reader.js 55 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762
  1. let currentCategory = '';
  2. let currentDoc = '';
  3. let docList = [];
  4. let currentMarkdownContent = ''; // 保存当前文档的markdown源码
  5. let isEditMode = false; // 是否处于编辑模式
  6. let savedScrollPosition = 0; // 保存的滚动位置
  7. let currentScrollObserver = null; // 保存当前的滚动监听器
  8. // DOM 元素缓存
  9. const DOM = {
  10. loading: null,
  11. content: null,
  12. docNav: null,
  13. toc: null,
  14. leftSidebar: null,
  15. rightSidebar: null,
  16. editBtn: null,
  17. editorContainer: null,
  18. markdownEditor: null,
  19. editorDocName: null,
  20. navPrev: null,
  21. navNext: null,
  22. contentArea: null,
  23. searchContainer: null,
  24. searchToggleBtn: null,
  25. searchInput: null,
  26. searchBtn: null,
  27. searchResults: null,
  28. closeSearchBoxBtn: null,
  29. saveBtn: null,
  30. cancelBtn: null,
  31. backToTopBtn: null,
  32. docNavigation: null,
  33. toggleLeft: null,
  34. toggleRight: null,
  35. categoryNameSpan: null,
  36. currentDocResults: null,
  37. otherDocResults: null
  38. };
  39. // 配置 marked
  40. marked.setOptions({
  41. highlight: function(code, lang) {
  42. if (lang && hljs.getLanguage(lang)) {
  43. try {
  44. const result = hljs.highlight(code, { language: lang });
  45. return result.value;
  46. } catch (err) {
  47. console.error('Highlight error:', err);
  48. }
  49. }
  50. // 自动检测语言
  51. const autoResult = hljs.highlightAuto(code);
  52. return autoResult.value;
  53. },
  54. breaks: true,
  55. gfm: true
  56. });
  57. // 从 URL 获取参数
  58. function getQueryParams() {
  59. const params = new URLSearchParams(window.location.search);
  60. return {
  61. category: params.get('category'),
  62. doc: params.get('doc')
  63. };
  64. }
  65. // 根据文档路径获取展示名称(仅保留最后一段)
  66. function getDocDisplayName(docName) {
  67. if (!docName || typeof docName !== 'string') {
  68. return '';
  69. }
  70. const segments = docName.split(/[\\\/]/);
  71. const name = segments.pop();
  72. return name || docName;
  73. }
  74. // ========== 工具函数 ==========
  75. // URL 编码路径(支持子目录)
  76. function encodeDocPath(docName) {
  77. return docName.split('/').map(part => encodeURIComponent(part)).join('/');
  78. }
  79. // API 错误处理
  80. async function handleApiError(response, defaultMessage) {
  81. const errorData = await response.json().catch(() => ({}));
  82. throw new Error(errorData.error || `${defaultMessage} (${response.status})`);
  83. }
  84. // 确保 DOM 元素已缓存
  85. function ensureDOM(key, id) {
  86. if (!DOM[key]) DOM[key] = document.getElementById(id);
  87. return DOM[key];
  88. }
  89. // 通用防抖函数
  90. function debounce(func, wait) {
  91. let timeout;
  92. return function executedFunction(...args) {
  93. clearTimeout(timeout);
  94. timeout = setTimeout(() => func.apply(this, args), wait);
  95. };
  96. }
  97. // 高亮代码块
  98. function highlightCodeBlock(block) {
  99. block.classList.add('hljs');
  100. // 如果已经高亮过了,跳过
  101. if (block.querySelector('span')) return;
  102. const lang = block.className.match(/language-(\w+)/)?.[1];
  103. try {
  104. const highlighted = (lang && hljs.getLanguage(lang))
  105. ? hljs.highlight(block.textContent, { language: lang })
  106. : hljs.highlightAuto(block.textContent);
  107. block.innerHTML = highlighted.value;
  108. if (highlighted.language) {
  109. block.classList.add(`language-${highlighted.language}`);
  110. }
  111. } catch (err) {
  112. console.error('Error highlighting code:', err);
  113. }
  114. }
  115. // 加载文档列表
  116. async function loadDocList() {
  117. const { category } = getQueryParams();
  118. if (!category) {
  119. window.location.href = '/';
  120. return;
  121. }
  122. currentCategory = category;
  123. if (!DOM.categoryNameSpan) DOM.categoryNameSpan = document.querySelector('#category-title .category-name');
  124. if (DOM.categoryNameSpan) {
  125. DOM.categoryNameSpan.textContent = category;
  126. }
  127. try {
  128. const response = await fetch(`/api/category/${encodeURIComponent(category)}`);
  129. if (!response.ok) throw new Error('获取文档列表失败');
  130. const categoryData = await response.json();
  131. docList = categoryData.docs.map(doc => ({
  132. ...doc,
  133. displayName: getDocDisplayName(doc.name)
  134. }));
  135. renderDocNav(docList);
  136. // 加载第一篇文档(或 URL 指定的文档)
  137. const { doc } = getQueryParams();
  138. const firstDoc = doc || docList[0]?.name;
  139. if (firstDoc) {
  140. loadDocument(firstDoc);
  141. }
  142. } catch (err) {
  143. console.error('Error loading doc list:', err);
  144. showError('加载文档列表失败');
  145. }
  146. }
  147. // 渲染文档导航
  148. function renderDocNav(docs) {
  149. const nav = DOM.docNav || document.getElementById('doc-nav');
  150. if (!DOM.docNav) DOM.docNav = nav;
  151. nav.innerHTML = '';
  152. docs.forEach(doc => {
  153. const item = document.createElement('div');
  154. item.className = `nav-item level-${doc.level}`;
  155. item.dataset.docName = doc.name;
  156. const link = document.createElement('a');
  157. link.href = '#';
  158. link.className = 'nav-link';
  159. link.textContent = doc.displayName || getDocDisplayName(doc.name);
  160. link.title = doc.name;
  161. item.appendChild(link);
  162. nav.appendChild(item);
  163. });
  164. // 使用事件委托 - 只添加一个监听器
  165. nav.removeEventListener('click', handleNavClick);
  166. nav.addEventListener('click', handleNavClick);
  167. }
  168. // 导航点击处理函数
  169. function handleNavClick(e) {
  170. if (e.target.classList.contains('nav-link')) {
  171. e.preventDefault();
  172. const item = e.target.parentElement;
  173. const docName = item.dataset.docName;
  174. if (docName) {
  175. loadDocument(docName);
  176. updateURL(currentCategory, docName);
  177. // 更新活动状态 - 使用缓存的查询结果
  178. const navItems = DOM.docNav.querySelectorAll('.nav-item');
  179. navItems.forEach(el => el.classList.toggle('active', el === item));
  180. }
  181. }
  182. }
  183. // 加载文档内容
  184. async function loadDocument(docName, scrollToText = null) {
  185. ensureDOM('loading', 'loading');
  186. ensureDOM('content', 'markdown-content');
  187. DOM.loading.style.display = 'flex';
  188. DOM.content.innerHTML = '';
  189. try {
  190. const encodedDocName = encodeDocPath(docName);
  191. const response = await fetch(`/api/doc/${encodeURIComponent(currentCategory)}/${encodedDocName}`);
  192. if (!response.ok) {
  193. await handleApiError(response, '加载失败');
  194. }
  195. const data = await response.json();
  196. // 验证数据有效性
  197. if (!data.content || typeof data.content !== 'string') {
  198. throw new Error('文档内容格式错误');
  199. }
  200. currentDoc = docName;
  201. currentMarkdownContent = data.content; // 保存markdown源码
  202. // 渲染 Markdown
  203. const html = marked.parse(data.content);
  204. DOM.content.innerHTML = html;
  205. // 处理图片路径(将相对路径转换为API路径)
  206. DOM.content.querySelectorAll('img').forEach(img => {
  207. const src = img.getAttribute('src');
  208. if (src && !src.match(/^https?:\/\//)) {
  209. img.setAttribute('data-original-src', src);
  210. img.src = `/api/image/${encodeURIComponent(currentCategory)}/${src}`;
  211. }
  212. });
  213. // 代码块高亮
  214. DOM.content.querySelectorAll('pre code').forEach(highlightCodeBlock);
  215. // 为所有代码块添加复制按钮
  216. addCopyButtonsToCodeBlocks();
  217. // 生成 TOC
  218. generateTOC();
  219. // 更新文档导航(上一页/下一页)
  220. updateDocNavigation();
  221. // 更新活动文档 - 使用 toggle 优化
  222. if (DOM.docNav) {
  223. const navItems = DOM.docNav.querySelectorAll('.nav-item');
  224. navItems.forEach(el => el.classList.toggle('active', el.dataset.docName === docName));
  225. }
  226. DOM.loading.style.display = 'none';
  227. // 如果指定了要滚动到的文本,等待渲染完成后滚动
  228. if (scrollToText) {
  229. setTimeout(() => {
  230. scrollToSearchMatch(scrollToText);
  231. }, 100);
  232. }
  233. } catch (err) {
  234. console.error('Error loading document:', err);
  235. DOM.loading.style.display = 'none';
  236. showError(`加载文档失败:${err.message || '请稍后重试'}`);
  237. }
  238. }
  239. // 生成 TOC
  240. function generateTOC() {
  241. ensureDOM('toc', 'toc');
  242. ensureDOM('content', 'markdown-content');
  243. // 先清空旧的TOC内容
  244. DOM.toc.innerHTML = '';
  245. const headings = DOM.content.querySelectorAll('h1, h2, h3, h4, h5, h6');
  246. if (headings.length === 0) {
  247. DOM.toc.innerHTML = '<p class="toc-empty">本文档没有标题</p>';
  248. return;
  249. }
  250. // 创建标题 ID 映射
  251. const headingMap = new Map();
  252. headings.forEach((heading, index) => {
  253. // 给标题添加 ID
  254. if (!heading.id) {
  255. heading.id = `heading-${index}`;
  256. }
  257. const level = parseInt(heading.tagName.substring(1));
  258. const link = document.createElement('a');
  259. link.href = `#${heading.id}`;
  260. link.className = `toc-link toc-level-${level}`;
  261. link.textContent = heading.textContent;
  262. headingMap.set(heading.id, heading);
  263. DOM.toc.appendChild(link);
  264. });
  265. // 使用事件委托 - 只添加一个监听器
  266. DOM.toc.removeEventListener('click', handleTocClick);
  267. DOM.toc.addEventListener('click', (e) => handleTocClick(e, headingMap));
  268. // 监听滚动,高亮当前标题
  269. setupScrollSpy(headings);
  270. }
  271. // TOC 点击处理函数
  272. function handleTocClick(e, headingMap) {
  273. if (e.target.classList.contains('toc-link')) {
  274. e.preventDefault();
  275. const headingId = e.target.getAttribute('href').substring(1);
  276. const heading = headingMap.get(headingId);
  277. if (heading) {
  278. heading.scrollIntoView({ behavior: 'smooth', block: 'start' });
  279. // 更新活动状态
  280. const tocLinks = DOM.toc.querySelectorAll('.toc-link');
  281. tocLinks.forEach(el => el.classList.toggle('active', el === e.target));
  282. }
  283. }
  284. }
  285. // 滚动监听
  286. function setupScrollSpy(headings) {
  287. // 清理之前的 observer
  288. if (currentScrollObserver) {
  289. currentScrollObserver.disconnect();
  290. currentScrollObserver = null;
  291. }
  292. // 如果没有标题,直接返回
  293. if (!headings || headings.length === 0) {
  294. return;
  295. }
  296. let activeLink = null;
  297. const observer = new IntersectionObserver((entries) => {
  298. entries.forEach(entry => {
  299. if (entry.isIntersecting) {
  300. const id = entry.target.id;
  301. const link = DOM.toc.querySelector(`.toc-link[href="#${id}"]`);
  302. if (link && link !== activeLink) {
  303. // 只在需要时更新,减少 DOM 操作
  304. if (activeLink) activeLink.classList.remove('active');
  305. link.classList.add('active');
  306. activeLink = link;
  307. }
  308. }
  309. });
  310. }, {
  311. rootMargin: '-100px 0px -80% 0px',
  312. threshold: 0
  313. });
  314. headings.forEach(heading => observer.observe(heading));
  315. // 保存当前的 observer 以便后续清理
  316. currentScrollObserver = observer;
  317. }
  318. // 更新 URL
  319. function updateURL(category, doc) {
  320. const url = new URL(window.location);
  321. url.searchParams.set('category', category);
  322. url.searchParams.set('doc', doc);
  323. window.history.pushState({}, '', url);
  324. }
  325. // 更新文档导航(上一页/下一页)
  326. function updateDocNavigation() {
  327. // 缓存 DOM 元素
  328. if (!DOM.navPrev) DOM.navPrev = document.getElementById('nav-prev');
  329. if (!DOM.navNext) DOM.navNext = document.getElementById('nav-next');
  330. if (!DOM.navPrev || !DOM.navNext || docList.length === 0) return;
  331. if (!DOM.docNavigation) DOM.docNavigation = document.getElementById('doc-navigation');
  332. if (!DOM.docNavigation) return;
  333. // 找到当前文档在列表中的索引
  334. const currentIndex = docList.findIndex(doc => doc.name === currentDoc);
  335. if (currentIndex === -1) {
  336. DOM.navPrev.style.display = 'none';
  337. DOM.navNext.style.display = 'none';
  338. DOM.docNavigation.className = 'doc-navigation';
  339. return;
  340. }
  341. const hasPrev = currentIndex > 0;
  342. const hasNext = currentIndex < docList.length - 1;
  343. // 辅助函数:设置导航按钮
  344. const setupNavButton = (button, doc) => {
  345. if (doc) {
  346. button.style.display = 'flex';
  347. const displayName = doc.displayName || getDocDisplayName(doc.name);
  348. button.querySelector('.nav-doc-name').textContent = displayName;
  349. button.onclick = () => {
  350. loadDocument(doc.name);
  351. updateURL(currentCategory, doc.name);
  352. // 滚动到顶部
  353. if (!DOM.contentArea) DOM.contentArea = document.getElementById('content-area');
  354. if (DOM.contentArea) {
  355. DOM.contentArea.scrollTo({ top: 0, behavior: 'smooth' });
  356. }
  357. };
  358. } else {
  359. button.style.display = 'none';
  360. }
  361. };
  362. // 设置上一页和下一页按钮
  363. setupNavButton(DOM.navPrev, hasPrev ? docList[currentIndex - 1] : null);
  364. setupNavButton(DOM.navNext, hasNext ? docList[currentIndex + 1] : null);
  365. // 根据导航按钮状态添加类,用于CSS定位
  366. if (hasPrev && hasNext) {
  367. DOM.docNavigation.className = 'doc-navigation has-both';
  368. } else if (hasPrev) {
  369. DOM.docNavigation.className = 'doc-navigation has-prev-only';
  370. } else if (hasNext) {
  371. DOM.docNavigation.className = 'doc-navigation has-next-only';
  372. } else {
  373. DOM.docNavigation.className = 'doc-navigation';
  374. }
  375. }
  376. // 显示错误
  377. function showError(message) {
  378. if (!DOM.content) DOM.content = document.getElementById('markdown-content');
  379. if (DOM.content) {
  380. DOM.content.innerHTML = `<div class="error-message">${message}</div>`;
  381. }
  382. }
  383. // 切换侧边栏(移动端)
  384. function setupSidebarToggles() {
  385. if (!DOM.toggleLeft) DOM.toggleLeft = document.getElementById('toggle-left');
  386. if (!DOM.toggleRight) DOM.toggleRight = document.getElementById('toggle-right');
  387. const toggleLeft = DOM.toggleLeft;
  388. const toggleRight = DOM.toggleRight;
  389. // 使用 DOM 缓存
  390. if (!DOM.leftSidebar) DOM.leftSidebar = document.getElementById('left-sidebar');
  391. if (!DOM.rightSidebar) DOM.rightSidebar = document.getElementById('right-sidebar');
  392. // 移动端/平板初始化:默认折叠侧边栏
  393. if (window.innerWidth <= 768) {
  394. DOM.leftSidebar.classList.add('collapsed');
  395. DOM.rightSidebar.classList.add('collapsed');
  396. } else if (window.innerWidth <= 1024) {
  397. // 平板:只折叠右侧栏
  398. DOM.rightSidebar.classList.add('collapsed');
  399. }
  400. // 监听窗口大小变化
  401. window.addEventListener('resize', () => {
  402. if (window.innerWidth <= 768) {
  403. // 移动端:确保左右侧边栏都折叠
  404. if (!DOM.leftSidebar.classList.contains('collapsed')) {
  405. DOM.leftSidebar.classList.add('collapsed');
  406. }
  407. if (!DOM.rightSidebar.classList.contains('collapsed')) {
  408. DOM.rightSidebar.classList.add('collapsed');
  409. }
  410. } else if (window.innerWidth <= 1024) {
  411. // 平板:只折叠右侧栏,展开左侧栏
  412. DOM.leftSidebar.classList.remove('collapsed');
  413. if (!DOM.rightSidebar.classList.contains('collapsed')) {
  414. DOM.rightSidebar.classList.add('collapsed');
  415. }
  416. } else {
  417. // 桌面端:展开所有侧边栏
  418. DOM.leftSidebar.classList.remove('collapsed');
  419. DOM.rightSidebar.classList.remove('collapsed');
  420. }
  421. });
  422. toggleLeft.onclick = (e) => {
  423. e.stopPropagation();
  424. // 如果右侧栏展开,先隐藏它
  425. if (!DOM.rightSidebar.classList.contains('collapsed')) {
  426. DOM.rightSidebar.classList.add('collapsed');
  427. }
  428. DOM.leftSidebar.classList.toggle('collapsed');
  429. };
  430. toggleRight.onclick = (e) => {
  431. e.stopPropagation();
  432. // 如果左侧栏展开,先隐藏它
  433. if (!DOM.leftSidebar.classList.contains('collapsed')) {
  434. DOM.leftSidebar.classList.add('collapsed');
  435. }
  436. DOM.rightSidebar.classList.toggle('collapsed');
  437. };
  438. // 点击侧边栏外部时隐藏所有已展开的侧边栏(仅在移动端和平板)
  439. document.addEventListener('click', (e) => {
  440. // 仅在移动端和平板上启用此功能
  441. if (window.innerWidth > 1024) return;
  442. const isClickInsideLeftSidebar = DOM.leftSidebar.contains(e.target);
  443. const isClickInsideRightSidebar = DOM.rightSidebar.contains(e.target);
  444. const isToggleButton = e.target.closest('#toggle-left') || e.target.closest('#toggle-right');
  445. // 如果点击的不是侧边栏内部,也不是切换按钮,则隐藏所有展开的侧边栏
  446. if (!isClickInsideLeftSidebar && !isClickInsideRightSidebar && !isToggleButton) {
  447. if (!DOM.leftSidebar.classList.contains('collapsed')) {
  448. DOM.leftSidebar.classList.add('collapsed');
  449. }
  450. if (!DOM.rightSidebar.classList.contains('collapsed')) {
  451. DOM.rightSidebar.classList.add('collapsed');
  452. }
  453. }
  454. });
  455. }
  456. // 搜索功能
  457. function initSearch() {
  458. // 初始化搜索相关的DOM缓存
  459. if (!DOM.searchContainer) DOM.searchContainer = document.getElementById('search-container');
  460. if (!DOM.searchToggleBtn) DOM.searchToggleBtn = document.getElementById('search-toggle-btn');
  461. if (!DOM.searchInput) DOM.searchInput = document.getElementById('search-input');
  462. if (!DOM.searchBtn) DOM.searchBtn = document.getElementById('search-btn');
  463. if (!DOM.searchResults) DOM.searchResults = document.getElementById('search-results');
  464. if (!DOM.closeSearchBoxBtn) DOM.closeSearchBoxBtn = document.getElementById('close-search-box');
  465. // 检查元素是否存在
  466. if (!DOM.searchContainer || !DOM.searchToggleBtn || !DOM.searchInput || !DOM.searchBtn || !DOM.searchResults || !DOM.closeSearchBoxBtn) {
  467. console.error('Search elements not found:', {
  468. searchContainer: !!DOM.searchContainer,
  469. searchToggleBtn: !!DOM.searchToggleBtn,
  470. searchInput: !!DOM.searchInput,
  471. searchBtn: !!DOM.searchBtn,
  472. searchResults: !!DOM.searchResults,
  473. closeSearchBoxBtn: !!DOM.closeSearchBoxBtn
  474. });
  475. return;
  476. }
  477. const searchContainer = DOM.searchContainer;
  478. const searchToggleBtn = DOM.searchToggleBtn;
  479. const searchInput = DOM.searchInput;
  480. const searchBtn = DOM.searchBtn;
  481. const searchResults = DOM.searchResults;
  482. const closeSearchBoxBtn = DOM.closeSearchBoxBtn;
  483. let searchTimeout;
  484. const SEARCH_HISTORY_KEY = 'cjydocs_search_history';
  485. // 保存搜索历史到localStorage
  486. const saveSearchHistory = (query) => {
  487. if (!query || query.trim().length < 2) return;
  488. try {
  489. let history = JSON.parse(localStorage.getItem(SEARCH_HISTORY_KEY) || '{}');
  490. history[currentCategory] = query;
  491. localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(history));
  492. } catch (err) {
  493. console.error('Failed to save search history:', err);
  494. }
  495. };
  496. // 搜索函数
  497. const performSearch = async () => {
  498. const query = searchInput.value.trim();
  499. if (query.length < 2) {
  500. searchResults.style.display = 'none';
  501. return;
  502. }
  503. // 保存搜索历史
  504. saveSearchHistory(query);
  505. try {
  506. const response = await fetch(
  507. `/api/search/${encodeURIComponent(currentCategory)}?q=${encodeURIComponent(query)}&currentDoc=${encodeURIComponent(currentDoc)}`
  508. );
  509. if (!response.ok) {
  510. await handleApiError(response, '搜索失败');
  511. }
  512. const data = await response.json();
  513. displaySearchResults(data);
  514. searchResults.style.display = 'block';
  515. } catch (err) {
  516. console.error('Search error:', err);
  517. displaySearchError(err.message || '搜索失败,请稍后重试');
  518. }
  519. };
  520. // 加载搜索历史
  521. const loadSearchHistory = () => {
  522. try {
  523. const history = JSON.parse(localStorage.getItem(SEARCH_HISTORY_KEY) || '{}');
  524. const lastQuery = history[currentCategory];
  525. if (lastQuery) {
  526. searchInput.value = lastQuery;
  527. // 自动搜索上次的内容
  528. performSearch();
  529. }
  530. } catch (err) {
  531. console.error('Failed to load search history:', err);
  532. }
  533. };
  534. // 清除其他分类的搜索历史
  535. const clearOtherCategoryHistory = () => {
  536. try {
  537. let history = JSON.parse(localStorage.getItem(SEARCH_HISTORY_KEY) || '{}');
  538. // 只保留当前分类
  539. history = { [currentCategory]: history[currentCategory] || '' };
  540. localStorage.setItem(SEARCH_HISTORY_KEY, JSON.stringify(history));
  541. } catch (err) {
  542. console.error('Failed to clear search history:', err);
  543. }
  544. };
  545. // 切换搜索框显示/隐藏
  546. searchToggleBtn.addEventListener('click', (e) => {
  547. e.stopPropagation();
  548. const isActive = searchContainer.classList.toggle('active');
  549. if (isActive) {
  550. // 加载搜索历史
  551. loadSearchHistory();
  552. // 聚焦到搜索框
  553. setTimeout(() => searchInput.focus(), 100);
  554. } else {
  555. // 隐藏搜索结果
  556. searchResults.style.display = 'none';
  557. }
  558. });
  559. // 输入时实时搜索(防抖) - 500ms 减少 API 调用
  560. searchInput.addEventListener('input', debounce(performSearch, 500));
  561. // 点击搜索按钮
  562. searchBtn.addEventListener('click', performSearch);
  563. // 按回车搜索
  564. searchInput.addEventListener('keypress', (e) => {
  565. if (e.key === 'Enter') {
  566. performSearch();
  567. }
  568. });
  569. // 关闭搜索框按钮
  570. closeSearchBoxBtn.addEventListener('click', (e) => {
  571. e.stopPropagation();
  572. searchContainer.classList.remove('active');
  573. searchResults.style.display = 'none';
  574. });
  575. // 点击搜索结果外部关闭
  576. searchResults.addEventListener('click', (e) => {
  577. // 如果点击的是搜索结果容器本身(即遮罩背景),关闭搜索
  578. if (e.target === searchResults) {
  579. searchResults.style.display = 'none';
  580. }
  581. });
  582. // 点击外部关闭
  583. document.addEventListener('click', (e) => {
  584. if (!searchResults.contains(e.target) &&
  585. !searchInput.contains(e.target) &&
  586. !searchBtn.contains(e.target) &&
  587. !searchContainer.contains(e.target) &&
  588. !searchToggleBtn.contains(e.target)) {
  589. searchResults.style.display = 'none';
  590. }
  591. });
  592. // 初始化时清除其他分类的历史
  593. clearOtherCategoryHistory();
  594. }
  595. // 显示搜索错误
  596. function displaySearchError(message) {
  597. if (!DOM.currentDocResults) DOM.currentDocResults = document.getElementById('current-doc-results');
  598. if (!DOM.otherDocResults) DOM.otherDocResults = document.getElementById('other-docs-results');
  599. const currentDocSection = DOM.currentDocResults ? DOM.currentDocResults.querySelector('.results-list') : null;
  600. const otherDocsSection = DOM.otherDocResults ? DOM.otherDocResults.querySelector('.results-list') : null;
  601. // 清空之前的结果
  602. currentDocSection.innerHTML = '';
  603. otherDocsSection.innerHTML = '';
  604. // 隐藏分组标题
  605. DOM.currentDocResults.style.display = 'none';
  606. DOM.otherDocResults.style.display = 'none';
  607. // 显示错误信息
  608. if (currentDocSection) {
  609. currentDocSection.innerHTML = `<p class="search-error" style="color: #d73a49; padding: 20px; text-align: center;">${message}</p>`;
  610. }
  611. DOM.currentDocResults.style.display = 'block';
  612. // 显示搜索结果面板
  613. if (DOM.searchResults) {
  614. DOM.searchResults.style.display = 'block';
  615. }
  616. }
  617. // 显示搜索结果
  618. function displaySearchResults(data) {
  619. // 获取搜索结果内容容器
  620. const searchResultsContent = document.querySelector('.search-results-content');
  621. // 检查是否完全没有结果
  622. const hasNoResults = data.currentDoc.length === 0 && data.otherDocs.length === 0;
  623. if (hasNoResults) {
  624. // 完全没有搜索结果时,显示友好的空状态
  625. // 先清空内容区
  626. searchResultsContent.innerHTML = '';
  627. // 创建空状态容器
  628. const emptyState = document.createElement('div');
  629. emptyState.className = 'empty-search-state';
  630. emptyState.innerHTML = `
  631. <div class="empty-icon">
  632. <svg width="64" height="64" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
  633. <circle cx="11" cy="11" r="8" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  634. <path d="m21 21-4.35-4.35" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/>
  635. <path d="M8 11h6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
  636. </svg>
  637. </div>
  638. <h3 class="empty-title">没有找到相关内容</h3>
  639. <p class="empty-text">试试其他关键词,或者检查拼写是否正确</p>
  640. `;
  641. searchResultsContent.appendChild(emptyState);
  642. return;
  643. }
  644. // 有搜索结果时,需要恢复正常的DOM结构
  645. // 先检查是否需要重建结构(从空状态恢复)
  646. let currentDocResults = document.getElementById('current-doc-results');
  647. let otherDocResults = document.getElementById('other-docs-results');
  648. // 如果结构不存在(被空状态替换了),重新创建
  649. if (!currentDocResults || !otherDocResults) {
  650. searchResultsContent.innerHTML = `
  651. <div id="current-doc-results" class="results-section">
  652. <h3 class="results-section-title">当前文档</h3>
  653. <div class="results-list"></div>
  654. </div>
  655. <div id="other-docs-results" class="results-section">
  656. <h3 class="results-section-title">其他文档</h3>
  657. <div class="results-list"></div>
  658. </div>
  659. `;
  660. // 重新获取引用
  661. currentDocResults = document.getElementById('current-doc-results');
  662. otherDocResults = document.getElementById('other-docs-results');
  663. // 更新DOM缓存
  664. DOM.currentDocResults = currentDocResults;
  665. DOM.otherDocResults = otherDocResults;
  666. }
  667. const currentDocSection = currentDocResults.querySelector('.results-list');
  668. const otherDocsSection = otherDocResults.querySelector('.results-list');
  669. // 清空之前的结果
  670. currentDocSection.innerHTML = '';
  671. otherDocsSection.innerHTML = '';
  672. // 隐藏/显示分组标题
  673. currentDocResults.style.display =
  674. data.currentDoc.length > 0 ? 'block' : 'none';
  675. otherDocResults.style.display =
  676. data.otherDocs.length > 0 ? 'block' : 'none';
  677. // 渲染当前文档结果
  678. if (data.currentDoc.length > 0) {
  679. data.currentDoc.forEach(doc => {
  680. const docResults = createDocResultElement(doc, true);
  681. currentDocSection.appendChild(docResults);
  682. });
  683. }
  684. // 渲染其他文档结果
  685. if (data.otherDocs.length > 0) {
  686. data.otherDocs.forEach(doc => {
  687. const docResults = createDocResultElement(doc, false);
  688. otherDocsSection.appendChild(docResults);
  689. });
  690. }
  691. }
  692. // 创建搜索结果元素
  693. function createDocResultElement(doc, isCurrent) {
  694. const container = document.createElement('div');
  695. container.className = 'search-result-item';
  696. const header = document.createElement('div');
  697. header.className = 'result-header';
  698. header.innerHTML = `
  699. <span class="result-doc-name">${doc.docName}</span>
  700. <span class="result-count">${doc.matchCount} 个匹配</span>
  701. `;
  702. container.appendChild(header);
  703. // 添加匹配片段
  704. doc.matches.forEach(match => {
  705. const matchItem = document.createElement('div');
  706. matchItem.className = 'result-match';
  707. // 高亮搜索词
  708. const highlightedSnippet = highlightSearchTerm(match.snippet, DOM.searchInput ? DOM.searchInput.value : '');
  709. matchItem.innerHTML = `
  710. <div class="match-line-number">行 ${match.line}</div>
  711. <div class="match-snippet">${highlightedSnippet}</div>
  712. `;
  713. // 点击跳转
  714. matchItem.onclick = () => {
  715. // 隐藏搜索框和搜索结果
  716. if (DOM.searchContainer) {
  717. DOM.searchContainer.classList.remove('active');
  718. }
  719. if (DOM.searchResults) {
  720. DOM.searchResults.style.display = 'none';
  721. }
  722. // 在移动端和平板上关闭所有侧边栏,确保用户能看到跳转后的内容
  723. if (window.innerWidth <= 1024) {
  724. if (DOM.leftSidebar && !DOM.leftSidebar.classList.contains('collapsed')) {
  725. DOM.leftSidebar.classList.add('collapsed');
  726. }
  727. if (DOM.rightSidebar && !DOM.rightSidebar.classList.contains('collapsed')) {
  728. DOM.rightSidebar.classList.add('collapsed');
  729. }
  730. }
  731. if (isCurrent) {
  732. // 当前文档,滚动到对应位置
  733. scrollToSearchMatch(match.fullLine);
  734. } else {
  735. // 其他文档,加载该文档并跳转到具体位置
  736. loadDocument(doc.docName, match.fullLine);
  737. }
  738. };
  739. container.appendChild(matchItem);
  740. });
  741. return container;
  742. }
  743. // 高亮搜索词
  744. function highlightSearchTerm(text, searchTerm) {
  745. const regex = new RegExp(`(${searchTerm})`, 'gi');
  746. return text.replace(regex, '<mark class="search-highlight">$1</mark>');
  747. }
  748. // 滚动到搜索匹配位置
  749. function scrollToSearchMatch(fullLine) {
  750. const content = document.getElementById('markdown-content');
  751. const searchText = fullLine.trim();
  752. if (!searchText) return;
  753. // 使用TreeWalker遍历所有文本节点
  754. const walker = document.createTreeWalker(
  755. content,
  756. NodeFilter.SHOW_TEXT,
  757. null
  758. );
  759. let found = false;
  760. let node;
  761. while (node = walker.nextNode()) {
  762. if (node.textContent.includes(searchText)) {
  763. const parentElement = node.parentElement;
  764. // 滚动到元素
  765. parentElement.scrollIntoView({ behavior: 'smooth', block: 'center' });
  766. // 临时高亮父元素
  767. parentElement.classList.add('temp-highlight');
  768. setTimeout(() => {
  769. parentElement.classList.remove('temp-highlight');
  770. }, 2000);
  771. found = true;
  772. break;
  773. }
  774. }
  775. // 如果没有找到精确匹配,尝试部分匹配
  776. if (!found) {
  777. const elements = content.querySelectorAll('p, li, td, th, h1, h2, h3, h4, h5, h6, blockquote, pre, code');
  778. for (const element of elements) {
  779. const text = element.textContent.trim();
  780. // 尝试匹配至少50%的内容
  781. if (text.length > 10 && searchText.includes(text.substring(0, Math.min(text.length, 50)))) {
  782. element.scrollIntoView({ behavior: 'smooth', block: 'center' });
  783. // 临时高亮
  784. element.classList.add('temp-highlight');
  785. setTimeout(() => {
  786. element.classList.remove('temp-highlight');
  787. }, 2000);
  788. break;
  789. }
  790. }
  791. }
  792. }
  793. // 设置回到顶部按钮
  794. function setupBackToTop() {
  795. if (!DOM.backToTopBtn) DOM.backToTopBtn = document.getElementById('back-to-top');
  796. const backToTopBtn = DOM.backToTopBtn;
  797. if (!backToTopBtn) return;
  798. // 初始状态:隐藏按钮
  799. backToTopBtn.classList.add('hidden');
  800. // 点击按钮滚动到顶部
  801. backToTopBtn.addEventListener('click', (e) => {
  802. e.preventDefault();
  803. e.stopPropagation();
  804. // 滚动到顶部
  805. window.scrollTo({
  806. top: 0,
  807. behavior: 'smooth'
  808. });
  809. });
  810. // 监听窗口滚动事件,根据滚动位置控制按钮显示/隐藏
  811. let scrollTimeout;
  812. const handleScroll = () => {
  813. clearTimeout(scrollTimeout);
  814. scrollTimeout = setTimeout(() => {
  815. const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
  816. // 滚动超过 100px 时显示按钮
  817. if (scrollTop > 100) {
  818. backToTopBtn.classList.remove('hidden');
  819. } else {
  820. backToTopBtn.classList.add('hidden');
  821. }
  822. }, 100);
  823. };
  824. window.addEventListener('scroll', handleScroll);
  825. }
  826. // 编辑功能
  827. function setupEditFeature() {
  828. // 缓存DOM元素
  829. if (!DOM.editBtn) DOM.editBtn = document.getElementById('edit-btn');
  830. if (!DOM.editorContainer) DOM.editorContainer = document.getElementById('editor-container');
  831. if (!DOM.markdownEditor) DOM.markdownEditor = document.getElementById('markdown-editor');
  832. if (!DOM.editorDocName) DOM.editorDocName = document.getElementById('editor-doc-name');
  833. if (!DOM.saveBtn) DOM.saveBtn = document.getElementById('save-btn');
  834. if (!DOM.cancelBtn) DOM.cancelBtn = document.getElementById('cancel-edit-btn');
  835. if (!DOM.contentArea) DOM.contentArea = document.getElementById('content-area');
  836. const saveBtn = DOM.saveBtn;
  837. const cancelBtn = DOM.cancelBtn;
  838. const contentArea = DOM.contentArea;
  839. // 编辑按钮点击事件 - 切换编辑/查看模式
  840. DOM.editBtn.addEventListener('click', () => {
  841. if (isEditMode) {
  842. exitEditMode();
  843. } else {
  844. enterEditMode();
  845. }
  846. });
  847. // 取消编辑
  848. cancelBtn.addEventListener('click', () => {
  849. exitEditMode();
  850. });
  851. // 保存按钮
  852. saveBtn.addEventListener('click', async () => {
  853. await saveDocument();
  854. });
  855. }
  856. // 进入编辑模式
  857. function enterEditMode() {
  858. if (!currentDoc || !currentMarkdownContent) {
  859. alert('请先加载一个文档');
  860. return;
  861. }
  862. isEditMode = true;
  863. // 更新编辑按钮状态
  864. DOM.editBtn.classList.add('active');
  865. DOM.editBtn.title = '退出编辑';
  866. // 保存当前滚动位置
  867. if (!DOM.contentArea) DOM.contentArea = document.getElementById('content-area');
  868. savedScrollPosition = DOM.contentArea.scrollTop;
  869. // 找到当前视口中心附近的元素
  870. const visibleElement = findVisibleElement();
  871. // 隐藏渲染的内容
  872. if (!DOM.content) DOM.content = document.getElementById('markdown-content');
  873. DOM.content.style.display = 'none';
  874. // 显示编辑器
  875. DOM.editorContainer.style.display = 'flex';
  876. DOM.editorDocName.textContent = `${currentDoc}.md`;
  877. DOM.markdownEditor.value = currentMarkdownContent;
  878. // 定位光标到对应位置
  879. setTimeout(() => {
  880. if (visibleElement) {
  881. positionCursorByElement(visibleElement);
  882. } else {
  883. // 如果找不到元素,使用滚动比例
  884. const scrollRatio = savedScrollPosition / DOM.contentArea.scrollHeight;
  885. DOM.markdownEditor.scrollTop = DOM.markdownEditor.scrollHeight * scrollRatio;
  886. }
  887. DOM.markdownEditor.focus();
  888. }, 50);
  889. }
  890. // 找到当前视口中可见的元素
  891. function findVisibleElement() {
  892. if (!DOM.contentArea) DOM.contentArea = document.getElementById('content-area');
  893. const viewportTop = DOM.contentArea.scrollTop;
  894. const viewportMiddle = viewportTop + DOM.contentArea.clientHeight / 3; // 视口上方1/3处
  895. // 查找所有重要元素(标题、段落等)
  896. const elements = DOM.content.querySelectorAll('h1, h2, h3, h4, h5, h6, p, li, blockquote, pre');
  897. let closestElement = null;
  898. let minDistance = Infinity;
  899. elements.forEach(el => {
  900. const rect = el.getBoundingClientRect();
  901. const elementTop = el.offsetTop;
  902. const distance = Math.abs(elementTop - viewportMiddle);
  903. if (distance < minDistance && elementTop <= viewportMiddle + 200) {
  904. minDistance = distance;
  905. closestElement = el;
  906. }
  907. });
  908. return closestElement;
  909. }
  910. // 根据元素定位光标
  911. function positionCursorByElement(element) {
  912. const elementText = element.textContent.trim();
  913. if (!elementText) {
  914. return;
  915. }
  916. // 获取元素标签类型
  917. const tagName = element.tagName.toLowerCase();
  918. let searchText = elementText;
  919. // 如果是标题,添加markdown标记进行搜索
  920. if (tagName.match(/^h[1-6]$/)) {
  921. const level = parseInt(tagName[1]);
  922. const hashes = '#'.repeat(level);
  923. // 尝试匹配标题行
  924. const lines = currentMarkdownContent.split('\n');
  925. let targetLine = -1;
  926. for (let i = 0; i < lines.length; i++) {
  927. const line = lines[i].trim();
  928. // 匹配 "# 标题" 格式
  929. if (line.startsWith(hashes + ' ') && line.substring(level + 1).trim() === elementText) {
  930. targetLine = i;
  931. break;
  932. }
  933. }
  934. if (targetLine !== -1) {
  935. setEditorCursorToLine(targetLine);
  936. return;
  937. }
  938. }
  939. // 对于其他元素,搜索文本内容
  940. const lines = currentMarkdownContent.split('\n');
  941. for (let i = 0; i < lines.length; i++) {
  942. const line = lines[i].trim();
  943. // 移除markdown标记进行比较
  944. const cleanLine = line.replace(/^[#\-*>]+\s*/, '').trim();
  945. if (cleanLine.includes(elementText.substring(0, Math.min(50, elementText.length)))) {
  946. setEditorCursorToLine(i);
  947. return;
  948. }
  949. }
  950. }
  951. // 设置编辑器光标到指定行
  952. function setEditorCursorToLine(lineNumber) {
  953. const lines = currentMarkdownContent.split('\n');
  954. // 计算目标位置的字符索引
  955. let charPosition = 0;
  956. for (let i = 0; i < lineNumber && i < lines.length; i++) {
  957. charPosition += lines[i].length + 1; // +1 for newline
  958. }
  959. // 设置光标位置
  960. DOM.markdownEditor.setSelectionRange(charPosition, charPosition);
  961. // 滚动到光标位置
  962. const linesBeforeCursor = lineNumber;
  963. const lineHeight = 22; // 大约的行高(px)
  964. const targetScrollTop = linesBeforeCursor * lineHeight - DOM.markdownEditor.clientHeight / 3;
  965. DOM.markdownEditor.scrollTop = Math.max(0, targetScrollTop);
  966. }
  967. // 退出编辑模式
  968. function exitEditMode() {
  969. isEditMode = false;
  970. // 更新编辑按钮状态
  971. DOM.editBtn.classList.remove('active');
  972. DOM.editBtn.title = '编辑文档';
  973. // 隐藏编辑器
  974. DOM.editorContainer.style.display = 'none';
  975. // 显示渲染的内容
  976. DOM.content.style.display = 'block';
  977. // 恢复滚动位置
  978. if (!DOM.contentArea) DOM.contentArea = document.getElementById('content-area');
  979. setTimeout(() => {
  980. DOM.contentArea.scrollTop = savedScrollPosition;
  981. }, 0);
  982. }
  983. // 保存文档
  984. async function saveDocument() {
  985. const newContent = DOM.markdownEditor.value;
  986. if (!currentCategory || !currentDoc) {
  987. alert('无法保存:缺少文档信息');
  988. return;
  989. }
  990. // 禁用保存按钮,防止重复点击
  991. ensureDOM('saveBtn', 'save-btn');
  992. DOM.saveBtn.disabled = true;
  993. DOM.saveBtn.textContent = '保存中...';
  994. try {
  995. const encodedDocName = encodeDocPath(currentDoc);
  996. const response = await fetch(`/api/doc/${encodeURIComponent(currentCategory)}/${encodedDocName}`, {
  997. method: 'PUT',
  998. headers: {
  999. 'Content-Type': 'application/json'
  1000. },
  1001. body: JSON.stringify({
  1002. content: newContent
  1003. })
  1004. });
  1005. if (!response.ok) {
  1006. await handleApiError(response, '保存失败');
  1007. }
  1008. const result = await response.json();
  1009. // 更新本地的markdown内容
  1010. currentMarkdownContent = newContent;
  1011. // 重新渲染内容
  1012. const html = marked.parse(newContent);
  1013. DOM.content.innerHTML = html;
  1014. // 重新生成TOC
  1015. generateTOC();
  1016. // 退出编辑模式
  1017. exitEditMode();
  1018. // 显示成功提示
  1019. showSuccessMessage('保存成功!');
  1020. } catch (error) {
  1021. console.error('Save error:', error);
  1022. alert(`保存失败:${error.message || '请稍后重试'}`);
  1023. } finally {
  1024. // 恢复保存按钮
  1025. DOM.saveBtn.disabled = false;
  1026. DOM.saveBtn.textContent = '保存';
  1027. }
  1028. }
  1029. // 显示成功提示
  1030. function showSuccessMessage(message) {
  1031. const toast = document.createElement('div');
  1032. toast.className = 'success-toast';
  1033. toast.textContent = message;
  1034. toast.style.cssText = `
  1035. position: fixed;
  1036. top: 20px;
  1037. right: 20px;
  1038. background: #28a745;
  1039. color: white;
  1040. padding: 12px 24px;
  1041. border-radius: 6px;
  1042. box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  1043. z-index: 10000;
  1044. animation: slideInRight 0.3s ease-out;
  1045. `;
  1046. document.body.appendChild(toast);
  1047. setTimeout(() => {
  1048. toast.style.animation = 'slideOutRight 0.3s ease-out';
  1049. setTimeout(() => {
  1050. document.body.removeChild(toast);
  1051. }, 300);
  1052. }, 2000);
  1053. }
  1054. // 为代码块添加复制按钮
  1055. function addCopyButtonsToCodeBlocks() {
  1056. const codeBlocks = document.querySelectorAll('pre');
  1057. codeBlocks.forEach(pre => {
  1058. // 如果已经有复制按钮,跳过
  1059. if (pre.querySelector('.code-copy-btn')) {
  1060. return;
  1061. }
  1062. // 创建包装容器
  1063. const wrapper = document.createElement('div');
  1064. wrapper.className = 'code-block-wrapper';
  1065. // 将pre元素包装起来
  1066. pre.parentNode.insertBefore(wrapper, pre);
  1067. wrapper.appendChild(pre);
  1068. // 创建复制按钮
  1069. const copyBtn = document.createElement('button');
  1070. copyBtn.className = 'code-copy-btn';
  1071. copyBtn.innerHTML = `
  1072. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  1073. <rect x="9" y="9" width="13" height="13" rx="2" ry="2"></rect>
  1074. <path d="M5 15H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a2 2 0 0 1 2 2v1"></path>
  1075. </svg>
  1076. <span>复制</span>
  1077. `;
  1078. // 添加点击事件
  1079. copyBtn.addEventListener('click', () => {
  1080. copyCodeToClipboard(pre, copyBtn);
  1081. });
  1082. wrapper.appendChild(copyBtn);
  1083. });
  1084. }
  1085. // 复制代码到剪贴板
  1086. async function copyCodeToClipboard(preElement, button) {
  1087. const codeElement = preElement.querySelector('code');
  1088. if (!codeElement) return;
  1089. // 获取纯文本内容(去除HTML标签)
  1090. const text = codeElement.textContent || codeElement.innerText;
  1091. try {
  1092. // 使用现代API复制
  1093. await navigator.clipboard.writeText(text);
  1094. // 显示成功状态
  1095. showCopySuccess(button);
  1096. } catch (err) {
  1097. // 降级方案:使用传统方法
  1098. const textArea = document.createElement('textarea');
  1099. textArea.value = text;
  1100. textArea.style.position = 'fixed';
  1101. textArea.style.left = '-9999px';
  1102. document.body.appendChild(textArea);
  1103. textArea.select();
  1104. try {
  1105. document.execCommand('copy');
  1106. showCopySuccess(button);
  1107. } catch (err) {
  1108. console.error('复制失败:', err);
  1109. showCopyError(button);
  1110. } finally {
  1111. document.body.removeChild(textArea);
  1112. }
  1113. }
  1114. }
  1115. // 显示复制成功
  1116. function showCopySuccess(button) {
  1117. // 更新按钮状态
  1118. const originalHTML = button.innerHTML;
  1119. button.classList.add('copied');
  1120. button.innerHTML = `
  1121. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  1122. <polyline points="20 6 9 17 4 12"></polyline>
  1123. </svg>
  1124. <span>已复制</span>
  1125. `;
  1126. // 2秒后恢复原状
  1127. setTimeout(() => {
  1128. button.classList.remove('copied');
  1129. button.innerHTML = originalHTML;
  1130. }, 2000);
  1131. }
  1132. // 显示复制失败
  1133. function showCopyError(button) {
  1134. const originalHTML = button.innerHTML;
  1135. button.innerHTML = `
  1136. <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
  1137. <circle cx="12" cy="12" r="10"></circle>
  1138. <line x1="12" y1="8" x2="12" y2="12"></line>
  1139. <line x1="12" y1="16" x2="12.01" y2="16"></line>
  1140. </svg>
  1141. <span>复制失败</span>
  1142. `;
  1143. setTimeout(() => {
  1144. button.innerHTML = originalHTML;
  1145. }, 2000);
  1146. }
  1147. // ==================== 语音朗读功能 ====================
  1148. let speechSynthesis = window.speechSynthesis;
  1149. let currentUtterance = null;
  1150. let isPaused = false;
  1151. let isPlaying = false;
  1152. let currentHighlightElement = null;
  1153. let speechTexts = []; // 存储所有要朗读的文本段落
  1154. let currentSpeechIndex = 0; // 当前朗读的段落索引
  1155. let lastPausedElement = null; // 记录上次暂停的元素
  1156. // 初始化语音朗读
  1157. function initSpeech() {
  1158. const speechBtn = document.getElementById('speech-btn');
  1159. if (!speechBtn) return;
  1160. // 检查浏览器是否支持语音合成
  1161. if (!('speechSynthesis' in window)) {
  1162. speechBtn.style.display = 'none';
  1163. return;
  1164. }
  1165. // 某些浏览器需要先加载语音列表
  1166. if (speechSynthesis.getVoices().length === 0) {
  1167. speechSynthesis.addEventListener('voiceschanged', () => {}, { once: true });
  1168. }
  1169. // 添加点击事件监听
  1170. speechBtn.addEventListener('click', (e) => {
  1171. e.preventDefault();
  1172. e.stopPropagation();
  1173. handleSpeechButtonClick();
  1174. });
  1175. }
  1176. // 获取当前视口中第一个可见的文本元素
  1177. function getFirstVisibleTextElement() {
  1178. const content = document.getElementById('markdown-content');
  1179. if (!content) return null;
  1180. // 获取所有可朗读的文本元素
  1181. const elements = content.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, blockquote, td, th');
  1182. const viewportHeight = window.innerHeight;
  1183. for (const element of elements) {
  1184. // 跳过代码块内的元素
  1185. if (element.closest('pre') || element.closest('code')) {
  1186. continue;
  1187. }
  1188. const rect = element.getBoundingClientRect();
  1189. // 检查元素是否在视口内(顶部在视口内或元素跨越视口)
  1190. if ((rect.top >= 0 && rect.top < viewportHeight) ||
  1191. (rect.top < 0 && rect.bottom > 0)) {
  1192. return element;
  1193. }
  1194. }
  1195. return null;
  1196. }
  1197. // 判断元素是否在视口内可见
  1198. function isElementVisible(element) {
  1199. if (!element) return false;
  1200. const rect = element.getBoundingClientRect();
  1201. const windowHeight = window.innerHeight;
  1202. // 元素至少有一部分在视口内
  1203. return rect.bottom > 0 && rect.top < windowHeight;
  1204. }
  1205. // 处理语音按钮点击
  1206. function handleSpeechButtonClick() {
  1207. const speechBtn = document.getElementById('speech-btn');
  1208. if (isPlaying && !isPaused) {
  1209. // 正在播放 -> 暂停
  1210. pauseSpeech();
  1211. speechBtn.classList.remove('playing');
  1212. speechBtn.classList.add('paused');
  1213. } else if (isPaused) {
  1214. // 已暂停 -> 判断暂停位置是否可见
  1215. if (isElementVisible(lastPausedElement)) {
  1216. // 暂停位置可见,继续播放
  1217. resumeSpeech();
  1218. speechBtn.classList.remove('paused');
  1219. speechBtn.classList.add('playing');
  1220. } else {
  1221. // 暂停位置不可见,从当前可见的第一行开始
  1222. const currentVisibleElement = getFirstVisibleTextElement();
  1223. stopSpeech();
  1224. isPaused = false;
  1225. isPlaying = false;
  1226. startSpeechFromElement(currentVisibleElement);
  1227. speechBtn.classList.remove('paused');
  1228. speechBtn.classList.add('playing');
  1229. }
  1230. } else {
  1231. // 未开始 -> 从当前滚动位置开始朗读
  1232. const currentVisibleElement = getFirstVisibleTextElement();
  1233. startSpeechFromElement(currentVisibleElement);
  1234. speechBtn.classList.add('playing');
  1235. }
  1236. }
  1237. // 从指定元素开始朗读
  1238. function startSpeechFromElement(startElement) {
  1239. if (!DOM.content) DOM.content = document.getElementById('markdown-content');
  1240. if (!DOM.content || !DOM.content.textContent.trim()) {
  1241. alert('请先加载文档内容');
  1242. return;
  1243. }
  1244. // 提取要朗读的文本
  1245. speechTexts = extractSpeechTexts();
  1246. if (speechTexts.length === 0) {
  1247. alert('没有找到可朗读的文本内容');
  1248. return;
  1249. }
  1250. // 如果指定了起始元素,找到它在列表中的位置
  1251. if (startElement) {
  1252. const startIndex = speechTexts.findIndex(item => item.element === startElement);
  1253. currentSpeechIndex = startIndex !== -1 ? startIndex :
  1254. // 如果没找到,找最接近的元素
  1255. speechTexts.reduce((closestIdx, item, idx) => {
  1256. const rect = item.element.getBoundingClientRect();
  1257. const distance = Math.abs(rect.top);
  1258. const prevRect = speechTexts[closestIdx].element.getBoundingClientRect();
  1259. return distance < Math.abs(prevRect.top) ? idx : closestIdx;
  1260. }, 0);
  1261. } else {
  1262. currentSpeechIndex = 0;
  1263. }
  1264. isPlaying = true;
  1265. isPaused = false;
  1266. lastPausedElement = null; // 清除之前的暂停记录
  1267. // 开始朗读
  1268. speakNextSegment();
  1269. }
  1270. // 提取要朗读的文本(跳过图片和代码块)
  1271. function extractSpeechTexts() {
  1272. const texts = [];
  1273. const content = document.getElementById('markdown-content');
  1274. if (!content) return texts;
  1275. // 获取所有文本元素,排除代码块和图片
  1276. const elements = content.querySelectorAll('p, h1, h2, h3, h4, h5, h6, li, blockquote, td, th');
  1277. elements.forEach(element => {
  1278. // 跳过代码块内的元素
  1279. if (element.closest('pre') || element.closest('code')) {
  1280. return;
  1281. }
  1282. // 获取纯文本内容
  1283. const text = element.textContent.trim();
  1284. if (text) {
  1285. texts.push({
  1286. text: text,
  1287. element: element
  1288. });
  1289. }
  1290. });
  1291. return texts;
  1292. }
  1293. // 朗读下一段
  1294. function speakNextSegment() {
  1295. if (currentSpeechIndex >= speechTexts.length) {
  1296. // 朗读完成
  1297. console.log('朗读完成');
  1298. stopSpeech();
  1299. return;
  1300. }
  1301. const segment = speechTexts[currentSpeechIndex];
  1302. console.log('朗读第', currentSpeechIndex + 1, '段,内容:', segment.text.substring(0, 50) + '...');
  1303. // 清除之前的高亮
  1304. clearHighlight();
  1305. // 高亮当前段落
  1306. highlightElement(segment.element);
  1307. // 取消之前的朗读(如果有)
  1308. if (speechSynthesis.speaking) {
  1309. speechSynthesis.cancel();
  1310. }
  1311. // 创建语音实例
  1312. currentUtterance = new SpeechSynthesisUtterance(segment.text);
  1313. // 设置语音参数 - 优先尝试中文,如果不支持则使用默认语言
  1314. const voices = speechSynthesis.getVoices();
  1315. const chineseVoice = voices.find(voice =>
  1316. voice.lang === 'zh-CN' ||
  1317. voice.lang.startsWith('zh') ||
  1318. voice.lang.includes('Chinese')
  1319. );
  1320. if (chineseVoice) {
  1321. currentUtterance.voice = chineseVoice;
  1322. currentUtterance.lang = chineseVoice.lang;
  1323. } else {
  1324. currentUtterance.lang = 'zh-CN'; // 仍然设置为中文,让系统选择最佳声音
  1325. }
  1326. currentUtterance.rate = 1.0; // 语速
  1327. currentUtterance.pitch = 1.0; // 音调
  1328. currentUtterance.volume = 1.0; // 音量
  1329. // 语音错误处理
  1330. currentUtterance.onerror = (event) => {
  1331. alert('语音朗读出现错误,请检查浏览器设置');
  1332. stopSpeech();
  1333. };
  1334. // 语音结束事件
  1335. currentUtterance.onend = () => {
  1336. currentSpeechIndex++;
  1337. if (isPlaying && !isPaused) {
  1338. // 延迟一点再朗读下一段,让用户有停顿感
  1339. setTimeout(() => {
  1340. if (isPlaying && !isPaused) {
  1341. speakNextSegment();
  1342. }
  1343. }, 300);
  1344. }
  1345. };
  1346. // 语音边界事件(用于更精确的高亮,但Web Speech API支持有限)
  1347. currentUtterance.onboundary = (event) => {
  1348. // 检查是否需要滚动
  1349. checkAndScroll(segment.element);
  1350. };
  1351. // 开始朗读
  1352. try {
  1353. speechSynthesis.speak(currentUtterance);
  1354. } catch (error) {
  1355. alert('无法启动语音朗读,请检查浏览器权限');
  1356. stopSpeech();
  1357. }
  1358. }
  1359. // 高亮元素
  1360. function highlightElement(element) {
  1361. if (!element) return;
  1362. currentHighlightElement = element;
  1363. element.classList.add('speech-highlight');
  1364. // 确保元素在视口内
  1365. checkAndScroll(element);
  1366. }
  1367. // 清除高亮
  1368. function clearHighlight() {
  1369. if (currentHighlightElement) {
  1370. currentHighlightElement.classList.remove('speech-highlight');
  1371. currentHighlightElement = null;
  1372. }
  1373. }
  1374. // 检查并滚动
  1375. function checkAndScroll(element) {
  1376. if (!element) return;
  1377. const rect = element.getBoundingClientRect();
  1378. const viewportHeight = window.innerHeight;
  1379. // 如果元素在视口底部附近(最后20%),向下滚动
  1380. if (rect.bottom > viewportHeight * 0.8) {
  1381. element.scrollIntoView({
  1382. behavior: 'smooth',
  1383. block: 'center'
  1384. });
  1385. }
  1386. // 如果元素在视口顶部之上,也滚动到中心
  1387. else if (rect.top < 0) {
  1388. element.scrollIntoView({
  1389. behavior: 'smooth',
  1390. block: 'center'
  1391. });
  1392. }
  1393. }
  1394. // 暂停朗读
  1395. function pauseSpeech() {
  1396. if (speechSynthesis && isPlaying) {
  1397. // 记录当前朗读的元素(优先使用当前高亮的元素)
  1398. if (currentHighlightElement) {
  1399. lastPausedElement = currentHighlightElement;
  1400. } else if (currentSpeechIndex < speechTexts.length) {
  1401. lastPausedElement = speechTexts[currentSpeechIndex].element;
  1402. }
  1403. speechSynthesis.pause();
  1404. isPaused = true;
  1405. }
  1406. }
  1407. // 继续朗读
  1408. function resumeSpeech() {
  1409. if (speechSynthesis && isPaused) {
  1410. speechSynthesis.resume();
  1411. isPaused = false;
  1412. }
  1413. }
  1414. // 停止朗读
  1415. function stopSpeech() {
  1416. if (speechSynthesis) {
  1417. speechSynthesis.cancel();
  1418. }
  1419. cleanupSpeechState();
  1420. }
  1421. // 清理语音状态
  1422. function cleanupSpeechState() {
  1423. isPlaying = false;
  1424. isPaused = false;
  1425. currentSpeechIndex = 0;
  1426. currentUtterance = null;
  1427. speechTexts = [];
  1428. lastPausedElement = null; // 清除暂停记录
  1429. // 清除高亮
  1430. clearHighlight();
  1431. // 重置按钮状态
  1432. const speechBtn = document.getElementById('speech-btn');
  1433. if (speechBtn) {
  1434. speechBtn.classList.remove('playing', 'paused');
  1435. }
  1436. }
  1437. // 当加载新文档时停止朗读
  1438. const originalLoadDocument = loadDocument;
  1439. loadDocument = function(docName, scrollToText = null) {
  1440. // 停止当前朗读
  1441. stopSpeech();
  1442. // 调用原始的loadDocument
  1443. return originalLoadDocument.call(this, docName, scrollToText);
  1444. };
  1445. // 初始化
  1446. document.addEventListener('DOMContentLoaded', () => {
  1447. loadDocList();
  1448. setupSidebarToggles();
  1449. initSearch();
  1450. setupBackToTop();
  1451. setupEditFeature();
  1452. // 延迟初始化语音朗读,确保DOM完全加载
  1453. setTimeout(() => {
  1454. initSpeech();
  1455. }, 500);
  1456. });
  1457. // 处理浏览器后退/前进
  1458. window.addEventListener('popstate', () => {
  1459. const { doc } = getQueryParams();
  1460. if (doc) {
  1461. loadDocument(doc);
  1462. }
  1463. });