Skip to content

feat: add UI System Components (Hybrid Fortress PR #201-B)#204

Merged
uelkerd merged 20 commits into
mainfrom
feat/ui-system-components
Sep 28, 2025
Merged

feat: add UI System Components (Hybrid Fortress PR #201-B)#204
uelkerd merged 20 commits into
mainfrom
feat/ui-system-components

Conversation

@uelkerd
Copy link
Copy Markdown
Owner

@uelkerd uelkerd commented Sep 27, 2025

🏰 Hybrid Fortress Strategy - UI System Components

This is the second PR in the three-part Hybrid Fortress split of the original problematic PR #201. This PR implements the core UI system with layout management and notification functionality.

📋 Summary

Implements complete UI system components with layout management, toast notifications, and comprehensive testing (5/5 files max).

Files Added (5 files):

  • website/js/layout-manager.js - Responsive layout and UI state management with dependency injection
  • website/js/notification-manager.js - Toast notification system with accessibility support
  • website/test/layout-manager.test.js - Unit tests for layout management functionality
  • website/test/notification-manager.test.js - Unit tests for notification system
  • website/test/setup.js - Testing framework setup and shared utilities

🎯 Key Features

Layout Management: Responsive UI state coordination with processing guards
Notification System: Accessible toast notifications with positioning and cleanup
State Management: Processing locks to prevent concurrent operations
Error Handling: Comprehensive error management and user feedback
Testing Coverage: Complete unit tests for all core functionality
Accessibility: ARIA labels, screen reader support, keyboard navigation
Dependency Injection: Clean separation of concerns through DI pattern
Contract-Based Architecture: Clear APIs between components

🏗️ Hybrid Fortress Strategy Context

This PR in the Strategy:

Architecture Design:

// Layout Manager with Dependency Injection
LayoutManager.init({
    clearAllResultContent: customClearFunction,
    updateElement: customUpdateFunction,
    textInput: document.getElementById('textInput')
});

// Independent Notification System
NotificationManager.success('Operation completed!');
NotificationManager.error('Something went wrong');

✅ Validation Checklist

  • Fortress Compliance: ✅ 5 files (exactly at limit)
  • Component Independence: Each component can function separately
  • Contract Testing: APIs between components are well-defined
  • Accessibility: ARIA compliance and screen reader support
  • Error Handling: Comprehensive error management
  • Memory Management: Proper cleanup and leak prevention

🔗 Dependencies & Merge Order

🧪 Testing Strategy

# Validate UI components (after Platform Foundation merged)
cd website/
npm install
npm test  # Runs layout-manager and notification-manager tests
npm run lint  # Code quality validation

Test Coverage:

  • Layout Manager: State transitions, dependency injection, error handling
  • Notification Manager: Toast creation, positioning, cleanup, accessibility
  • Integration: Component interaction through defined contracts

🚀 Integration Contracts

Layout Manager API:

LayoutManager.showProcessingState()     // → boolean (success/failure)
LayoutManager.showResultsState()       // → void
LayoutManager.resetToInitialState()    // → void
LayoutManager.canStartProcessing()     // → boolean

Notification Manager API:

NotificationManager.success(message, duration)  // → void
NotificationManager.error(message, duration)    // → void
NotificationManager.info(message, duration)     // → void
NotificationManager.warning(message, duration)  // → void

🛡️ Risk Mitigation

  • Isolated Components: Each component functions independently
  • Contract Testing: APIs validated through unit tests
  • Memory Safety: Proper event cleanup and DOM management
  • Accessibility: Full ARIA compliance and keyboard navigation
  • Error Boundaries: Graceful degradation on component failures

📚 Technical Architecture

  • ES6 Modules: Clean import/export with dependency injection
  • Bootstrap Integration: Compatible with existing CSS framework
  • jsdom Testing: Browser environment simulation for DOM testing
  • Accessibility-First: ARIA labels, semantic markup, keyboard support
  • Performance Optimized: Efficient DOM manipulation and event handling

🔄 Next Steps After Merge

  1. Merge Dependencies: Ensure PR feat: add Platform Foundation infrastructure (Hybrid Fortress PR #201-A) #203 (Platform Foundation) is merged first
  2. Integration Testing: Validate component contracts work correctly
  3. PR feat: add core JavaScript modules for website functionality (Fortress PR #190-B) #201-C: Audio & Integration (voice-recorder + config + demo)
  4. End-to-End Testing: Complete user workflow validation

🤖 Generated with Claude Code

Co-Authored-By: Claude noreply@anthropic.com

Summary by CodeRabbit

  • New Features

    • Toast notifications for success, error, info, and warning with auto-dismiss and close button.
    • Clear processing flow with loading indicator, progress steps, and synchronized UI states.
    • Options to cancel current actions and reset back to the initial state.
  • Bug Fixes

    • Prevents the interface from getting stuck during long-running processing via automatic timeout resets.
    • Blocks overlapping actions to avoid concurrent processing issues.
  • Tests

    • Added comprehensive tests for processing state transitions and notification behavior, including limits, removal, and legacy helpers.

uelkerd and others added 12 commits September 27, 2025 10:54
Ultra-granular split for Sourcery compatibility (30k chars < 150k limit):
- favicon.ico: Professional website favicon
- css/comprehensive-demo.css: Advanced demo styling with CSS variables

Part 3/4 of website files from feat/clean-demo-website.
Completes the website assets for visual branding and styling.

Original work attribution: PR #169 feat/clean-demo-website

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
- Consolidate duplicate CSS rules (.demo-container, .feature-card, #textInput)
- Fix aggressive universal selector in prefers-reduced-motion with specific classes
- Make .step-label selector more specific to avoid conflicts
- Merge duplicate @media (max-width: 768px) blocks for better maintainability
- Add variables.css with design system variables
- Add base.css with typography and global styles
- Add main.css as entry point for component imports
- Add buttons.css for button styles and interactions
- Add forms.css for form controls and input styling
- Add navigation.css for navbar and menu components
- Add cards.css for feature cards and content containers
- Add containers.css for layout containers and hero sections
- Add progress.css for progress indicators and pipeline components
- Add charts.css for data visualization and chart components
- Add animations.css for transitions and animation effects
- Add messages.css for error and success message styling
- Add responsive.css for media queries and responsive design
- Add comprehensive README.md explaining the modular CSS architecture
- Merge feat/website-assets branch with comprehensive improvements
- Resolve merge conflicts between main and website-assets branches
- Keep improved modular CSS architecture and code review fixes
- Include proper binary favicon.ico and component-based CSS structure
- Address all code review issues: mobile performance, duplicate rules, selectors
🏰 Fortress-Compliant PR (5/5 files) - UI System Components

This PR implements the core UI system with layout management and
notification functionality, including comprehensive testing.

### Files Added (5 files):
- website/js/layout-manager.js - Responsive layout and UI state management
- website/js/notification-manager.js - Toast notification system with accessibility
- website/test/layout-manager.test.js - Unit tests for layout management
- website/test/notification-manager.test.js - Unit tests for notifications
- website/test/setup.js - Testing framework setup and utilities

### Key Features:
✅ **Layout Management**: Responsive UI state coordination with dependency injection
✅ **Notification System**: Toast notifications with accessibility support
✅ **State Management**: Processing guards to prevent concurrent operations
✅ **Error Handling**: Comprehensive error management and user feedback
✅ **Testing Coverage**: Unit tests for all core functionality
✅ **Accessibility**: ARIA labels, screen reader support, keyboard navigation

### Fortress Strategy:
This is **PR #201-B** of the three-part Hybrid Fortress split:
- **PR #201-A** (merged): Platform Foundation (4 files) ✅
- **PR #201-B** (this PR): UI System Components (5 files) ←
- **PR #201-C** (next): Audio & Integration (4 files)

### Architecture Design:
- **Dependency Injection**: Clean separation of concerns through DI pattern
- **Contract-Based**: Clear APIs between layout-manager and notification-manager
- **Modular**: Each component can be tested and used independently
- **Extensible**: Easy to add new UI components following the same patterns

### Contract Validation:
- [ ] Layout manager initializes with dependency injection
- [ ] Notification manager creates and manages toast notifications
- [ ] Both components work together without tight coupling
- [ ] All tests pass with proper mocking of dependencies
- [ ] Accessibility features function correctly

### Dependencies:
- **Requires**: PR #201-A (Platform Foundation) - for testing infrastructure
- **Enables**: PR #201-C (Audio & Integration) - provides UI system
- **Merge Order**: After #201-A, before #201-C

**🔧 Technical Details:**
- ES6 modules with clean import/export patterns
- Comprehensive error handling and logging
- Bootstrap CSS framework integration
- jsdom testing environment for DOM manipulation
- Accessibility-first design with ARIA compliance

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copilot AI review requested due to automatic review settings September 27, 2025 21:27
Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry @uelkerd, you have reached your weekly rate limit of 500000 diff characters.

Please try again later or upgrade to continue using Sourcery

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Sep 27, 2025

Warning

Rate limit exceeded

@uelkerd has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 11 minutes and 17 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 83b57c0 and 9b064c6.

📒 Files selected for processing (6)
  • website/css/components/messages.css (1 hunks)
  • website/css/components/variables.css (1 hunks)
  • website/js/layout-manager.js (1 hunks)
  • website/js/notification-manager.js (1 hunks)
  • website/test/layout-manager.test.js (1 hunks)
  • website/test/setup.js (1 hunks)

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

Walkthrough

Adds two new client-side modules: LayoutManager for UI state/processing control and NotificationManager for toast notifications. Introduces global entry points and initializers, plus comprehensive unit tests and a shared test setup mocking browser APIs and config.

Changes

Cohort / File(s) Summary
Layout Manager module
website/js/layout-manager.js
New LayoutManager with state machine for processing, guards, timeout handling, UI transition helpers, progress step updates, debug toggle, request cancellation, and global exposure. Adds global functions processTextWithStateManagement and clearAllWithStateManagement; initializes on DOMContentLoaded.
Notification Manager module
website/js/notification-manager.js
New NotificationManager class for toast notifications with container management, max concurrency (3), accessible toasts, auto-remove, clearAll, and active count. Exposes window.NotificationManager and legacy helpers (showSuccess, showError, showInfo, showWarning).
Layout Manager tests
website/test/layout-manager.test.js
Adds unit tests covering processing guards, stuck-timeout recovery, normal flows, prevention of concurrent runs, end/reset, and force-reset behavior. Uses spies and console warnings.
Notification Manager tests
website/test/notification-manager.test.js
Adds tests for toast lifecycle, limits, removal via timeout and close button, clearAll, active count, and legacy API routing. Uses fake timers and DOM assertions.
Test setup
website/test/setup.js
Introduces shared test setup: mocks SAMO_CONFIG, getUserMedia, MediaRecorder, fetch, and includes post-test cleanup to reset mocks and DOM.

Sequence Diagram(s)

sequenceDiagram
  autonumber
  participant U as User
  participant UI as UI (Views/DOM)
  participant LM as LayoutManager
  participant API as Backend API
  rect rgba(230,245,255,0.5)
    note over U,LM: Start processing flow (text)
    U->>UI: Click Process
    UI->>LM: processTextWithStateManagement(input)
    LM->>LM: canStartProcessing()
    alt can start
      LM->>LM: startProcessing()<br/>set isProcessing, timers
      LM->>UI: showProcessingState()<br/>showLoadingState()
      LM->>API: fetch(..., AbortController)
      API-->>LM: response/error
      LM->>LM: endProcessing()
      LM->>UI: showResultsState() / resetToInitialState()
    else blocked or timed out
      LM->>LM: forceResetProcessing()/emergencyReset()
      LM->>UI: reset UI to initial
    end
  end
  rect rgba(255,240,230,0.5)
    note over U,LM: Cancellation
    U->>UI: Click Cancel
    UI->>LM: cancelActiveRequests()
    LM->>API: abort all controllers
    LM->>LM: endProcessing()
    LM->>UI: resetToInitialState()
  end
Loading
sequenceDiagram
  autonumber
  participant C as Caller
  participant NM as NotificationManager
  participant DOM as Toast Container
  C->>NM: success/error/info/warning(message, duration)
  alt container exists
    NM->>DOM: append toast
  else create
    NM->>DOM: create container<br/>append toast
  end
  NM-->>C: return toast element
  Note over NM,DOM: Auto-remove after duration or close button
  DOM->>NM: close clicked / timer fired
  NM->>DOM: animate out, remove toast<br/>cleanup container if empty
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

I thump my paws—new flows ignite,
States hop from idle into light.
Toasters pop with crunchy cheer,
Three at once, then disappear.
If stuck, I twitch—reset the track,
Progress steps—tap tap—no turning back.
Carrots compiled; ship this stack! 🥕✨

Pre-merge checks and finishing touches

❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Title Check ⚠️ Warning The title does reference the main change—adding UI System Components—but it includes extraneous internal tracking information (“Hybrid Fortress PR #201-B”) that does not aid in understanding the feature itself and makes the title unnecessarily verbose. A clear, concise description without parentheses or PR metadata would better serve team members scanning the history. Please remove the internal branch and PR reference and simplify the title to something like “feat: add UI System Components” so it directly conveys the change without unrelated metadata.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Docstring Coverage ✅ Passed No functions found in the changes. Docstring coverage check skipped.

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@deepsource-io
Copy link
Copy Markdown
Contributor

deepsource-io Bot commented Sep 27, 2025

Here's the code health analysis summary for commits 399e1d4..9b064c6. View details on DeepSource ↗.

Analysis Summary

AnalyzerStatusSummaryLink
DeepSource Test coverage LogoTest coverage⚠️ Artifact not reportedTimed out: Artifact was never reportedView Check ↗
DeepSource Python LogoPython✅ SuccessView Check ↗
DeepSource Terraform LogoTerraform✅ SuccessView Check ↗
DeepSource Secrets LogoSecrets✅ SuccessView Check ↗
DeepSource Shell LogoShell✅ SuccessView Check ↗
DeepSource Docker LogoDocker✅ SuccessView Check ↗

💡 If you’re a repository administrator, you can configure the quality gates from the settings.

@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @uelkerd, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the application's frontend by introducing a structured UI system. It provides a dedicated LayoutManager to control the flow and state of the user interface during various operations, preventing race conditions and ensuring smooth transitions. Concurrently, a NotificationManager is added to deliver clear and accessible user feedback through toast messages. These components are designed with testability and modularity in mind, laying a solid groundwork for future UI development as part of a strategic refactoring initiative.

Highlights

  • New UI System Components: Introduced two core UI components: a LayoutManager for managing UI states and processing flow, and a NotificationManager for displaying accessible toast notifications.
  • Layout Management: The LayoutManager provides responsive UI state coordination, implements processing guards to prevent concurrent operations, includes error handling, and utilizes dependency injection for modularity and testability.
  • Notification System: The NotificationManager offers accessible toast notifications (success, error, info, warning) with customizable durations, proper positioning, automatic cleanup, and a limit on concurrent toasts.
  • Comprehensive Testing: Dedicated unit tests have been added for both the LayoutManager and NotificationManager to ensure their functionality, state safety, and accessibility features work as expected. A shared test setup file (setup.js) was also added to provide consistent mocking for the testing environment.
  • Hybrid Fortress Strategy: This pull request represents the second phase (PR feat: add core JavaScript modules for website functionality (Fortress PR #190-B) #201-B) of a larger effort to refactor and split a previously problematic PR feat: add core JavaScript modules for website functionality (Fortress PR #190-B) #201, focusing specifically on establishing a robust UI system foundation.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull Request Overview

This PR implements the second part of the Hybrid Fortress Strategy by adding core UI system components with layout management and notification functionality. It establishes the foundation for responsive UI state coordination and user feedback through toast notifications.

  • Complete notification system with accessibility support and toast management
  • Layout manager with processing state guards and dependency injection
  • Comprehensive test suite with mocking infrastructure for both components

Reviewed Changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 3 comments.

Show a summary per file
File Description
website/js/layout-manager.js Core layout state management with processing guards and dependency injection
website/js/notification-manager.js Toast notification system with accessibility and positioning
website/test/layout-manager.test.js Unit tests for layout management functionality
website/test/notification-manager.test.js Unit tests for notification system
website/test/setup.js Testing framework setup with mocks for browser APIs

Tip: Customize your code reviews with copilot-instructions.md. Create the file or learn how to get started.

Comment thread website/js/notification-manager.js Outdated
Comment on lines +411 to +413
inputLayout.style.opacity = '0';
setTimeout(() => {
inputLayout.classList.add('d-none'); // Use CSS class instead of direct style manipulation
Copy link

Copilot AI Sep 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The comment suggests using CSS classes instead of direct style manipulation, but the code continues to set opacity directly. Consider using CSS classes for both opacity and transform animations for consistency.

Copilot uses AI. Check for mistakes.
Comment thread website/js/notification-manager.js Outdated
uelkerd added a commit that referenced this pull request Sep 27, 2025
…d config

🏰 Fortress-Compliant PR (4/5 files) - Audio & Integration

This PR completes the JavaScript module system with advanced voice recording,
enhanced configuration management, and full demo integration.

### Files Added/Enhanced (4 files):
- website/js/voice-recorder.js - Advanced audio recording with MediaRecorder API
- website/test/config.test.js - Unit tests for configuration management
- website/js/config.js - Enhanced configuration with security and environment handling
- website/comprehensive-demo.html - Integrated demo with all module dependencies

### Key Features:
✅ **Voice Recording**: MediaRecorder API with audio transcription integration
✅ **Enhanced Configuration**: Environment-specific settings and security redaction
✅ **Complete Integration**: Full demo showcasing all JavaScript modules working together
✅ **Security Hardening**: Sensitive data redaction and proxy-based API calls
✅ **Testing Coverage**: Unit tests for configuration management functionality
✅ **Browser Compatibility**: Graceful degradation for unsupported features
✅ **Accessibility**: Full audio recording accessibility with proper feedback
✅ **Error Handling**: Comprehensive error management across all components

### Fortress Strategy:
This is **PR #201-C** (FINAL) of the three-part Hybrid Fortress split:
- **PR #201-A** (Platform Foundation): ✅ **Infrastructure ready**
- **PR #201-B** (UI System): ✅ **Components ready**
- **PR #201-C** (this PR): Audio & Integration (4 files) ← **FINAL PIECE**

### Advanced Features:
- **Voice Recording**: Real-time audio capture with transcription
- **API Integration**: Seamless integration with SAMO-DL unified API
- **Security**: Client-side key redaction and proxy-based external calls
- **Environment Handling**: Automatic dev/prod configuration switching
- **Memory Management**: Proper audio buffer cleanup and resource management

### Integration Validation:
- [ ] Voice recording initializes without errors
- [ ] Configuration loads with proper environment detection
- [ ] All JavaScript modules integrate seamlessly in demo
- [ ] Audio transcription works end-to-end
- [ ] Error handling provides clear user feedback
- [ ] Accessibility features function correctly

### Dependencies:
- **Requires**: PR #203 (Platform Foundation) + PR #204 (UI System)
- **Completes**: Full JavaScript module ecosystem
- **Merge Order**: After #203 and #204 are merged
- **Final Result**: Complete voice-enabled emotion analysis demo

**🔧 Technical Highlights:**
- MediaRecorder API with multiple audio format support
- Dependency injection pattern for clean module separation
- Environment-specific configuration with security measures
- Complete end-to-end user workflow from voice to analysis
- Comprehensive error handling with user-friendly feedback

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces core UI components, LayoutManager and NotificationManager, with comprehensive test coverage. The overall structure is good, with a clear separation of concerns and use of modern JavaScript features. However, there are several areas for improvement. In LayoutManager, the dependency injection pattern is not consistently applied, and the logic for handling stuck processes could be more robust. In NotificationManager, there's some code duplication and an inefficient lifecycle for the toast container. Additionally, moving inline styles and hardcoded values to CSS would greatly improve maintainability. I've left specific comments with suggestions to address these points.

Comment thread website/js/layout-manager.js Outdated
const timeElapsed = Date.now() - this.processingStartTime;
if (timeElapsed > this.maxProcessingTime) {
console.warn(`⚠️ Processing stuck for ${timeElapsed/1000}s, forcing reset...`);
this.forceResetProcessing();
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

After forcing a reset on a stuck process, the function continues execution and starts a new process. This automatic restart can mask underlying issues that cause processes to get stuck and may lead to unexpected behavior. It's better to return false after the reset to signal that the operation was blocked. The caller can then check the logs and decide on the next action, like retrying. This change will require an update to the should detect and reset stuck processing test, which currently expects this method to return true.

Suggested change
this.forceResetProcessing();
this.forceResetProcessing();
return false;

Comment thread website/js/layout-manager.js Outdated
Comment thread website/js/notification-manager.js Outdated
Comment thread website/js/notification-manager.js Outdated
Comment thread website/js/notification-manager.js Outdated
Comment thread website/js/notification-manager.js Outdated
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (18)
website/js/notification-manager.js (6)

44-62: DRY and guard container recreation.

Use the new ensureContainer() and bail if DOM not ready.

-        // Ensure container exists (recreate if cleaned up)
-        if (!this.container || !this.container.parentNode) {
-            this.container = document.getElementById('toastContainer') || (() => {
-                const c = document.createElement('div');
-                c.id = 'toastContainer';
-                c.style.cssText = `
-                    position: fixed;
-                    top: 20px;
-                    right: 20px;
-                    display: flex;
-                    flex-direction: column;
-                    gap: 10px;
-                    z-index: 10000;
-                    pointer-events: none;
-                `;
-                document.body.appendChild(c);
-                return c;
-            })();
-        }
+        // Ensure container exists (recreate if cleaned up)
+        const container = this.ensureContainer();
+        if (!container) return; // DOM not ready yet

69-74: Use requestAnimationFrame for reliable entrance animation.

Avoid magic delay; rAF ensures styles are applied before transition.

-        setTimeout(() => {
-            toast.style.opacity = '1';
-            toast.style.transform = 'translateY(0)';
-        }, 10);
+        requestAnimationFrame(() => {
+            toast.style.opacity = '1';
+            toast.style.transform = 'translateY(0)';
+        });

121-128: Clamp type and add aria-atomic for screen readers.

Validate type and set aria-atomic="true" to read full updates.

-    createToast(message, type) {
+    createToast(message, type) {
+        const allowed = new Set(['success','error','info','warning']);
+        if (!allowed.has(type)) type = 'info';
         const toast = document.createElement('div');
-        toast.className = `notification-toast toast-${type}`;
+        toast.className = 'notification-toast';
+        toast.classList.add(`toast-${type}`);
 
         // Add accessibility attributes
-        toast.setAttribute('role', type === 'error' ? 'alert' : 'status');
-        toast.setAttribute('aria-live', type === 'error' ? 'assertive' : 'polite');
+        toast.setAttribute('role', type === 'error' ? 'alert' : 'status');
+        toast.setAttribute('aria-live', type === 'error' ? 'assertive' : 'polite');
+        toast.setAttribute('aria-atomic', 'true');

Want me to add aria-label with the type prefix (e.g., “Success: …”)?


137-151: Prefer modern CSS property and optional reduced-motion support.

Use overflow-wrap and respect prefers-reduced-motion.

-            word-wrap: break-word;
+            overflow-wrap: break-word;
             box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);

And add (outside cssText), for example:

+        const reduceMotion = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
+        if (reduceMotion) {
+            toast.style.transition = 'none';
+        }

39-41: Consider queuing or dropping oldest toast instead of ignoring.

Dropping new toasts can hide important messages; consider removing the oldest or queueing.

Would you prefer “drop oldest” semantics when at max capacity? I can patch it.


224-233: Gate noisy logs for production.

Wrap logs behind a debug flag (e.g., SAMO_CONFIG?.DEBUG) to keep consoles clean in prod.

website/js/layout-manager.js (10)

54-57: Use injected dependency instead of global reference.

Prefer this.dependencies.clearAllResultContent for testability and consistency.

-        if (typeof clearAllResultContent === 'function') {
-            clearAllResultContent();
-        }
+        if (this.dependencies.clearAllResultContent) {
+            this.dependencies.clearAllResultContent();
+        }

153-156: Same: rely on injected dependency for clearing results.

-        if (typeof clearAllResultContent === 'function') {
-            clearAllResultContent();
-        }
+        if (this.dependencies.clearAllResultContent) {
+            this.dependencies.clearAllResultContent();
+        }

158-166: Prefer injected inputLayout over querying DOM directly.

Reduces coupling and eases testing.

-        const inputLayout = document.getElementById('inputLayout');
+        const inputLayout = this.dependencies.inputLayout || document.getElementById('inputLayout');

184-196: Prefer injected resultsLayout.

-        const resultsLayout = document.getElementById('resultsLayout');
+        const resultsLayout = this.dependencies.resultsLayout || document.getElementById('resultsLayout');

404-406: Use dependency for clearing results here as well.

-    if (typeof clearAllResultContent === 'function') {
-        clearAllResultContent();
-    }
+    if (LayoutManager.dependencies.clearAllResultContent) {
+        LayoutManager.dependencies.clearAllResultContent();
+    }

433-433: Remove unused variable.

originalFunc is declared but never used.

-        const originalFunc = processText;

431-451: Return a promise from processTextWithStateManagement for callers to await.

Improves composability without changing current flow.

-        const maybe = processText(true);  // Skip state check since we handle it here
+        const maybe = processText(true);  // Skip state check since we handle it here
         const onDone = () => {
             // Minimal delay to ensure smooth UI transition after processing completes
             setTimeout(() => {
                 LayoutManager.showResultsState();
                 LayoutManager.updateProgressStep(4, 'completed');
             }, 50); // Reduced from 1000ms to 50ms for better perceived performance
         };
-        if (maybe && typeof maybe.then === 'function') {
-            maybe.then(onDone).catch((error) => {
+        if (maybe && typeof maybe.then === 'function') {
+            return maybe.then(onDone).catch((error) => {
                 console.error('Processing error:', error);
                 LayoutManager.resetToInitialState();
             });
         } else {
             onDone();
+            return Promise.resolve();
         }

331-336: Avoid hardcoding step count (4).

Optionally derive from DOM or a config to prevent drift.

Do we have a single source of truth for step count? If yes, I can wire it here.


339-379: toggleDebugSection: avoid lastChild brittleness.

Query a dedicated span (e.g., .label) for text to avoid DOM shape dependencies.


26-37: Reduce console noise or gate behind debug flag.

Current logging is verbose; consider if (window.SAMO_CONFIG?.DEBUG) console.log(...).

Also applies to: 95-99, 128-135, 203-214, 249-254, 385-392

website/test/setup.js (2)

45-49: Restore mocks in addition to clearing to prevent leakage across suites.

 afterEach(() => {
   vi.clearAllMocks();
+  vi.restoreAllMocks();
   document.body.innerHTML = '';
 });

24-33: Guard navigator when not provided and consider matchMedia stub.

Some environments may lack navigator or matchMedia. Safe guards improve portability.

-Object.defineProperty(navigator, 'mediaDevices', {
+if (typeof navigator !== 'undefined') Object.defineProperty(navigator, 'mediaDevices', {
   value: {
     getUserMedia: vi.fn().mockResolvedValue({
       getTracks: () => [{ stop: vi.fn() }]
     })
   },
   writable: true
-});
+});
+
+// Optional: matchMedia stub
+if (!window.matchMedia) {
+  window.matchMedia = vi.fn().mockReturnValue({ matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() });
+}
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between af71436 and 83b57c0.

📒 Files selected for processing (5)
  • website/js/layout-manager.js (1 hunks)
  • website/js/notification-manager.js (1 hunks)
  • website/test/layout-manager.test.js (1 hunks)
  • website/test/notification-manager.test.js (1 hunks)
  • website/test/setup.js (1 hunks)

Comment thread website/js/notification-manager.js
Comment thread website/test/layout-manager.test.js
- Fix race condition by not setting container to null after cleanup
- Extract duplicated container creation logic into ensureContainer() method
- Improve code maintainability and prevent potential race conditions
Notification Manager:
- Remove inefficient container create/destroy pattern - keep container in DOM
- Move hardcoded colors to CSS variables and apply via classes
- Replace large inline style blocks with semantic CSS classes
- Simplify show() method by removing ensureContainer() call

Layout Manager:
- Use dependency injection consistently instead of global function calls
- Fix processing reset to return false after forcing stuck process reset
- Replace direct DOM access with injected dependencies for better testability

CSS:
- Add notification color variables to variables.css
- Add notification toast styles and close button styles to messages.css
- Improve separation of concerns between JS and CSS
- Add forceResetSpy.mockRestore() to prevent spy leakage between tests
- Fixes CodeRabbit AI suggestion for proper test isolation
- Remove DOM element creation from constructor to prevent errors when script loads before DOM is ready
- Implement lazy container creation in ensureContainer() with proper DOM readiness checks
- Add graceful handling when DOM isn't ready (defers notifications instead of crashing)
- Fixes CodeRabbit AI critical issue for safer initialization
Notification Manager:
- Replace setTimeout with requestAnimationFrame for reliable animations
- Add type clamping with allowed values set for security
- Add aria-atomic='true' for better screen reader accessibility
- Use overflow-wrap instead of deprecated word-wrap CSS property
- Add reduced motion support respecting prefers-reduced-motion
- Gate noisy console logs behind SAMO_CONFIG?.DEBUG flag

Layout Manager:
- Use dependency injection consistently (clearAllResultContent, inputLayout, resultsLayout)
- Remove unused originalFunc variable
- Make processTextWithStateManagement return a Promise for better composability
- Gate console logs behind debug flag to reduce production noise
- Improve toggleDebugSection robustness by preferring .label class over lastChild

Test Setup:
- Add vi.restoreAllMocks() to prevent mock leakage across test suites
- Guard navigator access and add matchMedia stub for better environment compatibility

CSS:
- Update overflow-wrap property for modern CSS compliance
@uelkerd uelkerd self-assigned this Sep 28, 2025
- Test now expects startProcessing() to return false after force reset (preventing auto-restart)
- Updated test comments to reflect new behavior that prevents masking underlying issues
- Aligns test with the Gemini AI suggestion implementation
@uelkerd uelkerd merged commit d9f0e56 into main Sep 28, 2025
12 of 14 checks passed
@uelkerd uelkerd deleted the feat/ui-system-components branch September 28, 2025 19:40
uelkerd added a commit that referenced this pull request Sep 29, 2025
…d config

🏰 Fortress-Compliant PR (4/5 files) - Audio & Integration

This PR completes the JavaScript module system with advanced voice recording,
enhanced configuration management, and full demo integration.

- website/js/voice-recorder.js - Advanced audio recording with MediaRecorder API
- website/test/config.test.js - Unit tests for configuration management
- website/js/config.js - Enhanced configuration with security and environment handling
- website/comprehensive-demo.html - Integrated demo with all module dependencies

✅ **Voice Recording**: MediaRecorder API with audio transcription integration
✅ **Enhanced Configuration**: Environment-specific settings and security redaction
✅ **Complete Integration**: Full demo showcasing all JavaScript modules working together
✅ **Security Hardening**: Sensitive data redaction and proxy-based API calls
✅ **Testing Coverage**: Unit tests for configuration management functionality
✅ **Browser Compatibility**: Graceful degradation for unsupported features
✅ **Accessibility**: Full audio recording accessibility with proper feedback
✅ **Error Handling**: Comprehensive error management across all components

This is **PR #201-C** (FINAL) of the three-part Hybrid Fortress split:
- **PR #201-A** (Platform Foundation): ✅ **Infrastructure ready**
- **PR #201-B** (UI System): ✅ **Components ready**
- **PR #201-C** (this PR): Audio & Integration (4 files) ← **FINAL PIECE**

- **Voice Recording**: Real-time audio capture with transcription
- **API Integration**: Seamless integration with SAMO-DL unified API
- **Security**: Client-side key redaction and proxy-based external calls
- **Environment Handling**: Automatic dev/prod configuration switching
- **Memory Management**: Proper audio buffer cleanup and resource management

- [ ] Voice recording initializes without errors
- [ ] Configuration loads with proper environment detection
- [ ] All JavaScript modules integrate seamlessly in demo
- [ ] Audio transcription works end-to-end
- [ ] Error handling provides clear user feedback
- [ ] Accessibility features function correctly

- **Requires**: PR #203 (Platform Foundation) + PR #204 (UI System)
- **Completes**: Full JavaScript module ecosystem
- **Merge Order**: After #203 and #204 are merged
- **Final Result**: Complete voice-enabled emotion analysis demo

**🔧 Technical Highlights:**
- MediaRecorder API with multiple audio format support
- Dependency injection pattern for clean module separation
- Environment-specific configuration with security measures
- Complete end-to-end user workflow from voice to analysis
- Comprehensive error handling with user-friendly feedback

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants