@php use App\Enums\Content\BlockType; @endphp @props(['content', 'blocks']) @php /** * 見出しレベルのマッピング */ $headingLevels = [ BlockType::TitleH2->value => 2, BlockType::TitleH3->value => 3, BlockType::TitleH4->value => 4, BlockType::TitleH5->value => 5, ]; /** * ブロック一覧から見出しをフラットに収集する(枠内も再帰的に処理) */ if (!function_exists('collectHeadings')) { function collectHeadings(array $blocks, array $headingLevels): array { $headings = []; foreach ($blocks as $block) { $type = $block['block_type'] ?? null; // 枠の場合は内部ブロックを再帰処理 if ($type === BlockType::Frame->value) { $innerHeadings = collectHeadings($block['inner_blocks'] ?? [], $headingLevels); $headings = array_merge($headings, $innerHeadings); continue; } // 見出しブロックのみを目次に追加し、システムが割り振ったIDをアンカーとして利用する if (isset($headingLevels[$type])) { $anchor = heading_anchor($block); if ($anchor === null || ! filled($block['title'] ?? '')) { continue; } $headings[] = [ 'title' => $block['title'], 'anchor' => $anchor, 'level' => $headingLevels[$type], ]; } } return $headings; } } /** * フラットな見出しリストをネスト構造に変換する */ if (!function_exists('buildTocTree')) { function buildTocTree(array $headings): array { $toc = []; $stack = []; foreach ($headings as $heading) { $item = [ 'title' => $heading['title'], 'anchor' => $heading['anchor'], 'level' => $heading['level'], 'children' => [], ]; // スタックから現在のレベル以上の要素を除去 while (!empty($stack) && end($stack)['level'] >= $heading['level']) { array_pop($stack); } if (empty($stack)) { $toc[] = $item; $stack[] = &$toc[array_key_last($toc)]; } else { $parent = &$stack[array_key_last($stack)]; $parent['children'][] = $item; $stack[] = &$parent['children'][array_key_last($parent['children'])]; } } return $toc; } } /** * TOCツリーをHTML出力する */ if (!function_exists('renderTocTree')) { function renderTocTree(array $items, int $depth = 0): void { if (empty($items)) { return; } echo '