MediaWiki:Gadget-speechSynthewiki.js: различия между версиями
Ланселот (обсуждение | вклад) Нет описания правки |
Ланселот (обсуждение | вклад) Нет описания правки |
||
| (не показано 13 промежуточных версий этого же участника) | |||
| Строка 1: | Строка 1: | ||
/** | /** | ||
* Speech Synthewiki — гаджет озвучки статей браузером | * Speech Synthewiki — гаджет озвучки статей браузером для скина Vector-10 | ||
* Версия 0.3.1 | * Версия 0.3.1 (absurdoversion, beta) — ещё надо поработать над озвучкой формул | ||
* | * Кнопки по языку интерфейса пользователя, пока поддержка 4 языков | ||
* | * Лицензия: MIT (opensource.org/license/mit) ==> 2026, absurdopedia.wiki | ||
*/ | |||
/* | |||
/*****************************************************************/ | |||
// ИСПОЛЬЗОВАНИЕ | |||
// Возле каждого раздела статьи появляется ссылка «озвучить» | |||
// Нажимаешь → читает весь текст под этим заголовком | |||
// Если хочешь остановить — жмёшь «стоп» (кнопка меняется) | |||
// Когда раздел заканчивается — воспроизведение останавливается | |||
// Кнопка «озвучить всё» озвучивает всю статью | |||
// Исключается шаблон «Месяц» (таблица с 10+ месяцами подряд) | |||
/*****************************************************************/ | |||
(function () { | (function () { | ||
| Строка 13: | Строка 22: | ||
var currentButton = null; | var currentButton = null; | ||
var voicesReady = false; | var voicesReady = false; | ||
// ---------- разрешённые пространства имён ---------- | |||
var ALLOWED_NS = [0, 4, 100, 114, 116, 118, 120]; | |||
// ---------- локализация ---------- | |||
var I18N = { | |||
ru: { | |||
speak: 'озвучить', | |||
stop: 'стоп', | |||
speakAll: '🔊 озвучить всё', | |||
noText: 'Под этим заголовком нет текста для озвучки', | |||
noSynth: 'Браузер не поддерживает синтез речи' | |||
}, | |||
en: { | |||
speak: 'listen', | |||
stop: 'stop', | |||
speakAll: '🔊 listen to all' | |||
}, | |||
eo: { | |||
speak: 'laŭtlegi', | |||
stop: 'halti', | |||
speakAll: '🔊 laŭtlegi ĉion' | |||
}, | |||
udm: { | |||
speak: 'куараё карыны', | |||
stop: 'дугдытыны', | |||
speakAll: '🔊 ваньзэ куараё карыны' | |||
} | |||
}; | |||
function detectLang() { | |||
try { | |||
var explicit = mw.user.options.get('gadget-SpeechSynthewiki-lang'); | |||
if (explicit && I18N[explicit]) return explicit; | |||
} catch (e) { /* ignore */ } | |||
var ui = (mw.config.get('wgUserLanguage') || '').toLowerCase(); | |||
if (ui.indexOf('udm') === 0) return 'udm'; | |||
if (ui.indexOf('en') === 0) return 'en'; | |||
if (ui.indexOf('eo') === 0) return 'eo'; | |||
if (ui.indexOf('ru') === 0) return 'ru'; | |||
var content = (mw.config.get('wgContentLanguage') || '').toLowerCase(); | |||
if (I18N[content]) return content; | |||
return 'ru'; | |||
} | |||
var LANG = detectLang(); | |||
var T = I18N[LANG] || I18N.ru; | |||
function msg(key) { | |||
return (T && T[key]) || I18N.ru[key] || ''; | |||
} | |||
// ---------- служебные элементы, которые не озвучиваем ---------- | // ---------- служебные элементы, которые не озвучиваем ---------- | ||
var SKIP_SELECTORS = [ | var SKIP_SELECTORS = [ | ||
'#siteSub', '#contentSub', '#jump-to-nav', '.mw-jump-link', | |||
'.mw-indicators', '.catlinks', '.printfooter', '.mw-hidden-catlinks', | |||
'.noprint', '.metadata', | |||
'.navbox', '.vertical-navbox', '.sistersitebox', '.ambox', | |||
'.mbox-text-span', '.mw-references-wrap', 'ol.references', | |||
'.reference', 'sup.reference', '.reflist', | |||
'style', 'script', | |||
'.mw-empty-elt', '.mw-kartographer-maplink', | |||
'.cyclo-tts-start', '.cyclo-tts-lead', | |||
'.mw-editsection', '.editsection', | |||
'#toc', '.toc', '.mw-toc', '#mw-toc', '#mw-toc-heading', | |||
'#toctitle', '.toctitle', '.vector-toc', '.vector-toc-heading', | |||
'#mw-panel-toc', '.tocnumber', '.toctext', | |||
'.sidebar-toc', '.minerva-toc' | |||
].join(','); | |||
].join(','); | |||
var SKIP_TOP = [ | |||
'h1.firstHeading', '#siteSub', '#contentSub', '.mw-indicators', | |||
'.mw-jump-link', '.printfooter', '.catlinks', | |||
'.cyclo-tts-lead', '.cyclo-tts-start', | |||
'#toc', '.toc', '#toctitle', '.toctitle', | |||
'.vector-toc', '.mw-toc', '#mw-panel-toc' | |||
].join(','); | |||
// ---------- признаки шаблона «Месяц» ---------- | |||
var MONTH_NAMES = [ | |||
'Январь', 'Февраль', 'Март', 'Апрель', 'Май', 'Июнь', | |||
'Июль', 'Август', 'Сентябрь', 'Октябрь', 'Ноябрь', 'Декабрь' | |||
]; | |||
function isMonthTable($table) { | |||
var t = $table.text(); | |||
var count = 0; | |||
for (var i = 0; i < MONTH_NAMES.length; i++) { | |||
if (t.indexOf(MONTH_NAMES[i]) !== -1) count++; | |||
} | |||
return count >= 10; | |||
} | |||
// ---------- голоса ---------- | // ---------- голоса ---------- | ||
function getRussianVoice() { | function getRussianVoice() { | ||
| Строка 52: | Строка 139: | ||
} | } | ||
// ---------- очистка клона | // ---------- сброс всех кнопок в исходное состояние ---------- | ||
function resetAllButtons() { | |||
$('.cyclo-tts-start a, .cyclo-tts-lead a').each(function () { | |||
var $btn = $(this); | |||
if ($btn.data('lead') === 'full') { | |||
$btn.text(T.speakAll); | |||
} else { | |||
$btn.text(T.speak); | |||
} | |||
}); | |||
currentButton = null; | |||
currentUtterance = null; | |||
} | |||
// ---------- очистка клона ---------- | |||
function cleanClone(cloned) { | function cleanClone(cloned) { | ||
cloned.find([ | cloned.find([ | ||
| Строка 59: | Строка 160: | ||
'ul.gallery', 'div.gallery', 'li.gallerybox', 'div.thumb', | 'ul.gallery', 'div.gallery', 'li.gallerybox', 'div.thumb', | ||
'.gallerycaption', 'sup.reference', '.metadata', '.noprint', | '.gallerycaption', 'sup.reference', '.metadata', '.noprint', | ||
// подписи к картинкам | |||
'figcaption', '.mw-caption', '.image-caption', '.caption', | |||
'img', 'a.image', 'style', 'script' | 'img', 'a.image', 'style', 'script' | ||
].join(',')).remove(); | ].join(',')).remove(); | ||
// Вырезаем таблицу шаблона «Месяц» по содержимому | |||
cloned.find('table').filter(function () { | |||
return isMonthTable($(this)); | |||
}).remove(); | |||
cloned.contents().each(function () { | cloned.contents().each(function () { | ||
| Строка 83: | Строка 191: | ||
function mathToSpeech($math) { | function mathToSpeech($math) { | ||
var $clone = $math.clone(); | var $clone = $math.clone(); | ||
$clone.find('annotation').remove(); | $clone.find('annotation').remove(); | ||
var parts = []; | var parts = []; | ||
| Строка 92: | Строка 198: | ||
$(this).remove(); | $(this).remove(); | ||
}); | }); | ||
$clone.find('mfrac').each(function () { | $clone.find('mfrac').each(function () { | ||
var $ch = $(this).children(); | var $ch = $(this).children(); | ||
parts.push(' дробь ' + $ch.eq(0).text().trim() + ' на ' + $ch.eq(1).text().trim() + ' '); | |||
$(this).remove(); | $(this).remove(); | ||
}); | }); | ||
$clone.find('msup').each(function () { | $clone.find('msup').each(function () { | ||
var $ch = $(this).children(); | var $ch = $(this).children(); | ||
| Строка 110: | Строка 212: | ||
$(this).remove(); | $(this).remove(); | ||
}); | }); | ||
$clone.find('msub').each(function () { | $clone.find('msub').each(function () { | ||
var $ch = $(this).children(); | var $ch = $(this).children(); | ||
| Строка 144: | Строка 245: | ||
} | } | ||
// ---------- сбор текста секции | // ---------- сбор текста секции ---------- | ||
function buildSpeechText($startNode, $stopNode) { | function buildSpeechText($startNode, $stopNode) { | ||
var chunks = []; | var chunks = []; | ||
| Строка 155: | Строка 256: | ||
var $cloned = cleanClone($node.clone()); | var $cloned = cleanClone($node.clone()); | ||
$cloned.find(SKIP_SELECTORS).remove(); | $cloned.find(SKIP_SELECTORS).remove(); | ||
if ($cloned.is(SKIP_SELECTORS)) { | if ($cloned.is(SKIP_SELECTORS)) { | ||
| Строка 161: | Строка 261: | ||
continue; | continue; | ||
} | } | ||
$cloned.find('math').each(function () { | $cloned.find('math').each(function () { | ||
var spoken = mathToSpeech($(this)); | var spoken = mathToSpeech($(this)); | ||
if (spoken) | if (spoken) $(this).replaceWith(document.createTextNode(' формула: ' + spoken + ' ')); | ||
else $(this).remove(); | |||
}); | }); | ||
| Строка 181: | Строка 277: | ||
function buildLeadText() { | function buildLeadText() { | ||
var $root = $('#mw-content-text .mw-parser-output'); | var $root = $('#mw-content-text .mw-parser-output'); | ||
if (!$root.length) $root = $('#mw-content-text'); | |||
if (!$root.length) return ''; | if (!$root.length) return ''; | ||
// | // первый заголовок — либо сам h1..h6, либо его обёртка .mw-heading | ||
var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6, .mw-heading').first(); | var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6, .mw-heading').first(); | ||
var stopEl = $firstHeader.length ? $firstHeader[0] : null; | var stopEl = $firstHeader.length ? $firstHeader[0] : null; | ||
| Строка 189: | Строка 286: | ||
var chunks = []; | var chunks = []; | ||
$root.children().each(function () { | $root.children().each(function () { | ||
if (stopEl && this === stopEl) return false; | // останавливаемся на первом заголовке или на его обёртке | ||
if (stopEl && (this === stopEl || $(this).is(stopEl) || $(this).find(stopEl).length)) { | |||
return false; | |||
} | |||
var $el = $(this); | var $el = $(this); | ||
// | // Пропускаем таблицу шаблона «Месяц» по содержимому | ||
if ($el.is(' | if ($el.is('table') && isMonthTable($el)) { | ||
return true; | return true; | ||
} | } | ||
if ($el.is(SKIP_TOP)) return true; | |||
if ($el.find('#toctitle, .toctitle').length) return true; | |||
var $cloned = cleanClone($el.clone()); | var $cloned = cleanClone($el.clone()); | ||
| Строка 203: | Строка 306: | ||
$cloned.find('math').each(function () { | $cloned.find('math').each(function () { | ||
var spoken = mathToSpeech($(this)); | var spoken = mathToSpeech($(this)); | ||
if (spoken) | if (spoken) $(this).replaceWith(document.createTextNode(' формула: ' + spoken + ' ')); | ||
else $(this).remove(); | |||
}); | }); | ||
| Строка 218: | Строка 318: | ||
} | } | ||
// ---------- | // ---------- сбор текста всей статьи ---------- | ||
function buildFullText() { | |||
var $root = $('#mw-content-text .mw-parser-output'); | |||
if (!$root.length) $root = $('#mw-content-text'); | |||
if (!$root.length) return ''; | |||
var chunks = []; | |||
var lead = buildLeadText(); | |||
if (lead) chunks.push(lead); | |||
$root.find('.mw-heading, h1, h2, h3, h4, h5, h6').each(function () { | |||
var $h = $(this); | |||
if ($h.is('#mw-toc-heading, #toctitle, .toctitle')) return; | |||
if ($h.closest('#toc, .toc, .vector-toc, .mw-toc, #mw-panel-toc').length) return; | |||
if ($h.find('#toctitle, .toctitle').length) return; | |||
var $realHeader = $h.is('.mw-heading') | |||
? $h.children('h1,h2,h3,h4,h5,h6') | |||
: $h; | |||
var $start = $realHeader.next(); | |||
if (!$start.length) $start = $realHeader.parent().next(); | |||
var $stop = $start.nextAll('.mw-heading, h1, h2, h3, h4, h5, h6').first(); | |||
var t = $start.length ? buildSpeechText($start, $stop.length ? $stop : null) : ''; | |||
if (t) chunks.push(t); | |||
}); | |||
return chunks.join('\n'); | |||
} | |||
// ---------- клик ---------- | |||
function onClick(event) { | function onClick(event) { | ||
event.preventDefault(); | event.preventDefault(); | ||
var a = event.currentTarget; | var a = event.currentTarget; | ||
if (currentButton === a && window.speechSynthesis.speaking) { | if (currentButton === a && window.speechSynthesis.speaking) { | ||
window.speechSynthesis.cancel(); | window.speechSynthesis.cancel(); | ||
$(a).text(' | $(a).text($(a).data('lead') === 'full' ? T.speakAll : T.speak); | ||
currentButton = null; | currentButton = null; | ||
currentUtterance = null; | currentUtterance = null; | ||
| Строка 233: | Строка 362: | ||
var text; | var text; | ||
var mode = $(a).data('lead'); | |||
if (mode === 'lead-only') { | |||
text = buildLeadText(); | text = buildLeadText(); | ||
} else if (mode === 'full') { | |||
text = buildFullText(); | |||
} else { | } else { | ||
var $heading = $(a).closest('.mw-heading, h1, h2, h3, h4, h5, h6'); | var $heading = $(a).closest('.mw-heading, h1, h2, h3, h4, h5, h6'); | ||
| Строка 240: | Строка 372: | ||
? $heading.children('h1,h2,h3,h4,h5,h6') | ? $heading.children('h1,h2,h3,h4,h5,h6') | ||
: $heading; | : $heading; | ||
var $start = $realHeader.next(); | var $start = $realHeader.next(); | ||
if (!$start.length) $start = $realHeader.parent().next(); | |||
var $stop = $start.nextAll('.mw-heading, h1, h2, h3, h4, h5, h6').first(); | var $stop = $start.nextAll('.mw-heading, h1, h2, h3, h4, h5, h6').first(); | ||
text = $start.length | text = $start.length ? buildSpeechText($start, $stop.length ? $stop : null) : ''; | ||
} | } | ||
if (!text) { | if (!text) { | ||
mw.notify(' | resetAllButtons(); | ||
mw.notify(msg('noText'), { type: 'warn' }); | |||
return; | return; | ||
} | } | ||
if (window.speechSynthesis.speaking) { | if (window.speechSynthesis.speaking) { | ||
window.speechSynthesis.cancel(); | window.speechSynthesis.cancel(); | ||
if (currentButton) $(currentButton).text(' | if (currentButton) $(currentButton).text( | ||
$(currentButton).data('lead') === 'full' ? T.speakAll : T.speak | |||
); | |||
} | } | ||
| Строка 269: | Строка 403: | ||
currentUtterance.onstart = function () { | currentUtterance.onstart = function () { | ||
$(a).text( | $(a).text(T.stop); | ||
currentButton = a; | currentButton = a; | ||
}; | }; | ||
currentUtterance.onend = function () { | currentUtterance.onend = function () { | ||
$(a).text(' | $(a).text( | ||
$(a).data('lead') === 'full' ? T.speakAll : T.speak | |||
); | |||
if (currentButton === a) { currentButton = null; currentUtterance = null; } | if (currentButton === a) { currentButton = null; currentUtterance = null; } | ||
}; | }; | ||
currentUtterance.onerror = function (ev) { | currentUtterance.onerror = function (ev) { | ||
if (ev.error !== 'interrupted' && ev.error !== 'canceled') { | if (ev.error !== 'interrupted' && ev.error !== 'canceled') { | ||
$(a). | var restore = $(a).data('lead') === 'full' ? T.speakAll : T.speak; | ||
if ($(a).text() !== restore) $(a).text(restore); | |||
if (currentButton === a) { currentButton = null; currentUtterance = null; } | if (currentButton === a) { currentButton = null; currentUtterance = null; } | ||
} | } | ||
| Строка 291: | Строка 426: | ||
// ---------- вставка кнопок ---------- | // ---------- вставка кнопок ---------- | ||
function addButtons() { | function addButtons() { | ||
// Только в разрешённых пространствах имён | |||
var ns = mw.config.get('wgNamespaceNumber'); | |||
if (ALLOWED_NS.indexOf(ns) === -1) return; | |||
var $root = $('#mw-content-text .mw-parser-output'); | var $root = $('#mw-content-text .mw-parser-output'); | ||
if (!$root.length) $root = $('#mw-content-text'); | |||
if (!$root.length) return; | if (!$root.length) return; | ||
// --- | // --- кнопки по краям: «озвучить всё» слева, «озвучить» справа --- | ||
if (!$root.find('.cyclo-tts-lead').length) { | |||
var $leadBar = $('<div class="cyclo-tts-lead" style="margin:.5em 0;display:flex;flex-wrap:wrap;gap:.5em;justify-content:space-between;align-items:center;"></div>'); | |||
var $fullBtn = $('<a href="#" style="cursor:pointer;"></a>') | |||
.text(T.speakAll) | |||
.data('lead', 'full'); | |||
$fullBtn.on('click', onClick); | |||
var $leadOnlyBtn = $('<a href="#" style="cursor:pointer;"></a>') | |||
.text(T.speak) | |||
.data('lead', 'lead-only'); | |||
$leadOnlyBtn.on('click', onClick); | |||
$leadBar.append($fullBtn).append($leadOnlyBtn); | |||
$root.prepend($leadBar); | $root.prepend($leadBar); | ||
} | } | ||
// --- кнопки у | // --- кнопки у заголовков --- | ||
$root.find('.mw-heading, h1, h2, h3, h4, h5, h6').each(function () { | $root.find('.mw-heading, h1, h2, h3, h4, h5, h6').each(function () { | ||
var $h = $(this); | var $h = $(this); | ||
if ($h.hasClass('cyclo-tts-start')) return; | if ($h.hasClass('cyclo-tts-start')) return; | ||
var $edit = $h.find('.mw-editsection').first(); | |||
if (!$edit.length) return; | if ($h.is('#mw-toc-heading, #toctitle, .toctitle')) return; | ||
if ($h.closest('#toc, .toc, .vector-toc, .mw-toc, #mw-panel-toc').length) return; | |||
if ($h.find('#toctitle, .toctitle').length) return; | |||
var $edit = $h.find('.mw-editsection, .editsection').first(); | |||
if (!$edit.length) return; | |||
if ($edit.prev().hasClass('cyclo-tts-start')) return; | if ($edit.prev().hasClass('cyclo-tts-start')) return; | ||
var $span = $('<span class="mw-editsection cyclo-tts-start">[<a href="#" style="cursor:pointer;"> | var $span = $('<span class="mw-editsection cyclo-tts-start">[<a href="#" style="cursor:pointer;"></a>]</span> '); | ||
$span.find('a').text(T.speak); | |||
$span.on('click', 'a', onClick); | $span.on('click', 'a', onClick); | ||
$edit.before($span); | $edit.before($span); | ||
| Строка 332: | Строка 475: | ||
mw.loader.using(['jquery'], function () { | mw.loader.using(['jquery'], function () { | ||
$(function () { | $(function () { | ||
if (window.speechSynthesis) | if (!window.speechSynthesis) { | ||
console.warn('[Speech Synthewiki] ' + msg('noSynth')); | |||
return; | |||
console.warn('[Speech Synthewiki] | |||
} | } | ||
addButtons(); | |||
mw.hook('userjs.languageChanged').add(function () { | |||
LANG = detectLang(); | |||
T = I18N[LANG] || I18N.ru; | |||
$('.cyclo-tts-start a').text(T.speak); | |||
$('.cyclo-tts-lead a').each(function () { | |||
var $btn = $(this); | |||
if ($btn.data('lead') === 'full') $btn.text(T.speakAll); | |||
else $btn.text(T.speak); | |||
}); | |||
}); | |||
}); | }); | ||
}); | }); | ||
})(); | })(); | ||