Lesson 08-UI, UX Design, and Interaction

UI/UX Design Principles and Interaction for Browser Extensions

The UI/UX design of browser extensions is a critical factor in determining user experience. Its uniqueness lies in delivering efficient functional interactions within extremely limited screen space (e.g., popup windows, toolbar icons) while ensuring cross-platform consistency, performance optimization, and accessibility. This section systematically explores the UI/UX design principles, interaction patterns, and cross-platform adaptation strategies for browser extensions.

Extension UI Design Principles and Patterns

Design Philosophy Under Space Constraints

Browser extension UI containers (e.g., popup windows, sidebars, toolbar icons) typically have strict size limitations, requiring designs to adhere to the principle of “less is more” by leveraging precise information architecture and interaction design to enhance efficiency.

Core Design Principles:

  1. Single-Task Focus: Each UI component should address a single core issue (e.g., “one-click cache clearing” rather than “settings management”).
  2. Progressive Disclosure: Display high-frequency functions by default, with secondary functions accessible via clicks (e.g., hamburger menu → advanced settings).
  3. Immediate Feedback: All operations must provide visual feedback within 200ms (e.g., icon state changes, micro-interaction animations).
  4. Maximized Space Efficiency: Use compact layouts (e.g., vertical stacking instead of horizontal arrangement) and symbolic icons (avoiding text labels).

Typical Space Allocation Schemes:

Container TypeRecommended Size RangeFunctional ComplexityTypical Layout Pattern
Toolbar Icon16×16–48×48Single OperationStatus Icon + Tooltip
Popup Window240×320–400×600Medium ComplexityVertical Card Layout
Sidebar200px–400px WidthHigh ComplexityColumn List + Detail Panel
Options PageFull Screen/PopupHigh ComplexityMulti-Tab Form

Micro-Interaction Design Patterns

Micro-interactions are critical details for enhancing extension usability, guiding user perception of operation outcomes through animations and transitions.

// Popup window loading micro-interaction example
document.addEventListener('DOMContentLoaded', () => {
  const popup = document.getElementById('popup-container');
  const loadingSpinner = document.createElement('div');
  loadingSpinner.className = 'loading-spinner';

  // Initial state: Show loading animation
  popup.appendChild(loadingSpinner);

  // Simulate asynchronous data loading
  setTimeout(() => {
    // Remove loading animation
    popup.removeChild(loadingSpinner);

    // Fade-in content
    const content = document.getElementById('popup-content');
    content.style.opacity = '0';
    content.style.transition = 'opacity 0.3s ease-in';
    setTimeout(() => {
      content.style.opacity = '1';
    }, 10);

    // Trigger layout animation
    animateLayout();
  }, 800);

  // Layout animation function
  function animateLayout() {
    const cards = document.querySelectorAll('.card');
    cards.forEach((card, index) => {
      card.style.transform = 'translateY(20px)';
      card.style.opacity = '0';
      card.style.transition = `all 0.3s ease-out ${index * 0.1}s`;

      setTimeout(() => {
        card.style.transform = 'translateY(0)';
        card.style.opacity = '1';
      }, 50);
    });
  }
});

Key Micro-Interaction Patterns:

  1. State Transition Feedback:
    • Icon color changes (gray → blue to indicate activation).
    • Progress indicators (circular progress bars instead of loading text).
    • Micro-animations (slight button scaling on click).
  2. Operation Guidance Prompts:
    • First-use onboarding overlays (progressive disclosure).
    • Hover state scaling (CSS transform: scale(1.05)).
    • Tooltips (following cursor movement).
  3. Error Recovery Prompts:
    • Shake animations (indicating input errors).
    • Pulsing error icons (CSS opacity animation).
    • Auto-disappearing notification bars (fade out after 5 seconds).

Cross-Platform UI Adaptation Strategies

Platform Visual Language Adaptation

Different browser platforms have distinct visual standards, necessitating a unified adaptation layer to achieve “design once, adapt to multiple platforms.”

Platform Design Specification Comparison:

Design ElementChrome/EdgeFirefoxSafari
Color SystemMaterial DesignPhoton Design SystemApple Human Interface
Font StackRobotosystem-ui-apple-system
Icon StyleLinear Icons + Rounded CornersLinear Icons + Sharp CornersFlat Icons
Shadow EffectsElevation LevelsLight ShadowsMinimal Shadows
Animation Curveease-in-outcubic-bezier(0.2, 0.8)linear

Adaptation Layer Implementation:

/* Platform adaptation variable definitions */
:root {
  /* Default values (Chrome) */
  --primary-color: #4285f4;
  --text-color: #333333;
  --border-radius: 8px;
  --shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  --transition: all 0.3s ease-in-out;
}

/* Firefox adaptation */
@-moz-document url-prefix() {
  :root {
    --primary-color: #ff9500;
    --border-radius: 4px;
    --shadow: 0 1px 5px rgba(0, 0, 0, 0.1);
  }
}

/* Safari adaptation */
@media not all and (min-resolution:.001dpcm) { 
  @supports (-webkit-appearance:none) {
    :root {
      --primary-color: #007aff;
      --shadow: none;
      --transition: all 0.2s linear;
    }
  }
}

/* Apply variables to components */
.popup-button {
  background-color: var(--primary-color);
  color: white;
  border-radius: var(--border-radius);
  box-shadow: var(--shadow);
  transition: var(--transition);
}

Icon System Adaptation:

// Dynamically load platform-specific icons
class IconLoader {
  constructor() {
    this.platform = this.detectPlatform();
    this.init();
  }

  detectPlatform() {
    if (navigator.userAgent.includes('Firefox')) return 'firefox';
    if (navigator.userAgent.includes('Safari') && !navigator.userAgent.includes('Chrome')) return 'safari';
    return 'chrome'; // Default to Chrome
  }

  async init() {
    const iconSet = await this.loadIconSet(this.platform);
    this.injectIcons(iconSet);
  }

  async loadIconSet(platform) {
    // In practice, load different icon sets from CDN or locally
    const iconMaps = {
      chrome: {
        settings: 'icons/chrome/settings.svg',
        refresh: 'icons/chrome/refresh.svg'
      },
      firefox: {
        settings: 'icons/firefox/settings.svg',
        refresh: 'icons/firefox/refresh.svg'
      },
      safari: {
        settings: 'icons/safari/settings.svg',
        refresh: 'icons/safari/refresh.svg'
      }
    };

    return iconMaps[platform];
  }

  injectIcons(iconMap) {
    document.querySelectorAll('[data-icon]').forEach(element => {
      const iconName = element.dataset.icon;
      if (iconMap[iconName]) {
        element.innerHTML = `<img src="${iconMap[iconName]}" alt="${iconName}">`;
      }
    });
  }
}

// Usage example
new IconLoader();

Responsive Layout Techniques

Extension UIs must adapt to different container sizes, making responsive design techniques essential.

CSS Grid Layout Example:

/* Popup window base layout */
.popup-container {
  display: grid;
  grid-template-rows: auto 1fr auto;
  height: 100vh;
  padding: 16px;
  box-sizing: border-box;
}

/* Card grid layout */
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
  gap: 12px;
  overflow-y: auto;
}

/* Platform-specific adjustments */
@-moz-document url-prefix() {
  .card-grid {
    grid-template-columns: repeat(auto-fill, minmax(100px, 1fr));
  }
}

@media (max-width: 320px) {
  .card-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

/* Toolbar responsive layout */
.toolbar {
  display: flex;
  gap: 8px;
  overflow-x: auto;
  scrollbar-width: none; /* Firefox */
}

.toolbar::-webkit-scrollbar {
  display: none; /* Chrome/Safari */
}

.toolbar-button {
  flex-shrink: 0;
  min-width: 40px;
}

JavaScript Dynamic Layout Adjustment:

// Dynamic layout adjustment class
class LayoutAdapter {
  constructor() {
    this.popup = document.getElementById('popup-container');
    this.init();
  }

  init() {
    this.setupResizeObserver();
    this.adjustLayout();
  }

  setupResizeObserver() {
    const resizeObserver = new ResizeObserver(entries => {
      for (let entry of entries) {
        if (entry.target === this.popup) {
          this.adjustLayout();
        }
      }
    });

    resizeObserver.observe(this.popup);
  }

  adjustLayout() {
    const width = this.popup.clientWidth;

    // Switch layout mode based on width
    if (width < 280) {
      this.activateCompactMode();
    } else if (width < 400) {
      this.activateStandardMode();
    } else {
      this.activateExpandedMode();
    }
  }

  activateCompactMode() {
    document.body.classList.add('layout-compact');
    document.body.classList.remove('layout-standard', 'layout-expanded');

    // Adjust font size
    document.documentElement.style.fontSize = '12px';

    // Hide secondary elements
    document.querySelectorAll('.secondary-action').forEach(el => {
      el.style.display = 'none';
    });
  }

  activateStandardMode() {
    document.body.classList.add('layout-standard');
    document.body.classList.remove('layout-compact', 'layout-expanded');

    document.documentElement.style.fontSize = '14px';
    document.querySelectorAll('.secondary-action').forEach(el => {
      el.style.display = 'block';
    });
  }

  activateExpandedMode() {
    document.body.classList.add('layout-expanded');
    document.body.classList.remove('layout-compact', 'layout-standard');

    document.documentElement.style.fontSize = '16px';
    // Show all functional elements
  }
}

// Usage example
new LayoutAdapter();

Advanced Interaction Patterns

Complex Gesture Interaction Support

Extension UIs need to support rich interaction methods, including mouse, touch, and keyboard operations.

Drag-and-Drop Sorting Example:

// Draggable list component
class DraggableList {
  constructor(containerId) {
    this.container = document.getElementById(containerId);
    this.items = Array.from(this.container.children);
    this.draggedItem = null;
    this.init();
  }

  init() {
    this.items.forEach(item => {
      item.draggable = true;
      item.addEventListener('dragstart', this.handleDragStart.bind(this));
      item.addEventListener('dragover', this.handleDragOver.bind(this));
      item.addEventListener('drop', this.handleDrop.bind(this));
      item.addEventListener('dragend', this.handleDragEnd.bind(this));
    });
  }

  handleDragStart(e) {
    this.draggedItem = e.target;
    setTimeout(() => {
      e.target.classList.add('dragging');
    }, 0);

    // Set drag data
    e.dataTransfer.setData('text/plain', e.target.dataset.id);
    e.dataTransfer.effectAllowed = 'move';
  }

  handleDragOver(e) {
    e.preventDefault();
    const afterElement = this.getDragAfterElement(this.container, e.clientY);
    if (afterElement == null) {
      this.container.appendChild(this.draggedItem);
    } else {
      this.container.insertBefore(this.draggedItem, afterElement);
    }
  }

  getDragAfterElement(container, y) {
    const draggableElements = [...container.querySelectorAll('.draggable:not(.dragging)')];

    return draggableElements.reduce((closest, child) => {
      const box = child.getBoundingClientRect();
      const offset = y - box.top - box.height / 2;

      if (offset < 0 && offset > closest.offset) {
        return { offset: offset, element: child };
      } else {
        return closest;
      }
    }, { offset: Number.NEGATIVE_INFINITY }).element;
  }

  handleDrop(e) {
    e.preventDefault();
    // Handle data updates...
  }

  handleDragEnd(e) {
    this.draggedItem.classList.remove('dragging');
    this.draggedItem = null;

    // Trigger layout update animation
    this.animateLayoutUpdate();
  }

  animateLayoutUpdate() {
    this.items = Array.from(this.container.children);
    this.items.forEach((item, index) => {
      item.style.transform = `translateY(0)`;
      item.style.transition = 'transform 0.3s ease';

      // Add position change animations if needed
    });
  }
}

// Usage example
new DraggableList('sortable-list');

Keyboard Navigation Support:

// Keyboard navigation controller
class KeyboardNavigator {
  constructor(focusableSelector) {
    this.focusableElements = Array.from(document.querySelectorAll(focusableSelector));
    this.currentIndex = 0;
    this.init();
  }

  init() {
    document.addEventListener('keydown', this.handleKeyDown.bind(this));

    // Set initial focus
    if (this.focusableElements.length > 0) {
      this.focusableElements[0].focus();
    }
  }

  handleKeyDown(e) {
    switch (e.key) {
      case 'ArrowDown':
      case 'ArrowRight':
        e.preventDefault();
        this.moveFocus(1);
        break;
      case 'ArrowUp':
      case 'ArrowLeft':
        e.preventDefault();
        this.moveFocus(-1);
        break;
      case 'Home':
        e.preventDefault();
        this.currentIndex = 0;
        this.focusableElements[0].focus();
        break;
      case 'End':
        e.preventDefault();
        this.currentIndex = this.focusableElements.length - 1;
        this.focusableElements[this.currentIndex].focus();
        break;
    }
  }

  moveFocus(step) {
    this.currentIndex = (this.currentIndex + step + this.focusableElements.length) % this.focusableElements.length;
    this.focusableElements[this.currentIndex].focus();
  }
}

// Usage example
new KeyboardNavigator('.popup-button, .list-item');

Accessibility Design

Ensuring that the extension UI is accessible to all users, including those using assistive technologies, is critical.

ARIA Attribute Best Practices:

<!-- Accessible popup window example -->
<div 
  id="popup-container"
  role="dialog"
  aria-labelledby="popup-title"
  aria-modal="true"
  aria-describedby="popup-description"
>
  <h2 id="popup-title">Extension Settings</h2>
  <p id="popup-description">Adjust the behavior and appearance of the extension</p>

  <div class="settings-group">
    <label for="theme-select">Theme Selection</label>
    <select 
      id="theme-select"
      aria-label="Select extension theme"
      aria-required="true"
    >
      <option value="light">Light</option>
      <option value="dark">Dark</option>
      <option value="system">Follow System</option>
    </select>
  </div>

  <button 
    id="save-button"
    aria-label="Save settings"
    aria-live="polite"
  >
    Save
  </button>
</div>

Accessibility Interaction Enhancements:

// Accessibility controller
class AccessibilityEnhancer {
  constructor() {
    this.init();
  }

  init() {
    this.enhanceFocusManagement();
    this.addAriaLiveRegions();
    this.setupKeyboardShortcuts();
  }

  enhanceFocusManagement() {
    // Trap focus within popup
    document.addEventListener('keydown', (e) => {
      if (e.key === 'Tab') {
        const popup = document.getElementById('popup-container');
        if (popup && popup.contains(document.activeElement)) {
          const focusable = this.getFocusableElements(popup);
          if (e.shiftKey && document.activeElement === focusable[0]) {
            e.preventDefault();
            focusable[focusable.length - 1].focus();
          } else if (!e.shiftKey && document.activeElement === focusable[focusable.length - 1]) {
            e.preventDefault();
            focusable[0].focus();
          }
        }
      }
    });
  }

  getFocusableElements(container) {
    return Array.from(container.querySelectorAll(
      'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
    )).filter(el => !el.disabled && el.offsetParent !== null);
  }

  addAriaLiveRegions() {
    // Add ARIA live region for dynamic content
    const statusRegion = document.createElement('div');
    statusRegion.setAttribute('aria-live', 'polite');
    statusRegion.setAttribute('aria-atomic', 'true');
    statusRegion.className = 'sr-only';
    document.body.appendChild(statusRegion);

    // Example: Update status message
    this.updateStatus = (message) => {
      statusRegion.textContent = message;
    };
  }

  setupKeyboardShortcuts() {
    // Global keyboard shortcuts
    document.addEventListener('keydown', (e) => {
      // Ctrl+Shift+Y to open extension (Windows/Linux)
      if (e.ctrlKey && e.shiftKey && e.key === 'Y') {
        this.openPopup();
      }
      // Command+Shift+Y to open extension (Mac)
      else if (e.metaKey && e.shiftKey && e.key === 'Y') {
        this.openPopup();
      }
    });
  }

  openPopup() {
    const popup = document.getElementById('popup-container');
    if (popup) {
      popup.style.display = 'block';
      // Set initial focus
      const firstFocusable = this.getFocusableElements(popup)[0];
      if (firstFocusable) {
        firstFocusable.focus();
      }
      this.updateStatus('Extension settings panel opened');
    }
  }
}

// Usage example
new AccessibilityEnhancer();

Performance Optimization and Experience Enhancement

UI Rendering Performance Optimization

Extension UIs must remain smooth in resource-constrained environments, making performance optimization critical.

CSS Hardware Acceleration Techniques:

/* Enable GPU-accelerated animations */
.animated-element {
  transform: translateZ(0); /* Trigger hardware acceleration */
  will-change: transform, opacity; /* Hint browser for optimization */

  /* Use composite properties for animations */
  transition: 
    transform 0.3s cubic-bezier(0.2, 0.8, 0.2, 1),
    opacity 0.2s ease;
}

/* Avoid repaints in layout */
.static-layout {
  position: absolute;
  contain: layout style; /* Restrict browser repaint scope */
}

/* Efficient selectors */
.popup-button { /* Good: Class selector */ }
div ul li a { /* Bad: Overly specific selector */ }

JavaScript Rendering Optimization:

// Virtual list implementation example
class VirtualList {
  constructor(containerId, itemHeight, totalItems, renderItem) {
    this.container = document.getElementById(containerId);
    this.itemHeight = itemHeight;
    this.totalItems = totalItems;
    this.renderItem = renderItem;
    this.visibleItems = Math.ceil(this.container.clientHeight / this.itemHeight);
    this.init();
  }

  init() {
    // Set container height to create scroll space
    this.container.style.height = `${this.totalItems * this.itemHeight}px`;

    // Create viewport placeholder
    this.viewport = document.createElement('div');
    this.viewport.className = 'viewport';
    this.container.appendChild(this.viewport);

    // Initial rendering
    this.renderVisibleItems();

    // Scroll event handling (with throttling)
    this.handleScroll = this.throttle(this.handleScroll.bind(this), 16);
    this.container.addEventListener('scroll', this.handleScroll);
  }

  throttle(fn, limit) {
    let lastFn;
    let lastRan;
    return function() {
      const context = this;
      const args = arguments;
      if (!lastRan) {
        fn.apply(context, args);
        lastRan = Date.now();
      } else {
        clearTimeout(lastFn);
        lastFn = setTimeout(function() {
          if ((Date.now() - lastRan) >= limit) {
            fn.apply(context, args);
            lastRan = Date.now();
          }
        }, limit - (Date.now() - lastRan));
      }
    };
  }

  handleScroll() {
    this.renderVisibleItems();
  }

  renderVisibleItems() {
    const scrollTop = this.container.scrollTop;
    const startIndex = Math.floor(scrollTop / this.itemHeight);
    const endIndex = Math.min(startIndex + this.visibleItems + 2, this.totalItems);

    // Reuse existing DOM elements
    const existingChildren = Array.from(this.viewport.children);
    const neededChildren = endIndex - startIndex;

    // Update existing elements
    for (let i = 0; i < neededChildren && i < existingChildren.length; i++) {
      const itemIndex = startIndex + i;
      this.renderItem(existingChildren[i], itemIndex);
      existingChildren[i].style.transform = `translateY(${itemIndex * this.itemHeight}px)`;
    }

    // Remove excess elements
    while (existingChildren.length > neededChildren) {
      this.viewport.removeChild(existingChildren.pop());
    }

    // Add new elements
    while (existingChildren.length < neededChildren) {
      const newItem = document.createElement('div');
      newItem.className = 'list-item';
      this.renderItem(newItem, startIndex + existingChildren.length);
      newItem.style.transform = `translateY(${(startIndex + existingChildren.length) * this.itemHeight}px)`;
      this.viewport.appendChild(newItem);
    }
  }
}

// Usage example
new VirtualList('scroll-container', 40, 1000, (element, index) => {
  element.textContent = `Item ${index + 1}`;
});

Data Loading and Caching Strategies

Optimizing data flow can significantly improve extension responsiveness.

Smart Preloading Pattern:

// Data preloading controller
class DataPreloader {
  constructor() {
    this.cache = new Map();
    this.prefetchQueue = [];
    this.init();
  }

  init() {
    // Listen for user behavior to predict preloading
    this.setupBehaviorPrediction();

    // Preload critical data
    this.prefetchCriticalData();
  }

  setupBehaviorPrediction() {
    // Example: Predict buttons users may click
    const buttons = document.querySelectorAll('.predictive-button');
    buttons.forEach(button => {
      button.addEventListener('mouseenter', () => {
        const dataKey = button.dataset.prefetch;
        if (dataKey && !this.cache.has(dataKey)) {
          this.addToPrefetchQueue(dataKey);
        }
      });

      button.addEventListener('click', () => {
        const dataKey = button.dataset.dataKey;
        this.loadData(dataKey);
      });
    });
  }

  prefetchCriticalData() {
    // Preload data needed for initial screen
    this.prefetchData('userProfile');
    this.prefetchData('commonSettings');
  }

  addToPrefetchQueue(key) {
    if (!this.prefetchQueue.includes(key)) {
      this.prefetchQueue.push(key);
      this.processPrefetchQueue();
    }
  }

  async processPrefetchQueue() {
    while (this.prefetchQueue.length > 0) {
      const key = this.prefetchQueue.shift();
      if (!this.cache.has(key)) {
        await this.loadData(key);
      }
    }
  }

  async loadData(key) {
    // Check cache
    if (this.cache.has(key)) {
      return this.cache.get(key);
    }

    // Show loading indicator
    this.showLoadingIndicator(key);

    try {
      // Simulate API request
      const data = await this.fetchDataFromSource(key);

      // Cache data
      this.cache.set(key, data);

      // Hide loading indicator
      this.hideLoadingIndicator(key);

      return data;
    } catch (error) {
      console.error(`Failed to load data ${key}:`, error);
      this.hideLoadingIndicator(key);
      throw error;
    }
  }

  fetchDataFromSource(key) {
    // Replace with actual data source in practice
    return new Promise(resolve => {
      setTimeout(() => {
        resolve({ key, data: `Sample data ${key}` });
      }, 300); // Simulate network delay
    });
  }

  showLoadingIndicator(key) {
    // Show loading state UI
    console.log(`Showing ${key} loading indicator`);
  }

  hideLoadingIndicator(key) {
    // Hide loading state UI
    console.log(`Hiding ${key} loading indicator`);
  }
}

// Usage example
const preloader = new DataPreloader();

// When data is needed
async function showUserData() {
  const data = await preloader.loadData('userProfile');
  document.getElementById('user-profile').textContent = data.data;
}

Local Caching Strategy:

// Smart cache manager
class SmartCacheManager {
  constructor(namespace = 'ext_cache') {
    this.namespace = namespace;
    this.init();
  }

  init() {
    // Initialize cache statistics
    this.cacheStats = {
      hits: 0,
      misses: 0,
      size: 0
    };

    // Load cache metadata
    this.loadMetadata();
  }

  async loadMetadata() {
    const meta = await chrome.storage.local.get(`${this.namespace}_meta`);
    if (meta[`${this.namespace}_meta`]) {
      this.cacheMetadata = meta[`${this.namespace}_meta`];
    } else {
      this.cacheMetadata = {};
    }
  }

  async get(key) {
    // Check memory cache
    if (this.memoryCache && this.memoryCache.has(key)) {
      this.cacheStats.hits++;
      return this.memoryCache.get(key);
    }

    // Check storage cache
    const cached = await chrome.storage.local.get(`${this.namespace}_${key}`);
    if (cached[`${this.namespace}_${key}`]) {
      this.cacheStats.hits++;

      // Update memory cache
      if (!this.memoryCache) {
        this.memoryCache = new Map();
      }
      this.memoryCache.set(key, cached[`${this.namespace}_${key}`]);

      return cached[`${this.namespace}_${key}`];
    }

    this.cacheStats.misses++;
    return null;
  }

  async set(key, value, ttl = 3600) {
    // Update memory cache
    if (!this.memoryCache) {
      this.memoryCache = new Map();
    }
    this.memoryCache.set(key, value);

    // Store to chrome.storage
    await chrome.storage.local.set({
      [`${this.namespace}_${key}`]: value
    });

    // Update metadata
    this.cacheMetadata[key] = {
      timestamp: Date.now(),
      ttl: ttl
    };
    await chrome.storage.local.set({
      [`${this.namespace}_meta`]: this.cacheMetadata
    });

    // Check cache size and clean up
    this.checkCacheSize();
  }

  async checkCacheSize() {
    // Simplified implementation: Calculate storage usage in practice
    const MAX_ITEMS = 100;
    if (Object.keys(this.cacheMetadata).length > MAX_ITEMS) {
      // Find oldest entry
      const oldestKey = Object.entries(this.cacheMetadata)
        .sort((a, b) => a[1].timestamp - b[1].timestamp)[0][0];

      // Remove oldest entry
      await chrome.storage.local.remove([
        `${this.namespace}_${oldestKey}`,
        `${this.namespace}_meta`
      ]);

      // Update metadata
      delete this.cacheMetadata[oldestKey];
      await chrome.storage.local.set({
        [`${this.namespace}_meta`]: this.cacheMetadata
      });
    }
  }

  async clear() {
    await chrome.storage.local.remove([
      ...Object.keys(this.cacheMetadata).map(key => `${this.namespace}_${key}`),
      `${this.namespace}_meta`
    ]);

    this.cacheMetadata = {};
    if (this.memoryCache) {
      this.memoryCache.clear();
    }
  }
}

// Usage example
const cache = new SmartCacheManager('user_data');

// Store data
await cache.set('preferences', { theme: 'dark' });

// Retrieve data
const prefs = await cache.get('preferences');
Share your love