diff --git a/2-common/common-mobile-app.md b/2-common/common-mobile-app.md new file mode 100644 index 0000000..8b13789 --- /dev/null +++ b/2-common/common-mobile-app.md @@ -0,0 +1 @@ + diff --git a/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-1-architecture-rules.mdc b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-1-architecture-rules.mdc new file mode 100644 index 0000000..6be9692 --- /dev/null +++ b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-1-architecture-rules.mdc @@ -0,0 +1,154 @@ +--- +description: USE WHEN designing frontend architecture, implementing design patterns, organizing code structure, or discussing architectural decisions for creating maintainable, scalable component architectures +globs: ["**/*"] +alwaysApply: false +--- +# Hybrid Development Architecture Rules + +## SOLID Principles in Components + +### Single Responsibility Principle (SOLID - S) +- Each component must have ONE clear, well-defined purpose across all target platforms +- Split components that handle multiple concerns into smaller, focused units +- Name components based on their single responsibility (Button, Modal, UserCard) +- If component description uses "AND", consider splitting it +- Keep business logic separate from platform-specific rendering logic + +### Open/Closed Principle (SOLID - O) +- Design components for extension without modification across platforms +- Use composition patterns over inheritance +- Leverage props/attributes/parameters for cross-platform configuration +- Implement plugin patterns for platform-specific extensibility +- Use platform-agnostic styling approaches for customization + +### Liskov Substitution Principle (SOLID - L) +- Components should be replaceable with their implementations without breaking functionality on any platform +- Ensure consistent behavior across component variants and platforms +- Maintain compatible interfaces when extending components across different environments +- Avoid breaking contracts in component inheritance chains +- Test component substitutability across different platforms and contexts + +### Interface Segregation Principle (SOLID - I) +- Create focused, minimal interfaces rather than large, monolithic ones +- Split complex prop/parameter interfaces into smaller, platform-specific contracts +- Avoid forcing components to depend on platform-specific props they don't use +- Use composition to combine focused interfaces when needed +- Keep component APIs lean and purposeful across platforms + +### Dependency Inversion (SOLID - D) +- Depend on abstractions, not platform-specific implementations +- Inject dependencies through props, context, or dependency injection containers +- Abstract API calls behind service interfaces that work across platforms +- Use dependency injection for external services and platform-specific features + +## Component Structure & Organization + +### File Organization +- One component per file with descriptive filename +- Co-locate related files (styles, tests, types, platform-specific implementations) in component folders +- Use consistent naming conventions across the project and platforms +- Group related components in feature/domain folders +- Keep shared/common components in dedicated cross-platform directory + +### Component Interface Design +- Define clear, minimal interfaces that work across platforms +- Use descriptive, semantic property names +- Distinguish between required and optional parameters +- Provide sensible defaults for optional parameters +- Document platform-specific behaviors and limitations + +### Composition Patterns +- Favor composition over inheritance for cross-platform component reuse +- Use compound component patterns for complex UI that adapts to different platforms +- Implement render props or equivalent patterns for behavior sharing +- Create higher-order components for cross-cutting concerns +- Use slots/children/content projection for platform-appropriate content injection + +## Component Data Flow + +### Component Communication +- Pass data down through props, attributes, or parameters +- Use callback functions or event systems for upward communication +- Implement clear interfaces between parent and child components +- Avoid deep prop drilling through component hierarchies +- Use context, state management, or dependency injection for cross-cutting data + +## Component Lifecycle & Side Effects + +### Effect Management +- Handle side effects in appropriate lifecycle hooks or equivalent mechanisms +- Clean up subscriptions and event listeners across platforms +- Avoid memory leaks from uncleaned references +- Implement proper error boundaries or equivalent error handling +- Use cancellation tokens for async operations + +### Event Handling +- Use consistent naming for event handlers across platforms +- Handle events at the appropriate component level +- Prevent event bubbling when necessary and supported +- Implement proper input event handling (keyboard, touch, mouse) +- Clean up event listeners on component destruction + +## Component Optimization + +### Component Design for Performance +- Design components with minimal re-render impact across platforms +- Use proper component boundaries to isolate updates +- Implement efficient composition patterns that work across different rendering engines +- Design reusable components with cross-platform performance in mind + +## Error Handling + +### Component Error Boundaries +- Implement error boundaries at strategic component levels where supported +- Provide fallback UI for component errors appropriate to each platform +- Log errors with sufficient context for debugging across platforms +- Allow graceful error recovery when possible +- Avoid cascading failures through proper error isolation + +### Input Validation +- Validate props/parameters at component boundaries +- Use type systems for compile-time checking where available +- Implement runtime validation for external data +- Provide clear error messages for invalid inputs appropriate to each platform +- Handle edge cases gracefully across platforms +- Validate data at all entry points +- Use schema validation for complex data structures +- Provide immediate feedback on invalid input using platform-appropriate UI patterns +- Sanitize user input before processing +- Implement client-side validation as UX enhancement, not security + +## Component Structure Standards + +### Platform-Appropriate Structure +- Build components with proper structural foundation for each platform +- Follow semantic principles appropriate to each target platform +- Ensure components generate accessible output where supported + +## Testing Architecture + +### Testable Design +- Design components with testing in mind across platforms +- Use dependency injection for external services +- Keep business logic in pure functions separate from platform-specific code +- Avoid testing implementation details +- Focus on component behavior and outputs across different platforms + +### Test Organization +- Co-locate tests with components +- Use descriptive test names that explain behavior +- Group related tests logically +- Test component integration across platforms, not just units +- Mock external dependencies and platform-specific APIs appropriately + +## 12-Factor App Principles for Hybrid Development + +### Configuration Management (12-Factor III) +- Externalize configuration through environment variables or platform-appropriate configuration systems +- Separate development, staging, and production configurations across all platforms +- Avoid hardcoding environment-specific values in source code +- Use configuration objects injected at runtime for each platform + +### Development and Production Parity (12-Factor X) +- Maintain consistent API contracts across environments and platforms +- Use feature flags instead of environment-specific or platform-specific code branches \ No newline at end of file diff --git a/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-2-ui-patterns-rules.mdc b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-2-ui-patterns-rules.mdc new file mode 100644 index 0000000..170ede2 --- /dev/null +++ b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-2-ui-patterns-rules.mdc @@ -0,0 +1,161 @@ +--- +description: USE WHEN implementing UI patterns and user interactions to create interfaces that are intuitive, accessible, and performant across all devices and user capabilities +globs: ["**/*"] +alwaysApply: false +--- + +# Hybrid UI/UX Patterns Rules + +## Responsive Design Patterns + +### Mobile-First Development (Progressive Enhancement) +- Start all layouts with mobile viewport constraints +- Use relative units (rem, em, %, vw, vh) over fixed pixels +- Design touch-friendly interfaces from the ground up +- Implement progressive enhancement for larger screens + +### Flexible Layout Systems +- Use layout primitives that adapt across platforms (View, ScrollView, etc.) +- Avoid fixed widths on container elements +- Implement fluid spacing with token-based design systems +- Design components to reflow gracefully at any screen size + +### Breakpoint Management +- Define semantic layout breakpoints for key devices (mobile, tablet, desktop) +- Use consistent breakpoint logic across platform-specific styles +- Avoid magic numbers in responsive rules +- Create utility classes or tokens for responsive behavior +- Document breakpoint decisions in comments + +## User Interface Patterns + +### Consistent Interaction States +- Define press, focus, active, and disabled states for all interactive elements +- Use consistent timing for state transitions (150-300ms) +- Provide immediate visual feedback for user actions +- Implement loading states for async operations +- Maintain state consistency across similar components + +### Visual Hierarchy +- Use size, color, and spacing to establish clear hierarchy +- Apply consistent spacing scale throughout the interface +- Ensure important elements have sufficient visual weight +- Group related content with proximity and visual cues +- Use typography scale to reinforce content hierarchy + +### Empty and Error State Design +- Show skeleton screens for better perceived performance +- Provide progress feedback for multi-step processes +- Design meaningful empty states with clear actions +- Design error states with clear recovery actions + +## Form Design Patterns + +### Input Design +- Label all form inputs clearly and descriptively +- Use appropriate input types for data (email, tel, date) +- Implement placeholder text as hints, not replacements for labels +- Group related fields with visual sections +- Show input format requirements upfront + +### Form Validation and Accessibility +- Show inline validation feedback near relevant fields +- Use clear, actionable error messages for form validation +- Validate on blur for individual fields +- Preserve user input when showing validation errors +- Highlight form fields that need attention with visual indicators +- Associate labels with form controls programmatically +- Provide clear instructions before form fields +- Mark required fields clearly and consistently + +### Progressive Disclosure +- Show only essential fields initially +- Reveal additional options contextually +- Use progressive steps for complex forms +- Implement collapsible sections for optional areas +- Keep forms as concise as possible + +## Animation and Motion Patterns + +### Performance-Conscious Animation (Performance First) +- Use GPU-accelerated transitions (translate, scale, opacity) +- Avoid layout-triggering animations (top/left/width) +- Keep animation duration under 300ms for UI feedback +- Use easing curves that feel natural (ease-out for entrances) +- Provide reduced-motion alternatives + +### Meaningful Motion +- Use animation to guide user attention to important changes +- Animate state transitions smoothly to maintain context +- Keep animations subtle and purposeful +- Ensure animations enhance rather than distract from content +- Provide clear entry and exit animations for overlays + +## Touch and Gesture Patterns + +### Touch Target Optimization +- Make interactive elements at least 44x44 units +- Add sufficient padding around touchable items +- Account for thumb reach zones on mobile devices +- Prevent accidental touches with spacing and alignment +- Use visual feedback for touch interactions + +### Gesture Support +- Support common touch gestures (tap, swipe, long press) +- Provide visual feedback during gesture recognition +- Don't rely solely on gestures for core functionality +- Implement gesture fallbacks where needed + +## Navigation Patterns + +### Clear Navigation Hierarchy +- Implement consistent navigation patterns across screens +- Use breadcrumbs or back buttons for deep navigation structures +- Provide clear indicators for current location +- Ensure navigation is accessible across devices +- Structure navigation with clear visual hierarchy + +### Menu and Dropdown Patterns +- Support both touch and keyboard navigation where applicable +- Implement proper focus or highlight management for menus +- Provide clear visual indicators for expandable items +- Handle menu positioning for edge cases (viewport boundaries) + +## Content Patterns + +### Typography and Readability +- Use adequate line height (1.4-1.6) for body text +- Implement proper content hierarchy with heading levels +- Ensure sufficient color contrast for all text +- Use consistent text alignment and spacing +- Support user font size preferences + +### Image and Media Handling +- Implement responsive images across device types +- Use lazy loading where possible +- Provide alternative text for all meaningful images +- Optimize image formats and sizes for mobile delivery +- Handle loading and error states for media content + +## Accessibility-First Patterns + +### Screen Reader Optimization +- Add descriptive labels for interactive elements +- Announce dynamic content changes with live regions or alerts +- Provide context for complex interactions +- Design interfaces that work well with assistive technologies + +## Performance UI Patterns + +### Perceived Performance +- Show content immediately, even if incomplete +- Use optimistic UI updates for user actions +- Implement skeleton screens during data loading +- Provide immediate feedback for user interactions +- Use progressive enhancement for non-critical features + +### Efficient Updates +- Minimize layout thrashing and unnecessary re-renders +- Use virtualization for large lists or scrolls +- Batch state updates where possible +- Optimize rendering performance with memoization or pure components \ No newline at end of file diff --git a/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-3-data-state-rules.mdc b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-3-data-state-rules.mdc new file mode 100644 index 0000000..2bed387 --- /dev/null +++ b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-3-data-state-rules.mdc @@ -0,0 +1,78 @@ +--- +description: USE WHEN handling application state and data flow for efficient, predictable data and state management +globs: ["**/*"] +alwaysApply: false +--- + +# Hybrid Frontend Data & State Management Rules + +## 12-Factor App Principles for Hybrid Frontend + +### Stateless Components (12-Factor VI) +- Design components to be stateless when possible +- Store session state in client-side or shared backing services (localStorage, SecureStore, etc.) +- Avoid storing session data in the memory of a single front-end instance +- Make components work regardless of previous interactions +- Handle component state restoration gracefully + +## State Management Principles + +### State Ownership and Boundaries (Single Responsibility) +- Keep state as close to its usage as possible +- Lift state up only when multiple components genuinely need access +- Avoid prop drilling beyond 2-3 component levels +- Clearly define state ownership at component boundaries +- Use context or state management libraries for deeply nested sharing + +### Immutability Patterns (Functional Programming) +- Treat all state as immutable - never mutate existing state objects +- Use spread operators for shallow object/array updates +- Implement pure update functions for state transformations +- Use immutability helper libraries for complex nested updates +- Return new references when state changes + +### State Types and Separation +- Distinguish between UI state and business/domain state +- Separate local component state from global application state +- Handle server state differently from client state +- Compute derived state rather than storing it +- Keep state structure flat to avoid nested update complexity + +## Data Flow Architecture + +### Unidirectional Data Flow +- Data flows down through props/attributes +- Events and actions flow up through callbacks +- Avoid two-way data binding patterns when possible +- Make data flow explicit and traceable +- Use event emitters or observable patterns for complex communications + +### Action Patterns +- Use descriptive action names that explain intent +- Keep actions pure and predictable +- Separate action creators from business logic +- Handle async operations with consistent patterns +- Implement proper error handling for actions + +## State Persistence + +### Local Storage Management +- Persist critical user state across sessions (use appropriate storage API like AsyncStorage) +- Serialize and deserialize state properly +- Handle storage quota limits gracefully +- Clear sensitive data appropriately + +### Session Management +- Clear sensitive data on logout +- Handle session expiration gracefully +- Restore appropriate state after app reload +- Implement proper state hydration +- Handle authentication state changes + +## Data Validation + +### State Integrity +- Ensure state transitions are valid +- Prevent invalid state combinations +- Log state violations for debugging +- Implement state invariants \ No newline at end of file diff --git a/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-4-api-integration-service-layer.mdc b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-4-api-integration-service-layer.mdc new file mode 100644 index 0000000..0fcdb2d --- /dev/null +++ b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-4-api-integration-service-layer.mdc @@ -0,0 +1,33 @@ +--- +description: USE WHEN intergrating APIs +globs: ["**/*"] +alwaysApply: false +--- +# Hybrid API Integration and Service Layer + +### Service Abstraction +- Create abstraction layer for all API interactions +- Handle errors at service boundaries, not in components +- Transform API responses to match application models +- Implement consistent request/response patterns +- Use proper HTTP methods and status code handling + +### Loading State Management +- Track loading state for all async operations +- Handle concurrent requests appropriately +- Show appropriate UI feedback during loading +- Implement request cancellation for cleanup (e.g., using AbortController or cancellation tokens if supported) +- Use loading state to prevent duplicate requests + +### Error Handling Strategies +- Catch and handle errors at appropriate levels +- Provide meaningful error messages to users +- Implement retry mechanisms for transient failures +- Log errors with sufficient context for debugging +- Handle network failures gracefully + +### Subscription Lifecycle +- Unsubscribe from data sources on component cleanup +- Prevent memory leaks from active subscriptions +- Implement proper cleanup in useEffect or lifecycle equivalents +- Handle subscription errors gracefully \ No newline at end of file diff --git a/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-5-performance-rules.mdc b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-5-performance-rules.mdc new file mode 100644 index 0000000..3dbc916 --- /dev/null +++ b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-5-performance-rules.mdc @@ -0,0 +1,107 @@ +--- +description: USE WHEN optimizing for speed, efficiency, and user experience while maintaining the performance optimization principles +globs: ["**/*"] +alwaysApply: false +--- +# Hybrid Frontend Performance Optimization Rules + +## Bundle and Asset Optimization + +### Code Splitting Strategies (Lazy Loading) +- Split code by routes and features to reduce initial bundle size +- Use dynamic imports for components not needed immediately +- Create separate chunks for vendor libraries and dependencies +- Implement lazy loading for conditional features and routes +- Load components on demand based on user interactions + +### Tree Shaking and Dead Code Elimination +- Import only specific functions from libraries, avoid default imports +- Use ES modules for better tree shaking support +- Remove unused code and dead branches regularly +- Avoid importing entire utility libraries when only using specific functions + +### Asset Optimization +- Compress and optimize images before bundling +- Use modern image formats (WebP) with fallbacks where supported +- Implement responsive images where applicable +- Use vector icons or icon libraries for small graphics +- Minimize and compress CSS and JavaScript files + +## Runtime Performance Optimization + +### Rendering Optimization (Performance First) +- Minimize component re-renders through proper state management +- Use memoization strategically for expensive computations +- Implement proper key props for list rendering +- Avoid creating objects and functions during render +- Use virtualization for large lists and tables + +### Memory Management +- Remove object references when components unmount +- Manage memory usage in hybrid apps to prevent performance drops + +### Efficient UI Operations +- Batch UI updates to reduce rendering overhead +- Avoid frequent style changes that trigger layout +- Optimize views rendered off-screen + +## Network and Loading Optimization + +### Resource Loading Strategies +- Preload critical resources if supported +- Implement progressive enhancement patterns +- Optimize critical rendering path +- Use offline support and caching mechanisms + +### Caching Strategies +- Use appropriate hybrid storage solutions for caching +- Cache API responses with proper invalidation +- Version static assets for cache busting + +### Request Optimization +- Batch multiple API calls when possible +- Implement request deduplication for concurrent requests +- Use efficient data fetching patterns +- Compress request and response payloads + +## Initial Load Performance + +### Critical UI Optimization +- Prioritize loading of essential UI components +- Defer non-critical assets and modules +- Remove unused CSS and JS where possible + +### JavaScript Loading Optimization +- Defer non-critical logic until after initial load +- Load third-party modules efficiently +- Implement loading strategies based on user interaction + +## User Experience Performance + +### Perceived Performance +- Show skeleton loaders or placeholders during data fetch +- Implement optimistic UI updates +- Provide immediate feedback for user actions +- Use progressive loading for images and assets + +### Smooth Interactions +- Keep main thread free for user input +- Respond to user actions within 100ms +- Implement instant touch feedback +- Debounce expensive operations triggered by user input + +## Performance Monitoring (DevOps) + +### Performance Budgets +- Track key metrics during development +- Add performance logging for hybrid render paths + +### Development Performance Practices +- Use profiling tools to measure component render times +- Add comments documenting performance decisions + +## Performance Testing + +### Performance Test Implementation +- Write tests to ensure performance budgets are met +- Measure and assert key render and interaction times \ No newline at end of file diff --git a/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-6-security-rules.mdc b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-6-security-rules.mdc new file mode 100644 index 0000000..a1f67c8 --- /dev/null +++ b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-6-security-rules.mdc @@ -0,0 +1,96 @@ +--- +description: USE WHEN securing frontend applications that protect both your users and your systems from common web security threats protect your applications and users from common security vulnerabilities +globs: ["**/*"] +alwaysApply: false +--- +# Hybrid Frontend Security Rules + +## Input Security and Data Validation (Defense in Depth) + +### User Input Sanitization +- Sanitize all user input before rendering or processing +- Escape HTML entities in dynamic content to prevent XSS +- Validate input on both client and server sides +- Use allowlists instead of blocklists for input validation +- Never trust data from external sources without validation + +### XSS Prevention (Defense in Depth) +- Use framework-provided safe rendering methods +- Avoid unsafe HTML rendering for user-generated content +- Apply appropriate content restrictions in hybrid environments +- Encode data based on context (HTML, URL, JavaScript) +- Use rendering mechanisms that automatically escape content + +### Form Security +- Implement proper input validation +- Use secure transport for all form submissions (HTTPS or native secure handlers) +- Validate file uploads thoroughly +- Implement rate limiting for form submissions +- Use anti-automation techniques when applicable + +## Authentication and Session Security (Defense in Depth) + +### Secure Token Handling +- Store authentication tokens securely (prefer secure storage mechanisms like SecureStore) +- Avoid localStorage or sessionStorage for sensitive tokens +- Implement proper token expiration and refresh handling +- Use platform-specific secure attributes where applicable +- Clear tokens on logout and session expiration + +### Session Management +- Handle session expiration gracefully +- Implement logout functionality that clears all sensitive data +- Clear sensitive data on session end +- Log session events securely +- Handle app lifecycle events (pause, background, close) + +## API Security + +### Secure API Communication +- Use HTTPS for all API communications +- Implement proper error handling without leaking sensitive info +- Validate API responses before use +- Handle API rate limiting gracefully +- Never expose API keys or sensitive configuration + +### Data Protection +- Encrypt sensitive data before storage +- Use secure communication protocols +- Implement proper CORS-like access control where needed +- Validate all data from external sources +- Handle PII data with care + +## Client-Side Security + +### Content Security Strategy +- Restrict content execution from untrusted sources +- Avoid inline scripts where possible +- Restrict resource loading to trusted domains +- Monitor security violations where applicable +- Review policies when adding third-party dependencies + +### Dependency Security +- Use lockfiles for consistent dependency versions + +### Error Handling and Information Disclosure +- Handle errors gracefully without exposing internal logic +- Log errors securely +- Provide user-friendly error messages +- Implement proper fallback mechanisms +- Track security-related error patterns + +## Third-Party Integration Security + +### External Service Integration +- Validate all third-party scripts before loading +- Use integrity checks for external resources when possible +- Isolate untrusted content where possible +- Handle third-party service failures gracefully +- Prepare fallback logic for failed integrations + +### Data Validation from External Sources +- Never trust external data without validation +- Implement schema validation for received data +- Sanitize external data +- Use type checking +- Implement timeouts for external requests \ No newline at end of file diff --git a/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-7-accessibility-rules.mdc b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-7-accessibility-rules.mdc new file mode 100644 index 0000000..f4a6967 --- /dev/null +++ b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-7-accessibility-rules.mdc @@ -0,0 +1,115 @@ +--- +description: USE WHEN creating inclusive, accessible web applications to ensure application work for all users, including those with disabilities +globs: ["**/*"] +alwaysApply: false +--- +# Hybrid Frontend Accessibility Rules + +## Semantic HTML Foundation (Web Standards) + +### Proper Element Usage +- Use appropriate components or native elements for semantic purpose +- Choose UI elements based on meaning, not appearance +- Maintain logical structure for accessibility tools +- Use accessible equivalents for lists and headings +- Implement accessible regions for navigation structure + +### Heading Hierarchy +- Start with accessible title component or heading for main page title +- Use heading levels sequentially without skipping where possible +- Don’t use headings solely for styling +- Ensure headings describe section content accurately +- Use accessibility attributes to associate headings with regions + +### List Structures +- Use accessible list components for ordered/unordered content +- Avoid lists for non-list content +- Ensure proper list item nesting and semantics + +## ARIA Implementation (WCAG) + +### Labels and Descriptions +- Use accessibility labels (e.g., accessibilityLabel) for elements without visible text +- Use accessibilityHint or descriptions for additional context +- Avoid redundant roles or labels where native components provide semantics +- Keep labels concise and purposeful + +### Roles and States +- Apply roles to enhance semantic clarity where needed +- Use accessibilityState for dynamic changes (expanded, checked) +- Update accessibility state when UI changes +- Hide decorative elements from accessibility tree +- Use live regions to announce dynamic content + +### Live Regions +- Use accessibilityLiveRegion for content that updates dynamically +- Choose appropriate announcement levels +- Ensure whole message is read when needed +- Use status role for updates +- Announce loading and progress indicators + +## Keyboard Navigation (WCAG) + +### Focus Management +- Ensure all interactive elements are keyboard accessible +- Maintain logical tab order +- Provide visible and styled focus indicators +- Manage focus during dynamic UI changes +- Use skip links or equivalents for navigation + +### Keyboard Interaction Patterns +- Support arrow key navigation in lists/menus +- Use Enter and Space for activations +- Escape to close modals or popups +- Provide shortcut support for key actions +- Handle Home/End navigation for elements + +### Skip Links and Shortcuts +- Provide skip links or accessibility actions for quick navigation +- Make skip links visible when focused +- Use access keys or gestures where appropriate +- Document supported keyboard and gesture actions + +## Visual Accessibility + +### Color and Contrast +- Ensure WCAG-compliant contrast ratios +- Don’t use color alone for conveying meaning +- Support dark/light mode themes +- Use visual cues alongside colors + +### Typography and Spacing +- Use scalable units (rem, em) for font sizing +- Support 200% zoom readability +- Maintain readable line height and element spacing +- Respect user preferences for text sizing + +## Accessible Form Interactions + +### Advanced Form Accessibility +- Use accessibilityRole and accessibilityLabel for form controls +- Announce form state changes using alerts or live regions +- Support keyboard and screen reader navigation +- Provide real-time validation feedback + +## Component-Specific Accessibility + +### Modal and Dialog Patterns +- Trap focus inside modal while open +- Return focus to invoking element on close +- Use role="dialog" and appropriate labeling +- Implement Escape key to dismiss modal +- Provide accessible close button + +### Table Accessibility +- Use semantic table structure with headers +- Define relationships using accessibility attributes +- Provide captions or summaries for context +- Ensure responsive tables retain accessibility features +- Indicate sort order using ARIA where needed + +## Testing and Validation + +### Accessibility Testing +- Use accessibility validation tools and emulators +- Verify ARIA usage and state changes are announced properly \ No newline at end of file diff --git a/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-8-testing-rules.mdc b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-8-testing-rules.mdc new file mode 100644 index 0000000..5d4c807 --- /dev/null +++ b/6-mobile-app/javascript/hybrid-frontend/hybrid-frontend-8-testing-rules.mdc @@ -0,0 +1,86 @@ +--- +description: USE WHEN writing test for ensuring testing and quality principles to build reliable, maintainable frontend applications with comprehensive test coverage and robust error handling +globs: ["**/*"] +alwaysApply: false +--- +# Hybrid Frontend Testing & Quality Rules + +## Testing Strategy and Organization + +### Test Pyramid Structure (Testing Pyramid) +- Write more unit tests than integration tests, more integration than e2e tests +- Focus unit tests on business logic and pure functions +- Use integration tests for component interactions +- Reserve e2e tests for critical user flows only +- Keep tests focused and isolated + +### Test Organization and Structure +- Co-locate tests with source code files or components +- Use descriptive test names explaining expected behavior +- Group related tests using describe blocks +- Follow Arrange-Act-Assert structure +- Minimize and clarify test setup + +## Component Testing Best Practices + +### Testing User Interactions (User-Centric Testing) +- Test components from a user perspective +- Focus on behavior rather than implementation details +- Use accessibility-focused queries (e.g., getByRole, getByLabelText) +- Test user interactions and resulting state changes +- Validate visual feedback and side effects + +### Mocking and Test Isolation +- Mock dependencies such as services or storage access +- Keep mocks simple and aligned to test goals +- Reset mocks between each test +- Choose mock level based on usage (function, module, network) +- Use dependency injection or providers for flexible mocking + +## Integration Testing + +### Component Integration +- Validate how components interact and share data +- Test context consumers and their dependencies +- Test navigation flows between views +- Validate hybrid form handling and submission flow + +### API Integration Testing +- Use mocked endpoints or native HTTP mocks +- Validate request and response logic +- Test edge cases and error handling +- Confirm transformation logic works correctly +- Ensure proper states for loading and errors + +## Code Quality Standards + +### Code Organization and Structure (Single Responsibility) +- Follow consistent file/folder naming patterns +- Group logically related functionality +- Keep functions/component logic scoped and focused +- Name variables and functions descriptively +- Handle all errors and edge cases in logic + +### Type Safety and Validation +- Use TypeScript or PropTypes for type safety +- Validate parameters and return types where necessary +- Document expected interfaces +- Apply runtime validation for critical flows +- Use schema validation for data coming from APIs + +## Error Handling and Debugging + +### Comprehensive Error Handling +- Use error boundaries or hybrid equivalents for UI-level errors +- Handle async errors and rejections gracefully +- Display user-friendly error messages +- Log sufficient context for debugging issues +- Provide UI fallbacks for error states + +### Systematic Logging and Debugging +- Implement unified logging strategies across environments +- Log state transitions and key user interactions +- Use structured log messages +- Support debug mode toggles for testing environments +- Write utilities to trace and profile components +- Use clear naming and consistent commenting for debuggability \ No newline at end of file diff --git a/6-mobile-app/javascript/react-native/react-native-1-architecture-rules.mdc b/6-mobile-app/javascript/react-native/react-native-1-architecture-rules.mdc new file mode 100644 index 0000000..4008d5c --- /dev/null +++ b/6-mobile-app/javascript/react-native/react-native-1-architecture-rules.mdc @@ -0,0 +1,382 @@ +--- +description: USE WHEN designing frontend architecture, implementing design patterns, organizing code structure, or discussing architectural decisions for creating maintainable, scalable component architectures +globs: ["**/*"] +alwaysApply: false +--- +# React Native Architecture Rules + +## SOLID Principles in React Native Components + +### Single Responsibility Principle (SOLID - S) + +- Each React Native component must have ONE clear, well-defined purpose +- Split components that handle multiple concerns into smaller, focused units +- Name components based on their single responsibility (Button, Modal, UserCard) +- Keep business logic separate from UI rendering logic + +```tsx +// Good: Single responsibility +export const UserAvatar: React.FC = ({ user, size = 'md' }) => { + return ( + + ); +}; +``` + +### Open/Closed Principle (SOLID - O) + +- Design React Native components for extension without modification +- Use composition patterns over inheritance +- Leverage props and children for configuration + +```tsx +interface ButtonProps { + variant?: 'primary' | 'secondary'; + children: React.ReactNode; + leftIcon?: React.ReactNode; +} + +export const Button: React.FC = ({ + variant = 'primary', + children, + leftIcon, + ...props +}) => ( + + {leftIcon && {leftIcon}} + {children} + +); +``` + +### Liskov Substitution Principle (SOLID - L) + +- React Native components should be replaceable with their implementations without breaking functionality +- Ensure consistent behavior across component variants + +```tsx +interface BaseInputProps { + value: string; + onChangeText: (value: string) => void; + editable?: boolean; +} + +export const TextInputField: React.FC = (props) => ( + +); + +export const EmailInputField: React.FC = (props) => ( + +); +``` + +### Interface Segregation Principle (SOLID - I) + +- Create focused, minimal prop interfaces rather than large, monolithic ones +- Split complex prop interfaces into smaller, specific contracts + +```tsx +interface BaseComponentProps { + style?: ViewStyle; + children?: React.ReactNode; +} + +interface TouchableProps { + onPress: (event: GestureResponderEvent) => void; + disabled?: boolean; +} + +interface FormFieldProps { + name: string; + label: string; + error?: string; +} + +type TouchableButton = BaseComponentProps & TouchableProps; +``` + +### Dependency Inversion (SOLID - D) + +- Depend on abstractions, not concrete implementations +- Inject dependencies through props or context + +```tsx +interface UserService { + fetchUser: (id: string) => Promise; + updateUser: (user: User) => Promise; +} + +interface UserProfileProps { + userId: string; + userService: UserService; +} + +export const UserProfile: React.FC = ({ userId, userService }) => { + const { data: user, loading } = useQuery(['user', userId], () => userService.fetchUser(userId)); + // Component implementation +}; +``` + +## React Native Component Structure & Organization + +### Atomic Design with React Native + +- **Atoms**: Basic React Native components (Button, Input, Icon) +- **Molecules**: Combinations of atoms (SearchBox, FormField) +- **Organisms**: Complex UI sections (Header, UserForm, ProductList) +- **Templates**: Page layouts with placeholder content +- **Screens**: Complete route components with real data + +```tsx +// Atom +export const Button: React.FC = ({ children, ...props }) => ( + {children} +); + +// Molecule +export const SearchBox: React.FC = ({ onSearch }) => ( + + + + +); +``` + +### File Organization + +- Use PascalCase for component files: `UserProfile.tsx` +- Co-locate related files in component folders +- Export components as named exports, not default exports + +``` +/components + /atoms + /Button + - Button.tsx + - Button.test.tsx + - index.ts + /molecules + /organisms +``` + +### Component Interface Design + +- Define props interfaces with descriptive names ending in "Props" +- Use strict TypeScript typing for all props + +```tsx +interface UserCardProps { + user: User; + onEdit?: (user: User) => void; + showActions?: boolean; + style?: ViewStyle; +} + +export const UserCard: React.FC = ({ + user, + onEdit, + showActions = true, + style +}) => { + // Component implementation +}; +``` + +## React Native Data Flow Architecture + +### Component Communication + +- Pass data down through props +- Use callback functions for upward communication +- Avoid deep prop drilling beyond 2-3 levels +- Use React Context for cross-cutting concerns + +```tsx +interface TodoListProps { + todos: Todo[]; + onToggle: (id: string) => void; + onDelete: (id: string) => void; +} + +export const TodoList: React.FC = ({ todos, onToggle, onDelete }) => ( + item.id} + renderItem={({ item }) => ( + onToggle(item.id)} + onDelete={() => onDelete(item.id)} + /> + )} + /> +); +``` + +### Custom Hooks for Logic Reuse + +- Extract reusable stateful logic into custom hooks +- Prefix custom hook names with "use" +- Keep custom hooks focused on single responsibility + +```tsx +interface UseApiResult { + data: T | null; + loading: boolean; + error: string | null; + refetch: () => void; +} + +export const useApi = (url: string): UseApiResult => { + const [data, setData] = useState(null); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(null); + + const fetchData = useCallback(async () => { + setLoading(true); + try { + const response = await fetch(url); + const result = await response.json(); + setData(result); + } catch (err) { + setError(err instanceof Error ? err.message : 'Unknown error'); + } finally { + setLoading(false); + } + }, [url]); + + useEffect(() => { + fetchData(); + }, [fetchData]); + + return { data, loading, error, refetch: fetchData }; +}; +``` + +## React Native Component Lifecycle & Side Effects + +### Effect Management with Hooks + +- Use `useEffect` for side effects and lifecycle events +- Always include dependency arrays in `useEffect` +- Clean up subscriptions and event listeners + +```tsx +export const UserProfile: React.FC<{ userId: string }> = ({ userId }) => { + const [user, setUser] = useState(null); + + useEffect(() => { + const abortController = new AbortController(); + + const fetchUser = async () => { + try { + const response = await fetch(`/api/users/${userId}`, { + signal: abortController.signal + }); + const userData = await response.json(); + setUser(userData); + } catch (error: any) { + if (error.name !== 'AbortError') { + console.error('Failed to fetch user:', error); + } + } + }; + + fetchUser(); + return () => abortController.abort(); + }, [userId]); + + return user ? {user.name} : Loading...; +}; +``` + +## React Native Error Handling + +### Error Boundaries + +- Implement Error Boundaries at strategic component levels +- Provide fallback UI for component errors + +```tsx +interface ErrorBoundaryState { + hasError: boolean; + error?: Error; +} + +export class ErrorBoundary extends React.Component< + React.PropsWithChildren<{}>, + ErrorBoundaryState +> { + constructor(props: React.PropsWithChildren<{}>) { + super(props); + this.state = { hasError: false }; + } + + static getDerivedStateFromError(error: Error): ErrorBoundaryState { + return { hasError: true, error }; + } + + componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { + console.error('Component error:', error, errorInfo); + } + + render() { + if (this.state.hasError) { + return ( + + Something went wrong. + + + ); + } + + return this.props.children; + } +} +``` + +## Testing Architecture + +### Testable React Native Component Design + +- Design components with testing in mind +- Use dependency injection for external services +- Keep business logic in custom hooks + +```tsx +interface UserListProps { + userService: UserService; +} + +export const UserList: React.FC = ({ userService }) => { + const { data: users, loading, error } = useUsers(userService); + + if (loading) return Loading...; + if (error) return Error: {error}; + + return ( + user.id} + renderItem={({ item }) => {item.name}} + /> + ); +}; + +// Test +it('UserList displays users when loaded', async () => { + const mockUserService = { + fetchUsers: jest.fn().mockResolvedValue([{ id: '1', name: 'John' }]) + }; + + const { findByText } = render(); + + expect(await findByText('John')).toBeTruthy(); +}); +``` diff --git a/6-mobile-app/javascript/react-native/react-native-2-ui-patterns-rules.mdc b/6-mobile-app/javascript/react-native/react-native-2-ui-patterns-rules.mdc new file mode 100644 index 0000000..a7e0940 --- /dev/null +++ b/6-mobile-app/javascript/react-native/react-native-2-ui-patterns-rules.mdc @@ -0,0 +1,331 @@ +--- +description: USE WHEN implementing UI patterns and user interactions to create interfaces that are intuitive, accessible, and performant across all devices and user capabilities +globs: ["**/*"] +alwaysApply: false +--- + +# React Native UI/UX Patterns Rules + +```tsx +// Required imports for the examples below +import React, { useState } from "react"; +import { + View, + Text, + TouchableOpacity, + TextInput, + ActivityIndicator, + FlatList, + StyleSheet, +} from "react-native"; +``` + +## React Native Responsive Design Patterns + +### Mobile-First Components + +- Design components for mobile viewports by default +- Use `Dimensions` or `useWindowDimensions` for layout-based decisions +- Implement props to conditionally render layout variations + +```tsx +import { useWindowDimensions } from "react-native"; + +interface ResponsiveCardProps { + title: string; + content: string; + layout?: "mobile" | "desktop" | "auto"; +} + +export const ResponsiveCard: React.FC = ({ + title, + content, + layout = "auto", +}) => { + const { width } = useWindowDimensions(); + const isMobile = layout === "mobile" || (layout === "auto" && width < 768); + + return ( + + {title} + {content} + + ); +}; + +const styles = StyleSheet.create({ + card: { padding: 16, borderWidth: 1, borderRadius: 8 }, + row: { flexDirection: "row" }, + column: { flexDirection: "column" }, + title: { fontSize: 18, fontWeight: "600", marginBottom: 8 }, + content: { flex: 1 }, +}); +``` + +### Flexible Layout Components + +- Use Flexbox layout for responsive spacing and alignment +- Create reusable layout components with props for direction and spacing + +```tsx +interface FlexLayoutProps { + children: React.ReactNode; + direction?: "row" | "column"; + justify?: "flex-start" | "center" | "flex-end" | "space-between"; + gap?: number; +} + +export const FlexLayout: React.FC = ({ + children, + direction = "row", + justify = "flex-start", + spacing = 8, +}) => ( + + {children} + +); +``` + +## React Native User Interface Patterns + +### Interactive State Management + +- Handle interactive states using React state + +```tsx +interface InteractiveButtonProps { + children: React.ReactNode; + onPress?: () => void; + disabled?: boolean; + loading?: boolean; + variant?: "primary" | "secondary" | "danger"; +} + +export const InteractiveButton: React.FC = ({ + children, + onPress, + disabled = false, + loading = false, + variant = "primary", +}) => { + const [isPressed, setIsPressed] = useState(false); + + const backgroundColor = { + primary: "#3B82F6", + secondary: "#E5E7EB", + danger: "#EF4444", + }[variant]; + + return ( + setIsPressed(true)} + onPressOut={() => setIsPressed(false)} + style={{ + paddingVertical: 8, + paddingHorizontal: 16, + borderRadius: 6, + backgroundColor, + opacity: disabled ? 0.5 : 1, + transform: [{ scale: isPressed ? 0.95 : 1 }], + }} + > + {loading ? : children} + + ); +}; +``` + +### Loading and Empty States + +- Create components for loading and empty views + +```tsx +interface LoadingStateProps { + text?: string; +} + +export const LoadingState: React.FC = ({ text }) => ( + + + {text && {text}} + +); + +interface EmptyStateProps { + title: string; + description?: string; + action?: { + label: string; + onPress: () => void; + }; +} + +export const EmptyState: React.FC = ({ + title, + description, + action, +}) => ( + + {title} + {description && {description}} + {action && ( + + {action.label} + + )} + +); +``` + +## React Native Form Design Patterns + +### Controlled Form Components + +```tsx +interface FormFieldProps { + label: string; + value: string; + onChange: (value: string) => void; + error?: string; + secureTextEntry?: boolean; +} + +export const FormField: React.FC = ({ + label, + value, + onChange, + error, + secureTextEntry = false, +}) => ( + + {label} + + {error && {error}} + +); +``` + +## React Native Touch and Gesture Patterns + +### Touch-Friendly Components + +- Ensure components are at least 44x44 for accessibility +- Handle touch gestures using `PanResponder` or state-based logic + +```tsx +import { GestureResponderEvent } from "react-native"; + +interface TouchableCardProps { + children: React.ReactNode; + onTap?: () => void; +} + +export const TouchableCard: React.FC = ({ + children, + onTap, +}) => { + const [isPressed, setIsPressed] = useState(false); + + return ( + setIsPressed(true)} + onPressOut={() => setIsPressed(false)} + style={{ + padding: 12, + borderRadius: 6, + transform: [{ scale: isPressed ? 0.95 : 1 }], + backgroundColor: "#fff", + }} + > + {children} + + ); +}; +``` + +## React Native Navigation Patterns + +### Navigation Components + +- Use `@react-navigation/native` for navigation +- Use active state based on route name or focus status + +```tsx +import { useNavigation, useRoute } from "@react-navigation/native"; + +interface NavigationItem { + name: string; + label: string; + onPress: () => void; +} + +interface NavigationProps { + items: NavigationItem[]; +} + +export const Navigation: React.FC = ({ items }) => { + const route = useRoute(); + + return ( + + {items.map((item) => { + const isActive = route.name === item.name; + return ( + + + {item.label} + + + ); + })} + + ); +}; +``` + +## React Native Performance UI Patterns + +### Virtual Scrolling for Large Lists + +- Use FlatList with `initialNumToRender` and `windowSize` for performance + +```tsx +interface User { + name: string; +} + +export const UserList: React.FC<{ users: User[] }> = ({ users }) => { + return ( + item.id} + renderItem={({ item }) => ( + + {item.name} + + )} + initialNumToRender={10} + windowSize={5} + /> + ); +}; +``` diff --git a/6-mobile-app/javascript/react-native/react-native-3-data-state-rules.mdc b/6-mobile-app/javascript/react-native/react-native-3-data-state-rules.mdc new file mode 100644 index 0000000..94153e5 --- /dev/null +++ b/6-mobile-app/javascript/react-native/react-native-3-data-state-rules.mdc @@ -0,0 +1,374 @@ +--- +description: USE WHEN handling application state and data flow for efficient, predictable data and state management +globs: ["**/*"] +alwaysApply: false +--- + +# React Native Data & State Management Rules + +## React State Management Principles + +### State Ownership and Boundaries + +- Keep state as close to its usage as possible with `useState` +- Lift state up only when multiple components genuinely need access +- Avoid prop drilling beyond 2-3 component levels +- Use React Context for deeply nested sharing, custom hooks for logic reuse + +```tsx +// Good: State close to usage +const TodoItem = ({ todo, onToggle }) => { + const [isHovered, setIsHovered] = useState(false); + + return ( + setIsHovered(true)} + onPressOut={() => setIsHovered(false)} + > + onToggle(todo.id)} + /> + {todo.text} + {isHovered &&