User:David Xuang/scripts/translit.js
外观
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
(function () {
'use strict';
const letter = String.raw`(?!\u02BC)\p{L}\p{M}*`;
const part = `(?:(?:${letter}\\.)+|(?:${letter})+|(?:St|Ste|Mt|Ft|Sr|Jr)\\.)`;
const join = String.raw`['’\u02BC\u00B7\u30FB\u2010\u2011-]`;
const word = `${part}(?:${join}${part})*`;
const nameRE = new RegExp(`^${word}(?: +${word})*(?![\\s\\S])`, 'u');
const hanRE = /\p{Script=Han}/u;
const wikiStructure = /[{}\[\]<>\n\r\u2028\u2029]|'{2}|-\||\|-/u;
const safeTranslation = (value) => Boolean(value) && !wikiStructure.test(value) && !/[|=]/u.test(value);
const normalize = (value) => value.normalize('NFC');
class TranslationError extends Error {
constructor(hans, hant = hans) {
super(hans);
this.hant = hant;
}
}
function parseSelection(selection) {
const text = selection.trim();
if (!text) {
throw new TranslationError(
'请先选中要翻译的人名、地名或跨语言模板。',
'請先選取要翻譯的人名、地名或跨語言模板。',
);
}
const offset = selection.indexOf(text);
let original = text;
let template;
if (text.startsWith('{{') && text.endsWith('}}')) {
const body = text.slice(2, -2);
if (wikiStructure.test(body)) {
throw new TranslationError('请选择一个结构简单的跨语言模板。', '請選取一個結構簡單的跨語言模板。');
}
const [templateName, ...fields] = body.split('|');
const kind = templateName.trim().toLowerCase();
const tsl = kind === 'tsl';
if (!tsl && !/^link-[a-z]{2,3}(?:-[a-z0-9]+)*$/.test(kind)) {
throw new TranslationError('请选择纯名称、{{tsl}} 或 {{link-xx}}。', '請選取純名稱、{{tsl}} 或 {{link-xx}}。');
}
const positions = new Map();
let next = 1;
fields.forEach((field, index) => {
const equals = field.indexOf('=');
const key = equals < 0 ? next++ : field.slice(0, equals).trim();
if (typeof key === 'string' && !/^[1-9]\d*$/.test(key)) return;
const number = Number(key);
if (positions.has(number) || (number > (tsl ? 4 : 3) && equals < 0)) {
throw new TranslationError('模板的位置参数重复或超出支持范围。', '模板的位置參數重複或超出支援範圍。');
}
positions.set(number, { index, equals, value: field.slice(equals + 1).trim() });
});
const foreign = positions.get(2);
const language = tsl ? positions.get(1)?.value : kind.slice(5);
if (!foreign?.value || !/^[a-z]{2,3}(?:-[a-z0-9]+)*$/i.test(language || '')) {
throw new TranslationError('模板需要有效的语言代码和外语条目名。', '模板需要有效的語言代碼和外語條目名。');
}
original = foreign.value;
template = {
templateName,
fields,
positions,
next,
titleNumber: tsl ? 3 : 1,
display: positions.get(tsl ? 4 : 3),
};
}
// Keep an article's disambiguator in the link target. Query only the name.
const base = template ? original.replace(/ +\([^()]+\)$/u, '') : original;
const query = normalize(base).replace(/ +/g, ' ');
if (hanRE.test(original)) throw new TranslationError('外语名称不能含有汉字。', '外語名稱不能含有漢字。');
if (!nameRE.test(query)) throw new TranslationError('名称的格式不受支持。', '不支援此名稱格式。');
return {
original,
query,
template,
leading: selection.slice(0, offset),
trailing: selection.slice(offset + text.length),
};
}
function renderSelection(input, translation) {
if (!safeTranslation(translation)) throw new TranslationError('请输入有效的译文。', '請輸入有效的譯文。');
let result;
if (!input.template) {
result = `${translation}({{lang|en|${input.original}}})`;
} else {
const { templateName, fields, positions, next, titleNumber, display } = input.template;
const updated = fields.slice();
const title = positions.get(titleNumber);
if (title) {
const prefix = updated[title.index].slice(0, title.equals + 1);
const old = updated[title.index].slice(title.equals + 1);
const leading = old.match(/^\s*/u)[0];
const trailing = old.slice(leading.length).match(/\s*$/u)[0];
updated[title.index] = `${prefix}${leading}${translation}${trailing}`;
} else {
updated.push(next === titleNumber ? translation : `${titleNumber}=${translation}`);
}
if (display && normalize(display.value) === normalize(input.original)) updated.splice(display.index, 1);
result = `{{${[templateName, ...updated].join('|')}}}`;
}
return input.leading + result + input.trailing;
}
function matchesName(original, query, kind) {
const normalized = normalize(original);
if (normalized === query) return true;
// In the personal-name dictionary, a comma can introduce the given name.
const inverted = kind === 'XA' && /^([^,,]+)[,,]\s?([^,,]+)$/u.exec(normalized);
return Boolean(inverted && `${inverted[2]} ${inverted[1]}` === query);
}
function candidates(data, query, whole) {
if (!Array.isArray(data?.result)) {
throw new TranslationError('字统网返回了无法识别的数据。', '字統網傳回了無法辨識的資料。');
}
const seen = new Set();
const options = [];
for (const pair of data.result) {
if (!Array.isArray(pair) || !Array.isArray(pair[0])) continue;
const [[original, location, entry, kind, id], rank] = pair;
if (kind !== 'YC' && kind !== (whole ? 'XA' : 'YA')) continue;
if (typeof original !== 'string' || typeof entry !== 'string') continue;
const exact = matchesName(original, query, kind);
if (whole && !exact) continue;
const region = location || (kind === 'XA' ? entry.match(/〈([^〉]+)〉/u)?.[1] : '') || '';
// The name dictionaries append notes in parentheses, after a comma, or after 〈地域〉.
const entries = kind === 'YA' ? entry.split(/[;;](?![^()()]*[))])/u) : [entry];
const translations = kind === 'YC' ? entries : entries.map((value) => value.split(/[〈((,,。]/u, 1)[0]);
for (const value of translations) {
const translation = value.trim();
if (!safeTranslation(translation)) continue;
const key = JSON.stringify([kind, id ?? original, translation, region]);
if (seen.has(key)) continue;
seen.add(key);
options.push({ original, translation, region, kind, exact, apiExact: rank === 'exact' });
}
}
return options.sort(
(a, b) =>
Number(b.apiExact) - Number(a.apiExact) ||
Number(a.kind === 'YC') - Number(b.kind === 'YC') ||
Number(b.exact) - Number(a.exact),
);
}
function makeStep(query, options) {
const matches = options.filter((option) => option.exact);
return { query, options, automatic: matches.length === 1 ? matches[0].translation : null };
}
async function findSteps(query, search) {
const words = query.split(' ');
if (words.length > 1) {
const options = candidates(await search(query), query, true);
if (options.length) return [makeStep(query, options)];
}
const lookups = new Map();
for (const word of words) {
if (!lookups.has(word)) lookups.set(word, search(word));
}
return Promise.all(words.map(async (word) => makeStep(word, candidates(await lookups.get(word), word, false))));
}
async function search(query) {
const controller = new AbortController();
const timeout = setTimeout(() => controller.abort(), 15000);
try {
const response = await fetch(`https://zi.tools/api/transliteration/search/${encodeURIComponent(query)}`, {
credentials: 'omit',
signal: controller.signal,
});
if (!response.ok) {
throw new TranslationError(
`字统网查询失败(HTTP ${response.status})。`,
`字統網查詢失敗(HTTP ${response.status})。`,
);
}
return await response.json();
} catch (error) {
if (error.name === 'AbortError')
throw new TranslationError('字统网查询超时,请重试。', '字統網查詢逾時,請再試一次。');
if (error instanceof TypeError)
throw new TranslationError('无法连接字统网,请重试。', '無法連線到字統網,請再試一次。');
throw error;
} finally {
clearTimeout(timeout);
}
}
if (typeof module === 'object' && module.exports) {
module.exports = { parseSelection, renderSelection, candidates, findSteps };
return;
}
if (window.nameTranslatorLoaded || mw.config.get('wgPageContentModel') !== 'wikitext') return;
window.nameTranslatorLoaded = true;
mw.loader
.using(['mediawiki.util', 'oojs-ui-widgets', 'oojs-ui-windows', 'ext.gadget.HanAssist', 'ext.gadget.EditorAPIs'])
.then((require) => {
const { conv } = require('ext.gadget.HanAssist');
const t = (hans, hant = hans) => conv({ hans, hant });
const title = t('翻译人名地名', '翻譯人名地名');
const customLabel = t('自订译文', '自訂譯文');
const toolClass = 'name-translator-tool';
const fallbackToolbars = new WeakMap();
let busy = false;
let epoch = 0;
let manager;
let dialog;
mw.util.addCSS(`
.name-translator-tool { margin-inline: .5em; }
.name-translator-choice-area { max-height: min(52vh, 30em); overflow: auto; }
.name-translator-row {
display: grid; grid-template-columns: auto minmax(0,4fr) minmax(0,4fr) minmax(0,2fr);
align-items: start; gap: .55em; box-sizing: border-box;
padding: .5em .35em; border-bottom: 1px solid var(--border-color-subtle, #dadde3);
cursor: pointer;
}
.name-translator-row input { margin-top: .25em; }
.name-translator-row span { overflow-wrap: anywhere; min-width: 0; }
.name-translator-custom {
display: flex; align-items: center; gap: .55em; padding: .55em .35em;
position: sticky; bottom: 0; z-index: 1;
background: var(--background-color-base, #fff);
border-top: 1px solid var(--border-color-subtle, #dadde3);
}
.name-translator-custom .oo-ui-inputWidget { flex: 1; min-width: 0; max-width: none; }
`);
function ChoiceDialog(config) {
ChoiceDialog.super.call(this, config);
}
OO.inheritClass(ChoiceDialog, OO.ui.ProcessDialog);
ChoiceDialog.static.name = 'nameTranslatorChoices';
ChoiceDialog.static.title = title;
ChoiceDialog.static.actions = [
{ action: 'exit', label: t('退出'), flags: 'safe', modes: ['single', 'first'] },
{ action: 'back', label: t('上一步'), flags: 'safe', modes: ['middle', 'last'] },
{ action: 'next', label: t('下一步'), flags: ['primary', 'progressive'], modes: ['first', 'middle'] },
{ action: 'apply', label: t('确认', '確認'), flags: ['primary', 'progressive'], modes: ['single', 'last'] },
];
ChoiceDialog.prototype.initialize = function () {
ChoiceDialog.super.prototype.initialize.call(this);
this.panel = new OO.ui.PanelLayout({ padded: true, expanded: false });
this.prompt = $('<p>');
this.area = $('<div>').addClass('name-translator-choice-area');
this.panel.$element.append(this.prompt, this.area);
this.$body.append(this.panel.$element);
};
ChoiceDialog.prototype.getSetupProcess = function (data) {
return ChoiceDialog.super.prototype.getSetupProcess.call(this, data).next(() => {
this.steps = data.steps;
this.choices = this.steps.map(() => ({ choice: null, custom: '' }));
this.index = 0;
this.renderStep();
});
};
ChoiceDialog.prototype.getBodyHeight = function () {
return this.panel.$element.outerHeight(true);
};
ChoiceDialog.prototype.renderStep = function () {
const step = this.steps[this.index];
const state = this.choices[this.index];
const last = this.index === this.steps.length - 1;
this.actions.setMode(
this.steps.length === 1 ? 'single' : this.index === 0 ? 'first' : last ? 'last' : 'middle',
);
this.prompt.text(`${this.index + 1} / ${this.steps.length} ${step.query}`);
const update = () => {
const value = state.choice === 'custom' ? state.custom.trim() : step.options[state.choice]?.translation;
this.actions.setAbilities({ next: safeTranslation(value), apply: safeTranslation(value) });
};
const radio = (value, label) =>
$('<input>', {
type: 'radio',
name: 'name-translator-choice',
'aria-label': label,
})
.prop('checked', state.choice === value)
.on('change', () => {
state.choice = value;
update();
});
const rows = step.options.map((option, index) => {
const region = option.kind === 'YC' ? `${t('地名,')}${option.region}` : option.region;
return $('<label>')
.addClass('name-translator-row')
.append(
radio(index, `${option.translation},${option.original} ${region}`),
$('<span>').text(option.translation),
$('<span>').attr('dir', 'auto').text(option.original),
$('<span>').text(region),
)[0];
});
const customRadio = radio('custom', customLabel);
const custom = new OO.ui.TextInputWidget({
value: state.custom,
placeholder: t('输入自订译文', '輸入自訂譯文'),
});
custom.$input.attr('aria-label', customLabel);
const selectCustom = () => {
state.choice = 'custom';
state.custom = custom.getValue();
customRadio.prop('checked', true);
update();
};
custom.$input.on('focus', selectCustom);
custom.on('change', selectCustom);
const customRow = $('<div>').addClass('name-translator-custom').append(customRadio, custom.$element);
this.area.empty().append(rows, customRow).scrollTop(0);
update();
this.updateSize();
};
ChoiceDialog.prototype.getActionProcess = function (action) {
return new OO.ui.Process(() => {
if (action === 'exit' || action === '') this.close();
if (action === 'back' || action === 'next') {
this.index += action === 'back' ? -1 : 1;
this.renderStep();
}
if (action === 'apply') {
const values = this.choices.map(({ choice, custom }, index) =>
choice === 'custom' ? custom.trim() : this.steps[index].options[choice]?.translation,
);
if (values.every(safeTranslation)) this.close({ values });
}
});
};
async function choose(steps) {
if (!dialog) {
manager = new OO.ui.WindowManager();
$(OO.ui.getTeleportTarget()).append(manager.$element);
dialog = new ChoiceDialog({ size: 'larger' });
manager.addWindows([dialog]);
}
const lifecycle = manager.openWindow(dialog, { steps });
await lifecycle.opened;
const result = await lifecycle.closed;
return result?.values;
}
function activeEditor() {
const editor = window.wikitextEditor;
return editor && !editor.readonly && !['view', 'none', 'codeeditor'].includes(editor.mode) ? editor : null;
}
function capture(editor) {
const mode = editor.mode;
const version = epoch;
const rawApi = editor._rawApi;
const target = window.ve?.init?.target;
const surface = target?.getSurface();
const sameEditor = () =>
activeEditor() === editor &&
editor.mode === mode &&
epoch === version &&
editor._rawApi === rawApi &&
(!surface || target.getSurface() === surface);
const ensure = (valid) => {
if (!sameEditor() || !valid) {
throw new TranslationError(
'编辑器或内容已改变,请重新选中文字后重试。',
'編輯器或內容已變更,請重新選取文字後再試。',
);
}
};
const range = editor.getSelectionRange();
if (range[0] === null || range[0] === range[1]) return null;
if (surface?.getMode() === 'visual') {
const model = surface.getModel();
const documentModel = model.getDocument();
const selection = model.getSelection();
const fragment = model.getFragment(selection, true);
const snapshot = JSON.stringify(fragment.getData());
const check = () => ensure(snapshot === JSON.stringify(fragment.getData()));
return {
read: () => target.getWikitextFragment(documentModel.shallowCloneFromSelection(selection)),
check,
async replace(value) {
const parsed = await target.parseWikitextFragment(value, false, documentModel);
const html = parsed.visualeditor.content;
const replacement = window.ve.dm.converter.getModelFromDom(
window.ve.createDocumentFromHtml(html),
documentModel,
);
const data = replacement.getData();
if (data[0]?.type !== 'paragraph') {
throw new TranslationError('无法在可视化编辑器中插入译文。', '無法在視覺化編輯器中插入譯文。');
}
const end = data.findIndex((item) => item?.type === '/paragraph');
if (end < 2 || data.slice(end + 1).some((item) => item?.type === 'paragraph')) {
throw new TranslationError('译文需要能插入同一段落。', '譯文必須能插入同一段落。');
}
check();
fragment.insertDocument(replacement, new window.ve.Range(1, end), true).select();
},
};
}
const before = editor.text;
const selected = editor.selectionText;
const check = () => ensure(editor.text === before);
return {
read: () => selected,
check,
async replace(value) {
check();
if ((await editor.insertText(value, range)) === false) {
throw new TranslationError('无法替换所选文字。', '無法取代選取的文字。');
}
},
};
}
async function translate() {
const editor = activeEditor();
if (busy || !editor) return;
busy = true;
try {
const selection = capture(editor);
if (!selection) throw new TranslationError('请先选中要翻译的文字。', '請先選取要翻譯的文字。');
const input = parseSelection(await selection.read());
selection.check();
const steps = await findSteps(input.query, search);
selection.check();
const pending = steps.filter((step) => step.automatic === null);
const values = pending.length ? await choose(pending) : [];
if (!values) return;
let index = 0;
const translation = steps.map((step) => step.automatic ?? values[index++]).join('·');
await selection.replace(renderSelection(input, translation));
} catch (error) {
const message =
error instanceof TranslationError
? t(error.message, error.hant)
: t('名称翻译失败,请重试。', '名稱翻譯失敗,請再試一次。');
if (!(error instanceof TranslationError)) console.error('Name translator:', error);
mw.notify(message, { type: 'warn' });
} finally {
busy = false;
}
}
function makeButton() {
const button = new OO.ui.ButtonWidget({ label: title, framed: false, icon: 'language' });
button.$element.addClass(toolClass).on('mousedown', (event) => event.preventDefault());
button.on('click', translate);
return button.$element;
}
function installToolbar() {
const editor = activeEditor();
if (!editor) return;
const target = window.ve?.init?.target;
const toolbar = target?.getSurface() && target.getToolbar?.();
if (toolbar?.$after?.length && /^(?:visual|wikitext2017)/.test(editor.mode)) {
if (!toolbar.$after.find(`.${toolClass}`).length) toolbar.$after.append(makeButton());
return;
}
const $textarea = $(editor._rawApi?._textboxSelector || '#wpTextbox1').first();
if (!$textarea.length) return;
const textarea = $textarea[0];
const context = $textarea.data('wikiEditor-context');
const $wikiToolbar = context?.$ui?.find('.wikiEditor-ui-toolbar');
if ($wikiToolbar?.length && !$wikiToolbar.find(`.${toolClass}`).length) {
fallbackToolbars.get(textarea)?.remove();
fallbackToolbars.delete(textarea);
$textarea.wikiEditor('addToToolbar', {
section: 'secondary',
group: 'default',
tools: { nameTranslator: { type: 'element', element: makeButton } },
});
} else if (!$wikiToolbar?.length && !fallbackToolbars.get(textarea)?.[0].isConnected) {
const $fallback = $('<div>')
.addClass('name-translator-toolbar')
.attr({ role: 'toolbar', 'aria-label': title })
.append(makeButton())
.insertBefore($textarea);
fallbackToolbars.set(textarea, $fallback);
}
}
mw.hook('editorapi.ready').add(() => {
epoch++;
installToolbar();
});
mw.hook('wikiEditor.toolbarReady').add(installToolbar);
mw.hook('ve.activationComplete').add(installToolbar);
installToolbar();
})
.catch((error) => {
window.nameTranslatorLoaded = false;
console.error('Name translator:', error);
});
})();