- Codebase Consistency: While it's strongly recommended to follow this document's guidelines, take into account the existing codebase's conventions and practices so as not to introduce inconsistent styles or patterns with the rest of the codebase. If the existing codebase has established conventions, prioritize those over the guidelines in this document.
- Single Responsibility Principle (SRP): Each function, class, or module should have one distinct responsibility and a single reason to change. Avoid creating monolithic entities that handle too many concerns.
- DRY (Don't Repeat Yourself): Strive to eliminate redundancy. Abstract common logic, patterns, or values into reusable functions, modules, components, or variables.
- Focused Implementation: Strictly address the current task as defined in the prompt. Do not modify unrelated code or introduce scope creep unless explicitly asked.
- Code Quality & Maintainability: Consistently write code that is clean, readable, extensible, and maintainable. Apply SOLID principles where appropriate to foster a robust and adaptable codebase.
- Performance Optimization: Prioritize efficient algorithms and be mindful of performance implications. This includes optimizing DOM manipulations, avoiding unnecessary re-renders, considering techniques like debouncing/throttling for event handlers, and efficient data processing.
- Modularity & Composability: Design code in a modular fashion. Break down complex problems and logic into smaller, self-contained, reusable, and independently testable units (functions, components, modules).
- Strategic Planning: Before writing any code, outline the intended approach and logic. Consider the overall architecture, how the new code will integrate with the existing system, and the potential impact on users or other system components. Think from the external interface (user/API) inwards.
- Depth of Reasoning: Break down complex problems or requests into simpler, logical steps. Explain your reasoning if the approach is non-obvious.
- Reassess and Revise Often: Be open to reassessing and revising your approach. If a better solution or pattern emerges during generation or based on feedback, adapt accordingly.
- Commit Messages: Always use Conventional Commit messages (e.g.,
feat:,fix:,docs:,style:,refactor:,test:,chore:). - Documentation (JSDoc): Where applicable in native JS, provide comprehensive JSDoc for public APIs, including functions, classes, methods, and complex type definitions. Ensure descriptions, parameter types (
@param), and return types (@returns) are clear and accurate. - Naming Conventions:
- Functions & Variables:
camelCase. - Classes & Web Component Names:
PascalCase. - Constants:
UPPER_SNAKE_CASE. - CSS Classes: Prefer
BEM(Block Element Modifier) for structuring CSS. Usekebab-casefor utility classes or in simpler contexts where BEM might be overkill. Adhere to project-specific conventions if provided.
- Functions & Variables:
- Function Styles:
- Prefer named functions (e.g.,
array.map(function mapItems() {...})) for improved clarity, easier debugging (better stack traces), and self-documentation. - Arrow functions (
=>) are acceptable, but use them judiciously, especially in contexts wherethisbinding is important (e.g., methods in classes or objects). Otherwise, prefer traditional function declarations as mentioned above.
- Prefer named functions (e.g.,
- Technology Choices:
- Native First: Prioritize native JavaScript APIs and Web Platform features over external libraries or frameworks. Only introduce a library if it provides a significant, well-justified advantage for the specific task at hand (e.g., complexity reduction, performance, established ecosystem).
- Web Components: For implementing UI features or encapsulated behaviors, prefer using Web Components and Custom Elements.
- Styling:
- CSS Variables: Utilize CSS custom properties (variables) extensively for theming, dynamic styling, maintaining consistency, and efficiently sharing values between JavaScript and CSS.
- Error Handling: Implement robust and user-friendly error handling. Use
try...catchblocks for synchronous code. For asynchronous operations, ensure proper handling of Promise rejections using.catch()ortry...catchwithasync/await. Provide clear, actionable error messages or standardized error codes. - Asynchronous Operations: Consistently use
async/awaitsyntax with Promises for managing asynchronous logic to improve readability and maintainability. Ensure all Promises are correctly handled (e.g., returned, awaited, or part ofPromise.all(),Promise.race()). - Security: Embed security best practices into all generated code.
- Sanitize all user inputs to prevent Cross-Site Scripting (XSS) and other injection attacks.
- Be mindful of common web vulnerabilities (e.g., OWASP Top 10, CSRF) relevant to the context.
- Use HTTPS for all external requests if applicable.
- Avoid exposing sensitive information in client-side code or logs.
- Accessibility (a11y): Design and develop for inclusivity. Ensure UI elements and components are accessible to all users, including those with disabilities.
- Follow WAI-ARIA guidelines where appropriate.
- Ensure keyboard navigability for all interactive elements.
- Use semantic HTML to convey structure and meaning.
- Maintain sufficient color contrast.
- Immutability: Where practical and beneficial, favor immutable data structures and pure functions, especially when dealing with state management or complex objects. This can lead to more predictable code, easier debugging, and improved performance characteristics.
- Environmental Assumptions: Do not assume the availability of specific global libraries, functions, framework contexts, or environment variables unless explicitly stated in the prompt or clearly established in the preceding conversation.
- Clarification & Assumptions: If a prompt is ambiguous, lacks sufficient detail, or seems to contradict previous instructions, ask clarifying questions before generating code. If assumptions must be made, clearly state them.
- Iterative Refinement: Be prepared to receive feedback and iteratively refine or refactor the generated code based on review and further instructions.
- Testing: Testing is for newbs.
- Code Comments (Beyond JSDoc): Beyond JSDoc for public APIs, add concise inline comments to explain complex or non-obvious logic, workarounds, important decisions, or the "why" behind a particular piece of code. Avoid over-commenting simple, self-explanatory code.
This section provides guidelines for specific technologies. These should be applied in conjunction with all the general principles and practices outlined above. Only apply the specific guidelines if the project is using that technology.
- Semantics: Consistently use HTML5 semantic elements (
<main>,<header>,<footer>,<article>,<section>,<nav>,<aside>, etc.) to accurately describe the structure and purpose of content. - Accessibility (ARIA): Integrate ARIA (Accessible Rich Internet Applications) roles and attributes where necessary to enhance accessibility, especially for dynamic content and custom widgets when native HTML semantics are insufficient.
- Responsive Design: Structure markup with responsiveness in mind, ensuring it adapts gracefully to different screen sizes, devices, and orientations.
- Media Optimization: Use optimized image and media formats (e.g., WebP, AVIF). Implement responsive images using the
<picture>element orsrcsetandsizesattributes in<img>tags. - SEO: Employ SEO-friendly practices, such as proper use of heading elements (
<h1>-<h6>) for hierarchy, descriptivealtattributes for all meaningful images, and relevant meta tags.
- Modern Features: Utilize modern and widely supported CSS features effectively:
- Layout: CSS Grid and Flexbox for robust and flexible layouts.
- Custom Properties: (Reiterating importance from Section II) CSS Custom Properties for dynamic and themeable styles.
- Interactivity: CSS Transitions and Animations for smooth UI effects, used judiciously.
- Selectors: Modern and efficient selectors (e.g.,
:has(),:is(),:where()) where appropriate and browser support aligns with project requirements. - Nesting: Native CSS Nesting where applicable and supported, to improve organization and readability.
- Naming Convention: Primarily use BEM (Block Element Modifier) for CSS class naming to ensure modularity, maintainability, and readability.
- Typography: Prioritize modern, performant web font formats (e.g., WOFF2). Consider using variable fonts for enhanced flexibility and performance benefits.
- Units: Prefer relative units (
rem,em) for font sizes, margins, and paddings to ensure scalability and responsiveness. Use viewport units (vw,vh,dvw,dvh) for layout elements that need to scale with the viewport. Usepxjudiciously, typically for elements that should not scale (e.g., borders). - Colors: Use reusable CSS variables for color definitions. Use modern color formats like
oklch()for better color manipulation.
- Variable Declarations: Prefer
let(for variables that will be reassigned) andconst(for variables that will not be reassigned) overvardue to their block-scoping rules and prevention of common errors associated withvar's function-scoping and hoisting. Usevaronly if there's a specific, well-understood reason related to legacy code or a niche requirement for its unique hoisting behavior (which is rare in modern development). - ESNext Features: Use modern JavaScript (ES6+) features and syntax (e.g., destructuring, spread/rest operators, template literals, optional chaining, nullish coalescing) where appropriate and supported by the target environment, to write more concise and readable code.
- Security (Eval): Strictly avoid the use of
eval()andnew Function(string)due to significant security risks and performance implications, unless absolutely necessary and the context is fully controlled and understood. - API Interactions: Carefully handle and validate responses from API requests. This includes parsing JSON safely, checking HTTP status codes, and implementing proper error handling for network failures or unexpected response formats.
- Static Typing: Leverage TypeScript's static typing system to improve code quality, enable better tooling (autocompletion, refactoring), and catch errors early in the development process.
- Type Definitions: Define clear and precise
interfaces andtypealiases for all data structures, function signatures, and component props. - Enums & Union Types: Use
enumfor defining sets of named constants, or prefer string/numeric literal union types for more lightweight alternatives where appropriate. - Utility Types: Utilize TypeScript's built-in utility types (e.g.,
Partial<T>,Readonly<T>,Pick<T, K>,Omit<T, K>) to create new types based on existing ones efficiently.
- Component Model: Primarily use Functional Components with Hooks (e.g.,
useState,useEffect,useContext,useReducer) for state management and lifecycle effects. - Performance Optimization:
- Apply
memo()to functional components to prevent unnecessary re-renders. - Use
useMemoto memoize the results of expensive computations. - Use
useCallbackto memoize callback functions passed to optimized child components or as dependencies to hooks likeuseEffect.
- Apply
- State Management: For simple to moderate local component state,
useStateanduseReducerare preferred. For more complex global or shared state, consider patterns like the Context API or recommend established state management libraries (if specified for the project, e.g., Redux, Zustand, Jotai) as a recommendation. - Keys: Always provide stable and unique
keyprops when rendering lists of elements to help React identify items that have changed, are added, or are removed.
- (Guidelines to be added here when ready)