跳转到内容

MediaWiki:Gadget-ViewerMode.js

来自槌基百科
LocalAdmin留言 | 贡献2026年3月12日 (四) 13:23的版本 (Fix: use direct btn reference so label is set before DOM insertion)

注意:在发布之后,您可能需要清除浏览器缓存才能看到所作出的更改的影响。

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Edge:按住Ctrl的同时单击刷新,或按Ctrl-F5
/**
 * ViewerMode gadget — reader/editor toggle pill in the site header.
 * Also fixes the missing icon on the "My blog" menu item.
 */
( function () {
    'use strict';

    if ( mw.user.isAnon() ) { return; }

    var STORAGE_KEY = 'mw-viewer-mode';
    var active      = localStorage.getItem( STORAGE_KEY ) === '1';
    var btn         = null;   // set once DOM is ready

    /* Apply class immediately to avoid flicker */
    if ( active ) { document.documentElement.classList.add( 'viewer-mode' ); }

    function updateBtn() {
        if ( !btn ) { return; }
        if ( active ) {
            btn.textContent = '✏️ 编辑视图';
            btn.title       = '切换回编辑视图';
            btn.classList.add( 'vm-active' );
        } else {
            btn.textContent = '📖 阅读视图';
            btn.title       = '切换至阅读视图(隐藏编辑工具)';
            btn.classList.remove( 'vm-active' );
        }
    }

    function toggle() {
        active = !active;
        localStorage.setItem( STORAGE_KEY, active ? '1' : '0' );
        document.documentElement.classList.toggle( 'viewer-mode', active );
        updateBtn();
    }

    $( function () {
        /* ── Fix missing icon on "My blog" ─────────────────────── */
        var blogLink = document.querySelector( '#pt-simpleblog_myblog a' );
        if ( blogLink && !blogLink.querySelector( '.vector-icon' ) ) {
            var blogIcon = document.createElement( 'span' );
            blogIcon.className = 'vector-icon mw-ui-icon-article mw-ui-icon-wikimedia-article';
            blogLink.insertBefore( blogIcon, blogLink.firstChild );
        }

        /* ── Build toggle pill and set its label immediately ────── */
        btn = document.createElement( 'button' );
        btn.id        = 'vm-toggle';
        btn.className = 'vm-toggle';
        btn.addEventListener( 'click', toggle );
        updateBtn();   // btn is now in scope — label is set before insertion

        /* Inject into header user-links area */
        var target = document.querySelector( '.vector-user-links-main' ) ||
                     document.querySelector( '.vector-user-links' );
        if ( target ) {
            target.insertBefore( btn, target.firstChild );
        }
    } );
}() );