# Side navigation

Provides a structural view of a services's navigation, allowing users to easily navigate sections and pages within the service.

## Key UX concepts

### Navigation structure

Organize the side navigation according to the information architecture (IA) of your service, the primary use case of the user, and the user's mental model of involved resources. Within the [side navigation](/components/side-navigation/index.html.md) component are four possible types of information architecture, with various hierarchies. [Breadcrumbs](/components/breadcrumb-group/index.html.md) displayed on each page should reflect the same information architecture as used in the side navigation.

**Note** : A use case not currently supported by this pattern is services organized as service hubs. Typically, these types of services are organized by top-level projects.

### Collapsed vs closed states

In its **expanded state** , the side navigation displays all text and section labels in full. The side navigation supports two alternatives to the expanded state for products where content density is a concern:

- **Closed**   : In this state, the navigation drawer is hidden completely out of view.
- **Collapsed:**   In this state, the navigation reduces to a narrow navigation rail of icons, text labels are surfaced as tooltips. Because labels are hidden by default in the collapsed state, the rail depends on icons that users can recognize or learn easily.

## Simple

The pages are hierarchically all on one level, listed one after another. Dividers may be used to provide additional organization between these links when different sets are fundamentally not related to each other. For example, a set of pages that manage the resources provided by the service, versus a set of pages that provide additional information regarding the general service for example, notifications or additional documentation.

##### Standard navigation

## Simple

- [Dashboard](about:blank/index.html.md)
- [Storage](about:blank/index.html.md)
- [Metrics](about:blank/index.html.md)

- [Notifications](about:blank/index.html.md)
- [Support](https://example.com/)

##### Collapsible navigation

## Simple

- [Dashboard](about:blank/index.html.md)
- [Storage](about:blank/index.html.md)
- [Metrics](about:blank/index.html.md)

- [Notifications](about:blank/index.html.md)
- [Support](https://example.com/)

- [Dashboard](about:blank/index.html.md)
- [Storage](about:blank/index.html.md)
- [Metrics](about:blank/index.html.md)

- [Notifications](about:blank/index.html.md)
- [Support](https://example.com/)

##### Example IA

```side-navigation-pattern-simple.tsx
import React, { useState } from 'react';
import Icon from '@cloudscape-design/components/icon';
import SideNavigation, { SideNavigationProps } from '@cloudscape-design/components/side-navigation';
import Box from '@cloudscape-design/components/box';
import SpaceBetween from '@cloudscape-design/components/space-between';
import {
  colorBackgroundCellShaded,
  colorBackgroundStatusInfo,
  colorBackgroundStatusSuccess,
  colorBackgroundStatusWarning,
  colorTextBodyDefault,
  colorTextStatusInfo,
  colorTextStatusSuccess,
  colorTextStatusWarning,
  fontFamilyBase,
} from '@cloudscape-design/design-tokens/index.js';

/**
 * IATreeVisualizer renders an SVG-based node-link tree diagram showing the
 * information architecture of a SideNavigation item set.
 *
 * - Plain links, and items inside a `section`/`section-group`, are flattened
 *   to a single depth: they all branch directly off the main trunk. A
 *   `section`/`section-group` has no href (it's just a label), so it does not
 *   get a node — instead its title is drawn as a text label beside the trunk,
 *   with extra vertical spacing inserted before its first child to set the
 *   group apart.
 * - `link-group` / `expandable-link-group` items ARE real nodes (they have
 *   their own href), so they keep their nested children on a genuine
 *   sub-trunk/sub-branch one depth deeper.
 * - Divider items are silently skipped.
 *
 * Nodes are colored by depth (root = "A", depth 1 = "B", depth 2 = "C", ...),
 * not by sibling group, so every node at the same indentation level shares a
 * color. Within a sibling group, letters are shown only when at least one
 * member of that group is itself expandable (has nested children) — e.g. in
 * `expandable-link-groups`, "Projects"/"Groups" are lettered but plain-link
 * siblings like "Home" render blank, since the letter is meant to signal
 * "this expands" rather than merely "this is at depth N". When no sibling in
 * a group is expandable (e.g. `simple`, `organized-with-sections`), every
 * node in that group keeps its letter.
 *
 * Color tokens used (all from the public design-tokens surface):
 * - Root node (depth 0): colorBackgroundCellShaded (neutral grey fill) + colorBorderInputDefault (border)
 * - Depth 1: colorBackgroundStatusInfo (light blue fill) + colorBorderStatusInfo (blue stroke)
 * - Depth 2: colorBackgroundStatusSuccess (light green fill) + colorBorderStatusSuccess (green stroke)
 * - Depth 3+: colorBackgroundStatusWarning (light amber fill) + colorBorderStatusWarning (amber stroke), repeating
 */
const CONNECTOR_STROKE_WIDTH = 2;
const NODE_STROKE_WIDTH = 1;

const DEPTH_COLORS = [
  { fill: colorBackgroundCellShaded, stroke: colorTextBodyDefault }, // depth 0 (root)
  { fill: colorBackgroundStatusInfo, stroke: colorTextStatusInfo }, // depth 1
  { fill: colorBackgroundStatusSuccess, stroke: colorTextStatusSuccess }, // depth 2
  { fill: colorBackgroundStatusWarning, stroke: colorTextStatusWarning }, // depth 3+
];

function depthColor(depth: number) {
  return DEPTH_COLORS[Math.min(depth, DEPTH_COLORS.length - 1)];
}

function depthLetter(depth: number) {
  return String.fromCharCode('A'.charCodeAt(0) + depth);
}

// Items whose header is a label only (no href) — their children flatten to
// the parent's depth instead of nesting on a sub-branch.
function isLabelOnlyGroup(
  item: SideNavigationProps.Item
): item is SideNavigationProps.Section | SideNavigationProps.SectionGroup {
  return item.type === 'section' || item.type === 'section-group';
}

// Items that are real nodes (have an href) whose children genuinely nest one
// depth deeper on their own sub-branch.
function getNestedChildren(item: SideNavigationProps.Item): ReadonlyArray<SideNavigationProps.Item> | null {
  switch (item.type) {
    case 'link-group':
    case 'expandable-link-group':
      return item.items;
    default:
      return null;
  }
}

function groupTitle(item: SideNavigationProps.Section | SideNavigationProps.SectionGroup): string {
  return item.type === 'section' ? item.text : item.title;
}

// A flat row in the tree: either a real node (with optional nested children)
// or a label-only group boundary that introduces extra spacing before its
// (already-flattened) children. `dividerBefore` marks a row that was
// immediately preceded by a real `divider` item in the source data — this is
// the ONLY thing that produces a dashed trunk segment (dashes represent an
// actual divider, not a generic "list is long" cue). `href` identifies the
// underlying nav item so callers can annotate a specific node (e.g. via
// `moreResourcesHrefs`) without the visualizer needing item identity beyond href.
// `nestingDepth` counts how many label-only groups (section / section-group)
// this row is nested inside BEYOND the first one — e.g. 0 for a row directly
// under the top-level items or under a single (non-nested) section, 1 for a
// section nested inside another section-group (like "Security" inside
// "Reports and analytics"). This only shifts the row's x position for visual
// indentation; the row still connects directly to the main trunk, since it's
// still technically a sibling of the outer group's other rows, not a child.
interface TreeRow {
  isNode: boolean;
  label: string | null;
  extraGapBefore: boolean;
  dividerBefore: boolean;
  href: string | undefined;
  nestingDepth: number;
  nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
}

// Flattens a list of items to depth-1 tree rows. Label-only groups (section /
// section-group) contribute no node of their own — their children are
// recursively flattened into the same row list, with the group's title
// attached to the first child row and an extra gap inserted before it.
// Divider items contribute no node either, but mark the following row as
// `dividerBefore` so it renders with a dashed (not solid) trunk segment above it.
function buildRows(items: ReadonlyArray<SideNavigationProps.Item>, nestingDepth = 0, isInsideGroup = false): TreeRow[] {
  const rows: TreeRow[] = [];
  let pendingDivider = false;
  items.forEach(item => {
    if (item.type === 'divider') {
      pendingDivider = true;
      return;
    }
    if (isLabelOnlyGroup(item)) {
      // A label-only group nested INSIDE another label-only group indents
      // one level deeper. A top-level label-only group (nestingDepth === 0
      // here, i.e. not itself inside another group) stays unindented, same
      // as its non-nested siblings — pass nestingDepth + 1 only when this
      // group is being flattened from within an enclosing group's items.
      const childNestingDepth = isInsideGroup ? nestingDepth + 1 : nestingDepth;
      const childRows = buildRows(item.items, childNestingDepth, true);
      if (childRows.length > 0) {
        childRows[0] = {
          ...childRows[0],
          label: groupTitle(item),
          extraGapBefore: true,
          dividerBefore: pendingDivider,
        };
        pendingDivider = false;
      }
      rows.push(...childRows);
      return;
    }
    rows.push({
      isNode: true,
      label: null,
      extraGapBefore: false,
      dividerBefore: pendingDivider,
      href: 'href' in item ? item.href : undefined,
      nestingDepth,
      nestedChildren: getNestedChildren(item),
    });
    pendingDivider = false;
  });
  return rows;
}

function IATreeVisualizer({
  items,
  moreResourcesHrefs,
}: {
  items: SideNavigationProps.Item[];
  /**
   * hrefs of expandable-link-group / link-group items that have more
   * resources than are shown as children — rendered with a trailing stack of
   * dashed "ghost" boxes and an "Existing resources" label, e.g. to indicate
   * a group backed by a large/unbounded resource list.
   */
  moreResourcesHrefs?: ReadonlyArray<string>;
}) {
  const rows = buildRows(items);

  // A node is only lettered when at least one sibling in its group is itself
  // an expandable node (has nested children) — e.g. in expandable-link-groups,
  // "Projects"/"Groups" are lettered but plain-link siblings like "Home" are
  // blank. When no sibling in the group is expandable (simple, sectioned
  // examples), every node in that group keeps its letter.
  const topLevelHasExpandableSibling = rows.some(row => !!row.nestedChildren && row.nestedChildren.length > 0);

  // Layout constants (condensed)
  const nodeSize = 24;
  const nodeRadius = 6;
  const rowSpacing = 36;
  const groupGap = 24; // extra vertical space inserted before a label-only group's first child
  const edgeMargin = NODE_STROKE_WIDTH; // breathing room on every edge so stroked node borders never get clipped by the viewBox
  const trunkX = edgeMargin + nodeSize / 2;
  const branchOffset = 36;
  const nestedBranchOffset = 36;
  const rootGap = 28; // vertical gap from the root node down to the first branch point (larger than a regular row gap)
  const fontSize = 12;

  interface NodePosition {
    x: number;
    y: number;
    depth: number;
    parentY: number;
  }

  const positions: NodePosition[] = [];
  const rowPositions: {
    y: number;
    label: string | null;
    dividerBefore: boolean;
    href: string | undefined;
    x: number;
    nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
  }[] = [];

  const rootY = edgeMargin;
  let currentY = rootY + nodeSize + rootGap;
  let maxDepth = 1;

  rows.forEach(row => {
    // A divider and a label-only group boundary both introduce the same
    // extra vertical breathing room before the row that follows them.
    if (row.extraGapBefore || row.dividerBefore) {
      currentY += groupGap;
    }
    const y = currentY;
    // A section/section-group nested inside another section/section-group
    // (e.g. "Security" inside "Reports and analytics") indents visually —
    // but still connects directly to the main trunk below, since it's still
    // a sibling of the outer group's other rows, not a child of them.
    const x = branchOffset + row.nestingDepth * nestedBranchOffset;
    rowPositions.push({
      y,
      label: row.label,
      dividerBefore: row.dividerBefore,
      href: row.href,
      x,
      nestedChildren: row.nestedChildren,
    });
    positions.push({ x, y, depth: 1, parentY: y });
    currentY += rowSpacing;
    maxDepth = Math.max(maxDepth, 1 + row.nestingDepth);

    if (row.nestedChildren && row.nestedChildren.length > 0) {
      maxDepth = Math.max(maxDepth, 2 + row.nestingDepth);
      row.nestedChildren
        .filter(child => child.type !== 'divider')
        .forEach(() => {
          positions.push({ x: x + nestedBranchOffset, y: currentY, depth: 2, parentY: y });
          currentY += rowSpacing;
        });
    }
  });

  // The trunk ends at the vertical center of the last top-level row — not at
  // the running layout cursor, which may have advanced past it (e.g. through
  // trailing nested-child rows or a group gap) and no longer reflects that point.
  const lastRowY = rowPositions.length > 0 ? rowPositions[rowPositions.length - 1].y : rootY + nodeSize;
  const trunkEndY = lastRowY + nodeSize / 2;
  // contentBottomY is the center of the last positioned node (top-level or
  // nested child, whichever comes last) — the drawing must extend past its
  // full bottom edge (+ nodeSize / 2), not just its center.
  const contentBottomY = currentY - rowSpacing / 2;

  // "More resources" ghost-box stack sizing (peeks out horizontally behind its
  // real node — see rendering below). Computed here so both svgHeight and
  // svgWidth can account for the extra space it needs.
  const hasMoreResourcesRow = rowPositions.some(row => row.href && moreResourcesHrefs?.includes(row.href));
  const ghostBoxCount = 3;
  const ghostBoxOffset = 10; // horizontal stagger between successive stacked ghost boxes, peeking out behind the real node
  const ghostStackExtent = ghostBoxCount * ghostBoxOffset;
  const ghostToLabelGap = 16; // gap between the rightmost ghost box's edge and its connector/label
  const moreResourcesLabel = 'Existing resources';
  const moreResourcesLabelCharWidth = fontSize * 0.62; // rough monospace-agnostic estimate, just for layout sizing
  const moreResourcesLabelExtent = ghostToLabelGap + 4 + moreResourcesLabel.length * moreResourcesLabelCharWidth;

  const svgHeight = Math.max(trunkEndY, contentBottomY) + nodeSize / 2 + edgeMargin;

  // Compute the drawing width from actual content: branchOffset/nestedBranchOffset
  // are already absolute x-coordinates (they include the left edgeMargin via
  // trunkX), so the rightmost content edge is the deepest branch column's node
  // plus a matching right margin — unless a "more resources" ghost stack (see
  // below) peeks out further right from behind its node, in which case that
  // extends the rightmost edge instead.
  const rightmostBranchX = branchOffset + (maxDepth - 1) * nestedBranchOffset;
  const svgWidth =
    Math.max(
      rightmostBranchX + nodeSize,
      hasMoreResourcesRow ? branchOffset + nodeSize + ghostStackExtent + moreResourcesLabelExtent : 0
    ) + edgeMargin;

  // Curved connector path from trunk to node (S-curve bezier)
  function connectorPath(fromX: number, fromY: number, toX: number, toY: number, stroke: string) {
    const midX = fromX + (toX - fromX) * 0.4;
    const d = `M ${fromX} ${fromY} C ${midX} ${fromY}, ${midX} ${toY}, ${toX} ${toY}`;
    return (
      <path
        key={`conn-${fromX}-${fromY}-${toX}-${toY}`}
        d={d}
        fill="none"
        stroke={stroke}
        strokeWidth={CONNECTOR_STROKE_WIDTH}
        strokeLinecap="round"
      />
    );
  }

  // Only nodes that actually expand into children are lettered by depth —
  // a sibling at the same depth with no nested children (e.g. a plain link
  // next to an expandable-link-group) renders as a blank node so the letter
  // reads as "this expands" rather than just "this is at depth N".
  function node(x: number, y: number, depth: number, key: string, hasChildren: boolean) {
    const colors = depthColor(depth);
    return (
      <g key={key}>
        <rect
          x={x}
          y={y}
          width={nodeSize}
          height={nodeSize}
          rx={nodeRadius}
          ry={nodeRadius}
          fill={colors.fill}
          stroke={colors.stroke}
          strokeWidth={NODE_STROKE_WIDTH}
        />
        {hasChildren && (
          <text
            x={x + nodeSize / 2}
            y={y + nodeSize / 2}
            textAnchor="middle"
            dominantBaseline="central"
            fontSize={fontSize}
            fill={colors.stroke}
          >
            {depthLetter(depth)}
          </text>
        )}
      </g>
    );
  }

  // Trunk segments: split into solid runs, with a dashed run wherever a row
  // is marked `dividerBefore` — dashes represent an actual `divider` item
  // from the source data, spanning the full gap between that row and the one
  // before it (not a generic "list is long" cue).
  const trunkSegments: { y1: number; y2: number; dashed: boolean }[] = [];
  let segmentStartY = rootY + nodeSize;
  rowPositions.forEach((row, idx) => {
    if (row.dividerBefore && idx > 0) {
      const gapStartY = rowPositions[idx - 1].y + nodeSize / 2;
      const gapEndY = row.y + nodeSize / 2;
      trunkSegments.push({ y1: segmentStartY, y2: gapStartY, dashed: false });
      trunkSegments.push({ y1: gapStartY, y2: gapEndY, dashed: true });
      segmentStartY = gapEndY;
    }
  });
  trunkSegments.push({ y1: segmentStartY, y2: trunkEndY, dashed: false });

  return (
    <svg
      width={svgWidth}
      height={svgHeight}
      viewBox={`0 0 ${svgWidth} ${svgHeight}`}
      style={{ display: 'block', fontFamily: fontFamilyBase }}
      aria-hidden="true"
      role="img"
    >
      {/* Root node */}
      {node(trunkX - nodeSize / 2, rootY, 0, 'root-node', true)}

      {/* Main trunk line, with an optional dashed segment spanning one full inter-row gap */}
      {trunkSegments.map((segment, idx) => (
        <line
          key={`trunk-${idx}`}
          x1={trunkX}
          y1={segment.y1}
          x2={trunkX}
          y2={segment.y2}
          stroke={DEPTH_COLORS[1].stroke}
          strokeWidth={CONNECTOR_STROKE_WIDTH}
          strokeLinecap="round"
          strokeDasharray={segment.dashed ? '4 4' : undefined}
        />
      ))}

      {/* Top-level connectors, nodes, and group labels */}
      {rowPositions.map((row, idx) => {
        const nodeY = row.y;
        const nodeCenterY = nodeY + nodeSize / 2;
        const elements: React.ReactNode[] = [];

        // Connector from trunk to top-level node — always originates from the
        // main trunk, even for a nested section/section-group row (indented
        // via row.x), since it's still a sibling of the outer group's other
        // rows, not a child of them.
        elements.push(connectorPath(trunkX, nodeCenterY, row.x, nodeCenterY, DEPTH_COLORS[1].stroke));

        // "More resources" annotation: a stack of dashed ghost boxes peeking
        // out horizontally from behind the real node, for groups whose real
        // children are only a partial view of a larger/unbounded resource
        // list. Pushed BEFORE the real node so — in SVG's painter's-model
        // ordering — the node draws on top and only each ghost box's right
        // edge remains visible, like a stack of cards fanned out sideways.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const ghostColors = depthColor(1);
          for (let i = ghostBoxCount; i >= 1; i--) {
            elements.push(
              <rect
                key={`ghost-${idx}-${i}`}
                x={row.x + i * ghostBoxOffset}
                y={nodeY}
                width={nodeSize}
                height={nodeSize}
                rx={nodeRadius}
                ry={nodeRadius}
                fill={ghostColors.fill}
                stroke={ghostColors.stroke}
                strokeWidth={NODE_STROKE_WIDTH}
                strokeDasharray="3 3"
              />
            );
          }
        }

        // Top-level node — lettered only if this row is itself expandable, or
        // no sibling in this group is expandable (see topLevelHasExpandableSibling).
        const hasNestedChildren = !!(row.nestedChildren && row.nestedChildren.length > 0);
        const tlLettered = hasNestedChildren || !topLevelHasExpandableSibling;
        elements.push(node(row.x, nodeY, 1, `tl-node-${idx}`, tlLettered));

        // Connector + "Existing resources" label trailing the ghost stack,
        // anchored past its rightmost (most-offset) box.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const stackRightX = row.x + ghostBoxCount * ghostBoxOffset + nodeSize;
          const labelLineX = stackRightX + ghostToLabelGap;
          elements.push(
            <line
              key={`ghost-connector-${idx}`}
              x1={stackRightX}
              y1={nodeCenterY}
              x2={labelLineX}
              y2={nodeCenterY}
              stroke={colorTextBodyDefault}
              strokeWidth={1}
            />
          );
          elements.push(
            <text
              key={`ghost-label-${idx}`}
              x={labelLineX + 4}
              y={nodeCenterY}
              dominantBaseline="central"
              fontSize={fontSize}
              fontWeight="bold"
              fill={colorTextBodyDefault}
            >
              {moreResourcesLabel}
            </text>
          );
        }

        // If this node has real nested children (link-group / expandable-link-group), draw sub-trunk and children
        if (row.nestedChildren && row.nestedChildren.length > 0) {
          const colors = depthColor(2);
          const subTrunkX = row.x + nodeSize / 2;
          const childNodes = positions.filter(p => p.depth === 2 && p.parentY === nodeY);
          const subTrunkStartY = nodeY + nodeSize;
          const subTrunkEndY =
            childNodes.length > 0 ? childNodes[childNodes.length - 1].y + nodeSize / 2 : subTrunkStartY;

          elements.push(
            <line
              key={`sub-trunk-${idx}`}
              x1={subTrunkX}
              y1={subTrunkStartY}
              x2={subTrunkX}
              y2={subTrunkEndY}
              stroke={colors.stroke}
              strokeWidth={CONNECTOR_STROKE_WIDTH}
              strokeLinecap="round"
            />
          );

          const nestedChildItems = row.nestedChildren.filter(child => child.type !== 'divider');
          const nestedHasExpandableSibling = nestedChildItems.some(child => !!getNestedChildren(child)?.length);
          childNodes.forEach((child, childIdx) => {
            const childCenterY = child.y + nodeSize / 2;
            const childHasNestedChildren = !!getNestedChildren(nestedChildItems[childIdx])?.length;
            const childLettered = childHasNestedChildren || !nestedHasExpandableSibling;
            elements.push(connectorPath(subTrunkX, childCenterY, child.x, childCenterY, colors.stroke));
            elements.push(node(child.x, child.y, 2, `child-${idx}-${childIdx}`, childLettered));
          });
        }

        return <g key={`group-${idx}`}>{elements}</g>;
      })}
    </svg>
  );
}

function stripIcons(items: ReadonlyArray<SideNavigationProps.Item>): SideNavigationProps.Item[] {
  return items.map((item): SideNavigationProps.Item => {
    switch (item.type) {
      case 'divider':
        return item;
      case 'link':
        return { ...item, icon: undefined };
      case 'section':
        return { ...item, items: stripIcons(item.items) };
      case 'link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'expandable-link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'section-group':
        return {
          ...item,
          items: stripIcons(item.items) as Array<
            | SideNavigationProps.Section
            | SideNavigationProps.Link
            | SideNavigationProps.LinkGroup
            | SideNavigationProps.ExpandableLinkGroup
          >,
        };
    }
  });
}

function renderSideNavConfigs(
  itemsWithIcons: SideNavigationProps.Item[],
  activeHref: string,
  setActiveHref: (href: string) => void,
  header: SideNavigationProps['header'],
  options?: { hideCollapsible?: boolean; moreResourcesHrefs?: ReadonlyArray<string> }
) {
  const onFollow: SideNavigationProps['onFollow'] = event => {
    if (!event.detail.external) {
      event.preventDefault();
      setActiveHref(event.detail.href);
    }
  };

  return (
    <SpaceBetween direction="horizontal" size="l">
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Standard navigation</Box>
        <SideNavigation
          activeHref={activeHref}
          header={header}
          onFollow={onFollow}
          items={stripIcons(itemsWithIcons)}
        />
      </SpaceBetween>
      <div style={{ paddingInlineStart: '60px' }}></div>
      {!options?.hideCollapsible && (
        <SpaceBetween direction="vertical" size="s" alignItems="center">
          <Box variant="h5">Collapsible navigation</Box>
          <SpaceBetween size="l" direction="horizontal">
            <SideNavigation activeHref={activeHref} header={header} onFollow={onFollow} items={itemsWithIcons} />
            <div style={{ minWidth: '52px', maxWidth: '56px', marginBlockStart: '80px' }}>
              <SideNavigation
                activeHref={activeHref}
                collapsed={true}
                header={header}
                onFollow={onFollow}
                items={itemsWithIcons}
              />
            </div>
          </SpaceBetween>
        </SpaceBetween>
      )}
      {!options?.hideCollapsible && <div style={{ paddingInlineStart: '60px' }}></div>}
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Example IA</Box>
        <div style={{ marginBlockStart: '24px' }}>
          <IATreeVisualizer items={itemsWithIcons} moreResourcesHrefs={options?.moreResourcesHrefs} />
        </div>
      </SpaceBetween>
    </SpaceBetween>
  );
}

const navItems: SideNavigationProps.Item[] = [
  {
    type: 'link',
    text: 'Dashboard',
    href: '#/page1',
    icon: (
      <Icon
        svg={
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="3 3 18 18">
            <path
              stroke="currentColor"
              d="M4 5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5ZM14 5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1V5ZM4 16a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-3ZM14 13a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1v-6Z"
            />
          </svg>
        }
      />
    ),
  },
  {
    type: 'link',
    text: 'Storage',
    href: '#/page2',
    icon: (
      <Icon
        svg={
          <svg viewBox="0 0 16 16" height="16" width="16">
            <path
              className="filled no-stroke"
              fill="currentColor"
              fillRule="evenodd"
              d="M3.3.79C4.54.29 6.2 0 8 0s3.46.29 4.7.79a5 5 0 0 1 1.57.94c.41.39.73.9.73 1.52v9.5a2 2 0 0 1-.73 1.52 5 5 0 0 1-1.57.94c-1.24.5-2.9.79-4.7.79s-3.46-.29-4.7-.79a5 5 0 0 1-1.57-.94A2 2 0 0 1 1 12.75v-9.5c0-.62.32-1.13.73-1.52A5 5 0 0 1 3.3.8m-.8 4.54V8c0 .07.03.22.26.43q.33.33 1.1.64c1.02.41 2.49.68 4.14.68s3.12-.27 4.14-.68q.77-.31 1.1-.64c.23-.21.26-.36.26-.43V5.33a6 6 0 0 1-.8.38c-1.24.5-2.9.79-4.7.79s-3.46-.29-4.7-.79a6 6 0 0 1-.8-.38m11-2.08c0 .07-.03.22-.26.43q-.33.33-1.1.64C11.12 4.73 9.65 5 8 5s-3.12-.27-4.14-.68q-.77-.31-1.1-.64c-.23-.21-.26-.36-.26-.43s.03-.22.26-.43q.33-.33 1.1-.64C4.88 1.77 6.35 1.5 8 1.5s3.12.27 4.14.68q.77.31 1.1.64c.23.21.26.36.26.43m0 6.83a6 6 0 0 1-.8.38c-1.24.5-2.9.79-4.7.79s-3.46-.29-4.7-.79a6 6 0 0 1-.8-.38v2.67c0 .07.03.22.26.43q.33.33 1.1.64c1.02.41 2.49.68 4.14.68s3.12-.27 4.14-.68q.77-.31 1.1-.64c.23-.21.26-.36.26-.43z"
              clipRule="evenodd"
            ></path>
          </svg>
        }
      />
    ),
  },
  {
    type: 'link',
    text: 'Metrics',
    href: '#/page3',
    icon: (
      <Icon
        svg={
          <svg viewBox="0 0 16 16" height="16" width="16">
            <path
              className="filled no-stroke"
              fill="currentColor"
              fillRule="evenodd"
              d="M1 1v11.75C1 13.99 2 15 3.25 15H15v-1.5H3.25a.75.75 0 0 1-.75-.75V1zm13.3 5.01.51-.54-1.1-1.03-.5.55-3.23 3.43-2.27-2.27a1 1 0 0 0-1.42 0L4.22 8.22l-.53.53 1.06 1.06.53-.53L7 7.56l2.29 2.29a1 1 0 0 0 1.43-.03z"
              clipRule="evenodd"
            ></path>
          </svg>
        }
      />
    ),
  },
  { type: 'divider' },
  {
    type: 'link',
    text: 'Notifications',
    href: '#/notifications',
    icon: <Icon name="notification" />,
  },
  {
    type: 'link',
    text: 'Support',
    href: 'https://example.com',
    external: true,
    icon: <Icon name="support" />,
  },
];

export default function SideNavigationSimple() {
  const [activeHref, setActiveHref] = useState('#/page1');
  return renderSideNavConfigs(navItems, activeHref, setActiveHref, { href: '#/', text: 'Simple' });
}
```

#### A. Service homepage

The introduction or home page for a service. This is always the top page of the service's IA.

#### B. Page

Page of a service that is hierarchically on the second level of a service's IA. In the collapsible navigation , each page that has an icon appears in the navigation rail; pages without an icon are hidden.

## Organized with sections

A set of links that are conceptually related to each other can be grouped together under a single section header to provide further organization. The links should have a clear relationship to one another and to the section header. Avoid redundancy by not repeating the title for a link in the section header.

##### Standard navigation

## Service

- [Dashboard](about:blank/index.html.md)
- [Deployments](about:blank/index.html.md)
- Reports and Analytics
  - [Usage](about:blank/index.html.md)
  - [Alarms](about:blank/index.html.md)
  - [Logs](about:blank/index.html.md)
- Security
  - [API Keys](about:blank/index.html.md)
  - [Encryption](about:blank/index.html.md)
  - [Authentication](about:blank/index.html.md)

##### Collapsible navigation

## Service

- [Dashboard](about:blank/index.html.md)
- [Deployments](about:blank/index.html.md)
- Reports and Analytics
  - [Usage](about:blank/index.html.md)
  - [Alarms](about:blank/index.html.md)
  - [Logs](about:blank/index.html.md)
- Security
  - [API Keys](about:blank/index.html.md)
  - [Encryption](about:blank/index.html.md)
  - [Authentication](about:blank/index.html.md)

- [Dashboard](about:blank/index.html.md)
- [Deployments](about:blank/index.html.md)
- Reports and Analytics
  - [Usage](about:blank/index.html.md)
  - [Alarms](about:blank/index.html.md)
  - [Logs](about:blank/index.html.md)
- Security
  - [API Keys](about:blank/index.html.md)
  - [Encryption](about:blank/index.html.md)
  - [Authentication](about:blank/index.html.md)

##### Example IA

```side-navigation-pattern-organized-with-sections.tsx
import React, { useState } from 'react';
import Icon from '@cloudscape-design/components/icon';
import SideNavigation, { SideNavigationProps } from '@cloudscape-design/components/side-navigation';
import Box from '@cloudscape-design/components/box';
import SpaceBetween from '@cloudscape-design/components/space-between';
import {
  colorBackgroundCellShaded,
  colorBackgroundStatusInfo,
  colorBackgroundStatusSuccess,
  colorBackgroundStatusWarning,
  colorTextBodyDefault,
  colorTextStatusInfo,
  colorTextStatusSuccess,
  colorTextStatusWarning,
  fontFamilyBase,
} from '@cloudscape-design/design-tokens/index.js';

/**
 * IATreeVisualizer renders an SVG-based node-link tree diagram showing the
 * information architecture of a SideNavigation item set.
 *
 * - Plain links, and items inside a `section`/`section-group`, are flattened
 *   to a single depth: they all branch directly off the main trunk. A
 *   `section`/`section-group` has no href (it's just a label), so it does not
 *   get a node — instead its title is drawn as a text label beside the trunk,
 *   with extra vertical spacing inserted before its first child to set the
 *   group apart.
 * - `link-group` / `expandable-link-group` items ARE real nodes (they have
 *   their own href), so they keep their nested children on a genuine
 *   sub-trunk/sub-branch one depth deeper.
 * - Divider items are silently skipped.
 *
 * Nodes are colored by depth (root = "A", depth 1 = "B", depth 2 = "C", ...),
 * not by sibling group, so every node at the same indentation level shares a
 * color. Within a sibling group, letters are shown only when at least one
 * member of that group is itself expandable (has nested children) — e.g. in
 * `expandable-link-groups`, "Projects"/"Groups" are lettered but plain-link
 * siblings like "Home" render blank, since the letter is meant to signal
 * "this expands" rather than merely "this is at depth N". When no sibling in
 * a group is expandable (e.g. `simple`, `organized-with-sections`), every
 * node in that group keeps its letter.
 *
 * Color tokens used (all from the public design-tokens surface):
 * - Root node (depth 0): colorBackgroundCellShaded (neutral grey fill) + colorBorderInputDefault (border)
 * - Depth 1: colorBackgroundStatusInfo (light blue fill) + colorBorderStatusInfo (blue stroke)
 * - Depth 2: colorBackgroundStatusSuccess (light green fill) + colorBorderStatusSuccess (green stroke)
 * - Depth 3+: colorBackgroundStatusWarning (light amber fill) + colorBorderStatusWarning (amber stroke), repeating
 */
const CONNECTOR_STROKE_WIDTH = 2;
const NODE_STROKE_WIDTH = 1;

const DEPTH_COLORS = [
  { fill: colorBackgroundCellShaded, stroke: colorTextBodyDefault }, // depth 0 (root)
  { fill: colorBackgroundStatusInfo, stroke: colorTextStatusInfo }, // depth 1
  { fill: colorBackgroundStatusSuccess, stroke: colorTextStatusSuccess }, // depth 2
  { fill: colorBackgroundStatusWarning, stroke: colorTextStatusWarning }, // depth 3+
];

function depthColor(depth: number) {
  return DEPTH_COLORS[Math.min(depth, DEPTH_COLORS.length - 1)];
}

function depthLetter(depth: number) {
  return String.fromCharCode('A'.charCodeAt(0) + depth);
}

// Items whose header is a label only (no href) — their children flatten to
// the parent's depth instead of nesting on a sub-branch.
function isLabelOnlyGroup(
  item: SideNavigationProps.Item
): item is SideNavigationProps.Section | SideNavigationProps.SectionGroup {
  return item.type === 'section' || item.type === 'section-group';
}

// Items that are real nodes (have an href) whose children genuinely nest one
// depth deeper on their own sub-branch.
function getNestedChildren(item: SideNavigationProps.Item): ReadonlyArray<SideNavigationProps.Item> | null {
  switch (item.type) {
    case 'link-group':
    case 'expandable-link-group':
      return item.items;
    default:
      return null;
  }
}

function groupTitle(item: SideNavigationProps.Section | SideNavigationProps.SectionGroup): string {
  return item.type === 'section' ? item.text : item.title;
}

// A flat row in the tree: either a real node (with optional nested children)
// or a label-only group boundary that introduces extra spacing before its
// (already-flattened) children. `dividerBefore` marks a row that was
// immediately preceded by a real `divider` item in the source data — this is
// the ONLY thing that produces a dashed trunk segment (dashes represent an
// actual divider, not a generic "list is long" cue). `href` identifies the
// underlying nav item so callers can annotate a specific node (e.g. via
// `moreResourcesHrefs`) without the visualizer needing item identity beyond href.
// `nestingDepth` counts how many label-only groups (section / section-group)
// this row is nested inside BEYOND the first one — e.g. 0 for a row directly
// under the top-level items or under a single (non-nested) section, 1 for a
// section nested inside another section-group (like "Security" inside
// "Reports and analytics"). This only shifts the row's x position for visual
// indentation; the row still connects directly to the main trunk, since it's
// still technically a sibling of the outer group's other rows, not a child.
interface TreeRow {
  isNode: boolean;
  label: string | null;
  extraGapBefore: boolean;
  dividerBefore: boolean;
  href: string | undefined;
  nestingDepth: number;
  nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
}

// Flattens a list of items to depth-1 tree rows. Label-only groups (section /
// section-group) contribute no node of their own — their children are
// recursively flattened into the same row list, with the group's title
// attached to the first child row and an extra gap inserted before it.
// Divider items contribute no node either, but mark the following row as
// `dividerBefore` so it renders with a dashed (not solid) trunk segment above it.
function buildRows(items: ReadonlyArray<SideNavigationProps.Item>, nestingDepth = 0, isInsideGroup = false): TreeRow[] {
  const rows: TreeRow[] = [];
  let pendingDivider = false;
  items.forEach(item => {
    if (item.type === 'divider') {
      pendingDivider = true;
      return;
    }
    if (isLabelOnlyGroup(item)) {
      // A label-only group nested INSIDE another label-only group indents
      // one level deeper. A top-level label-only group (nestingDepth === 0
      // here, i.e. not itself inside another group) stays unindented, same
      // as its non-nested siblings — pass nestingDepth + 1 only when this
      // group is being flattened from within an enclosing group's items.
      const childNestingDepth = isInsideGroup ? nestingDepth + 1 : nestingDepth;
      const childRows = buildRows(item.items, childNestingDepth, true);
      if (childRows.length > 0) {
        childRows[0] = {
          ...childRows[0],
          label: groupTitle(item),
          extraGapBefore: true,
          dividerBefore: pendingDivider,
        };
        pendingDivider = false;
      }
      rows.push(...childRows);
      return;
    }
    rows.push({
      isNode: true,
      label: null,
      extraGapBefore: false,
      dividerBefore: pendingDivider,
      href: 'href' in item ? item.href : undefined,
      nestingDepth,
      nestedChildren: getNestedChildren(item),
    });
    pendingDivider = false;
  });
  return rows;
}

function IATreeVisualizer({
  items,
  moreResourcesHrefs,
}: {
  items: SideNavigationProps.Item[];
  /**
   * hrefs of expandable-link-group / link-group items that have more
   * resources than are shown as children — rendered with a trailing stack of
   * dashed "ghost" boxes and an "Existing resources" label, e.g. to indicate
   * a group backed by a large/unbounded resource list.
   */
  moreResourcesHrefs?: ReadonlyArray<string>;
}) {
  const rows = buildRows(items);

  // A node is only lettered when at least one sibling in its group is itself
  // an expandable node (has nested children) — e.g. in expandable-link-groups,
  // "Projects"/"Groups" are lettered but plain-link siblings like "Home" are
  // blank. When no sibling in the group is expandable (simple, sectioned
  // examples), every node in that group keeps its letter.
  const topLevelHasExpandableSibling = rows.some(row => !!row.nestedChildren && row.nestedChildren.length > 0);

  // Layout constants (condensed)
  const nodeSize = 24;
  const nodeRadius = 6;
  const rowSpacing = 36;
  const groupGap = 24; // extra vertical space inserted before a label-only group's first child
  const edgeMargin = NODE_STROKE_WIDTH; // breathing room on every edge so stroked node borders never get clipped by the viewBox
  const trunkX = edgeMargin + nodeSize / 2;
  const branchOffset = 36;
  const nestedBranchOffset = 36;
  const rootGap = 28; // vertical gap from the root node down to the first branch point (larger than a regular row gap)
  const fontSize = 12;

  interface NodePosition {
    x: number;
    y: number;
    depth: number;
    parentY: number;
  }

  const positions: NodePosition[] = [];
  const rowPositions: {
    y: number;
    label: string | null;
    dividerBefore: boolean;
    href: string | undefined;
    x: number;
    nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
  }[] = [];

  const rootY = edgeMargin;
  let currentY = rootY + nodeSize + rootGap;
  let maxDepth = 1;

  rows.forEach(row => {
    // A divider and a label-only group boundary both introduce the same
    // extra vertical breathing room before the row that follows them.
    if (row.extraGapBefore || row.dividerBefore) {
      currentY += groupGap;
    }
    const y = currentY;
    // A section/section-group nested inside another section/section-group
    // (e.g. "Security" inside "Reports and analytics") indents visually —
    // but still connects directly to the main trunk below, since it's still
    // a sibling of the outer group's other rows, not a child of them.
    const x = branchOffset + row.nestingDepth * nestedBranchOffset;
    rowPositions.push({
      y,
      label: row.label,
      dividerBefore: row.dividerBefore,
      href: row.href,
      x,
      nestedChildren: row.nestedChildren,
    });
    positions.push({ x, y, depth: 1, parentY: y });
    currentY += rowSpacing;
    maxDepth = Math.max(maxDepth, 1 + row.nestingDepth);

    if (row.nestedChildren && row.nestedChildren.length > 0) {
      maxDepth = Math.max(maxDepth, 2 + row.nestingDepth);
      row.nestedChildren
        .filter(child => child.type !== 'divider')
        .forEach(() => {
          positions.push({ x: x + nestedBranchOffset, y: currentY, depth: 2, parentY: y });
          currentY += rowSpacing;
        });
    }
  });

  // The trunk ends at the vertical center of the last top-level row — not at
  // the running layout cursor, which may have advanced past it (e.g. through
  // trailing nested-child rows or a group gap) and no longer reflects that point.
  const lastRowY = rowPositions.length > 0 ? rowPositions[rowPositions.length - 1].y : rootY + nodeSize;
  const trunkEndY = lastRowY + nodeSize / 2;
  // contentBottomY is the center of the last positioned node (top-level or
  // nested child, whichever comes last) — the drawing must extend past its
  // full bottom edge (+ nodeSize / 2), not just its center.
  const contentBottomY = currentY - rowSpacing / 2;

  // "More resources" ghost-box stack sizing (peeks out horizontally behind its
  // real node — see rendering below). Computed here so both svgHeight and
  // svgWidth can account for the extra space it needs.
  const hasMoreResourcesRow = rowPositions.some(row => row.href && moreResourcesHrefs?.includes(row.href));
  const ghostBoxCount = 3;
  const ghostBoxOffset = 10; // horizontal stagger between successive stacked ghost boxes, peeking out behind the real node
  const ghostStackExtent = ghostBoxCount * ghostBoxOffset;
  const ghostToLabelGap = 16; // gap between the rightmost ghost box's edge and its connector/label
  const moreResourcesLabel = 'Existing resources';
  const moreResourcesLabelCharWidth = fontSize * 0.62; // rough monospace-agnostic estimate, just for layout sizing
  const moreResourcesLabelExtent = ghostToLabelGap + 4 + moreResourcesLabel.length * moreResourcesLabelCharWidth;

  const svgHeight = Math.max(trunkEndY, contentBottomY) + nodeSize / 2 + edgeMargin;

  // Compute the drawing width from actual content: branchOffset/nestedBranchOffset
  // are already absolute x-coordinates (they include the left edgeMargin via
  // trunkX), so the rightmost content edge is the deepest branch column's node
  // plus a matching right margin — unless a "more resources" ghost stack (see
  // below) peeks out further right from behind its node, in which case that
  // extends the rightmost edge instead.
  const rightmostBranchX = branchOffset + (maxDepth - 1) * nestedBranchOffset;
  const svgWidth =
    Math.max(
      rightmostBranchX + nodeSize,
      hasMoreResourcesRow ? branchOffset + nodeSize + ghostStackExtent + moreResourcesLabelExtent : 0
    ) + edgeMargin;

  // Curved connector path from trunk to node (S-curve bezier)
  function connectorPath(fromX: number, fromY: number, toX: number, toY: number, stroke: string) {
    const midX = fromX + (toX - fromX) * 0.4;
    const d = `M ${fromX} ${fromY} C ${midX} ${fromY}, ${midX} ${toY}, ${toX} ${toY}`;
    return (
      <path
        key={`conn-${fromX}-${fromY}-${toX}-${toY}`}
        d={d}
        fill="none"
        stroke={stroke}
        strokeWidth={CONNECTOR_STROKE_WIDTH}
        strokeLinecap="round"
      />
    );
  }

  // Only nodes that actually expand into children are lettered by depth —
  // a sibling at the same depth with no nested children (e.g. a plain link
  // next to an expandable-link-group) renders as a blank node so the letter
  // reads as "this expands" rather than just "this is at depth N".
  function node(x: number, y: number, depth: number, key: string, hasChildren: boolean) {
    const colors = depthColor(depth);
    return (
      <g key={key}>
        <rect
          x={x}
          y={y}
          width={nodeSize}
          height={nodeSize}
          rx={nodeRadius}
          ry={nodeRadius}
          fill={colors.fill}
          stroke={colors.stroke}
          strokeWidth={NODE_STROKE_WIDTH}
        />
        {hasChildren && (
          <text
            x={x + nodeSize / 2}
            y={y + nodeSize / 2}
            textAnchor="middle"
            dominantBaseline="central"
            fontSize={fontSize}
            fill={colors.stroke}
          >
            {depthLetter(depth)}
          </text>
        )}
      </g>
    );
  }

  // Trunk segments: split into solid runs, with a dashed run wherever a row
  // is marked `dividerBefore` — dashes represent an actual `divider` item
  // from the source data, spanning the full gap between that row and the one
  // before it (not a generic "list is long" cue).
  const trunkSegments: { y1: number; y2: number; dashed: boolean }[] = [];
  let segmentStartY = rootY + nodeSize;
  rowPositions.forEach((row, idx) => {
    if (row.dividerBefore && idx > 0) {
      const gapStartY = rowPositions[idx - 1].y + nodeSize / 2;
      const gapEndY = row.y + nodeSize / 2;
      trunkSegments.push({ y1: segmentStartY, y2: gapStartY, dashed: false });
      trunkSegments.push({ y1: gapStartY, y2: gapEndY, dashed: true });
      segmentStartY = gapEndY;
    }
  });
  trunkSegments.push({ y1: segmentStartY, y2: trunkEndY, dashed: false });

  return (
    <svg
      width={svgWidth}
      height={svgHeight}
      viewBox={`0 0 ${svgWidth} ${svgHeight}`}
      style={{ display: 'block', fontFamily: fontFamilyBase }}
      aria-hidden="true"
      role="img"
    >
      {/* Root node */}
      {node(trunkX - nodeSize / 2, rootY, 0, 'root-node', true)}

      {/* Main trunk line, with an optional dashed segment spanning one full inter-row gap */}
      {trunkSegments.map((segment, idx) => (
        <line
          key={`trunk-${idx}`}
          x1={trunkX}
          y1={segment.y1}
          x2={trunkX}
          y2={segment.y2}
          stroke={DEPTH_COLORS[1].stroke}
          strokeWidth={CONNECTOR_STROKE_WIDTH}
          strokeLinecap="round"
          strokeDasharray={segment.dashed ? '4 4' : undefined}
        />
      ))}

      {/* Top-level connectors, nodes, and group labels */}
      {rowPositions.map((row, idx) => {
        const nodeY = row.y;
        const nodeCenterY = nodeY + nodeSize / 2;
        const elements: React.ReactNode[] = [];

        // Connector from trunk to top-level node — always originates from the
        // main trunk, even for a nested section/section-group row (indented
        // via row.x), since it's still a sibling of the outer group's other
        // rows, not a child of them.
        elements.push(connectorPath(trunkX, nodeCenterY, row.x, nodeCenterY, DEPTH_COLORS[1].stroke));

        // "More resources" annotation: a stack of dashed ghost boxes peeking
        // out horizontally from behind the real node, for groups whose real
        // children are only a partial view of a larger/unbounded resource
        // list. Pushed BEFORE the real node so — in SVG's painter's-model
        // ordering — the node draws on top and only each ghost box's right
        // edge remains visible, like a stack of cards fanned out sideways.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const ghostColors = depthColor(1);
          for (let i = ghostBoxCount; i >= 1; i--) {
            elements.push(
              <rect
                key={`ghost-${idx}-${i}`}
                x={row.x + i * ghostBoxOffset}
                y={nodeY}
                width={nodeSize}
                height={nodeSize}
                rx={nodeRadius}
                ry={nodeRadius}
                fill={ghostColors.fill}
                stroke={ghostColors.stroke}
                strokeWidth={NODE_STROKE_WIDTH}
                strokeDasharray="3 3"
              />
            );
          }
        }

        // Top-level node — lettered only if this row is itself expandable, or
        // no sibling in this group is expandable (see topLevelHasExpandableSibling).
        const hasNestedChildren = !!(row.nestedChildren && row.nestedChildren.length > 0);
        const tlLettered = hasNestedChildren || !topLevelHasExpandableSibling;
        elements.push(node(row.x, nodeY, 1, `tl-node-${idx}`, tlLettered));

        // Connector + "Existing resources" label trailing the ghost stack,
        // anchored past its rightmost (most-offset) box.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const stackRightX = row.x + ghostBoxCount * ghostBoxOffset + nodeSize;
          const labelLineX = stackRightX + ghostToLabelGap;
          elements.push(
            <line
              key={`ghost-connector-${idx}`}
              x1={stackRightX}
              y1={nodeCenterY}
              x2={labelLineX}
              y2={nodeCenterY}
              stroke={colorTextBodyDefault}
              strokeWidth={1}
            />
          );
          elements.push(
            <text
              key={`ghost-label-${idx}`}
              x={labelLineX + 4}
              y={nodeCenterY}
              dominantBaseline="central"
              fontSize={fontSize}
              fontWeight="bold"
              fill={colorTextBodyDefault}
            >
              {moreResourcesLabel}
            </text>
          );
        }

        // If this node has real nested children (link-group / expandable-link-group), draw sub-trunk and children
        if (row.nestedChildren && row.nestedChildren.length > 0) {
          const colors = depthColor(2);
          const subTrunkX = row.x + nodeSize / 2;
          const childNodes = positions.filter(p => p.depth === 2 && p.parentY === nodeY);
          const subTrunkStartY = nodeY + nodeSize;
          const subTrunkEndY =
            childNodes.length > 0 ? childNodes[childNodes.length - 1].y + nodeSize / 2 : subTrunkStartY;

          elements.push(
            <line
              key={`sub-trunk-${idx}`}
              x1={subTrunkX}
              y1={subTrunkStartY}
              x2={subTrunkX}
              y2={subTrunkEndY}
              stroke={colors.stroke}
              strokeWidth={CONNECTOR_STROKE_WIDTH}
              strokeLinecap="round"
            />
          );

          const nestedChildItems = row.nestedChildren.filter(child => child.type !== 'divider');
          const nestedHasExpandableSibling = nestedChildItems.some(child => !!getNestedChildren(child)?.length);
          childNodes.forEach((child, childIdx) => {
            const childCenterY = child.y + nodeSize / 2;
            const childHasNestedChildren = !!getNestedChildren(nestedChildItems[childIdx])?.length;
            const childLettered = childHasNestedChildren || !nestedHasExpandableSibling;
            elements.push(connectorPath(subTrunkX, childCenterY, child.x, childCenterY, colors.stroke));
            elements.push(node(child.x, child.y, 2, `child-${idx}-${childIdx}`, childLettered));
          });
        }

        return <g key={`group-${idx}`}>{elements}</g>;
      })}
    </svg>
  );
}

function stripIcons(items: ReadonlyArray<SideNavigationProps.Item>): SideNavigationProps.Item[] {
  return items.map((item): SideNavigationProps.Item => {
    switch (item.type) {
      case 'divider':
        return item;
      case 'link':
        return { ...item, icon: undefined };
      case 'section':
        return { ...item, items: stripIcons(item.items) };
      case 'link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'expandable-link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'section-group':
        return {
          ...item,
          items: stripIcons(item.items) as Array<
            | SideNavigationProps.Section
            | SideNavigationProps.Link
            | SideNavigationProps.LinkGroup
            | SideNavigationProps.ExpandableLinkGroup
          >,
        };
    }
  });
}

function renderSideNavConfigs(
  itemsWithIcons: SideNavigationProps.Item[],
  activeHref: string,
  setActiveHref: (href: string) => void,
  header: SideNavigationProps['header'],
  options?: { hideCollapsible?: boolean; moreResourcesHrefs?: ReadonlyArray<string> }
) {
  const onFollow: SideNavigationProps['onFollow'] = event => {
    if (!event.detail.external) {
      event.preventDefault();
      setActiveHref(event.detail.href);
    }
  };

  return (
    <SpaceBetween direction="horizontal" size="l">
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Standard navigation</Box>
        <SideNavigation
          activeHref={activeHref}
          header={header}
          onFollow={onFollow}
          items={stripIcons(itemsWithIcons)}
        />
      </SpaceBetween>
      <div style={{ paddingInlineStart: '60px' }}></div>
      {!options?.hideCollapsible && (
        <SpaceBetween direction="vertical" size="s" alignItems="center">
          <Box variant="h5">Collapsible navigation</Box>
          <SpaceBetween size="l" direction="horizontal">
            <SideNavigation activeHref={activeHref} header={header} onFollow={onFollow} items={itemsWithIcons} />
            <div style={{ minWidth: '52px', maxWidth: '56px', marginBlockStart: '80px' }}>
              <SideNavigation
                activeHref={activeHref}
                collapsed={true}
                header={header}
                onFollow={onFollow}
                items={itemsWithIcons}
              />
            </div>
          </SpaceBetween>
        </SpaceBetween>
      )}
      {!options?.hideCollapsible && <div style={{ paddingInlineStart: '60px' }}></div>}
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Example IA</Box>
        <div style={{ marginBlockStart: '24px' }}>
          <IATreeVisualizer items={itemsWithIcons} moreResourcesHrefs={options?.moreResourcesHrefs} />
        </div>
      </SpaceBetween>
    </SpaceBetween>
  );
}

const navItems: SideNavigationProps.Item[] = [
  {
    type: 'link',
    text: 'Dashboard',
    href: '#/page1',
    icon: (
      <Icon
        svg={
          <svg xmlns="http://www.w3.org/2000/svg" viewBox="3 3 18 18">
            <path
              stroke="currentColor"
              d="M4 5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5ZM14 5a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1V5ZM4 16a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v3a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1v-3ZM14 13a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1h-4a1 1 0 0 1-1-1v-6Z"
            />
          </svg>
        }
      />
    ),
  },
  {
    type: 'link',
    text: 'Deployments',
    href: '#/page2',
    icon: (
      <Icon
        svg={
          <svg viewBox="0 0 16 16" height="16" width="16">
            <path
              className="filled no-stroke"
              fill="currentColor"
              d="m8.35.34 6.25 3.25.4.2v8.42l-.4.2-6.25 3.26-.35.18-.35-.18-6.25-3.25-.4-.21V3.8l.4-.21L7.65.34 8 .15zM2.5 11.3l4.75 2.46V7.81L2.5 5.44zM8.75 7.8v5.95l4.75-2.46V5.44zM3.42 4.22 8 6.52l4.58-2.3L8 1.85z"
            ></path>
          </svg>
        }
      />
    ),
  },
  {
    type: 'section',
    text: 'Reports and Analytics',
    items: [
      {
        type: 'link',
        text: 'Usage',
        href: '#/page4',
        icon: (
          <Icon
            svg={
              <svg viewBox="0 0 16 16" height="16" width="16">
                <path
                  className="filled no-stroke"
                  fill="currentColor"
                  fillRule="evenodd"
                  d="M1 1v11.75C1 13.99 2 15 3.25 15H15v-1.5H3.25a.75.75 0 0 1-.75-.75V1zm8.5 2.75V3H8v9h1.5V3.75M6 8v4H4.5V8zm7-1.25V6h-1.5v6H13V6.75"
                  clipRule="evenodd"
                ></path>
              </svg>
            }
          />
        ),
      },
      {
        type: 'link',
        text: 'Alarms',
        href: '#/page5',
        icon: <Icon name="status-warning" />,
      },
      {
        type: 'link',
        text: 'Logs',
        href: '#/page6',
        icon: <Icon name="list-view" />,
      },
    ],
  },
  {
    type: 'section',
    text: 'Security',
    items: [
      {
        type: 'link',
        text: 'API Keys',
        href: '#/page7',
        icon: <Icon name="key" />,
      },
      {
        type: 'link',
        text: 'Encryption',
        href: '#/page8',
        icon: <Icon name="lock-private" />,
      },
      {
        type: 'link',
        text: 'Authentication',
        href: '#/page9',
        icon: <Icon name="user-profile" />,
      },
    ],
  },
];

export default function SideNavigationExpandableSections() {
  const [activeHref, setActiveHref] = useState('#/page1');
  return renderSideNavConfigs(navItems, activeHref, setActiveHref, { href: '#/', text: 'Service' });
}
```

#### A. Service homepage

The introduction or home page for a service. This is always the top page of the service's IA.

#### B. Page

Page of a service that is hierarchically on the second level of a service's IA. In the collapsible navigation , each page that has an icon appears in the navigation rail; pages without an icon are hidden.

#### C. Section header

Group header title, with related pages below. A section header is not a link but provides a label for the section. In the collapsible navigation, section headers are hidden and the section's child pages appear as a flat list of icons.

### Corresponding with breadcrumbs - optional

Section headers may be included within the breadcrumbs as a prefix to the breadcrumb item for the current page, separated by a colon. We recommend this when the additional context will help users maintain the mental model of the service's IA and resources.

## Organized with group sections

A set of links that are conceptually related to each other can be grouped together under a single section group to provide further organization. You can nest expandable sections, link groups, and expandable link groups within a section group depending on you IA needs.

##### Standard navigation

## Service

- [Dashboard](about:blank/index.html.md)
- [Distributions](about:blank/index.html.md)

- ### Reports and analytics

  - [Cache statistics](about:blank/index.html.md)
  - [Monitoring and alarms](about:blank/index.html.md)
  - [Popular objects](about:blank/index.html.md)
  - Security
    - [Origin access identity](about:blank/index.html.md)
    - [Public key](about:blank/index.html.md)
    - [Field-level encryption](about:blank/index.html.md)

- [Settings](about:blank/index.html.md)

##### Example IA

```side-navigation-pattern-organized-with-nested-groups.tsx
import React, { useState } from 'react';
import SideNavigation, { SideNavigationProps } from '@cloudscape-design/components/side-navigation';
import Box from '@cloudscape-design/components/box';
import SpaceBetween from '@cloudscape-design/components/space-between';
import {
  colorBackgroundCellShaded,
  colorBackgroundStatusInfo,
  colorBackgroundStatusSuccess,
  colorBackgroundStatusWarning,
  colorTextBodyDefault,
  colorTextStatusInfo,
  colorTextStatusSuccess,
  colorTextStatusWarning,
  fontFamilyBase,
} from '@cloudscape-design/design-tokens/index.js';

/**
 * IATreeVisualizer renders an SVG-based node-link tree diagram showing the
 * information architecture of a SideNavigation item set.
 *
 * - Plain links, and items inside a `section`/`section-group`, are flattened
 *   to a single depth: they all branch directly off the main trunk. A
 *   `section`/`section-group` has no href (it's just a label), so it does not
 *   get a node — instead its title is drawn as a text label beside the trunk,
 *   with extra vertical spacing inserted before its first child to set the
 *   group apart.
 * - `link-group` / `expandable-link-group` items ARE real nodes (they have
 *   their own href), so they keep their nested children on a genuine
 *   sub-trunk/sub-branch one depth deeper.
 * - Divider items are silently skipped.
 *
 * Nodes are colored by depth (root = "A", depth 1 = "B", depth 2 = "C", ...),
 * not by sibling group, so every node at the same indentation level shares a
 * color. Within a sibling group, letters are shown only when at least one
 * member of that group is itself expandable (has nested children) — e.g. in
 * `expandable-link-groups`, "Projects"/"Groups" are lettered but plain-link
 * siblings like "Home" render blank, since the letter is meant to signal
 * "this expands" rather than merely "this is at depth N". When no sibling in
 * a group is expandable (e.g. `simple`, `organized-with-sections`), every
 * node in that group keeps its letter.
 *
 * Color tokens used (all from the public design-tokens surface):
 * - Root node (depth 0): colorBackgroundCellShaded (neutral grey fill) + colorBorderInputDefault (border)
 * - Depth 1: colorBackgroundStatusInfo (light blue fill) + colorBorderStatusInfo (blue stroke)
 * - Depth 2: colorBackgroundStatusSuccess (light green fill) + colorBorderStatusSuccess (green stroke)
 * - Depth 3+: colorBackgroundStatusWarning (light amber fill) + colorBorderStatusWarning (amber stroke), repeating
 */
const CONNECTOR_STROKE_WIDTH = 2;
const NODE_STROKE_WIDTH = 1;

const DEPTH_COLORS = [
  { fill: colorBackgroundCellShaded, stroke: colorTextBodyDefault }, // depth 0 (root)
  { fill: colorBackgroundStatusInfo, stroke: colorTextStatusInfo }, // depth 1
  { fill: colorBackgroundStatusSuccess, stroke: colorTextStatusSuccess }, // depth 2
  { fill: colorBackgroundStatusWarning, stroke: colorTextStatusWarning }, // depth 3+
];

function depthColor(depth: number) {
  return DEPTH_COLORS[Math.min(depth, DEPTH_COLORS.length - 1)];
}

function depthLetter(depth: number) {
  return String.fromCharCode('A'.charCodeAt(0) + depth);
}

// Items whose header is a label only (no href) — their children flatten to
// the parent's depth instead of nesting on a sub-branch.
function isLabelOnlyGroup(
  item: SideNavigationProps.Item
): item is SideNavigationProps.Section | SideNavigationProps.SectionGroup {
  return item.type === 'section' || item.type === 'section-group';
}

// Items that are real nodes (have an href) whose children genuinely nest one
// depth deeper on their own sub-branch.
function getNestedChildren(item: SideNavigationProps.Item): ReadonlyArray<SideNavigationProps.Item> | null {
  switch (item.type) {
    case 'link-group':
    case 'expandable-link-group':
      return item.items;
    default:
      return null;
  }
}

function groupTitle(item: SideNavigationProps.Section | SideNavigationProps.SectionGroup): string {
  return item.type === 'section' ? item.text : item.title;
}

// A flat row in the tree: either a real node (with optional nested children)
// or a label-only group boundary that introduces extra spacing before its
// (already-flattened) children. `dividerBefore` marks a row that was
// immediately preceded by a real `divider` item in the source data — this is
// the ONLY thing that produces a dashed trunk segment (dashes represent an
// actual divider, not a generic "list is long" cue). `href` identifies the
// underlying nav item so callers can annotate a specific node (e.g. via
// `moreResourcesHrefs`) without the visualizer needing item identity beyond href.
// `nestingDepth` counts how many label-only groups (section / section-group)
// this row is nested inside BEYOND the first one — e.g. 0 for a row directly
// under the top-level items or under a single (non-nested) section, 1 for a
// section nested inside another section-group (like "Security" inside
// "Reports and analytics"). This only shifts the row's x position for visual
// indentation; the row still connects directly to the main trunk, since it's
// still technically a sibling of the outer group's other rows, not a child.
interface TreeRow {
  isNode: boolean;
  label: string | null;
  extraGapBefore: boolean;
  dividerBefore: boolean;
  href: string | undefined;
  nestingDepth: number;
  nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
}

// Flattens a list of items to depth-1 tree rows. Label-only groups (section /
// section-group) contribute no node of their own — their children are
// recursively flattened into the same row list, with the group's title
// attached to the first child row and an extra gap inserted before it.
// Divider items contribute no node either, but mark the following row as
// `dividerBefore` so it renders with a dashed (not solid) trunk segment above it.
function buildRows(items: ReadonlyArray<SideNavigationProps.Item>, nestingDepth = 0, isInsideGroup = false): TreeRow[] {
  const rows: TreeRow[] = [];
  let pendingDivider = false;
  items.forEach(item => {
    if (item.type === 'divider') {
      pendingDivider = true;
      return;
    }
    if (isLabelOnlyGroup(item)) {
      // A label-only group nested INSIDE another label-only group indents
      // one level deeper. A top-level label-only group (nestingDepth === 0
      // here, i.e. not itself inside another group) stays unindented, same
      // as its non-nested siblings — pass nestingDepth + 1 only when this
      // group is being flattened from within an enclosing group's items.
      const childNestingDepth = isInsideGroup ? nestingDepth + 1 : nestingDepth;
      const childRows = buildRows(item.items, childNestingDepth, true);
      if (childRows.length > 0) {
        childRows[0] = {
          ...childRows[0],
          label: groupTitle(item),
          extraGapBefore: true,
          dividerBefore: pendingDivider,
        };
        pendingDivider = false;
      }
      rows.push(...childRows);
      return;
    }
    rows.push({
      isNode: true,
      label: null,
      extraGapBefore: false,
      dividerBefore: pendingDivider,
      href: 'href' in item ? item.href : undefined,
      nestingDepth,
      nestedChildren: getNestedChildren(item),
    });
    pendingDivider = false;
  });
  return rows;
}

function IATreeVisualizer({
  items,
  moreResourcesHrefs,
}: {
  items: SideNavigationProps.Item[];
  /**
   * hrefs of expandable-link-group / link-group items that have more
   * resources than are shown as children — rendered with a trailing stack of
   * dashed "ghost" boxes and an "Existing resources" label, e.g. to indicate
   * a group backed by a large/unbounded resource list.
   */
  moreResourcesHrefs?: ReadonlyArray<string>;
}) {
  const rows = buildRows(items);

  // A node is only lettered when at least one sibling in its group is itself
  // an expandable node (has nested children) — e.g. in expandable-link-groups,
  // "Projects"/"Groups" are lettered but plain-link siblings like "Home" are
  // blank. When no sibling in the group is expandable (simple, sectioned
  // examples), every node in that group keeps its letter.
  const topLevelHasExpandableSibling = rows.some(row => !!row.nestedChildren && row.nestedChildren.length > 0);

  // Layout constants (condensed)
  const nodeSize = 24;
  const nodeRadius = 6;
  const rowSpacing = 36;
  const groupGap = 24; // extra vertical space inserted before a label-only group's first child
  const edgeMargin = NODE_STROKE_WIDTH; // breathing room on every edge so stroked node borders never get clipped by the viewBox
  const trunkX = edgeMargin + nodeSize / 2;
  const branchOffset = 36;
  const nestedBranchOffset = 36;
  const rootGap = 28; // vertical gap from the root node down to the first branch point (larger than a regular row gap)
  const fontSize = 12;

  interface NodePosition {
    x: number;
    y: number;
    depth: number;
    parentY: number;
  }

  const positions: NodePosition[] = [];
  const rowPositions: {
    y: number;
    label: string | null;
    dividerBefore: boolean;
    href: string | undefined;
    x: number;
    nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
  }[] = [];

  const rootY = edgeMargin;
  let currentY = rootY + nodeSize + rootGap;
  let maxDepth = 1;

  rows.forEach(row => {
    // A divider and a label-only group boundary both introduce the same
    // extra vertical breathing room before the row that follows them.
    if (row.extraGapBefore || row.dividerBefore) {
      currentY += groupGap;
    }
    const y = currentY;
    // A section/section-group nested inside another section/section-group
    // (e.g. "Security" inside "Reports and analytics") indents visually —
    // but still connects directly to the main trunk below, since it's still
    // a sibling of the outer group's other rows, not a child of them.
    const x = branchOffset + row.nestingDepth * nestedBranchOffset;
    rowPositions.push({
      y,
      label: row.label,
      dividerBefore: row.dividerBefore,
      href: row.href,
      x,
      nestedChildren: row.nestedChildren,
    });
    positions.push({ x, y, depth: 1, parentY: y });
    currentY += rowSpacing;
    maxDepth = Math.max(maxDepth, 1 + row.nestingDepth);

    if (row.nestedChildren && row.nestedChildren.length > 0) {
      maxDepth = Math.max(maxDepth, 2 + row.nestingDepth);
      row.nestedChildren
        .filter(child => child.type !== 'divider')
        .forEach(() => {
          positions.push({ x: x + nestedBranchOffset, y: currentY, depth: 2, parentY: y });
          currentY += rowSpacing;
        });
    }
  });

  // The trunk ends at the vertical center of the last top-level row — not at
  // the running layout cursor, which may have advanced past it (e.g. through
  // trailing nested-child rows or a group gap) and no longer reflects that point.
  const lastRowY = rowPositions.length > 0 ? rowPositions[rowPositions.length - 1].y : rootY + nodeSize;
  const trunkEndY = lastRowY + nodeSize / 2;
  // contentBottomY is the center of the last positioned node (top-level or
  // nested child, whichever comes last) — the drawing must extend past its
  // full bottom edge (+ nodeSize / 2), not just its center.
  const contentBottomY = currentY - rowSpacing / 2;

  // "More resources" ghost-box stack sizing (peeks out horizontally behind its
  // real node — see rendering below). Computed here so both svgHeight and
  // svgWidth can account for the extra space it needs.
  const hasMoreResourcesRow = rowPositions.some(row => row.href && moreResourcesHrefs?.includes(row.href));
  const ghostBoxCount = 3;
  const ghostBoxOffset = 10; // horizontal stagger between successive stacked ghost boxes, peeking out behind the real node
  const ghostStackExtent = ghostBoxCount * ghostBoxOffset;
  const ghostToLabelGap = 16; // gap between the rightmost ghost box's edge and its connector/label
  const moreResourcesLabel = 'Existing resources';
  const moreResourcesLabelCharWidth = fontSize * 0.62; // rough monospace-agnostic estimate, just for layout sizing
  const moreResourcesLabelExtent = ghostToLabelGap + 4 + moreResourcesLabel.length * moreResourcesLabelCharWidth;

  const svgHeight = Math.max(trunkEndY, contentBottomY) + nodeSize / 2 + edgeMargin;

  // Compute the drawing width from actual content: branchOffset/nestedBranchOffset
  // are already absolute x-coordinates (they include the left edgeMargin via
  // trunkX), so the rightmost content edge is the deepest branch column's node
  // plus a matching right margin — unless a "more resources" ghost stack (see
  // below) peeks out further right from behind its node, in which case that
  // extends the rightmost edge instead.
  const rightmostBranchX = branchOffset + (maxDepth - 1) * nestedBranchOffset;
  const svgWidth =
    Math.max(
      rightmostBranchX + nodeSize,
      hasMoreResourcesRow ? branchOffset + nodeSize + ghostStackExtent + moreResourcesLabelExtent : 0
    ) + edgeMargin;

  // Curved connector path from trunk to node (S-curve bezier)
  function connectorPath(fromX: number, fromY: number, toX: number, toY: number, stroke: string) {
    const midX = fromX + (toX - fromX) * 0.4;
    const d = `M ${fromX} ${fromY} C ${midX} ${fromY}, ${midX} ${toY}, ${toX} ${toY}`;
    return (
      <path
        key={`conn-${fromX}-${fromY}-${toX}-${toY}`}
        d={d}
        fill="none"
        stroke={stroke}
        strokeWidth={CONNECTOR_STROKE_WIDTH}
        strokeLinecap="round"
      />
    );
  }

  // Only nodes that actually expand into children are lettered by depth —
  // a sibling at the same depth with no nested children (e.g. a plain link
  // next to an expandable-link-group) renders as a blank node so the letter
  // reads as "this expands" rather than just "this is at depth N".
  function node(x: number, y: number, depth: number, key: string, hasChildren: boolean) {
    const colors = depthColor(depth);
    return (
      <g key={key}>
        <rect
          x={x}
          y={y}
          width={nodeSize}
          height={nodeSize}
          rx={nodeRadius}
          ry={nodeRadius}
          fill={colors.fill}
          stroke={colors.stroke}
          strokeWidth={NODE_STROKE_WIDTH}
        />
        {hasChildren && (
          <text
            x={x + nodeSize / 2}
            y={y + nodeSize / 2}
            textAnchor="middle"
            dominantBaseline="central"
            fontSize={fontSize}
            fill={colors.stroke}
          >
            {depthLetter(depth)}
          </text>
        )}
      </g>
    );
  }

  // Trunk segments: split into solid runs, with a dashed run wherever a row
  // is marked `dividerBefore` — dashes represent an actual `divider` item
  // from the source data, spanning the full gap between that row and the one
  // before it (not a generic "list is long" cue).
  const trunkSegments: { y1: number; y2: number; dashed: boolean }[] = [];
  let segmentStartY = rootY + nodeSize;
  rowPositions.forEach((row, idx) => {
    if (row.dividerBefore && idx > 0) {
      const gapStartY = rowPositions[idx - 1].y + nodeSize / 2;
      const gapEndY = row.y + nodeSize / 2;
      trunkSegments.push({ y1: segmentStartY, y2: gapStartY, dashed: false });
      trunkSegments.push({ y1: gapStartY, y2: gapEndY, dashed: true });
      segmentStartY = gapEndY;
    }
  });
  trunkSegments.push({ y1: segmentStartY, y2: trunkEndY, dashed: false });

  return (
    <svg
      width={svgWidth}
      height={svgHeight}
      viewBox={`0 0 ${svgWidth} ${svgHeight}`}
      style={{ display: 'block', fontFamily: fontFamilyBase }}
      aria-hidden="true"
      role="img"
    >
      {/* Root node */}
      {node(trunkX - nodeSize / 2, rootY, 0, 'root-node', true)}

      {/* Main trunk line, with an optional dashed segment spanning one full inter-row gap */}
      {trunkSegments.map((segment, idx) => (
        <line
          key={`trunk-${idx}`}
          x1={trunkX}
          y1={segment.y1}
          x2={trunkX}
          y2={segment.y2}
          stroke={DEPTH_COLORS[1].stroke}
          strokeWidth={CONNECTOR_STROKE_WIDTH}
          strokeLinecap="round"
          strokeDasharray={segment.dashed ? '4 4' : undefined}
        />
      ))}

      {/* Top-level connectors, nodes, and group labels */}
      {rowPositions.map((row, idx) => {
        const nodeY = row.y;
        const nodeCenterY = nodeY + nodeSize / 2;
        const elements: React.ReactNode[] = [];

        // Connector from trunk to top-level node — always originates from the
        // main trunk, even for a nested section/section-group row (indented
        // via row.x), since it's still a sibling of the outer group's other
        // rows, not a child of them.
        elements.push(connectorPath(trunkX, nodeCenterY, row.x, nodeCenterY, DEPTH_COLORS[1].stroke));

        // "More resources" annotation: a stack of dashed ghost boxes peeking
        // out horizontally from behind the real node, for groups whose real
        // children are only a partial view of a larger/unbounded resource
        // list. Pushed BEFORE the real node so — in SVG's painter's-model
        // ordering — the node draws on top and only each ghost box's right
        // edge remains visible, like a stack of cards fanned out sideways.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const ghostColors = depthColor(1);
          for (let i = ghostBoxCount; i >= 1; i--) {
            elements.push(
              <rect
                key={`ghost-${idx}-${i}`}
                x={row.x + i * ghostBoxOffset}
                y={nodeY}
                width={nodeSize}
                height={nodeSize}
                rx={nodeRadius}
                ry={nodeRadius}
                fill={ghostColors.fill}
                stroke={ghostColors.stroke}
                strokeWidth={NODE_STROKE_WIDTH}
                strokeDasharray="3 3"
              />
            );
          }
        }

        // Top-level node — lettered only if this row is itself expandable, or
        // no sibling in this group is expandable (see topLevelHasExpandableSibling).
        const hasNestedChildren = !!(row.nestedChildren && row.nestedChildren.length > 0);
        const tlLettered = hasNestedChildren || !topLevelHasExpandableSibling;
        elements.push(node(row.x, nodeY, 1, `tl-node-${idx}`, tlLettered));

        // Connector + "Existing resources" label trailing the ghost stack,
        // anchored past its rightmost (most-offset) box.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const stackRightX = row.x + ghostBoxCount * ghostBoxOffset + nodeSize;
          const labelLineX = stackRightX + ghostToLabelGap;
          elements.push(
            <line
              key={`ghost-connector-${idx}`}
              x1={stackRightX}
              y1={nodeCenterY}
              x2={labelLineX}
              y2={nodeCenterY}
              stroke={colorTextBodyDefault}
              strokeWidth={1}
            />
          );
          elements.push(
            <text
              key={`ghost-label-${idx}`}
              x={labelLineX + 4}
              y={nodeCenterY}
              dominantBaseline="central"
              fontSize={fontSize}
              fontWeight="bold"
              fill={colorTextBodyDefault}
            >
              {moreResourcesLabel}
            </text>
          );
        }

        // If this node has real nested children (link-group / expandable-link-group), draw sub-trunk and children
        if (row.nestedChildren && row.nestedChildren.length > 0) {
          const colors = depthColor(2);
          const subTrunkX = row.x + nodeSize / 2;
          const childNodes = positions.filter(p => p.depth === 2 && p.parentY === nodeY);
          const subTrunkStartY = nodeY + nodeSize;
          const subTrunkEndY =
            childNodes.length > 0 ? childNodes[childNodes.length - 1].y + nodeSize / 2 : subTrunkStartY;

          elements.push(
            <line
              key={`sub-trunk-${idx}`}
              x1={subTrunkX}
              y1={subTrunkStartY}
              x2={subTrunkX}
              y2={subTrunkEndY}
              stroke={colors.stroke}
              strokeWidth={CONNECTOR_STROKE_WIDTH}
              strokeLinecap="round"
            />
          );

          const nestedChildItems = row.nestedChildren.filter(child => child.type !== 'divider');
          const nestedHasExpandableSibling = nestedChildItems.some(child => !!getNestedChildren(child)?.length);
          childNodes.forEach((child, childIdx) => {
            const childCenterY = child.y + nodeSize / 2;
            const childHasNestedChildren = !!getNestedChildren(nestedChildItems[childIdx])?.length;
            const childLettered = childHasNestedChildren || !nestedHasExpandableSibling;
            elements.push(connectorPath(subTrunkX, childCenterY, child.x, childCenterY, colors.stroke));
            elements.push(node(child.x, child.y, 2, `child-${idx}-${childIdx}`, childLettered));
          });
        }

        return <g key={`group-${idx}`}>{elements}</g>;
      })}
    </svg>
  );
}

function stripIcons(items: ReadonlyArray<SideNavigationProps.Item>): SideNavigationProps.Item[] {
  return items.map((item): SideNavigationProps.Item => {
    switch (item.type) {
      case 'divider':
        return item;
      case 'link':
        return { ...item, icon: undefined };
      case 'section':
        return { ...item, items: stripIcons(item.items) };
      case 'link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'expandable-link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'section-group':
        return {
          ...item,
          items: stripIcons(item.items) as Array<
            | SideNavigationProps.Section
            | SideNavigationProps.Link
            | SideNavigationProps.LinkGroup
            | SideNavigationProps.ExpandableLinkGroup
          >,
        };
    }
  });
}

function renderSideNavConfigs(
  itemsWithIcons: SideNavigationProps.Item[],
  activeHref: string,
  setActiveHref: (href: string) => void,
  header: SideNavigationProps['header'],
  options?: { hideCollapsible?: boolean; moreResourcesHrefs?: ReadonlyArray<string> }
) {
  const onFollow: SideNavigationProps['onFollow'] = event => {
    if (!event.detail.external) {
      event.preventDefault();
      setActiveHref(event.detail.href);
    }
  };

  return (
    <SpaceBetween direction="horizontal" size="l">
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Standard navigation</Box>
        <SideNavigation
          activeHref={activeHref}
          header={header}
          onFollow={onFollow}
          items={stripIcons(itemsWithIcons)}
        />
      </SpaceBetween>
      <div style={{ paddingInlineStart: '60px' }}></div>
      {!options?.hideCollapsible && (
        <SpaceBetween direction="vertical" size="s" alignItems="center">
          <Box variant="h5">Collapsible navigation</Box>
          <SpaceBetween size="l" direction="horizontal">
            <SideNavigation activeHref={activeHref} header={header} onFollow={onFollow} items={itemsWithIcons} />
            <div style={{ minWidth: '52px', maxWidth: '56px', marginBlockStart: '80px' }}>
              <SideNavigation
                activeHref={activeHref}
                collapsed={true}
                header={header}
                onFollow={onFollow}
                items={itemsWithIcons}
              />
            </div>
          </SpaceBetween>
        </SpaceBetween>
      )}
      {!options?.hideCollapsible && <div style={{ paddingInlineStart: '60px' }}></div>}
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Example IA</Box>
        <div style={{ marginBlockStart: '24px' }}>
          <IATreeVisualizer items={itemsWithIcons} moreResourcesHrefs={options?.moreResourcesHrefs} />
        </div>
      </SpaceBetween>
    </SpaceBetween>
  );
}

const navItems: SideNavigationProps.Item[] = [
  {
    type: 'link',
    text: 'Dashboard',
    href: '#/page1',
  },
  {
    type: 'link',
    text: 'Distributions',
    href: '#/page2',
  },
  { type: 'divider' },
  {
    type: 'section-group',
    title: 'Reports and analytics',
    items: [
      {
        type: 'link',
        text: 'Cache statistics',
        href: '#/page3',
      },
      {
        type: 'link',
        text: 'Monitoring and alarms',
        href: '#/page4',
      },
      {
        type: 'link',
        text: 'Popular objects',
        href: '#/page5',
      },
      {
        type: 'section',
        text: 'Security',
        items: [
          {
            type: 'link',
            text: 'Origin access identity',
            href: '#/page6',
          },
          {
            type: 'link',
            text: 'Public key',
            href: '#/page7',
          },
          {
            type: 'link',
            text: 'Field-level encryption',
            href: '#/page8',
          },
        ],
      },
    ],
  },
  { type: 'divider' },
  {
    type: 'link',
    text: 'Settings',
    href: '#/page9',
  },
];

export default function SideNavigationOrganizedWithNestedGroups() {
  const [activeHref, setActiveHref] = useState('#/page5');
  return renderSideNavConfigs(
    navItems,
    activeHref,
    setActiveHref,
    { href: '#/', text: 'Service' },
    { hideCollapsible: true }
  );
}
```

#### A. Service homepage

The introduction or home page for a service. This is always the top page of the service's IA.

#### B. Page

Page of a service that is hierarchically on the second level of a service's IA.

#### C. Section header

Group header title, with related pages below. A section header is not a link but provides a label for the section. In the collapsible navigation, section headers are hidden and the section's child pages appear as a flat list of icons.

### Corresponding with breadcrumbs - optional

Section group headers may be included within the breadcrumbs as a prefix to the breadcrumb item for the current page, separated by a colon. We recommend this when the additional context will help users maintain the mental model of the service's IA and resources.

## Nesting with expandable link groups

This structure supports a primary and secondary level to allow nesting of child pages. We recommend child pages be hidden unless the section has an active link (on the parent or any child pages) or the user has expanded the section into view.

When there are three or more levels of hierarchy with in the service's IA, the user may navigate to them via links and actions embedded within the first and second level pages. The breadcrumbs will then become the method for the user to understand where they are and how to get back. If this strategy is not optimal, consider restructuring the IA. Keeping the navigation shallow helps surface functionality to users faster and helps them keep a mental model of the service.

##### Standard navigation

## Service

- [Home](about:blank/index.html.md)
- [Deployments](about:blank/index.html.md)
- [Projects](about:blank/index.html.md)
  - [Project 1](about:blank/index.html.md)
  - [Project 2](about:blank/index.html.md)
  - [Project 3](about:blank/index.html.md)
- [Groups](about:blank/index.html.md)
  - [My team](about:blank/index.html.md)
  - [My org](about:blank/index.html.md)
  - [My company](about:blank/index.html.md)

- [Help and support](https://example.com/)
- [Feedback](about:blank/index.html.md)

##### Collapsible navigation

## Service

- [Home](about:blank/index.html.md)
- [Deployments](about:blank/index.html.md)
- [Projects](about:blank/index.html.md)
  - [Project 1](about:blank/index.html.md)
  - [Project 2](about:blank/index.html.md)
  - [Project 3](about:blank/index.html.md)
- [Groups](about:blank/index.html.md)
  - [My team](about:blank/index.html.md)
  - [My org](about:blank/index.html.md)
  - [My company](about:blank/index.html.md)

- [Help and support](https://example.com/)
- [Feedback](about:blank/index.html.md)

- [Home](about:blank/index.html.md)
- [Deployments](about:blank/index.html.md)
- [Projects](about:blank/index.html.md)
  - [Project 1](about:blank/index.html.md)
  - [Project 2](about:blank/index.html.md)
  - [Project 3](about:blank/index.html.md)
- [Groups](about:blank/index.html.md)
  - [My team](about:blank/index.html.md)
  - [My org](about:blank/index.html.md)
  - [My company](about:blank/index.html.md)

- [Help and support](https://example.com/)
- [Feedback](about:blank/index.html.md)

##### Example IA

```side-navigation-pattern-expandable-link-groups.tsx
import React, { useState } from 'react';
import Icon from '@cloudscape-design/components/icon';
import SideNavigation, { SideNavigationProps } from '@cloudscape-design/components/side-navigation';
import Box from '@cloudscape-design/components/box';
import SpaceBetween from '@cloudscape-design/components/space-between';
import {
  colorBackgroundCellShaded,
  colorBackgroundStatusInfo,
  colorBackgroundStatusSuccess,
  colorBackgroundStatusWarning,
  colorTextBodyDefault,
  colorTextStatusInfo,
  colorTextStatusSuccess,
  colorTextStatusWarning,
  fontFamilyBase,
} from '@cloudscape-design/design-tokens/index.js';

/**
 * IATreeVisualizer renders an SVG-based node-link tree diagram showing the
 * information architecture of a SideNavigation item set.
 *
 * - Plain links, and items inside a `section`/`section-group`, are flattened
 *   to a single depth: they all branch directly off the main trunk. A
 *   `section`/`section-group` has no href (it's just a label), so it does not
 *   get a node — instead its title is drawn as a text label beside the trunk,
 *   with extra vertical spacing inserted before its first child to set the
 *   group apart.
 * - `link-group` / `expandable-link-group` items ARE real nodes (they have
 *   their own href), so they keep their nested children on a genuine
 *   sub-trunk/sub-branch one depth deeper.
 * - Divider items are silently skipped.
 *
 * Nodes are colored by depth (root = "A", depth 1 = "B", depth 2 = "C", ...),
 * not by sibling group, so every node at the same indentation level shares a
 * color. Within a sibling group, letters are shown only when at least one
 * member of that group is itself expandable (has nested children) — e.g. in
 * `expandable-link-groups`, "Projects"/"Groups" are lettered but plain-link
 * siblings like "Home" render blank, since the letter is meant to signal
 * "this expands" rather than merely "this is at depth N". When no sibling in
 * a group is expandable (e.g. `simple`, `organized-with-sections`), every
 * node in that group keeps its letter.
 *
 * Color tokens used (all from the public design-tokens surface):
 * - Root node (depth 0): colorBackgroundCellShaded (neutral grey fill) + colorBorderInputDefault (border)
 * - Depth 1: colorBackgroundStatusInfo (light blue fill) + colorBorderStatusInfo (blue stroke)
 * - Depth 2: colorBackgroundStatusSuccess (light green fill) + colorBorderStatusSuccess (green stroke)
 * - Depth 3+: colorBackgroundStatusWarning (light amber fill) + colorBorderStatusWarning (amber stroke), repeating
 */
const CONNECTOR_STROKE_WIDTH = 2;
const NODE_STROKE_WIDTH = 1;

const DEPTH_COLORS = [
  { fill: colorBackgroundCellShaded, stroke: colorTextBodyDefault }, // depth 0 (root)
  { fill: colorBackgroundStatusInfo, stroke: colorTextStatusInfo }, // depth 1
  { fill: colorBackgroundStatusSuccess, stroke: colorTextStatusSuccess }, // depth 2
  { fill: colorBackgroundStatusWarning, stroke: colorTextStatusWarning }, // depth 3+
];

function depthColor(depth: number) {
  return DEPTH_COLORS[Math.min(depth, DEPTH_COLORS.length - 1)];
}

function depthLetter(depth: number) {
  return String.fromCharCode('A'.charCodeAt(0) + depth);
}

// Items whose header is a label only (no href) — their children flatten to
// the parent's depth instead of nesting on a sub-branch.
function isLabelOnlyGroup(
  item: SideNavigationProps.Item
): item is SideNavigationProps.Section | SideNavigationProps.SectionGroup {
  return item.type === 'section' || item.type === 'section-group';
}

// Items that are real nodes (have an href) whose children genuinely nest one
// depth deeper on their own sub-branch.
function getNestedChildren(item: SideNavigationProps.Item): ReadonlyArray<SideNavigationProps.Item> | null {
  switch (item.type) {
    case 'link-group':
    case 'expandable-link-group':
      return item.items;
    default:
      return null;
  }
}

function groupTitle(item: SideNavigationProps.Section | SideNavigationProps.SectionGroup): string {
  return item.type === 'section' ? item.text : item.title;
}

// A flat row in the tree: either a real node (with optional nested children)
// or a label-only group boundary that introduces extra spacing before its
// (already-flattened) children. `dividerBefore` marks a row that was
// immediately preceded by a real `divider` item in the source data — this is
// the ONLY thing that produces a dashed trunk segment (dashes represent an
// actual divider, not a generic "list is long" cue). `href` identifies the
// underlying nav item so callers can annotate a specific node (e.g. via
// `moreResourcesHrefs`) without the visualizer needing item identity beyond href.
// `nestingDepth` counts how many label-only groups (section / section-group)
// this row is nested inside BEYOND the first one — e.g. 0 for a row directly
// under the top-level items or under a single (non-nested) section, 1 for a
// section nested inside another section-group (like "Security" inside
// "Reports and analytics"). This only shifts the row's x position for visual
// indentation; the row still connects directly to the main trunk, since it's
// still technically a sibling of the outer group's other rows, not a child.
interface TreeRow {
  isNode: boolean;
  label: string | null;
  extraGapBefore: boolean;
  dividerBefore: boolean;
  href: string | undefined;
  nestingDepth: number;
  nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
}

// Flattens a list of items to depth-1 tree rows. Label-only groups (section /
// section-group) contribute no node of their own — their children are
// recursively flattened into the same row list, with the group's title
// attached to the first child row and an extra gap inserted before it.
// Divider items contribute no node either, but mark the following row as
// `dividerBefore` so it renders with a dashed (not solid) trunk segment above it.
function buildRows(items: ReadonlyArray<SideNavigationProps.Item>, nestingDepth = 0, isInsideGroup = false): TreeRow[] {
  const rows: TreeRow[] = [];
  let pendingDivider = false;
  items.forEach(item => {
    if (item.type === 'divider') {
      pendingDivider = true;
      return;
    }
    if (isLabelOnlyGroup(item)) {
      // A label-only group nested INSIDE another label-only group indents
      // one level deeper. A top-level label-only group (nestingDepth === 0
      // here, i.e. not itself inside another group) stays unindented, same
      // as its non-nested siblings — pass nestingDepth + 1 only when this
      // group is being flattened from within an enclosing group's items.
      const childNestingDepth = isInsideGroup ? nestingDepth + 1 : nestingDepth;
      const childRows = buildRows(item.items, childNestingDepth, true);
      if (childRows.length > 0) {
        childRows[0] = {
          ...childRows[0],
          label: groupTitle(item),
          extraGapBefore: true,
          dividerBefore: pendingDivider,
        };
        pendingDivider = false;
      }
      rows.push(...childRows);
      return;
    }
    rows.push({
      isNode: true,
      label: null,
      extraGapBefore: false,
      dividerBefore: pendingDivider,
      href: 'href' in item ? item.href : undefined,
      nestingDepth,
      nestedChildren: getNestedChildren(item),
    });
    pendingDivider = false;
  });
  return rows;
}

function IATreeVisualizer({
  items,
  moreResourcesHrefs,
}: {
  items: SideNavigationProps.Item[];
  /**
   * hrefs of expandable-link-group / link-group items that have more
   * resources than are shown as children — rendered with a trailing stack of
   * dashed "ghost" boxes and an "Existing resources" label, e.g. to indicate
   * a group backed by a large/unbounded resource list.
   */
  moreResourcesHrefs?: ReadonlyArray<string>;
}) {
  const rows = buildRows(items);

  // A node is only lettered when at least one sibling in its group is itself
  // an expandable node (has nested children) — e.g. in expandable-link-groups,
  // "Projects"/"Groups" are lettered but plain-link siblings like "Home" are
  // blank. When no sibling in the group is expandable (simple, sectioned
  // examples), every node in that group keeps its letter.
  const topLevelHasExpandableSibling = rows.some(row => !!row.nestedChildren && row.nestedChildren.length > 0);

  // Layout constants (condensed)
  const nodeSize = 24;
  const nodeRadius = 6;
  const rowSpacing = 36;
  const groupGap = 24; // extra vertical space inserted before a label-only group's first child
  const edgeMargin = NODE_STROKE_WIDTH; // breathing room on every edge so stroked node borders never get clipped by the viewBox
  const trunkX = edgeMargin + nodeSize / 2;
  const branchOffset = 36;
  const nestedBranchOffset = 36;
  const rootGap = 28; // vertical gap from the root node down to the first branch point (larger than a regular row gap)
  const fontSize = 12;

  interface NodePosition {
    x: number;
    y: number;
    depth: number;
    parentY: number;
  }

  const positions: NodePosition[] = [];
  const rowPositions: {
    y: number;
    label: string | null;
    dividerBefore: boolean;
    href: string | undefined;
    x: number;
    nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
  }[] = [];

  const rootY = edgeMargin;
  let currentY = rootY + nodeSize + rootGap;
  let maxDepth = 1;

  rows.forEach(row => {
    // A divider and a label-only group boundary both introduce the same
    // extra vertical breathing room before the row that follows them.
    if (row.extraGapBefore || row.dividerBefore) {
      currentY += groupGap;
    }
    const y = currentY;
    // A section/section-group nested inside another section/section-group
    // (e.g. "Security" inside "Reports and analytics") indents visually —
    // but still connects directly to the main trunk below, since it's still
    // a sibling of the outer group's other rows, not a child of them.
    const x = branchOffset + row.nestingDepth * nestedBranchOffset;
    rowPositions.push({
      y,
      label: row.label,
      dividerBefore: row.dividerBefore,
      href: row.href,
      x,
      nestedChildren: row.nestedChildren,
    });
    positions.push({ x, y, depth: 1, parentY: y });
    currentY += rowSpacing;
    maxDepth = Math.max(maxDepth, 1 + row.nestingDepth);

    if (row.nestedChildren && row.nestedChildren.length > 0) {
      maxDepth = Math.max(maxDepth, 2 + row.nestingDepth);
      row.nestedChildren
        .filter(child => child.type !== 'divider')
        .forEach(() => {
          positions.push({ x: x + nestedBranchOffset, y: currentY, depth: 2, parentY: y });
          currentY += rowSpacing;
        });
    }
  });

  // The trunk ends at the vertical center of the last top-level row — not at
  // the running layout cursor, which may have advanced past it (e.g. through
  // trailing nested-child rows or a group gap) and no longer reflects that point.
  const lastRowY = rowPositions.length > 0 ? rowPositions[rowPositions.length - 1].y : rootY + nodeSize;
  const trunkEndY = lastRowY + nodeSize / 2;
  // contentBottomY is the center of the last positioned node (top-level or
  // nested child, whichever comes last) — the drawing must extend past its
  // full bottom edge (+ nodeSize / 2), not just its center.
  const contentBottomY = currentY - rowSpacing / 2;

  // "More resources" ghost-box stack sizing (peeks out horizontally behind its
  // real node — see rendering below). Computed here so both svgHeight and
  // svgWidth can account for the extra space it needs.
  const hasMoreResourcesRow = rowPositions.some(row => row.href && moreResourcesHrefs?.includes(row.href));
  const ghostBoxCount = 3;
  const ghostBoxOffset = 10; // horizontal stagger between successive stacked ghost boxes, peeking out behind the real node
  const ghostStackExtent = ghostBoxCount * ghostBoxOffset;
  const ghostToLabelGap = 16; // gap between the rightmost ghost box's edge and its connector/label
  const moreResourcesLabel = 'Existing resources';
  const moreResourcesLabelCharWidth = fontSize * 0.62; // rough monospace-agnostic estimate, just for layout sizing
  const moreResourcesLabelExtent = ghostToLabelGap + 4 + moreResourcesLabel.length * moreResourcesLabelCharWidth;

  const svgHeight = Math.max(trunkEndY, contentBottomY) + nodeSize / 2 + edgeMargin;

  // Compute the drawing width from actual content: branchOffset/nestedBranchOffset
  // are already absolute x-coordinates (they include the left edgeMargin via
  // trunkX), so the rightmost content edge is the deepest branch column's node
  // plus a matching right margin — unless a "more resources" ghost stack (see
  // below) peeks out further right from behind its node, in which case that
  // extends the rightmost edge instead.
  const rightmostBranchX = branchOffset + (maxDepth - 1) * nestedBranchOffset;
  const svgWidth =
    Math.max(
      rightmostBranchX + nodeSize,
      hasMoreResourcesRow ? branchOffset + nodeSize + ghostStackExtent + moreResourcesLabelExtent : 0
    ) + edgeMargin;

  // Curved connector path from trunk to node (S-curve bezier)
  function connectorPath(fromX: number, fromY: number, toX: number, toY: number, stroke: string) {
    const midX = fromX + (toX - fromX) * 0.4;
    const d = `M ${fromX} ${fromY} C ${midX} ${fromY}, ${midX} ${toY}, ${toX} ${toY}`;
    return (
      <path
        key={`conn-${fromX}-${fromY}-${toX}-${toY}`}
        d={d}
        fill="none"
        stroke={stroke}
        strokeWidth={CONNECTOR_STROKE_WIDTH}
        strokeLinecap="round"
      />
    );
  }

  // Only nodes that actually expand into children are lettered by depth —
  // a sibling at the same depth with no nested children (e.g. a plain link
  // next to an expandable-link-group) renders as a blank node so the letter
  // reads as "this expands" rather than just "this is at depth N".
  function node(x: number, y: number, depth: number, key: string, hasChildren: boolean) {
    const colors = depthColor(depth);
    return (
      <g key={key}>
        <rect
          x={x}
          y={y}
          width={nodeSize}
          height={nodeSize}
          rx={nodeRadius}
          ry={nodeRadius}
          fill={colors.fill}
          stroke={colors.stroke}
          strokeWidth={NODE_STROKE_WIDTH}
        />
        {hasChildren && (
          <text
            x={x + nodeSize / 2}
            y={y + nodeSize / 2}
            textAnchor="middle"
            dominantBaseline="central"
            fontSize={fontSize}
            fill={colors.stroke}
          >
            {depthLetter(depth)}
          </text>
        )}
      </g>
    );
  }

  // Trunk segments: split into solid runs, with a dashed run wherever a row
  // is marked `dividerBefore` — dashes represent an actual `divider` item
  // from the source data, spanning the full gap between that row and the one
  // before it (not a generic "list is long" cue).
  const trunkSegments: { y1: number; y2: number; dashed: boolean }[] = [];
  let segmentStartY = rootY + nodeSize;
  rowPositions.forEach((row, idx) => {
    if (row.dividerBefore && idx > 0) {
      const gapStartY = rowPositions[idx - 1].y + nodeSize / 2;
      const gapEndY = row.y + nodeSize / 2;
      trunkSegments.push({ y1: segmentStartY, y2: gapStartY, dashed: false });
      trunkSegments.push({ y1: gapStartY, y2: gapEndY, dashed: true });
      segmentStartY = gapEndY;
    }
  });
  trunkSegments.push({ y1: segmentStartY, y2: trunkEndY, dashed: false });

  return (
    <svg
      width={svgWidth}
      height={svgHeight}
      viewBox={`0 0 ${svgWidth} ${svgHeight}`}
      style={{ display: 'block', fontFamily: fontFamilyBase }}
      aria-hidden="true"
      role="img"
    >
      {/* Root node */}
      {node(trunkX - nodeSize / 2, rootY, 0, 'root-node', true)}

      {/* Main trunk line, with an optional dashed segment spanning one full inter-row gap */}
      {trunkSegments.map((segment, idx) => (
        <line
          key={`trunk-${idx}`}
          x1={trunkX}
          y1={segment.y1}
          x2={trunkX}
          y2={segment.y2}
          stroke={DEPTH_COLORS[1].stroke}
          strokeWidth={CONNECTOR_STROKE_WIDTH}
          strokeLinecap="round"
          strokeDasharray={segment.dashed ? '4 4' : undefined}
        />
      ))}

      {/* Top-level connectors, nodes, and group labels */}
      {rowPositions.map((row, idx) => {
        const nodeY = row.y;
        const nodeCenterY = nodeY + nodeSize / 2;
        const elements: React.ReactNode[] = [];

        // Connector from trunk to top-level node — always originates from the
        // main trunk, even for a nested section/section-group row (indented
        // via row.x), since it's still a sibling of the outer group's other
        // rows, not a child of them.
        elements.push(connectorPath(trunkX, nodeCenterY, row.x, nodeCenterY, DEPTH_COLORS[1].stroke));

        // "More resources" annotation: a stack of dashed ghost boxes peeking
        // out horizontally from behind the real node, for groups whose real
        // children are only a partial view of a larger/unbounded resource
        // list. Pushed BEFORE the real node so — in SVG's painter's-model
        // ordering — the node draws on top and only each ghost box's right
        // edge remains visible, like a stack of cards fanned out sideways.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const ghostColors = depthColor(1);
          for (let i = ghostBoxCount; i >= 1; i--) {
            elements.push(
              <rect
                key={`ghost-${idx}-${i}`}
                x={row.x + i * ghostBoxOffset}
                y={nodeY}
                width={nodeSize}
                height={nodeSize}
                rx={nodeRadius}
                ry={nodeRadius}
                fill={ghostColors.fill}
                stroke={ghostColors.stroke}
                strokeWidth={NODE_STROKE_WIDTH}
                strokeDasharray="3 3"
              />
            );
          }
        }

        // Top-level node — lettered only if this row is itself expandable, or
        // no sibling in this group is expandable (see topLevelHasExpandableSibling).
        const hasNestedChildren = !!(row.nestedChildren && row.nestedChildren.length > 0);
        const tlLettered = hasNestedChildren || !topLevelHasExpandableSibling;
        elements.push(node(row.x, nodeY, 1, `tl-node-${idx}`, tlLettered));

        // Connector + "Existing resources" label trailing the ghost stack,
        // anchored past its rightmost (most-offset) box.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const stackRightX = row.x + ghostBoxCount * ghostBoxOffset + nodeSize;
          const labelLineX = stackRightX + ghostToLabelGap;
          elements.push(
            <line
              key={`ghost-connector-${idx}`}
              x1={stackRightX}
              y1={nodeCenterY}
              x2={labelLineX}
              y2={nodeCenterY}
              stroke={colorTextBodyDefault}
              strokeWidth={1}
            />
          );
          elements.push(
            <text
              key={`ghost-label-${idx}`}
              x={labelLineX + 4}
              y={nodeCenterY}
              dominantBaseline="central"
              fontSize={fontSize}
              fontWeight="bold"
              fill={colorTextBodyDefault}
            >
              {moreResourcesLabel}
            </text>
          );
        }

        // If this node has real nested children (link-group / expandable-link-group), draw sub-trunk and children
        if (row.nestedChildren && row.nestedChildren.length > 0) {
          const colors = depthColor(2);
          const subTrunkX = row.x + nodeSize / 2;
          const childNodes = positions.filter(p => p.depth === 2 && p.parentY === nodeY);
          const subTrunkStartY = nodeY + nodeSize;
          const subTrunkEndY =
            childNodes.length > 0 ? childNodes[childNodes.length - 1].y + nodeSize / 2 : subTrunkStartY;

          elements.push(
            <line
              key={`sub-trunk-${idx}`}
              x1={subTrunkX}
              y1={subTrunkStartY}
              x2={subTrunkX}
              y2={subTrunkEndY}
              stroke={colors.stroke}
              strokeWidth={CONNECTOR_STROKE_WIDTH}
              strokeLinecap="round"
            />
          );

          const nestedChildItems = row.nestedChildren.filter(child => child.type !== 'divider');
          const nestedHasExpandableSibling = nestedChildItems.some(child => !!getNestedChildren(child)?.length);
          childNodes.forEach((child, childIdx) => {
            const childCenterY = child.y + nodeSize / 2;
            const childHasNestedChildren = !!getNestedChildren(nestedChildItems[childIdx])?.length;
            const childLettered = childHasNestedChildren || !nestedHasExpandableSibling;
            elements.push(connectorPath(subTrunkX, childCenterY, child.x, childCenterY, colors.stroke));
            elements.push(node(child.x, child.y, 2, `child-${idx}-${childIdx}`, childLettered));
          });
        }

        return <g key={`group-${idx}`}>{elements}</g>;
      })}
    </svg>
  );
}

function stripIcons(items: ReadonlyArray<SideNavigationProps.Item>): SideNavigationProps.Item[] {
  return items.map((item): SideNavigationProps.Item => {
    switch (item.type) {
      case 'divider':
        return item;
      case 'link':
        return { ...item, icon: undefined };
      case 'section':
        return { ...item, items: stripIcons(item.items) };
      case 'link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'expandable-link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'section-group':
        return {
          ...item,
          items: stripIcons(item.items) as Array<
            | SideNavigationProps.Section
            | SideNavigationProps.Link
            | SideNavigationProps.LinkGroup
            | SideNavigationProps.ExpandableLinkGroup
          >,
        };
    }
  });
}

function renderSideNavConfigs(
  itemsWithIcons: SideNavigationProps.Item[],
  activeHref: string,
  setActiveHref: (href: string) => void,
  header: SideNavigationProps['header'],
  options?: { hideCollapsible?: boolean; moreResourcesHrefs?: ReadonlyArray<string> }
) {
  const onFollow: SideNavigationProps['onFollow'] = event => {
    if (!event.detail.external) {
      event.preventDefault();
      setActiveHref(event.detail.href);
    }
  };

  return (
    <SpaceBetween direction="horizontal" size="l">
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Standard navigation</Box>
        <SideNavigation
          activeHref={activeHref}
          header={header}
          onFollow={onFollow}
          items={stripIcons(itemsWithIcons)}
        />
      </SpaceBetween>
      <div style={{ paddingInlineStart: '60px' }}></div>
      {!options?.hideCollapsible && (
        <SpaceBetween direction="vertical" size="s" alignItems="center">
          <Box variant="h5">Collapsible navigation</Box>
          <SpaceBetween size="l" direction="horizontal">
            <SideNavigation activeHref={activeHref} header={header} onFollow={onFollow} items={itemsWithIcons} />
            <div style={{ minWidth: '52px', maxWidth: '56px', marginBlockStart: '80px' }}>
              <SideNavigation
                activeHref={activeHref}
                collapsed={true}
                header={header}
                onFollow={onFollow}
                items={itemsWithIcons}
              />
            </div>
          </SpaceBetween>
        </SpaceBetween>
      )}
      {!options?.hideCollapsible && <div style={{ paddingInlineStart: '60px' }}></div>}
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Example IA</Box>
        <div style={{ marginBlockStart: '24px' }}>
          <IATreeVisualizer items={itemsWithIcons} moreResourcesHrefs={options?.moreResourcesHrefs} />
        </div>
      </SpaceBetween>
    </SpaceBetween>
  );
}

const navItems: SideNavigationProps.Item[] = [
  {
    type: 'link',
    text: 'Home',
    href: '#/page1',
    icon: (
      <Icon
        svg={
          <svg
            xmlns="http://www.w3.org/2000/svg"
            viewBox="0 0 16 16"
            width="16"
            height="16"
            fill="none"
            stroke="currentColor"
          >
            <path d="M1.75 6.75 L8 1.5 L14.25 6.75 V13.5 A1 1 0 0 1 13.25 14.5 H2.75 A1 1 0 0 1 1.75 13.5 Z" />
            <path d="M5.75 14.5 V9.5 H10.25 V14.5" />
          </svg>
        }
      />
    ),
  },
  {
    type: 'link',
    text: 'Deployments',
    href: '#/page2',
    icon: (
      <Icon
        svg={
          <svg viewBox="0 0 16 16" height="16" width="16">
            <path
              className="filled no-stroke"
              fill="currentColor"
              d="m8.35.34 6.25 3.25.4.2v8.42l-.4.2-6.25 3.26-.35.18-.35-.18-6.25-3.25-.4-.21V3.8l.4-.21L7.65.34 8 .15zM2.5 11.3l4.75 2.46V7.81L2.5 5.44zM8.75 7.8v5.95l4.75-2.46V5.44zM3.42 4.22 8 6.52l4.58-2.3L8 1.85z"
            ></path>
          </svg>
        }
      />
    ),
  },
  {
    type: 'expandable-link-group',
    text: 'Projects',
    href: '#/group1',
    icon: <Icon name="grid-view" />,
    defaultExpanded: true,
    items: [
      {
        type: 'link',
        text: 'Project 1',
        href: '#/page4',
      },
      {
        type: 'link',
        text: 'Project 2',
        href: '#/page5',
      },
      {
        type: 'link',
        text: 'Project 3',
        href: '#/page6',
      },
    ],
  },
  {
    type: 'expandable-link-group',
    text: 'Groups',
    href: '#/group2',
    icon: <Icon name="group" />,
    defaultExpanded: true,
    items: [
      {
        type: 'link',
        text: 'My team',
        href: '#/page7',
      },
      {
        type: 'link',
        text: 'My org',
        href: '#/page8',
      },
      {
        type: 'link',
        text: 'My company',
        href: '#/page9',
      },
    ],
  },
  { type: 'divider' },
  {
    type: 'link',
    text: 'Help and support',
    href: 'https://example.com',
    external: true,
    icon: <Icon name="support" />,
  },
  {
    type: 'link',
    text: 'Feedback',
    href: '#/notifications',
    icon: <Icon name="contact" />,
  },
];

export default function SideNavigationELGs() {
  const [activeHref, setActiveHref] = useState('#/page1');
  return renderSideNavConfigs(navItems, activeHref, setActiveHref, { href: '#/', text: 'Service' });
}
```

#### A. Service homepage

The introduction or home page for a service. This is always the top page of the service's IA.

#### B. Parent page

Page that has children pages directly related to it.

#### C. Child page

Page that is hierarchically on the third level of a service's IA, and one level below a parent page.

### Corresponding with breadcrumbs

Child pages are listed as a separate breadcrumb item to the parent page that it is secondary to.

## Link groups for large resource details

Some services may contain resources that are too large or complex to use the [details page with tabs](/patterns/resource-management/details/details-page-with-tabs/index.html.md) or [detail pages as a hub](/patterns/resource-management/details/details-page-as-hub/index.html.md) structures, and must split it into multiple pages to manage the resource. In this case, a link group may be used to organize the resource detail pages.

After an existing resource has been selected from a collection via a [view resource page](/patterns/resource-management/view/index.html.md) (E), the links for the selected [resource's detail pages](/patterns/resource-management/details/index.html.md) (F) appear nested below the overarching view resource page. The landing page for the specific resource should be listed as the first link of the nested link group. We recommend that all primary actions and information relevant to the resource be made available on the first (and landing) detail page for the resource.

##### Standard navigation

## Service

- [Dashboard](about:blank/index.html.md)
- [Data sources](about:blank/index.html.md)
  - [Data summary](about:blank/index.html.md)
  - [Target distributions](about:blank/index.html.md)
  - [Missing values](about:blank/index.html.md)
  - [Attributes](about:blank/index.html.md)
- [ML models](about:blank/index.html.md)
- [Evaluations](about:blank/index.html.md)
- [Batch predictions](about:blank/index.html.md)

##### Example IA

```side-navigation-pattern-large-resource-link-groups.tsx
import React, { useState } from 'react';
import SideNavigation, { SideNavigationProps } from '@cloudscape-design/components/side-navigation';
import Box from '@cloudscape-design/components/box';
import SpaceBetween from '@cloudscape-design/components/space-between';
import {
  colorBackgroundCellShaded,
  colorBackgroundStatusInfo,
  colorBackgroundStatusSuccess,
  colorBackgroundStatusWarning,
  colorTextBodyDefault,
  colorTextStatusInfo,
  colorTextStatusSuccess,
  colorTextStatusWarning,
  fontFamilyBase,
} from '@cloudscape-design/design-tokens/index.js';

/**
 * IATreeVisualizer renders an SVG-based node-link tree diagram showing the
 * information architecture of a SideNavigation item set.
 *
 * - Plain links, and items inside a `section`/`section-group`, are flattened
 *   to a single depth: they all branch directly off the main trunk. A
 *   `section`/`section-group` has no href (it's just a label), so it does not
 *   get a node — instead its title is drawn as a text label beside the trunk,
 *   with extra vertical spacing inserted before its first child to set the
 *   group apart.
 * - `link-group` / `expandable-link-group` items ARE real nodes (they have
 *   their own href), so they keep their nested children on a genuine
 *   sub-trunk/sub-branch one depth deeper.
 * - Divider items are silently skipped.
 *
 * Nodes are colored by depth (root = "A", depth 1 = "B", depth 2 = "C", ...),
 * not by sibling group, so every node at the same indentation level shares a
 * color. Within a sibling group, letters are shown only when at least one
 * member of that group is itself expandable (has nested children) — e.g. in
 * `expandable-link-groups`, "Projects"/"Groups" are lettered but plain-link
 * siblings like "Home" render blank, since the letter is meant to signal
 * "this expands" rather than merely "this is at depth N". When no sibling in
 * a group is expandable (e.g. `simple`, `organized-with-sections`), every
 * node in that group keeps its letter.
 *
 * Color tokens used (all from the public design-tokens surface):
 * - Root node (depth 0): colorBackgroundCellShaded (neutral grey fill) + colorBorderInputDefault (border)
 * - Depth 1: colorBackgroundStatusInfo (light blue fill) + colorBorderStatusInfo (blue stroke)
 * - Depth 2: colorBackgroundStatusSuccess (light green fill) + colorBorderStatusSuccess (green stroke)
 * - Depth 3+: colorBackgroundStatusWarning (light amber fill) + colorBorderStatusWarning (amber stroke), repeating
 */
const CONNECTOR_STROKE_WIDTH = 2;
const NODE_STROKE_WIDTH = 1;

const DEPTH_COLORS = [
  { fill: colorBackgroundCellShaded, stroke: colorTextBodyDefault }, // depth 0 (root)
  { fill: colorBackgroundStatusInfo, stroke: colorTextStatusInfo }, // depth 1
  { fill: colorBackgroundStatusSuccess, stroke: colorTextStatusSuccess }, // depth 2
  { fill: colorBackgroundStatusWarning, stroke: colorTextStatusWarning }, // depth 3+
];

function depthColor(depth: number) {
  return DEPTH_COLORS[Math.min(depth, DEPTH_COLORS.length - 1)];
}

function depthLetter(depth: number) {
  return String.fromCharCode('A'.charCodeAt(0) + depth);
}

// Items whose header is a label only (no href) — their children flatten to
// the parent's depth instead of nesting on a sub-branch.
function isLabelOnlyGroup(
  item: SideNavigationProps.Item
): item is SideNavigationProps.Section | SideNavigationProps.SectionGroup {
  return item.type === 'section' || item.type === 'section-group';
}

// Items that are real nodes (have an href) whose children genuinely nest one
// depth deeper on their own sub-branch.
function getNestedChildren(item: SideNavigationProps.Item): ReadonlyArray<SideNavigationProps.Item> | null {
  switch (item.type) {
    case 'link-group':
    case 'expandable-link-group':
      return item.items;
    default:
      return null;
  }
}

function groupTitle(item: SideNavigationProps.Section | SideNavigationProps.SectionGroup): string {
  return item.type === 'section' ? item.text : item.title;
}

// A flat row in the tree: either a real node (with optional nested children)
// or a label-only group boundary that introduces extra spacing before its
// (already-flattened) children. `dividerBefore` marks a row that was
// immediately preceded by a real `divider` item in the source data — this is
// the ONLY thing that produces a dashed trunk segment (dashes represent an
// actual divider, not a generic "list is long" cue). `href` identifies the
// underlying nav item so callers can annotate a specific node (e.g. via
// `moreResourcesHrefs`) without the visualizer needing item identity beyond href.
// `nestingDepth` counts how many label-only groups (section / section-group)
// this row is nested inside BEYOND the first one — e.g. 0 for a row directly
// under the top-level items or under a single (non-nested) section, 1 for a
// section nested inside another section-group (like "Security" inside
// "Reports and analytics"). This only shifts the row's x position for visual
// indentation; the row still connects directly to the main trunk, since it's
// still technically a sibling of the outer group's other rows, not a child.
interface TreeRow {
  isNode: boolean;
  label: string | null;
  extraGapBefore: boolean;
  dividerBefore: boolean;
  href: string | undefined;
  nestingDepth: number;
  nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
}

// Flattens a list of items to depth-1 tree rows. Label-only groups (section /
// section-group) contribute no node of their own — their children are
// recursively flattened into the same row list, with the group's title
// attached to the first child row and an extra gap inserted before it.
// Divider items contribute no node either, but mark the following row as
// `dividerBefore` so it renders with a dashed (not solid) trunk segment above it.
function buildRows(items: ReadonlyArray<SideNavigationProps.Item>, nestingDepth = 0, isInsideGroup = false): TreeRow[] {
  const rows: TreeRow[] = [];
  let pendingDivider = false;
  items.forEach(item => {
    if (item.type === 'divider') {
      pendingDivider = true;
      return;
    }
    if (isLabelOnlyGroup(item)) {
      // A label-only group nested INSIDE another label-only group indents
      // one level deeper. A top-level label-only group (nestingDepth === 0
      // here, i.e. not itself inside another group) stays unindented, same
      // as its non-nested siblings — pass nestingDepth + 1 only when this
      // group is being flattened from within an enclosing group's items.
      const childNestingDepth = isInsideGroup ? nestingDepth + 1 : nestingDepth;
      const childRows = buildRows(item.items, childNestingDepth, true);
      if (childRows.length > 0) {
        childRows[0] = {
          ...childRows[0],
          label: groupTitle(item),
          extraGapBefore: true,
          dividerBefore: pendingDivider,
        };
        pendingDivider = false;
      }
      rows.push(...childRows);
      return;
    }
    rows.push({
      isNode: true,
      label: null,
      extraGapBefore: false,
      dividerBefore: pendingDivider,
      href: 'href' in item ? item.href : undefined,
      nestingDepth,
      nestedChildren: getNestedChildren(item),
    });
    pendingDivider = false;
  });
  return rows;
}

function IATreeVisualizer({
  items,
  moreResourcesHrefs,
}: {
  items: SideNavigationProps.Item[];
  /**
   * hrefs of expandable-link-group / link-group items that have more
   * resources than are shown as children — rendered with a trailing stack of
   * dashed "ghost" boxes and an "Existing resources" label, e.g. to indicate
   * a group backed by a large/unbounded resource list.
   */
  moreResourcesHrefs?: ReadonlyArray<string>;
}) {
  const rows = buildRows(items);

  // A node is only lettered when at least one sibling in its group is itself
  // an expandable node (has nested children) — e.g. in expandable-link-groups,
  // "Projects"/"Groups" are lettered but plain-link siblings like "Home" are
  // blank. When no sibling in the group is expandable (simple, sectioned
  // examples), every node in that group keeps its letter.
  const topLevelHasExpandableSibling = rows.some(row => !!row.nestedChildren && row.nestedChildren.length > 0);

  // Layout constants (condensed)
  const nodeSize = 24;
  const nodeRadius = 6;
  const rowSpacing = 36;
  const groupGap = 24; // extra vertical space inserted before a label-only group's first child
  const edgeMargin = NODE_STROKE_WIDTH; // breathing room on every edge so stroked node borders never get clipped by the viewBox
  const trunkX = edgeMargin + nodeSize / 2;
  const branchOffset = 36;
  const nestedBranchOffset = 36;
  const rootGap = 28; // vertical gap from the root node down to the first branch point (larger than a regular row gap)
  const fontSize = 12;

  interface NodePosition {
    x: number;
    y: number;
    depth: number;
    parentY: number;
  }

  const positions: NodePosition[] = [];
  const rowPositions: {
    y: number;
    label: string | null;
    dividerBefore: boolean;
    href: string | undefined;
    x: number;
    nestedChildren: ReadonlyArray<SideNavigationProps.Item> | null;
  }[] = [];

  const rootY = edgeMargin;
  let currentY = rootY + nodeSize + rootGap;
  let maxDepth = 1;

  rows.forEach(row => {
    // A divider and a label-only group boundary both introduce the same
    // extra vertical breathing room before the row that follows them.
    if (row.extraGapBefore || row.dividerBefore) {
      currentY += groupGap;
    }
    const y = currentY;
    // A section/section-group nested inside another section/section-group
    // (e.g. "Security" inside "Reports and analytics") indents visually —
    // but still connects directly to the main trunk below, since it's still
    // a sibling of the outer group's other rows, not a child of them.
    const x = branchOffset + row.nestingDepth * nestedBranchOffset;
    rowPositions.push({
      y,
      label: row.label,
      dividerBefore: row.dividerBefore,
      href: row.href,
      x,
      nestedChildren: row.nestedChildren,
    });
    positions.push({ x, y, depth: 1, parentY: y });
    currentY += rowSpacing;
    maxDepth = Math.max(maxDepth, 1 + row.nestingDepth);

    if (row.nestedChildren && row.nestedChildren.length > 0) {
      maxDepth = Math.max(maxDepth, 2 + row.nestingDepth);
      row.nestedChildren
        .filter(child => child.type !== 'divider')
        .forEach(() => {
          positions.push({ x: x + nestedBranchOffset, y: currentY, depth: 2, parentY: y });
          currentY += rowSpacing;
        });
    }
  });

  // The trunk ends at the vertical center of the last top-level row — not at
  // the running layout cursor, which may have advanced past it (e.g. through
  // trailing nested-child rows or a group gap) and no longer reflects that point.
  const lastRowY = rowPositions.length > 0 ? rowPositions[rowPositions.length - 1].y : rootY + nodeSize;
  const trunkEndY = lastRowY + nodeSize / 2;
  // contentBottomY is the center of the last positioned node (top-level or
  // nested child, whichever comes last) — the drawing must extend past its
  // full bottom edge (+ nodeSize / 2), not just its center.
  const contentBottomY = currentY - rowSpacing / 2;

  // "More resources" ghost-box stack sizing (peeks out horizontally behind its
  // real node — see rendering below). Computed here so both svgHeight and
  // svgWidth can account for the extra space it needs.
  const hasMoreResourcesRow = rowPositions.some(row => row.href && moreResourcesHrefs?.includes(row.href));
  const ghostBoxCount = 3;
  const ghostBoxOffset = 10; // horizontal stagger between successive stacked ghost boxes, peeking out behind the real node
  const ghostStackExtent = ghostBoxCount * ghostBoxOffset;
  const ghostToLabelGap = 16; // gap between the rightmost ghost box's edge and its connector/label
  const moreResourcesLabel = 'Existing resources';
  const moreResourcesLabelCharWidth = fontSize * 0.62; // rough monospace-agnostic estimate, just for layout sizing
  const moreResourcesLabelExtent = ghostToLabelGap + 4 + moreResourcesLabel.length * moreResourcesLabelCharWidth;

  const svgHeight = Math.max(trunkEndY, contentBottomY) + nodeSize / 2 + edgeMargin;

  // Compute the drawing width from actual content: branchOffset/nestedBranchOffset
  // are already absolute x-coordinates (they include the left edgeMargin via
  // trunkX), so the rightmost content edge is the deepest branch column's node
  // plus a matching right margin — unless a "more resources" ghost stack (see
  // below) peeks out further right from behind its node, in which case that
  // extends the rightmost edge instead.
  const rightmostBranchX = branchOffset + (maxDepth - 1) * nestedBranchOffset;
  const svgWidth =
    Math.max(
      rightmostBranchX + nodeSize,
      hasMoreResourcesRow ? branchOffset + nodeSize + ghostStackExtent + moreResourcesLabelExtent : 0
    ) + edgeMargin;

  // Curved connector path from trunk to node (S-curve bezier)
  function connectorPath(fromX: number, fromY: number, toX: number, toY: number, stroke: string) {
    const midX = fromX + (toX - fromX) * 0.4;
    const d = `M ${fromX} ${fromY} C ${midX} ${fromY}, ${midX} ${toY}, ${toX} ${toY}`;
    return (
      <path
        key={`conn-${fromX}-${fromY}-${toX}-${toY}`}
        d={d}
        fill="none"
        stroke={stroke}
        strokeWidth={CONNECTOR_STROKE_WIDTH}
        strokeLinecap="round"
      />
    );
  }

  // Only nodes that actually expand into children are lettered by depth —
  // a sibling at the same depth with no nested children (e.g. a plain link
  // next to an expandable-link-group) renders as a blank node so the letter
  // reads as "this expands" rather than just "this is at depth N".
  function node(x: number, y: number, depth: number, key: string, hasChildren: boolean) {
    const colors = depthColor(depth);
    return (
      <g key={key}>
        <rect
          x={x}
          y={y}
          width={nodeSize}
          height={nodeSize}
          rx={nodeRadius}
          ry={nodeRadius}
          fill={colors.fill}
          stroke={colors.stroke}
          strokeWidth={NODE_STROKE_WIDTH}
        />
        {hasChildren && (
          <text
            x={x + nodeSize / 2}
            y={y + nodeSize / 2}
            textAnchor="middle"
            dominantBaseline="central"
            fontSize={fontSize}
            fill={colors.stroke}
          >
            {depthLetter(depth)}
          </text>
        )}
      </g>
    );
  }

  // Trunk segments: split into solid runs, with a dashed run wherever a row
  // is marked `dividerBefore` — dashes represent an actual `divider` item
  // from the source data, spanning the full gap between that row and the one
  // before it (not a generic "list is long" cue).
  const trunkSegments: { y1: number; y2: number; dashed: boolean }[] = [];
  let segmentStartY = rootY + nodeSize;
  rowPositions.forEach((row, idx) => {
    if (row.dividerBefore && idx > 0) {
      const gapStartY = rowPositions[idx - 1].y + nodeSize / 2;
      const gapEndY = row.y + nodeSize / 2;
      trunkSegments.push({ y1: segmentStartY, y2: gapStartY, dashed: false });
      trunkSegments.push({ y1: gapStartY, y2: gapEndY, dashed: true });
      segmentStartY = gapEndY;
    }
  });
  trunkSegments.push({ y1: segmentStartY, y2: trunkEndY, dashed: false });

  return (
    <svg
      width={svgWidth}
      height={svgHeight}
      viewBox={`0 0 ${svgWidth} ${svgHeight}`}
      style={{ display: 'block', fontFamily: fontFamilyBase }}
      aria-hidden="true"
      role="img"
    >
      {/* Root node */}
      {node(trunkX - nodeSize / 2, rootY, 0, 'root-node', true)}

      {/* Main trunk line, with an optional dashed segment spanning one full inter-row gap */}
      {trunkSegments.map((segment, idx) => (
        <line
          key={`trunk-${idx}`}
          x1={trunkX}
          y1={segment.y1}
          x2={trunkX}
          y2={segment.y2}
          stroke={DEPTH_COLORS[1].stroke}
          strokeWidth={CONNECTOR_STROKE_WIDTH}
          strokeLinecap="round"
          strokeDasharray={segment.dashed ? '4 4' : undefined}
        />
      ))}

      {/* Top-level connectors, nodes, and group labels */}
      {rowPositions.map((row, idx) => {
        const nodeY = row.y;
        const nodeCenterY = nodeY + nodeSize / 2;
        const elements: React.ReactNode[] = [];

        // Connector from trunk to top-level node — always originates from the
        // main trunk, even for a nested section/section-group row (indented
        // via row.x), since it's still a sibling of the outer group's other
        // rows, not a child of them.
        elements.push(connectorPath(trunkX, nodeCenterY, row.x, nodeCenterY, DEPTH_COLORS[1].stroke));

        // "More resources" annotation: a stack of dashed ghost boxes peeking
        // out horizontally from behind the real node, for groups whose real
        // children are only a partial view of a larger/unbounded resource
        // list. Pushed BEFORE the real node so — in SVG's painter's-model
        // ordering — the node draws on top and only each ghost box's right
        // edge remains visible, like a stack of cards fanned out sideways.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const ghostColors = depthColor(1);
          for (let i = ghostBoxCount; i >= 1; i--) {
            elements.push(
              <rect
                key={`ghost-${idx}-${i}`}
                x={row.x + i * ghostBoxOffset}
                y={nodeY}
                width={nodeSize}
                height={nodeSize}
                rx={nodeRadius}
                ry={nodeRadius}
                fill={ghostColors.fill}
                stroke={ghostColors.stroke}
                strokeWidth={NODE_STROKE_WIDTH}
                strokeDasharray="3 3"
              />
            );
          }
        }

        // Top-level node — lettered only if this row is itself expandable, or
        // no sibling in this group is expandable (see topLevelHasExpandableSibling).
        const hasNestedChildren = !!(row.nestedChildren && row.nestedChildren.length > 0);
        const tlLettered = hasNestedChildren || !topLevelHasExpandableSibling;
        elements.push(node(row.x, nodeY, 1, `tl-node-${idx}`, tlLettered));

        // Connector + "Existing resources" label trailing the ghost stack,
        // anchored past its rightmost (most-offset) box.
        if (row.href && moreResourcesHrefs?.includes(row.href)) {
          const stackRightX = row.x + ghostBoxCount * ghostBoxOffset + nodeSize;
          const labelLineX = stackRightX + ghostToLabelGap;
          elements.push(
            <line
              key={`ghost-connector-${idx}`}
              x1={stackRightX}
              y1={nodeCenterY}
              x2={labelLineX}
              y2={nodeCenterY}
              stroke={colorTextBodyDefault}
              strokeWidth={1}
            />
          );
          elements.push(
            <text
              key={`ghost-label-${idx}`}
              x={labelLineX + 4}
              y={nodeCenterY}
              dominantBaseline="central"
              fontSize={fontSize}
              fontWeight="bold"
              fill={colorTextBodyDefault}
            >
              {moreResourcesLabel}
            </text>
          );
        }

        // If this node has real nested children (link-group / expandable-link-group), draw sub-trunk and children
        if (row.nestedChildren && row.nestedChildren.length > 0) {
          const colors = depthColor(2);
          const subTrunkX = row.x + nodeSize / 2;
          const childNodes = positions.filter(p => p.depth === 2 && p.parentY === nodeY);
          const subTrunkStartY = nodeY + nodeSize;
          const subTrunkEndY =
            childNodes.length > 0 ? childNodes[childNodes.length - 1].y + nodeSize / 2 : subTrunkStartY;

          elements.push(
            <line
              key={`sub-trunk-${idx}`}
              x1={subTrunkX}
              y1={subTrunkStartY}
              x2={subTrunkX}
              y2={subTrunkEndY}
              stroke={colors.stroke}
              strokeWidth={CONNECTOR_STROKE_WIDTH}
              strokeLinecap="round"
            />
          );

          const nestedChildItems = row.nestedChildren.filter(child => child.type !== 'divider');
          const nestedHasExpandableSibling = nestedChildItems.some(child => !!getNestedChildren(child)?.length);
          childNodes.forEach((child, childIdx) => {
            const childCenterY = child.y + nodeSize / 2;
            const childHasNestedChildren = !!getNestedChildren(nestedChildItems[childIdx])?.length;
            const childLettered = childHasNestedChildren || !nestedHasExpandableSibling;
            elements.push(connectorPath(subTrunkX, childCenterY, child.x, childCenterY, colors.stroke));
            elements.push(node(child.x, child.y, 2, `child-${idx}-${childIdx}`, childLettered));
          });
        }

        return <g key={`group-${idx}`}>{elements}</g>;
      })}
    </svg>
  );
}

function stripIcons(items: ReadonlyArray<SideNavigationProps.Item>): SideNavigationProps.Item[] {
  return items.map((item): SideNavigationProps.Item => {
    switch (item.type) {
      case 'divider':
        return item;
      case 'link':
        return { ...item, icon: undefined };
      case 'section':
        return { ...item, items: stripIcons(item.items) };
      case 'link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'expandable-link-group':
        return { ...item, icon: undefined, items: stripIcons(item.items) };
      case 'section-group':
        return {
          ...item,
          items: stripIcons(item.items) as Array<
            | SideNavigationProps.Section
            | SideNavigationProps.Link
            | SideNavigationProps.LinkGroup
            | SideNavigationProps.ExpandableLinkGroup
          >,
        };
    }
  });
}

function renderSideNavConfigs(
  itemsWithIcons: SideNavigationProps.Item[],
  activeHref: string,
  setActiveHref: (href: string) => void,
  header: SideNavigationProps['header'],
  options?: { hideCollapsible?: boolean; moreResourcesHrefs?: ReadonlyArray<string> }
) {
  const onFollow: SideNavigationProps['onFollow'] = event => {
    if (!event.detail.external) {
      event.preventDefault();
      setActiveHref(event.detail.href);
    }
  };

  return (
    <SpaceBetween direction="horizontal" size="l">
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Standard navigation</Box>
        <SideNavigation
          activeHref={activeHref}
          header={header}
          onFollow={onFollow}
          items={stripIcons(itemsWithIcons)}
        />
      </SpaceBetween>
      <div style={{ paddingInlineStart: '60px' }}></div>
      {!options?.hideCollapsible && (
        <SpaceBetween direction="vertical" size="s" alignItems="center">
          <Box variant="h5">Collapsible navigation</Box>
          <SpaceBetween size="l" direction="horizontal">
            <SideNavigation activeHref={activeHref} header={header} onFollow={onFollow} items={itemsWithIcons} />
            <div style={{ minWidth: '52px', maxWidth: '56px', marginBlockStart: '80px' }}>
              <SideNavigation
                activeHref={activeHref}
                collapsed={true}
                header={header}
                onFollow={onFollow}
                items={itemsWithIcons}
              />
            </div>
          </SpaceBetween>
        </SpaceBetween>
      )}
      {!options?.hideCollapsible && <div style={{ paddingInlineStart: '60px' }}></div>}
      <SpaceBetween direction="vertical" size="s" alignItems="center">
        <Box variant="h5">Example IA</Box>
        <div style={{ marginBlockStart: '24px' }}>
          <IATreeVisualizer items={itemsWithIcons} moreResourcesHrefs={options?.moreResourcesHrefs} />
        </div>
      </SpaceBetween>
    </SpaceBetween>
  );
}

const navItems: SideNavigationProps.Item[] = [
  {
    type: 'link',
    text: 'Dashboard',
    href: '#/page1',
  },
  {
    type: 'expandable-link-group',
    text: 'Data sources',
    href: '#/group1',
    defaultExpanded: true,
    items: [
      {
        type: 'link',
        text: 'Data summary',
        href: '#/page2',
      },
      {
        type: 'link',
        text: 'Target distributions',
        href: '#/page3',
      },
      {
        type: 'link',
        text: 'Missing values',
        href: '#/page4',
      },
      {
        type: 'link',
        text: 'Attributes',
        href: '#/page5',
      },
    ],
  },
  {
    type: 'link',
    text: 'ML models',
    href: '#/page6',
  },
  {
    type: 'link',
    text: 'Evaluations',
    href: '#/page7',
  },
  {
    type: 'link',
    text: 'Batch predictions',
    href: '#/page8',
  },
];

export default function SideNavigationLargeResourceLinkGroups() {
  const [activeHref, setActiveHref] = useState('#/page2');
  return renderSideNavConfigs(
    navItems,
    activeHref,
    setActiveHref,
    { href: '#/', text: 'Service' },
    {
      hideCollapsible: true,
      moreResourcesHrefs: ['#/group1'],
    }
  );
}
```

#### A. Service homepage

The introduction or home page for a service. This is always the top page of the service's IA.

#### B. View resource page for large resources

The view resource page that becomes the parent page for a group of [resource detail pages](/patterns/resource-management/details/index.html.md) utilized for a single existing resource.

#### C. Resource detail page

A resource detail page for a large resource with multiple detail pages. These sets of detail pages only appear in the side navigation once a specific resource has been selected.

### Corresponding with breadcrumbs

The name of the selected resource is included as a prefix to the breadcrumb item for the current page, separated by a colon.

## Service identity

The service identity tells the user which service they're using. Always link it to the homepage of your particular service, so users can learn more about it. The service identity is always displayed at the top page of the service's IA.

You may choose to use a logo in the navigation, in order to provide additional brand awareness. Logos can be used together with the service name, or separately.

## General guidelines

### Do

- Organize the side navigation to best support the user's primary use cases and the mental model for the involved resources rather than treating the navigation as a site map. Avoid including links for pages which are best intended to be accessed inline a page, such as: [create resource](/patterns/resource-management/create/index.html.md)   flows, [edit resource](/patterns/resource-management/edit/index.html.md)   flows, and [view resource](/patterns/resource-management/view/index.html.md)   pages accessed from another [details page as a hub](/patterns/resource-management/details/details-page-as-hub/index.html.md)  .
- Keep groupings to a minimum when organizing the side navigation with sections or expandable link groups.
- Organize and order your links from general to specific, in order of usefulness, relevance, or frequency of use.
- Use dividers sparingly to separate sets of links that are fundamentally not related to each other.
- Keep the name of the items within the side navigation consistent with the breadcrumb items.
- By default side navigation is closed on [create resource](/patterns/resource-management/create/index.html.md)   and [edit resource](/patterns/resource-management/edit/index.html.md)   pages. It is open on all other pages.
- Keep the side navigation open by default for returning users and new users. I   f the user closes it, remember that and keep it closed as they move around the service.
- Always ensure one link in the side navigation is active. If the user is on a [resource details](/patterns/resource-management/details/index.html.md)   page, the resources type link should be active. For example,* *   when on *Service > Distributions > SLCCSMWOHOFUY0, Distributions*   should be highlighted in the side navigation.
- In a collapsible navigation, apply icons consistently at one level of the navigation: give every sibling in that level an icon. For example, all parent pages, or all children of a section.
- Choose icons that are easily recognizable and distinct from one another so users can tell destinations apart without labels.

### Don't

- Avoid using sections and expandable link groups in the same side navigation.
- Avoid sections with only two links.
- Don't use badges with section headers or for labeling links with static messages. For example: *Preview*   , *New*   , or *Beta*   . Badges may be used to surface actionable areas to a page.
- When opening a [resource details](/patterns/resource-management/details/index.html.md)   page, don't add a new item to the side navigation.
- Don't use the collapsible navigation pattern with overly complex navigations such as the link groups for large resources pattern. Especially if the deep links are contextual and transient, making them difficult to learn or completely hidden when collapsed.
- Don't offer a navigation rail for occasional-use services, or where destinations can't be clearly represented by icons.

## Related patterns

### Side navigation

A list of navigational links that point to the pages within an application.

[View Documentation](/patterns/general/service-navigation/side-navigation/index.html.md)

### Breadcrumb group

Displays a series of navigational links in a hierarchical list.

[View Documentation](/components/breadcrumb-group/index.html.md)

### Resource details

On a resource details page, users can view the details of a resource and, when relevant, any related resources.

[View Documentation](/patterns/resource-management/details/index.html.md)

### View resources

With the view resources patterns, users can find and take action on a collection of resources in the most efficient way possible.---

[View Documentation](/patterns/resource-management/view/index.html.md)

## Search Cloudscape