Storyline: unfoldable section list per chapter in the sidebar

Each chapter in the right-hand menu gets a caret that unfolds its
numbered sections (e.g. the prologue's 28 scenes); clicking one jumps
straight to it. The chapter you're reading starts unfolded, other
chapters' sections link across (/storyline/overview#section-…), and the
section at the top of the pane is highlighted as you scroll.

- ChapterOutline service parses each rendered chapter for its
  <h2 class="storyline-section"> headings, adds anchor ids and returns the
  outline; the controller renders all chapters once to feed the sidebar.
- storyline-toc Stimulus controller: fold/unfold, in-pane jump, scroll-spy
  (works in the split view and in the small-screen window-scroll fallback).
- Tests for the outline parser.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
Frank
2026-09-21 18:44:54 +02:00
co-authored by Claude Sonnet 5
parent 8b8f67c1d0
commit b77e5eaa4f
6 changed files with 229 additions and 8 deletions
@@ -0,0 +1,72 @@
import { Controller } from '@hotwired/stimulus';
/*
* Sidebar table of contents on a storyline chapter page.
*
* - the caret unfolds/folds a chapter's section list
* - links for the chapter being read (target "link", href="#section-…")
* jump inside the split view's scrolling pane
* - the section currently at the top of the pane is highlighted
*/
export default class extends Controller {
static targets = ['link'];
connect() {
this.pane = this.element.closest('.storyline-split-main');
this.onScroll = () => {
if (this.frame) return;
this.frame = requestAnimationFrame(() => {
this.frame = null;
this.highlight();
});
};
(this.pane || window).addEventListener('scroll', this.onScroll, { passive: true });
window.addEventListener('scroll', this.onScroll, { passive: true });
this.highlight();
}
disconnect() {
(this.pane || window).removeEventListener('scroll', this.onScroll);
window.removeEventListener('scroll', this.onScroll);
}
fold(event) {
const item = event.currentTarget.closest('.storyline-toc-item');
const open = item.classList.toggle('is-open');
event.currentTarget.setAttribute('aria-expanded', open ? 'true' : 'false');
}
jump(event) {
const id = event.currentTarget.getAttribute('href').slice(1);
const el = document.getElementById(id);
if (!el) return;
event.preventDefault();
el.scrollIntoView({ block: 'start' });
history.replaceState(null, '', `#${id}`);
}
linkTargetConnected(link) {
link.addEventListener('click', (e) => this.jump({ currentTarget: link, preventDefault: () => e.preventDefault() }));
}
highlight() {
if (!this.hasLinkTarget) return;
// In the split view the pane scrolls; on small screens the window does.
const paneScrolls = this.pane && getComputedStyle(this.pane).overflowY !== 'visible';
const top = paneScrolls ? this.pane.getBoundingClientRect().top : 0;
let current = null;
for (const link of this.linkTargets) {
const el = document.getElementById(link.getAttribute('href').slice(1));
if (el && el.getBoundingClientRect().top - top <= 90) current = link;
}
this.linkTargets.forEach((l) => l.classList.toggle('is-current', l === current));
if (current && this.pane) {
const list = current.closest('.storyline-toc-sections');
if (list && list.scrollHeight > list.clientHeight) {
const c = current.getBoundingClientRect();
const l = list.getBoundingClientRect();
if (c.top < l.top || c.bottom > l.bottom) current.scrollIntoView({ block: 'nearest' });
}
}
}
}
+43
View File
@@ -260,6 +260,49 @@ table.dataTable {
color: var(--bs-secondary-color);
}
/* Unfoldable per-chapter section lists */
.storyline-toc-row { display: flex; align-items: flex-start; gap: 0.15rem; }
.storyline-toc-row .storyline-toc-link { flex: 1 1 auto; min-width: 0; }
.storyline-toc-fold {
flex: 0 0 1.4rem;
height: 1.9rem;
padding: 0;
border: 0;
background: none;
color: var(--bs-secondary-color);
cursor: pointer;
transition: transform 0.15s ease;
}
button.storyline-toc-fold:hover { color: var(--bs-body-color); }
.storyline-toc-item.is-open > .storyline-toc-row > button.storyline-toc-fold { transform: rotate(90deg); }
.storyline-toc-sections {
display: none;
margin: 0.1rem 0 0.4rem 1.4rem;
padding: 0;
max-height: 45vh;
overflow-y: auto;
scrollbar-width: none;
font-size: 0.875rem;
}
.storyline-toc-sections::-webkit-scrollbar { display: none; }
.storyline-toc-item.is-open > .storyline-toc-sections { display: block; }
.storyline-toc-sub {
display: flex;
gap: 0.5rem;
padding: 0.2rem 0.5rem;
border-left: 2px solid var(--bs-border-color);
text-decoration: none;
color: var(--bs-secondary-color);
}
.storyline-toc-sub:hover { color: var(--bs-body-color); background: var(--bs-tertiary-bg); }
.storyline-toc-sub.is-current {
color: var(--bs-body-color);
border-left-color: var(--bs-primary);
font-weight: 600;
}
.storyline-toc-sub .storyline-toc-num { flex: 0 0 1.4rem; }
.storyline-section { scroll-margin-top: 0.75rem; }
/* --- Storyline: the document itself --------------------------------- */
.storyline-doc {
max-width: 46rem;
+16 -1
View File
@@ -4,6 +4,7 @@ namespace App\Controller;
use App\Form\ChapterNoteType;
use App\Repository\ChapterNoteRepository;
use App\Storyline\ChapterOutline;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
@@ -51,7 +52,7 @@ class StorylineController extends AbstractController
}
#[Route('/storyline/{slug}', name: 'app_storyline_chapter', requirements: ['slug' => '[a-z0-9-]+'], methods: ['GET', 'POST'])]
public function chapter(string $slug, Request $request, ChapterNoteRepository $notes, EntityManagerInterface $em): Response
public function chapter(string $slug, Request $request, ChapterNoteRepository $notes, EntityManagerInterface $em, ChapterOutline $outline): Response
{
if (!isset(self::CHAPTERS[$slug])) {
throw $this->createNotFoundException('No such storyline chapter.');
@@ -71,6 +72,18 @@ class StorylineController extends AbstractController
return $this->redirectToRoute('app_storyline_chapter', ['slug' => $slug]);
}
// Render every chapter once: the current one is shown (with anchors),
// the rest only feed the sidebar's per-section jump lists.
$sections = [];
$body = '';
foreach (self::CHAPTERS as $s => $c) {
$processed = $outline->process($this->renderView($c['template']));
$sections[$s] = $processed['sections'];
if ($s === $slug) {
$body = $processed['html'];
}
}
$slugs = array_keys(self::CHAPTERS);
$pos = array_search($slug, $slugs, true);
@@ -78,6 +91,8 @@ class StorylineController extends AbstractController
'chapters' => self::CHAPTERS,
'slug' => $slug,
'chapter' => self::CHAPTERS[$slug],
'body' => $body,
'sections' => $sections,
'note' => $note,
'form' => $form,
'prev' => $pos > 0 ? $slugs[$pos - 1] : null,
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Storyline;
use Symfony\Component\String\Slugger\AsciiSlugger;
/**
* Turns a rendered chapter into an outline: finds each numbered section
* heading (<h2 class="storyline-section"><span>21</span> Title</h2>), gives it
* an anchor id, and reports it so the sidebar can link straight to it.
*/
final class ChapterOutline
{
private const HEADING = '~<h2 class="storyline-section"([^>]*)>\s*<span>(.*?)</span>\s*(.*?)</h2>~s';
/**
* @return array{html: string, sections: list<array{id: string, num: string, title: string}>}
*/
public function process(string $html): array
{
$slugger = new AsciiSlugger();
$sections = [];
$n = 0;
$html = preg_replace_callback(self::HEADING, function (array $m) use (&$sections, &$n, $slugger): string {
++$n;
$num = trim(html_entity_decode(strip_tags($m[2]), \ENT_QUOTES | \ENT_HTML5));
$title = trim(html_entity_decode(strip_tags($m[3]), \ENT_QUOTES | \ENT_HTML5));
$id = sprintf('section-%d-%s', $n, strtolower($slugger->slug($title)->toString()));
$sections[] = ['id' => $id, 'num' => $num, 'title' => $title];
return sprintf('<h2 class="storyline-section" id="%s"%s><span>%s</span> %s</h2>', $id, $m[1], $m[2], $m[3]);
}, $html) ?? $html;
return ['html' => $html, 'sections' => $sections];
}
}
+23 -3
View File
@@ -12,13 +12,33 @@
<div class="storyline-toc">
<a href="{{ path('app_storyline') }}" class="text-decoration-none small d-inline-block mb-2">&larr; All chapters</a>
<div class="text-uppercase small text-body-secondary fw-semibold mb-2" style="letter-spacing:.08em">Chapters</div>
<ol class="list-unstyled mb-0">
<ol class="list-unstyled mb-0" data-controller="storyline-toc">
{% for s, c in chapters %}
<li>
{% set open = s == slug %}
<li class="storyline-toc-item{{ open ? ' is-open' }}">
<div class="storyline-toc-row">
{% if sections[s] is not empty %}
<button type="button" class="storyline-toc-fold" data-action="storyline-toc#fold"
aria-expanded="{{ open ? 'true' : 'false' }}"
aria-label="Show sections of {{ c.title }}">&#9656;</button>
{% else %}<span class="storyline-toc-fold"></span>{% endif %}
<a href="{{ path('app_storyline_chapter', {slug: s}) }}"
class="storyline-toc-link{{ s == slug ? ' is-active' }}">
<span class="storyline-toc-num">{{ c.tag }}</span>{{ c.title }}
</a>
</div>
{% if sections[s] is not empty %}
<ol class="storyline-toc-sections list-unstyled">
{% for sec in sections[s] %}
<li>
<a href="{{ s == slug ? '#' ~ sec.id : path('app_storyline_chapter', {slug: s}) ~ '#' ~ sec.id }}"
class="storyline-toc-sub" {% if s == slug %}data-storyline-toc-target="link"{% endif %}>
<span class="storyline-toc-num">{{ sec.num }}</span>{{ sec.title }}
</a>
</li>
{% endfor %}
</ol>
{% endif %}
</li>
{% endfor %}
</ol>
@@ -33,7 +53,7 @@
<p class="storyline-standfirst">{{ chapter.summary }}</p>
</header>
{{ include(chapter.template) }}
{{ body|raw }}
</article>
<nav class="storyline-pager">
+34
View File
@@ -0,0 +1,34 @@
<?php
namespace App\Tests\Storyline;
use App\Storyline\ChapterOutline;
use PHPUnit\Framework\TestCase;
class ChapterOutlineTest extends TestCase
{
public function testFindsSectionsAndAddsAnchors(): void
{
$html = '<p>intro</p>'
.'<h2 class="storyline-section"><span>21</span> Finding the Hearthburrow</h2><p>x</p>'
.'<h2 class="storyline-section"><span>&plus;</span> Appendix &mdash; Timing</h2>';
$out = (new ChapterOutline())->process($html);
self::assertSame('21', $out['sections'][0]['num']);
self::assertSame('Finding the Hearthburrow', $out['sections'][0]['title']);
self::assertSame('section-1-finding-the-hearthburrow', $out['sections'][0]['id']);
self::assertSame('+', $out['sections'][1]['num']);
self::assertSame('Appendix — Timing', $out['sections'][1]['title']);
self::assertStringContainsString('<h2 class="storyline-section" id="section-1-finding-the-hearthburrow">', $out['html']);
self::assertStringContainsString('<p>intro</p>', $out['html']);
}
public function testChapterWithoutSectionsIsUntouched(): void
{
$out = (new ChapterOutline())->process('<p>plain</p>');
self::assertSame([], $out['sections']);
self::assertSame('<p>plain</p>', $out['html']);
}
}