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

“User:Bhsd/tool.js”的版本间差异

来自LLWiki
跳转到导航 跳转到搜索
(// 使用Wikiplus小工具快速编辑)
标签移动版网页编辑 移动版编辑
 
(未显示同一用户的50个中间版本)
第1行: 第1行:
// 由[[Special:Mypage/common.js]]调用,可以使用ES6语法
/* 生成JS文件大小
/**
var api = new mw.Api(),
* @Description: 自用的工具函数
table = $('table').first(),
* @Author: [[User:Bhsd]]
list = table.find('td:first-child a');
*/
table.find('th').first().after( '<th>大小</th>' );
"use strict";
list.each(function() {
// jshint varstmt: true
var ele = $(this);
/**
var title = ele.attr('href').substring(4);
* @Function: 批量添加文件授权协议,只能处理不超过500个文件的分类
api.get({ action:'query', formatversion:2, prop:'info', titles:title }).then(function(data) {
* @Dependencies: mediawiki.api, ext.gadget.site-lib
var length = data.query.pages[0].length;
* @Param {String} cmtitle 分类名,默认为当前所在分类页
ele.parent().after('<td>' + length + '</td>');
*/
});
mw.myCopyright = (cmtitle = mw.config.get( 'wgTitle' )) => {
});
const cats = ['原作者保留权利的文件', '可自由使用的文件', 'LLWiki版权所有的文件', '使用CC Zero协议的文件'],
*/
api = new mw.Api();
mw.timedQuery(api, { prop: 'categories', generator: 'categorymembers', gcmtitle: `Category:${cmtitle}`,
gcmtype: 'file', gcmlimit: 'max', clcategories: cats.map(ele => `Category:${ele}`).join( '|' ), cllimit: 'max'
}, '分类下无授权协议的文件').then(res => {
res.query.pages.filter(ele => !ele.categories).forEach(ele => {
api.postWithToken('csrf', {action: 'edit', pageid: ele.pageid, minor: 1, bot: 1,
prependtext: '==授权协议==\n{{copyright}}\n', summary: '使用API批量添加授权协议',
}).catch(reason => { console.error( `页面${ele.pageid}无法添加授权协议,错误原因:${reason}` ); });
});
}, () => {});
};


/**
// 引自[[wikipedia:User:Kephir/gadgets/table-editor.js]]
* @Function: 查询JS页面大小
$(function() {
* @Dependencies: mediawiki.api, ext.gadget.site-lib
if(!['edit', 'submit'].includes( mw.config.get('wgAction') ) ||
*/
mw.config.get('wgPageContentModel') != 'wikitext')
mw.myJsSize = () => {
return;
const $table = $('.jsTable'), // 总是获取当前页面中的表格
$items = $table.find( 'tr:nth-child(n+1)' ),
titles = $items.find( 'a' ).toArray().map(ele => ele.title);
mw.timedQuery(new mw.Api(), {prop: 'info', titles: titles.join( '|' )}, 'JS页面大小').then(data => {
$table.toggleClass( 'jsTable jsTable2' );
// 注意返回的结果可能顺序不同
const lengths = Object.fromEntries( data.query.pages.map(ele => [ele.title, ele.length]) );
$items.children( 'td:last-child' ).text(i => (lengths[ titles[i] ] / 1024).toFixed(1));
}, () => { $('#myJsSize').off( 'click' ).one('click', mw.myJsSize); });
};


mw.hook( 'wikipage.content' ).add($content => {
/* 表格列操作 */
const $btn = $content.find( '#myJsSize' ).one('click', mw.myJsSize);
var editBox = $('#wpTextbox1');
if ($btn.length === 0) { return; }
function getSelection(textarea) {
console.log('Hook: wikipage.content, 开始添加JS大小查询按钮');
var start = textarea.prop('selectionStart'),
});
end = textarea.prop('selectionEnd');
return [textarea.val().substring(0, start),
textarea.val().substring(start, end),
textarea.val().substring(end)
];
}
function readTable(table) {
table = table.trim();
if( !/^{\|[\s\S]*\|}$/.test(table) ) { return false; }
table = table.substring(2, table.length - 2).trim();
var tableProperty = table.match(/^([\s\S]*?)\n/)[1],
tbody = table.substring( tableProperty.length ).trim(),
tr = tbody.split('|-').map(e => e.trim()).filter(e => /[\|!]/.test(e));
trProperty = tr.map(e => e.match(/^([\s\S]*?)[\|!]/)[1]),
td = tr.map( (e, i) => [e.charAt(trProperty[i].length), ...e.substring( trProperty[i].length + 1 ).split(/(\|\||\n[\s]*\||!!|\n[\s]*!)/)]);
return {tableProperty: tableProperty, trProperty: trProperty, td: td};
}
function parseTable(table) {
var result = "{|" + table.tableProperty.trim() + "\n",
td = table.td;
table.trProperty.forEach(function(e, i) {
if(i || e.trim()) { result += "|-" + e.trim() + "\n"; }
for(var j = 0; j < td[i].length / 2; j++) {
result += td[i][j * 2].slice(-1) + td[i][j * 2 + 1] + "\n";
}
});
return result + "|}";
}
function parseCompactTable(table) {
var result = "{|" + table.tableProperty.trim() + "\n",
td = table.td;
table.trProperty.forEach(function(e, i) {
if(i || e.trim()) { result += "|-" + e.trim() + "\n"; }
for(var j = 0; j < td[i].length / 2; j++) {
result += td[i][j * 2].slice(-1) + td[i][j * 2 + 1] + (td[i][j * 2 + 2] || "\n").slice(-1);
}
});
return result + "|}";
}
function insertCol(table) {
var init = prompt( wgULS("请输入插入列的初始值:", "請輸入插入列的初始值") );
table.td.map(e => [...e, '|', init]);
return table;
}
function permuteCol(table) {
var order = prompt( wgULS("请输入新的列序。原第一列记为0,依次类推。以半角符号(,)分隔,省略想要删除的列的序号", "請輸入新的列序。原第一列記為0,依此類推。以半形符號(,)分隔,省略想要刪除的列的序號") ).split(',').filter(e => !isNaN(e) && e >= 0);
if(order.length === 0) {
mw.notify("列序输入格式不正确", "列序輸入格式不正確");
return table;
}
table.td = table.td.map(e => {
var newTr = [];
order.forEach(function(i) {
newTr.push(e[2 * i] || '|');
newTr.push(e[2 * i + 1] || ' ');
});
return newTr;
});
return table;
}


(() => {
editBox.wikiEditor('addToToolbar', {
/**
sections: {
* @Function: 记录所有触发的Hook
'tables': {
*/
type: 'toolbar',
const start = mw.now();
label: '表格'
['postEdit', 'wikipage.content', 'wikipage.collapsibleContent', 'wikipage.categories', 'wikipage.diff',
}
'wikipage.editform', 'structuredChangeFilters.ui.initialized', 'codeEditor.configure', // MW原生Hook
}
'code.prettify', 'wikiplus.dialog', 'local.comments', 'hotcat.ready',
});
'settings.dialog', 'to.bottom' // 小工具Hook
editBox.wikiEditor('addToToolbar', {
].forEach(ele => {
section: 'tables',
mw.hook( ele ).add(x => {
groups: {
console.log(`Hook: ${ele} after ${mw.now() - start} ms`);
'tables': {}
if (x) { console.info(x); }
}
});
});
});
function addButton(text, icon, handler) {
}) ();
editBox.wikiEditor('addToToolbar', {
section: 'tables',
group: 'tables',
tools: {
ident: {
label: text,
type: 'button',
icon: icon,
action: {
type: 'callback',
execute: function() {
var parts = getSelection(editBox),
table = readTable( parts[1] );
if(!table) {
mw.notify( wgULS("表格不完整或存在错误", "表格不完整或存在錯誤") );
return;
}
editBox.val( parts[0] + handler(table) + parts[2] );
}
}
}
}
});
}
addButton(wgULS("<tr>分行书写", "<tr>分行書寫"),
"//upload.wikimedia.org/wikipedia/commons/c/c0/Knop_onzijdig.png",
parseTable
);
addButton(wgULS("<tr>一行书写", "<tr>一行書寫"),
"//upload.wikimedia.org/wikipedia/commons/8/8e/Button_number_1.png",
parseCompactTable
);
addButton(wgULS("在最右侧插入一列", "在最右側插入一列"),
"//upload.wikimedia.org/wikipedia/commons/6/60/Button_support.png",
function(table) {
return parseCompactTable( insertCol(table) );
}
);
addButton(wgULS("改变列序和/或删除部分列", "改變列序和/或刪除部分列"),
"//upload.wikimedia.org/wikipedia/commons/9/98/Button_oppose.png",
function(table) {
return parseCompactTable( permuteCol(table) );
}
);
});

2023年3月17日 (五) 13:30的最新版本

// 由[[Special:Mypage/common.js]]调用,可以使用ES6语法
/**
 * @Description: 自用的工具函数
 * @Author: [[User:Bhsd]]
 */
"use strict";
// jshint varstmt: true
/**
 * @Function: 批量添加文件授权协议,只能处理不超过500个文件的分类
 * @Dependencies: mediawiki.api, ext.gadget.site-lib
 * @Param {String} cmtitle 分类名,默认为当前所在分类页
 */
mw.myCopyright = (cmtitle = mw.config.get( 'wgTitle' )) => {
	const cats = ['原作者保留权利的文件', '可自由使用的文件', 'LLWiki版权所有的文件', '使用CC Zero协议的文件'],
		api = new mw.Api();
	mw.timedQuery(api, { prop: 'categories', generator: 'categorymembers', gcmtitle: `Category:${cmtitle}`,
		gcmtype: 'file', gcmlimit: 'max', clcategories: cats.map(ele => `Category:${ele}`).join( '|' ), cllimit: 'max'
	}, '分类下无授权协议的文件').then(res => {
		res.query.pages.filter(ele => !ele.categories).forEach(ele => {
			api.postWithToken('csrf', {action: 'edit', pageid: ele.pageid, minor: 1, bot: 1,
				prependtext: '==授权协议==\n{{copyright}}\n', summary: '使用API批量添加授权协议',
			}).catch(reason => { console.error( `页面${ele.pageid}无法添加授权协议,错误原因:${reason}` ); });
		});
	}, () => {});
};

/**
 * @Function: 查询JS页面大小
 * @Dependencies: mediawiki.api, ext.gadget.site-lib
 */
mw.myJsSize = () => {
	const $table = $('.jsTable'), // 总是获取当前页面中的表格
		$items = $table.find( 'tr:nth-child(n+1)' ),
		titles = $items.find( 'a' ).toArray().map(ele => ele.title);
	mw.timedQuery(new mw.Api(), {prop: 'info', titles: titles.join( '|' )}, 'JS页面大小').then(data => {
		$table.toggleClass( 'jsTable jsTable2' );
		// 注意返回的结果可能顺序不同
		const lengths = Object.fromEntries( data.query.pages.map(ele => [ele.title, ele.length]) );
		$items.children( 'td:last-child' ).text(i => (lengths[ titles[i] ] / 1024).toFixed(1));
	}, () => { $('#myJsSize').off( 'click' ).one('click', mw.myJsSize); });
};

mw.hook( 'wikipage.content' ).add($content => {
	const $btn = $content.find( '#myJsSize' ).one('click', mw.myJsSize);
	if ($btn.length === 0) { return; }
	console.log('Hook: wikipage.content, 开始添加JS大小查询按钮');
});

(() => {
	/**
	 * @Function: 记录所有触发的Hook
	 */
	const start = mw.now();
	['postEdit', 'wikipage.content', 'wikipage.collapsibleContent', 'wikipage.categories', 'wikipage.diff',
		'wikipage.editform', 'structuredChangeFilters.ui.initialized', 'codeEditor.configure', // MW原生Hook
		'code.prettify', 'wikiplus.dialog', 'local.comments', 'hotcat.ready',
		'settings.dialog', 'to.bottom' // 小工具Hook
	].forEach(ele => {
		mw.hook( ele ).add(x => {
			console.log(`Hook: ${ele} after ${mw.now() - start} ms`);
			if (x) { console.info(x); }
		});
	});
}) ();