BookController.php 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589
  1. <?php
  2. namespace App\Http\Controllers\Library;
  3. use App\Http\Api\ChannelApi;
  4. use App\Http\Api\StudioApi;
  5. use App\Http\Controllers\Controller;
  6. use App\Models\PaliText;
  7. use App\Models\ProgressChapter;
  8. use App\Models\Sentence;
  9. use App\Services\ChapterService;
  10. use App\Services\PaliContentService;
  11. use App\Services\PaliTextService;
  12. use App\Services\TipitakaCatalogService;
  13. use App\Services\V3\PaliTextService as PaliTexts;
  14. use Illuminate\Http\RedirectResponse;
  15. use Illuminate\Http\Request;
  16. use Illuminate\Support\Facades\Cookie;
  17. use Illuminate\Support\Str;
  18. use Illuminate\View\View;
  19. class BookController extends Controller
  20. {
  21. /**
  22. * chapter 聚合显示的字符数阈值。
  23. *
  24. * ES 中每个 chapter 节点只保存「本节点 → 下一节点」之间的正文,选中含子
  25. * chapter 的父节点时其自身文档往往只有标题。显示时按本阈值决定聚合粒度:
  26. * chapter_strlen 小于该值的节点,连同其覆盖区间内的所有子 chapter 一并展示;
  27. * 超过该值则向下钻取第一个不超过阈值的子 chapter。
  28. */
  29. protected $maxChapterStrlen = 30000;
  30. protected $minChapterLen = 100;
  31. /**
  32. * 构造函数,注入文本、段落内容与三藏目录服务
  33. */
  34. public function __construct(
  35. protected PaliTextService $paliTextService,
  36. protected PaliContentService $paliContentService,
  37. protected TipitakaCatalogService $catalog,
  38. protected PaliTexts $paliTexts,
  39. ) {}
  40. /**
  41. * 作品详情:某 channel 的某部作品(work_id = book_titles.sn)。该 channel 没收录这部作品时 404。
  42. */
  43. public function show(string $channel, int $sn): View
  44. {
  45. $work = $this->catalog->work($sn);
  46. $channelModel = $this->catalog->channel($channel);
  47. abort_unless($work && $channelModel, 404);
  48. $progress = $this->catalog->channelProgress($channel)["{$work['book']}-{$work['para']}"] ?? null;
  49. abort_unless($progress, 404);
  50. $channelInfo = [
  51. 'uid' => $channel,
  52. 'name' => $channelModel->name,
  53. 'type' => $channelModel->type,
  54. 'lang' => $channelModel->lang,
  55. 'owner' => $channelModel->owner,
  56. ];
  57. $book = $this->catalog->bookCard($work, $channelInfo, $progress);
  58. $book['channel'] = $channelInfo;
  59. $book['pali_title'] = $work['title'];
  60. $book['updated_at'] = $progress['updated_at'];
  61. $book['read_url'] = route('library.tipitaka.channels.work.read', ['channel' => $channel, 'sn' => $sn]);
  62. $book['contents'] = $this->getBookToc($work['book'], $work['para'], $channel, 2, 2, null, [$work['para'], $work['end']]);
  63. $names = $this->catalog->localNames($this->catalog->categories(), Cookie::get('language') ?? 'en');
  64. $book['categories'] = $work['category_id'] === null ? [] : array_map(fn ($c) => [
  65. 'name' => $names[$c['name']] ?? $c['name'],
  66. 'url' => route('library.tipitaka.channels.category', ['channel' => $channel, 'id' => $c['id']]),
  67. ], $this->catalog->categoryPath($work['category_id']));
  68. $otherVersions = array_map(fn ($c) => [
  69. ...$c,
  70. 'url' => route('library.tipitaka.channels.work', ['channel' => $c['uid'], 'sn' => $sn]),
  71. ], $this->catalog->workChannels($work, $channel));
  72. // 同一分类下、本 channel 也收录了的其他作品
  73. $channelProgress = $this->catalog->channelProgress($channel);
  74. $relatedWorks = $work['category_id'] === null ? [] : collect($this->catalog->worksInCategory($work['category_id']))
  75. ->filter(fn ($w) => $w['sn'] !== $sn && isset($channelProgress["{$w['book']}-{$w['para']}"]))
  76. ->take(5)
  77. ->map(fn ($w) => [
  78. 'title' => $channelProgress["{$w['book']}-{$w['para']}"]['title'] ?: $w['title'],
  79. 'url' => route('library.tipitaka.channels.work', ['channel' => $channel, 'sn' => $w['sn']]),
  80. ])
  81. ->values()
  82. ->all();
  83. return view('library.tipitaka.show', compact('book', 'otherVersions', 'relatedWorks'));
  84. }
  85. /**
  86. * 阅读入口:作品区间内第一个本 channel 有译文的章节(level 2–7),没有就从作品起点读。
  87. * 目标随翻译进度变化,所以是 302。
  88. */
  89. public function readWork(string $channel, int $sn): RedirectResponse
  90. {
  91. $work = $this->catalog->work($sn);
  92. abort_unless($work && ChannelApi::getById($channel), 404);
  93. $chapterParas = PaliText::where('book', $work['book'])
  94. ->whereBetween('paragraph', [$work['para'], $work['end']])
  95. ->whereBetween('level', [2, 7])
  96. ->pluck('paragraph');
  97. $first = ProgressChapter::where('channel_id', $channel)
  98. ->where('book', $work['book'])
  99. ->whereIn('para', $chapterParas)
  100. ->min('para');
  101. return redirect()->route('library.tipitaka.channels.chapter', [
  102. 'channel' => $channel,
  103. 'chapter' => "{$work['book']}-".($first ?? $work['para']),
  104. ]);
  105. }
  106. /**
  107. * 旧地址 /library/tipitaka/{book}-{para}/read?channel=x → 新地址(301)。
  108. * 没带 channel 的读巴利原文;其余查询参数(如 comm)原样带过去。
  109. */
  110. public function legacyRead(Request $request, string $id): RedirectResponse
  111. {
  112. $channelId = $request->query('channel') ?: ChannelApi::getSysChannel('_System_Pali_VRI_');
  113. abort_unless(Str::isUuid($channelId) && ChannelApi::getById($channelId), 404);
  114. return redirect()->route('library.tipitaka.channels.chapter', [
  115. 'channel' => $channelId,
  116. 'chapter' => $id,
  117. ...$request->except('channel'),
  118. ], 301);
  119. }
  120. /**
  121. * 旧地址 /library/tipitaka/{progress_chapters.uid} → 该 channel 的作品详情(301)。
  122. */
  123. public function legacyShow(string $id): RedirectResponse
  124. {
  125. $row = ProgressChapter::find($id);
  126. $work = $row ? $this->catalog->workAt((int) $row->book, (int) $row->para) : null;
  127. abort_unless($work, 404);
  128. return redirect()->route('library.tipitaka.channels.work', ['channel' => $row->channel_id, 'sn' => $work['sn']], 301);
  129. }
  130. private function fetchCommentary(int $book, int $paraStart, int $paraEnd, string $channelId)
  131. {
  132. $notes = Sentence::where('book_id', $book)
  133. ->whereBetween('paragraph', [$paraStart, $paraEnd])
  134. ->where('channel_uid', $channelId)
  135. ->select(['uid', 'book_id', 'paragraph', 'word_start', 'word_end'])->get()->toArray();
  136. return $notes;
  137. }
  138. private function injectNoteMarkers(string $html, array $notesMap): string
  139. {
  140. if (empty($notesMap)) {
  141. return $html;
  142. }
  143. return preg_replace_callback(
  144. '/(<div class=\'sentence\' data-sid=\'([^\']+)\')/',
  145. function ($matches) use ($notesMap) {
  146. $sid = $matches[2];
  147. if (! isset($notesMap[$sid])) {
  148. return $matches[0];
  149. }
  150. $uid = $notesMap[$sid];
  151. return $matches[1]." data-note-id='{$uid}'";
  152. },
  153. $html
  154. );
  155. }
  156. /**
  157. * 阅读页 /library/tipitaka/channels/{channel}/chapter/{book}-{para}。
  158. */
  159. public function read(Request $request, string $channel, string $chapter): View
  160. {
  161. $channelId = $channel;
  162. $id = $chapter;
  163. // 读的是巴利原文(旧地址没带 channel 时也落到这里),提示可切换版本
  164. $isDefaultChannel = $channelId === ChannelApi::getSysChannel('_System_Pali_VRI_');
  165. abort_unless(preg_match('/^\d+-\d+$/', $id), 404);
  166. [$bookId, $paraId] = explode('-', $id);
  167. $bookId = (int) $bookId;
  168. $paraId = (int) $paraId;
  169. $channel = ChannelApi::getById($channelId);
  170. abort_unless($channel, 404);
  171. // 解析选中 chapter 的实际显示区间(起始/终止段落号),再按段落号聚合 HTML,
  172. // 避免选中父 chapter 时仅显示一个标题。
  173. $range = $this->resolveDisplayRange($bookId, $paraId);
  174. $chapter = $this->fetchRangeContent($bookId, $channelId, $range['start'], $range['end'], $paraId);
  175. if ($request->has('comm')) {
  176. // 注释范围与显示区间保持一致(聚合后可能跨多个段落)
  177. $commentaries = $this->fetchCommentary($bookId, $range['start'], $range['end'], $request->input('comm'));
  178. // sid 格式:{book_id}-{paragraph}-{word_start}-{word_end}
  179. $notesMap = collect($commentaries)->keyBy(function ($note) {
  180. return "{$note['book_id']}-{$note['paragraph']}-{$note['word_start']}-{$note['word_end']}";
  181. })->map(fn ($note) => $note['uid'])->toArray();
  182. }
  183. $chapterService = app(ChapterService::class);
  184. $book = [];
  185. $book['toc'] = $this->getBookToc($bookId, $paraId, $channelId, 2, 7, [$range['start'], $range['end']]);
  186. $studio = StudioApi::getById($channel['studio_id']);
  187. $book['categories'] = $chapter['category'];
  188. $book['title'] = $chapter['title'];
  189. $book['author'] = $channel['name'];
  190. $book['is_original'] = in_array($channel['type'], ['original', 'wbw'], true);
  191. $book['studio'] = $studio;
  192. $book['tags'] = [];
  193. $book['book_title'] = $this->getBookTitle($bookId, $paraId, $channelId);
  194. $book['pagination'] = $this->pagination($bookId, $paraId, $channelId);
  195. if (isset($notesMap)) {
  196. $book['content'] = $this->injectNoteMarkers($chapter['display'], $notesMap);
  197. } else {
  198. $book['content'] = $chapter['display'];
  199. }
  200. $allChannels = $chapterService->publicChannels((int) $bookId, (int) $paraId);
  201. $commentaryChannels = array_filter($allChannels, function ($channel) {
  202. return $channel['type'] === 'commentary';
  203. });
  204. $channels = array_map(fn ($channel) => [
  205. ...$channel,
  206. 'url' => route('library.tipitaka.channels.chapter', ['channel' => $channel['id'], 'chapter' => $id, ...$request->query()]),
  207. ], array_filter($allChannels, function ($channel) {
  208. return $channel['type'] !== 'commentary';
  209. }));
  210. $work = $this->catalog->workAt($bookId, $paraId);
  211. $book['work_url'] = $work
  212. ? route('library.tipitaka.channels.work', ['channel' => $channelId, 'sn' => $work['sn']])
  213. : null;
  214. $editor_link = config('mint.server.dashboard_base_path')
  215. ."/workspace/tipitaka/chapter/{$id}?channel={$channelId}";
  216. $view = view('library.book.read', compact('book', 'channels', 'editor_link', 'commentaryChannels', 'isDefaultChannel', 'channelId'));
  217. return $view;
  218. }
  219. /**
  220. * 解析选中 chapter 的实际显示区间,返回区间的起始与终止段落号。
  221. *
  222. * ES 中每个 chapter 节点仅保存「本节点 → 下一节点」之间的正文,因此选中含
  223. * 子 chapter 的父节点时其自身文档往往只有标题。为完整呈现内容,这里按阈值
  224. * 决定显示区间终点:
  225. * - 选中节点 chapter_strlen 不超过阈值:终点为
  226. * [paragraph + chapter_len - 1];
  227. * - 否则向后下钻,找到第一个不超过阈值的子 chapter,以该子 chapter 的结束
  228. * 段落作为区间终点(起点仍为选中段落,保留上层标题作为阅读上下文)。
  229. *
  230. * @return array{start: int, end: int}
  231. */
  232. private function resolveDisplayRange(int $book, int $para): array
  233. {
  234. // 标题段取自缓存的经文静态数据(V3\PaliTextService),不查库
  235. $currBook = $this->paliTexts->bookStart($book, $para);
  236. abort_if($currBook === null, 404);
  237. $bookStart = $currBook['para'];
  238. $bookEnd = $currBook['para'] + $currBook['chapter_len'] - 1;
  239. // 本书内全部 chapter 节点(level < 8,即 book/chapter/subhead 等可导航节点)
  240. $paragraphs = [];
  241. foreach ($this->paliTexts->headings($book) as $paragraph => $heading) {
  242. if ($paragraph >= $bookStart && $paragraph <= $bookEnd) {
  243. $paragraphs[] = ['paragraph' => $paragraph] + $heading;
  244. }
  245. }
  246. $curr = collect($paragraphs)->firstWhere('paragraph', $para);
  247. // 选中的不是可导航的 chapter 节点(如正文段落 level=100)
  248. abort_if($curr === null, 404);
  249. $endParagraph = $curr['paragraph'] + $curr['chapter_len'] - 1;
  250. if ($curr['chapter_strlen'] > $this->maxChapterStrlen) {
  251. // 选中节点过大:向后下钻,找到第一个不超过阈值的子 chapter
  252. foreach ($paragraphs as $key => $paragraph) {
  253. if ($paragraph['paragraph'] <= $curr['paragraph']) {
  254. continue;
  255. }
  256. if ($paragraph['chapter_strlen'] <= $this->maxChapterStrlen) {
  257. $endParagraph = $paragraph['paragraph'] + $paragraph['chapter_len'] - 1;
  258. break;
  259. }
  260. if ($paragraph['level'] <= $curr['level']) {
  261. // 已离开选中节点的子树,无法继续下钻,止步于上一个节点
  262. $endParagraph = $paragraphs[$key - 1]['paragraph'] + $paragraphs[$key - 1]['chapter_len'] - 1;
  263. break;
  264. }
  265. }
  266. }
  267. return [
  268. 'start' => $curr['paragraph'],
  269. 'end' => $endParagraph,
  270. ];
  271. }
  272. /**
  273. * 聚合区间内全部段落的阅读模式 HTML。
  274. *
  275. * 交给 PaliContentService::readChapters():按平铺章节缓存,命中时每章一次 GET、不查库,
  276. * 没命中的一起渲染。章节标题不进缓存:优先取 ProgressChapter.title,回退到巴利标题(toc)。
  277. *
  278. * @return array{display: string, title: string, category: array}
  279. */
  280. private function fetchRangeContent(int $book, string $channelId, int $start, int $end, int $selectedPara): array
  281. {
  282. $display = $this->paliContentService->readChapters($book, $start, $end, $channelId, 'html');
  283. $title = ProgressChapter::where('book', $book)
  284. ->where('para', $selectedPara)
  285. ->where('channel_id', $channelId)
  286. ->value('title');
  287. if (empty($title)) {
  288. $title = $this->paliTexts->heading($book, $selectedPara)['toc'] ?? null;
  289. }
  290. return [
  291. 'display' => $display,
  292. 'title' => $title ?? '',
  293. 'category' => [],
  294. ];
  295. }
  296. public function toggleTheme(Request $request)
  297. {
  298. $theme = $request->input('theme', 'light');
  299. session(['theme' => $theme]);
  300. return response()->json(['status' => 'success']);
  301. }
  302. private function getBookTitle(int $book, int $paragraph, string $channelId)
  303. {
  304. $bookTopPara = $this->paliTextService->getBookPara($book, $paragraph)->paragraph;
  305. $title = ProgressChapter::where('book', $book)
  306. ->where('para', $bookTopPara)
  307. ->where('channel_id', $channelId)
  308. ->value('title');
  309. if (empty($title)) {
  310. $title = PaliText::where('book', $book)
  311. ->where('paragraph', $bookTopPara)
  312. ->value('toc');
  313. }
  314. return $title;
  315. }
  316. /**
  317. * @param array{0: int, 1: int}|null $activeRange 实际显示的段落区间 [start, end];
  318. * 传入时区间内的所有 chapter 均高亮(active),
  319. * 用于聚合显示多个 chapter 的场景。不传则仅高亮选中段落。
  320. * @param array{0: int, 1: int}|null $bounds 目录的段落范围;不传取所在 level-1 节点(整本书)。
  321. * 作品详情页传作品区间(一个 level-1 节点里可能有多部作品)。
  322. */
  323. private function getBookToc(int $book, int $paragraph, string $channelId, $minLevel = 2, $maxLevel = 2, ?array $activeRange = null, ?array $bounds = null): array
  324. {
  325. if ($bounds !== null) {
  326. [$start, $end] = $bounds;
  327. } else {
  328. $currBook = $this->bookStart($book, $paragraph);
  329. $start = $currBook->paragraph;
  330. $end = $currBook->paragraph + $currBook->chapter_len - 1;
  331. }
  332. $paliTexts = PaliText::where('book', $book)
  333. ->whereBetween('paragraph', [$start, $end])
  334. ->whereBetween('level', [$minLevel, $maxLevel])
  335. ->orderBy('paragraph')
  336. ->get();
  337. // Log::debug('toc', ['toc' => $paliTexts->toArray()]);
  338. if ($paliTexts->isEmpty()) {
  339. return [];
  340. }
  341. $chapters = ProgressChapter::where('book', $book)
  342. ->whereBetween('para', [$start, $end])
  343. ->where('channel_id', $channelId)
  344. ->orderBy('para')
  345. ->get();
  346. // keyBy 建索引,map 里 O(1) 查找,完全避免 toArray() 序列化和 array_filter O(n×m) 扫描
  347. $chaptersIndexed = $chapters->keyBy('para');
  348. // 当前阅读章节的 toc id,用于高亮(active)与折叠展开(hide)
  349. $currentId = "{$book}-{$paragraph}";
  350. // 折叠逻辑:列表有序,父节点 = 之前最近的更小 level 节点
  351. // 参见 AnthologyReadController::buildCollapsedToc()
  352. $parents = []; // id => parent_id|null
  353. $stack = []; // 祖先栈 [ ['id'=>..., 'level'=>...], ... ]
  354. foreach ($paliTexts as $paliText) {
  355. $id = "{$paliText->book}-{$paliText->paragraph}";
  356. $level = (int) $paliText->level;
  357. while (! empty($stack) && $stack[count($stack) - 1]['level'] >= $level) {
  358. array_pop($stack);
  359. }
  360. $parents[$id] = empty($stack) ? null : $stack[count($stack) - 1]['id'];
  361. $stack[] = ['id' => $id, 'level' => $level];
  362. }
  363. // 高亮(active)集合:聚合显示时为区间内所有 chapter,否则仅选中段落
  364. $activeSet = [];
  365. foreach ($paliTexts as $paliText) {
  366. $id = "{$paliText->book}-{$paliText->paragraph}";
  367. $active = $activeRange !== null
  368. ? ($paliText->paragraph >= $activeRange[0] && $paliText->paragraph <= $activeRange[1])
  369. : ($id === $currentId);
  370. if ($active) {
  371. $activeSet[$id] = true;
  372. }
  373. }
  374. // 需要展开子节点的集合 = 每个 active 节点及其祖先链。
  375. // 聚合显示跨多级时,区间内各级 chapter 都需展开,其子级才能完整显示,
  376. // 否则仅围绕单个当前节点展开,最多只能显示两级。
  377. $expandParentSet = [];
  378. foreach (array_keys($activeSet) as $activeId) {
  379. $expandParentSet[$activeId] = true;
  380. $cursor = $activeId;
  381. while (! empty($parents[$cursor])) {
  382. $cursor = $parents[$cursor];
  383. $expandParentSet[$cursor] = true;
  384. }
  385. }
  386. // 顶层 level(列表中最浅的一层,折叠模式下始终可见)
  387. $topLevel = (int) $paliTexts->min('level');
  388. $output = $paliTexts->map(function ($paliText) use ($chaptersIndexed, $channelId, $parents, $expandParentSet, $activeSet, $topLevel) {
  389. $id = "{$paliText->book}-{$paliText->paragraph}";
  390. $level = (int) $paliText->level;
  391. $title = $paliText->toc;
  392. $summary = '';
  393. $progress = 0;
  394. $disabled = true;
  395. /** @var ProgressChapter|null $chapter */
  396. $chapter = $chaptersIndexed->get($paliText->paragraph);
  397. if ($chapter) {
  398. if (! empty($chapter->title)) {
  399. $title = $chapter->title;
  400. }
  401. if (! empty($chapter->summary)) {
  402. $summary = $chapter->summary;
  403. }
  404. $progress = (int) ($chapter->progress * 100);
  405. $disabled = false;
  406. }
  407. $parentId = $parents[$id];
  408. // 折叠模式可见:顶层节点,或父节点在展开集合中(祖先链 / 当前节点的直接子节点)
  409. $visible = $level === $topLevel
  410. || ($parentId !== null && isset($expandParentSet[$parentId]));
  411. $active = isset($activeSet[$id]);
  412. return [
  413. 'id' => $id,
  414. 'channel' => $channelId,
  415. 'title' => $title,
  416. 'summary' => $summary,
  417. 'progress' => $progress,
  418. 'level' => $level,
  419. 'disabled' => $disabled,
  420. 'active' => $active,
  421. 'hide' => ! $visible,
  422. ];
  423. })->all();
  424. // Log::debug('toc output', ['data' => $output]);
  425. return $output;
  426. }
  427. public function getBookCategory($book, $paragraph)
  428. {
  429. $tags = PaliText::with('tagMaps.tags')
  430. ->where('book', $book)
  431. ->where('paragraph', $paragraph)
  432. ->first()->tagMaps->map(function ($tagMap) {
  433. return $tagMap->tags;
  434. })->toArray();
  435. return $tags;
  436. }
  437. private function bookStart($book, $paragraph)
  438. {
  439. $currBook = PaliText::where('book', $book)
  440. ->where('paragraph', '<=', $paragraph)
  441. ->where('level', 1)
  442. ->orderBy('paragraph', 'desc')
  443. ->first();
  444. return $currBook;
  445. }
  446. public function pagination(int $book, int $para, string $channelId)
  447. {
  448. // 与正文显示共用同一区间解析,保证分页边界与实际展示内容一致
  449. $range = $this->resolveDisplayRange($book, $para);
  450. $start = $range['start'];
  451. $end = $range['end'];
  452. // next/prev 以显示区间为边界,而非某个节点的层级:
  453. // 聚合显示子 chapter 时,下一页应是区间 end 之后的第一个可导航段落,
  454. // 上一页应是区间 start 之前最近的可导航段落。若按 current 的 level 取同级节点,
  455. // 会在章节边界处跳过父级标题页或落入子节点。
  456. $nextPali = $this->nextChapter($book, $end);
  457. $prevPali = $this->prevChapter($book, $start);
  458. $next = null;
  459. if ($nextPali) {
  460. $nextTranslation = ProgressChapter::with('channel.owner')
  461. ->where('book', $nextPali->book)
  462. ->where('para', $nextPali->paragraph)
  463. ->where('channel_id', $channelId)
  464. ->first();
  465. if ($nextTranslation) {
  466. if (! empty($nextTranslation->title)) {
  467. $next['title'] = $nextTranslation->title;
  468. } else {
  469. $next['title'] = $nextPali->toc;
  470. }
  471. $next['id'] = "{$nextPali->book}-{$nextPali->paragraph}";
  472. }
  473. }
  474. $prev = null;
  475. if ($prevPali) {
  476. $prevTranslation = ProgressChapter::with('channel.owner')
  477. ->where('book', $prevPali->book)
  478. ->where('para', $prevPali->paragraph)
  479. ->where('channel_id', $channelId)
  480. ->first();
  481. if ($prevTranslation) {
  482. if (! empty($prevTranslation->title)) {
  483. $prev['title'] = $prevTranslation->title;
  484. } else {
  485. $prev['title'] = $prevPali->toc;
  486. }
  487. $prev['id'] = "{$prevPali->book}-{$prevPali->paragraph}";
  488. }
  489. }
  490. return compact('start', 'end', 'next', 'prev');
  491. }
  492. /**
  493. * 显示区间之后的第一个可导航 chapter 节点(level < 8)。
  494. */
  495. public function nextChapter(int $book, int $endParagraph): ?PaliText
  496. {
  497. return PaliText::where('book', $book)
  498. ->where('paragraph', '>', $endParagraph)
  499. ->where('level', '<', 8)
  500. ->orderBy('paragraph')
  501. ->first();
  502. }
  503. /**
  504. * 显示区间之前最近的一个可导航 chapter 节点(level < 8)。
  505. */
  506. public function prevChapter(int $book, int $startParagraph): ?PaliText
  507. {
  508. return PaliText::where('book', $book)
  509. ->where('paragraph', '<', $startParagraph)
  510. ->where('level', '<', 8)
  511. ->orderBy('paragraph', 'desc')
  512. ->first();
  513. }
  514. }