suitable as Cursor AI IDE tools such as Windsurf, Cline, etc. normalize the code generated for front-end projects. Such tools, althoughGenerate full project codeThe ability is very powerful, but the lack of basic constraints can lead to a large number of invalid tokens consumption, especially when generating front-end projects, because there is no constraints on the basic development framework, the default front-end page generation effect is lower than the bolt ,v0.dev A class of tools.
Introducing a mature technical framework and basic constraints at this point can lead to better front-end project code generation with fewer steps and tokens to consume.
Next.js 14 Development Rules Original
# Rules for Next.js 14 Development ## General Guidelines 1. Use Next.js 14 with TypeScript and Tailwind CSS for optimal developer experience and type safety. 2. 2. Use `bun` for all package installations and management. 3. 3. Implement the App Router, which is the recommended routing system for Next.js 14. 4. 4. Utilize Server Components by default, using Client Components only when necessary for interactivity or client-side state. 5. 5. Leverage Server Actions for handling data mutations and form submissions. 6. 6. Implement proper caching strategies using Next.js built-in caching mechanisms. 7. 7. Ensure all components and pages are accessible, following WCAG guidelines. 8. 8. Use environment variables for configuration following Next.js conventions. 9. Implement performance optimizations such as code splitting, lazy loading, and parallel data fetching where appropriate. 10. Provide clear, concise comments explaining complex logic or design decisions. ## Code Structure and Syntax 1. Use the `app` directory for all components and pages. 2. 2. Implement the following file conventions in the `app` directory. - `layout.tsx`: For shared UI across multiple pages - `page.tsx`: For unique page content - `loading.tsx`: For loading UI - `error.tsx`: For error handling UI - `not-found.tsx`: For 404 pages 3. Use Server Components by default. Add the `'use client'` directive only when creating Client Components. 4. Define components using arrow function syntax with TypeScript. ``tsx import { FC } from 'react'; } interface ComponentProps { // Props definition } const Component: FC = ({ prop1, prop2 }) => { // Component logic } export default Component. ``` 5. For page components, use default exports. ``tsx export default function Page() { // Page component logic } ``` 6. If explicit typing is needed, prefer `React.FC` or `React.ReactNode`. ``tsx import React from 'react'. const ComponentName: React.FC = () => { // Component logic }; } // OR const ComponentName = (): React.ReactNode => { // Component logic }; ``` ## Routing and Navigation 1. Implement nested routing using folder structure in the `app` directory. 2. 2. Use the `<link>` component from `next/link` for client-side navigation. ``tsx import Link from 'next/link'. <link href="/about">About</Link> `` 3. Implement dynamic routes using folder names with square brackets (e.g., `[id]`). 4. Use `generateStaticParams` for generating static paths in dynamic routes. ## Data Fetching and API Routes 1. Use Server Components and the `fetch` API for data fetching, leveraging Next.js automatic request deduplication: `[id]`. 5. ``tsx async function getData() { const res = await fetch('<https:>', { next: { revalidate: 3600 } }); if (!res.ok) throw new Error('Failed to fetch data'); return res.json(); if (! return res.json(); } } export default async function Page() { const data = await getData(); // Render component using data. // Render component using data } `` 2. Implement Server Actions for data mutations. ``tsx 'use server'; ``tsx''. import { revalidatePath } from 'next/cache'. export async function updateData(formData: FormData) { // Update data in your database revalidatePath('/data'); } } `` 3. Use route handlers (route.ts) for API routes in the App Router. 4. Implement Static Site Generation (SSG) and Server-Side Rendering (SSR) using App Router conventions when appropriate. ## State Management and Interactivity 1. Use Server Actions for form submissions and data mutations. ```tsx import { updateData } from '. /actions'. export default function Form() { return ( <form action="{updateData}" data-trp-original-action="{updateData}"> <input type="text" name="data" /> <button type="submit">Update</button> <input type="hidden" name="trp-form-language" value="en"/></form> ); } `` 2. Implement React hooks for client-side state management when necessary. 3. Use the `useState` and `useEffect` hooks in Client Components for local state and side effects. ## Styling 1. Use Tailwind CSS classes exclusively for styling. Avoid inline styles. ```tsx <div classname="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"> {/* Component content */} </div> `` 2. Create custom Tailwind classes in the `tailwind.config.js` file for reusable styles. 3. Use CSS Modules for component-specific styles when needed. ## Performance Optimization 1. Implement automatic static optimization for eligible pages. 2. 2. Use dynamic imports for code splitting. ```tsx import dynamic from 'next/dynamic'. const DynamicComponent = dynamic(() => import('... /components/DynamicComponent')); const `` 3. Utilize the Image component from `next/image` for automatic image optimization. ``tsx import Image from 'next/image'; ``tsx''. <image src="/image.jpg" alt="Description" width="{500}" height="{300}" /> `` 4. Implement proper caching strategies using the Data Cache and Full Route Cache. 5. Use Next.js 14's built-in caching and revalidation features for optimal performance. ```tsx import { unstable_cache } from 'next/cache'; const getCachedUser = unstable_cache( async (id: string) => getUser(id), ['user-cache'], { revalidate: 3600 } // Revalidate every hour ); `` 6. Use on-demand revalidation when appropriate. ``tsx import { revalidatePath, revalidateTag } from 'next/cache'; export async function updateData() { // Update data in your database revalidatePath('/data'); // Revalidate a specific path revalidateTag('data-tag'); // Revalidate all entries with this tag } ``` 7. Implement parallel data fetching for improved performance. ``tsx async function ParallelDataFetch() { const dataPromise = fetch('<https:>'); const userPromise = fetch('<https:>'). const [data, user] = await Promise.all([ dataPromise.then(res => res.json()), userPromise.then(res => res.json())) ]); return { data, user }; } `` ## Error Handling and Loading States 1. Create error.tsx files for error boundaries. ```tsx 'use client'; ``tsx export default function Error({ error, reset error, reset, }: { error, reset, reset, reset, reset, reset }: { error: Error & { digest?: string }; reset: () => void; } reset: () => void; }) { error: Error & { digest? }) { return ( <div> <h2>Something went wrong!</h2> <button onclick="{()" > reset()}>Try again</button> </div> ); } `` 2. Implement loading.tsx files for managing loading states. 3. Use React Suspense for more granular loading states. ``tsx import { Suspense } from 'react'. export default function Page() { return ( <suspense fallback="{<Loading" />}> <somecomponent /> </Suspense> ); } `` ## SEO and Metadata 1. Use the Metadata API for SEO optimization. ```tsx import type { Metadata } from 'next'; export const metadata: Metadata = { title: 'Page Title', description: 'Page description', } }; } ``` 2. Implement dynamic metadata using generateMetadata for pages with dynamic content. ## Composer Mode-Specific Guidelines 1. When using Composer mode, provide clear, natural language descriptions of desired changes or additions. 2. 2. For multi-file operations, specify the files involved and their relationships. 3. 3. When requesting code generation, provide context about the desired functionality and how it fits into the existing project structure. 4. 4. For refactoring tasks, describe the current code structure and the desired outcome. 5. 5. When addressing errors, provide details about the error message and the surrounding code context. Remember to adapt these rules based on specific project requirements and personal preferences. Always prioritize clean, efficient, and maintainable code that adheres to Next. code that adheres to Next.js 14 best practices.
Next.js 14 Development Rules Translation
# Next.js 14 Development Rules ## General Guidelines 1. Use Next.js 14 with TypeScript and Tailwind CSS for the best development experience and type safety. 2. Use `bun` for all package installation and management. 3. 3. implement App Router, which is the Next.js 14 recommended routing system. 4. use Server Components by default, and Client Components only when interaction or client-side state is required. 5. utilize Server Components for server-side operations. 5. Use Server Actions to handle data changes and form submissions. 6. 6. Implement appropriate caching policies using Next.js' built-in caching mechanisms. 7. Ensure that all components and pages meet the accessibility standards of the WCAG guidelines. 8. Follow Next.js conventions for configuration using environment variables. 9. implement performance optimizations such as code splitting, lazy loading, and parallel data fetching. 10. provide clear and concise annotations for complex logic or design decisions. ## Code Structure and Syntax 1. Use the `app` directory to store all components and pages. 2. 2. The following file naming conventions are followed in the `app` directory: - `layout.tsx`: UI shared by multiple pages. - `page.tsx`: for unique page content - `loading.tsx`: for the loading UI - `error.tsx`: UI for error handling - `not-found.tsx`: for 404 pages. 3. Use server-side components by default. Only add the `'use client'` directive when creating client-side components. 4. 4. Use TypeScript's arrow function syntax to define components: ``tsx import { FC } from 'react'; ``tsx''; ``tsx''; ``tsx'' interface ComponentProps { // Property definition } const Component: FC<componentprops> = ({ prop1, prop2 }) => { // Component logic }; export default Component. ``` 5. For page components, use the default export: ``tsx export default function Page() { // The page component logic } ``` 6. If explicit types are required, use `React.FC` or `React.ReactNode` in preference: ``tsx import React from 'react'; ``tsx const ComponentName: React.FC = () => { // Component logic }; // or const ComponentName = (): React.ReactNode => { // Component logic }; `` ## Routing and Navigation 1. implement nested routing in the `app` directory through a folder structure. 2. use the `next/link` provided by `next/link`. 2. use the ``next/link`` provided by ``next/link``.<link>` component for client-side navigation: ``tsx import Link from 'next/link'; <link href="/about">About Us</Link> `` 3. Use folder names with square brackets (e.g. `[id]`) to implement dynamic routes. 4. Use `generateStaticParams` to generate static paths for dynamic routes. ## Data Acquisition and API Routing 1. Use server-side components and the `fetch` API to fetch data, utilizing Next.js's automatic request de-duplication feature: ``tsx async function getData() { const res = await fetch('<https:>', { next: { revalidate: 3600 } }); if (!res.ok) throw new Error('Failed to fetch data'); return res.json(); } export default async function Page() { const data = await getData(); // Render the component using the data } `` 2. Use server-side operations to handle data changes: ```tsx 'use server'. import { revalidatePath } from 'next/cache'. export async function updateData(formData: FormData) { // Update the data in the database revalidatePath('/data'); } } `` 3. implement API routing in App Router using route.ts. 4. use App Router conventions to implement static site generation (SSG) and server-side rendering (SSR) where appropriate. ## State Management and Interaction 1. use server-side actions to handle form submissions and data changes: ```tsx import { updateData } from '. /actions'; export default function Form() { return ( <form action="{updateData}" data-trp-original-action="{updateData}"> <input type="text" name="data" /> <button type="submit">update</button> <input type="hidden" name="trp-form-language" value="en"/></form> ); } `` 2. use React hooks for client-side state management when needed. 3. Use `useState` and `useEffect` hooks to manage local state and side effects in client-side components. ## Styles 1. Use the Tailwind CSS class for styling and avoid inline styles: ```tsx <div classname="bg-white shadow-md rounded px-8 pt-6 pb-8 mb-4"> {/* Component content */} </div> `` 2. Create a custom Tailwind class in the `tailwind.config.js` file to enable reusable styles. 3. 3. Use the CSS module to style specific components when needed. ## Performance Optimization 1. Automatic static optimization of eligible pages. 2. 2. Use dynamic imports for code splitting: ``tsx import dynamic from 'next/dynamic'. const DynamicComponent = dynamic(() => import('. /components/DynamicComponent')); ``` 3. Use the Image component of `next/image` for automatic image optimization: ``tsx import Image from 'next/image'; <image src="/image.jpg" alt="描述" width="{500}" height="{300}" /> `` 4. Use data caching and full route caching to implement appropriate caching policies. 5. Use Next.js 14 built-in caching and revalidation features to improve performance: ```tsx import { unstable_cache } from 'next/cache'. const getCachedUser = unstable_cache( async (id: string) => getUser(id), ['user-cache'], { revalidate: 3600 } // revalidate every hour ); `` 6. Use on-demand revalidation where appropriate: ```tsx import { revalidatePath, revalidateTag } from 'next/cache' ; export async function updateData() { // Update the data in the database revalidatePath('/data'); // revalidate a specific path revalidateTag('data-tag'); // revalidate all entries tagged with this tag } `` 7. Implement parallel data fetching to improve performance: ```tsx async function ParallelDataFetch() { const dataPromise = fetch('<https:>'); const userPromise = fetch('<https:>'). const [data, user] = await Promise.all([ dataPromise.then(res => res.json()), userPromise.then(res => res.json())) ]); return { data, user }; } `` ## Error Handling and Loading Status 1. Create the error.tsx file as an error boundary: ```tsx 'use client'. export default function Error({ error, reset error, reset, }: { error, reset, reset, reset, reset, reset }: { error: Error & { digest?: string }; reset: () => void; } reset: () => void; }) { error: Error & { digest? }) { return ( <div> <h2>An error occurred!</h2> <button onclick="{()" > reset()}>retry</button> </div> ); } `` 2. Create a loading.tsx file to manage loading state. 3. Use React Suspense to provide more granular loading state: ``tsx import { Suspense } from 'react'. export default function Page() { return ( <suspense fallback="{<Loading" />}> <somecomponent /> </Suspense> ); } `` ## SEO and metadata 1. Use the Metadata API for SEO optimization: ```tsx import type { Metadata } from 'next' ; export const metadata: Metadata = { title: 'Title of the page', description: 'Description of the page', ``tsx import type { metadata }; } ``` 2. For dynamic content pages, use generateMetadata to implement dynamic metadata. ## Composer Schema Specific Guidelines 1. when using the Composer schema, provide clear, natural language describing the changes or additions required. 2. for multiple file operations, be clear about the files involved and their relationships. 2. for multi-file operations, specify the files involved and their relationships. 3. 3. when requesting code generation, provide context about the desired functionality and how it fits within the existing project structure. 4. 4. for refactoring tasks, describe the current code structure and desired results. 5. 5. when resolving errors, provide detailed information about the error message and its context. Remember to adapt these rules to specific project needs and personal preferences. Always prioritize writing clear, efficient, and maintainable code that conforms to Next.js 14 best practices.
Original Swift and SwiftUI Development Rules
# SwiftUI Best Practices for iOS App Development When generating code, finding bugs, or optimizing SwiftUI projects, follow these guidelines. ## General Guidelines - You are an expert AI programming assistant focused on producing clear, readable SwiftUI code. - Always use the latest version of SwiftUI and Swift (as of August/September 2024), and be familiar with the latest features and best practices. - Provide accurate, factual, thoughtful answers, and excel at reasoning. - Follow the user's requirements carefully & to the letter. - Think step-by-step - describe your plan for what to build in pseudocode, written out in great detail. - Always confirm your understanding before writing code. - Write correct, up-to-date, bug-free, fully functional, working, secure, performant, and efficient code. - Prioritize readability over performance. - Fully implement all requested functionality. - Leave NO TODOs, placeholders, or missing pieces. - Minimize any other prose. - If you think there might not be a correct answer, say so. ## 1. State Management - Use appropriate property wrappers and macros. - Annotate view models with `@Observable`, e.g. `@Observable final class MyModel`. - Do not use @State in the SwiftUI View for view model observation. Instead, use `let model: MyModel`. - For reference type state shared with a child view, pass the dependency to the constructor of the child view. - For value type state shared with a child view, use SwiftUI bindings if and only if the child needs write access to the state. - For value type state shared with a child view, pass the value if the child view only needs read access to the state. - Use an `@Environment` for state that should be shared throughout the entire app, or large pieces of the app. - Use `@State` only for local state that is managed by the view itself. ## 2. Performance Optimization - Implement lazy loading for large lists or grids using `LazyVStack`, `LazyHStack`, or `LazyVGrid`. - Optimize ForEach loops by using stable identifiers. ## 3. Reusable Components - Implement custom view modifiers for shared styling and behavior. - Use extensions to add reusable functionality to existing types. ## 4. Accessibility - Add accessibility modifiers to all UI elements. - Support Dynamic Type for text scaling. - Provide clear accessibility labels and hints. ## 5. SwiftUI Lifecycle - Use `@main` and `App` protocol for the app's entry point. - Implement `Scene`s for managing app structure. - Use appropriate view lifecycle methods like `onAppear` and `onDisappear`. ## 6. Data Flow - Use the Observation framework (`@Observable`, `@State`, and `@Binding`) to build reactive views. - Implement proper error handling and propagation. ## 7. Testing - Write unit tests for ViewModels and business logic in the UnitTests folder. - Write unit tests for ViewModels and business logic in the UnitTests folder. Implement UI tests for critical user flows in the UITests folder. - Use Preview providers for rapid UI iteration and testing. ## 8. SwiftUI-specific Patterns - Use `@Binding` for two-way data flow between parent and child views. - Implement custom `PreferenceKey`s for child-to-parent communication. - Utilize `@Environment` for dependency injection. ## 9. Code Style and Formatting - Follow Swift style guidelines for naming conventions and code structure. - Use SwiftLint or similar tools to enforce consistent code style. When generating or reviewing code, ensure adherence to these best practices. Identify and fix any violations to maintain high-quality, performant, and maintainable SwiftUI code. Remember, the best structure is one that works well for your specific project and team. Feel free to adapt this structure as your project grows and your Feel free to adapt this structure as your project grows and your needs evolve.
Swift and SwiftUI Development Rules Translation
# SwiftUI Best Practices for Developing iOS Apps Follow these guidelines when generating code, finding bugs, or optimizing your SwiftUI project: ## General Guidelines - You are a professional AI programming assistant focused on generating clear, readable SwiftUI code. - Always use the latest version of SwiftUI and Swift (as of August/September 2024) and familiarize yourself with the latest features and best practices. - Provide accurate, fact-based, well-considered answers and excel at reasoning. - Strictly adheres to user requirements. - Think step-by-step - use pseudo-code to describe the build plan in detail. - Always confirm your understanding of the requirements before writing code. - Write code that is correct, up-to-date, bug-free, fully functional, secure, and efficient. - Prioritize code readability over performance. - Implement all requested functionality completely. - Leave no TODOs, placeholders, or missing sections. - Keep it simple and minimize other extraneous text. - If you think there may not be a correct answer, state so. If you don't know the answer, be upfront about that too. ## 1. status management - Use appropriate property wrappers and macros: - Use `@Observable` to label the view model, e.g. `@Observable final class MyModel`. - Do not use `@State` to observe the view model in a SwiftUI View. Instead, use `let model: MyModel`. - For reference type state shared with a subview, pass the dependency to the subview's constructor. - For value-type state shared with a subview, use SwiftUI bindings if the subview requires write access, or pass the value if it only requires read access. - Use `@Environment` for state that needs to be shared by the whole or most of the application. - Use `@State` only for local state managed by the view itself. ## 2. Performance Optimizations - Use `LazyVStack`, `LazyHStack` or `LazyVGrid` for inert loading of large lists or grids. - Optimize ForEach loops with stable identifiers. ## 3. Reusable components - Implement custom view modifiers to share styles and behaviors. - Use extensions to add reusable functionality to existing types. ## 4. Accessibility - Add accessibility modifiers to all UI elements. - Support dynamic font features for text scaling. - Provide clear accessibility labels and tips. ## 5. SwiftUI Lifecycle - Use `@main` and `App` protocols as entry points to the application. - Use `Scene` to manage the application structure. - Use appropriate view lifecycle methods such as `onAppear` and `onDisappear`. ## 6. Data Flow - Use the Observation framework (`@Observable`, `@State` and `@Binding`) to build responsive views. - Implement appropriate error handling and propagation. ## 7. Testing - Write unit tests for the view model and business logic in the UnitTests folder. - Implement UI tests for key user processes in the UITests folder. - Use the Preview provider for rapid UI iteration and testing. ## 8. SwiftUI Specific Patterns - Implement bi-directional data flow between parent and child views using `@Binding`. - Implement a custom `PreferenceKey` for child-to-parent communication. - Implement dependency injection using `@Environment`. ## 9. Code Style and Formatting - Follow Swift's naming conventions and code structure guidelines. - Use SwiftLint or similar tools to enforce consistent code style. Ensure that these best practices are followed when generating or reviewing code. Identify and fix any violations to maintain high-quality, high-performance, easy-to-maintain SwiftUI code. Remember that the best structure is one that can be adapted to the needs of a particular project and team. Have the flexibility to adapt these structures as your project grows and your needs change.