User:SunAfterRain/js/vector-2022-toc-covert-fix.js
外观
< User:SunAfterRain | js
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
/* jshint esversion: 8 */
// <nowiki>
$( async function () {
const $toc = $( "nav#mw-panel-toc" );
if ( mw.config.get( "skin" ) !== "vector-2022" || !$toc.length ) {
return;
}
function jQueryToHtml( $p ) {
return $( "<div>" ).append( $p ).html();
}
const api = new mw.Api();
await api.getMessages( [ "vector-toc-toggle-button-label" ] ).then( mw.messages.set.bind( mw.messages ) );
const { parse: { sections } } = await api.get( {
action: "parse",
variant: mw.config.get( "wgUserVariant" ),
page: mw.config.get( "wgPageName" ),
prop: "sections"
} );
const sectionsHtml = sections.map( function ( v ) {
return $( "<span>" )
.attr( {
class: "toc-precovert-item",
"data-rawId": v.anchor.replace( /{{/g, "{<nowiki />{" )
} )
.text( v.line );
} ).map( jQueryToHtml ).join( "" );
const covertHtml = await api.parse(
"<div style=\"display: none;\">{{ {{FULLPAGENAME}} }}</div><div id=\"toc-precovert-body\">" + sectionsHtml + "<div>",
{
variant: mw.config.get( "wgUserVariant" ),
title: mw.config.get( "wgPageName" )
}
);
const $preCovertBody = $( $.parseHTML( covertHtml ) ).find( "#toc-precovert-body" );
$preCovertBody.find( ".toc-precovert-item" ).toArray().forEach( function ( e ) {
const $that = $( e );
const $thisToc = $toc.find( "li#toc-" + $that.attr( "data-rawId" ).replace( /([:(){}])/g, "\\$1" ) );
if ( !$thisToc.length ) {
console.log( "[vector-2022-toc-covert-fix] Skip unknown toc item %s", $that.attr( "data-rawId" ) );
return;
}
const $text = $thisToc.find( ".sidebar-toc-text" );
if ( !$text.length ) {
console.log( "[vector-2022-toc-covert-fix] Skip unknown toc item \"nav#mw-panel-toc li#toc-%s .sidebar-toc-text\"", $that.attr( "data-rawId" ) );
return;
}
let html = "";
if ( $text.find( ".sidebar-toc-numb" ).length ) {
html = "<span class=\"sidebar-toc-numb\">" + $text.find( ".sidebar-toc-numb" ).text() + "</span>";
}
html += $that.text();
$text.html( html );
const $subToc = $thisToc.find( "button.sidebar-toc-toggle" );
if ( $subToc.length ) {
$subToc.html( mw.msg( "vector-toc-toggle-button-label", $that.text() ) );
}
} );
} );
// </nowiki>