Angular playground

Nova v3.37.0

Preview

Angular

nv-sidebar guide

Persistent and collapsible sidebars, with a complete example.

← nv-sidebar

nv-sidebar

Introduction

nv-sidebar provides a vertical navigation sidebar for application layouts. It supports persistent and collapsible modes, nested navigation groups with sub-items, notification badges, and automatic active-state highlighting based on the current route.

Key Features:

  • Persistent and collapsible sidebar modes
  • Nested navigation with sub-items
  • Notification badges with configurable intention and emphasis
  • Automatic active state management via active-path

Basic Usage

Persistent Sidebar

html<nv-sidebar type="persistent">
  <nv-sidebarlogo label="My App"></nv-sidebarlogo>

  <nv-sidebarcontent>
    <nv-sidebargroup label="Navigation">
      <nv-sidebarnavitem icon="home">
        <a href="/dashboard">Dashboard</a>
      </nv-sidebarnavitem>
      <nv-sidebarnavitem icon="user">
        <a href="/profile">Profile</a>
      </nv-sidebarnavitem>
    </nv-sidebargroup>
  </nv-sidebarcontent>
</nv-sidebar>

Collapsible Sidebar

html<nv-sidebar type="collapsible" open>
  <nv-sidebarlogo label="My App"></nv-sidebarlogo>

  <nv-sidebarcontent>
    <nv-sidebargroup label="Main">
      <nv-sidebarnavitem icon="home">
        <a href="/dashboard">Dashboard</a>
      </nv-sidebarnavitem>
    </nv-sidebargroup>
  </nv-sidebarcontent>
</nv-sidebar>

Complete Example

html<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Nova Sidebar Example</title>
</head>
<body>
  <div class="flex relative max-w-screen">
    <nv-sidebar
      type="collapsible"
      open
      active-path="/dashboard"
      notification-intention="brand"
      notification-emphasis="high"
    >
      <nv-sidebarlogo label="nova Web Components"></nv-sidebarlogo>

      <nv-sidebarcontent>
        <nv-sidebargroup label="Main">
          <nv-sidebarnavitem icon="home">
            <a href="/dashboard">Dashboard</a>
          </nv-sidebarnavitem>

          <nv-sidebarnavitem icon="chart-bar" collapsible>
            <span>Analytics</span>
            <nv-sidebarnavsubitem>
              <a href="/analytics/reports">Reports</a>
            </nv-sidebarnavsubitem>
            <nv-sidebarnavsubitem>
              <a href="/analytics/metrics">Metrics</a>
            </nv-sidebarnavsubitem>
          </nv-sidebarnavitem>

          <nv-sidebarnavitem icon="settings" collapsible notification-count="5">
            <span>Settings</span>
            <nv-sidebarnavsubitem>
              <a href="/settings/profile">Profile</a>
            </nv-sidebarnavsubitem>
            <nv-sidebarnavsubitem>
              <a href="/settings/security">Security</a>
            </nv-sidebarnavsubitem>
          </nv-sidebarnavitem>
        </nv-sidebargroup>

        <nv-sidebardivider></nv-sidebardivider>

        <nv-sidebargroup label="Other">
          <nv-sidebarnavitem icon="user" notification-count="12">
            <a href="/users">Users</a>
          </nv-sidebarnavitem>
        </nv-sidebargroup>
      </nv-sidebarcontent>

      <nv-sidebarfooter>
        <nv-sidebarnavitem icon="bell" notification-count="170">
          <a href="/notifications">Notifications</a>
        </nv-sidebarnavitem>
      </nv-sidebarfooter>
    </nv-sidebar>

    <main class="flex-1 min-w-0 p-4">
      <h1>Main Content</h1>
      <p>This is the main content area.</p>
    </main>
  </div>

  <script>
    // JavaScript for dynamic behavior
    const sidebar = document.querySelector('nv-sidebar');

    // Listen to open/close events
    sidebar.addEventListener('openChanged', (event) => {
      console.log('Sidebar open state:', event.detail);
    });

    // Programmatically control sidebar
    function toggleSidebar() {
      sidebar.open = !sidebar.open;
    }

    // Update active path based on current URL
    function updateActivePath() {
      sidebar.activePath = window.location.pathname;
    }

    // Listen to navigation changes (if using a router)
    window.addEventListener('popstate', updateActivePath);
    updateActivePath(); // Initialize
  </script>
</body>
</html>

Component Structure

nv-sidebar

The main container element with the following attributes:

AttributeTypeDefaultDescription
type'persistent' | 'collapsible''persistent'Sidebar behavior type
openbooleantrueControls open/closed state (collapsible only)
active-pathstringundefinedCurrent active path for automatic highlighting
notification-intention'neutral' | 'brand''brand'Default notification badge intention
notification-emphasis'high' | 'low''high'Default notification badge emphasis

Events:

  • openChanged: Fired when sidebar open state changes

nv-sidebarlogo

Displays the application logo/brand.

AttributeTypeDefaultDescription
labelstringundefinedLogo text label
logostringundefinedURL or path for the logo image
collapsed-logostringundefinedURL or path for the collapsed state logo

nv-sidebarheader

Optional header section below the logo.

nv-sidebarcontent

Container for navigation groups and dividers.

nv-sidebargroup

Groups related navigation items.

AttributeTypeDefaultDescription
labelstringundefinedGroup title

nv-sidebarnavitem

Individual navigation item with optional sub-items.

AttributeTypeDefaultDescription
iconIconNameundefinedIcon name from Nova icon set
collapsiblebooleanfalseMakes item expandable with sub-items
openbooleanfalseControls open/closed state of collapsible item
notification-countnumberundefinedNumber to display in notification badge
activebooleanfalseForces active state

nv-sidebarnavsubitem

Sub-navigation item (child of nv-sidebarnavitem).

nv-sidebardivider

Visual separator between groups.

nv-sidebarfooter

Container for footer navigation items.

JavaScript API

Properties

javascriptconst sidebar = document.querySelector('nv-sidebar');

// Get/set open state
console.log(sidebar.open); // true
sidebar.open = false;

// Get/set active path
sidebar.activePath = '/dashboard';

// Get/set notification settings
sidebar.notificationIntention = 'neutral';
sidebar.notificationEmphasis = 'low';

Events

javascriptconst sidebar = document.querySelector('nv-sidebar');

// Listen to open/close changes
sidebar.addEventListener('openChanged', (event) => {
  console.log('Sidebar is now:', event.detail ? 'open' : 'closed');
});

// Listen to navigation item clicks
const navItems = document.querySelectorAll('nv-sidebarnavitem');
navItems.forEach(item => {
  item.addEventListener('click', (event) => {
    console.log('Navigation item clicked:', event.target);
  });
});

Advanced Usage

Dynamic Content Loading

html<nv-sidebar id="main-sidebar" type="collapsible" open>
  <nv-sidebarlogo label="Dynamic App"></nv-sidebarlogo>
  <nv-sidebarcontent id="sidebar-content">
    <!-- Content will be loaded dynamically -->
  </nv-sidebarcontent>
</nv-sidebar>

<script>
async function loadNavigation() {
  try {
    const response = await fetch('/api/navigation');
    const navigationData = await response.json();

    const content = document.getElementById('sidebar-content');

    navigationData.groups.forEach(group => {
      const groupEl = document.createElement('nv-sidebargroup');
      groupEl.setAttribute('label', group.label);

      group.items.forEach(item => {
        const itemEl = document.createElement('nv-sidebarnavitem');
        itemEl.setAttribute('icon', item.icon);

        if (item.notifications) {
          itemEl.setAttribute('notification-count', item.notifications);
        }

        if (item.children) {
          itemEl.setAttribute('collapsible', 'true');
          itemEl.innerHTML = `<span>${item.label}</span>`;

          item.children.forEach(child => {
            const subItemEl = document.createElement('nv-sidebarnavsubitem');
            subItemEl.innerHTML = `<a href="${child.path}">${child.label}</a>`;
            itemEl.appendChild(subItemEl);
          });
        } else {
          itemEl.innerHTML = `<a href="${item.path}">${item.label}</a>`;
        }

        groupEl.appendChild(itemEl);
      });

      content.appendChild(groupEl);
    });

  } catch (error) {
    console.error('Failed to load navigation:', error);
  }
}

loadNavigation();
</script>

Router Integration

javascript// Simple SPA router integration
class SimpleRouter {
  constructor(sidebar) {
    this.sidebar = sidebar;
    this.routes = {};
    this.currentPath = window.location.pathname;

    // Listen to browser navigation
    window.addEventListener('popstate', () => {
      this.updateActivePath();
    });

    // Intercept link clicks
    document.addEventListener('click', (event) => {
      if (event.target.matches('a[href]')) {
        event.preventDefault();
        const href = event.target.getAttribute('href');
        this.navigate(href);
      }
    });

    this.updateActivePath();
  }

  addRoute(path, handler) {
    this.routes[path] = handler;
  }

  navigate(path) {
    window.history.pushState(null, '', path);
    this.updateActivePath();
    this.handleRoute(path);
  }

  updateActivePath() {
    this.currentPath = window.location.pathname;
    this.sidebar.activePath = this.currentPath;
  }

  handleRoute(path) {
    const handler = this.routes[path];
    if (handler) {
      handler();
    }
  }
}

// Usage
const sidebar = document.querySelector('nv-sidebar');
const router = new SimpleRouter(sidebar);

router.addRoute('/dashboard', () => {
  // Load dashboard content
  console.log('Loading dashboard...');
});

router.addRoute('/users', () => {
  // Load users content
  console.log('Loading users...');
});

Active State Management

javascriptclass ActiveStateManager {
  constructor(sidebar) {
    this.sidebar = sidebar;
    this.activeRules = [];

    // Update active state on navigation
    window.addEventListener('popstate', () => this.updateActiveStates());
    this.updateActiveStates();
  }

  addActiveRule(selector, pathPattern) {
    this.activeRules.push({ selector, pathPattern });
  }

  updateActiveStates() {
    const currentPath = window.location.pathname;

    // Reset all active states
    document.querySelectorAll('nv-sidebarnavitem').forEach(item => {
      item.removeAttribute('active');
    });

    // Apply custom rules
    this.activeRules.forEach(rule => {
      if (currentPath.match(rule.pathPattern)) {
        const element = document.querySelector(rule.selector);
        if (element) {
          element.setAttribute('active', 'true');
        }
      }
    });
  }
}

// Usage
const activeManager = new ActiveStateManager(sidebar);

// Projects section active for all /projects/* paths
activeManager.addActiveRule('nv-sidebarnavitem[icon="folder"]', /^\/projects/);

// Users section active for /users and /user/* paths
activeManager.addActiveRule('nv-sidebarnavitem[icon="user"]', /^\/users/);

State Management

Local Storage Integration

javascriptclass SidebarStateManager {
  constructor(sidebar) {
    this.sidebar = sidebar;
    this.storageKey = 'nova-sidebar-state';

    // Load saved state
    this.loadState();

    // Save state on changes
    sidebar.addEventListener('openChanged', () => this.saveState());
  }

  saveState() {
    const state = {
      open: this.sidebar.open,
      timestamp: Date.now()
    };
    localStorage.setItem(this.storageKey, JSON.stringify(state));
  }

  loadState() {
    try {
      const saved = localStorage.getItem(this.storageKey);
      if (saved) {
        const state = JSON.parse(saved);
        // Only restore if saved within last hour
        if (Date.now() - state.timestamp < 3600000) {
          this.sidebar.open = state.open;
        }
      }
    } catch (error) {
      console.warn('Failed to load sidebar state:', error);
    }
  }

  resetState() {
    localStorage.removeItem(this.storageKey);
    this.sidebar.open = true; // Default state
  }
}

// Usage
const stateManager = new SidebarStateManager(sidebar);

Global State with Custom Events

javascriptclass GlobalSidebarState {
  constructor() {
    this.state = {
      open: true,
      activePath: window.location.pathname
    };

    this.subscribers = [];
    this.init();
  }

  init() {
    // Listen to custom events
    document.addEventListener('sidebar:toggle', () => {
      this.setState({ open: !this.state.open });
    });

    document.addEventListener('sidebar:setPath', (event) => {
      this.setState({ activePath: event.detail });
    });

    // Update DOM elements
    this.updateDOM();
  }

  setState(newState) {
    this.state = { ...this.state, ...newState };
    this.updateDOM();
    this.notifySubscribers();
  }

  updateDOM() {
    const sidebar = document.querySelector('nv-sidebar');
    if (sidebar) {
      sidebar.open = this.state.open;
      sidebar.activePath = this.state.activePath;
    }
  }

  subscribe(callback) {
    this.subscribers.push(callback);
    return () => {
      this.subscribers = this.subscribers.filter(sub => sub !== callback);
    };
  }

  notifySubscribers() {
    this.subscribers.forEach(callback => callback(this.state));
  }
}

// Usage
const globalState = new GlobalSidebarState();

// Subscribe to state changes
const unsubscribe = globalState.subscribe((state) => {
  console.log('Sidebar state changed:', state);
});

// Dispatch custom events
document.dispatchEvent(new CustomEvent('sidebar:toggle'));
document.dispatchEvent(new CustomEvent('sidebar:setPath', {
  detail: '/dashboard'
}));

Styling

The sidebar follows Nova's design system and uses CSS variables for consistent theming. To maintain design consistency, override these variables only when integrating with your established design system:

css:root {
  --sidebar-width: 280px;
  --components-sidebar-background: var(--nv-color-surface-primary);
  --components-sidebar-border: var(--nv-color-border-primary);
}

Accessibility

  • Keyboard navigation support (Tab, Enter, Space, Arrow keys)
  • ARIA labels and roles
  • Focus management for collapsible items
  • Screen reader friendly notification counts
  • High contrast mode support

Keyboard Navigation

javascript// Enhanced keyboard navigation
document.addEventListener('keydown', (event) => {
  const sidebar = document.querySelector('nv-sidebar');

  if (event.key === 'b' && event.ctrlKey) {
    // Ctrl+B to toggle sidebar
    event.preventDefault();
    sidebar.open = !sidebar.open;
  }

  if (event.key === 'Escape' && sidebar.open) {
    // Escape to close sidebar on mobile
    if (window.innerWidth < 768) {
      sidebar.open = false;
    }
  }
});

Common Patterns

Single Page Application Layout

html<div class="flex relative max-w-screen">
  <nv-sidebar id="app-sidebar" type="collapsible" open>
    <!-- Sidebar content -->
  </nv-sidebar>

  <main class="flex-1 min-w-0 p-4" id="main-content">
    <!-- Dynamic content loaded here -->
  </main>
</div>

<script>
class SPAApp {
  constructor() {
    this.sidebar = document.getElementById('app-sidebar');
    this.content = document.getElementById('main-content');
    this.routes = {};

    this.init();
  }

  init() {
    // Handle navigation
    document.addEventListener('click', (event) => {
      if (event.target.matches('nv-sidebar a[href]')) {
        event.preventDefault();
        const path = event.target.getAttribute('href');
        this.navigate(path);
      }
    });

    // Handle browser back/forward
    window.addEventListener('popstate', () => {
      this.loadContent(window.location.pathname);
    });

    // Load initial content
    this.loadContent(window.location.pathname);
  }

  addRoute(path, component) {
    this.routes[path] = component;
  }

  navigate(path) {
    window.history.pushState(null, '', path);
    this.loadContent(path);
  }

  async loadContent(path) {
    const component = this.routes[path];
    if (component) {
      this.content.innerHTML = await component.render();
      this.sidebar.activePath = path;
    }
  }
}

// Usage
const app = new SPAApp();

app.addRoute('/dashboard', {
  render: () => '<h1>Dashboard</h1><p>Welcome to your dashboard!</p>'
});

app.addRoute('/users', {
  render: () => '<h1>Users</h1><p>Manage your users here.</p>'
});
</script>

Responsive Design

Note: Responsive design features are not currently implemented in the nv-sidebar component. Mobile-first responsive behavior will be considered for inclusion in a future v2 release, potentially including:

  • Automatic mobile/desktop mode switching
  • Touch-friendly interactions
  • Collapsible behavior based on screen size
  • Overlay modes for mobile devices

For now, implement responsive behavior at the application level using CSS media queries and vanilla JavaScript.

Performance Considerations

Lazy Loading

javascript// Lazy load sidebar content
const sidebarContent = document.querySelector('nv-sidebarcontent');
const observer = new IntersectionObserver((entries) => {
  entries.forEach(entry => {
    if (entry.isIntersecting) {
      loadSidebarContent();
      observer.disconnect();
    }
  });
});

observer.observe(sidebarContent);

async function loadSidebarContent() {
  // Load content dynamically
  const response = await fetch('/api/sidebar-content');
  const html = await response.text();
  sidebarContent.innerHTML = html;
}

Virtual Scrolling for Large Menus

javascriptclass VirtualSidebar {
  constructor(container, items) {
    this.container = container;
    this.items = items;
    this.visibleItems = 20;
    this.scrollTop = 0;

    this.init();
  }

  init() {
    this.container.addEventListener('scroll', () => {
      this.scrollTop = this.container.scrollTop;
      this.render();
    });

    this.render();
  }

  render() {
    const start = Math.floor(this.scrollTop / 40); // Item height
    const end = Math.min(start + this.visibleItems, this.items.length);

    const visibleItems = this.items.slice(start, end);
    const offsetY = start * 40;

    this.container.innerHTML = `
      <div style="height: ${this.items.length * 40}px; position: relative;">
        <div style="transform: translateY(${offsetY}px);">
          ${visibleItems.map(item => `<div class="sidebar-item">${item.label}</div>`).join('')}
        </div>
      </div>
    `;
  }
}

This approach ensures optimal performance even with hundreds of navigation items.