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

“MediaWiki:Gadget-inspect.js”的版本间差异

跳转到导航 跳转到搜索
删除1,769字节 、​ 2023年3月27日 (一) 13:11
无编辑摘要
 
(未显示2个用户的36个中间版本)
* @Function: 在页面内快速编辑和预览
* @Author: [[User:Bhsd]]
* @Translation: [[User:Lakejason0]]
*/
"use strict";
/*global mw, $, OO, CodeMirror, wgULS*/
$(() => { // 避免全局变量
let nextid, const idlist = mw.configstorage.getgetObject( 'wgArticleIdinspect-category' ), flag;
const curRevidid = mw.config.get( 'wgCurRevisionIdwgArticleId' ),
page = mw.config.get( 'wgPageName' ), // 这里未转义,后面应用时需要注意
isCode = mw.config.get( 'wgPageContentModel' ) != 'wikitext', // javascript/css/Scribunto/json
gadgets = mw.gadgets || {},
charInsert = gadgets.charinsert || {},
src = charInsert.src || 'special:我的用户页mypage/edittools',
// 由于resizable,left, top, height必须加!important,width不可加!important
cssHide = mw.util.addCSS( `#inspector { position:fixed; bottom:0; right:24px; left:unsetauto !important;
top:unsetauto !important; height:unsetauto !important; width:calc(50% - 7rem - 0.5px); }` ),
div.start-screen { bottom:40px; }` ),
$content = $('#mw-content-text, #mw-imagepage-content').last(),
$content = $('#mw-content-text, #mw-imagepage-content').last(),
// wikitext/Scribunto对应.mw-parser-output,javascript/css对应.mw-code,json对应.mw-json
// wikitext/Scribunto对应.mw-parser-output,javascript/css对应.mw-code,json对应.mw-json
$original = $content.children('.mw-json, .mw-code, .mw-parser-output'),
$original = $content.children('.mw-json, .mw-code, .mw-parser-output'),
$outer = $('<div>', {id: 'inspector', class: 'mw-ajax-loader'}).insertBefore( $original ),
$outer = $('<div>', {id: 'inspector', class: 'mw-ajax-loader'}).insertBefore( $original ),
api = new mw.Api(),
api = new mw.Api();
initList = (pages, ctn) => {
if (!list) { nextid = id + 1; }
console.info({pages: pages, ctn: ctn, id: id});
else {
flag = pages[0] == id || (ctn && pages.includes(id));
flag = list[0][ list = [pages,1] flag] ?== pages.indexOf(id) + 1 : 0];
if (flag) { list[1]++; }
if (ctn && !flag) { mw.notify(wgULS('当前页面并不属于该分类或名字空间!', '當前頁面並不屬於該分類或名字空間!'),
nextid = list[0][ list[1] ];
{type: 'warn'}); }
}
mw.storage.setObject( 'inspect-category', [pages, list[1] - flag] );
const btnGo = new OO.ui.ButtonWidget({flags: 'progressive', icon: 'next', btnGo.setHref(href: `/zh?redirect=no&curid=${pages[ list[1] ]nextid}` ).setDisabled( false );,
disabled: !nextid}),
};
initList = (pages, ctn) => {
let nextid, list = mw.storage.getObject( 'inspect-category' ), flag;
console.info({pages: pages, ctn: ctn, id: id});
if (!list) { nextid = id + 1; }
flag = pages[0] == id || ctn && pages.includes(id); // &&的优先级高于||
else {
list = [pages, flag ? pages.indexOf(id) + 1 : 0];
flag = (list[0][ list[1] ] == id);
if (ctn && !flag) { mw.notify(wgULS('当前页面并不属于该分类或命名空间!', '目前的頁面並不屬於此分類或命名空間!'),
if (flag) { list[1]++; }
{type: 'warn'}); }
nextid = list[0][ list[1] ];
mw.storage.setObject( 'inspect-category', [pages, list[1] - flag] );
}
const btnGo = new OO.ui.ButtonWidgetsetHref({flags: 'progressive', icon: 'next', href: `/zh?redirect=no&curid=${nextidpages[ list[1] ]}`, ).setDisabled( false );
},
disabled: !nextid}),
dialog = new OO.ui.MessageDialog(),
actionC = new OO.ui.ActionWidget({action: 'cancel', label: '取消'}),
actionG = new OO.ui.ActionWidget({action: 'go', label: wgULS('确定', '確認'), flags: 'progressive'}),
textInput = new OO.ui.TextInputWidget(),
fromHere = new OO.ui.CheckboxInputWidget(),
message = [ $('<p>', {text: wgULS('请输入分类名或空间编号:', '請輸入分類名或空間編號:')}),
textInput.$element,
new OO.ui.FieldLayout(fromHere, {label: wgULS('从当前页面继续', '從頁面繼續'), align: 'inline'}).$element
],
updateCat = function(cat, ctn) {
// 输入空白则清除分类
if (cat === '') {
mw.storage.remove( 'inspect-category' );
btnGo.setHref( `/zh?redirect=no&curid=${id + 1}` ).setDisabled( false );
return;
}
}
// 输入数字对应空间
if (!isNaN(cat)) {
if (!Object.keys( mw.config.get( 'wgFormattedNamespaces' ) ).includes(cat)) {
mw.notify(wgULS('错误的空间编号!', '錯誤的空間編號!'), {type: 'error'});
return;
}
}
mw.timedQuery(api, {list: 'allpages', apnamespace: cat, apfilterredir: 'nonredirects', aplimit: 'max'},
wgULS('该空间的页面列表', '此命空間的頁面列表清單')).then(ap => {
const pages = ap.query.allpages.map(ele => ele.pageid).sort((a, b) => a < b); // 由新到旧排列
if (pages.length === 0) {
mw.notify( wgULS('该空间沒有非重定向的页面!', '此命空間沒有非重新導向的頁面!'), {type: 'warn'} );
return;
}
}
initList(pages, ctn);
}, () => {}); // mw.timedQuery已经通知过错误信息,这里只要一个空函数处理reject,下同
return;
}
}
if (!/^(category|分[类類]):/i.test( cat )) { cat = `Category:${cat}`; }
// cmtitle参数不可自动转换,所以需要先获得转换后的正确标题
mw.timedQuery(api, {titles: cat, converttitles: 1}, wgULS('标准页面名称', '標準頁面名稱')).then(r => {
const target = r.query.pages[0];
if (target.missing) {
mw.notify(wgULS('错误的分类名!', '錯誤的分類名!'), {type: 'error'});
return;
}
}
mw.timedQuery(api, {list: 'categorymembers', cmtitle: target.title, cmprop: 'ids', cmlimit: 'max',
cmsort: 'timestamp', cmdir: 'older'}, wgULS('分类下的页面列表', '分類下的頁面列表清單')).then(cm => {
const pages = cm.query.categorymembers.map(ele => ele.pageid);
if (pages.length === 0) {
mw.notify( wgULS('该分类下无页面!', '分類下無頁面!'), {type: 'warn'} );
return;
}
}
initList(pages, ctn);
}, () => {});
}, () => {});
};
// 这个click事件不能绑到btnGo上,否则会禁用href跳转
btnGo.$element.click(() => { if (list && flag) { mw.storage.setObject( 'inspect-category', list ); } })
.contextmenu(e => {
e.preventDefault();
mw.dialog(dialog, [actionC, actionG], message).then(()action => {
if (action == actionG.$button.click(('go') => { updateCat( textInput.getValue(), fromHere.isSelected() ); });
});
});
// 模板、JavaScript、CSS、Lua、JSON只需要箭头按钮
if ((mw.config.get( 'wgNamespaceNumber' ) == 10 && !page.endsWith( '/doc' )) || isCode) {
$outer.removeClass( 'mw-ajax-loader' ).append( $('<div>', {id: 'inspector-btns', html: btnGo.$element}) );
mw.loader.addStyleTag( '#inspector-btns { width:auto; }' );
return;
}
}
// 先提交Ajax请求,这里手动设置cache: true
const getJSON = $mw.getloader.using({ dataType: 'jsonext.CodeMirror.data', cache: true),
getExt = mw.loader.using(['ext.CodeMirror.lib', 'ext.CodeMirror.mode.mediawiki']);
url: '/zh?title=mediawiki:gadget-CodeMirror.json&action=raw&ctype=application/json' }),
// 生成通用的API请求
getExt = mw.loader.using(['ext.CodeMirror.lib', 'ext.CodeMirror.mode.mediawiki']);
mw.standardQuery(api);
// 生成通用的API请求
let text, editor, $wrapper, $replace, $charinsert, prefix, ns, section, secTitle, summary,
mw.standardQuery(api);
lang = mw.config.get( 'wgUserVariant' );
$original.find( ':header:has(.mw-editsection)' ).dblclick(function() {
section = mw.util.getParamValue( 'section', $(this)original.find( ':header:has(.mw-editsection > a)' ).attrdblclick(function('href') );{
section = mw.util.getParamValue( 'section', $(this).find( '.mw-editsection > a' ).attr('href') );
mw.sectionQuery(api, section).then(r => {
mw.sectionQuery(api, section).then(r => {
editor.setValue( r.parse.wikitext );
secTitle = editor.setValue( r.parse.sections[0].linewikitext );
secTitle = r.parse.sections[0].anchor.replaceAll(' ', '_');
}, () => {});
}, () => {});
});
// 标注<p>标签
// 标注<p>标签
const css = mw.util.addCSS( `.empty { border:1px solid rgba(253,220,154,0.5); box-shadow:0 0 0.5em #fddc9a; }
const css = mw.util.addCSS( `.empty { border:1px solid rgba(253,220,154,0.5); box-shadow:0 0 0.5em #fddc9a; }
#mw-content-text .mw-parser-output { display:flow-root; overflow:hidden; word-wrap:break-word; }` );
#mw-content-text .mw-parser-output { display:flow-root; max-height:100vh; overflow:auto;
css.disabled = true;
word-wrap:break-word; }` );
let text, editor, $wrapper, $replace, $charinsert, prefix, ns, section, secTitle,
css.disabled = true;
lang = mw.config.get( 'wgUserVariant' );
// 也可以使用user.options,这里使用其他方法绕过
const isGadget = (name) => ['loaded', 'loading', 'ready'].includes( mw.loader.getState(`ext.gadget.${name}`) ),
isBackup = isGadget('contentBackup'),
backupObj = isBackup ? Object.fromEntries( mw.storage.getObject( 'LLWiki-contentBackup' ) || [] ) : {},
backup = isBackup ? () => {
backupObj[id] = [mw.now(), editor.getValue()];
mw.storage.setObject( 'LLWiki-contentBackup', Object.entries(backupObj) );
} : () => {},
loadBackup = () => {
const backupContent = (backupObj[id] || [])[1];
if (!backupContent) {
mw.notify(wgULS('当前页面尚未备份!', '頁面尚未備份!'), {type: 'warn'});
return;
}
}
mw.confirm( wgULS('要加载备份吗?', '要備份嗎?'), 'progressive' ).then(confirm => {
if (!confirm) { return; }
editor.setValue( backupContent );
mw.notify(wgULS('已还原备份!', '已原備份!'), {type: 'success'});
});
},
pEmpty = ($div) => {
$div.find( 'p:not(:has(script))' ).filter(function() { return !/\S/.test( this.textContent ); })
.addClass('empty');
},
placeholder = [
$placeholder = $('<div>', {class: "mw-parser-output"}).css('display', 'none'), // 用于替换时保留原始数据
$('<div>', {class: "mw-parser-output"}).css('display', 'none'),
$warning = $('<div>', {html: [wgULS("确定要还原为未编辑的状态吗?", "確認要復原為未編輯的狀態嗎?"), '<br>',
$('<h1>', {id: 'firstHeading', class: 'firstHeading'}),
wgULS("建议您做好编辑内容备份。", "建議您做好編輯內容備份。")]}),
$('<div>', {id: 'catlinks'}).css('display', 'none'),
btns = [new OO.ui.ButtonWidget({label: '提交', flags: ['primary', 'progressive']}).on('click', () => {
$('.mw-indicators')
backup();
], // 用于替换时保留原始数据
// 改变CSS样式表示提交中
$warning = $('<div>', {html: [wgULS("确定要还原为未编辑的状态吗?", "確認要還原為未編輯的狀態嗎?"), '<br>',
btns[0].setDisabled( true );
wgULS("建议您做好编辑内容备份。", "建議您做好編輯內容備份。")]}),
mw.safeEdit(api, curRevid, {pageid: id, text: editor.getValue(), section: section,
$heading = $('#firstHeading'),
summary: (section === undefined ? '' : `/* ${secTitle} */ //`) +
$cat = $('#catlinks'),
wgULS( '使用[[help:小工具/页面文本对比查看器|页面/文本对比查看器]]快速编辑',
$indicator = $('.mw-indicator'),
'使用[[help:小工具/页面文本对比查看器|頁面/文本對比察看器]]快速編輯')}, isBackup)
btns = [new OO.ui.ButtonWidget({label: '提交', flags: ['primary', 'progressive']}).on('click', () => {
.then(() => { location.reload(); },
backup();
reason => { btns[0].setDisabled( reason == 'editConflict' ); }); // 编辑冲突必须刷新页面,不应重复提交
// 改变CSS样式表示提交中
}), new OO.ui.ButtonWidget({label: wgULS('预览', '預覽')}).on('click', () => {
btns[0].setDisabled( true );
backup();
mw.safeEdit(api, {pageid: id, text: editor.getValue(), section: section,
// 改变CSS样式表示预览中
summary: (section === undefined ? '' : `/* ${secTitle} */ `) + (summary ? `${summary} //` : '//') +
btns[1].setDisabled( true );
wgULS( '使用[[help:小工具/页面文本对比查看器|页面/文本对比查看器]]快速编辑',
console.log('API request: 请求预览');
'使用[[help:小工具/页面文本对比查看器|頁面/文字對比檢視器]]快速編輯')}, isBackup)
const now = mw.now();
.then(() => { location.href = mw.util.getUrl( page ); },
api.parse(editor.getValue(), {title: page, uselang: lang, disablelimitreport: 1, disableeditsection: 1})
reason => { btns[0].setDisabled( reason == 'editConflict' ); }); // 编辑冲突必须刷新页面,不应重复提交
.then(html => {
}), new OO.ui.ButtonWidget({label: wgULS('预览', '預覽')}).on('click', () => {
console.log(`End API request: 已生成预览,用时 ${mw.now() - now} ms`);
backup();
if ($.contains( $content[0], $original[0] )) { $original.after( $placeholder ).detach(); }
// 改变CSS样式表示预览中
$content.children( '.mw-parser-output' ).replaceWith( html );
btns[1].setDisabled( true );
pEmpty( $content.children( '.mw-parser-output' ) );
mw.timedParse(api, {text: editor.getValue(), uselang: lang,
if (mw.resizeLyrics) { mw.resizeLyrics(); }
prop: 'text|categorieshtml|displaytitle|indicators|modules|headitems'
mw.hook( 'wikipage.content' ).fire($content);
}, reason => { mw.apiFailure(reason, wgULS('预览', '預覽'));.then(r })=> // mw.apiFailure不会抛出错误{
mw.loader.load( r.parse.modulestyles );
.then(() => { btns[1].setDisabled( false ); });
const tabsStyles = r.parse.headitems.find(function(ele) { return ele.tag === 'TabsStyles'; });
}), new OO.ui.ButtonWidget({label: wgULS('还原', '復原'), flags: 'destructive', disabled: true}).on('click', () => {
if (tabsStyles) {
mw.confirm($warning, ['primary', 'destructive']).then(confirm => {
$('head').append(tabsStyles.content); // 可能重复,但重复也没关系
if (!confirm) { return; }
}
section = undefined;
if ($.contains( $content[0], $original[0] )) {
editor.setValue( text );
$original.after( placeholder[0] ).detach();
$content.children( '.mw-parser-output' ).replaceWith( $original );
$heading.after( placeholder[1] ).detach();
if (mw.resizeLyrics) { mw.resizeLyrics(); }
$cat.after( placeholder[2] ).detach();
});
$indicator.detach();
}), new OO.ui.ButtonWidget({label: wgULS('显示', '顯示')}).on('click', () => {
}
css.disabled = !css.disabled;
$content.children( '.mw-parser-output' ).replaceWith( r.parse.text );
cssHide.disabled = !cssHide.disabled;
pEmpty( $content.children( '.mw-parser-output' ) );
$wrapper.toggle();
if (mw.resizeLyrics) { mw.resizeLyrics(); }
editor.setSize();
mw.hook( 'wikipage.content' ).fire($content);
btns[3].setLabel( css.disabled ? wgULS('显示', '顯示') : wgULS('隐藏', '隱藏'));
$('#catlinks').replaceWith( r.parse.categorieshtml );
btns[2].setDisabled( css.disabled ); // 折叠时无法更新textarea
placeholder[1].html( r.parse.displaytitle );
if (mw.resizeLyrics) { mw.resizeLyrics(); }
placeholder[3].html( Object.entries( r.parse.indicators ).map(ele =>
}), btnGo],
$('<div>', {class: 'mw-indicator', id: `mw-indicator-${ele[0]}`, html: ele[1]})) );
options = $('<div>', {text: wgULS('查找替换', '查找替換')}).click(() => {
}, () => {}).then(() => { btns[1].setDisabled( false ); });
if ($replace) {
}), new OO.ui.ButtonWidget({label: wgULS('还原', '還原'), flags: 'destructive', disabled: true}).on('click', () => {
$replace.show();
mw.confirm($warning, ['primary', 'destructive']).then(confirm => {
return;
if (!confirm) { return; }
}
section = undefined;
let replaceBackup;
editor.setValue( text );
const enable = () => { replaceBtn.setDisabled( false ); },
if ($.contains( $content[0], $original[0] )) { return; } // 无事发生
ptn = new OO.ui.TextInputWidget().on('change', enable),
$content.children( '.mw-parser-output' ).replaceWith( $original );
val = new OO.ui.MultilineTextInputWidget({autosize: true, maxRows: 3}).on('change', enable),
placeholder[1].replaceWith( $heading );
regex = new OO.ui.CheckboxInputWidget().on('change', enable),
$('#catlinks').replaceWith( $cat );
modifier = new OO.ui.CheckboxInputWidget().on('change', enable),
placeholder[3].html( $indicator );
undoBtn = new OO.ui.ButtonWidget({label: wgULS('撤销', '撤銷'), disabled: true, flags: ['destructive']})
if (mw.resizeLyrics) { mw.resizeLyrics(); }
.on('click', () => {
});
editor.setValue( replaceBackup );
}), new OO.ui.ButtonWidget({label: wgULS('显示', '顯示')}).on('click', () => {
enable();
css.disabled = !css.disabled;
}),
cssHide.disabled = !cssHide.disabled;
replaceBtn = new OO.ui.ButtonWidget({label: wgULS('替换', '替換'), flags: ['progressive']})
$wrapper.toggle();
.on('click', () => {
editor.setSize();
const pattern = ptn.getValue(),
btns[3].setLabel( css.disabled ? wgULS('显示', '顯示') : wgULS('隐藏', '隱藏'));
regexp = new RegExp(regex.isSelected() ? pattern : mw.util.escapeRegExp(pattern),
btns[2].setDisabled( css.disabled ); // 折叠时无法更新textarea
'g' + (modifier.isSelected() ? 'i' : ''));
if (mw.resizeLyrics) { mw.resizeLyrics(); }
replaceBackup = editor.getValue();
}), btnGo],
undoBtn.setDisabled( false );
options = $('<div>', {text: wgULS('查找替换', '尋找取代')}).click(() => {
replaceBtn.setDisabled( true ); // 防止连续点击造成无法撤销
if ($replace) {
editor.setValue( replaceBackup.replace(regexp, val.getValue()) );
$replace.show();
}),
return;
hideBtn = new OO.ui.ButtonWidget({label: wgULS('关闭', '關閉')})
}
.on('click', () => {
let replaceBackup;
$replace.hide();
const enable = () => { replaceBtn.setDisabled( false ); },
enable();
ptn = new OO.ui.TextInputWidget().on('change', enable),
});
val = new OO.ui.MultilineTextInputWidget({autosize: true, maxRows: 3}).on('change', enable),
$replace = $('<div>', {class: 'inspector-field', html: [
regex = new OO.ui.CheckboxInputWidget().on('change', enable),
$('<div>', {html: ['查找:', ptn.$element]}),
modifier = new OO.ui.CheckboxInputWidget().on('change', enable),
$('<div>', {html: [wgULS('替换:', '替換:'), val.$element]}),
undoBtn = new OO.ui.ButtonWidget({label: wgULS('撤销', '復原'), disabled: true, flags: ['destructive']})
$('<div>', {html: [
.on('click', () => {
new OO.ui.FieldLayout(regex, {label: wgULS('正则', '正則'), align: 'inline'}).$element,
editor.setValue( replaceBackup );
new OO.ui.FieldLayout(modifier, {label: $('<i>', {text: 'i'}), align: 'inline'}).$element,
enable();
replaceBtn.$element, undoBtn.$element, hideBtn.$element
}),
]})
replaceBtn = new OO.ui.ButtonWidget({label: wgULS('替换', '取代'), flags: ['progressive']})
]}).appendTo( 'body' ).draggable();
.on('click', () => {
}).add(isGadget('charinsert') ? $('<div>', {text: '快速插入'}).click(() => {
const pattern = ptn.getValue(),
if ($charinsert) {
regexp = new RegExp(regex.isSelected() ? pattern : mw.util.escapeRegExp(pattern),
$charinsert.show();
'g' + (modifier.isSelected() ? 'i' : ''));
return;
replaceBackup = editor.getValue();
}
undoBtn.setDisabled( false );
$charinsert = $('<div>', {html: $('<div>', {text: '快速插入工具', id: 'inspector-field-title'}),
replaceBtn.setDisabled( true ); // 防止连续点击造成无法撤销
class: 'inspector-field mw-ajax-loader'}).appendTo('body').draggable().contextmenu(e => {
editor.setValue( replaceBackup.replace(regexp, val.getValue()) );
e.preventDefault();
}),
$charinsert.hide();
hideBtn = new OO.ui.ButtonWidget({label: wgULS('关闭', '關閉')})
}).on('click', '.mw-charinsert-item', function() {
.on('click', () => {
const $this = $(this),
$replace.hide();
start = $this.data('mw-charinsert-start') || $this.data('start') || '',
enable();
end = $this.data('mw-charinsert-end') || $this.data('end') || '';
});
editor.replaceSelection( start + editor.getSelection() + end );
$replace = $('<div>', {class: 'inspector-field', html: [
editor.focus();
$('<div>', {html: [wgULS('查找:', '尋找:' ), ptn.$element]}),
});
$('<div>', {html: [wgULS('替换:', '取代:'), val.$element]}),
// 为了充分利用浏览器缓存,这里不使用API;注意url转义,这里不需要简化'/mediawiki/index.php'
$('<div>', {html: [
$.get({url: mw.util.getUrl(src, {variant: mw.config.get( 'wgUserLanguage' )}),
new OO.ui.FieldLayout(regex, {label: wgULS('正则', '正規表達式'), align: 'inline'}).$element,
cache: charInsert.cache !== false, dataType: 'text'}).then(doc => {
new OO.ui.FieldLayout(modifier, {label: $('<i>', {text: 'i'}), align: 'inline'}).$element,
$charinsert.append( $( doc.match(/<body[\s\S]+<\/body>/)[0] ).find( '.mw-parser-output' ) );
replaceBtn.$element, undoBtn.$element, hideBtn.$element
}, () => {
]})
mw.notify([
]}).appendTo( 'body' ).draggable();
wgULS('无法加载', '無法加載'),
}).add(isGadget('charinsert') ? $('<div>', {text: '快速插入'}).click(() => {
$('<a>', {text: src, href: mw.util.getUrl(src)}),
if ($charinsert) {
wgULS('!请检查该页面是否存在。', '!請檢查該頁面是否存在。')
$charinsert.show();
], {type: 'error', autoHideSeconds: 'long'});
return;
}).then(() => { $charinsert.removeClass( 'mw-ajax-loader' ); });
}
}) : null),
$charinsert = $dropdown('<div>', ={html: $('<div>', {classtext: "inspector-menu"'快速插入工具', htmlid: options'inspector-field-title'}),
$hints = $('<div>', { class: "'inspector-menu"field mw-ajax-loader'}).onappendTo('click', body').inspector-hint', functiondraggable().contextmenu(e => {
e.preventDefault();
const cursor = editor.getCursor();
$charinsert.hide();
editor.replaceRange(this.textContent + (ns > 0 ? '}}' : ']]'),
}).on('click', '.mw-charinsert-item', function() {
{line: cursor.line, ch: cursor.ch - prefix.length}, cursor);
const $this = $(this),
// 随后再次执行updateHints时会自行stop
start = $this.data('mw-charinsert-start') || $this.data('start') || '',
editor.focus();
end = $this.data('mw-charinsert-end') || $this.data('end') || '';
}),
editor.replaceSelection( start + editor.getSelection() + end );
// 判别模板时可能会误处理解析器函数
editor.focus();
regexps = {0: /\[\[\s*:?([^|[\]{}<>]*)$/i, 10: /{{\s*([^|[\]{}<>#]*)$/i,
});
828: /{{\s*#invoke:\s*([^|[\]{}<>#:]*)$/i, 274: /{{\s*#widget:\s*([^|[\]{}<>#:]*)$/i},
// 为了充分利用浏览器缓存,这里不使用API;注意url转义,这里不需要简化'/mediawiki/index.php'
$noHint = $('<span>', {class: 'error'}),
$.get({url: mw.util.getUrl(src, {variant: mw.config.get( 'wgUserLanguage' )}),
nsPrefixes = {0: '', 10: 'Template:', 828: '模块:', 274: 'Widget:'},
cache: charInsert.cache !== false, dataType: 'text'}).then(doc => {
autocomplete = isGadget('autocomplete') ? e => {
$charinsert.append( $( doc.match(/<body[\s\S]+<\/body>/)[0] ).find( '.mw-parser-output' ) );
if (![9, 27].includes( e.keyCode )) { return; } // tab和esc
}, () => {
let $cursor, before, sections, title;
mw.notify([
const cursorActivity = () => {
wgULS('无法加载', '無法載入'),
const newCursor = editor.getCursor(),
$('<a>', {text: src, href: mw.util.getUrl(src)}),
newLine = editor.getLine( newCursor.line ),
wgULS('!请检查该页面是否存在。', '!請檢查此頁面是否存在。')
newAfter = newLine.slice( newCursor.ch );
], {type: 'error', autoHideSeconds: 'long'});
// 如果光标改变过位置
}).then(() => { $charinsert.removeClass( 'mw-ajax-loader' ); });
if (newCursor.line != cursor.line || newAfter != after) {
}) : null),
stop();
$dropdown = $('<div>', {class: "inspector-menu", html: options}),
return;
$hints = $('<div>', {class: "inspector-menu"}).on('click', '.inspector-hint', function() {
}
const cursor = editor.getCursor();
before = newLine.slice(0, newCursor.ch);
editor.replaceRange(this.textContent + (ns > 0 ? '}}' : ']]'),
updateHints();
{line: cursor.line, ch: cursor.ch - prefix.length + 1}, cursor);
},
// 随后再次执行updateHints时会自行stop
stop = () => {
editor.focus();
$hints.slideUp('fast');
}),
editor.off('cursorActivity', cursorActivity);
// 判别模板时可能会误处理解析器函数
},
regexps = {0: /\[\[\s*:?([^|[\]{}<>]*)$/i, 10: /{{\s*([^|[\]{}<>#]*)$/i,
updateHints = mw.util.debounce(500, () => {
828: /{{\s*#invoke:\s*([^|[\]{}<>#:]*)$/i, 274: /{{\s*#widget:\s*([^|[\]{}<>#:]*)$/i},
if (!regexps[ns].test( before )) {
$noHint = $('<span>', {class: 'error'}),
stop();
nsPrefixes = {0: '', 10: 'Template:', 828: '模块:', 274: 'Widget:'},
return;
autocomplete = isGadget('autocomplete') ? e => {
}
if (![9, 27].includes( e.keyCode )) { return; } // tab和esc
$cursor = $wrapper.find( '.CodeMirror-cursor' );
let $cursor, before, sections, title;
prefix = before.match( regexps[ns] )[1];
const cursor = editor.getCursor(),
if (prefix === "" || prefix.startsWith('#')) { return; }
line = editor.getLine( cursor.line ),
if (ns == '0' && prefix.includes('#')) {
after = line.slice( cursor.ch );
const capture = prefix.match(/^(.+)#(.*)$/);
before = line.slice(0, cursor.ch);
prefix = capture[2];
const cursorActivity = () => {
(title == capture[1] ? Promise.resolve() : mw.timedQuery(api, {action: 'parse', page: capture[1],
const newCursor = editor.getCursor(),
prop: 'sections'}, wgULS('段落标题', '段落標題')).then(r => {
newLine = editor.getLine( newCursor.line ),
title = capture[1];
newAfter = newLine.slice( newCursor.ch );
sections = r.parse.sections.map(ele => $('<div>', {class: 'inspector-hint', text: ele.line}));
// 如果光标改变过位置
}, () => { throw null; })).then(() => {
if (newCursor.line != cursor.line || newAfter != after) {
$hints.html( sections.filter(ele => ele.text().startsWith( prefix )) )
stop();
.show().position({my: 'left top', of: $cursor, within: $wrapper, collision: 'fit'});
return;
if ($hints.children().length === 0) {
}
$noHint.text(wgULS('不存在对应段落!', '不存在對應段落!')).appendTo( $hints );
before = newLine.slice(0, newCursor.ch);
}
updateHints();
}, stop);
},
return;
stop = () => {
}
$hints.slideUp('fast');
mw.timedQuery(api, {list: 'prefixsearch', pssearch: prefix, psnamespace: ns},
editor.off('cursorActivity', cursorActivity);
wgULS('前缀相符的页面', '前綴相符的頁面')).then(r => {
},
$hints.html( r.query.prefixsearch.map(ele =>
updateHints = mw.util.debounce(500, () => {
$('<div>', {class: 'inspector-hint', text: ele.title.slice( nsPrefixes[ns].length )})
if (!regexps[ns].test( before )) {
) ).show().position({my: 'left top', of: $cursor, within: $wrapper, collision: 'fit'});
stop();
if ($hints.children().length === 0) {
return;
$noHint.text(wgULS('不存在对应页面!', '不存在對應頁面!')).appendTo( $hints );
}
}
$cursor = $wrapper.find( '.CodeMirror-cursor' );
}, stop);
prefix = before.match( regexps[ns] )[1];
});
if (prefix === "" || prefix.startsWith('#')) { return; }
if (e.keyCode == 27) {
if (ns == '0' && prefix.includes('#')) {
stop();
const capture = prefix.match(/^(.+)#(.*)$/);
return;
prefix = capture[2];
}
(title == capture[1] ? Promise.resolve() : mw.timedQuery(api, {action: 'parse', page: capture[1],
editor.execCommand( 'delCharBefore' ); // 删掉新增的\t
prop: 'sections'}, wgULS('段落标题', '段落標題')).then(r => {
const cursor = editor.getCursor(),
title = capture[1];
line = editor.getLine( cursor.line ),
sections = r.parse.sections.map(ele => $('<div>', {class: 'inspector-hint', text: ele.line}));
after = line.slice( cursor.ch );
}, () => { throw null; })).then(() => {
before = line.slice(0, cursor.ch);
$hints.html( sections.filter(ele => ele.text().startsWith( prefix )) )
$.each(regexps, (k, v) => { if (v.test(before)) { ns = k; } });
.show().position({my: 'left top', of: $cursor, within: $wrapper, collision: 'fit'});
if (!ns) { return; }
if ($hints.children().length === 0) {
mw.notify(wgULS('开启自动补全提示。', '開啟自動補全提示。'), {tag: 'autocomplete'});
$noHint.text(wgULS('不存在对应段落!', '不存在對應段落!')).appendTo( $hints );
editor.on('cursorActivity', cursorActivity);
}
// 实际上updateHints总是延迟500ms执行,因此下一行代码的位置影响不大
}, stop);
updateHints();
return;
} : () => {};
}
mw.loader.using('jquery.ui').then(() => {
mw.timedQuery(api, {list: 'prefixsearch', pssearch: prefix, psnamespace: ns},
const actionP = new OO.ui.ActionWidget({label: '是', target: '_blank', flags: 'progressive'}),
wgULS('前缀相符的页面', '前綴相符的頁面')).then(r => {
actionD = new OO.ui.ActionWidget({label: '否'}),
$hints.html( r.query.prefixsearch.map(ele =>
$url = $('<a>'), // 桌面版CSS不必需href
$('<div>', {class: 'inspector-hint', text: ele.title.slice( nsPrefixes[ns].length )})
label = [wgULS('要在新标签页打开', '要在新標籤頁打開'), $url, wgULS('吗?', '嗎?')];
) ).show().position({my: 'left top', of: $cursor, within: $wrapper, collision: 'fit'});
$outer.on('contextmenu', '.cm-mw-template-name', function() {
if ($hints.children().length === 0) {
const template = '模板:' + $(this).text();
$noHint.text(wgULS('不存在对应页面!', '不存在對應頁面!')).appendTo( $hints );
// 这里增加一次确认界面是因为部分浏览器不允许JS直接打开新标签页。
}
$url.text( template );
}, stop);
actionP.setHref( mw.util.getUrl(template) ); // 注意url转义
});
mw.dialog(dialog, [actionD, actionP], label);
if (e.keyCode == 27) {
return false; // 这里需要同时执行stopImmediatePropagation()和preventDefault()
stop();
}).on('contextmenu', '.CodeMirror', e => {
return;
e.preventDefault();
}
// 使用jquery.ui让菜单总是落在CodeMirror内,此时slideDown效果不生效
editor.execCommand( 'delCharBefore' ); // 删掉新增的\t
$dropdown.show().position({my: 'left top', of: e, within: $wrapper, collision: 'fit'});
$.each(regexps, (k, v) => { if (v.test(before)) { ns = k; } });
}).on('keydown', '.CodeMirror', autocomplete).resizable( {handles: 'w', minWidth: 350} );
if (!ns) { return; });
mw.notify(wgULS('开启自动补全提示。', '開啟自動補全提示。'), {tag: 'autocomplete'});
$('body').click(() => { $dropdown.slideUp('fast'); });
editor.on('cursorActivity', cursorActivity);
if (isBackup) {
// 实际上updateHints总是延迟500ms执行,因此下一行代码的位置影响不大
btns[2].$element.contextmenu(e => {
updateHints();
e.preventDefault();
} : () => {};
loadBackup();
mw.loader.using(['jquery.ui', 'user.options']).then(() => {
});
const actionP = new OO.ui.ActionWidget({label: '是', target: '_blank', flags: 'progressive'}),
}
actionD = new OO.ui.ActionWidget({label: '否'}),
if (isGadget( 'PreviewWithVariant' ) ) {
$url = $('<a>'), // 桌面版CSS不必需href
const options = [{label: "大陆简体", data: "zh-cn"}, {label: "香港繁體", data: "zh-hk"},
label = [wgULS('要在新标签页打开', '要在新分頁打開'), $url, wgULS('吗?', '嗎?')];
{label: "澳門繁體", data: "zh-mo"}, {label: "马来西亚简体", data: "zh-my"},
$outer.on('contextmenu', '.cm-mw-template-name', function() {
{label: "新加坡简体", data: "zh-sg"}, {label: "臺灣繁體", data: "zh-tw"}],
const template = '模板:' + $(this).text();
select = new OO.ui.DropdownInputWidget({classes: ['inspector-variant'], options: options, value: lang})
// 这里增加一次确认界面是因为部分浏览器不允许JS直接打开新标签页。
.on('change', () => { lang = select.getValue(); }),
$url.text( template );
menu = select.$element.find( '.oo-ui-menuSelectWidget' )
actionP.setHref( mw.util.getUrl(template) ); // 注意url转义
.click(() => { menu.addClass( 'oo-ui-element-hidden' ); });
mw.dialog(dialog, [actionD, actionP], label).catch(() => {});
select.$element.prependTo( btns[1].$element );
return false; // 这里需要同时执行stopImmediatePropagation()和preventDefault()
btns[1].$element.contextmenu(e => {
}).on('contextmenu', '.CodeMirror', e => {
e.preventDefault();
e.preventDefault();
menu.removeClass( 'oo-ui-element-hidden' );
// 使用jquery.ui让菜单总是落在CodeMirror内,此时slideDown效果不生效
}).children('a').blur(() => { menu.addClass( 'oo-ui-element-hidden' ); });
$dropdown.show().position({my: 'left top', of: e, within: $wrapper, collision: 'fit'});
}
}).on('keydown', '.CodeMirror', autocomplete).resizable( {handles: 'w', minWidth: 350} );
pEmpty( $original );
});
// $.when很容易出错,这里保险起见用Promise.all
$('body').click(() => { $dropdown.slideUp('fast'); });
Promise.all([getJSON, mw.request, getExt]).then(data => {
btns[0].$element.contextmenu(e => {
mw.config.set('extCodeMirrorConfig', data[0]);
e.preventDefault();
mw.hook( 'codemirror.config' ).fire();
OO.ui.prompt( wgULS('请输入编辑摘要:', '請輸入編輯摘要:') , {textInput: {value: summary}} ).then(input => {
text = data[1].query.pages[0].revisions[0].content;
if (input !== null) { summary = input; }
editor = new CodeMirror($outer[0], {value: text, mode: 'text/mediawiki', mwConfig: data[0],
});
lineWrapping: true, lineNumbers: true});
});
$wrapper = $( editor.getWrapperElement() ).toggle().append( [$dropdown, $hints] );
if (isBackup) {
$('<div>', {id: 'inspector-btns', html: btns.map(ele => ele.$element)}).appendTo( $outer );
btns[2].$element.contextmenu(e => {
// 处理页面上方的差异
e.preventDefault();
$('.diff').click(e => {
loadBackup();
const row = $( e.target ).closest('tr'),
});
isLineno = row.children( '.diff-lineno' ).length ? 1 : 0,
}
rowLineno = isLineno ? row : row.prevAll( ':has(.diff-lineno)' ).first(),
if (isGadget( 'PreviewWithVariant' ) ) {
n = parseInt( rowLineno.children().last().text().match(/\d+/) ) + row.index() - rowLineno.index()
const options = [{label: "大陆简体", data: "zh-cn"}, {label: "香港繁體", data: "zh-hk"},
- 2 + isLineno, // 使用parseInt规避可能的程序错误,注意CodeMirror的行号从0开始
{label: "澳門繁體", data: "zh-mo"}, {label: "大马简体", data: "zh-my"},
nLine = editor.lastLine();
{label: "新加坡简体", data: "zh-sg"}, {label: "臺灣正體", data: "zh-tw"}],
if (nLine >= n) {
select = new OO.ui.DropdownInputWidget({classes: ['inspector-variant'], options: options, value: lang})
editor.scrollIntoView(nLine);
.on('change', () => { lang = select.getValue(); }),
editor.scrollIntoView(n);
menu = select.$element.find( '.oo-ui-menuSelectWidget' )
}
.click(() => { menu.addClass( 'oo-ui-element-hidden' ); });
else { mw.notify( wgULS('当前不存在该行!', '當前不存在該行!'), {type: 'warn'} ); }
select.$element.prependTo( btns[1].$element );
});
btns[1].$element.contextmenu(e => {
}, reason => { mw.apiFailure(reason, `CodeMirror${wgULS('设置或页面', '設置或頁面')}Wikitext`); })
e.preventDefault();
.then(() => { $outer.removeClass( 'mw-ajax-loader' ); });
menu.removeClass( 'oo-ui-element-hidden' );
}).children('a').blur(() => { menu.addClass( 'oo-ui-element-hidden' ); });
}
pEmpty( $original );
// $.when很容易出错,这里保险起见用Promise.all
Promise.all([getJSON, mw.request, getExt]).then(data => {
mw.hook( 'codemirror.config' ).fire();
text = data[1].query.pages[0].revisions[0].content;
editor = new CodeMirror($outer[0], {value: text, mode: 'text/mediawiki',
mwConfig: mw.config.get('extCodeMirrorConfig'), lineWrapping: true, lineNumbers: true
});
$wrapper = $( editor.getWrapperElement() ).toggle().append( [$dropdown, $hints] );
$('<div>', {id: 'inspector-btns', html: btns.map(ele => ele.$element)}).appendTo( $outer );
// 处理页面上方的差异
$('.diff').click(e => {
const row = $( e.target ).closest('tr');
if (row.hasClass( 'diff-title' )) { return; }
const isLineno = row.children( '.diff-lineno' ).length ? 1 : 0,
rowLineno = isLineno ? row : row.prevAll( ':has(.diff-lineno)' ).first(),
n = parseInt( rowLineno.children().last().text().match(/\d+/) ) + row.index() - rowLineno.index()
- 2 + isLineno, // 使用parseInt规避可能的程序错误,注意CodeMirror的行号从0开始
nLine = editor.lastLine();
if (nLine >= n) {
editor.scrollIntoView(nLine);
editor.scrollIntoView(n);
}
else { mw.notify( wgULS('当前不存在该行!', '目前不存在此行!'), {type: 'warn'} ); }
});
}, reason => { mw.apiFailure(reason, `CodeMirror${wgULS('设置或页面', '設定或頁面')}Wikitext`); })
.then(() => { $outer.removeClass( 'mw-ajax-loader' ); });
});
//</nowiki>
6,698

个编辑

导航菜单