Sfoglia il codice sorgente

feat: 阅读页目录支持折叠/展开,默认仅显示当前章节路径

getBookToc 计算父子层级关系,标注 active(当前章节高亮)与 hide
(折叠模式下隐藏的节点);折叠/展开由 .toc-tree 的 .toc-expanded
类切换。同时顺手统一 BookController 代码风格(Laravel Pint)。

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
visuddhinanda 4 settimane fa
parent
commit
4442f63d77

+ 113 - 62
api-v13/app/Http/Controllers/Library/BookController.php

@@ -2,33 +2,26 @@
 
 namespace App\Http\Controllers\Library;
 
+use App\DTO\Search\HitItemDTO;
+use App\Http\Api\ChannelApi;
+use App\Http\Api\StudioApi;
 use App\Http\Controllers\Controller;
-
-
-
-use Illuminate\Http\Request;
-use App\Models\ProgressChapter;
 use App\Models\PaliText;
+use App\Models\ProgressChapter;
 use App\Models\Sentence;
-
 use App\Services\ChapterService;
-use App\Services\PaliTextService;
 use App\Services\OpenSearchService;
-
-use App\DTO\Search\HitItemDTO;
-use App\Http\Api\ChannelApi;
-use App\Http\Api\StudioApi;
-
+use App\Services\PaliTextService;
+use Illuminate\Http\Request;
 
 class BookController extends Controller
 {
     protected $maxChapterLen = 50000;
+
     protected $minChapterLen = 100;
 
     /**
      * 构造函数,注入 OpenSearchService
-     *
-     * @param  \App\Services\OpenSearchService  $searchService
      */
     public function __construct(
         protected OpenSearchService $searchService,
@@ -39,11 +32,11 @@ class BookController extends Controller
     {
         $bookRaw = $this->loadBook($id);
 
-        if (!$bookRaw) {
+        if (! $bookRaw) {
             abort(404);
         }
 
-        //查询章节
+        // 查询章节
         $channelId = $bookRaw->channel_id; // 替换为具体的 channel_id 值
 
         $book = $this->getBookInfo($bookRaw);
@@ -60,38 +53,44 @@ class BookController extends Controller
             ->get();
 
         $otherVersions = [];
-        $others->each(function ($book) use (&$otherVersions, $id) {
+        $others->each(function ($book) use (&$otherVersions) {
             $otherVersions[] = $this->getBookInfo($book);
         });
 
         return view('library.tipitaka.show', compact('book', 'otherVersions'));
     }
 
-
     private function fetchCommentary(int $book, int $paraStart, int $paraEnd, string $channelId)
     {
         $notes = Sentence::where('book_id', $book)
             ->whereBetween('paragraph', [$paraStart, $paraEnd])
             ->where('channel_uid', $channelId)
             ->select(['uid', 'book_id', 'paragraph', 'word_start', 'word_end'])->get()->toArray();
+
         return $notes;
     }
 
     private function injectNoteMarkers(string $html, array $notesMap): string
     {
-        if (empty($notesMap)) return $html;
+        if (empty($notesMap)) {
+            return $html;
+        }
 
         return preg_replace_callback(
             '/(<div class=\'sentence\' data-sid=\'([^\']+)\')/',
             function ($matches) use ($notesMap) {
                 $sid = $matches[2];
-                if (!isset($notesMap[$sid])) return $matches[0];
+                if (! isset($notesMap[$sid])) {
+                    return $matches[0];
+                }
                 $uid = $notesMap[$sid];
-                return $matches[1] . " data-note-id='{$uid}'";
+
+                return $matches[1]." data-note-id='{$uid}'";
             },
             $html
         );
     }
+
     public function read(Request $request, string $id)
     {
 
@@ -104,7 +103,7 @@ class BookController extends Controller
             $chapter = [
                 'category' => [],
                 'title' => '',
-                'display' => ''
+                'display' => '',
 
             ];
         }
@@ -116,32 +115,30 @@ class BookController extends Controller
             // sid 格式:{book_id}-{paragraph}-{word_start}-{word_end}
             $notesMap = collect($commentaries)->keyBy(function ($note) {
                 return "{$note['book_id']}-{$note['paragraph']}-{$note['word_start']}-{$note['word_end']}";
-            })->map(fn($note) => $note['uid'])->toArray();
+            })->map(fn ($note) => $note['uid'])->toArray();
         }
 
-
         $chapterService = app(ChapterService::class);
 
         $book = [];
 
-        $book['toc'] = $this->getBookToc((int)$bookId, (int)$paraId, $channelId, 2, 7);
+        $book['toc'] = $this->getBookToc((int) $bookId, (int) $paraId, $channelId, 2, 7);
         $channel = ChannelApi::getById($channelId);
         $studio = StudioApi::getById($channel['studio_id']);
         $book['categories'] = $chapter['category'];
-        $book['title']      = $chapter['title'];
-        $book['author']     = $channel['name'];
-        $book['studio']     = $studio;
-        $book['tags']       = [];
-
-        $book['pagination'] = $this->pagination((int)$bookId, (int)$paraId, $channelId);
+        $book['title'] = $chapter['title'];
+        $book['author'] = $channel['name'];
+        $book['studio'] = $studio;
+        $book['tags'] = [];
 
+        $book['pagination'] = $this->pagination((int) $bookId, (int) $paraId, $channelId);
 
         if (isset($notesMap)) {
             $book['content'] = $this->injectNoteMarkers($chapter['display'], $notesMap);
         } else {
             $book['content'] = $chapter['display'];
         }
-        $allChannels = $chapterService->publicChannels((int)$bookId, (int)$paraId);
+        $allChannels = $chapterService->publicChannels((int) $bookId, (int) $paraId);
         $commentaryChannels = array_filter($allChannels, function ($channel) {
             return $channel['type'] === 'commentary';
         });
@@ -150,18 +147,17 @@ class BookController extends Controller
         });
 
         $editor_link = config('mint.server.dashboard_base_path')
-            . "/workspace/tipitaka/chapter/{$id}?channel={$channelId}";
+            ."/workspace/tipitaka/chapter/{$id}?channel={$channelId}";
 
         $view = view('library.book.read', compact('book', 'channels', 'editor_link', 'commentaryChannels'));
 
         return $view;
     }
 
-
-
     private function loadBook(string $id)
     {
         $book = ProgressChapter::with('channel.owner')->find($id);
+
         return $book;
     }
 
@@ -169,6 +165,7 @@ class BookController extends Controller
     {
         $theme = $request->input('theme', 'light');
         session(['theme' => $theme]);
+
         return response()->json(['status' => 'success']);
     }
 
@@ -179,16 +176,17 @@ class BookController extends Controller
             $title = PaliText::where('book', $book->book)
                 ->where('paragraph', $book->para)->first()->toc;
         }
+
         return [
-            "id" => $book->uid,
-            "title" => $title,
-            "author" => $book->channel->name,
-            "publisher" => $book->channel->owner,
-            "type" => __('label.' . $book->channel->type),
-            "category_id" => 11,
-            "cover" => "/assets/images/cover/1/214.jpg",
-            "description" => $book->summary ?? "",
-            "language" => __('language.' . $book->channel->lang),
+            'id' => $book->uid,
+            'title' => $title,
+            'author' => $book->channel->name,
+            'publisher' => $book->channel->owner,
+            'type' => __('label.'.$book->channel->type),
+            'category_id' => 11,
+            'cover' => '/assets/images/cover/1/214.jpg',
+            'description' => $book->summary ?? '',
+            'language' => __('language.'.$book->channel->lang),
         ];
     }
 
@@ -197,7 +195,7 @@ class BookController extends Controller
         $currBook = $this->bookStart($book, $paragraph);
 
         $start = $currBook->paragraph;
-        $end   = $currBook->paragraph + $currBook->chapter_len - 1;
+        $end = $currBook->paragraph + $currBook->chapter_len - 1;
 
         $paliTexts = PaliText::where('book', $book)
             ->whereBetween('paragraph', [$start, $end])
@@ -205,6 +203,10 @@ class BookController extends Controller
             ->orderBy('paragraph')
             ->get();
 
+        if ($paliTexts->isEmpty()) {
+            return [];
+        }
+
         $chapters = ProgressChapter::where('book', $book)
             ->whereBetween('para', [$start, $end])
             ->where('channel_id', $channelId)
@@ -214,29 +216,74 @@ class BookController extends Controller
         // keyBy 建索引,map 里 O(1) 查找,完全避免 toArray() 序列化和 array_filter O(n×m) 扫描
         $chaptersIndexed = $chapters->keyBy('para');
 
-        return $paliTexts->map(function ($paliText) use ($chaptersIndexed, $channelId) {
-            $title    = $paliText->toc;
-            $summary  = '';
+        // 当前阅读章节的 toc id,用于高亮(active)与折叠展开(hide)
+        $currentId = "{$book}-{$paragraph}";
+
+        // 折叠逻辑:列表有序,父节点 = 之前最近的更小 level 节点
+        // 参见 AnthologyReadController::buildCollapsedToc()
+        $parents = [];  // id => parent_id|null
+        $stack = [];  // 祖先栈 [ ['id'=>..., 'level'=>...], ... ]
+        foreach ($paliTexts as $paliText) {
+            $id = "{$paliText->book}-{$paliText->paragraph}";
+            $level = (int) $paliText->level;
+            while (! empty($stack) && $stack[count($stack) - 1]['level'] >= $level) {
+                array_pop($stack);
+            }
+            $parents[$id] = empty($stack) ? null : $stack[count($stack) - 1]['id'];
+            $stack[] = ['id' => $id, 'level' => $level];
+        }
+
+        // 当前节点的祖先链
+        $ancestorSet = [];
+        $cursor = $currentId;
+        while (! empty($parents[$cursor])) {
+            $cursor = $parents[$cursor];
+            $ancestorSet[$cursor] = true;
+        }
+
+        // 需要展开子节点的集合 = 祖先链 + 当前节点
+        $expandParentSet = $ancestorSet;
+        $expandParentSet[$currentId] = true;
+
+        // 顶层 level(列表中最浅的一层,折叠模式下始终可见)
+        $topLevel = (int) $paliTexts->min('level');
+
+        return $paliTexts->map(function ($paliText) use ($chaptersIndexed, $channelId, $currentId, $parents, $expandParentSet, $topLevel) {
+            $id = "{$paliText->book}-{$paliText->paragraph}";
+            $level = (int) $paliText->level;
+            $title = $paliText->toc;
+            $summary = '';
             $progress = 0;
             $disabled = true;
 
             /** @var ProgressChapter|null $chapter */
             $chapter = $chaptersIndexed->get($paliText->paragraph);
             if ($chapter) {
-                if (!empty($chapter->title))   $title   = $chapter->title;
-                if (!empty($chapter->summary)) $summary = $chapter->summary;
-                $progress = (int)($chapter->progress * 100);
+                if (! empty($chapter->title)) {
+                    $title = $chapter->title;
+                }
+                if (! empty($chapter->summary)) {
+                    $summary = $chapter->summary;
+                }
+                $progress = (int) ($chapter->progress * 100);
                 $disabled = false;
             }
 
+            $parentId = $parents[$id];
+            // 折叠模式可见:顶层节点,或父节点在展开集合中(祖先链 / 当前节点的直接子节点)
+            $visible = $level === $topLevel
+                || ($parentId !== null && isset($expandParentSet[$parentId]));
+
             return [
-                'id'       => "{$paliText->book}-{$paliText->paragraph}",
-                'channel'  => $channelId,
-                'title'    => $title,
-                'summary'  => $summary,
+                'id' => $id,
+                'channel' => $channelId,
+                'title' => $title,
+                'summary' => $summary,
                 'progress' => $progress,
-                'level'    => (int)$paliText->level,
+                'level' => $level,
                 'disabled' => $disabled,
+                'active' => $id === $currentId,
+                'hide' => ! $visible,
             ];
         })->all();
     }
@@ -249,6 +296,7 @@ class BookController extends Controller
             ->first()->tagMaps->map(function ($tagMap) {
                 return $tagMap->tags;
             })->toArray();
+
         return $tags;
     }
 
@@ -259,10 +307,10 @@ class BookController extends Controller
             ->where('level', 1)
             ->orderBy('paragraph', 'desc')
             ->first();
+
         return $currBook;
     }
 
-
     public function pagination(int $book, int $para, string $channelId)
     {
         $currBook = $this->bookStart($book, $para);
@@ -275,10 +323,10 @@ class BookController extends Controller
             ->orderBy('paragraph')
             ->get();
         $curr = $paragraphs->firstWhere('paragraph', $para);
-        $current = $curr; //实际显示的段落
+        $current = $curr; // 实际显示的段落
         $endParagraph = $curr->paragraph + $curr->chapter_len - 1;
         if ($curr->chapter_strlen > $this->maxChapterLen) {
-            //太大了,修改结束位置 找到下一级
+            // 太大了,修改结束位置 找到下一级
             foreach ($paragraphs as $key => $paragraph) {
                 if ($paragraph->paragraph > $curr->paragraph) {
                     if ($paragraph->chapter_strlen <= $this->maxChapterLen) {
@@ -287,7 +335,7 @@ class BookController extends Controller
                         break;
                     }
                     if ($paragraph->level <= $curr->level) {
-                        //不能往下走了,就是它了
+                        // 不能往下走了,就是它了
                         $endParagraph = $paragraphs[$key - 1]->paragraph + $paragraphs[$key - 1]->chapter_len - 1;
                         $current = $paragraph;
                         break;
@@ -308,7 +356,7 @@ class BookController extends Controller
                 ->where('channel_id', $channelId)
                 ->first();
             if ($nextTranslation) {
-                if (!empty($nextTranslation->title)) {
+                if (! empty($nextTranslation->title)) {
                     $next['title'] = $nextTranslation->title;
                 } else {
                     $next['title'] = $nextPali->toc;
@@ -325,7 +373,7 @@ class BookController extends Controller
                 ->where('channel_id', $channelId)
                 ->first();
             if ($prevTranslation) {
-                if (!empty($prevTranslation->title)) {
+                if (! empty($prevTranslation->title)) {
                     $prev['title'] = $prevTranslation->title;
                 } else {
                     $prev['title'] = $prevPali->toc;
@@ -344,8 +392,10 @@ class BookController extends Controller
             ->where('level', $level)
             ->orderBy('paragraph')
             ->first();
+
         return $next ?? null;
     }
+
     public function prev($book, $paragraph, $level)
     {
         $prev = PaliText::where('book', $book)
@@ -356,6 +406,7 @@ class BookController extends Controller
 
         return $prev ?? null;
     }
+
     public function show2($id)
     {
         // Sample book data (replace with database query)

+ 26 - 0
api-v13/resources/css/modules/reader.css

@@ -233,6 +233,32 @@ body {
     border-left-color: #4dabf7;
 }
 
+/* TOC 折叠模式:默认隐藏 hide 项,.toc-expanded 时全部展开 */
+.toc-tree:not(.toc-expanded) .toc-hidden {
+    display: none;
+}
+
+.toc-toggle-all {
+    display: inline-flex;
+    align-items: center;
+    padding: 0 0 8px;
+    background: none;
+    border: none;
+    color: #206bc4;
+    font-size: 0.85rem;
+    cursor: pointer;
+}
+
+.dark-mode .toc-toggle-all {
+    color: #4dabf7;
+}
+
+/* 折叠时显示「展开全部」,展开时显示「折叠」 */
+.toc-tree.toc-expanded .toc-toggle-expand,
+.toc-tree:not(.toc-expanded) .toc-toggle-collapse {
+    display: none;
+}
+
 /* ══════════════════════════════════════════
    六、正文内容
    ══════════════════════════════════════════ */

+ 14 - 0
api-v13/resources/js/modules/reader.js

@@ -2,6 +2,20 @@
 
 export function initReader() {
     injectCommentaryMarkers();
+    initTocToggle();
+}
+
+// TOC 折叠/展开:点击按钮切换所在 .toc-tree 的 .toc-expanded 类
+// offcanvas 与侧边栏各有一份 toc,故对每个按钮分别绑定
+function initTocToggle() {
+    document.querySelectorAll('[data-toc-toggle]').forEach((btn) => {
+        btn.addEventListener('click', () => {
+            const tree = btn.closest('[data-toc-tree]');
+            if (tree) {
+                tree.classList.toggle('toc-expanded');
+            }
+        });
+    });
 }
 
 function injectCommentaryMarkers() {

+ 2 - 0
api-v13/resources/lang/en/library.php

@@ -65,6 +65,8 @@ return [
     'quality_level' => 'Quality Level',
     'other_versions' => 'Other Versions',
     'toc' => 'Table of Contents',
+    'expand_all' => 'Expand all',
+    'collapse_toc' => 'Collapse',
     'entry_info' => 'Entry Info',
     'category' => 'Category',
     'quality' => 'Quality',

+ 2 - 0
api-v13/resources/lang/my/library.php

@@ -65,6 +65,8 @@ return [
     'quality_level' => 'အရည်အသွေးအဆင့်',
     'other_versions' => 'အခြားဗားရှင်းများ',
     'toc' => 'မာတိကာ',
+    'expand_all' => 'အားလုံးဖြန့်ရန်',
+    'collapse_toc' => 'ခေါက်သိမ်းရန်',
     'entry_info' => 'ဝင်ခွင့်သတင်းအချက်အလက်',
     'category' => 'အမျိုးအစား',
     'quality' => 'အရည်အသွေး',

+ 2 - 0
api-v13/resources/lang/si/library.php

@@ -65,6 +65,8 @@ return [
     'quality_level' => 'ගුණාත්මක මට්ටම',
     'other_versions' => 'අනෙකුත් අනුවාද',
     'toc' => 'පටුනය',
+    'expand_all' => 'සියල්ල විදහන්න',
+    'collapse_toc' => 'හකුළන්න',
     'entry_info' => 'ඇතුළත්කිරීමේ තොරතුරු',
     'category' => 'කාණ්ඩය',
     'quality' => 'ගුණාත්මකභාවය',

+ 2 - 0
api-v13/resources/lang/th/library.php

@@ -65,6 +65,8 @@ return [
     'quality_level' => 'ระดับคุณภาพ',
     'other_versions' => 'เวอร์ชันอื่น',
     'toc' => 'สารบัญ',
+    'expand_all' => 'ขยายทั้งหมด',
+    'collapse_toc' => 'ย่อทั้งหมด',
     'entry_info' => 'ข้อมูลรายการ',
     'category' => 'หมวดหมู่',
     'quality' => 'คุณภาพ',

+ 3 - 1
api-v13/resources/lang/zh-Hans/library.php

@@ -65,6 +65,8 @@ return [
     'quality_level' => '质量等级',
     'other_versions' => '其他版本',
     'toc' => '目录',
+    'expand_all' => '展开全部',
+    'collapse_toc' => '折叠目录',
     'entry_info' => '条目信息',
     'category' => '分类',
     'quality' => '质量',
@@ -133,5 +135,5 @@ return [
     'no_toc' => '此书没有目录',
     'pāḷi' => '巴利原典',
     'aṭṭhakathā' => '义注',
-    'ṭīkā' => '复注'
+    'ṭīkā' => '复注',
 ];

+ 2 - 0
api-v13/resources/lang/zh-Hant/library.php

@@ -65,6 +65,8 @@ return [
     'quality_level' => '品質等級',
     'other_versions' => '其他版本',
     'toc' => '目錄',
+    'expand_all' => '展開全部',
+    'collapse_toc' => '摺疊目錄',
     'entry_info' => '詞條資訊',
     'category' => '分類',
     'quality' => '品質',

+ 21 - 8
api-v13/resources/views/library/book/toc.blade.php

@@ -1,13 +1,25 @@
 {{-- resources/views/library/book/toc.blade.php
      TOC 列表局部视图,在 offcanvas 和侧边栏中复用。
      变量:$toc array,$anthologyId(可选)
+     每个 item:active(当前章节高亮)、hide(折叠模式下隐藏的节点)。
+     折叠/展开由 .toc-tree 上的 .toc-expanded 类切换(见 reader.js / reader.css)。
 --}}
 @if(!empty($toc))
-<ul>
-    @foreach ($toc as $item)
-    <li class="toc_item toc-level-{{ $item['level'] }}
-               {{ ($item['active'] ?? false) ? 'toc-active' : ($item['disabled'] ? 'toc-disabled' : '') }}">
-        @if($item['active'] ?? false)
+@php $hasHidden = collect($toc)->contains(fn ($item) => $item['hide'] ?? false); @endphp
+<div class="toc-tree" data-toc-tree>
+    @if($hasHidden)
+    <button type="button" class="toc-toggle-all" data-toc-toggle>
+        <i class="ti ti-arrows-maximize me-1"></i>
+        <span class="toc-toggle-expand">{{ __('library.expand_all') }}</span>
+        <span class="toc-toggle-collapse">{{ __('library.collapse_toc') }}</span>
+    </button>
+    @endif
+    <ul>
+        @foreach ($toc as $item)
+        <li class="toc_item toc-level-{{ $item['level'] }}
+                   {{ ($item['active'] ?? false) ? 'toc-active' : ($item['disabled'] ? 'toc-disabled' : '') }}
+                   {{ ($item['hide'] ?? false) ? 'toc-hidden' : '' }}">
+            @if($item['active'] ?? false)
         <span title="{{ $item['title'] }}">{{ $item['title'] }}</span>
         @elseif(!$item['disabled'])
         @if(isset($anthologyId))
@@ -20,9 +32,10 @@
         @else
         <span title="{{ $item['title'] }}">{{ $item['title'] }}</span>
         @endif
-    </li>
-    @endforeach
-</ul>
+        </li>
+        @endforeach
+    </ul>
+</div>
 @else
 <div class="alert alert-warning">{{ __('library.no_toc') }}</div>
 @endif