# NavigationGroup

## Introduction

NavigationGroup is an expandable container for organizing related navigation items in a sidebar. Built on Joy UI's Accordion component, it provides a collapsible section that can hold NavigationItems or nested Navigator components. NavigationGroup creates hierarchical navigation structures where users can expand and collapse sections to access nested items.

```text
// Unable to derive source for Default
```

| Field                        | Description | Default |
| ---------------------------- | ----------- | ------- |
| Controls resolved at runtime | —           | —       |

## Usage

```tsx
import { NavigationGroup, NavigationItem } from '@ceed/cds';

function Sidebar() {
  return (
    <NavigationGroup
      title="User Management"
      startDecorator={<PeopleIcon />}
      defaultExpanded={true}
    >
      <NavigationItem id="users" level={1}>All Users</NavigationItem>
      <NavigationItem id="roles" level={1}>Roles</NavigationItem>
      <NavigationItem id="permissions" level={1}>Permissions</NavigationItem>
    </NavigationGroup>
  );
}
```

## Examples

### Default

Basic navigation group with a title and content.

```text
// Unable to derive source for Default
```

### Nesting Levels

NavigationGroup supports different indentation levels for nested hierarchies.

```text
// Unable to derive source for Level1
```

```text
// Unable to derive source for Level2
```

### With Start Decorator

Add an icon before the group title.

```text
// Unable to derive source for WithStartDecorator
```

### Levels with Icons

Icons work at any nesting level.

```text
// Unable to derive source for Level1WithStartDecorator
```

```text
// Unable to derive source for Level2WithStartDecorator
```

## When to Use

### ✅ Good Use Cases

- **Collapsible sidebar sections**: Organize navigation into expandable categories
- **Deep navigation hierarchies**: Group related items under collapsible headers
- **Admin interfaces**: Organize modules and sub-modules
- **Settings organization**: Group related settings under categories
- **File system navigation**: Folders containing nested items

### ❌ When Not to Use

- **Flat navigation**: When all items are at the same level
- **Tab-like navigation**: Use Tabs for switching between views
- **Simple menus**: For 5 or fewer items, consider flat NavigationItems
- **Modal dialogs**: Use proper modal patterns instead
- **Accordion content**: For non-navigation accordions, use Accordion directly

## Common Use Cases

### Admin Module Navigation

```tsx
function AdminNavigation() {
  return (
    <>
      <NavigationGroup
        title="User Management"
        startDecorator={<PeopleIcon />}
        defaultExpanded={true}
      >
        <NavigationItem id="users" level={1}>
          All Users
        </NavigationItem>
        <NavigationItem id="invite" level={1}>
          Invite User
        </NavigationItem>
        <NavigationItem id="roles" level={1}>
          Roles & Permissions
        </NavigationItem>
      </NavigationGroup>

      <NavigationGroup
        title="Content"
        startDecorator={<ArticleIcon />}
      >
        <NavigationItem id="posts" level={1}>
          Posts
        </NavigationItem>
        <NavigationItem id="categories" level={1}>
          Categories
        </NavigationItem>
        <NavigationItem id="media" level={1}>
          Media Library
        </NavigationItem>
      </NavigationGroup>

      <NavigationGroup
        title="Settings"
        startDecorator={<SettingsIcon />}
      >
        <NavigationItem id="general" level={1}>
          General
        </NavigationItem>
        <NavigationItem id="security" level={1}>
          Security
        </NavigationItem>
        <NavigationItem id="integrations" level={1}>
          Integrations
        </NavigationItem>
      </NavigationGroup>
    </>
  );
}
```

### Nested Groups

```tsx
function NestedNavigation() {
  return (
    <NavigationGroup
      title="E-commerce"
      startDecorator={<ShoppingCartIcon />}
      defaultExpanded={true}
    >
      <NavigationItem id="dashboard" level={1}>
        Dashboard
      </NavigationItem>

      <NavigationGroup
        title="Products"
        level={1}
        defaultExpanded={true}
      >
        <NavigationItem id="all-products" level={2}>
          All Products
        </NavigationItem>
        <NavigationItem id="add-product" level={2}>
          Add Product
        </NavigationItem>
        <NavigationItem id="categories" level={2}>
          Categories
        </NavigationItem>
      </NavigationGroup>

      <NavigationGroup
        title="Orders"
        level={1}
      >
        <NavigationItem id="all-orders" level={2}>
          All Orders
        </NavigationItem>
        <NavigationItem id="pending" level={2}>
          Pending
        </NavigationItem>
        <NavigationItem id="completed" level={2}>
          Completed
        </NavigationItem>
      </NavigationGroup>
    </NavigationGroup>
  );
}
```

### Documentation Sidebar

```tsx
function DocsSidebar({ sections, currentPath }) {
  return (
    <nav>
      {sections.map((section) => (
        <NavigationGroup
          key={section.id}
          title={section.title}
          startDecorator={<BookIcon />}
          defaultExpanded={currentPath.startsWith(section.basePath)}
        >
          {section.pages.map((page) => (
            <NavigationItem
              key={page.id}
              id={page.id}
              level={1}
              selected={currentPath === page.path}
              onClick={() => navigate(page.path)}
            >
              {page.title}
            </NavigationItem>
          ))}
        </NavigationGroup>
      ))}
    </nav>
  );
}
```

## Props and Customization

### Key Props

| Prop              | Type                  | Default | Description                   |
| ----------------- | --------------------- | ------- | ----------------------------- |
| `title`           | `string \| ReactNode` | -       | Group header title            |
| `children`        | `ReactNode`           | -       | Content shown when expanded   |
| `startDecorator`  | `ReactNode`           | -       | Icon before the title         |
| `level`           | `number`              | `0`     | Nesting level for indentation |
| `defaultExpanded` | `boolean`             | `false` | Initial expanded state        |

### Accordion Props

NavigationGroup extends Joy UI's Accordion, so you can use additional Accordion props:

```tsx
<NavigationGroup
  title="Settings"
  expanded={isExpanded}
  onChange={(event, expanded) => setIsExpanded(expanded)}
>
  {/* Content */}
</NavigationGroup>
```

### Custom Styling

```tsx
<NavigationGroup
  title="Custom Section"
  sx={{
    '& .NavigationGroup-Summary': {
      fontWeight: 600,
    },
    '& .NavigationGroup-Details': {
      backgroundColor: 'background.level2',
    },
  }}
>
  {/* Content */}
</NavigationGroup>
```

## Accessibility

NavigationGroup leverages Joy UI's Accordion accessibility features:

### ARIA Attributes

- `role="button"` on the expandable header
- `aria-expanded` indicates the current state
- `aria-controls` links header to content
- Content region has proper `role="region"`

### Keyboard Navigation

- **Tab**: Focus the group header
- **Enter/Space**: Toggle expanded state
- **Arrow Down**: Move to first item when expanded
- **Arrow Up**: Move to header from first item

### Screen Reader Support

```tsx
// Expansion state is announced
<NavigationGroup title="Settings" defaultExpanded={true}>
  {/* "Settings, expanded, button" */}
</NavigationGroup>
```

## Best Practices

### ✅ Do

1. **Use descriptive titles**: Group titles should clearly indicate the content category

```tsx
// ✅ Good: Descriptive title
<NavigationGroup title="User Management">

// ❌ Bad: Vague title
<NavigationGroup title="More">
```

2. **Expand active sections**: Auto-expand groups containing the current page

```tsx
<NavigationGroup
  title="Products"
  defaultExpanded={currentPath.startsWith('/products')}
>
```

3. **Limit group children**: Keep 3-7 items per group for easy scanning

4. **Use consistent icons**: If using icons, apply them to all groups

### ❌ Don't

1. **Don't over-nest**: Maximum 2-3 levels of nesting

```tsx
// ❌ Bad: Too deep
<NavigationGroup>
  <NavigationGroup level={1}>
    <NavigationGroup level={2}>
      <NavigationGroup level={3}>  {/* Too deep */}
```

2. **Don't mix patterns**: Be consistent with structure across all groups

3. **Don't put actions in groups**: Navigation only, not buttons or forms

4. **Don't hide critical navigation**: Important items should be easily discoverable

## Performance Considerations

### Lazy Load Content

For groups with heavy content, consider lazy loading:

```tsx
function LazyNavigationGroup({ title, loadContent }) {
  const [expanded, setExpanded] = useState(false);
  const [content, setContent] = useState(null);

  const handleChange = async (event, isExpanded) => {
    setExpanded(isExpanded);
    if (isExpanded && !content) {
      const loadedContent = await loadContent();
      setContent(loadedContent);
    }
  };

  return (
    <NavigationGroup
      title={title}
      expanded={expanded}
      onChange={handleChange}
    >
      {content || <Skeleton />}
    </NavigationGroup>
  );
}
```

### Controlled Expansion

For complex navigation, control expansion at the parent level:

```tsx
function SidebarNavigation() {
  const [expandedGroups, setExpandedGroups] = useState(['products']);

  const handleGroupChange = (groupId) => (event, isExpanded) => {
    setExpandedGroups((prev) =>
      isExpanded
        ? [...prev, groupId]
        : prev.filter((id) => id !== groupId)
    );
  };

  return (
    <>
      <NavigationGroup
        title="Products"
        expanded={expandedGroups.includes('products')}
        onChange={handleGroupChange('products')}
      >
        {/* Items */}
      </NavigationGroup>
      <NavigationGroup
        title="Orders"
        expanded={expandedGroups.includes('orders')}
        onChange={handleGroupChange('orders')}
      >
        {/* Items */}
      </NavigationGroup>
    </>
  );
}
```

NavigationGroup provides the structure for organizing hierarchical sidebar navigation. Combine it with NavigationItem for individual links, or use it within Navigator for a complete navigation solution.
