refactor: improve code maintainability

This commit is contained in:
Erzbir
2026-06-15 22:06:13 +08:00
parent 72346d78d2
commit fdec0aafa1
12 changed files with 421 additions and 291 deletions
+32 -24
View File
@@ -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);
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);
+32 -12
View File
@@ -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);
terminal.registerInitFunc(registerSearchButton);
terminal.registerInitFunc(registerPixelToggle);
terminal.registerInitFunc(registerThemeToggle);
+86 -33
View File
@@ -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;
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);
+125 -122
View File
@@ -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);
terminal.registerInitFunc(initToc);