Files
michaelschiemer/docs/livecomponents/livecomponents-dom-badges.md
Michael Schiemer 36ef2a1e2c
Some checks failed
🚀 Build & Deploy Image / Determine Build Necessity (push) Failing after 10m14s
🚀 Build & Deploy Image / Build Runtime Base Image (push) Has been skipped
🚀 Build & Deploy Image / Build Docker Image (push) Has been skipped
🚀 Build & Deploy Image / Run Tests & Quality Checks (push) Has been skipped
🚀 Build & Deploy Image / Auto-deploy to Staging (push) Has been skipped
🚀 Build & Deploy Image / Auto-deploy to Production (push) Has been skipped
Security Vulnerability Scan / Check for Dependency Changes (push) Failing after 11m25s
Security Vulnerability Scan / Composer Security Audit (push) Has been cancelled
fix: Gitea Traefik routing and connection pool optimization
- Remove middleware reference from Gitea Traefik labels (caused routing issues)
- Optimize Gitea connection pool settings (MAX_IDLE_CONNS=30, authentication_timeout=180s)
- Add explicit service reference in Traefik labels
- Fix intermittent 504 timeouts by improving PostgreSQL connection handling

Fixes Gitea unreachability via git.michaelschiemer.de
2025-11-09 14:46:15 +01:00

7.9 KiB

LiveComponents DOM Badges System

Visual component overlays for real-time monitoring and debugging.

Overview

The DOM Badges system provides visual overlays on LiveComponent elements, displaying component IDs, names, and activity counters directly on the page. This enables developers to quickly identify and debug components without opening the DevTools panel.

Features

Visual Component Identification

  • Component Name: Shows the component's display name
  • Component ID: Truncated ID (first 8 characters) for identification
  • Icon Indicator: icon for visual consistency

Real-Time Activity Tracking

  • Action Counter: Tracks number of actions executed on the component
  • Activity Animation: Badge pulses with green highlight when actions are triggered
  • Live Updates: Counter updates in real-time as actions execute

Interactive Features

  • Click to Focus: Click badge to open DevTools and focus on that component
  • Hover Highlight: Hover over badge to highlight the component element with blue outline
  • DevTools Integration: Clicking badge scrolls to component in tree and expands details

Badge Management

  • Toggle Visibility: Badge button in DevTools header to show/hide all badges
  • Auto-Positioning: Badges automatically position at top-left of component elements
  • Dynamic Updates: Badges track DOM changes and update positions accordingly

Architecture

Badge Data Structure

{
    badge: HTMLElement,      // Badge DOM element
    element: HTMLElement,    // Component element
    actionCount: number      // Number of actions executed
}

Badge Lifecycle

  1. Initialization: initializeDomBadges() sets up MutationObserver
  2. Creation: createDomBadge() creates badge for each component
  3. Positioning: positionBadge() calculates fixed position
  4. Updates: updateBadgeActivity() increments counter and triggers animation
  5. Cleanup: cleanupRemovedBadges() removes badges for destroyed components

Usage

Automatic Badge Creation

Badges are automatically created when:

  • DevTools is opened and components exist in DOM
  • New components are added to the page (via MutationObserver)
  • Badge visibility is toggled on

Toggle Badge Visibility

// Via DevTools UI: Click "⚡ Badges" button in header

// Programmatically
devTools.toggleBadges();

Badge Interactions

Click Badge:

  • Opens DevTools if closed
  • Switches to Components tab
  • Scrolls to component in tree
  • Expands component details

Hover Badge:

  • Shows blue outline around component element
  • Highlights component boundaries for easy identification

Styling

Badge Appearance

  • Background: Dark semi-transparent (#1e1e1e with 95% opacity)
  • Border: Blue (#007acc) that changes to green (#4ec9b0) on hover
  • Backdrop Filter: 4px blur for modern glass-morphism effect
  • Box Shadow: Subtle shadow for depth

Active Animation

@keyframes badge-pulse {
    0%   { transform: scale(1);   box-shadow: default }
    50%  { transform: scale(1.1); box-shadow: green glow }
    100% { transform: scale(1);   box-shadow: default }
}

Color Coding

  • Component Name: Blue (#569cd6) - VS Code variable color
  • Component ID: Gray (#858585) - subdued identifier
  • Action Count: Yellow (#dcdcaa) - VS Code function color
  • Active Border: Green (#4ec9b0) - VS Code string color

Technical Implementation

MutationObserver Integration

const observer = new MutationObserver(() => {
    this.updateDomBadges();
});

observer.observe(document.body, {
    childList: true,
    subtree: true,
    attributes: true,
    attributeFilter: ['data-component-id']
});

Position Calculation

Badges use fixed positioning with getBoundingClientRect():

const rect = element.getBoundingClientRect();
badge.style.position = 'fixed';
badge.style.top = `${rect.top + window.scrollY}px`;
badge.style.left = `${rect.left + window.scrollX}px`;

Activity Tracking Integration

// In logAction() method
logAction(componentId, ...) {
    // ... log action ...

    // Update badge
    this.updateBadgeActivity(componentId);
}

Performance Considerations

Efficient Updates

  • Deduplication: Checks if badge already exists before creating
  • Position Updates: Only updates position for existing badges
  • Cleanup: Removes badges for destroyed components to prevent memory leaks

Throttled DOM Operations

  • MutationObserver: Batches DOM changes
  • Single Reflow: Badge creation/positioning minimizes layout thrashing
  • Display None: Hidden badges use display: none instead of removal

Best Practices

When to Use Badges

Good Use Cases:

  • Debugging component layout and positioning
  • Identifying which components are active on a page
  • Tracking component action frequency
  • Visual confirmation of component presence

Avoid:

  • Production environments (only enabled in development)
  • Pages with 50+ components (visual clutter)
  • When precise layout debugging is needed (use browser DevTools instead)

Badge Visibility Toggle

  • Keep badges enabled when actively debugging components
  • Disable badges when focusing on other DevTools tabs
  • Badges automatically show when DevTools opens

Integration with DevTools Features

Component Tree

  • Clicking badge navigates to component in tree
  • Badge highlights component row with blue background
  • Component details automatically expand

Action Log

  • Badge counter matches action log entries
  • Activity animation syncs with action execution
  • Both show real-time component behavior

Event System

  • Badges react to component lifecycle events
  • Auto-created on component:initialized
  • Auto-removed on component:destroyed

Keyboard Shortcuts

No direct keyboard shortcuts for badges, but:

  • Ctrl+Shift+D: Toggle DevTools (shows/creates badges)
  • Click Badge: Focus component in DevTools

Browser Compatibility

  • Modern Browsers: Full support (Chrome, Firefox, Safari, Edge)
  • MutationObserver: Required (IE11+ supported)
  • CSS Animations: Fallback to no animation on older browsers
  • Backdrop Filter: Graceful degradation without blur effect

Troubleshooting

Badges Not Appearing

  1. Check if DevTools is enabled (data-env="development")
  2. Verify components have data-component-id attribute
  3. Ensure badges are enabled (check button opacity in header)
  4. Look for JavaScript errors in console

Badges in Wrong Position

  1. Check if component element has proper layout (not display: none)
  2. Verify parent containers don't have transform CSS
  3. Badge position updates on DOM mutations
  4. Manually refresh badges with toggle button

Performance Issues

  1. Reduce number of active components
  2. Disable badges when not actively debugging
  3. Check MutationObserver frequency in console
  4. Consider using Components tab instead for many components

Future Enhancements

Potential improvements for DOM badges:

  • State Preview: Show current component state in badge tooltip
  • Network Indicator: Visual indicator when component is loading
  • Error State: Red badge when component has errors
  • Badge Groups: Collapsible badges for nested components
  • Custom Badge Colors: User-configurable color schemes
  • Badge Size Options: Small/Medium/Large badge sizes
  • Filter by Type: Show only specific component types

Summary

DOM badges provide a powerful visual debugging tool that complements the DevTools overlay. They enable:

  • Instant Component Identification: See what's on the page without opening DevTools
  • Real-Time Activity Monitoring: Track action execution as it happens
  • Quick Navigation: Click to jump to component in DevTools
  • Visual Feedback: Animations and highlights for enhanced UX

The badge system is designed to be non-intrusive, performant, and seamlessly integrated with the LiveComponent lifecycle and DevTools features.