reader.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. // resources/js/modules/reader.js
  2. import { initIssueMarkers } from './issue-popover.js';
  3. export function initReader() {
  4. applyAnnotationMode();
  5. numberAnnotations();
  6. injectCommentaryMarkers();
  7. injectEvaluateMarkers();
  8. initIssueMarkers();
  9. initTocToggle();
  10. initHashScroll();
  11. initAnnotationMode();
  12. }
  13. // 读取阅读偏好 cookie(与 read.blade.php 内联脚本的 setCookie 对应)。注意:该 cookie
  14. // 由前端 document.cookie 明文写入,不经过 Laravel 加密,只能在客户端读。
  15. function readCookie(name) {
  16. const value = `; ${document.cookie}`;
  17. const parts = value.split(`; ${name}=`);
  18. if (parts.length === 2) {
  19. return decodeURIComponent(parts.pop().split(';').shift());
  20. }
  21. return null;
  22. }
  23. // 把「注释」呈现模式(行内 / 段后)从 cookie 应用到正文根节点。
  24. function applyAnnotationMode() {
  25. const article = document.querySelector('article.reader-body');
  26. if (!article) {
  27. return;
  28. }
  29. article.dataset.annotationMode =
  30. readCookie('annotation_mode') === 'footnote' ? 'footnote' : 'inline';
  31. }
  32. // 处理 URL hash(#354 / #94-354 / #para-354):滚动到对应段落并加高亮底色
  33. function initHashScroll() {
  34. const scrollToParagraph = (paragraph, smooth = false) => {
  35. const el = document.getElementById(`para-${paragraph}`);
  36. if (!el) {
  37. return;
  38. }
  39. document
  40. .querySelectorAll('.reader-para-anchor')
  41. .forEach((node) => node.classList.remove('reader-para-anchor'));
  42. el.classList.add('reader-para-anchor');
  43. el.scrollIntoView({ block: 'start', behavior: smooth ? 'smooth' : 'auto' });
  44. };
  45. // 统一解析为段落号:取最后一个 '-' 之后的数字,兼容 #354 与 #94-354
  46. const parseHash = (hash) => {
  47. if (!hash || hash === '#') {
  48. return null;
  49. }
  50. const paragraph = parseInt(hash.replace(/^#/, '').split('-').pop(), 10);
  51. return Number.isInteger(paragraph) && paragraph > 0 ? paragraph : null;
  52. };
  53. window.addEventListener('hashchange', () => {
  54. const paragraph = parseHash(window.location.hash);
  55. if (paragraph !== null) {
  56. scrollToParagraph(paragraph, true);
  57. }
  58. });
  59. const paragraph = parseHash(window.location.hash);
  60. if (paragraph !== null) {
  61. scrollToParagraph(paragraph);
  62. }
  63. }
  64. // TOC 折叠/展开:点击按钮切换所在 .toc-tree 的 .toc-expanded 类
  65. // offcanvas 与侧边栏各有一份 toc,故对每个按钮分别绑定
  66. function initTocToggle() {
  67. document.querySelectorAll('[data-toc-toggle]').forEach((btn) => {
  68. btn.addEventListener('click', () => {
  69. const tree = btn.closest('[data-toc-tree]');
  70. if (tree) {
  71. tree.classList.toggle('toc-expanded');
  72. }
  73. });
  74. });
  75. }
  76. // 注释编号:按「段」分组,给正文角标 .sidenote-number 与段后 .anno-footnote 分别
  77. // 编号 [1][2]…,二者一一对应(参照 wikipali-mobile 的 numberPara)。段后脚注的编号
  78. // <span class="anno-fn-num"> 由 JS 动态补进 label。
  79. function numberAnnotations() {
  80. document
  81. .querySelectorAll('article.reader-body div[data-para]')
  82. .forEach((para) => {
  83. para.querySelectorAll('.sidenote-number').forEach((marker, i) => {
  84. marker.dataset.idx = String(i + 1);
  85. });
  86. para.querySelectorAll('.anno-footnote').forEach((fn, i) => {
  87. fn.dataset.idx = String(i + 1);
  88. const label = fn.querySelector('.anno-fn-label');
  89. if (label && !label.querySelector('.anno-fn-num')) {
  90. const num = document.createElement('span');
  91. num.className = 'anno-fn-num';
  92. num.textContent = `[${i + 1}]`;
  93. num.dataset.idx = String(i + 1);
  94. label.insertBefore(num, label.firstChild);
  95. }
  96. });
  97. });
  98. }
  99. // 段后模式下的互跳:点正文角标 [N] → 滚到对应脚注;点脚注编号 [N] → 滚回正文角标。
  100. // 行内模式不挂此监听,保留 label 的原生 checkbox 展开行为。
  101. function initAnnotationMode() {
  102. const article = document.querySelector('article.reader-body');
  103. if (!article || article.dataset.annotationMode !== 'footnote') {
  104. return;
  105. }
  106. const flashAnno = (el) => {
  107. if (!el) {
  108. return;
  109. }
  110. el.classList.add('anno-highlight');
  111. setTimeout(() => el.classList.remove('anno-highlight'), 2200);
  112. };
  113. article.addEventListener('click', (e) => {
  114. const marker = e.target.closest('.sidenote-number');
  115. if (marker) {
  116. const para = marker.closest('div[data-para]');
  117. const fn =
  118. para &&
  119. para.querySelector(
  120. `.anno-footnote[data-idx="${marker.dataset.idx}"]`
  121. );
  122. if (fn) {
  123. e.preventDefault();
  124. fn.scrollIntoView({ block: 'center', behavior: 'smooth' });
  125. flashAnno(fn);
  126. }
  127. return;
  128. }
  129. const fnNum = e.target.closest('.anno-fn-num');
  130. if (fnNum) {
  131. const fn = fnNum.closest('.anno-footnote');
  132. const para = fn && fn.closest('div[data-para]');
  133. const marker =
  134. para &&
  135. para.querySelector(
  136. `.sidenote-number[data-idx="${fnNum.dataset.idx}"]`
  137. );
  138. if (marker) {
  139. e.preventDefault();
  140. marker.scrollIntoView({
  141. block: 'center',
  142. behavior: 'smooth',
  143. });
  144. flashAnno(marker);
  145. }
  146. }
  147. });
  148. }
  149. function injectCommentaryMarkers() {
  150. let counter = 0;
  151. document
  152. .querySelectorAll('div.sentence[data-note-id]')
  153. .forEach((sentenceEl) => {
  154. const uid = sentenceEl.dataset.noteId;
  155. counter++;
  156. const id = `commentary-${counter}`;
  157. // checkbox:控制展开,紧跟在 sentence 后
  158. const checkbox = document.createElement('input');
  159. checkbox.type = 'checkbox';
  160. checkbox.className = 'commentary-toggle';
  161. checkbox.id = id;
  162. // label(icon):行内,插在句子文字末尾
  163. const label = document.createElement('label');
  164. label.htmlFor = id;
  165. label.className = 'commentary-icon';
  166. label.innerHTML = '<i class="ti ti-message-circle"></i>';
  167. // 注释块:紧跟在 checkbox 后(CSS 相邻选择器依赖此顺序)
  168. const note = document.createElement('div');
  169. note.className = 'commentary-note';
  170. note.dataset.uuid = uid;
  171. note.dataset.loaded = 'false';
  172. // label 插入句子内文字末尾(行内不打断文字流)
  173. const innerSpan = sentenceEl.querySelector(':scope > span');
  174. (innerSpan ?? sentenceEl).appendChild(label);
  175. // sentence 后:先插 note,再插 checkbox(after 逆序)
  176. // 最终顺序:div.sentence → input.commentary-toggle → div.commentary-note
  177. sentenceEl.after(note);
  178. sentenceEl.after(checkbox);
  179. // 点击时懒加载
  180. checkbox.addEventListener('change', async () => {
  181. if (!checkbox.checked) {
  182. return;
  183. }
  184. if (note.dataset.loaded === 'true') {
  185. return;
  186. }
  187. note.innerHTML =
  188. '<span class="text-muted small">加载中…</span>';
  189. await fetchCommentary(note);
  190. });
  191. });
  192. }
  193. // 译文质量评估标注:把 <span class="evaluate evaluate-级别" title="…"> 就地
  194. // 升级为 Tufte 旁注。保留原 span(含背景色高亮)不动,在其后注入
  195. // span.evaluate → label.margin-toggle → input.margin-toggle → span.marginnote
  196. // 复用既有旁注样式:桌面端 marginnote 自动浮到右栏,手机端点击 label 展开。
  197. // 用 marginnote(而非 sidenote)以避免 ::before 计数器的 [N] 编号。
  198. function injectEvaluateMarkers() {
  199. let counter = 0;
  200. document
  201. .querySelectorAll('article.reader-body span.evaluate[title]')
  202. .forEach((evalEl) => {
  203. const info = evalEl.getAttribute('title').trim();
  204. if (info === '') {
  205. return;
  206. }
  207. counter++;
  208. const id = `evaluate-${counter}`;
  209. // label:手机端点击触发(桌面隐藏,marginnote 自动浮动)
  210. const label = document.createElement('label');
  211. label.htmlFor = id;
  212. label.className = 'margin-toggle';
  213. label.innerHTML = '<i class="ti ti-alert-triangle"></i>';
  214. // checkbox:控制手机端展开
  215. const checkbox = document.createElement('input');
  216. checkbox.type = 'checkbox';
  217. checkbox.className = 'margin-toggle';
  218. checkbox.id = id;
  219. // 旁注内容:取自 title,| 分隔的「问题简述/建议」分行显示
  220. const note = document.createElement('span');
  221. note.className = 'marginnote evaluate-note';
  222. info.split('|').forEach((part, index) => {
  223. if (index > 0) {
  224. note.appendChild(document.createElement('br'));
  225. }
  226. note.appendChild(document.createTextNode(part.trim()));
  227. });
  228. // 顺序:span.evaluate → label → input → span.marginnote
  229. // (input 与 marginnote 相邻,CSS :checked + .marginnote 依赖此顺序)
  230. evalEl.after(label, checkbox, note);
  231. });
  232. }
  233. async function fetchCommentary(noteEl) {
  234. const uuid = noteEl.dataset.uuid;
  235. try {
  236. const res = await fetch(`/api/v2/sentence/${uuid}?format=html`);
  237. if (!res.ok) {
  238. throw new Error(res.status);
  239. }
  240. const json = await res.json();
  241. if (!json.ok) {
  242. throw new Error('api error');
  243. }
  244. noteEl.innerHTML = json.data.html;
  245. noteEl.dataset.loaded = 'true';
  246. } catch {
  247. noteEl.innerHTML = '<span class="text-muted small">加载失败</span>';
  248. }
  249. }