Aller au contenu principal

Component Documentation Guide

Last Updated: November 5, 2025
Project: Baldr Dashboard
Standards: JSDoc 3.x + TypeScript


Table of Contents

  1. Introduction
  2. Documentation Standards
  3. Atomic Design Pattern
  4. Component Documentation Templates
  5. JSDoc Tag Reference
  6. Code Examples Best Practices
  7. Data Flow Documentation
  8. Accessibility Documentation
  9. Review Checklist

Introduction

This guide establishes documentation standards for all components in the Baldr Dashboard project. Following these guidelines ensures consistency, maintainability, and helps developers quickly understand component behavior and integration patterns.

Goals

  • Consistency: Uniform documentation structure across all components
  • Completeness: Cover functionality, props, state, side effects, and integration
  • Clarity: Clear, concise explanations with practical examples
  • Maintainability: Easy to update as components evolve

When to Document

Always Document:

  • Component purpose and responsibility
  • Props interface with types and descriptions
  • State management (useState, useReducer, context)
  • Side effects (useEffect, API calls)
  • Event handlers and callbacks
  • Complex logic or algorithms
  • Integration with external libraries
  • Accessibility features

Don't Document:

  • Self-explanatory variable names
  • Trivial implementations
  • Standard React patterns without customization

Documentation Standards

File-Level Documentation

Every component file should start with a comprehensive JSDoc block:

/**
* ComponentName
*
* @description
* Brief one-sentence description.
*
* Detailed explanation covering:
* - What the component does
* - When to use it
* - Key features or behaviors
* - Integration patterns
*
* @component
* @category [Atom|Molecule|Organism|Template|Page]
*
* @example
* ```tsx
* <ComponentName
* prop1="value"
* prop2={callback}
* />
* ```
*
* @see RelatedComponent - Brief relation description
* @see ExternalDoc.md - Additional context
*/

Props Documentation

Document props using TypeScript interfaces with JSDoc comments:

/**
* ComponentName Props
*
* @interface ComponentNameProps
*/
interface ComponentNameProps {
/**
* Brief description
* @required [if not optional]
* @default defaultValue [if applicable]
*/
propName: PropType;

/**
* Callback description with parameters
* @param arg1 - First argument description
* @returns Return value description
*/
onEvent?: (arg1: Type) => void;

/**
* Complex prop with multiple possibilities
* @example "option1" | "option2" | "option3"
*/
mode: "option1" | "option2" | "option3";
}

State Documentation

Document state variables and their purpose:

/**
* Controls visibility of the modal dialog
* @state
*/
const [isOpen, setIsOpen] = useState(false);

/**
* Stores validated form data before submission
* @state
* @type {FormData | null}
*/
const [formData, setFormData] = useState<FormData | null>(null);

Hook Documentation

Document custom hooks and their return values:

/**
* Custom Hook: useDataFetching
*
* @description
* Manages data fetching lifecycle with loading, error, and success states.
*
* @param {string} endpoint - API endpoint to fetch from
* @param {QueryOptions} options - TanStack Query options
*
* @returns {Object} Hook return value
* @returns {Data | undefined} returns.data - Fetched data
* @returns {boolean} returns.isLoading - Loading state
* @returns {Error | null} returns.error - Error state
* @returns {() => void} returns.refetch - Manual refetch function
*
* @example
* ```tsx
* const { data, isLoading, error } = useDataFetching('/api/users');
* ```
*/

Atomic Design Pattern

Baldr Dashboard follows the Atomic Design methodology for component organization.

Component Categories

🔹 Atoms

Definition: Basic building blocks that cannot be broken down further.

Examples:

  • Buttons
  • Input fields
  • Icons
  • Labels
  • Badges

Documentation Focus:

  • Visual variants (primary, secondary, danger)
  • Size options (small, medium, large)
  • States (hover, active, disabled, loading)
  • Accessibility attributes

Template:

/**
* Button Atom
*
* @description
* Reusable button component with multiple variants and states.
* Supports all native button attributes and custom styling.
*
* @component
* @category Atom
*
* @example
* ```tsx
* // Primary action button
* <Button variant="primary" onClick={handleSave}>
* Save Changes
* </Button>
*
* // Loading state
* <Button variant="secondary" loading>
* Processing...
* </Button>
* ```
*/

🔸 Molecules

Definition: Combinations of atoms that form simple functional units.

Examples:

  • Form fields (label + input + error)
  • Search bars (input + button)
  • Card headers (title + actions)
  • Language selectors (flags + dropdown)

Documentation Focus:

  • Composition of atoms
  • Internal state management
  • Validation logic
  • Event handling

Template:

/**
* InputField Molecule
*
* @description
* Complete form input field combining label, input element, and error display.
* Integrates with React Hook Form for validation and state management.
*
* @component
* @category Molecule
*
* **Features:**
* - Auto-generated IDs for accessibility
* - Built-in error display
* - Optional character counter
* - React Hook Form integration via forwardRef
*
* @example
* ```tsx
* // With React Hook Form
* const { register } = useForm();
* <InputField
* label="Email Address"
* type="email"
* {...register('email')}
* />
* ```
*
* @see useForm - React Hook Form documentation
*/

🔶 Organisms

Definition: Complex components composed of molecules and atoms with specific functionality.

Examples:

  • Table manager with sorting/filtering
  • Navigation menu
  • Login form
  • Statistics dashboard
  • Address forms

Documentation Focus:

  • Business logic
  • Data flow and state management
  • API integration
  • Complex interactions
  • Performance considerations

Template:

/**
* TableManager Organism
*
* @description
* Advanced data table with sorting, filtering, pagination, and CRUD operations.
* Supports six operation modes for different use cases.
*
* @component
* @category Organism
*
* **Operation Modes:**
* 1. `default` - Read-only table display
* 2. `edit` - In-line editing with save/cancel
* 3. `delete` - Row deletion with confirmation
* 4. `select` - Single/multiple row selection
* 5. `custom` - Custom action buttons
* 6. `hybrid` - Multiple operations combined
*
* **Key Features:**
* - Server-side pagination
* - Column sorting (single/multi)
* - Advanced filtering
* - Bulk operations
* - Export functionality
*
* @example
* ```tsx
* // Edit mode with inline editing
* <TableManager
* data={users}
* columns={columns}
* mode="edit"
* onEdit={handleEdit}
* onCancel={handleCancel}
* />
* ```
*
* @see TanStack Table - Table rendering library
* @see tableManager.examples.md - Detailed usage examples
*/

📄 Templates

Definition: Page-level layouts that combine organisms to create specific page structures.

Documentation Focus:

  • Layout structure
  • Responsive behavior
  • Section composition
  • Data passing patterns

🖥️ Pages

Definition: Specific instances of templates with real content and data.

Documentation Focus:

  • Route configuration
  • Data loading (loaders)
  • SEO metadata
  • Server-side rendering

Component Documentation Templates

Complete Component Example

/**
* StatisticsCard Molecule
*
* @description
* Displays a metric with icon, value, label, and optional trend indicator.
* Used throughout the dashboard to show KPIs and real-time statistics.
*
* @component
* @category Molecule
*
* **Visual Variants:**
* - `default` - White background with colored icon
* - `colored` - Gradient background with white text
*
* **Data Update:**
* Component automatically re-renders when value changes. Use React.memo()
* for performance optimization when rendering many cards.
*
* @example
* ```tsx
* // Basic usage with icon
* <StatisticsCard
* icon="group"
* label="Total Users"
* value={1234}
* />
*
* // With trend indicator
* <StatisticsCard
* icon="trending_up"
* label="Revenue"
* value="€45,678"
* trend={{ value: "+12%", positive: true }}
* />
*
* // Colored variant
* <StatisticsCard
* variant="colored"
* gradient="from-blue-500 to-purple-600"
* icon="star"
* label="Rating"
* value="4.8"
* />
* ```
*
* @see statisticsCards.organism.tsx - Parent organism component
* @see stats.context.tsx - Statistics data provider
*/

/**
* StatisticsCard Props
*
* @interface StatisticsCardProps
*/
interface StatisticsCardProps {
/**
* Material Symbols icon name
* @example "group" | "trending_up" | "euro_symbol"
* @see https://fonts.google.com/icons
*/
icon: string;

/**
* Metric label displayed below value
* @example "Total Users" | "Monthly Revenue"
*/
label: string;

/**
* Metric value (number or formatted string)
* @example 1234 | "€45,678" | "4.8"
*/
value: number | string;

/**
* Visual variant
* @default "default"
*/
variant?: "default" | "colored";

/**
* Tailwind gradient classes for colored variant
* @example "from-blue-500 to-purple-600"
*/
gradient?: string;

/**
* Trend indicator with percentage and direction
* @optional
*/
trend?: {
/** Percentage change as string */
value: string;
/** Whether trend is positive (green) or negative (red) */
positive: boolean;
};

/**
* Click handler for interactive cards
* @optional
*/
onClick?: () => void;

/**
* Additional CSS classes
* @optional
*/
className?: string;
}

const StatisticsCard: React.FC<StatisticsCardProps> = ({
icon,
label,
value,
variant = "default",
gradient,
trend,
onClick,
className,
}) => {
/**
* Determines card background classes based on variant
* @returns {string} Tailwind CSS classes
*/
const getBackgroundClasses = () => {
if (variant === "colored" && gradient) {
return `bg-gradient-to-r ${gradient} text-white`;
}
return "bg-white border border-gray-200";
};

return (
<div
className={cn(
"p-6 rounded-lg shadow-sm transition-all hover:shadow-md",
getBackgroundClasses(),
onClick && "cursor-pointer",
className
)}
onClick={onClick}
role={onClick ? "button" : undefined}
tabIndex={onClick ? 0 : undefined}
>
{/* Icon section */}
<div className="flex items-center justify-between mb-4">
<span className="material-symbols-rounded text-4xl">{icon}</span>
{trend && (
<span
className={cn(
"text-sm font-medium",
trend.positive ? "text-green-600" : "text-red-600"
)}
>
{trend.value}
</span>
)}
</div>

{/* Value and label */}
<div>
<p className="text-3xl font-bold mb-1">{value}</p>
<p className="text-sm opacity-75">{label}</p>
</div>
</div>
);
};

export default StatisticsCard;

JSDoc Tag Reference

Essential Tags

TagPurposeExample
@descriptionDetailed explanation@description Handles user authentication
@componentMarks as React component@component
@categoryComponent type@category Molecule
@paramFunction parameter@param {string} userId - User identifier
@returnsReturn value@returns {Promise<User>} User object
@exampleUsage exampleSee examples below
@seeCross-reference@see useAuth - Authentication hook
@defaultDefault value@default "primary"
@requiredRequired prop@required
@optionalOptional prop@optional
@deprecatedDeprecated feature@deprecated Use NewComponent instead

Advanced Tags

TagPurposeExample
@stateReact state variable@state
@constantConstant value@constant
@typeType annotation@type {FormData | null}
@interfaceInterface definition@interface UserProps
@throwsError conditions@throws {ValidationError} Invalid input
@asyncAsync function@async
@callbackCallback signature@callback onSaveCallback

Code Examples Best Practices

Example Structure

  1. Start Simple: Basic usage first
  2. Add Complexity: Show advanced features
  3. Real-World: Practical integration examples
  4. Edge Cases: Handle errors and special conditions

Good Examples

DO:

/**
* @example
* ```tsx
* // Basic usage
* <Button onClick={handleClick}>Click Me</Button>
*
* // With loading state
* <Button loading disabled>
* Processing...
* </Button>
*
* // Full form integration
* <form onSubmit={handleSubmit}>
* <Button type="submit" variant="primary">
* Submit
* </Button>
* </form>
* ```
*/

DON'T:

/**
* @example
* <Button /> // Too minimal, no context
*/

Multi-Step Examples

For complex components, show the complete setup:

/**
* @example
* ```tsx
* // 1. Setup form with validation
* const schema = z.object({
* email: z.string().email(),
* password: z.string().min(8)
* });
*
* // 2. Initialize form
* const { register, handleSubmit } = useForm({
* resolver: zodResolver(schema)
* });
*
* // 3. Render form with fields
* <form onSubmit={handleSubmit(onSubmit)}>
* <InputField
* label="Email"
* type="email"
* {...register('email')}
* />
* <PasswordInputField
* label="Password"
* {...register('password')}
* />
* <Button type="submit">Login</Button>
* </form>
* ```
*/

Data Flow Documentation

Context Providers

Document data flow for context-based components:

/**
* Data Flow: User Authentication
*
* ```
* UserProvider (context)
* ↓ provides
* { user, login, logout, isAuthenticated }
* ↓ consumed by
* LoginForm → calls login()
* ↓ triggers
* API call → credentialApi.login()
* ↓ updates
* UserContext state
* ↓ causes re-render
* Protected routes with new user data
* ```
*
* @see user.context.tsx - User context provider
* @see credential.api.ts - Authentication API
*/

TanStack Query Integration

/**
* Data Fetching with TanStack Query
*
* @example
* ```tsx
* // 1. Define query key and fetcher
* const { data, isLoading, error, refetch } = useQuery({
* queryKey: ['users', filters],
* queryFn: () => userApi.getAll(filters),
* staleTime: 5 * 60 * 1000, // 5 minutes
* });
*
* // 2. Handle states
* if (isLoading) return <Spinner />;
* if (error) return <ErrorMessage error={error} />;
*
* // 3. Render data
* return <UserTable data={data} onRefresh={refetch} />;
* ```
*
* **Cache Invalidation:**
* - On user creation: `queryClient.invalidateQueries(['users'])`
* - On user update: `queryClient.invalidateQueries(['users', userId])`
* - On logout: `queryClient.clear()`
*/

Accessibility Documentation

Document accessibility features explicitly:

/**
* Accessibility Features
*
* **ARIA Attributes:**
* - `aria-label`: Descriptive label for screen readers
* - `aria-expanded`: Indicates dropdown state
* - `aria-controls`: Links button to controlled element
*
* **Keyboard Navigation:**
* - `Tab`: Focus on button
* - `Enter/Space`: Activate button
* - `Escape`: Close dropdown (if open)
*
* **Focus Management:**
* - Visible focus indicator (2px blue ring)
* - Focus trap inside modal
* - Return focus to trigger on close
*
* **Screen Reader Support:**
* - Announces button state changes
* - Reads error messages on validation failure
* - Provides context for icon-only buttons
*
* @example
* ```tsx
* <button
* aria-label="Open user menu"
* aria-expanded={isOpen}
* aria-controls="user-menu"
* onClick={toggle}
* >
* <MenuIcon />
* </button>
* ```
*/

Review Checklist

Use this checklist when reviewing component documentation:

Content Completeness

  • File-level JSDoc block with description
  • Component category specified (Atom/Molecule/Organism)
  • Props interface fully documented
  • All props have type annotations
  • Default values documented
  • State variables explained
  • Side effects documented (useEffect)
  • Event handlers described

Code Examples

  • Basic usage example provided
  • Advanced features demonstrated
  • Integration patterns shown
  • Edge cases covered
  • Examples are syntactically correct
  • Examples follow project conventions

Cross-References

  • Related components linked with @see
  • External documentation referenced
  • API endpoints mentioned
  • Context providers linked
  • Hook dependencies noted

Accessibility

  • ARIA attributes documented
  • Keyboard navigation described
  • Focus management explained
  • Screen reader behavior noted

Code Quality

  • TypeScript types are accurate
  • No TypeScript errors
  • Follows project naming conventions
  • Consistent formatting
  • No spelling errors

Documentation Maintenance

When to Update Documentation

Update documentation when:

  • Adding new props or features
  • Changing component behavior
  • Deprecating functionality
  • Fixing bugs that affect usage
  • Adding integration examples
  • Improving accessibility

Versioning

Mark breaking changes clearly:

/**
* @version 2.0.0
* @breaking
* Prop `onSelect` now receives full object instead of just ID
*
* **Before (v1.x):**
* ```tsx
* onSelect={(id) => handleSelect(id)}
* ```
*
* **After (v2.x):**
* ```tsx
* onSelect={(item) => handleSelect(item.id, item.name)}
* ```
*/

Quick Reference Templates

Atom Template

/**
* [ComponentName] Atom
*
* @description
* One-line description.
*
* @component
* @category Atom
*
* @example
* ```tsx
* <ComponentName prop="value" />
* ```
*/
interface ComponentNameProps {
/** Prop description */
prop: string;
}

Molecule Template

/**
* [ComponentName] Molecule
*
* @description
* Brief description of composition and purpose.
*
* @component
* @category Molecule
*
* **Features:**
* - Feature 1
* - Feature 2
*
* @example
* ```tsx
* <ComponentName prop="value" />
* ```
*/

Organism Template

/**
* [ComponentName] Organism
*
* @description
* Detailed description with use cases.
*
* @component
* @category Organism
*
* **Key Features:**
* - Feature 1 with explanation
* - Feature 2 with explanation
*
* **Data Flow:**
* Context/API → Component → Child components
*
* @example
* ```tsx
* // Complete integration example
* <ComponentName
* data={data}
* onAction={handler}
* />
* ```
*
* @see RelatedComponent
* @see docs/SYSTEM.md
*/

Conclusion

Following this guide ensures:

  • Consistent documentation across the entire codebase
  • Faster onboarding for new developers
  • Better maintainability as the project evolves
  • Reduced bugs from clear component contracts
  • Improved accessibility through explicit documentation

For questions or suggestions, please update this guide to reflect evolving best practices.


Document Version: 1.0
Last Updated: November 5, 2025
Maintained By: Development Team