mirror of
https://github.com/hugo-fixit/FixIt.git
synced 2026-08-24 15:28:57 +00:00
14a965f9c1
* refactor: add TypeScript support and refactor utility functions * docs: add CLAUDE.md for Claude Code guidance Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(assets): replace factory-function pattern with service classes and DI container Introduce typed service container, event bus, and service interfaces to replace the shared FixItContext factory-function pattern. Each module is now a standalone class implementing a typed interface, with explicit constructor-injected dependencies. The window.fixit backward-compatibility facade is built via a publicAPI() helper that extracts class methods. Also removes unnecessary setTimeout/afterPaint deferred execution wrappers from init sequences, and improves module header comments. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor: replace private properties with class fields in modules Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * refactor(assets): rewrite link page script in TypeScript Rename pages/link.js to link.ts with proper type annotations and update the Hugo template reference accordingly. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * docs: rewrite CLAUDE.md and copilot-instructions.md in English Update both files to reflect the new service-class architecture with DI container, typed event bus, and ES6 # private fields. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com> * fix: update event handling to use CustomEvent for better type safety * refactor: enhance theme switching by adding isChanged flag to event details * refactor(assets): refactor Mermaid module structure and event wiring * refactor(assets): align lib integrations with TypedEventBus and add module overviews * chore(assets): remove vite-specific import ignore comments * refactor(assets): remove deprecated forEach utility and use native forEach Replace custom forEach wrapper with native .forEach() on NodeList, HTMLCollection (via querySelectorAll), and arrays. The utility was already marked @deprecated and all 30+ call sites use synchronous handlers, making the wrapper unnecessary. Also replace getElementsByClassName/getElementsByTagName with querySelectorAll for consistency. - Delete utils/array.ts (no longer needed) - Remove forEach export from utils/index.ts - Refactor 11 module files to use native .forEach() - Switch getElementsByClassName to querySelectorAll in theme.ts and charts.ts * refactor(assets): split ChartsModule into independent lib files Move ECharts, Mapbox GL, and TypeIt integrations from the ServiceContainer-managed ChartsModule into three standalone lib files (echarts.ts, mapbox.ts, typeit.ts). Each lib: - Instantiates its own TypedEventBus - Reads config from window.config.* - Self-initializes on DOMContentLoaded - Handles decrypt/re-init events independently - Uses implicit idempotency via DOM element queries Key improvements: - Reduces ServiceContainer complexity - Makes chart libs independently loadable - Fixes partial decryption handling in echarts (only re-inits decrypted portion) - Maintains consistency with aplayer/file-tree lib pattern * refactor(assets): extract third-party libraries to standalone lib files Extract twemoji, pangu, cookieconsent, watermark, lightgallery, and json-viewer from modules into separate lib files for better separation of concerns. Each lib is loaded conditionally via assets.html and handles its own initialization and event lifecycle independently. Additionally, unify fixit event handling by replacing document.addEventListener calls with TypedEventBus.on() in EncryptionModule and MiscModule for consistent event architecture. Remove unused MiscService dependency from ContentModule. * refactor(assets): unify js.Build pipeline and defaults - extract shared helper partial function/js-build.html for js.Build + minify - make plugin script renderer and Mermaid use the same js.Build logic - default Build.minify to hugo.IsProduction when unset - default Build.sourceMap to cond hugo.IsDevelopment "linked" "none" - remove duplicated sourceMap branching in layout templates - update js targetPath naming to .js (no explicit .min.js suffix) * refactor(assets): extract comment systems to independent lib files Extract comment system initialization logic from CommentModule into 7 independent lib files (artalk, gitalk, valine, waline, utterances, twikoo, giscus). Each lib: - Conditionally loads based on window.config.comment configuration - Handles backend-specific initialization via DOMContentLoaded - Manages its own theme synchronization and event listeners - Is loaded conditionally in assets.html only when enabled Simplify CommentModule to handle only: - Comment section UI display and visibility toggle - Shared lightGallery initialization utility (used by Artalk and Twikoo) - Comment expiration handling This reduces module complexity and enables per-backend lazy loading. * refactor(assets): unify js.Build pipeline and consolidate PWA config Enhance js-build.html to accept Build as bool/dict, auto-derive targetPath from resource name (.ts → .js), and skip js.Build when Build is false/omit. Simplify assets.html by removing explicit targetPath dicts for all .ts lib builds. Consolidate enablePWA and serviceWorkerURL into a PWA config object. * refactor(assets): decouple toc from content module and add JSDoc headers - Remove TocService dependency from ContentModule, toc now self-manages - Rename initContent() → setup(), init() → setup() for toc - Make initFootnotes private (#initFootnotes) - Add multi-line JSDoc headers with Responsibilities to all modules, main.ts, pages/link.ts, and head/color-scheme.ts * refactor(assets): split types.ts into types/ directory module * refactor(assets): simplify JS module architecture and expose typed window.fixit API - Remove DI container (core/container.ts), use direct constructor calls - Export shared eventBus singleton from core/event-bus.ts, remove 16 redundant instances - Merge thin modules: SvgModule/CommentModule/LinkGuardModule into ContentModule/MiscModule - Trim service interfaces to externally-used methods only - Replace publicAPI() reflection with minimal typed window.fixit facade - Expose public APIs: setThemeMode, eventBus, initContent, mask overlay, scroll state - Extract setThemeMode from initSwitchTheme closure as public method - Rename fixit:reset to fixit:re-encrypt, remove dead events - Replace custom.js.example with custom.ts.example - Update CLAUDE.md and copilot-instructions.md * style(i18n): use semantic names for comment dividers instead of file paths Replace file-path-based comment dividers (e.g. partials/base/header.html) with semantic names (e.g. Header) across all 16 i18n files for consistency. * chore(workflow): update cron schedule for library updates --------- Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
282 lines
11 KiB
TypeScript
282 lines
11 KiB
TypeScript
import type { TocService } from '../core/tokens'
|
|
import { animateCSS, isTocStatic } from '../utils'
|
|
|
|
/**
|
|
* Table of Contents module — TOC scroll tracking, active state sync, and dialog.
|
|
*
|
|
* Responsibilities:
|
|
* - Move TOC node to the correct container (static, auto, or drawer) on init.
|
|
* - Track scroll position and highlight the active heading in all TOC containers.
|
|
* - Initialize mobile TOC drawer dialog and its open/close handlers.
|
|
* - Clone TOC nodes to detach APlayer event listeners.
|
|
*/
|
|
export class TocModule implements TocService {
|
|
private activeTocId: string | null = null
|
|
|
|
/** Get the pixel height of the currently visible sticky header. */
|
|
getVisibleHeaderOffset(): number {
|
|
const $desktopHeader = document.getElementById('header-desktop')
|
|
const $mobileHeader = document.getElementById('header-mobile')
|
|
const $header = [$desktopHeader, $mobileHeader].find($el => $el && window.getComputedStyle($el).display !== 'none')
|
|
if (!$header)
|
|
return 0
|
|
const isDesktop = $header.id === 'header-desktop'
|
|
const headerMode = isDesktop ? document.body.dataset.headerDesktop : document.body.dataset.headerMobile
|
|
if (!['sticky', 'auto'].includes(headerMode!))
|
|
return 0
|
|
if (headerMode === 'auto' && $header.classList.contains('header__fadeOutUp'))
|
|
return 0
|
|
return $header.offsetHeight
|
|
}
|
|
|
|
/** Get the pixel height of the breadcrumb container. */
|
|
getBreadcrumbHeight(): number {
|
|
return document.querySelector<HTMLElement>('.breadcrumb-container')?.offsetHeight || 0
|
|
}
|
|
|
|
/** Get the combined vertical offset used to determine the active TOC heading. */
|
|
getTocIndexOffset(): number {
|
|
return 20 + this.getVisibleHeaderOffset() + this.getBreadcrumbHeight()
|
|
}
|
|
|
|
/** Get all heading elements that have an `id` attribute. */
|
|
getTocHeadingElements(): HTMLElement[] {
|
|
return Array.from(document.querySelectorAll<HTMLElement>('.heading-element[id]'))
|
|
}
|
|
|
|
/**
|
|
* Determine which heading is currently active based on scroll position.
|
|
* @param $headingElements - Array of heading elements with `id` attributes.
|
|
* @param indexOffset - Vertical offset from the top for the active threshold.
|
|
* @returns The active heading element, or `null` if none found.
|
|
*/
|
|
getActiveTocHeading($headingElements: HTMLElement[], indexOffset = this.getTocIndexOffset()): HTMLElement | null {
|
|
if (!$headingElements.length)
|
|
return null
|
|
const threshold = window.scrollY + indexOffset + 1
|
|
let $activeHeading = $headingElements[0]
|
|
for (const $heading of $headingElements) {
|
|
const headingTop = window.scrollY + $heading.getBoundingClientRect().top
|
|
if (headingTop <= threshold) {
|
|
$activeHeading = $heading
|
|
}
|
|
else {
|
|
break
|
|
}
|
|
}
|
|
return $activeHeading
|
|
}
|
|
|
|
/** Get all TOC root containers (static, auto, and drawer). */
|
|
getTocRoots(): HTMLElement[] {
|
|
return [
|
|
document.getElementById('TableOfContents'),
|
|
document.querySelector<HTMLElement>('#toc-content-static > nav'),
|
|
document.querySelector<HTMLElement>('#toc-content-drawer > nav'),
|
|
].filter(Boolean) as HTMLElement[]
|
|
}
|
|
|
|
/**
|
|
* Find the TOC link that points to the given heading id.
|
|
* @param $tocRoot - The TOC root container element.
|
|
* @param id - The heading id (without `#`).
|
|
* @returns The matching anchor element, or `null`.
|
|
*/
|
|
getTocLinkById($tocRoot: HTMLElement, id: string): HTMLAnchorElement | null {
|
|
if (!$tocRoot || !id)
|
|
return null
|
|
const targetHash = `#${id}`
|
|
return Array.from($tocRoot.querySelectorAll<HTMLAnchorElement>('a[href^="#"]')).find($link => $link.getAttribute('href') === targetHash) || null
|
|
}
|
|
|
|
/**
|
|
* Highlight the active TOC item and its parent chain.
|
|
* @param $tocRoot - The TOC root container element.
|
|
* @param activeId - The id of the currently active heading.
|
|
*/
|
|
applyTocActiveState($tocRoot: HTMLElement, activeId: string) {
|
|
if (!$tocRoot)
|
|
return
|
|
$tocRoot.querySelectorAll('a[href^="#"]').forEach(($tocLink: Element) => {
|
|
$tocLink.classList.remove('active')
|
|
})
|
|
$tocRoot.querySelectorAll('li').forEach(($tocLi: Element) => {
|
|
$tocLi.classList.remove('has-active')
|
|
})
|
|
const $activeLink = this.getTocLinkById($tocRoot, activeId)
|
|
if (!$activeLink)
|
|
return
|
|
$activeLink.classList.add('active')
|
|
let $parent = $activeLink.closest('li')
|
|
while ($parent) {
|
|
$parent.classList.add('has-active')
|
|
$parent = $parent.parentElement?.closest('li') || null
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Scroll the active TOC link into the visible area of its container.
|
|
* @param $tocRoot - The TOC root container element.
|
|
* @param activeId - The id of the currently active heading.
|
|
* @param $scrollContainer - The scrollable container (defaults to `$tocRoot`).
|
|
*/
|
|
scrollActiveTocLinkIntoView($tocRoot: HTMLElement, activeId: string, $scrollContainer: HTMLElement = $tocRoot) {
|
|
const $activeLink = this.getTocLinkById($tocRoot, activeId)
|
|
if (!$activeLink || !$scrollContainer)
|
|
return
|
|
const containerRect = $scrollContainer.getBoundingClientRect()
|
|
const linkRect = $activeLink.getBoundingClientRect()
|
|
const offsetTop = linkRect.top - containerRect.top
|
|
const offsetBottom = linkRect.bottom - containerRect.bottom
|
|
if (offsetTop < 0) {
|
|
$scrollContainer.scrollTop += offsetTop
|
|
}
|
|
else if (offsetBottom > 0) {
|
|
$scrollContainer.scrollTop += offsetBottom
|
|
}
|
|
}
|
|
|
|
/** Update the TOC container's max-height CSS variable to fit the viewport. */
|
|
syncTocHeight() {
|
|
const $toc = document.getElementById('toc-auto')
|
|
const $tocContentAuto = document.getElementById('toc-content-auto')
|
|
if ($toc && $tocContentAuto) {
|
|
const maxHeight = Math.max(window.innerHeight - $tocContentAuto.getBoundingClientRect().top - 16)
|
|
$tocContentAuto.style.setProperty('--fi-toc-content-max-height', `${Math.floor(maxHeight)}px`)
|
|
}
|
|
}
|
|
|
|
/** Sync the active heading highlight across all TOC containers. */
|
|
syncTocActiveState() {
|
|
const $headingElements = this.getTocHeadingElements()
|
|
const $activeHeading = this.getActiveTocHeading($headingElements)
|
|
if (!$activeHeading?.id)
|
|
return
|
|
const activeId = $activeHeading.id
|
|
const $tocRoots = this.getTocRoots()
|
|
$tocRoots.forEach(($tocRoot) => {
|
|
this.applyTocActiveState($tocRoot, activeId)
|
|
})
|
|
if (this.activeTocId !== activeId) {
|
|
this.activeTocId = activeId
|
|
if (!isTocStatic()) {
|
|
const $autoTocRoot = document.getElementById('TableOfContents')
|
|
const $autoTocContainer = document.getElementById('toc-content-auto')
|
|
if ($autoTocRoot && $autoTocContainer) {
|
|
this.scrollActiveTocLinkIntoView($autoTocRoot, activeId, $autoTocContainer)
|
|
}
|
|
}
|
|
if ((document.getElementById('toc-dialog') as HTMLDialogElement)?.open) {
|
|
const $dialogTocRoot = document.querySelector<HTMLElement>('#toc-content-drawer > nav')!
|
|
this.scrollActiveTocLinkIntoView($dialogTocRoot, activeId, $dialogTocRoot)
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Initialize TOC layout: move the TOC node to the correct container and sync state. */
|
|
initToc() {
|
|
const $tocCore = document.getElementById('TableOfContents')
|
|
if ($tocCore === null)
|
|
return
|
|
// TOC Drawer Button Visibility
|
|
const openButton = document.querySelector<HTMLElement>('#toc-drawer-button')
|
|
if (openButton) {
|
|
openButton.classList.toggle('d-none', !isTocStatic())
|
|
}
|
|
this.activeTocId = null
|
|
// TOC Static and TOC Dialog
|
|
if (isTocStatic()) {
|
|
const $tocContentStatic = document.getElementById('toc-content-static')!
|
|
if ($tocCore.parentElement !== $tocContentStatic) {
|
|
$tocCore.parentElement!.removeChild($tocCore)
|
|
$tocContentStatic.appendChild($tocCore)
|
|
}
|
|
this.syncTocHeight()
|
|
this.syncTocActiveState()
|
|
return
|
|
}
|
|
|
|
// TOC Auto
|
|
const $tocContentAuto = document.getElementById('toc-content-auto')!
|
|
if ($tocCore.parentElement !== $tocContentAuto) {
|
|
$tocCore.parentElement!.removeChild($tocCore)
|
|
$tocContentAuto.appendChild($tocCore)
|
|
}
|
|
const $toc = document.getElementById('toc-auto')!
|
|
$toc.style.visibility = 'visible'
|
|
animateCSS($toc, ['animate__fadeIn', 'animate__faster'], true)
|
|
this.syncTocHeight()
|
|
this.syncTocActiveState()
|
|
}
|
|
|
|
/** Bind the TOC title click handler for show/hide toggle. */
|
|
initTocListener() {
|
|
const $toc = document.getElementById('toc-auto')!
|
|
const $tocContentAuto = document.getElementById('toc-content-auto')!
|
|
document.querySelector<HTMLElement>('#toc-auto>.toc-title')?.addEventListener('click', () => {
|
|
const animation = ['animate__faster']
|
|
const tocHidden = $toc.classList.contains('toc-hidden')
|
|
animation.push(tocHidden ? 'animate__fadeIn' : 'animate__fadeOut')
|
|
if (tocHidden) {
|
|
$tocContentAuto.classList.remove('d-none', 'animate__fadeOut')
|
|
}
|
|
else {
|
|
$tocContentAuto.classList.remove('animate__fadeIn')
|
|
}
|
|
animateCSS($tocContentAuto, animation, true, () => {
|
|
$tocContentAuto.classList.contains('animate__fadeOut') && $tocContentAuto.classList.add('d-none')
|
|
})
|
|
$toc.classList.toggle('toc-hidden')
|
|
}, false)
|
|
}
|
|
|
|
/** Initialize the mobile TOC drawer dialog and its open/close handlers. */
|
|
initTocDialog() {
|
|
const dialog = document.querySelector<HTMLDialogElement>('#toc-dialog')
|
|
const openButton = document.querySelector<HTMLElement>('#toc-drawer-button')
|
|
if (!dialog || !openButton)
|
|
return
|
|
const closeButton = dialog.querySelector<HTMLElement>('.toc-close-btn')
|
|
closeButton?.addEventListener('click', () => dialog.close())
|
|
openButton.addEventListener('click', () => {
|
|
dialog.showModal()
|
|
openButton.setAttribute('aria-expanded', 'true')
|
|
this.syncTocHeight()
|
|
this.syncTocActiveState()
|
|
const $dialogTocRoot = document.querySelector<HTMLElement>('#toc-content-drawer > nav')!
|
|
this.scrollActiveTocLinkIntoView($dialogTocRoot, this.activeTocId!, $dialogTocRoot)
|
|
;(document.activeElement as HTMLElement)?.blur()
|
|
})
|
|
document.querySelectorAll<HTMLAnchorElement>('#toc-content-drawer a[href^="#"]').forEach(($link) => {
|
|
$link.addEventListener('click', () => dialog.close())
|
|
})
|
|
dialog.addEventListener('close', () => {
|
|
openButton.setAttribute('aria-expanded', 'false')
|
|
})
|
|
}
|
|
|
|
/** Clone TOC and heading-mark nodes to detach APlayer event listeners. */
|
|
fixTocScroll() {
|
|
if (typeof window.APlayer === 'function') {
|
|
let $tocCore = document.getElementById('TableOfContents')
|
|
if ($tocCore) {
|
|
const $newTocCore = $tocCore.cloneNode(true) as HTMLElement
|
|
$tocCore.parentElement!.replaceChild($newTocCore, $tocCore)
|
|
$tocCore = $newTocCore
|
|
}
|
|
document.querySelectorAll('.heading-mark').forEach(($headingMark: Element) => {
|
|
const $newHeadingMark = $headingMark.cloneNode(true)
|
|
$headingMark.parentElement!.replaceChild($newHeadingMark, $headingMark)
|
|
})
|
|
}
|
|
}
|
|
|
|
/** Initialize all TOC components and register event listeners. */
|
|
setup() {
|
|
this.fixTocScroll()
|
|
this.initToc()
|
|
this.initTocListener()
|
|
this.initTocDialog()
|
|
}
|
|
}
|