提示词场景库提示词场景库提示词场景库
提示词分类发现
提示词场景库·2026
关于/免责隐私条款

React / Next.js 项目通用指令

围绕「React / Next.js 项目通用指令」的提示词任务说明。

R
@ramazan747
1 天前2026年11月9日 02:31
网页开发

内容

变量
1# React / Next.js 项目通用指令
2
3你是「React / Next.js 项目通用指令」相关专家代理。先明确目标与约束,再给出可执行、可验证的产出;区分必须项与可选项。
4
5以下保留原提示词正文供结构与占位符对齐:
6
7# Universal Instructions for React / Next.js Projects
8
9> Purpose: General rules for developing various projects with React + TypeScript, Next.js + TypeScript, and Tailwind CSS.
10> Usage: Place this file in the root of a new project as `AGENTS.md`, `CLAUDE.md`, or `PROJECT_RULES.md`, or use it as a base instruction set for an AI agent.
11> Important: These instructions do not contain product-specific rules. Keep everything related to an individual project in a separate `PROJECT_RULES.md` file.
12
13---
14
15# 1. Core Principle
16
17Build a production-ready application, not a collection of disconnected components.
18
19Always follow this sequence:
20
211. Review the current project structure, `package.json`, routing, UI primitives, stores, hooks, schemas, and project rules.
222. Find existing actions, helpers, schemas, and components that can be reused.
233. Identify the smallest change required for the task.
244. Preserve existing behavior.
255. Implement each new feature end to end: model, validation, UI, storage/import/export, edge cases, and verification.
266. Run the relevant checks and report the results honestly.
27
28Do not add dependencies, abstractions, a global store, or an architectural layer unless they are genuinely necessary.
29Use `shadcn/ui` by default for UI work. Do not add another UI kit on top of it without a clear reason.
30
31---
32
33# 2. Choosing Between React and Next.js
34
35Use Next.js when the project needs:
36
37- routing;
38- SEO;
39- SSR / Server Components;
40- Server Actions;
41- Route Handlers / API routes;
42- authentication;
43- database access;
44- private environment variables;
45- content publishing.
46
47Use React + Vite when:
48
49- the application is entirely client-side;
50- SEO is not required;
51- it is a local tool, dashboard, editor, admin panel, or desktop-like UI;
52- the server already exists as a separate service.
53
54Do not choose Next.js simply because it is popular. Do not add Redux, Zustand, React Query, a form library, or another UI kit without a specific reason.
55
56---
57
58# 3. Default Stack and Checks
59
60Use the following by default:
61
62- React;
63- TypeScript in strict mode;
64- Tailwind CSS;
65- `shadcn/ui` as the required UI approach for clean design and rapid interface development;
66- Lucide React or the icon library used by the current shadcn configuration;
67- ESLint;
68- a shared `cn()` helper;
69- runtime validation for external data;
70- accessible HTML elements.
71
72Use `shadcn/ui` as the primary source of UI primitives: buttons, inputs, selects, dialogs, sheets, dropdowns, tooltips, tabs, carousels, cards, badges, skeletons, scroll areas, and other required components. Create custom primitives only when shadcn does not provide a suitable component or when the project already has a stable local primitive.
73
74For an MVP, begin with mock/JSON/localStorage data and validate local user flows first. Add the backend, database, payments, authentication, and external integrations last, once the UI, models, and flows are clear.
75
76At a minimum, run these commands after code changes:
77
78```bash
79npm run typecheck
80npm run lint
81npm run build
82```
83
84Do not claim that the project works if these commands were not run or completed with errors.
85
86---
87
88# 4. Architecture
89
90For Next.js projects expected to grow, keep source code inside `src/` by default: `src/app`, `src/components`, `src/lib`, `src/data`, `src/hooks`, and `src/features`. Keep root-level support folders and files (`public`, configuration files, lockfiles, and README) in the project root.
91
92For small projects, the following structure is acceptable:
93
94```text
95src/
96 app/ or pages/
97 components/
98 features/
99 lib/
100 shared/
101```
102
103For medium and large projects, use an FSD-like approach:
104
105```text
106src/
107 app/ # bootstrap, providers, layouts, routes
108 views/ # page-level composition
109 widgets/ # large UI blocks
110 features/ # user workflows
111 entities/ # domain model
112 shared/ # generic helpers, config, thin wrappers around shadcn/ui
113```
114
115Import direction:
116
117```text
118app/views -> widgets -> features -> entities -> shared
119```
120
121Do not:
122
123- import `widgets` into `features`;
124- place business logic in `shared`;
125- turn `shared/lib` into a dumping ground for unrelated functions;
126- duplicate mutation logic across multiple UI components;
127- use deep imports into another module's internals when that module exposes a public API.
128
129---
130
131# 5. Public API
132
133Every feature, entity, or shared UI folder should expose a clear public API through `index.ts` when the module is used externally. For shadcn primitives, the public API usually already lives in `components/ui/*` or the project's local UI layer.
134
135Good:
136
137```ts
138import { createTask } from "@/features/create-task";
139```
140
141Bad:
142
143```ts
144import { createTask } from "@/features/create-task/model/createTask";
145```
146
147Exception: internal code within the same feature or entity.
148
149---
150
151# 6. TypeScript
152
153Required:
154
155- enable `strict: true`;
156- do not use `any` except in isolated interoperability code;
157- do not hide type errors with `as` assertions;
158- use discriminated unions for complex state;
159- validate runtime JSON with a schema;
160- do not create multiple identical types without a meaningful reason.
161
162Example state type:
163
164```ts
165type LoadState<T> =
166 | { status: "idle" }
167 | { status: "loading" }
168 | { status: "success"; data: T }
169 | { status: "error"; message: string };
170```
171
172---
173
174# 7. React State and Effects
175
176Store state where it actually belongs:
177
178| State type | Where to store it |
179| ------------ | ----------------------------------------------------------- |
180| Local UI | `useState`, `useReducer` |
181| URL state | route/search parameters |
182| Server state | server rendering or a cache/query layer |
183| Form state | form hook/library |
184| Global UI | a small store when necessary |
185| Domain state | entity/store when the state is shared across multiple flows |
186
187Do not put the following in a global store:
188
189- hover state;
190- the state of a single dropdown;
191- the draft value of a single input;
192- the state of a single modal;
193- the temporary selected tab of one component.
194
195Use `useEffect` to synchronize with external systems:
196
197- browser APIs;
198- timers;
199- subscriptions;
200- external stores;
201- DOM integrations.
202
203Do not use `useEffect` for derived values.
204
205Bad:
206
207```tsx
208const [fullName, setFullName] = useState("");
209
210useEffect(() => {
211 setFullName(` `);
212}, [firstName, lastName]);
213```
214
215Good:
216
217```tsx
218const fullName = ` `;
219```
220
221---
222
223# 8. Next.js Boundaries
224
225In the App Router, components are Server Components by default.
226
227Add `"use client"` only where you need:
228
229- event handlers;
230- local state;
231- effects;
232- `window`, `document`, or `localStorage`;
233- drag and drop;
234- `contenteditable`;
235- client-only libraries.
236
237Do not make an entire layout a Client Component without a clear need.
238
239Server-only code includes:
240
241- database access;
242- authentication;
243- private API clients;
244- secret environment variables;
245- webhooks;
246- access checks.
247
248Never import a server-only module into a Client Component.
249
250---
251
252# 9. Runtime Validation and Migrations
253
254Validate all external data at the boundary:
255
256- request bodies;
257- form data;
258- URL/search parameters;
259- uploaded files;
260- imported JSON;
261- localStorage/IndexedDB data;
262- responses from external APIs.
263
264When adding a new model field, update the entire lifecycle:
265
2661. TypeScript type.
2672. Runtime schema.
2683. Factory/default values.
2694. Parser/migration for legacy data.
2705. Normalization helpers.
2716. Import/export.
2727. Search/filter indexing, if the field should be searchable.
2738. Undo/redo snapshots, if users can edit the field.
2749. UI for creating, editing, and clearing the field.
27510. Edge cases and checks.
276
277Example:
278
279```ts
280return {
281 ...item,
282 status: item.status ?? "active",
283 tags: normalizeTags(item.tags),
284 dueDate: normalizeDate(item.dueDate),
285};
286```
287
288Do not add a model field only in the UI.
289
290---
291
292# 10. Forms
293
294Every form must include:
295
296- a validation schema;
297- field errors;
298- a submitting/loading state;
299- a disabled submit button while submitting;
300- protection against duplicate submissions;
301- an error state;
302- success behavior;
303- reset/draft behavior, when applicable.
304
305A form is not complete if it works only when the request succeeds perfectly.
306
307---
308
309# 11. shadcn/ui and Shared UI
310
311Use `shadcn/ui` by default to build clean, consistent interfaces quickly.
312
313Rules:
314
315- first check whether the required component exists in the shadcn registry;
316- add shadcn components through the CLI or the project's established local method;
317- do not create a custom Button, Input, Modal, Dropdown, Tooltip, Tabs, or Card if shadcn already covers the use case;
318- adapt shadcn components through `className`, variants, and composition instead of copying similar components;
319- keep business components separate from primitives: `components/marketplace`, `features/*/ui`, `widgets/*`, or `entities/*/ui`;
320- keep only shadcn primitives and thin reusable wrappers in `components/ui` or `shared/ui`;
321- do not place product-specific business components there;
322- if shadcn does not provide a component, create a minimal local wrapper consistent with the current shadcn configuration.
323
324Base set of shadcn components for productivity interfaces:
325
326```text
327button
328input
329select
330textarea
331checkbox
332switch
333dialog
334sheet
335dropdown-menu
336popover
337tooltip
338tabs
339card
340badge
341avatar
342separator
343scroll-area
344skeleton
345carousel
346accordion
347collapsible
348hover-card
349```
350
351For marketplace, chat, and support flows, also plan for these newer shadcn components:
352
353```text
354message
355message-scroller
356attachment
357marker
358```
359
360Always use `cn()`:
361
362```ts
363export function cn(...values: Array<string | false | null | undefined>) {
364 return values.filter(Boolean).join(" ");
365}
366```
367
368---
369
370# 12. Choosing the Right UI Surface
371
372Before adding a new tool, choose the right surface:
373
374| Feature size | Placement | Example |
375| ---------------------------------- | --------------------------------- | ----------------------------------- |
376| 1-5 quick settings | context menu / dropdown / popover | status, due date, tags |
377| 5-12 grouped settings | sectioned, scrollable popover | entity properties, compact filters |
378| large data sets or bulk actions | sidebar / drawer | filters, tools panel |
379| complex form or dangerous action | modal | import/export, delete confirmation |
380| permanent workspace | dedicated view/page/widget | dashboard, calendar, editor |
381
382Rule:
383
384> If a control is used occasionally, keep it in a menu.
385> If a control is used constantly, keep it visible on the main surface.
386> If a control is complex and lengthy, move it to a sidebar or modal.
387
388Do not turn a small group of controls into a large card on the page. In productivity interfaces, this wastes valuable space.
389
390---
391
392# 13. Compact UI for Editors, Dashboards, and Workspaces
393
394In productivity applications, the primary content must remain the focus.
395
396Required:
397
398- the title, body, board, or editor must not be pushed downward by secondary controls;
399- entity properties should generally open from an icon button next to the title;
400- settings buttons must have an `aria-label`;
401- an important status can be shown as a small badge;
402- create/add actions must appear in a clear context;
403- sidebar-heavy flows must include a mobile-friendly menu or switcher;
404- do not make a productivity tool look like a landing page.
405
406Bad:
407
408```tsx
409
410 <Select>Status</Select>
411 <Select>Task</Select>
412 <Input>Date</Input>
413 <Input>Tags</Input>
414</LargePropertiesCard>
415```
416
417Good:
418
419```tsx
420
421 <TitleInput />
422 <PropertiesMenu />
423</TitleRow>
424```
425
426---
427
428# 14. Overlays, Dropdowns, Popovers, and Context Menus
429
430Every menu must behave as a true overlay.
431
432Rules:
433
434- if a menu may extend beyond its container, render it through `createPortal(..., document.body)`;
435- use `position: fixed` or a reliable positioning helper;
436- set an explicit `z-index`;
437- use an opaque `backgroundColor`;
438- do not rely only on a translucent `bg-black/50` background or blur;
439- add a border, ring, or shadow;
440- set `max-height` and `overflow-y-auto`;
441- close on `Escape`;
442- close on outside click/tap;
443- prevent page text from showing through or rendering over the menu;
444- hover and active states must not change the item's dimensions.
445
446Minimal overlay style:
447
448```tsx
449<div
450 role="menu"
451 className="rounded-2xl border p-2 shadow-2xl"
452 style="#151a21",
453 boxShadow: "0 24px 70px rgb(0 0 0 / 78%)",
454 isolation: "isolate",
455 zIndex: 1000,
456>
457 ...
458</div>
459```
460
461If the menu background does not render correctly or content appears above it, check:
462
463- the portal;
464- `position`;
465- `z-index`;
466- parent stacking contexts;
467- `isolation`;
468- opacity/background;
469- parent overflow/clipping.
470
471---
472
473# 15. Option Lists in Menus
474
475A list of tasks, projects, users, tags, or other options in a menu must not look like a dense wall of text.
476
477For a two-line item:
478
479- use a `min-height` of 40-44px;
480- include a `gap` between the icon, text, and checkmark;
481- use vertical padding such as `py-1.5`;
482- give the title and metadata different line heights;
483- add `mt-0.5` between the title and metadata;
484- apply `min-w-0` to the parent containing the text;
485- apply `truncate` to the title and metadata;
486- apply `shrink-0` to checkmarks and icons.
487
488Example:
489
490```tsx
491<button className="flex min-h-11 items-center gap-2.5 rounded-lg px-2.5 py-1.5">
492 <span className="min-w-0 flex-1">
493 <span className="block truncate font-medium leading-5"></span>
494 <span className="mt-0.5 block truncate text-xs leading-4 text-muted">
495 {meta}
496 </span>
497 </span>
498 {isActive ? <Check className="shrink-0" /> : null}
499</button>
500```
501
502---
503
504# 16. Long Text and Overflow
505
506Any user-provided text may contain a long word with no spaces.
507
508For editors, `contenteditable` elements, Markdown, card titles, and comments:
509
510- use `min-w-0` on flex/grid children;
511- use the current Tailwind utilities for wrapping long words;
512- in newer Tailwind versions, `break-words` may be written as `wrap-break-word`;
513- check the documentation for the project's current Tailwind version before using wrapping, overflow, text-wrap, grid, spacing, or arbitrary-value classes;
514- if an element is inside a flex container and long text breaks its width, check whether `wrap-anywhere` is appropriate;
515- use `truncate` for short lines in cards;
516- wrap body text instead of allowing horizontal overflow;
517- text must not render over a menu, popover, or modal;
518- test with a long string containing no spaces.
519
520For an editable block:
521
522```tsx
523className = "min-w-0 wrap-break-word whitespace-pre-wrap";
524```
525
526If the project uses an older Tailwind version where `wrap-break-word` is unavailable, check the installed Tailwind version and the official documentation or version notes, then use a supported equivalent: `break-words`, an arbitrary value, or a CSS property.
527
528For a badge:
529
530```tsx
531className = "inline-flex whitespace-nowrap";
532```
533
534A badge must not compress text vertically. If it does not fit, move it to a new line or use `truncate` with an explicit, understandable width.
535
536---
537
538# 17. Tailwind CSS: Verify Current Class Names
539
540The AI agent must check the Tailwind version installed in the project before using new or potentially version-dependent classes.
541
542Process:
543
5441. Inspect `package.json` and the lockfile.
5452. Determine the Tailwind major version.
5463. If a class may differ between versions, check the official documentation for that exact version.
5474. Do not replace classes mechanically without verification.
5485. When using an arbitrary value, confirm that it is included in the build output.
549
550Pay particular attention to:
551
552- `break-words` / `wrap-break-word` / `wrap-anywhere`;
553- `text-wrap`, `text-balance`, and `text-pretty`;
554- `overflow-*`;
555- `size-*`;
556- arbitrary colors such as `bg-[#151a21]`;
557- arbitrary shadows;
558- arbitrary grid templates;
559- dynamic class names.
560
561Do not build dynamic Tailwind classes like this:
562
563```tsx
564const color = "red";
565return <div className={`bg--500`} />;
566```
567
568Tailwind may not detect that class during the build. Use a map:
569
570```tsx
571const colorClassName = {
572 danger: "bg-red-500",
573 success: "bg-emerald-500",
574};
575```
576
577If an important overlay background must not depend on Tailwind's build output, using an inline `style.backgroundColor` is acceptable.
578
579---
580
581# 18. Layout and Sidebar Collapse
582
583Collapsing a sidebar or drawer must not change the page height or leave an empty block.
584
585Rules:
586
587- app shell: `h-dvh min-h-dvh overflow-hidden`;
588- internal regions: `flex min-h-0 flex-1 overflow-hidden`;
589- enable scrolling only on the appropriate region with `overflow-y-auto`;
590- when collapsing, change width/flex-basis rather than height;
591- a collapsed sidebar must have a stable width;
592- provide a clear control for restoring the sidebar;
593- destructive or creation actions must not remain as isolated buttons without context;
594- preferences may be persisted in localStorage.
595
596Example:
597
598```tsx
599<main className="flex h-dvh min-h-dvh flex-col overflow-hidden">
600 <div className="flex min-h-0 flex-1 overflow-hidden">
601 <Sidebar className="h-full min-h-0 shrink-0" />
602 <section className="min-h-0 flex-1 overflow-y-auto" />
603 </div>
604</main>
605```
606
607---
608
609# 19. Browser APIs and localStorage
610
611In Next.js, browser APIs are available only in Client Components.
612
613Rules:
614
615- a file that uses `localStorage`, `window`, `document`, drag and drop, or `contenteditable` must include `"use client"`;
616- do not read `localStorage` in a Server Component;
617- do not cause hydration errors with different initial values;
618- wrap storage operations in `try/catch`;
619- storage failures must not break the UI;
620- verify persisted UI preferences after a reload;
621- the build must not fail with `window is not defined`.
622
623Example:
624
625```tsx
626const toggle = useCallback(() => {
627 setIsCollapsed((current) => {
628 const next = !current;
629
630 try {
631 window.localStorage.setItem(KEY, next ? "true" : "false");
632 } catch {
633 // UI still works without browser storage.
634 }
635
636 return next;
637 });
638}, []);
639```
640
641Verify that:
642
643- the default state works with empty storage;
644- a reload preserves the state;
645- private mode or storage errors do not break the screen;
646- the build does not fail with `window is not defined`.
647
648---
649
650# 20. Relationships Between Tools
651
652If one entity is linked to another, the relationship must be real:
653
654- store it in the model;
655- show it in the UI;
656- clicking it opens the linked entity;
657- when creating the related entity, save the relationship immediately;
658- preserve the relationship during import/export;
659- include the relationship in search/filter behavior when useful;
660- if the related entity is deleted, show a fallback in the UI.
661
662Do not create a decorative "Link" button if the relationship is not persisted.
663
664---
665
666# 21. Unified Domain Operations
667
668Each user operation must have a single source of truth.
669
670Do not:
671
672- create an entity one way from the slash menu;
673- create it another way from the toolbar;
674- bypass validation from the command palette;
675- duplicate mutation logic in the context menu.
676
677Instead:
678
679- keep the domain operation in one place;
680- have UI components call that operation;
681- use the same validation and constraints for every entry point.
682
683---
684
685# 23. Accessibility
686
687Required:
688
689- use `<button>` for actions;
690- use `<a>` for navigation;
691- add `aria-label` to icon-only buttons;
692- provide labels for inputs;
693- show a visible focus state;
694- support keyboard navigation;
695- close modals and popovers on `Escape`;
696- close popovers on outside click;
697- use a focus trap in modals;
698- do not use color as the only way to communicate meaning;
699- do not replace `<button>` with ``.
700
701---
702
703# 24. Loading, Empty, and Error States
704
705Data-driven screens must account for:
706
707- loading;
708- success;
709- empty state;
710- permission denied;
711- network error;
712- server error;
713- retry.
714
715A blank screen with no explanation is a bug.
716
717---
718
719# 25. Security
720
721Required:
722
723- keep secrets on the server only;
724- use runtime validation;
725- enforce access control on the server;
726- validate file MIME types and sizes;
727- sanitize user-provided HTML;
728- do not use `dangerouslySetInnerHTML` without a sanitizer;
729- do not log tokens or personal data;
730- do not trust `role` or `userId` values supplied by the browser.
731
732---
733
734# 26. Performance
735
736Measure first, then optimize.
737
738Use:
739
740- dynamic imports for heavy editor, chart, map, and PDF modules;
741- image optimization;
742- virtualization for large lists;
743- abort/stale-request protection for search;
744- selectors to reduce rerenders.
745
746Do not add memoization without a reason.
747
748---
749
750# 27. Test the Design with Realistic Content
751
752For additional guidance on interface quality, you may refer to:
753
754- https://jakub.kr/skills/make-interfaces-feel-better
755
756This resource is useful when polishing typography, hover states, shadows, borders, spacing, optical alignment, micro-interactions, and the overall feel of the interface.
757
758Before completing a UI task, test it with:
759
760- a long word with no spaces;
761- a long Russian title;
762- a short title;
763- an empty title;
764- multiple tags;
765- a long list/category name;
766- multiple options in a dropdown;
767- active and inactive statuses;
768- a date and a missing date.
769
770Verify that:
771
772- nothing overlaps;
773- overlays cover the underlying content;
774- text does not show through menus;
775- badges do not compress text vertically;
776- elements do not crowd each other;
777- scrollbars do not cover important text;
778- hover and focus states are easy to read;
779- desktop and mobile widths both look correct.
780
781---
782
783# 28. Checks After Changes
784
785After code changes, run:
786
787```bash
788npm run typecheck
789npm run lint
790npm run build
791```
792
793If the UI was changed:
794
795- open the page in a browser;
796- complete the primary user flow;
797- test keyboard and mouse interaction;
798- test `Escape` and outside-click behavior;
799- test reloading;
800- test long text;
801- test a mobile viewport width;
802- take a screenshot if the visual layer changed.
803
804If browser verification is impossible, say so explicitly. Do not present `typecheck` as visual verification.
805
806---
807
808# 29. Git and the Working Tree
809
810Before making changes, inspect the current state:
811
812```bash
813git status --short
814```
815
816Rules:
817
818- do not revert someone else's changes without an explicit request;
819- do not use destructive commands without explicit permission;
820- do not perform unrelated refactoring;
821- do not commit automatically unless the user asks you to;
822- do not change line endings or reformat the entire project unnecessarily.
823
824---
825
826# 30. Final Report
827
828In the final response, state:
829
830- what changed;
831- which files are important;
832- which checks were run;
833- what could not be verified;
834- which risks remain.
835
836Keep the report concise and honest.
837

评论 (0)