MediaWiki:Timeless.js:修订间差异

来自「荏苒之境」
无编辑摘要
无编辑摘要
 
(未显示同一用户的1个中间版本)
第1行: 第1行:
/* 将为Timeless皮肤的用户加载此处的所有JavaScript  */
/* 将为Timeless皮肤的用户加载此处的所有JavaScript  */


const ua = navigator.userAgent;
// 精确判断 Safari:Chrome / Edge 的 UA 里也带 "Safari"
const isSafari = /Safari/i.test(ua) && !/Chrome|Chromium|Edg|OPR|CriOS/i.test(ua);
// ---------- 标题追踪 ----------
class HeadingTracker {
class HeadingTracker {
     constructor(rootElement) {
     constructor(rootElement) {
        this.rootElement = rootElement;
    this.rootElement = rootElement
         this.headings = [];
         this.headings = [];
         this.cacheExpired = true;
         this.cacheExpired = true;
第16行: 第11行:
     init() {
     init() {
         this.collectHeadings();
         this.collectHeadings();
         window.addEventListener('resize', () => {
         window.addEventListener('resize', () => this.cacheExpired = true);
            this.cacheExpired = true;
         window.addEventListener('DOMContentLoaded', () => this.cacheExpired = true);
        });
        // 图片/字体加载完可能改变标题位置,加载结束后重新测一次
         window.addEventListener('load', () => this.collectHeadings());
        if (document.readyState === 'loading') {
            document.addEventListener('DOMContentLoaded', () => this.collectHeadings());
        }
     }
     }


     collectHeadings() {
     collectHeadings() {
         const rawHeadings = Array.from(
         const rawHeadings = Array.from(this.rootElement.querySelectorAll('h1, h2, h3, h4, h5, h6'));
            this.rootElement.querySelectorAll('h1, h2, h3, h4, h5, h6')
        );
         this.headings = rawHeadings
         this.headings = rawHeadings
             .map(heading => ({
             .map(heading => ({
第40行: 第27行:


     getNearestHeadingAboveViewport() {
     getNearestHeadingAboveViewport() {
         if (this.cacheExpired) {
         if (this.cacheExpired) this.collectHeadings();
            this.collectHeadings();
 
        }
         const scrollY = window.scrollY + 60;
         const scrollY = window.scrollY + 60;
         let left = 0;
         let left = 0, right = this.headings.length - 1;
        let right = this.headings.length - 1;
         let result = null;
         let result = null;
         while (left <= right) {
         while (left <= right) {
             const mid = Math.floor((left + right) / 2);
             const mid = Math.floor((left + right) / 2);
第60行: 第46行:
}
}


// ---------- 浮动目录 ----------
class FloatingToC {
class FloatingToC {
    constructor(toc) {
constructor(toc) {
        this.element = toc;
this.element = toc;
        this.lastHeading = null;
this.ignoreScrollUpdate = false;
        // 点击目录项后的一小段时间内,忽略滚动事件带来的高亮更新
   
        this.ignoreScrollUntil = 0;
    let tocTextList = Array.from(toc.querySelectorAll(".toctext"));
    this.tocTexts = new Map(tocTextList.map(t => {
    let textContent = t.textContent
    t.parentElement.onclick = () => {
    this.ignoreScrollUpdate = true;
    this.setCurrentHeading(textContent);
    };
    return [textContent, t];
    }));


        // 用标题 id 关联目录项与正文标题,而不是用文字匹配
this.tracker = new HeadingTracker(
        // (标题重名时文字会撞 key,id 不会)
document.getElementById('mw-content-text'));
        this.headingToTocText = new Map();
        for (const text of toc.querySelectorAll('.toctext')) {
this.scrollHandler = this.onScroll.bind(this);
            const link = text.closest('a');
window.addEventListener('scroll', this.scrollHandler);
            if (!link) {
}
                continue;
            }
remove() {
            const id = decodeURIComponent(
window.removeEventListener('scroll', this.scrollHandler);
                (link.getAttribute('href') || '').replace(/^#/, '')
this.element.remove();
            );
}
            const heading = id ? document.getElementById(id) : null;
            if (!heading) {
    setCurrentHeading(heading) {
                continue;
    const lastHeading = this.lastHeading;
            }
    if (heading == lastHeading) {
            this.headingToTocText.set(heading, text);
    return;
            link.addEventListener('click', () => {
    }
                this.ignoreScrollUntil = Date.now() + 500;
    if (lastHeading) {
                this.setCurrentHeading(heading);
    let text = this.tocTexts.get(lastHeading)
            });
    if (text) text.classList.remove('current-heading');
        }
    }
    this.lastHeading = heading;
    if (heading) {
    let text = this.tocTexts.get(heading)
    if (text) text.classList.add('current-heading');
    }
    };
onScroll() {
if (window.innerWidth < 1100) {
return;
}
if (this.ignoreScrollUpdate) {
this.ignoreScrollUpdate = false;
return;
}
    let heading = this.tracker.getNearestHeadingAboveViewport();
    this.setCurrentHeading(heading ? heading.textContent : null);
}
}


        this.tracker = new HeadingTracker(
const userAgent = navigator.userAgent;
            document.getElementById('mw-content-text')
// Chrome/Edge 的 UA 里同样包含 "Safari",需要排除掉,否则宽度阈值会误用
        );
const isSafari = userAgent.includes("Safari") && !/(Chrome|CriOS|Edg|OPR|Android)/i.test(userAgent);


        this.scrollHandler = this.onScroll.bind(this);
mw.hook('ve.newTarget').add(target => {
        window.addEventListener('scroll', this.scrollHandler);
if (target.constructor.static.name !== 'article') {
    }
return;
 
}
    remove() {
target.on('teardown', () => {
        window.removeEventListener('scroll', this.scrollHandler);
var event = new CustomEvent("pageupdate");
        this.element.remove();
document.dispatchEvent(event);
    }
});
 
});
    setCurrentHeading(heading) {
        if (heading === this.lastHeading) {
            return;
        }
        if (this.lastHeading) {
            const text = this.headingToTocText.get(this.lastHeading);
            if (text) {
                text.classList.remove('current-heading');
            }
        }
        this.lastHeading = heading;
        if (heading) {
            const text = this.headingToTocText.get(heading);
            if (text) {
                text.classList.add('current-heading');
            }
        }
    }
 
    onScroll() {
        if (window.innerWidth < 1100) {
            return;
        }
        if (Date.now() < this.ignoreScrollUntil) {
            return;
        }
        const heading = this.tracker.getNearestHeadingAboveViewport();
        this.setCurrentHeading(heading);
    }
}


// ---------- 状态 ----------
let toc = null;
let toc = null;
let tocInitialParent = null;   // 目录原本在哪个容器里
let tocInitialParent = null;
let tocNextSibling = null;    // 目录原本插在哪个元素前面(还原用)
let floatingToC = null;
let floatingToC = null;
let siteNavigation = null;
let siteNavigation = null;


// ---------- 目录的移动逻辑 ----------
const updateToCParent = () => {
function isWideEnough() {
// 两个依赖元素都就绪后才真正搬移,避免竞态导致 ToC 一直留在文章容器里
    return isSafari ? window.innerWidth > 1354 : window.innerWidth > 1339;
if (siteNavigation == null || toc == null) {
}
return;
 
}
function findArticleTOC() {
let width = window.innerWidth;
    const content = document.getElementById('mw-content-text');
if (isSafari && width > 1354 || !isSafari && width > 1339) {
    return content ? content.querySelector('#toc') : null;
if (toc.parentNode != siteNavigation) {
}
toc.parentNode.removeChild(toc);
 
siteNavigation.appendChild(toc);
function restoreTOCToArticle() {
}
    if (tocInitialParent == null) {
}
        return;
else {
    }
if (toc.parentNode == tocInitialParent || toc.parentNode == siteNavigation) {
    if (tocNextSibling && tocNextSibling.parentNode === tocInitialParent) {
toc.parentNode.removeChild(toc);
        tocInitialParent.insertBefore(toc, tocNextSibling);
siteNavigation.parentNode.lastChild.before(toc);
    } else {
}
        tocInitialParent.appendChild(toc);
}
    }
}
 
function updateToCParent() {
    if (siteNavigation == null || toc == null) {
        return;
    }
    if (isWideEnough()) {
        // 宽屏:进侧边栏
        if (toc.parentNode !== siteNavigation) {
            siteNavigation.appendChild(toc);
        }
        return;
    }
    // 窄屏:放回文章里原本的位置
    if (toc.parentNode === siteNavigation) {
        restoreTOCToArticle();
    }
}
}
document.addEventListener('pageupdate', () => {
let newToC = document.querySelectorAll('.mw-parser-output > #toc')[0];
if (newToC == null) {
return;
}
if (floatingToC != null) {
floatingToC.remove();
}
toc = newToC;
tocInitialParent = toc.parentNode;
floatingToC = new FloatingToC(toc);
updateToCParent();
});


// ---------- 初始化 / 清理 ----------
function waitForElement(selector, callback) {
function teardownFloatingToC() {
// 元素如果已经存在于 DOM(ResourceLoader 的脚本常在页面渲染后才执行),
    if (floatingToC != null) {
// 必须立刻回调;否则只挂 MutationObserver 会永远等不到变化,整段逻辑都不运行。
        floatingToC.remove();
const existing = document.querySelector(selector);
        floatingToC = null;
if (existing) {
    }
callback(existing);
    toc = null;
return;
    tocInitialParent = null;
}
    tocNextSibling = null;
const observer = new MutationObserver(() => {
const element = document.querySelector(selector);
if (element) {
observer.disconnect(); // 找到后停止观察
callback(element);
}
});
observer.observe(document.body, { childList: true, subtree: true }); // 观察整个文档的变化
}
}


function initFloatingToC(newToc) {
waitForElement('#mw-site-navigation', elem => {
    if (newToc == null || newToc === toc) {
siteNavigation = elem;
        return;
// 侧栏就绪后必须重新触发一次搬移判断:如果 ToC 先加载完成,
    }
// 上面那次 updateToCParent 会因 siteNavigation 仍为 null 提前 return,
    if (floatingToC != null) {
// 之后没有任何代码再搬它,卡片就会一直卡在文章容器里。
        // 旧的目录可能还挂在侧边栏里,先摘掉再重新初始化
updateToCParent();
        floatingToC.remove();
        floatingToC = null;
    }
    toc = newToc;
    tocInitialParent = toc.parentNode;
    tocNextSibling = toc.nextSibling;
    floatingToC = new FloatingToC(toc);
    updateToCParent();
}
 
// 等待元素出现:先检查当前 DOM,没有再挂 MutationObserver。
// 之前只挂 observer,页面加载完就绪、没有任何后续变更时回调永远不会触发。
function waitForElement(getElement, callback) {
    const element = getElement();
    if (element) {
        callback(element);
        return;
    }
    const observer = new MutationObserver(() => {
        const el = getElement();
        if (el) {
            observer.disconnect();
            callback(el);
        }
    });
    observer.observe(document.body, { childList: true, subtree: true });
}
 
// VE 保存后内容重渲染,重走一遍:清掉旧目录,等新目录出现
document.addEventListener('pageupdate', () => {
    teardownFloatingToC();
    waitForElement(findArticleTOC, initFloatingToC);
});
});


// 启动:两个元素谁先出现都能收敛到正确状态
waitForElement('#toc', loadedToc => {
waitForElement(() => document.getElementById('mw-site-navigation'), elem => {
toc = loadedToc;
    siteNavigation = elem;
tocInitialParent = toc.parentElement;
    updateToCParent(); // 目录可能先出现,这里补一次移动
floatingToC = new FloatingToC(toc);
updateToCParent();
});
});


waitForElement(findArticleTOC, initFloatingToC);
// 窗口宽度变化时重新判断 ToC 该留在侧栏还是回到正文,避免卡片停在错误的容器里
 
window.addEventListener('resize', updateToCParent);
// 跨断点缩放时也要重新摆放目录
window.addEventListener('resize', () => updateToCParent());

2026年9月3日 (四) 21:55的最新版本

/* 将为Timeless皮肤的用户加载此处的所有JavaScript  */

class HeadingTracker {
    constructor(rootElement) {
    	this.rootElement = rootElement
        this.headings = [];
        this.cacheExpired = true;
        this.init();
    }

    init() {
        this.collectHeadings();
        window.addEventListener('resize', () => this.cacheExpired = true);
        window.addEventListener('DOMContentLoaded', () => this.cacheExpired = true);
    }

    collectHeadings() {
        const rawHeadings = Array.from(this.rootElement.querySelectorAll('h1, h2, h3, h4, h5, h6'));
        this.headings = rawHeadings
            .map(heading => ({
                element: heading,
                top: heading.getBoundingClientRect().top + window.scrollY
            }))
            .sort((a, b) => a.top - b.top);
        this.cacheExpired = false;
    }

    getNearestHeadingAboveViewport() {
        if (this.cacheExpired) this.collectHeadings();

        const scrollY = window.scrollY + 60;
        let left = 0, right = this.headings.length - 1;
        let result = null;

        while (left <= right) {
            const mid = Math.floor((left + right) / 2);
            if (this.headings[mid].top <= scrollY) {
                result = this.headings[mid].element;
                left = mid + 1;
            } else {
                right = mid - 1;
            }
        }
        return result;
    }
}

class FloatingToC {
	constructor(toc) {
		this.element = toc;
		this.ignoreScrollUpdate = false;
	    
	    let tocTextList = Array.from(toc.querySelectorAll(".toctext"));
	    this.tocTexts = new Map(tocTextList.map(t => {
	    	let textContent = t.textContent
	    	t.parentElement.onclick = () => {
	    		this.ignoreScrollUpdate = true;
	    		this.setCurrentHeading(textContent);
	    	};
	    	return [textContent, t];
	    }));

		this.tracker = new HeadingTracker(
			document.getElementById('mw-content-text'));
		
		this.scrollHandler = this.onScroll.bind(this);
		window.addEventListener('scroll', this.scrollHandler);
	}
	
	remove() {
		window.removeEventListener('scroll', this.scrollHandler);
		this.element.remove();
	}
	
    setCurrentHeading(heading) {
    	const lastHeading = this.lastHeading;
    	if (heading == lastHeading) {
    		return;
    	}
    	if (lastHeading) {
    		let text = this.tocTexts.get(lastHeading)
    		if (text) text.classList.remove('current-heading');
    	}
    	this.lastHeading = heading;
    	if (heading) {
    		let text = this.tocTexts.get(heading)
    		if (text) text.classList.add('current-heading');
    	}
    };
	
	onScroll() {
		if (window.innerWidth < 1100) {
			return;
		}
		if (this.ignoreScrollUpdate) {
			this.ignoreScrollUpdate = false;
			return;
		}
	    let heading = this.tracker.getNearestHeadingAboveViewport();
	    this.setCurrentHeading(heading ? heading.textContent : null);
	}
}

const userAgent = navigator.userAgent;
// Chrome/Edge 的 UA 里同样包含 "Safari",需要排除掉,否则宽度阈值会误用
const isSafari = userAgent.includes("Safari") && !/(Chrome|CriOS|Edg|OPR|Android)/i.test(userAgent);

mw.hook('ve.newTarget').add(target => {
	if (target.constructor.static.name !== 'article') {
		return;
	}
	target.on('teardown', () => {
		var event = new CustomEvent("pageupdate");
		document.dispatchEvent(event);
	});
});

let toc = null;
let tocInitialParent = null;
let floatingToC = null;
let siteNavigation = null;

const updateToCParent = () => {
	// 两个依赖元素都就绪后才真正搬移,避免竞态导致 ToC 一直留在文章容器里
	if (siteNavigation == null || toc == null) {
		return;
	}
	let width = window.innerWidth;
	if (isSafari && width > 1354 || !isSafari && width > 1339) {
		if (toc.parentNode != siteNavigation) {
			toc.parentNode.removeChild(toc);
			siteNavigation.appendChild(toc);
		}
	}
	else {
		if (toc.parentNode == tocInitialParent || toc.parentNode == siteNavigation) {
			toc.parentNode.removeChild(toc);
			siteNavigation.parentNode.lastChild.before(toc);
		}
	}
}
	
document.addEventListener('pageupdate', () => {
	let newToC = document.querySelectorAll('.mw-parser-output > #toc')[0];
	if (newToC == null) {
		return;
	}
	if (floatingToC != null) {
		floatingToC.remove();
	}
	toc = newToC;
	tocInitialParent = toc.parentNode;
	floatingToC = new FloatingToC(toc);
	updateToCParent();
});

function waitForElement(selector, callback) {
	// 元素如果已经存在于 DOM(ResourceLoader 的脚本常在页面渲染后才执行),
	// 必须立刻回调;否则只挂 MutationObserver 会永远等不到变化,整段逻辑都不运行。
	const existing = document.querySelector(selector);
	if (existing) {
		callback(existing);
		return;
	}
	const observer = new MutationObserver(() => {
		const element = document.querySelector(selector);
		if (element) {
			observer.disconnect(); // 找到后停止观察
			callback(element);
		}
	});
	observer.observe(document.body, { childList: true, subtree: true }); // 观察整个文档的变化
}

waitForElement('#mw-site-navigation', elem => {
	siteNavigation = elem;
	// 侧栏就绪后必须重新触发一次搬移判断:如果 ToC 先加载完成,
	// 上面那次 updateToCParent 会因 siteNavigation 仍为 null 提前 return,
	// 之后没有任何代码再搬它,卡片就会一直卡在文章容器里。
	updateToCParent();
});

waitForElement('#toc', loadedToc => {
	toc = loadedToc;
	tocInitialParent = toc.parentElement;
	floatingToC = new FloatingToC(toc);
	updateToCParent();
});

// 窗口宽度变化时重新判断 ToC 该留在侧栏还是回到正文,避免卡片停在错误的容器里
window.addEventListener('resize', updateToCParent);