LLWiki正在建设中,欢迎加入我们

MediaWiki:Gadget-inspect.js

来自LLWiki
Bhsd讨论 | 贡献2020年12月23日 (三) 01:11的版本
跳转到导航 跳转到搜索

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

  • Firefox或Safari:按住Shift的同时单击刷新,或按Ctrl-F5Ctrl-R(Mac为⌘-R
  • Google Chrome:Ctrl-Shift-R(Mac为⌘-Shift-R
  • Internet Explorer:按住Ctrl的同时单击刷新,或按Ctrl-F5
  • Opera:前往菜单 → 设置(Mac为Opera → Preferences),然后隐私和安全 → 清除浏览数据 → 缓存的图片和文件
// 由ResourceLoader直接调用,不可使用ES6语法
/**
 * @Author: [[User:Bhsd]]
 */
"use strict";
/*global mw, $, OO, CodeMirror, wgULS*/
const id = mw.config.get( 'wgArticleId' ),
    script = mw.config.get('wgScript'),
    gadgets = mw.gadgets || {},
    inspect = gadgets.inspect || {},
    rule = inspect.rule || true;
if (id > 0 && mw.config.get( 'wgNamespaceNumber' ) != 10 && mw.config.get('wgAction') == 'view' &&
    mw.config.get( 'wgPageContentModel' ) == 'wikitext' && !mw.util.getParamValue( 'oldid' ) &&
    !mw.util.getParamValue( 'diff' ) && rule) {
    const api = new mw.Api(),
        getJSON = $.ajax({ dataType: 'json', cache: true,
        url: script + '?title=mediawiki:gadget-CodeMirror.json&action=raw&ctype=application/json' });
    mw.request = mw.request || api.get({action: 'query', revids: mw.config.get('wgRevisionId'), prop: 'revisions',
        rvprop: 'content', curtimestamp: 1, formatversion: 2});
    const css = mw.util.addCSS( '#mw-content-text .mw-parser-output p { border:1px dashed; }' +
        '#mw-content-text .mw-parser-output { display:flow-root; overflow:hidden; word-wrap:break-word; }'),
        cssHide = mw.util.addCSS( '.inspector > div:last-child { margin-bottom:0.5em; }' +
        '.inspector { position:fixed; right:24px; left:unset !important; width:calc(50% - 7rem - 0.5px); }' );
    cssHide.disabled = true;
    var dialog, actionP, actionD, text, editor, wrapper, nextid;
    const $content = $('#mw-content-text, #mw-imagepage-content').last(),
        original = $content.children( '.mw-parser-output' ),
        placeholder = $('<div>', {class: "mw-parser-output"}).css('display', 'none'),
        urlDisplay = $('<a>', {href: "#"}).click(function(e) { e.preventDefault(); }),
        outer = $('<div>', {class: 'inspector mw-ajax-loader'}).insertBefore( original )
        .on('contextmenu', '.cm-mw-template-name, .cm-mw-link-pagename', function(e) {
        e.preventDefault();
        const ele = $(this);
        var url = ele.text();
        if (ele.hasClass( 'cm-mw-template-name' )) { url = '模板:' + url; }
        else if (ele.next( '.cm-mw-link' ).text() == '#') {
            url += '#' + ele.next().next( '.cm-mw-link-tosection' ).text();
        }
        urlDisplay.text( url );
        if (!mw.windowManager) {
            mw.windowManager = new OO.ui.WindowManager();
            $('body').append( mw.windowManager.$element );
        }
        if (!dialog) {
            dialog = new OO.ui.MessageDialog();
            actionP = new OO.ui.ActionWidget({label: '是', target: '_blank', flags: 'progressive'});
            actionD = new OO.ui.ActionWidget({label: '否', flags: 'destructive'});
            mw.windowManager.addWindows( [dialog] );
            dialog.message.$label.html( [wgULS('要在新标签页打开', '要在新標籤頁打開'), urlDisplay, wgULS('吗?', '嗎?')] );
        }
        actionP.setHref( script + '/' + url );
        mw.windowManager.openWindow( dialog, {actions: [actionP, actionD]}).opening.then(function() {
            actionP.$button.off( 'click' ).click(function() { dialog.close(); });
        });
    }),
        btns = [new OO.ui.ButtonWidget({label: '提交', flags: ['primary', 'progressive']}).on('click', function() {
        btns[0].setDisabled( true );
        mw.safeEdit(api, mw.request.curtimestamp, {pageid: id, text: editor.getValue(),
            summary: wgULS('使用页面/文本对比查看器快速编辑', '使用頁面/文本對比察看器快速編輯')}).then(function() {
            window.location.reload();
        }, function(reason) { if (reason != 'editConflict') { btns[0].setDisabled( false ); }
        });
    }), new OO.ui.ButtonWidget({label: wgULS('预览', '預覽')}).on('click', function() {
        btns[1].setDisabled( true );
        console.log('API request: 请求预览');
        const now = mw.now();
        api.parse( editor.getValue(), {title: mw.config.get('wgPageName'), disablelimitreport: 1,
            disableeditsection: 1} ).then(function(html) {
            console.log('End API request: 已生成预览,用时 ' + (mw.now() - now) + ' ms');
            if ($.contains( $content[0], original[0] )) { original.after( placeholder ).detach(); }
            $content.children( '.mw-parser-output' ).replaceWith( html );
            mw.hook( 'wikipage.content' ).fire($content);
        }, function(reason) { mw.apiFailure(reason, wgULS('预览', '預覽')); }).then(function() {
            btns[1].setDisabled( false );
        });
    }), new OO.ui.ButtonWidget({label: wgULS('还原', '復原'), flags: 'destructive'}).on('click', function() {
        editor.setValue( text );
        $content.children( '.mw-parser-output' ).replaceWith( original );
    }), new OO.ui.ButtonWidget({label: wgULS('隐藏', '隱藏')}).on('click', function() {
        css.disabled = !css.disabled;
        cssHide.disabled = !cssHide.disabled;
        wrapper.toggle();
        btns[3].setLabel( css.disabled ? wgULS('显示', '顯示') : wgULS('隐藏', '隱藏'));
    }), new OO.ui.ButtonWidget({flags: 'progressive', icon: 'next'})],
        list = mw.storage.getObject( 'inspect-category' );
    if (!list) { nextid = id + 1; }
    else {
        if (list[0][ list[1] ] == id) {
            list[1]++;
            mw.storage.setObject( 'inspect-category', list );
        }
        nextid = list[0][ list[1] ];
    }
    btns[4].setHref( '/?redirect=no&curid=' + nextid ).setDisabled( !nextid ).$element.contextmenu(function(e) {
        e.preventDefault();
        OO.ui.prompt( wgULS('请输入分类名:', '請輸入分類名:') ).then(function(cat) {
            if (cat === null) { return; }
            if (cat === '') {
                mw.storage.remove( 'inspect-category' );
                btns[4].setHref( '/?redirect=no&curid=' + (id + 1) ).setDisabled( false );
                return;
            }
            if (!/^([Cc]ategory|分[类類]):/.test( cat )) { cat = 'Category:' + cat; }
            console.log('API request: 查询标准的页面名');
            var now = mw.now();
            api.get({action: 'query', titles: cat, converttitles: 1, formatversion: 2}).then(function(response) {
                const target = response.query.pages[0];
                if (target.missing) {
                    mw.notify(wgULS('错误的分类名!', '錯誤的分類名!'), {type: 'error'});
                    return;
                }
                console.log('End API request: 已获得标准的页面名,用时 ' + (mw.now() - now) + ' ms');
                console.log('API request: 查询分类下的页面列表');
                now = mw.now();
                api.get({action: 'query', list: 'categorymembers', cmtitle: target.title, cmprop: 'ids',
                    cmlimit: 'max', cmsort: 'timestamp', cmdir: 'older', formatversion: 2}).then(function(cm) {
                    console.log('End API request: 已获得分类下的页面列表,用时 ' + (mw.now() - now) + ' ms');
                    const pages = cm.query.categorymembers.map(function(ele) { return ele.pageid; });
                    if (pages.length === 0) {
                        mw.notify('该分类下无页面!', {type: 'warn'});
                        return;
                    }
                    const currentIndex = pages[0] == id ? 1 : 0;
                    mw.storage.setObject( 'inspect-category', [pages, currentIndex] );
                    btns[4].setHref( '/?redirect=no&curid=' + pages[ currentIndex ] ).setDisabled( false );
                }, function(reason) { mw.apiFailure(reason, wgULS('该分类下的页面列表', '該分類下的頁面列表')); });
            }, function(reason) { mw.apiFailure(reason, wgULS('标准页面名称', '標準頁面名稱')); });
        });
    });
    $.when(getJSON, mw.request).then(function(data) {
        console.log('End API request: 已获得页面Wikitext');
        text = data[1].query.pages[0].revisions[0].content;
        outer.removeClass( 'mw-ajax-loader' );
        editor = new CodeMirror(outer[0], {value: text, mode: 'text/mediawiki', mwConfig: data[0],
            lineWrapping: true});
        wrapper = $( editor.getWrapperElement() );
        $('<div>', {html: btns.map(function(ele) { return ele.$element; })}).appendTo( outer );
    }, function(reason) { mw.apiFailure(reason, 'CodeMirror' + wgULS('设置或页面', '設置或頁面') + 'Wikitext'); });
}