reader.js 10 KB

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