@qlover/create-app 0.7.14 → 0.7.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/dist/index.cjs +1 -1
  3. package/dist/index.js +1 -1
  4. package/dist/templates/next-app/README.en.md +131 -0
  5. package/dist/templates/next-app/README.md +115 -20
  6. package/dist/templates/next-app/docs/en/api.md +387 -0
  7. package/dist/templates/next-app/docs/en/component.md +544 -0
  8. package/dist/templates/next-app/docs/en/database.md +496 -0
  9. package/dist/templates/next-app/docs/en/development-guide.md +727 -0
  10. package/dist/templates/next-app/docs/en/env.md +563 -0
  11. package/dist/templates/next-app/docs/en/i18n.md +287 -0
  12. package/dist/templates/next-app/docs/en/index.md +166 -0
  13. package/dist/templates/next-app/docs/en/page.md +457 -0
  14. package/dist/templates/next-app/docs/en/project-structure.md +177 -0
  15. package/dist/templates/next-app/docs/en/router.md +427 -0
  16. package/dist/templates/next-app/docs/en/theme.md +532 -0
  17. package/dist/templates/next-app/docs/en/validator.md +478 -0
  18. package/dist/templates/next-app/docs/zh/api.md +387 -0
  19. package/dist/templates/next-app/docs/zh/component.md +544 -0
  20. package/dist/templates/next-app/docs/zh/database.md +496 -0
  21. package/dist/templates/next-app/docs/zh/development-guide.md +727 -0
  22. package/dist/templates/next-app/docs/zh/env.md +563 -0
  23. package/dist/templates/next-app/docs/zh/i18n.md +287 -0
  24. package/dist/templates/next-app/docs/zh/index.md +166 -0
  25. package/dist/templates/next-app/docs/zh/page.md +457 -0
  26. package/dist/templates/next-app/docs/zh/project-structure.md +177 -0
  27. package/dist/templates/next-app/docs/zh/router.md +427 -0
  28. package/dist/templates/next-app/docs/zh/theme.md +532 -0
  29. package/dist/templates/next-app/docs/zh/validator.md +476 -0
  30. package/package.json +1 -1
  31. package/dist/templates/next-app/docs/env.md +0 -94
@@ -0,0 +1,457 @@
1
+ # Next.js Page Development Guide
2
+
3
+ ## Table of Contents
4
+
5
+ 1. [Page Development Overview](#page-development-overview)
6
+ 2. [Server Components in Detail](#server-components-in-detail)
7
+ 3. [Client Components in Detail](#client-components-in-detail)
8
+ 4. [Data Fetching and State Management](#data-fetching-and-state-management)
9
+ 5. [Page Routing and Metadata](#page-routing-and-metadata)
10
+ 6. [Best Practices and Performance Optimization](#best-practices-and-performance-optimization)
11
+
12
+ ## Page Development Overview
13
+
14
+ ### 1. Server Components vs Client Components
15
+
16
+ In Next.js 13+, all components are Server Components by default unless explicitly declared as Client Components.
17
+
18
+ ```typescript
19
+ // Server Component (default)
20
+ // page.tsx
21
+ export default function Page() {
22
+ return <div>Server-rendered content</div>;
23
+ }
24
+
25
+ // Client Component
26
+ // Requires 'use client' directive at the top of the file
27
+ 'use client';
28
+
29
+ export function ClientComponent() {
30
+ return <div>Client-rendered content</div>;
31
+ }
32
+ ```
33
+
34
+ ### 2. Selection Guide
35
+
36
+ **Use Server Components when**:
37
+
38
+ - Direct access to backend resources is needed
39
+ - Contains sensitive information (API keys, tokens, etc.)
40
+ - Depends on heavy backend operations
41
+ - Need to reduce client-side JavaScript bundle size
42
+ - SEO optimization is required
43
+ - For page-level components
44
+ - No client-side interaction needed
45
+ - No browser APIs needed
46
+
47
+ **Use Client Components when**:
48
+
49
+ - Need to add interactions and event handling
50
+ - Using browser APIs
51
+ - Using React hooks
52
+ - Need to maintain component state
53
+ - Need client-specific lifecycles
54
+ - Using third-party libraries that depend on browser APIs
55
+
56
+ ## Server Components in Detail
57
+
58
+ ### 1. Basic Structure
59
+
60
+ ```typescript
61
+ // app/[locale]/login/page.tsx
62
+ export default async function LoginPage(props: PageParamsProps) {
63
+ // 1. Parameter validation
64
+ if (!props.params) {
65
+ return notFound();
66
+ }
67
+
68
+ // 2. Server initialization
69
+ const params = await props.params;
70
+ const pageParams = new PageParams(params);
71
+ const server = new BootstrapServer();
72
+
73
+ // 3. Server-side data fetching and validation
74
+ if (await server.getIOC(ServerAuth).hasAuth()) {
75
+ return redirect({ href: '/', locale: params.locale! });
76
+ }
77
+
78
+ // 4. Get internationalized text
79
+ const tt = await pageParams.getI18nInterface(loginI18n);
80
+
81
+ // 5. Render page
82
+ return (
83
+ <BaseLayout>
84
+ <div>{/* Page content */}</div>
85
+ <ClientComponent /> {/* Embed client component */}
86
+ </BaseLayout>
87
+ );
88
+ }
89
+ ```
90
+
91
+ ### 2. Server-Side Data Fetching
92
+
93
+ ```typescript
94
+ // Fetch data directly in server component
95
+ export default async function UsersPage() {
96
+ const server = new BootstrapServer();
97
+
98
+ const result = await server
99
+ .use(new AdminAuthPlugin()) // Use server middleware
100
+ .execNoError(async ({ parameters: { IOC } }) => {
101
+ const userService = IOC(UserService);
102
+ return userService.getUsers();
103
+ });
104
+
105
+ // Pass data directly to client component
106
+ return <UserList initialData={result.data} />;
107
+ }
108
+ ```
109
+
110
+ ### 3. Static Generation and Dynamic Rendering
111
+
112
+ ```typescript
113
+ // Static page generation
114
+ export const dynamic = 'force-static'; // Force static generation
115
+ export const revalidate = 3600; // Regenerate every hour
116
+
117
+ // Dynamic page generation
118
+ export const dynamic = 'force-dynamic'; // Force dynamic generation
119
+
120
+ // Generate static route parameters
121
+ export async function generateStaticParams() {
122
+ return [{ locale: 'en' }, { locale: 'zh' }];
123
+ }
124
+ ```
125
+
126
+ ## Client Components in Detail
127
+
128
+ ### 1. Basic Structure
129
+
130
+ ```typescript
131
+ 'use client'; // Declare as client component
132
+
133
+ export function LoginForm(props: { tt: LoginI18nInterface }) {
134
+ // 1. Hooks usage
135
+ const [loading, setLoading] = useState(false);
136
+ const userService = useIOC(I.UserServiceInterface);
137
+
138
+ // 2. Event handling
139
+ const handleLogin = async (values: LoginFormData) => {
140
+ try {
141
+ setLoading(true);
142
+ await userService.login(values);
143
+ routerService.gotoHome();
144
+ } catch (error) {
145
+ logger.error(error);
146
+ } finally {
147
+ setLoading(false);
148
+ }
149
+ };
150
+
151
+ // 3. Render UI
152
+ return (
153
+ <Form onFinish={handleLogin}>
154
+ {/* Form content */}
155
+ </Form>
156
+ );
157
+ }
158
+ ```
159
+
160
+ ### 2. Client-Side State Management
161
+
162
+ ```typescript
163
+ 'use client';
164
+
165
+ export function UserProfile() {
166
+ // 1. Local state
167
+ const [isEditing, setIsEditing] = useState(false);
168
+
169
+ // 2. Service state
170
+ const userStore = useIOC(UserStore);
171
+ const user = useStore(userStore, userStore.selector.currentUser);
172
+
173
+ // 3. Form state
174
+ const [form] = Form.useForm();
175
+
176
+ // 4. Side effects
177
+ useEffect(() => {
178
+ if (user) {
179
+ form.setFieldsValue(user);
180
+ }
181
+ }, [user, form]);
182
+
183
+ return (
184
+ <div>{/* Component content */}</div>
185
+ );
186
+ }
187
+ ```
188
+
189
+ ### 3. Interaction with Server Components
190
+
191
+ ```typescript
192
+ // 1. Receive server data through props
193
+ interface Props {
194
+ initialData: UserData; // Initial data from server
195
+ tt: I18nInterface; // Translation text from server
196
+ }
197
+
198
+ 'use client';
199
+ export function UserList({ initialData, tt }: Props) {
200
+ const [data, setData] = useState(initialData);
201
+
202
+ // Initialize client state with server data
203
+ useEffect(() => {
204
+ setData(initialData);
205
+ }, [initialData]);
206
+
207
+ return (
208
+ <div>{/* Component content */}</div>
209
+ );
210
+ }
211
+ ```
212
+
213
+ ## Data Fetching and State Management
214
+
215
+ ### 1. Server-Side Data Fetching
216
+
217
+ ```typescript
218
+ // 1. Fetch data in server component
219
+ export default async function DashboardPage() {
220
+ const server = new BootstrapServer();
221
+
222
+ // Parallel data fetching
223
+ const [userData, statsData] = await Promise.all([
224
+ server.execNoError(async ({ IOC }) => IOC(UserService).getCurrentUser()),
225
+ server.execNoError(async ({ IOC }) => IOC(StatsService).getStats())
226
+ ]);
227
+
228
+ return (
229
+ <Dashboard
230
+ userData={userData}
231
+ statsData={statsData}
232
+ />
233
+ );
234
+ }
235
+
236
+ // 2. Use server action
237
+ export async function fetchUserData(userId: string) {
238
+ 'use server'; // Declare as server action
239
+
240
+ const server = new BootstrapServer();
241
+ return server.execNoError(async ({ IOC }) => {
242
+ return IOC(UserService).getUserById(userId);
243
+ });
244
+ }
245
+ ```
246
+
247
+ ### 2. Client-Side State Management
248
+
249
+ ```typescript
250
+ 'use client';
251
+
252
+ // 1. Use Store for state management
253
+ @injectable()
254
+ export class UserProfileStore extends StoreInterface<UserProfileState> {
255
+ constructor() {
256
+ super(() => ({
257
+ user: null,
258
+ loading: false,
259
+ error: null
260
+ }));
261
+ }
262
+
263
+ async fetchUser(id: string) {
264
+ this.emit({ ...this.state, loading: true });
265
+ try {
266
+ const user = await this.userService.getUser(id);
267
+ this.emit({ ...this.state, user, loading: false });
268
+ } catch (error) {
269
+ this.emit({ ...this.state, error, loading: false });
270
+ }
271
+ }
272
+ }
273
+
274
+ // 2. Use Store in component
275
+ export function UserProfile() {
276
+ const store = useIOC(UserProfileStore);
277
+ const user = useStore(store, store.selector.user);
278
+ const loading = useStore(store, store.selector.loading);
279
+
280
+ return (
281
+ <div>
282
+ {loading ? <Loading /> : <UserInfo user={user} />}
283
+ </div>
284
+ );
285
+ }
286
+ ```
287
+
288
+ ## Page Routing and Metadata
289
+
290
+ ### 1. Dynamic Routing
291
+
292
+ ```typescript
293
+ // app/[locale]/users/[id]/page.tsx
294
+ export default async function UserPage({
295
+ params: { locale, id }
296
+ }: {
297
+ params: { locale: string; id: string };
298
+ }) {
299
+ // Handle route parameters
300
+ }
301
+
302
+ // Generate static routes
303
+ export async function generateStaticParams() {
304
+ const users = await fetchUsers();
305
+
306
+ return users.map((user) => ({
307
+ locale: ['en', 'zh'],
308
+ id: user.id
309
+ }));
310
+ }
311
+ ```
312
+
313
+ ### 2. Metadata Generation
314
+
315
+ ```typescript
316
+ // 1. Static metadata
317
+ export const metadata: Metadata = {
318
+ title: 'User Profile',
319
+ description: 'User profile page'
320
+ };
321
+
322
+ // 2. Dynamic metadata
323
+ export async function generateMetadata({
324
+ params
325
+ }: {
326
+ params: PageParamsType;
327
+ }): Promise<Metadata> {
328
+ const pageParams = new PageParams(await params);
329
+ const tt = await pageParams.getI18nInterface(userI18n);
330
+
331
+ return {
332
+ title: tt.pageTitle,
333
+ description: tt.pageDescription
334
+ };
335
+ }
336
+ ```
337
+
338
+ ## Best Practices and Performance Optimization
339
+
340
+ ### 1. Component Splitting Principles
341
+
342
+ ```typescript
343
+ // ❌ Wrong: Mixing server and client logic in one component
344
+ export default function Page() {
345
+ const [state, setState] = useState(); // Error: Server components can't use hooks
346
+ const data = await fetchData(); // Correct: Server-side data fetching
347
+
348
+ return <div>{/* ... */}</div>;
349
+ }
350
+
351
+ // ✅ Correct: Separate server and client logic
352
+ // page.tsx (Server Component)
353
+ export default async function Page() {
354
+ const data = await fetchData(); // Server-side data fetching
355
+ return <ClientComponent data={data} />;
356
+ }
357
+
358
+ // ClientComponent.tsx (Client Component)
359
+ 'use client';
360
+ export function ClientComponent({ data }) {
361
+ const [state, setState] = useState(); // Client-side state management
362
+ return <div>{/* ... */}</div>;
363
+ }
364
+ ```
365
+
366
+ ### 2. Performance Optimization Strategies
367
+
368
+ ```typescript
369
+ // 1. Component-level caching
370
+ export default async function UserList() {
371
+ const users = await fetchUsers();
372
+
373
+ return (
374
+ <div>
375
+ {users.map(user => (
376
+ <Suspense key={user.id} fallback={<Loading />}>
377
+ <UserCard user={user} />
378
+ </Suspense>
379
+ ))}
380
+ </div>
381
+ );
382
+ }
383
+
384
+ // 2. Route-level caching
385
+ export const revalidate = 3600; // Cache for one hour
386
+
387
+ // 3. Selective hydration
388
+ export default function Page() {
389
+ return (
390
+ <>
391
+ <StaticContent />
392
+ <Suspense fallback={<Loading />}>
393
+ <DynamicContent />
394
+ </Suspense>
395
+ </>
396
+ );
397
+ }
398
+ ```
399
+
400
+ ### 3. Error Handling
401
+
402
+ ```typescript
403
+ // 1. Error boundary
404
+ 'use client';
405
+ export function ErrorBoundary({
406
+ error,
407
+ reset
408
+ }: {
409
+ error: Error;
410
+ reset: () => void;
411
+ }) {
412
+ return (
413
+ <div>
414
+ <h2>Something went wrong!</h2>
415
+ <button onClick={reset}>Try again</button>
416
+ </div>
417
+ );
418
+ }
419
+
420
+ // 2. Loading state
421
+ export default async function Page() {
422
+ return (
423
+ <Suspense fallback={<Loading />}>
424
+ <SlowComponent />
425
+ </Suspense>
426
+ );
427
+ }
428
+ ```
429
+
430
+ ## Summary
431
+
432
+ Key points for Next.js 13+ page development:
433
+
434
+ 1. **Component Type Selection**:
435
+ - Use Server Components by default
436
+ - Use Client Components only when necessary
437
+ - Properly split component responsibilities
438
+
439
+ 2. **Data Flow Handling**:
440
+ - Prioritize server-side data fetching
441
+ - Pass data to client through props
442
+ - Use Store for client-side state management
443
+
444
+ 3. **Performance Optimization**:
445
+ - Use caching strategies appropriately
446
+ - Implement selective hydration
447
+ - Optimize loading performance
448
+
449
+ 4. **Development Experience**:
450
+ - Clear code organization
451
+ - Type safety
452
+ - Comprehensive error handling
453
+
454
+ 5. **Best Practices**:
455
+ - Follow Single Responsibility Principle
456
+ - Implement graceful degradation
457
+ - Maintain code maintainability
@@ -0,0 +1,177 @@
1
+ # Detailed Project Structure
2
+
3
+ ## Directory Structure Overview
4
+
5
+ ```
6
+ next-app/
7
+ ├── config/ # Global configuration files
8
+ ├── src/ # Source code directory
9
+ │ ├── app/ # Next.js app router
10
+ │ ├── base/ # Client core code
11
+ │ ├── core/ # Core bootstrap and IOC configuration
12
+ │ ├── server/ # Server-side code
13
+ │ ├── styles/ # Style files
14
+ │ └── uikit/ # UI component library
15
+ └── public/ # Static assets
16
+ ```
17
+
18
+ ## Detailed Structure Explanation
19
+
20
+ ### 1. Client Architecture (src/base)
21
+
22
+ #### 1.1 Interface Layer (src/base/port)
23
+
24
+ - `AdminLayoutInterface.ts` - Admin layout interface
25
+ - `AdminPageInterface.ts` - Admin page interface
26
+ - `AppApiInterface.ts` - Application API interface
27
+ - `AppUserApiInterface.ts` - User API interface
28
+ - `AsyncStateInterface.ts` - Asynchronous state interface
29
+ - `I18nServiceInterface.ts` - Internationalization service interface
30
+ - `IOCInterface.ts` - Dependency injection interface
31
+ - `RouterInterface.ts` - Router interface
32
+ - `UserServiceInterface.ts` - User service interface
33
+
34
+ #### 1.2 Business Logic Layer (src/base/cases)
35
+
36
+ - State management controllers
37
+ - Dialog handling
38
+ - Router service
39
+ - User service
40
+ - Encryption service
41
+
42
+ #### 1.3 Service Implementation Layer (src/base/services)
43
+
44
+ - `AdminUserService.ts` - Admin user service
45
+ - `I18nService.ts` - Internationalization service
46
+ - `UserService.ts` - User service
47
+ - `adminApi/` - Admin API implementation
48
+ - `appApi/` - Application API implementation
49
+
50
+ ### 2. Server Architecture (src/server)
51
+
52
+ #### 2.1 Interface Layer (src/server/port)
53
+
54
+ - `CrentialTokenInterface.ts` - Credential token interface
55
+ - `DBBridgeInterface.ts` - Database bridge interface
56
+ - `DBTableInterface.ts` - Database table interface
57
+ - `PaginationInterface.ts` - Pagination interface
58
+ - `ParamsHandlerInterface.ts` - Parameter handling interface
59
+ - `ServerAuthInterface.ts` - Server authentication interface
60
+ - `ServerInterface.ts` - Server interface
61
+ - `UserRepositoryInterface.ts` - User repository interface
62
+ - `ValidatorInterface.ts` - Validator interface
63
+
64
+ #### 2.2 Core Implementation
65
+
66
+ - `AppErrorApi.ts` - API error handling
67
+ - `AppSuccessApi.ts` - API success response
68
+ - `ServerAuth.ts` - Server authentication implementation
69
+ - `UserCredentialToken.ts` - User credential token
70
+
71
+ #### 2.3 Service Layer (src/server/services)
72
+
73
+ - `AdminAuthPlugin.ts` - Admin authentication plugin
74
+ - `AIService.ts` - AI service
75
+ - `ApiUserService.ts` - API user service
76
+ - `UserService.ts` - User service
77
+
78
+ #### 2.4 Data Access Layer
79
+
80
+ - `repositorys/UserRepository.ts` - User data repository
81
+ - `sqlBridges/SupabaseBridge.ts` - Supabase database bridge
82
+
83
+ #### 2.5 Validators (src/server/validators)
84
+
85
+ - `LoginValidator.ts` - Login validation
86
+ - `PaginationValidator.ts` - Pagination validation
87
+
88
+ ### 3. API Route Structure (src/app/api)
89
+
90
+ ```
91
+ api/
92
+ ├── admin/ # Admin endpoints
93
+ │ └── users/ # User management
94
+ ├── ai/ # AI-related endpoints
95
+ │ └── completions/ # AI completions
96
+ └── user/ # User endpoints
97
+ ├── login/ # Login
98
+ ├── logout/ # Logout
99
+ └── register/ # Registration
100
+ ```
101
+
102
+ ### 4. Page Route Structure (src/app/[locale])
103
+
104
+ ```
105
+ [locale]/
106
+ ├── admin/ # Admin pages
107
+ │ └── users/ # User management
108
+ ├── login/ # Login page
109
+ ├── register/ # Registration page
110
+ └── page.tsx # Homepage
111
+ ```
112
+
113
+ ### 5. UI Component Library (src/uikit)
114
+
115
+ #### 5.1 Components (components)
116
+
117
+ - `AdminLayout.tsx` - Admin layout
118
+ - `BaseHeader.tsx` - Base header
119
+ - `BaseLayout.tsx` - Base layout
120
+ - `ChatRoot.tsx` - Chat root component
121
+ - `LanguageSwitcher.tsx` - Language switcher
122
+ - `ThemeSwitcher.tsx` - Theme switcher
123
+ - Other common components
124
+
125
+ #### 5.2 Hooks and Context
126
+
127
+ - `useI18nInterface.ts` - Internationalization hook
128
+ - `useIOC.ts` - IOC container hook
129
+ - `useStore.ts` - State management hook
130
+ - `IOCContext.ts` - IOC context
131
+
132
+ ## Technical Features
133
+
134
+ 1. **Dependency Injection Pattern**
135
+ - Using IOC container for dependency management
136
+ - Separate IOC containers for client and server
137
+ - Decoupling through interfaces
138
+
139
+ 2. **Layered Architecture**
140
+ - Clear interface definitions
141
+ - Well-defined implementation layers
142
+ - Loosely coupled module design
143
+
144
+ 3. **State Management**
145
+ - Controller-based state management
146
+ - Reactive data flow
147
+ - Predictable state changes
148
+
149
+ 4. **Internationalization Support**
150
+ - Multi-language support based on next-intl
151
+ - Dynamic language switching
152
+ - Route-level language isolation
153
+
154
+ 5. **Theme System**
155
+ - Based on Tailwind CSS
156
+ - Dark mode support
157
+ - Configurable theme variables
158
+
159
+ ## Development Workflow
160
+
161
+ 1. **API Development**
162
+ - Define interface (port)
163
+ - Implement validator (validators)
164
+ - Implement service (services)
165
+ - Create API route (api)
166
+
167
+ 2. **Page Development**
168
+ - Create page component
169
+ - Implement controller
170
+ - Register dependencies
171
+ - Add route
172
+
173
+ 3. **Component Development**
174
+ - Create UI component
175
+ - Implement business logic
176
+ - Inject dependencies
177
+ - Add styles