From fdec0aafa1a81d59b466ea095aa6913862bc577e Mon Sep 17 00:00:00 2001 From: Erzbir Date: Mon, 15 Jun 2026 22:06:13 +0800 Subject: [PATCH] refactor: improve code maintainability --- src/module/effect.js | 56 ++++---- src/module/header.js | 44 ++++-- src/module/moments.js | 119 +++++++++++----- src/module/post.js | 247 +++++++++++++++++----------------- src/terminal.js | 6 +- src/utils/dom.js | 13 ++ templates/error/404.html | 6 +- templates/error/5xx.html | 6 +- templates/error/error.html | 6 +- templates/modules/header.html | 4 +- templates/modules/layout.html | 197 ++++++++++++++++----------- templates/moments.html | 8 +- 12 files changed, 421 insertions(+), 291 deletions(-) create mode 100644 src/utils/dom.js diff --git a/src/module/effect.js b/src/module/effect.js index 90ae13c..92dadce 100644 --- a/src/module/effect.js +++ b/src/module/effect.js @@ -1,28 +1,36 @@ -function type() { - document.addEventListener('DOMContentLoaded', () => { - let typedTextContainer = document.querySelector('.typed-text'); - if (!typedTextContainer) { - return; - } +import {terminal} from "../terminal.js"; - function typeWriter(container) { - let text = container.innerText; - container.innerText = ''; - let i = 0; +const TYPED_TEXT_SELECTOR = ".typed-text"; +const TYPED_FLAG = "typed"; +const MIN_TYPE_DELAY = 50; +const TYPE_DELAY_VARIANCE = 200; - function _type() { - if (i < text.length) { - container.innerHTML += text.charAt(i); - i++; - setTimeout(_type, Math.random() * 200 + 50); - } - } - - _type(); - } - - typeWriter(typedTextContainer); - }) +function getTypeDelay() { + return Math.random() * TYPE_DELAY_VARIANCE + MIN_TYPE_DELAY; } -terminal.registerRefresh(type); \ No newline at end of file +function typeWriter(container) { + if (!container || container.dataset[TYPED_FLAG] === "true") return; + + const text = container.textContent || ""; + container.dataset[TYPED_FLAG] = "true"; + container.textContent = ""; + + let index = 0; + + function writeNextCharacter() { + if (index >= text.length) return; + + container.textContent += text.charAt(index); + index++; + window.setTimeout(writeNextCharacter, getTypeDelay()); + } + + writeNextCharacter(); +} + +function typeTypedText() { + document.querySelectorAll(TYPED_TEXT_SELECTOR).forEach(typeWriter); +} + +terminal.registerRefresh(typeTypedText); diff --git a/src/module/header.js b/src/module/header.js index 11097b7..dd1be24 100644 --- a/src/module/header.js +++ b/src/module/header.js @@ -1,29 +1,49 @@ -function register_themeToggle() { +import {terminal} from "../terminal.js"; + +const THEME_MODE_STORAGE_KEY = "theme-mode"; +const PIXEL_STYLE_STORAGE_KEY = "pixel_style"; + +function registerSearchButton() { + const searchButton = document.querySelector('[data-header-action="open-search"]'); + if (!searchButton) return; + + searchButton.addEventListener("click", function () { + if (typeof window.SearchWidget?.open === "function") { + window.SearchWidget.open(); + } + }); +} + +function registerThemeToggle() { const toggle = document.getElementById("theme-toggle"); + if (!toggle || typeof window.applyTheme !== "function") return; toggle.addEventListener("click", function () { const currentScheme = document.documentElement.getAttribute("data-color-scheme"); const nextMode = currentScheme === "dark" ? "light" : "dark"; - applyTheme(nextMode); + window.applyTheme(nextMode); const isSystemMode = currentScheme === "system"; if (!isSystemMode) { - localStorage.setItem("theme-mode", nextMode); + localStorage.setItem(THEME_MODE_STORAGE_KEY, nextMode); } }); } -function register_pixelToggle() { - const pixel_toggle = document.getElementById('pixel-toggle'); +function registerPixelToggle() { + const pixelToggle = document.getElementById("pixel-toggle"); + if (!pixelToggle) return; - pixel_toggle.addEventListener('click', function () { - let storedStatus = localStorage.getItem("pixel_style"); - let newStatus = storedStatus === 'true' ? 'false' : 'true'; - document.documentElement.setAttribute("pixel_style", newStatus); - localStorage.setItem("pixel_style", newStatus); + pixelToggle.addEventListener("click", function () { + const storedStatus = localStorage.getItem(PIXEL_STYLE_STORAGE_KEY); + const newStatus = storedStatus === "true" ? "false" : "true"; + document.documentElement.setAttribute(PIXEL_STYLE_STORAGE_KEY, newStatus); + localStorage.setItem(PIXEL_STYLE_STORAGE_KEY, newStatus); + window.TerminalTheme?.syncPixelFont?.(); }); } -terminal.registerInitFunc(register_pixelToggle); -terminal.registerInitFunc(register_themeToggle); \ No newline at end of file +terminal.registerInitFunc(registerSearchButton); +terminal.registerInitFunc(registerPixelToggle); +terminal.registerInitFunc(registerThemeToggle); diff --git a/src/module/moments.js b/src/module/moments.js index 017788a..68208ab 100644 --- a/src/module/moments.js +++ b/src/module/moments.js @@ -1,50 +1,83 @@ import {terminal} from "../terminal.js"; -const key = 'moment'; -const group = 'moment.halo.run'; -const plural = 'moments'; +const RESOURCE_KEY = "moment"; +const RESOURCE_GROUP = "moment.halo.run"; +const RESOURCE_PLURAL = "moments"; +const UPVOTED_NAMES_STORAGE_KEY = `walker.upvoted.${RESOURCE_KEY}.names`; +const UPVOTE_BUTTON_SELECTOR = ".moment-upvote-btn"; +const UPVOTE_COUNT_SELECTOR = `.upvote-count[data-${RESOURCE_KEY}-name]`; +const MOMENT_ACTION_SELECTOR = "[data-moment-action]"; +const UPVOTE_API = "/apis/api.halo.run/v1alpha1/trackers/upvote"; +const MOMENT_ACTIONS = { + upvote: "upvote", + toggleComment: "toggle-comment" +}; -let upvotedNames = JSON.parse(localStorage.getItem('walker.upvoted.' + key + '.names') || '[]') +let upvotedNames = readUpvotedNames(); +let actionListenerRegistered = false; + +function readUpvotedNames() { + try { + const names = JSON.parse(localStorage.getItem(UPVOTED_NAMES_STORAGE_KEY) || "[]"); + return Array.isArray(names) ? names : []; + } catch { + return []; + } +} + +function saveUpvotedNames() { + localStorage.setItem(UPVOTED_NAMES_STORAGE_KEY, JSON.stringify(upvotedNames)); +} function upvoted(id) { return upvotedNames.includes(id); } +function recordUpvote(name) { + if (upvoted(name)) return; + upvotedNames = [...upvotedNames, name]; + saveUpvotedNames(); +} + +function findUpvoteCountNode(name) { + return [...document.querySelectorAll(UPVOTE_COUNT_SELECTOR)] + .find(node => node.dataset[`${RESOURCE_KEY}Name`] === name); +} + +function incrementUpvoteCount(name) { + const upvoteNode = findUpvoteCountNode(name); + if (!upvoteNode) return; + + const upvoteCount = Number.parseInt(upvoteNode.textContent || "0", 10) || 0; + upvoteNode.textContent = String(upvoteCount + 1); +} + +function syncUpvotedButtons() { + document.querySelectorAll(UPVOTE_BUTTON_SELECTOR).forEach(btn => { + btn.classList.toggle("active", upvoted(btn.dataset.momentName)); + }); +} function handleUpvote(name) { + if (!name) return; if (upvoted(name)) return; const xhr = new XMLHttpRequest(); - xhr.open('POST', '/apis/api.halo.run/v1alpha1/trackers/upvote'); - xhr.setRequestHeader('Content-Type', 'application/json'); + xhr.open("POST", UPVOTE_API); + xhr.setRequestHeader("Content-Type", "application/json"); xhr.onload = () => { - upvotedNames = [...upvotedNames, name]; - localStorage.setItem('walker.upvoted.' + key + '.names', JSON.stringify(upvotedNames)); - - const upvoteNode = document.querySelector('[data-' + key + '-name="' + name + '"]'); - if (!upvoteNode) return; - - const upvoteCount = parseInt(upvoteNode.textContent || '0'); - upvoteNode.textContent = upvoteCount + 1 + ''; + if (xhr.status < 200 || xhr.status >= 300) return; + recordUpvote(name); + incrementUpvoteCount(name); + syncUpvotedButtons(); }; xhr.onerror = function () { - alert('Network Error'); + alert("Network Error"); }; - xhr.send(JSON.stringify({group: group, plural: plural, name: name})); -} - -function register_upvoted() { - document.addEventListener('DOMContentLoaded', function () { - document.querySelectorAll('.moment-upvote-btn').forEach(btn => { - const name = btn.dataset.name - if (upvoted(name)) { - btn.classList.add('active') - } - }) - }); + xhr.send(JSON.stringify({group: RESOURCE_GROUP, plural: RESOURCE_PLURAL, name: name})); } function showComment(name) { @@ -52,16 +85,36 @@ function showComment(name) { if (!section) return; - const show = section.classList.contains('active'); + const show = section.classList.contains("active"); if (show) { - section.classList.remove('active'); + section.classList.remove("active"); } else { - section.classList.add('active'); + section.classList.add("active"); } } -terminal.registerInitFunc(register_upvoted) +function handleMomentAction(event) { + const actionNode = event.target.closest(MOMENT_ACTION_SELECTOR); + if (!actionNode) return; -window.handleUpvote = handleUpvote; -window.showComment = showComment; \ No newline at end of file + const action = actionNode.dataset.momentAction; + if (action === MOMENT_ACTIONS.upvote) { + handleUpvote(actionNode.dataset.momentName); + return; + } + + if (action === MOMENT_ACTIONS.toggleComment) { + showComment(actionNode.dataset.commentTarget); + } +} + +function registerMomentActions() { + if (actionListenerRegistered) return; + + document.addEventListener("click", handleMomentAction); + actionListenerRegistered = true; +} + +terminal.registerInitFunc(registerMomentActions); +terminal.registerRefresh(syncUpvotedButtons); diff --git a/src/module/post.js b/src/module/post.js index 5d8f4ad..4d877a7 100644 --- a/src/module/post.js +++ b/src/module/post.js @@ -1,169 +1,172 @@ +import {terminal} from "../terminal.js"; +import {debounce, toggleClass} from "../utils/dom.js"; import tocbot from "tocbot"; -let toc_icon = "☰" -let toc_close_icon = "✕" +const TOC_SELECTOR = "#toc"; +const TOC_CONTENT_SELECTOR = ".toc-content"; +const CONTENT_SELECTOR = "#content"; +const HEADING_SELECTOR = "h1, h2, h3, h4"; +const TOC_VISIBLE_CLASS = "toc-visible"; +const TOC_TOGGLE_ID = "toc-toggle"; +const TOC_OPEN_ICON = "☰"; +const TOC_CLOSE_ICON = "✕"; +const DESKTOP_TOC_WIDTH = 1400; +const TOC_GAP = 12; +const FALLBACK_TOC_WIDTH_REM = 17.5; +const RESIZE_DEBOUNCE_MS = 250; + +let resizeListenerRegistered = false; function isTocDefaultOpen(toc) { return toc?.dataset?.defaultOpen !== "false"; } -function toggleToc() { - const toc = document.getElementById("toc"); - if (!toc) return; - const toc_toggle = document.getElementById("toc-toggle"); - - if (!toc_toggle) return; - - const isVisible = toc.classList.contains('toc-visible'); - - if (isVisible) { - toc.classList.remove('toc-visible'); - toc_toggle.innerHTML = toc_icon; - toc_toggle.setAttribute('aria-label', 'Show Table of Contents'); - - } else { - toc.classList.add('toc-visible'); - toc_toggle.innerHTML = toc_close_icon; - toc_toggle.setAttribute('aria-label', 'Hide Table of Contents'); - } - void locateToc(); +function getToc() { + return document.querySelector(TOC_SELECTOR); } -async function generateToc() { - const toc = document.getElementById("toc"); - if (!toc) return; +function getTocToggle() { + return document.getElementById(TOC_TOGGLE_ID); +} - const content = document.getElementById("content"); - const titles = content.querySelectorAll("h1, h2, h3, h4"); +function getContent() { + return document.querySelector(CONTENT_SELECTOR); +} - if (!titles || titles.length === 0) { - toc.style.display = "none"; - toc.remove(); - return; - } - - if (typeof tocbot !== 'undefined') { +function destroyTocbot() { + if (typeof tocbot !== "undefined") { tocbot.destroy(); - tocbot.init({ - tocSelector: ".toc-content", - contentSelector: "#content", - headingSelector: "h1, h2, h3, h4", - extraListClasses: "toc-list", - extraLinkClasses: "toc-link", - headingsOffset: 96, - scrollSmoothOffset: -96, - scrollSmooth: true, - }); } - - setupTocVisibility(); - setupToggleButton(); - void locateToc(); } -function setupTocVisibility() { - const toc = document.querySelector(".toc"); +function syncToggleButton(toc = getToc()) { + const tocToggle = getTocToggle(); + if (!toc || !tocToggle) return; + + const isVisible = toc.classList.contains(TOC_VISIBLE_CLASS); + tocToggle.textContent = isVisible ? TOC_CLOSE_ICON : TOC_OPEN_ICON; + tocToggle.setAttribute("aria-label", isVisible ? "Hide Table of Contents" : "Show Table of Contents"); + + if (tocToggle.dataset.tocBound === "true") return; + tocToggle.addEventListener("click", toggleToc); + tocToggle.dataset.tocBound = "true"; +} + +function setTocVisible(toc, visible) { + toggleClass(toc, TOC_VISIBLE_CLASS, visible); + syncToggleButton(toc); +} + +function toggleToc() { + const toc = getToc(); + if (!toc) return; + + const isVisible = toc.classList.contains(TOC_VISIBLE_CLASS); + setTocVisible(toc, !isVisible); + locateToc(); +} + +function hideToc(toc) { + toc.style.display = "none"; + toc.remove(); + destroyTocbot(); +} + +function initTocbot() { + destroyTocbot(); + tocbot.init({ + tocSelector: TOC_CONTENT_SELECTOR, + contentSelector: CONTENT_SELECTOR, + headingSelector: HEADING_SELECTOR, + extraListClasses: "toc-list", + extraLinkClasses: "toc-link", + headingsOffset: 96, + scrollSmoothOffset: -96, + scrollSmooth: true, + }); +} + +function shouldShowExpandedToc(toc) { + return isTocDefaultOpen(toc) && window.innerWidth > DESKTOP_TOC_WIDTH; +} + +function setupTocVisibility(toc = getToc()) { if (!toc) return; toc.style.display = "block"; + setTocVisible(toc, shouldShowExpandedToc(toc)); +} - if (isTocDefaultOpen(toc) && window.innerWidth > 1400) { - toc.classList.add('toc-visible'); - } else { - toc.classList.remove('toc-visible'); +function generateToc() { + const toc = getToc(); + const content = getContent(); + + if (!toc || !content) { + destroyTocbot(); + return; } + + const titles = content.querySelectorAll(HEADING_SELECTOR); + if (!titles || titles.length === 0) { + hideToc(toc); + return; + } + + initTocbot(); + setupTocVisibility(toc); + syncToggleButton(toc); + locateToc(); } -function setupToggleButton() { - const toc = document.getElementById("toc"); - const toc_toggle = document.getElementById("toc-toggle"); - - const isVisible = toc.classList.contains('toc-visible'); - toc_toggle.innerHTML = isVisible ? toc_close_icon : toc_icon; - toc_toggle.setAttribute('aria-label', isVisible ? 'Hide Table of Contents' : 'Show Table of Contents'); - - toc_toggle.addEventListener('click', toggleToc); -} - -function hasEnoughSpace() { - const content = document.getElementById("content"); - const toc = document.getElementById("toc"); - if (!content || !toc) return false; - - const contentRect = content.getBoundingClientRect(); - const gap = 12; - const tocExpandedWidth = toc.offsetWidth > 0 +function getTocExpandedWidth(toc) { + return toc.offsetWidth > 0 ? toc.offsetWidth - : parseInt(getComputedStyle(document.documentElement).fontSize) * 17.5; + : Number.parseFloat(getComputedStyle(document.documentElement).fontSize) * FALLBACK_TOC_WIDTH_REM; +} - const spaceRight = window.innerWidth - contentRect.right - gap; +function hasEnoughSpace(content, toc) { + const contentRect = content.getBoundingClientRect(); + const tocExpandedWidth = getTocExpandedWidth(toc); + + const spaceRight = window.innerWidth - contentRect.right - TOC_GAP; return spaceRight >= tocExpandedWidth; } -async function locateToc() { - const toc = document.getElementById("toc"); +function locateToc() { + const toc = getToc(); if (!toc) return; - const content = document.getElementById("content"); + const content = getContent(); if (!content) return; const contentRect = content.getBoundingClientRect(); - const gap = 12; - if (hasEnoughSpace()) { - toc.style.left = `${contentRect.right + gap}px`; - toc.style.right = 'auto'; + if (hasEnoughSpace(content, toc)) { + toc.style.left = `${contentRect.right + TOC_GAP}px`; + toc.style.right = "auto"; } else { - toc.style.left = 'auto'; - toc.style.right = `${gap}px`; - toc.style.top = 'auto'; + toc.style.left = "auto"; + toc.style.right = `${TOC_GAP}px`; + toc.style.top = "auto"; } } function handleResize() { - const toc = document.getElementById("toc"); + const toc = getToc(); if (!toc) return; - setupTocVisibility(); - setupToggleButton(); - void locateToc(); + setupTocVisibility(toc); + syncToggleButton(toc); + locateToc(); } -function debounce(func, wait) { - let timeout; - return function executedFunction(...args) { - const later = () => { - clearTimeout(timeout); - func(...args); - }; - clearTimeout(timeout); - timeout = setTimeout(later, wait); - }; -} - -function destroyToc() { - const toc = document.getElementById("toc") - if (!toc) return; - toc.style.display = "none"; - toc.remove(); - if (typeof tocbot !== 'undefined') { - tocbot.destroy(); - } -} - -async function init_toc() { - void generateToc(); - window.addEventListener('resize', debounce(handleResize, 250)); - -} - -function registerToc() { - document.addEventListener('DOMContentLoaded', () => { - void init_toc(); - }); +function initToc() { + if (resizeListenerRegistered) return; + window.addEventListener("resize", debounce(handleResize, RESIZE_DEBOUNCE_MS)); + resizeListenerRegistered = true; } terminal.registerRefresh(generateToc); -terminal.registerInitFunc(registerToc); \ No newline at end of file +terminal.registerInitFunc(initToc); diff --git a/src/terminal.js b/src/terminal.js index 0fd9981..4cd5811 100644 --- a/src/terminal.js +++ b/src/terminal.js @@ -6,10 +6,12 @@ export class Terminal { } registerRefresh(func) { + if (typeof func !== "function") return; this._refreshFunctions.push(func); } registerInitFunc(func) { + if (typeof func !== "function") return; this._initFunctions.push(func); } @@ -22,5 +24,5 @@ export class Terminal { } } -export var terminal = new Terminal(); -window.terminal = terminal; \ No newline at end of file +export const terminal = new Terminal(); +window.terminal = terminal; diff --git a/src/utils/dom.js b/src/utils/dom.js new file mode 100644 index 0000000..8b1d6bf --- /dev/null +++ b/src/utils/dom.js @@ -0,0 +1,13 @@ +export function debounce(callback, wait = 250) { + let timeoutId; + + return (...args) => { + window.clearTimeout(timeoutId); + timeoutId = window.setTimeout(() => callback(...args), wait); + }; +} + +export function toggleClass(element, className, enabled) { + if (!element) return; + element.classList.toggle(className, enabled); +} diff --git a/templates/error/404.html b/templates/error/404.html index e8263a5..8b973a8 100644 --- a/templates/error/404.html +++ b/templates/error/404.html @@ -10,10 +10,10 @@

- + - \ No newline at end of file + diff --git a/templates/error/5xx.html b/templates/error/5xx.html index 37ecd9c..0d2f438 100644 --- a/templates/error/5xx.html +++ b/templates/error/5xx.html @@ -10,10 +10,10 @@

- + - \ No newline at end of file + diff --git a/templates/error/error.html b/templates/error/error.html index 82125b8..f28748c 100644 --- a/templates/error/error.html +++ b/templates/error/error.html @@ -10,10 +10,10 @@

- + - \ No newline at end of file + diff --git a/templates/modules/header.html b/templates/modules/header.html index bc7a253..7f34ffe 100644 --- a/templates/modules/header.html +++ b/templates/modules/header.html @@ -12,8 +12,8 @@ id="search-button" aria-label="Open Search" type="button" - th:if="${pluginFinder.available('PluginSearchWidget')}" - onclick="SearchWidget.open()"> + data-header-action="open-search" + th:if="${pluginFinder.available('PluginSearchWidget')}"> diff --git a/templates/moments.html b/templates/moments.html index b1ad278..19864ba 100644 --- a/templates/moments.html +++ b/templates/moments.html @@ -17,7 +17,7 @@ mediaGridClass=${mediaSize == 1 ? 'grid-cols-1' : (mediaSize < 5 ? 'grid-cols-2' : 'grid-cols-3')} " class="moment on-list post" - th:attr="x-data=|{ name: '${name}', showComment: false }|"> + th:attr="data-moment-name=${name}">