User:Barkeep49/ACPosting.js
Appearance
Code that you insert on this page could contain malicious content capable of compromising your account. If you import a script from another page with "importScript", "mw.loader.load", "iusc", or "lusc", take note that this causes you to dynamically load a remote script, which could be changed by others. Editors are responsible for all edits and actions they perform, including by scripts. User scripts are not centrally supported and may malfunction or become inoperable due to software changes. A guide to help you find broken scripts is available. If you are unsure whether code you are adding to this page is safe, you can ask at the appropriate village pump.
This code will be executed when previewing this page.
This code will be executed when previewing this page.
Documentation for this user script can be added at User:Barkeep49/ACPosting.
/**
* ArbCom Posting Tool (BETA) 1.0.0
* Fork of the U4C Posting Tool for English Wikipedia Arbitration Committee clerks.
*
* One toolbar link ("ArbCom notifications") opens a menu of notification modules:
*
* On Wikipedia:Arbitration/Requests/Case (live page or an old revision):
* - Request declined / withdrawn (parties)
* - Statement word-limit signals ({{ACWordStatus}} + {{ArbComSize}})
* - Case opened ({{ArbComOpened}} + creates the Update list)
* On a case page (Wikipedia[ talk]:Arbitration/Requests/Case/<case>[/...]):
* - Add party during case ({{ArbComOpened}} with added-by-arbs-after-opening)
* - Evidence word-limit signals ({{ACWordStatus}}, {{ApprovedWordLimit}}, over-length notices)
* - Phase closing soon (evidence / workshop talk page)
* - Proposed decision posted ({{ArbComPD}} + Update-list message)
* - Case update to the Update list
* - Case closed / suspended (WP:AC/N announcement for ArbClerkBot + manual backup)
*
* Only existing templates and wording copied from real clerk notices are used.
* Delivery to the Update list uses the edit API (no MassMessage).
*
* Install on your enwiki common.js page, e.g.:
* mw.loader.load('//en.wikipedia.org/w/index.php?title=User:Barkeep49/ACPosting.js&action=raw&ctype=text/javascript');
*/
(function () {
'use strict';
const REQUESTS_PAGE = 'Wikipedia:Arbitration/Requests/Case';
const ACN_PAGE = 'Wikipedia:Arbitration Committee/Noticeboard';
const WORDCOUNT_PAGE = 'User:ClerkBot/ArbCom word counts/data';
const MODAL_ID = 'arbcom-modal-container';
const TOOL_NAME = 'ArbCom Posting Tool';
const SCRIPT_PAGE = 'User:Barkeep49/ACPosting.js';
// Ends every edit summary this tool writes, linking back to the script.
const VIA = `(via [[${SCRIPT_PAGE}|${TOOL_NAME}]])`;
function debugLog(message, data) {
console.log(`[${new Date().toISOString()}] ${TOOL_NAME}: ${message}`, data || '');
}
// ---- Pure parsing helpers (no mw/DOM: extracted and tested in Node) ----
const DEFAULT_DAYS = 14;
const CASE_PAGE_PREFIX = 'Wikipedia:Arbitration/Requests/Case/';
// MediaWiki runs its pre-save transform on user JS pages too (verified on enwiki): substitution
// calls, safe-substitution calls, signature tildes and the empty-label pipe trick written
// literally anywhere in this file (comments included) get expanded when the page is saved,
// which corrupts the script. So the substitution opener is built from two pieces, and
// tests/test-wiki-safe.js fails if any of those sequences appears literally.
const SUBST = '{' + '{subst:';
// Tildes stay escaped so MediaWiki can never expand them if this source is processed as wikitext.
const WIKI_SIGNATURE = '\u007E\u007E\u007E\u007E';
function escapeRegExp(text) {
return String(text).replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}
// "mdm.bla" / "Foo_bar" -> underscores to spaces, trimmed, first letter uppercased.
function normalizeUsername(name) {
const clean = String(name).replace(/_/g, ' ').replace(/\s+/g, ' ').trim();
return clean.charAt(0).toUpperCase() + clean.slice(1);
}
function nameKey(name) {
return normalizeUsername(name).toLowerCase();
}
// Splits wikitext into level-2 sections: [{ title, body }].
function splitRequests(wikitext) {
const requests = [];
const headingRe = /^==\s*([^=\n][^\n]*?)\s*==[ \t]*$/gm;
let match;
let last = null;
while ((match = headingRe.exec(wikitext)) !== null) {
if (last) last.body = wikitext.slice(last.start, match.index);
last = { title: match[1].trim(), start: match.index + match[0].length, body: '' };
requests.push(last);
}
if (last) last.body = wikitext.slice(last.start);
return requests.map(r => ({ title: r.title, body: r.body }));
}
// Usernames from the "Proposed parties" / "Involved parties" bullet list.
function parseParties(body) {
const headingMatch = body.match(/^===\s*(?:proposed\s+|involved\s+)?parties\s*===[ \t]*$/im);
if (!headingMatch) return [];
let section = body.slice(headingMatch.index + headingMatch[0].length);
// The list ends at the next heading or at the first ";" definition line.
const end = section.search(/^(?:=+[^=\n]+=+|;)/m);
if (end !== -1) section = section.slice(0, end);
const found = [];
const seen = new Set();
const add = name => {
const clean = normalizeUsername(name);
if (clean && !seen.has(clean.toLowerCase())) {
seen.add(clean.toLowerCase());
found.push(clean);
}
};
const tplRe = /^\*+\s*\{\{\s*[^|{}]+\|\s*(?:1\s*=\s*)?([^|{}]+?)\s*(?:\||\}\})/;
const linkRe = /\[\[:?User:([^\]|\/#]+)/i;
section.split('\n').forEach(line => {
if (!/^\*/.test(line)) return;
const tpl = line.match(tplRe);
if (tpl) { add(tpl[1]); return; }
const link = line.match(linkRe);
if (link) add(link[1]);
});
return found;
}
// Candidate signature authors in one statement section, in order of appearance.
function findSignatureNames(text) {
const names = [];
const linkRe = /\[\[:?User(?:[ _]talk)?:([^\]|\/#]+)/gi;
text.split('\n').forEach(line => {
const utc = line.lastIndexOf('(UTC)');
if (utc === -1) return;
const before = line.slice(0, utc);
let last = null;
let m;
linkRe.lastIndex = 0;
while ((m = linkRe.exec(before)) !== null) last = m[1];
if (last) names.push(normalizeUsername(last));
});
return names;
}
function headingToName(heading) {
return normalizeUsername(heading.replace(/\s*\([^)]*\)\s*$/, ''));
}
// One entry per "=== Statement by X ===" section:
// { heading, username, source: 'signature' | 'heading' }.
function parseStatements(body) {
const statements = [];
const sectionRe = /^===\s*([^=\n][^\n]*?)\s*===[ \t]*$/gm;
const sections = [];
let m;
while ((m = sectionRe.exec(body)) !== null) {
if (sections.length) sections[sections.length - 1].end = m.index;
sections.push({ heading: m[1].trim(), start: m.index + m[0].length, end: body.length });
}
sections.forEach(sec => {
const h = sec.heading.match(/^Statement\s+by\s+(.+)$/i);
if (!h || /[{}]/.test(h[1])) return; // skips the "{Non-party}" template
const headingName = headingToName(h[1]);
const sigs = findSignatureNames(body.slice(sec.start, sec.end));
const headingMatch = sigs.find(n => nameKey(n) === nameKey(headingName));
if (headingMatch) {
statements.push({ heading: sec.heading, username: headingMatch, source: 'signature' });
} else if (sigs.length) {
statements.push({ heading: sec.heading, username: sigs[0], source: 'signature' });
} else {
statements.push({ heading: sec.heading, username: headingName, source: 'heading' });
}
});
return statements;
}
// Non-party statement authors (deduplicated, parties removed).
function buildNonParties(parties, statements) {
const partyKeys = new Set(parties.map(nameKey));
const seen = new Set();
const out = [];
statements.forEach(s => {
const key = nameKey(s.username);
if (partyKeys.has(key) || seen.has(key)) return;
seen.add(key);
out.push(s);
});
return out;
}
// kind: 'party' | 'nonparty' | 'arbadded'. `days` only appears for a custom timetable.
function buildNoticeTemplate({ caseName, days, kind }) {
let code = `${SUBST}ArbComOpened|${caseName}`;
if (days && Number(days) !== DEFAULT_DAYS) code += `|days=${Number(days)}`;
if (kind === 'nonparty') code += '|party=no';
else if (kind === 'arbadded') code += '|added-by-arbs-after-opening=yes';
return code + '}}';
}
// "User talk:Foo | 1250" -> { target: 'User talk:Foo', count: 1250 }; count is null when absent.
function splitTargetCount(line) {
const m = String(line).match(/^(.*?)\s*\|\s*(\d[\d,]*)\s*$/);
return m
? { target: m[1].trim(), count: Number(m[2].replace(/,/g, '')) }
: { target: String(line).trim(), count: null };
}
// Items under a "==Remedies==" / "==Findings of fact==" section:
// [{ heading, number, text, passed, passedLine }]. `text` has the "N)" prefix and the
// ":''Passed X to Y ...''" tally line removed.
function parseDecisionItems(wikitext, sectionName) {
const text = wikitext.replace(/<!--[\s\S]*?-->/g, '');
const sectionMatch = new RegExp('^==\\s*' + escapeRegExp(sectionName) + '\\s*==[ \\t]*$', 'im').exec(text);
if (!sectionMatch) return [];
let rest = text.slice(sectionMatch.index + sectionMatch[0].length);
const end = rest.search(/^={1,2}[^=\n][^\n]*?={1,2}[ \t]*$/m);
if (end !== -1) rest = rest.slice(0, end);
const items = [];
const headingRe = /^===\s*([^=\n][^\n]*?)\s*===[ \t]*$/gm;
let m;
let prev = null;
while ((m = headingRe.exec(rest)) !== null) {
if (prev) prev.body = rest.slice(prev.start, m.index);
prev = { heading: m[1].trim(), start: m.index + m[0].length, body: '' };
items.push(prev);
}
if (prev) prev.body = rest.slice(prev.start);
return items.map(item => {
// On the Proposed decision page the proposal is followed by arbitrators' ":Support:" /
// ":Oppose:" vote lists, which name arbitrators and are not part of the proposal.
const voteStart = item.body.search(/^:+\s*(?:Support|Oppose|Abstain|Comments?)\b/im);
if (voteStart !== -1) item.body = item.body.slice(0, voteStart);
const lines = item.body.split('\n');
const passedIdx = lines.findIndex(l => /^:+\s*''\s*Passed\b/i.test(l));
const passedLine = passedIdx >= 0 ? lines[passedIdx].trim() : '';
const body = lines.filter((l, i) => i !== passedIdx).join('\n').trim();
const num = body.match(/^(\d+(?:\.\d+)?)\)\s*/);
return {
heading: item.heading,
number: num ? num[1] : '',
text: (num ? body.slice(num[0].length) : body).trim(),
passed: passedIdx >= 0,
passedLine
};
});
}
// Users named in decision items: { 'Normalized name': [item headings] }. Known names
// (the parties) match as whole words; {{user|X}} and [[User:X]] links match too.
function findMentionedUsers(items, knownNames) {
const found = {};
const add = (name, heading) => {
const n = normalizeUsername(name);
if (!n) return;
if (!found[n]) found[n] = [];
if (!found[n].includes(heading)) found[n].push(heading);
};
items.forEach(item => {
const text = item.heading + '\n' + item.text;
knownNames.forEach(n => {
if (new RegExp('(?<![\\w])' + escapeRegExp(n) + '(?![\\w])').test(text)) add(n, item.heading);
});
for (const m of text.matchAll(/\{\{\s*(?:user|u|userlinks|admin|np2|noping)\s*\|\s*(?:1\s*=\s*)?([^|}]+)/gi)) add(m[1], item.heading);
for (const m of text.matchAll(/\[\[:?User(?: talk)?:([^\]|\/#]+)/gi)) add(m[1], item.heading);
});
return found;
}
// Fields of a case's /Data subpage that the tool uses.
function parseCaseData(wikitext) {
const wanted = {
'date-opened': 'dateOpened', 'date-evidence': 'dateEvidence', 'date-workshop': 'dateWorkshop',
'date-pd': 'datePd', 'workshop-skipped': 'workshopSkipped'
};
const out = {};
const text = wikitext.replace(/<!--[\s\S]*?-->/g, '');
for (const m of text.matchAll(/^\|\s*([a-z0-9-]+)\s*=([^\n]*)$/gm)) {
const key = wanted[m[1]];
if (key && !(key in out)) out[key] = m[2].trim();
}
return out;
}
const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];
function parseUtcDate(text) {
const m = String(text || '').match(/(\d{1,2})\s+([A-Za-z]+)\s+(\d{4})/);
if (!m) return NaN;
const month = MONTHS.indexOf(m[2].toLowerCase());
return month < 0 ? NaN : Date.UTC(Number(m[3]), month, Number(m[1]));
}
// Calendar days from `nowMs` (UTC date) to "15 August 2026"; what {{ArbComOpened|days=}} needs.
function daysUntilDate(dateText, nowMs) {
const target = parseUtcDate(dateText);
if (Number.isNaN(target)) return null;
const now = new Date(nowMs);
const today = Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate());
return Math.round((target - today) / 86400000);
}
// "15 August 2026" -> "23:59, 15 August 2026 (UTC)" (phase deadlines are 23:59 UTC).
function formatDeadline(dateText) {
const m = String(dateText || '').match(/(\d{1,2})\s+([A-Za-z]+)\s+(\d{4})/);
return m ? `23:59, ${m[1]} ${m[2]} ${m[3]} (UTC)` : String(dateText || '');
}
// A case's Update list (MassMessageListContent JSON). Targets on other wikis are dropped.
function parseUpdateList(jsonText) {
try {
const data = JSON.parse(jsonText);
const targets = (data.targets || [])
.filter(t => t && t.title && (!t.site || t.site === 'en.wikipedia.org'))
.map(t => t.title);
return { description: data.description || '', targets };
} catch (e) {
return { description: '', targets: [] };
}
}
// Reads ClerkBot's nested {{#switch}} word-count data into
// { page: { section: { user: { words, uncollapsed, limit, status } } } }.
function parseWordCountData(wikitext) {
const root = {};
const stack = [root];
wikitext.split('\n').forEach(raw => {
const line = raw.trim();
const open = line.match(/^\|\s*(.+?)\s*=\s*\{\{#switch:\s*\{\{\{\w+\}\}\}\s*$/);
if (open) {
const node = {};
stack[stack.length - 1][open[1]] = node;
stack.push(node);
return;
}
if (/^\}\}\s*$/.test(line)) {
if (stack.length > 1) stack.pop();
return;
}
const leaf = line.match(/^\|\s*(words|uncollapsed|limit|status)\s*=\s*(.+?)\s*$/);
if (leaf) {
stack[stack.length - 1][leaf[1]] = leaf[1] === 'status' ? leaf[2] : Number(leaf[2]);
}
});
return root;
}
// ArbClerkBot cross-posts to a linked user when "[:|]Name[]|}]" appears in the section.
function botWillReach(wikitext, name) {
const body = escapeRegExp(normalizeUsername(name)).replace(/ /g, '[ _]');
return new RegExp('[:|]' + body + '[\\]|}]').test(wikitext);
}
// Links the first plain mention of each recipient with {{user|X}} so ArbClerkBot reaches them;
// recipients that can't be linked in the text are returned in `bcc` (for {{bcc|...}}).
function linkRecipients(text, recipients, linkUsers) {
const bcc = [];
(recipients || []).forEach(name => {
if (botWillReach(text, name)) return;
if (linkUsers) {
const re = new RegExp('(?<![\\w\\[|:/#])' + escapeRegExp(name).replace(/ /g, '[ _]') + '(?![\\w\\]|}])');
if (re.test(text)) {
text = text.replace(re, '{{user|' + name + '}}');
return;
}
}
bcc.push(name);
});
return { text, bcc };
}
// Case-closed announcement in the wording of the real Gun control 2 notice.
function buildClosing({ caseName, remedies, recipients, linkUsers }) {
const page = CASE_PAGE_PREFIX + caseName;
const bullets = remedies.map(r => r.trim().split('\n').map((line, i) => {
if (i === 0) return '* ' + line;
return /^\*/.test(line) ? '*' + line : line;
}).join('\n')).join('\n');
const linked = linkRecipients(bullets, recipients, linkUsers);
const bcc = linked.bcc.length ? ' {{bcc|' + linked.bcc.join('|') + '}}' : '';
return {
heading: `[[${page}]] closed`,
body: `An arbitration case, [[${page}]], has been now closed. The final decision is available at the link above. The following remedies have been enacted regarding this case:${bcc}\n${linked.text}\nFor the Arbitration Committee, ${WIKI_SIGNATURE}`,
unlinked: linked.bcc
};
}
// Motion announcement (layout of "Arbitration motion regarding ..." on the ACN / Procedures/Statement).
function buildMotionAnnouncement({ caseName, permalink, motionText, recipients, linkUsers }) {
const page = CASE_PAGE_PREFIX + caseName;
const linked = linkRecipients(motionText, recipients, linkUsers);
const bcc = linked.bcc.length ? ' {{bcc|' + linked.bcc.join('|') + '}}' : '';
return {
heading: `Arbitration motion regarding [[${page}|''${caseName}'']]`,
body: `The Arbitration Committee has resolved by [[${permalink || 'Special:Permalink/'}|motion]] that:${bcc}\n{{ivmbox|1=${linked.text}}}\nFor the Arbitration Committee, ${WIKI_SIGNATURE}`,
unlinked: linked.bcc
};
}
// Wording of real "phase closing soon" notices (SilverLocust / HouseBlaster on past cases).
function buildPhaseClosing({ phase, deadline }) {
if (phase === 'Workshop') {
return {
heading: 'Workshop phase closing soon',
text: `The workshop phase is closing in just under 24 hours, at ${deadline}. Please have all your workshopping completed by that time. ${WIKI_SIGNATURE}`
};
}
return {
heading: 'Evidence phase closing soon',
text: `The evidence phase closes at ${deadline}, which is just under 24 hours after this comment. Please ensure all evidence is submitted before that time. ${WIKI_SIGNATURE}`
};
}
// Wording of real Update-list messages (HouseBlaster / SilverLocust on past cases).
function buildUpdateHeading(caseName) {
return `[[${CASE_PAGE_PREFIX}${caseName}|''${caseName}'']] updates`;
}
function buildUpdateIntro(caseName) {
const page = CASE_PAGE_PREFIX + caseName;
return `You are receiving this message because you are on [[${page}/Update list|the update list]] for [[${page}|''${caseName}'']].`;
}
function buildPdMemberMessage(caseName) {
const page = CASE_PAGE_PREFIX + caseName;
return {
heading: `Proposed decision for ${caseName} posted`,
text: `${buildUpdateIntro(caseName)} The [[${page}/Proposed decision|<strong>proposed decision</strong>]] has been posted. Your comments are welcome on [[Wikipedia talk:${page.replace(/^Wikipedia:/, '')}/Proposed decision|the talk page]] <strong>in your own section</strong>. For the Arbitration Committee, ${WIKI_SIGNATURE}`
};
}
// ArbComPD (substituted) takes the custom text as parameter 2.
function buildPdTemplate({ caseName, custom }) {
const extra = custom && custom.trim() ? `|2=${custom.trim()}` : '';
return `${SUBST}ArbComPD|${caseName}${extra}}}`;
}
// ArbComSize has no heading and no signature of its own, so the signature is added here.
function buildSizeTemplate(request) {
return `${SUBST}ArbComSize|${request}}} ${WIKI_SIGNATURE}`;
}
// Fallback only: the wording of {{Arb declined}} (heading and body) written out. The template had a
// malformed "</includeonly" between June 2023 and its fix on 2026-10-31; the default is the template.
function buildDeclinedNotice({ oldid, name, withdrawn }) {
const verb = withdrawn ? 'withdrawn and archived' : 'declined';
return `== Request for Arbitration declined ==\nThis is a courtesy notice to inform you that a request for arbitration, which named you as a party, has been {{Diff|Wikipedia:Arbitration/Requests/Case|next|${oldid}|${verb}}}. Feel free to see {{oldid2|${oldid}|${name}: Arbitrators' opinion on hearing this matter|the Arbitrators' opinions}} for potential suggestions on moving forward.\n\nFor the Arbitration Committee, ${WIKI_SIGNATURE}`;
}
function buildDeclinedTemplateCall({ oldid, name, withdrawn }) {
return `${SUBST}Arb declined|oldid=${oldid}|name=${name}${withdrawn ? '|withdrawn=yes' : ''}}}`;
}
// Over-length evidence: {{Evidence too long}} for parties (its limit is 1000 words);
// the Procedures page wording for non-parties (500 words / 50 diffs).
function buildEvidenceNotice({ kind, words }) {
if (kind === 'party') return `${SUBST}Evidence too long|${words}}} ${WIKI_SIGNATURE}`;
return `The Arbitration Committee has asked that evidence presentations be kept to around 500 words and 50 diffs. Your presentation is over ${words} words. Please edit your section to focus on the most relevant evidence. If you wish to submit over-length evidence, you must first obtain the agreement of the arbitrators by posting a request on the /Evidence talk page. For the Arbitration Committee, ${WIKI_SIGNATURE}`;
}
// Adds {{ACWordStatus}} lines under "<prefix> <user>" headings. targets: [{ user, headingName }].
function insertWordStatus(wikitext, { prefix, targets, makeLine }) {
const wanted = new Map(targets.map(t => [nameKey(t.headingName || t.user), t.user]));
const headRe = new RegExp('^(={2,4})\\s*' + escapeRegExp(prefix) + '\\s+(.+?)\\s*\\1\\s*$', 'i');
const lines = wikitext.split('\n');
const out = [];
const inserted = [];
for (let i = 0; i < lines.length; i++) {
out.push(lines[i]);
const m = lines[i].match(headRe);
if (!m) continue;
const key = nameKey(headingToName(m[2]));
if (!wanted.has(key)) continue;
let j = i + 1;
while (j < lines.length && lines[j].trim() === '') j++;
if (j < lines.length && /ACWordStatus/i.test(lines[j])) continue;
out.push(makeLine(wanted.get(key)));
inserted.push(wanted.get(key));
}
return { text: out.join('\n'), inserted };
}
// Records a granted extension: {{ApprovedWordLimit}} under the user's heading
// (after their {{ACWordStatus}} line, if present).
function recordExtension(wikitext, { prefix, user, words }) {
const headRe = new RegExp('^(={2,4})\\s*' + escapeRegExp(prefix) + '\\s+(.+?)\\s*\\1\\s*$', 'i');
const lines = wikitext.split('\n');
for (let i = 0; i < lines.length; i++) {
const m = lines[i].match(headRe);
if (!m || nameKey(headingToName(m[2])) !== nameKey(user)) continue;
// Already recorded with this value anywhere in the user's section: leave the text alone.
let end = i + 1;
while (end < lines.length && !headRe.test(lines[end]) && !/^==[^=]/.test(lines[end])) end++;
const already = lines.slice(i + 1, end).some(l => new RegExp('\\{\\{\\s*ApprovedWordLimit\\s*\\|\\s*words\\s*=\\s*' + Number(words) + '\\b', 'i').test(l));
if (already) return { text: wikitext, done: true, already: true };
let at = i + 1;
let j = i + 1;
while (j < lines.length && lines[j].trim() === '') j++;
if (j < lines.length && /ACWordStatus/i.test(lines[j])) at = j + 1;
lines.splice(at, 0, `{{ApprovedWordLimit|words=${words}|sig=${WIKI_SIGNATURE}}}`);
return { text: lines.join('\n'), done: true };
}
return { text: wikitext, done: false };
}
// Applies fn(sectionBody) to one level-2 section's text and splices the result back in.
function replaceRequestSection(wikitext, title, fn) {
const start = new RegExp('^==\\s*' + escapeRegExp(title) + '\\s*==[ \\t]*$', 'm').exec(wikitext);
if (!start) return null;
const bodyStart = start.index + start[0].length;
const rest = wikitext.slice(bodyStart);
const next = rest.search(/^==[^=\n][^\n]*?==[ \t]*$/m);
const bodyEnd = next === -1 ? wikitext.length : bodyStart + next;
return wikitext.slice(0, bodyStart) + fn(wikitext.slice(bodyStart, bodyEnd)) + wikitext.slice(bodyEnd);
}
// Body of the level-2 section with this heading (heading line excluded), or null.
function extractSection(wikitext, heading) {
const start = new RegExp('^==\\s*' + escapeRegExp(heading.trim()) + '\\s*==[ \\t]*$', 'm').exec(wikitext);
if (!start) return null;
const rest = wikitext.slice(start.index + start[0].length);
const next = rest.search(/^==[^=\n][^\n]*?==[ \t]*$/m);
return (next === -1 ? rest : rest.slice(0, next)).trim();
}
// Drops names whose nameKey is in `staffKeys` (current arbitrators and clerks).
function withoutStaff(names, staffKeys) {
return names.filter(n => !staffKeys.has(nameKey(n)));
}
function hasCaseClosedStamp(wikitext) {
return /'''Case closed'''\s+on/.test(wikitext.replace(/<!--[\s\S]*?-->/g, ''));
}
// ---- End pure helpers ----
// ---------- Page context ----------
function isRequestsPage() {
return window.location.hostname === 'en.wikipedia.org' && mw.config.get('wgPageName') === REQUESTS_PAGE;
}
// "Wikipedia[_talk]:Arbitration/Requests/Case/<case>[/...]" -> "<case>" (spaces, not underscores).
function getCaseNameFromPage() {
if (window.location.hostname !== 'en.wikipedia.org') return null;
const m = (mw.config.get('wgPageName') || '').match(/^Wikipedia(?:_talk)?:Arbitration\/Requests\/Case\/([^/]+)/);
return m ? m[1].replace(/_/g, ' ') : null;
}
function init() {
if (!mw?.config?.get('wgUserName')) return;
if (!isRequestsPage() && !getCaseNameFromPage()) {
debugLog('Not an arbitration requests/case page; the tools link is only added on WP:A/R/C and case pages.');
return;
}
const add = () => {
if (!mw.util?.addPortletLink || document.getElementById('t-arbcomclerk')) return;
// "p-tb" is the Tools menu in both Vector and Vector 2022 (pinned sidebar and dropdown are
// the same element); "p-cactions" is a fallback for skins that lack it.
const portlet = document.getElementById('p-tb') ? 'p-tb' : 'p-cactions';
try {
const link = mw.util.addPortletLink(portlet, '#', 'ArbCom notifications', 't-arbcomclerk', 'Arbitration Committee notifications');
if (link) link.addEventListener('click', e => { e.preventDefault(); showMenu(); });
else debugLog('addPortletLink returned nothing for #' + portlet);
} catch (error) {
debugLog('Could not add the portlet link', error);
}
};
if (document.readyState !== 'loading') add();
else document.addEventListener('DOMContentLoaded', add);
}
// ---------- Small shared helpers ----------
function getErrorMessage(error) {
if (!error) return 'An unknown error occurred.';
if (error.code) return `${error.code}: ${error.info}`;
if (error.message) return error.message;
return String(error);
}
function escapeHtml(text) {
return String(text)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
function flashButton(btn, text = 'Copied!') {
const original = btn.textContent;
btn.textContent = text;
setTimeout(() => { btn.textContent = original; }, 2000);
}
function copyToClipboard(text, btn, flashText) {
navigator.clipboard.writeText(text)
.then(() => { if (btn) flashButton(btn, flashText); })
.catch(() => alert('Failed to copy to clipboard.'));
}
// Namespace ID for a page's prefix, or null when it has no recognized prefix.
function getNamespaceId(page) {
const colonIndex = page.indexOf(':');
if (colonIndex <= 0) return null;
const prefix = page.slice(0, colonIndex).trim().toLowerCase().replace(/ /g, '_');
const ids = mw.config.get('wgNamespaceIds') || {};
return Object.prototype.hasOwnProperty.call(ids, prefix) ? ids[prefix] : null;
}
// "User talk:Foo/Archive 1" -> "Foo".
function getTargetBaseName(page) {
const colonIndex = page.indexOf(':');
const base = colonIndex === -1 ? page : page.slice(colonIndex + 1);
return base.split('/')[0].replace(/_/g, ' ').trim();
}
function toTalkTarget(name) {
return getNamespaceId(name) === null ? 'User talk:' + name : name;
}
function parseTargetList(text) {
return text.split('\n').map(l => l.replace(/_/g, ' ').replace(/\s+/g, ' ').trim()).filter(Boolean);
}
// ---------- API helpers ----------
async function fetchWikitext(title) {
const r = await new mw.Api().get({
action: 'query', prop: 'revisions', rvprop: 'content|ids|timestamp', rvslots: 'main',
titles: title, formatversion: 2
});
const page = r.query.pages[0];
if (page.missing) return null;
const rev = page.revisions[0];
return { text: rev.slots.main.content, revid: rev.revid, timestamp: rev.timestamp };
}
// Many pages at once (50 per request): Map of lower-cased title -> wikitext (null if missing).
async function fetchManyContents(titles) {
const out = new Map();
const api = new mw.Api();
for (let i = 0; i < titles.length; i += 50) {
const r = await api.get({
action: 'query', prop: 'revisions', rvprop: 'content', rvslots: 'main',
titles: titles.slice(i, i + 50).join('|'), formatversion: 2
});
r.query.pages.forEach(p => out.set(p.title.toLowerCase(), p.missing ? null : p.revisions[0].slots.main.content));
// Requested titles that the API normalized (underscores, first letter) point at the same text.
(r.query.normalized || []).forEach(n => out.set(n.from.toLowerCase(), out.get(n.to.toLowerCase())));
}
return out;
}
async function loadRequests() {
const response = await new mw.Api().get({ action: 'parse', oldid: mw.config.get('wgRevisionId'), prop: 'wikitext', formatversion: 2 });
if (!response.parse?.wikitext) throw new Error('Could not fetch page wikitext.');
const requests = splitRequests(response.parse.wikitext)
.map(r => ({ title: r.title, parties: parseParties(r.body), statements: parseStatements(r.body) }))
.filter(r => r.parties.length || r.statements.length);
if (!requests.length) throw new Error('No case requests with parties or statements were found on this revision.');
return requests;
}
async function loadUpdateList(caseName) {
const page = await fetchWikitext(`${CASE_PAGE_PREFIX}${caseName}/Update list`);
return page ? { exists: true, ...parseUpdateList(page.text) } : { exists: false, description: '', targets: [] };
}
async function loadCaseData(caseName) {
const base = CASE_PAGE_PREFIX + caseName;
const [main, data, updateList] = await Promise.all([fetchWikitext(base), fetchWikitext(base + '/Data'), loadUpdateList(caseName)]);
return {
mainText: main ? main.text : '',
parties: main ? parseParties(main.text) : [],
data: data ? parseCaseData(data.text) : {},
updateList
};
}
// Current arbitrators and clerks, read live from the list ArbClerkBot itself uses to skip them
// (User:ArbClerkBot/Authorized users), so term changes need no maintenance here. Returns a
// Set of nameKeys; empty if the list can't be read (nothing is filtered then).
async function loadStaffKeys() {
try {
const r = await new mw.Api().get({
action: 'query', prop: 'links', titles: 'User:ArbClerkBot/Authorized users',
plnamespace: 2, pllimit: 'max', formatversion: 2
});
const links = r.query.pages[0].links || [];
return new Set(links.map(l => nameKey(getTargetBaseName(l.title))));
} catch (error) {
debugLog('Could not read the arbitrator/clerk list', error);
return new Set();
}
}
async function loadWordCounts() {
const page = await fetchWikitext(WORDCOUNT_PAGE);
return page ? parseWordCountData(page.text) : {};
}
// Creates the case's Update list, or adds only the missing members (edit API; no MassMessage).
async function ensureUpdateList(caseName, userTargets) {
const title = `${CASE_PAGE_PREFIX}${caseName}/Update list`;
const api = new mw.Api();
const existing = await fetchWikitext(title);
if (!existing) {
const description = `Update list for the ''${caseName}'' case. Parties to the case and all users who offered statements in the case request have been added to this list. Any user may add themselves to this list to receive updates. Users except for parties may remove themselves from this list.`;
await api.postWithEditToken({
action: 'edit', title, createonly: true, contentmodel: 'MassMessageListContent',
text: JSON.stringify({ description, targets: userTargets.map(t => ({ title: t })) }, null, '\t'),
summary: `Creating update list ${VIA}`, format: 'json'
});
return { created: true, added: userTargets };
}
const have = new Set(parseUpdateList(existing.text).targets.map(t => t.replace(/_/g, ' ').toLowerCase()));
const missing = userTargets.filter(t => !have.has(t.replace(/_/g, ' ').toLowerCase()));
if (missing.length) {
await api.postWithEditToken({ action: 'editmassmessagelist', spamlist: title, add: missing.join('|'), format: 'json' });
}
return { created: false, added: missing };
}
// ---------- Modal ----------
function createModalContainer(title, bodyContent) {
[MODAL_ID, 'arbcom-modal-overlay'].forEach(id => document.getElementById(id)?.remove());
const overlay = Object.assign(document.createElement('div'), { id: 'arbcom-modal-overlay' });
overlay.style.cssText = 'position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); z-index: 1001;';
const formContainer = Object.assign(document.createElement('div'), { id: MODAL_ID });
formContainer.setAttribute('dir', 'ltr');
// Explicit colours: Vector 2022's night mode would otherwise give light text on this white box.
formContainer.style.cssText = 'position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: white; color: #202122; color-scheme: light; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); z-index: 1002; max-width: 720px; width: 90%; max-height: 90vh; display: flex; flex-direction: column; text-align: left;';
formContainer.innerHTML = `
<div id="arbcom-modal-header" style="display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid #ddd; padding-bottom: 10px; margin-bottom: 15px; cursor: move; user-select: none;">
<h2 style="margin: 0;">${title}</h2>
<button id="arbcom-modal-close" style="background: none; border: none; font-size: 24px; cursor: pointer; line-height: 1;">×</button>
</div>
<div class="modal-body" style="overflow-y: auto;">${bodyContent}</div>`;
document.body.append(overlay, formContainer);
const header = formContainer.querySelector('#arbcom-modal-header');
let dragOffset = null;
const onDragMove = e => {
if (!dragOffset) return;
const maxLeft = window.innerWidth - formContainer.offsetWidth;
const maxTop = window.innerHeight - formContainer.offsetHeight;
formContainer.style.left = Math.min(Math.max(e.clientX - dragOffset.x, 0), Math.max(maxLeft, 0)) + 'px';
formContainer.style.top = Math.min(Math.max(e.clientY - dragOffset.y, 0), Math.max(maxTop, 0)) + 'px';
};
const onDragEnd = () => { dragOffset = null; };
header.addEventListener('mousedown', e => {
if (e.target.closest('#arbcom-modal-close')) return;
const rect = formContainer.getBoundingClientRect();
formContainer.style.transform = 'none';
formContainer.style.left = rect.left + 'px';
formContainer.style.top = rect.top + 'px';
dragOffset = { x: e.clientX - rect.left, y: e.clientY - rect.top };
e.preventDefault();
});
document.addEventListener('mousemove', onDragMove);
document.addEventListener('mouseup', onDragEnd);
const close = () => {
document.removeEventListener('mousemove', onDragMove);
document.removeEventListener('mouseup', onDragEnd);
overlay.remove();
formContainer.remove();
};
overlay.addEventListener('click', close);
formContainer.querySelector('#arbcom-modal-close').addEventListener('click', close);
return { formContainer };
}
function showMenu() {
const modules = isRequestsPage()
? [
['Request declined / withdrawn', 'Notify the parties of a request that was declined or withdrawn.', showDeclinedModule],
['Statement word-limit signals', "Add {{ACWordStatus}} under flagged statements; optional {{ArbComSize}} notices.", showStatementSignalsModule],
['Case opened', 'Notify parties and statement authors; creates the Update list.', showOpenedModule]
]
: [
['Add party during case', 'Notify a party added after the case opened.', showAddPartyModule],
['Evidence word-limit signals', 'Add {{ACWordStatus}}, record extensions, send over-length notices.', showEvidenceSignalsModule],
['Phase closing soon', 'Remind participants that the evidence or workshop phase is closing.', showPhaseClosingModule],
['Proposed decision posted', 'Notify affected editors and the Update list.', showProposedDecisionModule],
['Case update to the Update list', 'Send an update to everyone on the Update list.', showUpdateModule],
['Case closed / suspended', 'Post the WP:AC/N announcement and check ArbClerkBot cross-posts.', showClosingModule]
];
const { formContainer } = createModalContainer('ArbCom notifications', `
<div>${modules.map((m, i) => `
<button type="button" data-module="${i}" style="display: block; width: 100%; text-align: left; padding: 10px; margin-bottom: 8px; border: 1px solid #a2a9b1; background: #f8f9fa; border-radius: 4px; cursor: pointer;">
<strong>${escapeHtml(m[0])}</strong><br><span style="font-size: 0.85em; color: #555;">${escapeHtml(m[1])}</span>
</button>`).join('')}</div>`);
formContainer.querySelectorAll('[data-module]').forEach(btn => {
btn.addEventListener('click', () => modules[Number(btn.dataset.module)][2]());
});
}
// ---------- Shared notice engine ----------
//
// cfg: { title, intro, fields[], groups[], postLabel, expectedNamespaces, init(ctx),
// onChange(ctx, changedId), status(ctx), validate(ctx), buildJobs(ctx), afterPost(ctx, okJobs),
// actions[{ id, label, run(ctx) }] }
// field: { id, type: text|number|textarea|select|checkbox|checklist, label, hint, value, options, auto, hidden, height }
// group: { id, label, hint, optional, enabled, noPost, code(ctx) }
// job: { target, mode: 'append'|'new', sectiontitle, text, summary, group }
function fieldHtml(f) {
const attrs = `id="arb-f-${f.id}" data-fid="${f.id}"${f.auto ? ' data-auto="1"' : ''}`;
const hint = f.hint ? `<div style="font-size: 0.85em; color: #666; margin-bottom: 4px;">${f.hint}</div>` : '';
if (f.type === 'checkbox') {
return `<div id="arb-w-${f.id}" style="margin-bottom: 12px;${f.hidden ? ' display: none;' : ''}"><label style="display: flex; align-items: center; gap: 6px; cursor: pointer;"><input type="checkbox" ${attrs}${f.value ? ' checked' : ''}> ${f.label}</label>${hint}</div>`;
}
let control;
if (f.type === 'textarea') {
control = `<textarea ${attrs} dir="ltr" style="width: 100%; height: ${f.height || 100}px; padding: 5px;">${escapeHtml(f.value || '')}</textarea>`;
} else if (f.type === 'select') {
control = `<select ${attrs} style="width: 100%; padding: 5px;">${(f.options || []).map(o => `<option value="${escapeHtml(o.value)}">${escapeHtml(o.label)}</option>`).join('')}</select>`;
} else if (f.type === 'checklist') {
control = `<div ${attrs}></div>`;
} else {
control = `<input type="${f.type === 'number' ? 'number' : 'text'}" ${attrs} dir="ltr" value="${escapeHtml(f.value ?? '')}" style="width: ${f.type === 'number' ? '90px' : '100%'}; padding: 5px;">`;
}
const label = f.label ? `<label for="arb-f-${f.id}" style="display: block; margin-bottom: 2px; font-weight: bold;">${f.label}</label>` : '';
return `<div id="arb-w-${f.id}" style="margin-bottom: 12px;${f.hidden ? ' display: none;' : ''}">${label}${hint}${control}</div>`;
}
// Each recipient list gets one colour, used again in the preview so it is clear which notice
// goes to which list (parties vs. uninvolved editors vs. ...).
const GROUP_COLORS = ['#3366cc', '#b8860b', '#2e8b57', '#8a3fb5'];
const groupColor = index => (index >= 0 ? GROUP_COLORS[index % GROUP_COLORS.length] : '#666');
function groupHtml(g, index) {
const color = groupColor(index);
const enable = g.optional
? `<input type="checkbox" id="arb-ge-${g.id}"${g.enabled === false ? '' : ' checked'}> `
: '';
return `
<div style="margin-bottom: 15px; border-left: 6px solid ${color}; padding-left: 10px;">
<label for="arb-g-${g.id}" style="display: block; margin-bottom: 2px; font-weight: bold; color: ${color};">${enable}${g.label} <span id="arb-g-${g.id}-count" style="font-weight: normal; color: #666;"></span></label>
${g.hint ? `<div style="font-size: 0.85em; color: #666; margin-bottom: 4px;">${g.hint}</div>` : ''}
<textarea id="arb-g-${g.id}" dir="ltr" style="width: 100%; height: ${g.height || 90}px; white-space: pre; overflow-wrap: normal; overflow-x: auto;"></textarea>
<div id="arb-g-${g.id}-notes" style="font-size: 0.85em; color: #8a6d00; margin-top: 2px;"></div>
${g.code ? `<div style="margin-top: 4px;"><code id="arb-g-${g.id}-code" style="font-size: 0.85em;"></code> <button type="button" id="arb-g-${g.id}-copy" style="margin-left: 6px; padding: 1px 8px; font-size: 0.85em; cursor: pointer;">Copy code</button></div>` : ''}
</div>`;
}
function showNoticeModule(cfg) {
const buttonStyle = 'padding: 8px 16px; border: none; border-radius: 4px; cursor: pointer; margin-right: 4px;';
const { formContainer } = createModalContainer(cfg.title, `
<form id="arb-form">
${cfg.intro ? `<div style="font-size: 0.9em; color: #444; margin-bottom: 12px;">${cfg.intro}</div>` : ''}
<div id="arb-load-status"><p>Loading…</p></div>
${(cfg.fields || []).map(fieldHtml).join('')}
${(cfg.groups || []).map((g, i) => groupHtml(g, i)).join('')}
<div id="arb-status" style="margin-bottom: 12px;"></div>
<div id="arb-preview" style="display: none; margin-bottom: 15px; padding: 10px; border: 1px solid #ddd; background: #f9f9f9;"></div>
<button type="submit" id="arb-submit" style="${buttonStyle} background-color: #36c; color: white; font-weight: bold;">${cfg.postLabel || 'Post notifications'}</button>
<button type="button" id="arb-preview-btn" style="${buttonStyle} background-color: #ccc; color: #333;">Preview</button>
${(cfg.actions || []).map(a => `<button type="button" data-action="${a.id}" style="${buttonStyle} background-color: #f8f9fa; color: #333; border: 1px solid #a2a9b1;">${a.label}</button>`).join('')}
<div id="arb-results" style="margin-top: 20px; display: none;"></div>
</form>`);
const $ = sel => formContainer.querySelector(sel);
const form = $('#arb-form');
const ctx = {
modal: formContainer,
$,
val(id) {
const el = $('#arb-f-' + id);
if (!el) return '';
return el.type === 'checkbox' ? el.checked : el.value;
},
// Programmatic writes never mark a field as hand-edited; `force` also clears that mark.
set(id, value, force) {
const el = $('#arb-f-' + id);
if (!el) return;
if (!force && el.dataset.edited === '1') return;
if (force) delete el.dataset.edited;
if (el.type === 'checkbox') el.checked = !!value;
else el.value = value;
},
setOptions(id, options) {
const el = $('#arb-f-' + id);
if (el) el.innerHTML = options.map(o => `<option value="${escapeHtml(o.value)}">${escapeHtml(o.label)}</option>`).join('');
},
show(id, on) {
const w = $('#arb-w-' + id);
if (w) w.style.display = on ? '' : 'none';
},
checked(id) {
return [...formContainer.querySelectorAll(`#arb-f-${id} input[type=checkbox]:checked`)].map(i => i.dataset.item);
},
setChecklist(id, items) {
const el = $('#arb-f-' + id);
if (el) {
el.innerHTML = items.map(it => `<label style="display: block; margin-bottom: 3px; cursor: pointer;"><input type="checkbox" data-fid="${id}" data-item="${escapeHtml(it.id)}"${it.checked === false ? '' : ' checked'}> ${escapeHtml(it.label)}</label>`).join('');
}
},
targets(id) {
const el = $('#arb-g-' + id);
return el ? parseTargetList(el.value) : [];
},
enabled(id) {
const cb = $('#arb-ge-' + id);
return cb ? cb.checked : true;
},
setTargets(id, list, notesHtml) {
const el = $('#arb-g-' + id);
if (el) el.value = list.join('\n');
const notes = $(`#arb-g-${id}-notes`);
if (notes && notesHtml !== undefined) notes.innerHTML = notesHtml;
},
setStatus(html) { $('#arb-status').innerHTML = html; },
setLoad(html) { $('#arb-load-status').innerHTML = html; },
log(html) {
const r = $('#arb-results');
r.style.display = 'block';
const div = document.createElement('div');
div.style.marginBottom = '6px';
div.innerHTML = html;
r.appendChild(div);
},
resultsList() {
const r = $('#arb-results');
r.style.display = 'block';
let ul = r.querySelector('ul');
if (!ul) { ul = document.createElement('ul'); r.appendChild(ul); }
return ul;
},
refresh(changedId) {
(cfg.groups || []).forEach(g => {
const count = $(`#arb-g-${g.id}-count`);
if (count) count.textContent = `(${ctx.targets(g.id).length})`;
});
if (cfg.onChange) cfg.onChange(ctx, changedId);
(cfg.groups || []).forEach(g => {
if (g.code) $(`#arb-g-${g.id}-code`).textContent = g.code(ctx);
});
if (cfg.status) ctx.setStatus(cfg.status(ctx));
}
};
const onFieldEvent = e => {
const el = e.target;
if (el.dataset?.auto === '1' && e.isTrusted && e.type === 'input') el.dataset.edited = '1';
// 'group' = typing in a recipient list: modules must not re-fill lists on that.
ctx.refresh(el.dataset?.fid || 'group');
};
form.addEventListener('input', onFieldEvent);
form.addEventListener('change', onFieldEvent);
(cfg.groups || []).forEach(g => {
if (g.code) $(`#arb-g-${g.id}-copy`).addEventListener('click', e => copyToClipboard($(`#arb-g-${g.id}-code`).textContent, e.target));
});
const submitBtn = $('#arb-submit');
// Jobs for enabled groups; first job per target wins.
const collectJobs = async () => {
const raw = ((await cfg.buildJobs(ctx)) || []).filter(Boolean);
const seen = new Set();
const jobs = [];
const duplicates = [];
raw.forEach(j => {
const key = j.target.toLowerCase();
if (seen.has(key)) { duplicates.push(j.target); return; }
seen.add(key);
jobs.push(j);
});
return { jobs, duplicates };
};
$('#arb-preview-btn').addEventListener('click', async () => {
const previewDiv = $('#arb-preview');
previewDiv.style.display = 'block';
previewDiv.innerHTML = '<em>Loading preview…</em>';
try {
const problem = cfg.validate ? cfg.validate(ctx) : null;
if (problem) { previewDiv.innerHTML = `<p style="color: red;">${escapeHtml(problem)}</p>`; return; }
const { jobs } = await collectJobs();
if (!jobs.length) { previewDiv.innerHTML = '<p>Nothing to preview.</p>'; return; }
// Bucket the jobs by the recipient list they came from (same colours as the lists above).
const groups = cfg.groups || [];
const buckets = new Map();
jobs.forEach(j => {
const index = groups.findIndex(g => g.id === j.groupId);
const key = index >= 0 ? 'g' + index : 'x:' + j.group;
if (!buckets.has(key)) buckets.set(key, { index, label: index >= 0 ? groups[index].label : j.group, jobs: [] });
buckets.get(key).jobs.push(j);
});
const api = new mw.Api();
const plural = n => `${n} recipient${n === 1 ? '' : 's'}`;
let html = `<h3 style="margin-top: 0;">Preview</h3><div style="margin-bottom: 8px;"><strong>${jobs.length}</strong> page${jobs.length === 1 ? '' : 's'} will be posted to: ` +
[...buckets.values()].map(b => `<span style="color: ${groupColor(b.index)}; font-weight: bold;">${b.jobs.length} × ${escapeHtml(b.label)}</span>`).join(', ') + '</div>';
const skipped = groups.filter((g, i) => g.optional && !ctx.enabled(g.id) && ctx.targets(g.id).length);
if (skipped.length) {
html += `<div style="font-size: 0.85em; color: #666; margin-bottom: 8px;">Not sent (box unticked): ${skipped.map(g => `${escapeHtml(g.label)} (${ctx.targets(g.id).length})`).join('; ')}</div>`;
}
for (const bucket of buckets.values()) {
const first = bucket.jobs[0];
const color = groupColor(bucket.index);
const group = bucket.index >= 0 ? groups[bucket.index] : null;
const code = group && group.code ? group.code(ctx) : '';
const wikitext = first.mode === 'new' ? `== ${first.sectiontitle} ==\n\n${first.text}` : first.text;
// `title` makes BASEPAGENAME (used by the substituted templates) resolve to the real target, as on save.
const result = await api.post({
action: 'parse', text: wikitext, title: first.target, prop: 'text', pst: true,
contentmodel: 'wikitext', disablelimitreport: true, formatversion: 2
});
html += `<div class="arb-preview-block" style="border-left: 6px solid ${color}; margin: 12px 0; padding: 6px 10px; background: #fff;">
<div style="font-weight: bold; color: ${color};">${escapeHtml(bucket.label)} — ${plural(bucket.jobs.length)}</div>
${code ? `<div style="font-size: 0.85em;">Posts: <code>${escapeHtml(code)}</code></div>` : ''}
<div style="font-size: 0.85em; color: #444; max-height: 5.5em; overflow: auto; margin: 4px 0;">Sent to: ${bucket.jobs.map(j => escapeHtml(j.target)).join(' · ')}</div>
<div style="font-size: 0.85em; color: #666;">What <strong>${escapeHtml(first.target)}</strong> will see:</div>
<div style="border-top: 1px dashed #ccc; margin-top: 4px;">${result.parse.text}</div>
</div>`;
}
previewDiv.innerHTML = html;
} catch (error) {
previewDiv.innerHTML = `<p style="color: red;">Error loading preview: ${escapeHtml(getErrorMessage(error))}</p>`;
}
});
form.addEventListener('submit', async e => {
e.preventDefault();
const problem = cfg.validate ? cfg.validate(ctx) : null;
if (problem) { alert(problem); return; }
const { jobs, duplicates } = await collectJobs();
if (!jobs.length) { alert('There is nothing to post.'); return; }
const expected = cfg.expectedNamespaces || [3];
const offNamespace = jobs.filter(j => !expected.includes(getNamespaceId(j.target))).map(j => j.target);
if (offNamespace.length && !confirm(`These targets are not in the expected namespace:\n\n${offNamespace.join('\n')}\n\nContinue anyway?`)) return;
if (duplicates.length && !confirm(`These pages appear more than once and will only be posted to once (first occurrence):\n\n${[...new Set(duplicates)].join('\n')}\n\nContinue?`)) return;
const counts = new Map();
jobs.forEach(j => counts.set(j.group, (counts.get(j.group) || 0) + 1));
const summary = [...counts].map(([g, n]) => `${n} × ${g}`).join('\n');
if (!confirm(`Post to ${jobs.length} page${jobs.length === 1 ? '' : 's'}?\n\n${summary}`)) return;
submitBtn.disabled = true;
try {
const resultsDiv = $('#arb-results');
resultsDiv.style.display = 'block';
resultsDiv.innerHTML = '<h3>Posting Results</h3><ul></ul>';
const api = new mw.Api();
const okJobs = [];
for (const job of jobs) {
if (await postToPage(api, resultsDiv.querySelector('ul'), job)) okJobs.push(job);
}
if (cfg.afterPost) await cfg.afterPost(ctx, okJobs);
} catch (error) {
ctx.log(`<span style="color: red;">Error: ${escapeHtml(getErrorMessage(error))}</span>`);
} finally {
submitBtn.disabled = false;
}
});
(cfg.actions || []).forEach(a => {
const btn = $(`[data-action="${a.id}"]`);
btn.addEventListener('click', async () => {
btn.disabled = true;
try {
await a.run(ctx);
} catch (error) {
ctx.log(`<span style="color: red;">Error: ${escapeHtml(getErrorMessage(error))}</span>`);
} finally {
btn.disabled = false;
}
});
});
ctx.refresh('init');
Promise.resolve(cfg.init ? cfg.init(ctx) : null)
.then(() => { ctx.setLoad(''); ctx.refresh('init'); })
.catch(error => {
ctx.setLoad(`<p style="color: red;">Error: ${escapeHtml(getErrorMessage(error))}</p>`);
});
return ctx;
}
// mode 'append' adds to the end of a page (for templates that bring their own heading and
// signature); 'new' posts a new section. Returns true on success.
async function postToPage(api, resultsList, { target, mode, sectiontitle, text, summary }) {
const li = document.createElement('li');
li.style.cssText = 'display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-bottom: 10px; padding: 10px; border: 1px solid #ddd; border-radius: 4px;';
li.innerHTML = `<strong>${escapeHtml(target)}</strong>: <span class="status">Posting...</span>`;
resultsList.appendChild(li);
try {
const params = { action: 'edit', title: target, summary: `${summary} ${VIA}`, format: 'json' };
if (mode === 'new') {
params.section = 'new';
params.sectiontitle = sectiontitle;
params.text = text;
} else {
params.appendtext = text;
}
const result = await api.postWithEditToken(params);
if (result.edit?.result === 'Success') {
const diffUrl = `${mw.config.get('wgServer')}${mw.config.get('wgScript')}?title=${encodeURIComponent(target)}&diff=${result.edit.newrevid}&oldid=${result.edit.oldrevid}`;
li.querySelector('.status').innerHTML = `<span style="color: green; font-weight: bold;">Success</span> (<a href="${diffUrl}" target="_blank">View Diff</a>)`;
const copyButton = document.createElement('button');
copyButton.textContent = 'Copy Diff';
copyButton.style.cssText = 'padding: 2px 8px; font-size: 0.9em; cursor: pointer;';
copyButton.addEventListener('click', () => copyToClipboard(diffUrl, copyButton));
li.appendChild(copyButton);
return true;
}
throw (result.error || { message: 'Unknown API error' });
} catch (error) {
debugLog('Edit failed for ' + target, error);
li.querySelector('.status').innerHTML = `<span style="color: red; font-weight: bold;">Error:</span> ${escapeHtml(getErrorMessage(error))}`;
return false;
}
}
const requestOptions = requests => requests.map((r, i) => ({ value: String(i), label: r.title }));
// Report the outcome of an Update-list sync in the results area.
async function syncUpdateList(ctx, caseName, targets) {
if (!targets.length) return;
try {
const result = await ensureUpdateList(caseName, targets);
ctx.log(result.created
? `Created <strong>${escapeHtml(caseName)}/Update list</strong> with ${result.added.length} members.`
: result.added.length
? `Added ${result.added.length} member(s) to the Update list.`
: 'Update list already contained everyone.');
} catch (error) {
ctx.log(`<span style="color: red;">Could not update the Update list: ${escapeHtml(getErrorMessage(error))}</span>`);
}
}
// ---------- Module 1: request declined / withdrawn ----------
async function showDeclinedModule() {
let requests = [];
showNoticeModule({
title: 'ArbCom: Request Declined / Withdrawn',
intro: 'Notifies the parties of the chosen request with <code>' + SUBST + 'Arb declined}}</code>, which supplies its own heading and signature. The links use revision <strong>' + escapeHtml(mw.config.get('wgRevisionId')) + '</strong> (the one you are viewing — it should be the last revision still containing the request).',
fields: [
{ id: 'request', type: 'select', label: 'Request:', options: [] },
{ id: 'withdrawn', type: 'checkbox', label: 'Withdrawn by the filing party (instead of declined)' },
{ id: 'writtenout', type: 'checkbox', label: 'Fallback: post the template\'s wording written out, instead of substituting the template', hint: 'Only needed if the template misbehaves again; check Preview.' }
],
groups: [{ id: 'parties', label: 'Parties', hint: 'Named parties of the request.' }],
async init(ctx) {
requests = await loadRequests();
ctx.setOptions('request', requestOptions(requests));
ctx.setTargets('parties', requests[0].parties.map(toTalkTarget));
},
onChange(ctx, id) {
if (id === 'request' && requests[Number(ctx.val('request'))]) {
ctx.setTargets('parties', requests[Number(ctx.val('request'))].parties.map(toTalkTarget));
}
},
buildJobs(ctx) {
const req = requests[Number(ctx.val('request'))];
if (!req) return [];
const withdrawn = ctx.val('withdrawn');
const args = { oldid: mw.config.get('wgRevisionId'), name: req.title, withdrawn };
const text = '\n\n' + (ctx.val('writtenout') ? buildDeclinedNotice(args) : buildDeclinedTemplateCall(args));
return ctx.targets('parties').map(target => ({
target, mode: 'append', text, group: 'Parties', groupId: 'parties',
summary: `Notification: arbitration case request ${withdrawn ? 'withdrawn' : 'declined'}`
}));
}
});
}
// ---------- Module 2: statement word-limit signals ----------
async function showStatementSignalsModule() {
let requests = [];
let wordCounts = {};
const flaggedFor = req => {
const section = wordCounts.ARC?.[req.title] || {};
return Object.entries(section).filter(([, v]) => v.status === 'over' || v.status === 'within 10%');
};
showNoticeModule({
title: 'ArbCom: Statement Word-Limit Signals',
intro: "Counts come from ClerkBot (<code>User:ClerkBot/ArbCom word counts/data</code>, refreshed every 15 minutes); nothing is counted here. <strong>Insert status</strong> adds <code>{{ACWordStatus}}</code> under flagged statements on the live page. The optional group sends <code>{{ArbComSize}}</code> to editors who are over the limit.",
fields: [
{ id: 'request', type: 'select', label: 'Request:', options: [] },
{ id: 'allstatus', type: 'checkbox', label: 'Add the status box to every statement, not only flagged ones' }
],
groups: [{ id: 'size', label: 'Notify with {{ArbComSize}} (over the limit)', optional: true, enabled: false, hint: 'Editors ClerkBot marks "over".', code: ctx => buildSizeTemplate(requests[Number(ctx.val('request'))]?.title || '') }],
async init(ctx) {
[requests, wordCounts] = await Promise.all([loadRequests(), loadWordCounts()]);
ctx.setOptions('request', requestOptions(requests));
},
onChange(ctx, id) {
const req = requests[Number(ctx.val('request'))];
if (!req) return;
if (id === 'request' || id === 'init') {
const flagged = flaggedFor(req);
ctx.setTargets('size', flagged.filter(([, v]) => v.status === 'over').map(([u]) => toTalkTarget(u)),
flagged.map(([u, v]) => `${escapeHtml(u)}: ${v.words}/${v.limit} words (${escapeHtml(v.status)})`).join('<br>'));
}
},
status(ctx) {
const req = requests[Number(ctx.val('request'))];
if (!req) return '';
return flaggedFor(req).length ? '' : '<em>No flagged statements in ClerkBot\'s data for this request (it may not have been counted yet).</em>';
},
buildJobs(ctx) {
const req = requests[Number(ctx.val('request'))];
if (!req || !ctx.enabled('size')) return [];
return ctx.targets('size').map(target => ({
target, mode: 'new', group: 'ArbComSize', groupId: 'size',
sectiontitle: 'Please trim your statement at arbitration case requests',
text: buildSizeTemplate(req.title),
summary: 'Notification: statement length'
}));
},
actions: [{
id: 'insert', label: 'Insert status boxes',
async run(ctx) {
const req = requests[Number(ctx.val('request'))];
if (!req) return;
if (mw.config.get('wgRevisionId') !== mw.config.get('wgCurRevisionId')) {
ctx.log('<span style="color: red;">Open the current revision of the page first; status boxes can only be added to the live request.</span>');
return;
}
const targets = ctx.val('allstatus')
? req.statements.map(s => ({ user: headingToName(s.heading.replace(/^Statement\s+by\s+/i, '')), headingName: s.heading.replace(/^Statement\s+by\s+/i, '') }))
: flaggedFor(req).map(([user]) => ({ user }));
if (!targets.length) { ctx.log('Nothing to insert: no flagged statements.'); return; }
const page = await fetchWikitext(REQUESTS_PAGE);
let inserted = [];
const text = replaceRequestSection(page.text, req.title, body => {
const r = insertWordStatus(body, {
prefix: 'Statement by', targets,
makeLine: user => `{{ACWordStatus|page=ARC|section=${req.title}|user=${user}}}`
});
inserted = r.inserted;
return r.text;
});
if (text === null) { ctx.log('<span style="color: red;">Could not find that request on the live page.</span>'); return; }
if (!inserted.length) { ctx.log('Every flagged statement already has a status box (or its heading was not found).'); return; }
await new mw.Api().postWithEditToken({
action: 'edit', title: REQUESTS_PAGE, text, baserevid: page.revid,
summary: `Adding {{ACWordStatus}} to statements: ${inserted.join(', ')} ${VIA}`, format: 'json'
});
ctx.log(`Added status boxes for: ${escapeHtml(inserted.join(', '))}.`);
}
}]
});
}
// ---------- Module 3: case opened ----------
const OPENED_GROUPS = [
{ kind: 'party', id: 'parties', label: 'Parties', hint: 'Named parties in the request (standard wording).' },
{ kind: 'nonparty', id: 'nonparties', label: 'Uninvolved editors who made a statement', hint: 'Posted with party=no.' },
{ kind: 'arbadded', id: 'arbadded', label: 'Added as parties by the arbitrators after opening (optional)', hint: 'Posted with added-by-arbs-after-opening=yes. Starts empty — paste names if any.' }
];
async function showOpenedModule() {
let requests = [];
const days = ctx => (ctx.val('custom') ? Number(ctx.val('days')) || DEFAULT_DAYS : null);
const loadRequest = (ctx, index) => {
const req = requests[index];
ctx.set('casename', req.title, true);
ctx.setTargets('parties', req.parties.map(toTalkTarget), '');
const nonParties = buildNonParties(req.parties, req.statements);
const notes = nonParties
.filter(s => s.source === 'heading' || nameKey(s.username) !== nameKey(headingToName(s.heading.replace(/^Statement\s+by\s+/i, ''))))
.map(s => s.source === 'heading'
? `${escapeHtml(s.heading)} → ${escapeHtml(s.username)} (no signature found; taken from heading — check)`
: `${escapeHtml(s.heading)} → ${escapeHtml(s.username)} (from signature)`);
ctx.setTargets('nonparties', nonParties.map(s => toTalkTarget(s.username)), notes.join('<br>'));
ctx.setTargets('arbadded', [], '');
};
showNoticeModule({
title: 'ArbCom: Case Opened Notifications',
fields: [
{ id: 'request', type: 'select', label: 'Request:', options: [] },
{ id: 'casename', type: 'text', auto: true, label: `Case name (as in <code>${CASE_PAGE_PREFIX}…</code>):` },
{ id: 'custom', type: 'checkbox', label: 'Custom evidence timetable' },
{ id: 'days', type: 'number', value: DEFAULT_DAYS, label: 'Days for the evidence phase:' },
{ id: 'updatelist', type: 'checkbox', value: true, label: 'Create / update the case\'s <code>/Update list</code> with everyone notified' }
],
groups: OPENED_GROUPS.map(g => ({ ...g, code: ctx => buildNoticeTemplate({ caseName: ctx.val('casename').trim() || '(case name)', days: days(ctx), kind: g.kind }) })),
async init(ctx) {
requests = await loadRequests();
ctx.setOptions('request', requestOptions(requests));
loadRequest(ctx, 0);
},
onChange(ctx, id) {
ctx.show('days', !!ctx.val('custom'));
if (id === 'request' && requests[Number(ctx.val('request'))]) loadRequest(ctx, Number(ctx.val('request')));
},
validate: ctx => (ctx.val('casename').trim() ? null : 'Case name is required.'),
buildJobs(ctx) {
const caseName = ctx.val('casename').trim();
return OPENED_GROUPS.flatMap(g => ctx.targets(g.id).map(target => ({
target, mode: 'append', group: g.label, groupId: g.id,
// {{ArbComOpened}} supplies its own heading and signature, so it is appended.
text: '\n\n' + buildNoticeTemplate({ caseName, days: days(ctx), kind: g.kind }),
summary: `Notification: [[${CASE_PAGE_PREFIX}${caseName}|${caseName}]] arbitration case opened`
})));
},
async afterPost(ctx, okJobs) {
if (ctx.val('updatelist')) await syncUpdateList(ctx, ctx.val('casename').trim(), okJobs.map(j => j.target));
}
});
}
// ---------- Module 4: add party during case ----------
async function showAddPartyModule() {
const caseName = getCaseNameFromPage();
showNoticeModule({
title: 'ArbCom: Party Added During Case',
intro: 'Posts <code>' + SUBST + 'ArbComOpened|…|added-by-arbs-after-opening=yes}}</code>. The days value is the number of calendar days from today to the evidence deadline in the case\'s <code>/Data</code> page, so the template shows the same closing date as everyone else.',
fields: [
{ id: 'casename', type: 'text', value: caseName, label: 'Case name:' },
{ id: 'days', type: 'number', label: 'Days until the evidence phase closes:', hint: 'Blank = standard 14-day wording.' },
{ id: 'updatelist', type: 'checkbox', value: true, label: 'Add them to the case\'s <code>/Update list</code>' }
],
groups: [{ id: 'added', label: 'Editors added as parties', hint: 'Usernames or <code>User talk:</code> pages, one per line.', code: ctx => buildNoticeTemplate({ caseName: ctx.val('casename').trim(), days: Number(ctx.val('days')) || null, kind: 'arbadded' }) }],
async init(ctx) {
const info = await loadCaseData(caseName);
const left = daysUntilDate(info.data.dateEvidence, Date.now());
if (left !== null) ctx.set('days', Math.max(left, 1));
if (left !== null && left < 1) ctx.setStatus('<em>The evidence phase has already closed according to /Data.</em>');
},
validate: ctx => (ctx.val('casename').trim() ? (ctx.targets('added').length ? null : 'Enter at least one username.') : 'Case name is required.'),
buildJobs(ctx) {
const name = ctx.val('casename').trim();
return ctx.targets('added').map(raw => ({
target: toTalkTarget(raw), mode: 'append', group: 'Added as party', groupId: 'added',
text: '\n\n' + buildNoticeTemplate({ caseName: name, days: Number(ctx.val('days')) || null, kind: 'arbadded' }),
summary: `Notification: added as a party to the [[${CASE_PAGE_PREFIX}${name}|${name}]] arbitration case`
}));
},
async afterPost(ctx, okJobs) {
if (ctx.val('updatelist')) await syncUpdateList(ctx, ctx.val('casename').trim(), okJobs.map(j => j.target));
}
});
}
// ---------- Module 5: evidence word-limit signals ----------
async function showEvidenceSignalsModule() {
const caseName = getCaseNameFromPage();
let evidence = {};
let parties = [];
const flagged = () => Object.entries(evidence).filter(([, v]) => v.status === 'over' || v.status === 'within 10%');
const isParty = user => parties.some(p => nameKey(p) === nameKey(user));
const noteFor = ([u, v]) => `${escapeHtml(u)}: ${v.words}/${v.limit} words (${escapeHtml(v.status)})`;
const evidenceTitle = `${CASE_PAGE_PREFIX}${caseName}/Evidence`;
showNoticeModule({
title: 'ArbCom: Evidence Word-Limit Signals',
intro: `Counts come from ClerkBot (<code>Case pages → ${escapeHtml(caseName)}/Evidence</code>); nothing is counted here. Over-limit notices: <code>{{Evidence too long}}</code> for parties (its limit is 1000 words); the Procedures page wording for non-parties (500 words / 50 diffs).`,
fields: [
{ id: 'heading', type: 'text', auto: true, value: `[[${evidenceTitle}]]`, label: 'Section heading for over-limit notices:' },
{ id: 'allstatus', type: 'checkbox', label: 'Add the status box to every evidence section, not only flagged ones' },
{ id: 'extuser', type: 'text', label: 'Record an extension for (username):', hint: 'Fill in both boxes, then press "Record extension".' },
{ id: 'extwords', type: 'number', label: 'Approved word limit:' }
],
groups: [
{ id: 'parties', label: 'Parties over the limit', optional: true, hint: '<code>' + SUBST + 'Evidence too long}}</code>. For anyone ClerkBot has no count for, add the word count after a bar, e.g. <code>User talk:Name | 1250</code>.' },
{ id: 'nonparties', label: 'Non-parties over the limit', optional: true, hint: 'Procedures wording, 500 words / 50 diffs. Add a count after a bar for anyone ClerkBot has not counted, e.g. <code>User talk:Name | 700</code>.' }
],
async init(ctx) {
const [wc, info] = await Promise.all([loadWordCounts(), loadCaseData(caseName)]);
evidence = {};
Object.entries(wc['Case pages']?.[`${caseName}/Evidence`] || {}).forEach(([u, v]) => { evidence[u.replace(/[{}]/g, '')] = v; });
parties = info.parties;
const over = Object.entries(evidence).filter(([, v]) => v.status === 'over');
ctx.setTargets('parties', over.filter(([u]) => isParty(u)).map(([u]) => toTalkTarget(u)), over.filter(([u]) => isParty(u)).map(noteFor).join('<br>'));
ctx.setTargets('nonparties', over.filter(([u]) => !isParty(u)).map(([u]) => toTalkTarget(u)), over.filter(([u]) => !isParty(u)).map(noteFor).join('<br>'));
if (!Object.keys(evidence).length) ctx.setStatus('<em>ClerkBot has no data for this case\'s Evidence page yet.</em>');
},
// The notices state a word count, so every recipient needs a real one: ClerkBot's, or one
// typed after a bar ("User talk:Name | 1250"). A placeholder is never posted.
validate(ctx) {
const missing = [];
['parties', 'nonparties'].forEach(id => {
if (!ctx.enabled(id)) return;
ctx.targets(id).forEach(line => {
const { target, count } = splitTargetCount(line);
if (count === null && !evidence[getTargetBaseName(target)]?.words) missing.push(target);
});
});
return missing.length
? `No word count for: ${missing.join(', ')}.\n\nClerkBot has no count for them (it may not be counting this case's Evidence page yet). Add the count after a bar on the same line, e.g. "User talk:Name | 1250".`
: null;
},
buildJobs(ctx) {
const heading = ctx.val('heading').trim();
const make = (id, kind, label) => ctx.enabled(id) ? ctx.targets(id).map(line => {
const { target, count } = splitTargetCount(line);
const words = count !== null ? count : evidence[getTargetBaseName(target)].words;
return {
target, mode: 'new', sectiontitle: heading, group: label, groupId: id,
text: buildEvidenceNotice({ kind, words }),
summary: 'Notification: evidence length'
};
}) : [];
return [...make('parties', 'party', 'Parties over the limit'), ...make('nonparties', 'nonparty', 'Non-parties over the limit')];
},
actions: [
{
id: 'insert', label: 'Insert status boxes',
async run(ctx) {
const targets = ctx.val('allstatus') ? Object.keys(evidence).map(user => ({ user })) : flagged().map(([user]) => ({ user }));
if (!targets.length) { ctx.log('Nothing to insert: no flagged evidence sections.'); return; }
const page = await fetchWikitext(evidenceTitle);
if (!page) { ctx.log('<span style="color: red;">Evidence page not found.</span>'); return; }
const r = insertWordStatus(page.text, {
prefix: 'Evidence presented by', targets,
makeLine: user => `{{ACWordStatus|page=Case pages|section=${caseName}/Evidence|user=${user}}}`
});
if (!r.inserted.length) { ctx.log('Every flagged section already has a status box (or its heading was not found).'); return; }
await new mw.Api().postWithEditToken({
action: 'edit', title: evidenceTitle, text: r.text, baserevid: page.revid,
summary: `Adding {{ACWordStatus}}: ${r.inserted.join(', ')} ${VIA}`, format: 'json'
});
ctx.log(`Added status boxes for: ${escapeHtml(r.inserted.join(', '))}.`);
}
},
{
id: 'extension', label: 'Record extension',
async run(ctx) {
const user = ctx.val('extuser').trim();
const words = Number(ctx.val('extwords'));
if (!user || !words) { ctx.log('<span style="color: red;">Enter a username and an approved word limit.</span>'); return; }
const page = await fetchWikitext(evidenceTitle);
if (!page) { ctx.log('<span style="color: red;">Evidence page not found.</span>'); return; }
const r = recordExtension(page.text, { prefix: 'Evidence presented by', user, words });
if (!r.done) { ctx.log(`<span style="color: red;">No "Evidence presented by ${escapeHtml(user)}" heading found.</span>`); return; }
if (r.already) { ctx.log(`${escapeHtml(user)} already has a ${words}-word approved limit recorded; nothing to do.`); return; }
await new mw.Api().postWithEditToken({
action: 'edit', title: evidenceTitle, text: r.text, baserevid: page.revid,
summary: `Recording approved word limit (${words}) for ${user} ${VIA}`, format: 'json'
});
ctx.log(`Recorded a ${words}-word limit for ${escapeHtml(user)}.`);
}
}
]
});
}
// ---------- Module 6: phase closing soon ----------
async function showPhaseClosingModule() {
const caseName = getCaseNameFromPage();
let data = {};
const apply = ctx => {
const phase = ctx.val('phase');
const deadline = ctx.val('deadline').trim();
const built = buildPhaseClosing({ phase, deadline });
ctx.set('heading', built.heading);
ctx.set('message', built.text);
ctx.setTargets('page', [`Wikipedia talk:${CASE_PAGE_PREFIX.replace(/^Wikipedia:/, '')}${caseName}/${phase}`]);
};
showNoticeModule({
title: 'ArbCom: Phase Closing Soon',
intro: 'Posts a reminder on the phase\'s talk page about 24 hours before it closes. Wording follows past reminders on real cases (editable).',
fields: [
{ id: 'phase', type: 'select', label: 'Phase:', options: [{ value: 'Evidence', label: 'Evidence' }, { value: 'Workshop', label: 'Workshop' }] },
{ id: 'deadline', type: 'text', auto: true, label: 'Deadline (from the case\'s /Data):' },
{ id: 'heading', type: 'text', auto: true, label: 'Section heading:' },
{ id: 'message', type: 'textarea', auto: true, height: 90, label: 'Message:' }
],
groups: [{ id: 'page', label: 'Talk page to post on', height: 40 }],
async init(ctx) {
data = (await loadCaseData(caseName)).data;
ctx.set('deadline', formatDeadline(data.dateEvidence));
apply(ctx);
},
onChange(ctx, id) {
if (id === 'phase') {
const date = ctx.val('phase') === 'Workshop' ? data.dateWorkshop : data.dateEvidence;
ctx.set('deadline', formatDeadline(date), true);
apply(ctx);
} else if (id === 'deadline') {
apply(ctx);
}
if (ctx.val('phase') === 'Workshop' && data.workshopSkipped) {
ctx.setStatus('<em>/Data says the workshop was skipped for this case.</em>');
}
},
expectedNamespaces: [5],
validate: ctx => (ctx.val('deadline').trim() && ctx.val('message').trim() ? null : 'Deadline and message are required.'),
buildJobs: ctx => ctx.targets('page').map(target => ({
target, mode: 'new', sectiontitle: ctx.val('heading').trim(), text: ctx.val('message').trim(),
group: 'Talk page', groupId: 'page', summary: `${ctx.val('phase')} phase closing soon`
}))
});
}
// ---------- Module 7: proposed decision posted ----------
async function showProposedDecisionModule() {
const caseName = getCaseNameFromPage();
let others = [];
showNoticeModule({
title: 'ArbCom: Proposed Decision Posted',
intro: 'Affected editors get <code>{{ArbComPD}}</code>. Everyone else on the case\'s Update list gets the wording of past "Proposed decision … posted" messages (optional).',
fields: [
{ id: 'casename', type: 'text', value: caseName, label: 'Case name:' },
{ id: 'custom', type: 'textarea', height: 60, label: 'Custom message for {{ArbComPD}} (optional, appended to the standard text):', hint: 'As in the template documentation, e.g. "Specifically, an arbitrator has proposed that [[…#section|you be topic-banned]]".' },
{ id: 'memberheading', type: 'text', auto: true, label: 'Heading for the Update-list message:' }
],
groups: [
{ id: 'affected', label: 'Affected editors ({{ArbComPD}})', hint: 'Parties and update-list members named in the proposed findings/remedies; edit freely.', code: ctx => buildPdTemplate({ caseName: ctx.val('casename').trim(), custom: ctx.val('custom') }) },
{ id: 'others', label: 'Other Update-list members', optional: true, hint: 'Update-list members not named above.' }
],
async init(ctx) {
const info = await loadCaseData(caseName);
const pd = await fetchWikitext(`${CASE_PAGE_PREFIX}${caseName}/Proposed decision`);
// The PD page's sections are "Proposed findings of fact" / "Proposed remedies".
const items = pd
? ['Proposed findings of fact', 'Proposed remedies', 'Findings of fact', 'Remedies'].flatMap(name => parseDecisionItems(pd.text, name))
: [];
const known = [...new Set([...info.parties, ...info.updateList.targets.map(getTargetBaseName)])];
const mentioned = findMentionedUsers(items, known);
// Arbitrators and clerks named in proposals are not "affected editors".
const staff = await loadStaffKeys();
const affected = withoutStaff(Object.keys(mentioned), staff);
const skipped = Object.keys(mentioned).length - affected.length;
const affectedKeys = new Set(affected.map(nameKey));
others = info.updateList.targets.filter(t => !affectedKeys.has(nameKey(getTargetBaseName(t))));
ctx.setTargets('affected', affected.map(toTalkTarget), affected.map(n => `${escapeHtml(n)}: ${mentioned[n].map(escapeHtml).join('; ')}`).join('<br>'));
ctx.setTargets('others', others);
ctx.set('memberheading', buildPdMemberMessage(caseName).heading);
const notes = [];
if (!pd) notes.push('No Proposed decision page found for this case.');
if (!info.updateList.exists) notes.push('This case has no /Update list.');
if (skipped) notes.push(`${skipped} arbitrator(s)/clerk(s) named in the proposals were left out (per ArbClerkBot's authorized-users list).`);
if (notes.length) ctx.setStatus(`<em>${notes.map(escapeHtml).join('<br>')}</em>`);
},
validate: ctx => (ctx.val('casename').trim() ? null : 'Case name is required.'),
buildJobs(ctx) {
const name = ctx.val('casename').trim();
const jobs = ctx.targets('affected').map(target => ({
target, mode: 'new', sectiontitle: 'Proposed decision relating to you', group: 'Affected editors', groupId: 'affected',
text: buildPdTemplate({ caseName: name, custom: ctx.val('custom') }),
summary: `Notification: proposed decision in the [[${CASE_PAGE_PREFIX}${name}|${name}]] arbitration case`
}));
if (ctx.enabled('others')) {
const member = buildPdMemberMessage(name);
ctx.targets('others').forEach(target => jobs.push({
target, mode: 'new', sectiontitle: ctx.val('memberheading').trim() || member.heading, group: 'Update-list members', groupId: 'others',
text: member.text, summary: `Proposed decision in the ${name} arbitration case posted`
}));
}
return jobs;
}
});
}
// ---------- Module 8: case update to the Update list ----------
async function showUpdateModule() {
const caseName = getCaseNameFromPage();
showNoticeModule({
title: 'ArbCom: Case Update to the Update List',
intro: 'Sends a message to everyone on the case\'s Update list, in the wording of past case updates: a standard first sentence, your text, and the signature.',
fields: [
{ id: 'casename', type: 'text', value: caseName, label: 'Case name:' },
{ id: 'heading', type: 'text', auto: true, value: buildUpdateHeading(caseName), label: 'Section heading:' },
{ id: 'free', type: 'textarea', height: 120, label: 'Your message:' }
],
groups: [{ id: 'members', label: 'Update-list members', hint: 'Loaded from the case\'s /Update list; edit freely.' }],
async init(ctx) {
const list = await loadUpdateList(caseName);
ctx.setTargets('members', list.targets);
if (!list.exists) ctx.setStatus('<em>This case has no /Update list.</em>');
},
onChange(ctx, id) {
if (id === 'casename') ctx.set('heading', buildUpdateHeading(ctx.val('casename').trim()));
},
validate: ctx => (ctx.val('free').trim() ? null : 'Write a message first.'),
buildJobs(ctx) {
const name = ctx.val('casename').trim();
const text = `${buildUpdateIntro(name)} ${ctx.val('free').trim()} For the Arbitration Committee, ${WIKI_SIGNATURE}`;
return ctx.targets('members').map(target => ({
target, mode: 'new', sectiontitle: ctx.val('heading').trim(), text, group: 'Update-list members', groupId: 'members',
summary: `${name} arbitration case update`
}));
}
});
}
// ---------- Module 9: case closed / suspended ----------
async function showClosingModule() {
const caseName = getCaseNameFromPage();
let remedies = [];
let missing = [];
let savedSection = '';
let warnings = '';
const build = ctx => {
const recipients = ctx.targets('recipients').map(getTargetBaseName);
const linkUsers = ctx.val('link');
if (ctx.val('kind') === 'suspended') {
return buildMotionAnnouncement({
caseName: ctx.val('casename').trim(), permalink: ctx.val('permalink').trim(),
motionText: ctx.val('motion').trim(), recipients, linkUsers
});
}
const chosen = ctx.checked('remedies').map(i => remedies[Number(i)].text);
return buildClosing({ caseName: ctx.val('casename').trim(), remedies: chosen, recipients, linkUsers });
};
const apply = ctx => {
const built = build(ctx);
ctx.set('heading', built.heading);
ctx.set('body', built.body);
};
showNoticeModule({
title: 'ArbCom: Case Closed / Suspended',
intro: 'Posts the announcement to WP:AC/N; ArbClerkBot then cross-posts it to every user linked in it. Recipients are linked with <code>{{user}}</code> (first mention) or listed in <code>{{bcc}}</code>. Afterwards, <strong>Check bot cross-posts</strong> finds anyone it missed.',
postLabel: 'Post to WP:AC/N',
expectedNamespaces: [4],
fields: [
{ id: 'kind', type: 'select', label: 'Announcement:', options: [{ value: 'closed', label: 'Case closed' }, { value: 'suspended', label: 'Case suspended (motion)' }] },
{ id: 'casename', type: 'text', value: caseName, label: 'Case name:' },
{ id: 'remedies', type: 'checklist', label: 'Remedies enacted (passed items, copied verbatim):' },
{ id: 'permalink', type: 'text', hidden: true, label: 'Motion permalink (e.g. <code>Special:Permalink/123456#Motion</code>):' },
{ id: 'motion', type: 'textarea', hidden: true, height: 80, label: 'Motion text:' },
{ id: 'link', type: 'checkbox', value: true, label: 'Link recipients with {{user}} (otherwise all go in {{bcc}})' },
{ id: 'heading', type: 'text', auto: true, label: 'Section heading:' },
{ id: 'body', type: 'textarea', auto: true, height: 200, label: 'Announcement:' }
],
groups: [{ id: 'recipients', label: 'Recipients (ArbClerkBot delivers to those linked)', noPost: true, hint: 'Parties and users named in passed findings and remedies; add any others.' }],
async init(ctx) {
const info = await loadCaseData(caseName);
const findings = parseDecisionItems(info.mainText, 'Findings of fact').filter(i => i.passed);
remedies = parseDecisionItems(info.mainText, 'Remedies').filter(i => i.passed);
ctx.setChecklist('remedies', remedies.map((r, i) => ({ id: String(i), label: r.heading })));
const mentioned = findMentionedUsers([...findings, ...remedies], info.parties);
// Parties are always kept; other named users are checked against the live arbitrator/clerk list.
const staff = await loadStaffKeys();
const names = [...new Set([...info.parties, ...withoutStaff(Object.keys(mentioned), staff)])];
ctx.setTargets('recipients', names.map(toTalkTarget));
if (!hasCaseClosedStamp(info.mainText)) warnings += '<div><em>The case page has no "Case closed on" stamp yet (step 6 of the closing procedure).</em></div>';
if (!remedies.length) warnings += '<div><em>No passed remedies found on the case page yet.</em></div>';
apply(ctx);
},
onChange(ctx, id) {
const suspended = ctx.val('kind') === 'suspended';
ctx.show('remedies', !suspended);
ctx.show('permalink', suspended);
ctx.show('motion', suspended);
if (id !== 'heading' && id !== 'body') apply(ctx);
},
status(ctx) {
const body = ctx.val('body');
if (!body) return warnings;
const lines = ctx.targets('recipients').map(t => {
const name = getTargetBaseName(t);
return botWillReach(body, name)
? `<span style="color: #080;">✓ ${escapeHtml(name)}</span>`
: `<span style="color: #c00;">✗ ${escapeHtml(name)} (not linked — will need a manual post)</span>`;
});
return `${warnings}<div style="font-size: 0.85em;">${lines.join(' ')}</div>`;
},
validate: ctx => (ctx.val('heading').trim() && ctx.val('body').trim() ? null : 'Heading and announcement are required.'),
buildJobs: ctx => [{
target: ACN_PAGE, mode: 'new', sectiontitle: ctx.val('heading').trim(), text: ctx.val('body').trim(),
group: 'WP:AC/N announcement', summary: ctx.val('kind') === 'suspended' ? 'Case suspended' : 'Case closed'
}],
afterPost(ctx) {
ctx.log('Posted. ArbClerkBot normally acts within about 5 minutes — then press <strong>Check bot cross-posts</strong>.');
},
actions: [
{
id: 'check', label: 'Check bot cross-posts',
async run(ctx) {
const heading = ctx.val('heading').trim();
const acn = await fetchWikitext(ACN_PAGE);
const section = acn ? extractSection(acn.text, heading) : null;
if (section === null) { ctx.log('That section is not on WP:AC/N yet — has it been posted?'); return; }
if (!/Discuss this at/i.test(section)) { ctx.log('ArbClerkBot has not added its "Discuss this" link yet (it runs about every 5 minutes). Try again shortly.'); return; }
savedSection = section;
const titles = ctx.targets('recipients');
const contents = await fetchManyContents(titles);
missing = titles.filter(t => {
const text = contents.get(t.toLowerCase());
return !text || extractSection(text, heading) === null;
});
const delivered = titles.length - missing.length;
ctx.log(`<strong>${delivered}</strong> of ${titles.length} recipients already have the announcement.` +
(missing.length ? `<br>Missing: ${missing.map(escapeHtml).join(', ')}` : ' Nothing left to cross-post.'));
}
},
{
id: 'crosspost', label: 'Cross-post to missing',
async run(ctx) {
if (!missing.length || !savedSection) { ctx.log('Run <strong>Check bot cross-posts</strong> first (nothing is missing yet).'); return; }
if (!confirm(`Cross-post the saved ACN announcement to ${missing.length} user talk page(s)?\n\n${missing.join('\n')}`)) return;
const heading = ctx.val('heading').trim();
const api = new mw.Api();
const ul = ctx.resultsList();
const stillMissing = [];
for (const target of missing) {
const ok = await postToPage(api, ul, {
target, mode: 'new', sectiontitle: heading, text: savedSection,
summary: 'Cross-posting arbitration announcement'
});
if (!ok) stillMissing.push(target);
}
missing = stillMissing;
}
}
]
});
}
mw.loader.using(['mediawiki.api', 'mediawiki.util']).then(init);
})();