Browse Source

Merge pull request #2420 from visuddhinanda/development

Development
visuddhinanda 4 weeks ago
parent
commit
25ff5e64b8

+ 290 - 117
api-v13/app/Http/Controllers/Library/BookController.php

@@ -2,33 +2,36 @@
 
 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;
+use Illuminate\Support\Collection;
+use Illuminate\Support\Facades\Log;
 
 class BookController extends Controller
 {
-    protected $maxChapterLen = 50000;
+    /**
+     * chapter 聚合显示的字符数阈值。
+     *
+     * ES 中每个 chapter 节点只保存「本节点 → 下一节点」之间的正文,选中含子
+     * chapter 的父节点时其自身文档往往只有标题。显示时按本阈值决定聚合粒度:
+     * chapter_strlen 小于该值的节点,连同其覆盖区间内的所有子 chapter 一并展示;
+     * 超过该值则向下钻取第一个不超过阈值的子 chapter。
+     */
+    protected $maxChapterStrlen = 30000;
+
     protected $minChapterLen = 100;
 
     /**
      * 构造函数,注入 OpenSearchService
-     *
-     * @param  \App\Services\OpenSearchService  $searchService
      */
     public function __construct(
         protected OpenSearchService $searchService,
@@ -39,16 +42,16 @@ class BookController extends Controller
     {
         $bookRaw = $this->loadBook($id);
 
-        if (!$bookRaw) {
+        if (! $bookRaw) {
             abort(404);
         }
 
-        //查询章节
+        // 查询章节
         $channelId = $bookRaw->channel_id; // 替换为具体的 channel_id 值
 
         $book = $this->getBookInfo($bookRaw);
         $book['contents'] = $this->getBookToc($bookRaw->book, $bookRaw->para, $channelId);
-
+        $book['book_title'] = $this->getBookTitle($bookRaw->book, $bookRaw->para, $channelId);
         // 获取其他版本
         $others = ProgressChapter::with('channel.owner')
             ->where('book', $bookRaw->book)
@@ -60,88 +63,89 @@ 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)
     {
 
         $channelId = $request->input('channel');
-        $openSearchId = "tipitaka_chapter_{$id}_{$channelId}";
 
-        try {
-            $chapter = HitItemDTO::fromArray($this->searchService->get($openSearchId))->toArray();
-        } catch (\Throwable $th) {
-            $chapter = [
-                'category' => [],
-                'title' => '',
-                'display' => ''
+        [$bookId, $paraId] = explode('-', $id);
+        $bookId = (int) $bookId;
+        $paraId = (int) $paraId;
 
-            ];
-        }
+        // 解析选中 chapter 的实际显示区间,并聚合区间内全部 chapter 节点的 ES 内容,
+        // 避免选中父 chapter 时仅显示一个标题。
+        $range = $this->resolveDisplayRange($bookId, $paraId);
+        $chapter = $this->fetchRangeContent($bookId, $channelId, $range['chapters'], $id);
 
-        [$bookId, $paraId] = explode('-', $id);
         if ($request->has('comm')) {
-            $currChapter = $this->paliTextService->getCurrChapter($bookId, $paraId);
-            $commentaries = $this->fetchCommentary($bookId, $paraId, $paraId + $currChapter->chapter_len - 1, $request->input('comm'));
+            // 注释范围与显示区间保持一致(聚合后可能跨多个段落)
+            $commentaries = $this->fetchCommentary($bookId, $range['start'], $range['end'], $request->input('comm'));
             // 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($bookId, $paraId, $channelId, 2, 7, [$range['start'], $range['end']]);
         $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['book_title'] = $this->getBookTitle($bookId, $paraId, $channelId);
 
+        $book['pagination'] = $this->pagination($bookId, $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 +154,114 @@ 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;
     }
 
+    /**
+     * 解析选中 chapter 的实际显示区间。
+     *
+     * ES 中每个 chapter 节点仅保存「本节点 → 下一节点」之间的正文,因此选中含
+     * 子 chapter 的父节点时其自身文档往往只有标题。为完整呈现内容,这里把选中
+     * chapter 覆盖区间内的所有 chapter 节点聚合为一个显示单元:
+     *  - 选中节点 chapter_strlen 不超过阈值:直接使用其覆盖区间
+     *    [paragraph, paragraph + chapter_len - 1];
+     *  - 否则向后下钻,找到第一个不超过阈值的子 chapter,以该子 chapter 的结束
+     *    段落作为区间终点(起点仍为选中段落,保留上层标题作为阅读上下文)。
+     *
+     * @return array{current: PaliText, start: int, end: int, chapters: Collection<int, PaliText>}
+     */
+    private function resolveDisplayRange(int $book, int $para): array
+    {
+        $currBook = $this->bookStart($book, $para);
+        $bookStart = $currBook->paragraph;
+        $bookEnd = $currBook->paragraph + $currBook->chapter_len - 1;
+
+        // 本书内全部 chapter 节点(level < 8,即 book/chapter/subhead 等可导航节点)
+        $paragraphs = PaliText::where('book', $book)
+            ->whereBetween('paragraph', [$bookStart, $bookEnd])
+            ->where('level', '<', 8)
+            ->orderBy('paragraph')
+            ->get();
+
+        $curr = $paragraphs->firstWhere('paragraph', $para);
+        $current = $curr;
+        $endParagraph = $curr->paragraph + $curr->chapter_len - 1;
+
+        if ($curr->chapter_strlen > $this->maxChapterStrlen) {
+            // 选中节点过大:向后下钻,找到第一个不超过阈值的子 chapter
+            foreach ($paragraphs as $key => $paragraph) {
+                if ($paragraph->paragraph <= $curr->paragraph) {
+                    continue;
+                }
+                if ($paragraph->chapter_strlen <= $this->maxChapterStrlen) {
+                    $endParagraph = $paragraph->paragraph + $paragraph->chapter_len - 1;
+                    $current = $paragraph;
+                    break;
+                }
+                if ($paragraph->level <= $curr->level) {
+                    // 已离开选中节点的子树,无法继续下钻,止步于上一个节点
+                    $endParagraph = $paragraphs[$key - 1]->paragraph + $paragraphs[$key - 1]->chapter_len - 1;
+                    $current = $paragraph;
+                    break;
+                }
+            }
+        }
+
+        $start = $curr->paragraph;
+        $end = $endParagraph;
+
+        // 区间内的全部 chapter 节点,用于聚合 ES 内容
+        $chapters = $paragraphs->filter(function ($paragraph) use ($start, $end) {
+            return $paragraph->paragraph >= $start && $paragraph->paragraph <= $end;
+        })->values();
+
+        return compact('current', 'start', 'end', 'chapters');
+    }
+
+    /**
+     * 聚合区间内全部 chapter 节点的 ES 内容。
+     *
+     * 逐个按 ES 文档 id(tipitaka_chapter_{book}-{paragraph}_{channel})获取并按段落
+     * 顺序拼接 display;缺失或获取失败的节点跳过。选中(即传入 $selectedId 的)
+     * 节点同时提供页面标题与分类。
+     *
+     * @param  Collection<int, PaliText>  $chapters
+     * @return array{display: string, title: string, category: array}
+     */
+    private function fetchRangeContent(int $book, string $channelId, $chapters, string $selectedId): array
+    {
+        $display = '';
+        $title = '';
+        $category = [];
+
+        foreach ($chapters as $chapter) {
+            $openSearchId = "tipitaka_chapter_{$book}-{$chapter->paragraph}_{$channelId}";
+
+            try {
+                $doc = HitItemDTO::fromArray($this->searchService->get($openSearchId))->toArray();
+            } catch (\Throwable $th) {
+                continue;
+            }
 
+            $display .= $doc['display'] ?? '';
+
+            if ("{$book}-{$chapter->paragraph}" === $selectedId) {
+                $title = $doc['title'] ?? '';
+                $category = $doc['category'] ?? [];
+            }
+        }
+
+        return compact('display', 'title', 'category');
+    }
 
     private function loadBook(string $id)
     {
         $book = ProgressChapter::with('channel.owner')->find($id);
+
         return $book;
     }
 
@@ -169,6 +269,7 @@ class BookController extends Controller
     {
         $theme = $request->input('theme', 'light');
         session(['theme' => $theme]);
+
         return response()->json(['status' => 'success']);
     }
 
@@ -179,31 +280,57 @@ 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),
         ];
     }
 
-    private function getBookToc(int $book, int $paragraph, string $channelId, $minLevel = 2, $maxLevel = 2): array
+    private function getBookTitle(int $book, int $paragraph, string $channelId)
+    {
+        $bookTopPara = $this->paliTextService->getBookPara($book, $paragraph)->paragraph;
+        $title = ProgressChapter::where('book', $book)
+            ->where('para', $bookTopPara)
+            ->where('channel_id', $channelId)
+            ->value('title');
+        if (empty($title)) {
+            $title = PaliText::where('book', $book)
+                ->where('paragraph', $bookTopPara)
+                ->value('toc');
+        }
+
+        return $title;
+    }
+
+    /**
+     * @param  array{0: int, 1: int}|null  $activeRange  实际显示的段落区间 [start, end];
+     *                                                   传入时区间内的所有 chapter 均高亮(active),
+     *                                                   用于聚合显示多个 chapter 的场景。不传则仅高亮选中段落。
+     */
+    private function getBookToc(int $book, int $paragraph, string $channelId, $minLevel = 2, $maxLevel = 2, ?array $activeRange = null): array
     {
         $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])
             ->whereBetween('level', [$minLevel, $maxLevel])
             ->orderBy('paragraph')
             ->get();
+        // Log::debug('toc', ['toc' => $paliTexts->toArray()]);
+        if ($paliTexts->isEmpty()) {
+            return [];
+        }
 
         $chapters = ProgressChapter::where('book', $book)
             ->whereBetween('para', [$start, $end])
@@ -214,31 +341,94 @@ 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];
+        }
+
+        // 高亮(active)集合:聚合显示时为区间内所有 chapter,否则仅选中段落
+        $activeSet = [];
+        foreach ($paliTexts as $paliText) {
+            $id = "{$paliText->book}-{$paliText->paragraph}";
+            $active = $activeRange !== null
+                ? ($paliText->paragraph >= $activeRange[0] && $paliText->paragraph <= $activeRange[1])
+                : ($id === $currentId);
+            if ($active) {
+                $activeSet[$id] = true;
+            }
+        }
+
+        // 需要展开子节点的集合 = 每个 active 节点及其祖先链。
+        // 聚合显示跨多级时,区间内各级 chapter 都需展开,其子级才能完整显示,
+        // 否则仅围绕单个当前节点展开,最多只能显示两级。
+        $expandParentSet = [];
+        foreach (array_keys($activeSet) as $activeId) {
+            $expandParentSet[$activeId] = true;
+            $cursor = $activeId;
+            while (! empty($parents[$cursor])) {
+                $cursor = $parents[$cursor];
+                $expandParentSet[$cursor] = true;
+            }
+        }
+
+        // 顶层 level(列表中最浅的一层,折叠模式下始终可见)
+        $topLevel = (int) $paliTexts->min('level');
+
+        $output = $paliTexts->map(function ($paliText) use ($chaptersIndexed, $channelId, $parents, $expandParentSet, $activeSet, $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]));
+
+            $active = isset($activeSet[$id]);
+
             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' => $active,
+                'hide' => ! $visible,
             ];
         })->all();
+
+        // Log::debug('toc output', ['data' => $output]);
+        return $output;
     }
 
     public function getBookCategory($book, $paragraph)
@@ -249,6 +439,7 @@ class BookController extends Controller
             ->first()->tagMaps->map(function ($tagMap) {
                 return $tagMap->tags;
             })->toArray();
+
         return $tags;
     }
 
@@ -259,46 +450,23 @@ 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);
-        $start = $currBook->paragraph;
-        $end = $currBook->paragraph + $currBook->chapter_len - 1;
-        // 查询起始段落
-        $paragraphs = PaliText::where('book', $book)
-            ->whereBetween('paragraph', [$start, $end])
-            ->where('level', '<', 8)
-            ->orderBy('paragraph')
-            ->get();
-        $curr = $paragraphs->firstWhere('paragraph', $para);
-        $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) {
-                        $endParagraph = $paragraph->paragraph + $paragraph->chapter_len - 1;
-                        $current = $paragraph;
-                        break;
-                    }
-                    if ($paragraph->level <= $curr->level) {
-                        //不能往下走了,就是它了
-                        $endParagraph = $paragraphs[$key - 1]->paragraph + $paragraphs[$key - 1]->chapter_len - 1;
-                        $current = $paragraph;
-                        break;
-                    }
-                }
-            }
-        }
-        $start = $curr->paragraph;
-        $end = $endParagraph;
-        $nextPali = $this->next($current->book, $current->paragraph, $current->level);
-        $prevPali = $this->prev($current->book, $current->paragraph, $current->level);
+        // 与正文显示共用同一区间解析,保证分页边界与实际展示内容一致
+        $range = $this->resolveDisplayRange($book, $para);
+        $start = $range['start'];
+        $end = $range['end'];
+
+        // next/prev 以显示区间为边界,而非某个节点的层级:
+        // 聚合显示子 chapter 时,下一页应是区间 end 之后的第一个可导航段落,
+        // 上一页应是区间 start 之前最近的可导航段落。若按 current 的 level 取同级节点,
+        // 会在章节边界处跳过父级标题页或落入子节点。
+        $nextPali = $this->nextChapter($book, $end);
+        $prevPali = $this->prevChapter($book, $start);
 
         $next = null;
         if ($nextPali) {
@@ -308,7 +476,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 +493,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;
@@ -337,25 +505,30 @@ class BookController extends Controller
         return compact('start', 'end', 'next', 'prev');
     }
 
-    public function next($book, $paragraph, $level)
+    /**
+     * 显示区间之后的第一个可导航 chapter 节点(level < 8)。
+     */
+    public function nextChapter(int $book, int $endParagraph): ?PaliText
     {
-        $next = PaliText::where('book', $book)
-            ->where('paragraph', '>', $paragraph)
-            ->where('level', $level)
+        return PaliText::where('book', $book)
+            ->where('paragraph', '>', $endParagraph)
+            ->where('level', '<', 8)
             ->orderBy('paragraph')
             ->first();
-        return $next ?? null;
     }
-    public function prev($book, $paragraph, $level)
+
+    /**
+     * 显示区间之前最近的一个可导航 chapter 节点(level < 8)。
+     */
+    public function prevChapter(int $book, int $startParagraph): ?PaliText
     {
-        $prev = PaliText::where('book', $book)
-            ->where('paragraph', '<', $paragraph)
-            ->where('level', $level)
+        return PaliText::where('book', $book)
+            ->where('paragraph', '<', $startParagraph)
+            ->where('level', '<', 8)
             ->orderBy('paragraph', 'desc')
             ->first();
-
-        return $prev ?? null;
     }
+
     public function show2($id)
     {
         // Sample book data (replace with database query)

+ 15 - 6
api-v13/app/Services/PaliTextService.php

@@ -11,11 +11,12 @@ class PaliTextService
     public function getParent(int $book, int $para)
     {
         $parent = PaliText::where('book', $book)
-            ->where('paragraph',  $para)->value('parent');
+            ->where('paragraph', $para)->value('parent');
 
         return $parent ? PaliText::where('book', $book)
-            ->where('paragraph',  $parent)->first() : null;
+            ->where('paragraph', $parent)->first() : null;
     }
+
     public function getCurrChapter(int $book, int $para)
     {
         $paragraph = PaliText::where('book', $book)
@@ -28,22 +29,26 @@ class PaliTextService
             return null;
         }
     }
+
     public function getBookPara(int $book, int $para)
     {
         $paragraph = PaliText::where('book', $book)
             ->where('paragraph', '<=', $para)
             ->where('level', 1)
             ->orderBy('paragraph', 'asc')->first();
-        if (!$paragraph) {
+        if (! $paragraph) {
             Log::warning('not found book ', ['book' => $book, 'para' => $para]);
+
             return null;
         }
+
         return $paragraph;
     }
+
     public function getParaCategoryTags(int $book, int $para): array
     {
         $bookPara = self::getBookPara($book, $para);
-        if (!$bookPara) {
+        if (! $bookPara) {
             return [];
         }
         if (Str::isUuid($bookPara->uid)) {
@@ -52,20 +57,24 @@ class PaliTextService
             Log::error('book uid not uuid', [
                 'book' => $book,
                 'para' => $para,
-                'uid' => $bookPara->uid
+                'uid' => $bookPara->uid,
             ]);
+
             return [];
         }
     }
+
     public function getParaInfo(int $book, int $para)
     {
         return PaliText::where('book', $book)
-            ->where('paragraph',  $para)
+            ->where('paragraph', $para)
             ->first();
     }
+
     public function getParaPathTitle(int $book, int $para)
     {
         $para = self::getParaInfo($book, $para);
+
         return array_map(function ($item) {
             return $item->title;
         }, json_decode($para->path));

+ 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;
+}
+
 /* ══════════════════════════════════════════
    六、正文内容
    ══════════════════════════════════════════ */

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

@@ -2,6 +2,21 @@
 
 export function initReader() {
     injectCommentaryMarkers();
+    injectEvaluateMarkers();
+    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() {
@@ -58,6 +73,53 @@ function injectCommentaryMarkers() {
         });
 }
 
+// 译文质量评估标注:把 <span class="evaluate evaluate-级别" title="…"> 就地
+// 升级为 Tufte 旁注。保留原 span(含背景色高亮)不动,在其后注入
+//   span.evaluate → label.margin-toggle → input.margin-toggle → span.marginnote
+// 复用既有旁注样式:桌面端 marginnote 自动浮到右栏,手机端点击 label 展开。
+// 用 marginnote(而非 sidenote)以避免 ::before 计数器的 [N] 编号。
+function injectEvaluateMarkers() {
+    let counter = 0;
+
+    document
+        .querySelectorAll('article.reader-body span.evaluate[title]')
+        .forEach((evalEl) => {
+            const info = evalEl.getAttribute('title').trim();
+            if (info === '') {
+                return;
+            }
+
+            counter++;
+            const id = `evaluate-${counter}`;
+
+            // label:手机端点击触发(桌面隐藏,marginnote 自动浮动)
+            const label = document.createElement('label');
+            label.htmlFor = id;
+            label.className = 'margin-toggle';
+            label.innerHTML = '<i class="ti ti-alert-triangle"></i>';
+
+            // checkbox:控制手机端展开
+            const checkbox = document.createElement('input');
+            checkbox.type = 'checkbox';
+            checkbox.className = 'margin-toggle';
+            checkbox.id = id;
+
+            // 旁注内容:取自 title,| 分隔的「问题简述/建议」分行显示
+            const note = document.createElement('span');
+            note.className = 'marginnote evaluate-note';
+            info.split('|').forEach((part, index) => {
+                if (index > 0) {
+                    note.appendChild(document.createElement('br'));
+                }
+                note.appendChild(document.createTextNode(part.trim()));
+            });
+
+            // 顺序:span.evaluate → label → input → span.marginnote
+            // (input 与 marginnote 相邻,CSS :checked + .marginnote 依赖此顺序)
+            evalEl.after(label, checkbox, note);
+        });
+}
+
 async function fetchCommentary(noteEl) {
     const uuid = noteEl.dataset.uuid;
 

+ 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' => 'คุณภาพ',

+ 2 - 0
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' => '质量',

+ 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' => '品質',

+ 2 - 2
api-v13/resources/views/library/book/read.blade.php

@@ -135,7 +135,7 @@
 {{-- TOC Offcanvas(mobile) --}}
 <div class="offcanvas offcanvas-start" tabindex="-1" id="tocDrawer">
     <div class="offcanvas-header">
-        <h5 class="offcanvas-title">{{ __('library.toc') }}</h5>
+        <h5 class="offcanvas-title">{{ $book['book_title'] }}</h5>
         <button type="button" class="btn-close" data-bs-dismiss="offcanvas"></button>
     </div>
     <div class="offcanvas-body">
@@ -150,7 +150,7 @@
         {{-- TOC 侧边栏(tablet+) --}}
         <div class="toc-sidebar card">
             <div class="card-body">
-                <h5>{{ __('library.toc') }}</h5>
+                <h5>{{ $book['book_title'] }}</h5>
                 @include('library.book.toc', ['toc' => $book['toc'] ?? []])
             </div>
         </div>

+ 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