Mayx's Home Page
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

316 lines
12 KiB

  1. /**
  2. * PJAX 初始化与页面切换重绑定脚本
  3. * 依赖jQuery, jquery.pjax.min.js
  4. * 加载顺序 jquery.pjax.min.js 之后body 末尾
  5. */
  6. (function ($) {
  7. // ========== 常量 ==========
  8. var CONTAINER = '#pjax-container';
  9. var PJAX_OPTS = {
  10. container: CONTAINER,
  11. fragment: CONTAINER,
  12. timeout: 8000,
  13. scrollTo: false
  14. };
  15. // ========== 工具函数 ==========
  16. var _loadedScripts = {};
  17. /** 动态加载外部 CSS(避免重复加载) */
  18. function loadCSS(href) {
  19. if ($('link[href="' + href + '"]').length) return;
  20. $('<link rel="stylesheet" href="' + href + '" />').appendTo('head');
  21. }
  22. /** 动态加载外部 JS(去重) */
  23. function loadScript(src, callback) {
  24. if (_loadedScripts[src]) {
  25. if (typeof callback === 'function') callback();
  26. return;
  27. }
  28. _loadedScripts[src] = true;
  29. var s = document.createElement('script');
  30. s.src = src;
  31. s.onload = callback || null;
  32. document.body.appendChild(s);
  33. }
  34. // ========== 页面类型判断 ==========
  35. /** 是否为文章页(非首页/分页) */
  36. function isPostPage(pathname) {
  37. return !/^(\/(index\.html)?|\/page\d+(\/index\.html)?)$/.test(pathname || window.location.pathname);
  38. }
  39. /** 是否为真正的文章页(用 DOM 特征判断,仅 post 布局才有这些元素) */
  40. function isRealPostPage() {
  41. return $(CONTAINER + ' #gitalk-container').length > 0;
  42. }
  43. // ========== 欢迎语生成 ==========
  44. /**
  45. * 根据当前时间和页面生成 Live2D 欢迎语
  46. * 此函数暴露到 window._live2d.getWelcomeText message.js 首次加载时复用
  47. * @param {string} [pathname] - 页面路径默认当前路径
  48. * @param {string} [title] - 页面标题默认从 document.title 提取
  49. * @returns {string} 欢迎语 HTML
  50. */
  51. function getWelcomeText(pathname, title) {
  52. pathname = pathname || window.location.pathname;
  53. title = title || document.title.split(' | ')[0];
  54. if (pathname === '/' || pathname === '/index.html') {
  55. var now = (new Date()).getHours();
  56. if (now > 23 || now <= 5) return '你是夜猫子呀?这么晚还不睡觉,明天起的来嘛?';
  57. if (now > 5 && now <= 7) return '早上好!一日之计在于晨,美好的一天就要开始了!';
  58. if (now > 7 && now <= 11) return '上午好!工作顺利嘛,不要久坐,多起来走动走动哦!';
  59. if (now > 11 && now <= 14) return '中午了,工作了一个上午,现在是午餐时间!';
  60. if (now > 14 && now <= 17) return '午后很容易犯困呢,今天的运动目标完成了吗?';
  61. if (now > 17 && now <= 19) return '傍晚了!窗外夕阳的景色很美丽呢,最美不过夕阳红~~';
  62. if (now > 19 && now <= 21) return '晚上好,今天过得怎么样?';
  63. if (now > 21 && now <= 23) return '已经这么晚了呀,早点休息吧,晚安~~';
  64. return '嗨~ 快来逗我玩吧!';
  65. }
  66. return '欢迎阅读<span style="color:#0099cc;">「 ' + title + ' 」</span>';
  67. }
  68. // ========== 各组件重初始化 ==========
  69. /** 访问量统计 */
  70. function reinitVisitors() {
  71. if (typeof BlogAPI === 'undefined') return;
  72. var apiBase = BlogAPI;
  73. if ($('.visitors').length === 1) {
  74. var $visitor = $('.visitors:first');
  75. $.get(apiBase + '/count_click_add?id=' + $visitor.attr('id'), function (data) {
  76. $visitor.text(Number(data));
  77. });
  78. } else if ($('.visitors-index').length > 0) {
  79. $('.visitors-index').each(function () {
  80. var $elem = $(this);
  81. $.get(apiBase + '/count_click?id=' + $elem.attr('id'), function (data) {
  82. $elem.text(Number(data));
  83. });
  84. });
  85. }
  86. }
  87. /** AI 摘要(post.html 内联脚本,pjax 后触发) */
  88. function reinitAISummary() {
  89. if (typeof ai_gen === 'function' && $('#ai-output').length) {
  90. try { ai_gen(); } catch (e) { /* ignore */ }
  91. }
  92. }
  93. /** 代码块复制按钮 */
  94. function reinitCopyButtons() {
  95. $('.copy').remove();
  96. $('div.highlight').each(function () {
  97. var $block = $(this);
  98. var $btn = $('<button>', { class: 'copy', type: 'button', text: '📋' });
  99. $block.append($btn);
  100. $btn.on('click', function () {
  101. var code = $btn.siblings('pre').find('code').text().trim();
  102. navigator.clipboard.writeText(code)
  103. .then(function () { $btn.text('✅'); })
  104. .catch(function () { $btn.text('❌'); })
  105. .finally(function () { setTimeout(function () { $btn.text('📋'); }, 1500); });
  106. });
  107. });
  108. }
  109. /** Gitalk 评论(post 页面专属) */
  110. function reinitGitalk() {
  111. if ($(CONTAINER + ' #gitalk-container').length === 0) return;
  112. loadCSS('/assets/css/gitalk.css');
  113. function doInitGitalk() {
  114. if (typeof Gitalk === 'undefined') {
  115. loadScript('/assets/js/gitalk.min.js', doInitGitalk);
  116. return;
  117. }
  118. var pageId = $(CONTAINER + ' #gitalk-container').data('page-id') || window.location.pathname;
  119. try {
  120. new Gitalk(Object.assign({ id: pageId }, window.GitalkConfig))
  121. .render('gitalk-container');
  122. } catch (e) {
  123. console.warn('[pjax] Gitalk init error:', e);
  124. }
  125. }
  126. $('#gitalk-container').empty();
  127. doInitGitalk();
  128. }
  129. /** 关键词高亮 */
  130. function reinitHighlight() {
  131. var keyword = new URLSearchParams(window.location.search).get('kw');
  132. if (!keyword) return;
  133. keyword = keyword.trim();
  134. if (!keyword) return;
  135. var escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
  136. var regex = new RegExp('(' + escaped + ')', 'gi');
  137. var escapeHTML = function (str) {
  138. return str.replace(/[&<>"']/g, function (t) {
  139. return { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[t] || t;
  140. });
  141. };
  142. function walk(node) {
  143. $(node).contents().each(function () {
  144. if (this.nodeType === Node.TEXT_NODE) {
  145. var $t = $(this);
  146. var text = escapeHTML($t.text());
  147. if (regex.test(text)) $t.replaceWith(text.replace(regex, '<mark>$1</mark>'));
  148. } else if (this.nodeType === Node.ELEMENT_NODE && !$(this).is('script, style, noscript, textarea')) {
  149. walk(this);
  150. }
  151. });
  152. }
  153. $('section').each(function () { walk(this); });
  154. }
  155. /** Google Analytics 页面浏览事件 */
  156. function trackPageView() {
  157. if (typeof gtag === 'function') {
  158. gtag('config', window._gaId || '', { page_path: window.location.pathname });
  159. }
  160. }
  161. /** Live2D 重初始化 */
  162. var _live2dSelectors = ['.post-link', '#search-input'];
  163. var _live2dDelegateBound = false;
  164. function reinitLive2d() {
  165. if (!window._live2d) return;
  166. var pathname = window.location.pathname;
  167. // 更新"想问这篇文章"相关状态(仅真正的文章页显示)
  168. $('#post_id').val(pathname);
  169. if (isRealPostPage()) {
  170. $('.live_talk_input_name_body').show();
  171. } else {
  172. $('.live_talk_input_name_body').hide();
  173. $('#load_this').prop('checked', false);
  174. }
  175. // 音乐按钮:根据当前页面是否有 BGM 输入来显示/隐藏
  176. if (typeof window._live2d.initBGM === 'function') {
  177. window._live2d.initBGM();
  178. }
  179. // 事件委托绑定(只执行一次)
  180. if (!_live2dDelegateBound && typeof String.prototype.renderTip === 'function') {
  181. var selector = CONTAINER + ' ' + _live2dSelectors.join(', ' + CONTAINER + ' ');
  182. $(document).on('mouseover._live2d_pjax', selector, function (e) {
  183. var $el = $(e.currentTarget || e.target);
  184. if ($el.is('.post-link')) {
  185. window._live2d.showMessage('要看看 ' + $el.text() + ' 么?', 3000);
  186. } else if ($el.is('#search-input')) {
  187. window._live2d.showMessage('在找什么东西呢,需要帮忙吗?', 3000);
  188. }
  189. });
  190. $(document).on('mouseout._live2d_pjax', selector, function () {
  191. if (window._live2d.showHitokoto) window._live2d.showHitokoto();
  192. });
  193. _live2dDelegateBound = true;
  194. }
  195. // 欢迎语
  196. if (typeof window._live2d.showMessage === 'function') {
  197. window._live2d.showMessage(getWelcomeText(pathname), 6000);
  198. }
  199. }
  200. // ========== PJAX 导航 ==========
  201. /** PJAX 完成后的统一处理 */
  202. function doPjaxComplete() {
  203. $('body').removeClass('pjax-loading');
  204. // 清理可能残留的浮层(如推荐文章 tooltip,hover 后点击跳转时 mouseleave 来不及触发)
  205. $('.content-tooltip').hide();
  206. onPjaxComplete();
  207. }
  208. /** 暴露给模板内 onclick/onchange 调用的导航函数 */
  209. window.go = function (url) {
  210. if (!url || url === '#') return;
  211. if (/^(https?:)?\/\//.test(url) || url.startsWith('mailto:')) {
  212. window.location.href = url;
  213. return;
  214. }
  215. $('body').addClass('pjax-loading');
  216. $.ajax({
  217. url: url,
  218. beforeSend: function (xhr) {
  219. xhr.setRequestHeader('X-PJAX', 'true');
  220. xhr.setRequestHeader('X-PJAX-Container', CONTAINER);
  221. },
  222. success: function (html) {
  223. try {
  224. var doc = (new DOMParser()).parseFromString(html, 'text/html');
  225. var fragment = doc.querySelector(CONTAINER);
  226. if (fragment) {
  227. // 用 adoptNode 搬运所有子节点(包括 script 元素),让浏览器自行处理脚本执行
  228. // 这能正确支持 type="module"、顶层 await 等,避免手动提取重建的坑
  229. $(CONTAINER).empty(); // jQuery 清理旧元素的事件和数据,避免内存泄漏
  230. var container = document.querySelector(CONTAINER);
  231. while (fragment.firstChild) {
  232. container.appendChild(document.adoptNode(fragment.firstChild));
  233. }
  234. document.title = doc.title;
  235. history.pushState({ url: url }, document.title, url);
  236. doPjaxComplete();
  237. } else {
  238. window.location.href = url;
  239. }
  240. } catch (e) {
  241. console.warn('[go] parse error, fallback:', e);
  242. window.location.href = url;
  243. }
  244. },
  245. error: function () { window.location.href = url; },
  246. timeout: PJAX_OPTS.timeout
  247. });
  248. };
  249. /** 暴露 getWelcomeText 供 message.js 首次加载时复用,避免欢迎语逻辑重复 */
  250. window._pjaxGetWelcomeText = getWelcomeText;
  251. // ========== 初始化 ==========
  252. /** 每次 pjax 完成后执行所有重初始化 */
  253. function onPjaxComplete() {
  254. reinitVisitors();
  255. reinitCopyButtons();
  256. reinitHighlight();
  257. reinitGitalk();
  258. reinitAISummary();
  259. reinitLive2d();
  260. trackPageView();
  261. window.scrollTo(0, 0);
  262. }
  263. $(document).ready(function () {
  264. // 排除列表:外链、锚点、静态资源、Live2D 目录
  265. var exclude = ':not([target="_blank"]):not([href^="http"]):not([href^="//"])' +
  266. ':not([href^="mailto"]):not([href^="#"])' +
  267. ':not([href$=".xml"]):not([href$=".json"]):not([href$=".tgz"]):not([href$=".zip"])' +
  268. ':not([href^="/Live2dHistoire"])';
  269. $(document).pjax('a' + exclude, PJAX_OPTS.container, PJAX_OPTS);
  270. $(document).on('pjax:send', function () {
  271. $('body').addClass('pjax-loading');
  272. });
  273. $(document).on('pjax:complete', doPjaxComplete);
  274. $(document).on('pjax:error', function (xhr, textStatus, error) {
  275. console.warn('[pjax] error, fallback:', error);
  276. });
  277. // 首次加载初始化
  278. reinitCopyButtons();
  279. });
  280. })(jQuery);