跳转到内容

User:Vesekskiy/PlanSummary.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
mw.loader.using(['oojs-ui', 'mediawiki.api', 'mediawiki.util'], function () {

if (mw.config.get('wgAction') !== 'edit') return;

//const username = mw.config.get('wgUserName');
const planPage = `User:Vesekskiy/个人编辑计划`; //User:${username}

let sectionsCache = null;
let disableList = [];

function getId(line) {
    const m = line.trim().match(/^(\d+(?:\.\d+)?)/);
    return m ? m[1] : null;
}

function extractDisableList(wikitext) {
    const match = wikitext.match(/<!--\s*disable:\s*([^>]+)\s*-->/i);
    if (!match) return [];

    return match[1]
        .split(',')
        .map(s => s.trim())
        .filter(Boolean);
}

function loadData() {
    if (sectionsCache) return Promise.resolve(sectionsCache);

    const api = new mw.Api();

    return Promise.all([
        api.get({
            action: 'parse',
            page: planPage,
            prop: 'sections'
        }),
        api.get({
            action: 'query',
            prop: 'revisions',
            titles: planPage,
            rvprop: 'content',
            rvslots: 'main'
        })
    ]).then(([secData, textData]) => {

        const sections = secData.parse.sections;

        const page = Object.values(textData.query.pages)[0];
        const wikitext = page.revisions[0].slots.main['*'];

        disableList = extractDisableList(wikitext);

        sectionsCache = sections.filter(s => {
            if (!(s.level === '2' || s.level === '3')) return false;

            const id = getId(s.line);
            if (!id) return false;

            if (s.level === '2') return /^\d+$/.test(id);
            if (s.level === '3') return /^\d+\.\d+$/.test(id);

            return false;
        });

        return sectionsCache;
    });
}

function PlanDialog(config) {
    PlanDialog.super.call(this, config);
}
OO.inheritClass(PlanDialog, OO.ui.ProcessDialog);

PlanDialog.static.name = 'planDialog';
PlanDialog.static.title = '填写计划摘要';
PlanDialog.static.actions = [
    { action: 'confirm', label: '确定', flags: ['primary', 'progressive'] },
    { action: 'cancel', label: '取消', flags: 'safe' }
];

PlanDialog.prototype.initialize = function () {
    PlanDialog.super.prototype.initialize.apply(this, arguments);

    this.panel = new OO.ui.PanelLayout({
        padded: true,
        expanded: false
    });

    this.content = new OO.ui.FieldsetLayout();
    this.checkboxes = [];

    this.panel.$element.append(this.content.$element);
    this.$body.append(this.panel.$element);
};

PlanDialog.prototype.getSetupProcess = function () {
    return PlanDialog.super.prototype.getSetupProcess.call(this).next(() => {

        this.content.clearItems();
        this.checkboxes = [];

        return loadData().then(sections => {

            sections.forEach(sec => {
				
                const id = getId(sec.line);
                if (!id) return;

                const isLevel3 = sec.level === '3';
                const isDisabled = disableList.includes(id);

                const checkbox = new OO.ui.CheckboxInputWidget({
                    data: { number: id },
                    disabled: isDisabled
                });

                const field = new OO.ui.FieldLayout(checkbox, {
                    label: `${id} ${sec.line.replace(/^\d+(\.\d+)?\s*/, '')}`,
                    align: 'inline'
                });

                if (isLevel3) {
                    field.$element.css('margin-left', '20px');
                }
				
                if (isDisabled) {
                    field.$element.css({ color: '#888', opacity: 0.8 });
                }

                this.checkboxes.push(checkbox);
                this.content.addItems([field]);
            });
        });
    });
};

PlanDialog.prototype.getActionProcess = function (action) {

    if (action === 'cancel') {
        return new OO.ui.Process(() => {
            this.close();
        });
    }

    if (action === 'confirm') {
        return new OO.ui.Process(() => {

            const selected = this.checkboxes
                .filter(cb => cb.isSelected() && !cb.isDisabled())
                .map(cb => cb.getData().number);

            if (!selected.length) return;

            const links = selected.map((num, i) => {
                const text = (i === 0)
                    ? `个人编辑计划${num}`
                    : num;

                return `[[${planPage}#${num}|${text}]]`;
            });

            const result = links.join('、');

            const $summary = $('#wpSummary');

            if (!$summary.val().trim()) {
                $summary.val(result);
            } else {
                $summary.val($summary.val() + ';' + result);
            }

            this.close();
        });
    }

    return PlanDialog.super.prototype.getActionProcess.call(this, action);
};

let windowManager, dialog;

function openDialog() {
    if (!windowManager) {
        windowManager = new OO.ui.WindowManager();
        $(document.body).append(windowManager.$element);

        dialog = new PlanDialog();
        windowManager.addWindows([dialog]);
    }

    windowManager.openWindow(dialog);
}

function addPortletButton() {
    const link = mw.util.addPortletLink(
        'p-cactions',
        '#',
        '填写计划摘要',
        'ca-plan-summary',
        '根据个人编辑计划生成摘要'
    );

    if (link) {
        $(link).on('click', function (e) {
            e.preventDefault();
            openDialog();
        });
    }
}

$(addPortletButton);

});