MediaWiki:Gadget-speechSynthewiki.js: различия между версиями
Ланселот (обсуждение | вклад) Нет описания правки |
Ланселот (обсуждение | вклад) Нет описания правки |
||
| (не показаны 3 промежуточные версии этого же участника) | |||
| Строка 1: | Строка 1: | ||
/** | /** | ||
* Speech Synthewiki — гаджет озвучки статей браузером | * Speech Synthewiki — гаджет озвучки статей браузером для скина Vector-10 | ||
* Версия 0.3 (beta) — ещё надо поработать над озвучкой формул | * Версия 0.3.1 (absurdoversion, beta) — ещё надо поработать над озвучкой формул | ||
* Кнопки по языку интерфейса пользователя, пока поддержка 4 языков | * Кнопки по языку интерфейса пользователя, пока поддержка 4 языков | ||
* Лицензия: MIT (opensource.org/license/mit) ==> 2026, absurdopedia.wiki | |||
*/ | */ | ||
| Строка 12: | Строка 13: | ||
// Когда раздел заканчивается — воспроизведение останавливается | // Когда раздел заканчивается — воспроизведение останавливается | ||
// Кнопка «озвучить всё» озвучивает всю статью | // Кнопка «озвучить всё» озвучивает всю статью | ||
// Исключается шаблон «Месяц» (таблица с 10+ месяцами подряд) | |||
/*****************************************************************/ | /*****************************************************************/ | ||
| Строка 20: | Строка 22: | ||
var currentButton = null; | var currentButton = null; | ||
var voicesReady = false; | var voicesReady = false; | ||
// ---------- разрешённые пространства имён ---------- | |||
var ALLOWED_NS = [0, 4, 100, 114, 116, 118, 120]; | |||
// ---------- локализация ---------- | // ---------- локализация ---------- | ||
| Строка 68: | Строка 74: | ||
var T = I18N[LANG] || I18N.ru; | var T = I18N[LANG] || I18N.ru; | ||
function msg(key) { | function msg(key) { | ||
return (T && T[key]) || I18N.ru[key] || ''; | return (T && T[key]) || I18N.ru[key] || ''; | ||
| Строка 98: | Строка 103: | ||
'.vector-toc', '.mw-toc', '#mw-panel-toc' | '.vector-toc', '.mw-toc', '#mw-panel-toc' | ||
].join(','); | ].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; | |||
} | |||
// ---------- голоса ---------- | // ---------- голоса ---------- | ||
| Строка 117: | Строка 137: | ||
}; | }; | ||
window.speechSynthesis.addEventListener('voiceschanged', handler); | window.speechSynthesis.addEventListener('voiceschanged', handler); | ||
} | |||
// ---------- сброс всех кнопок в исходное состояние ---------- | |||
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; | |||
} | } | ||
| Строка 126: | Строка 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 () { | ||
| Строка 239: | Строка 280: | ||
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; | ||
| Строка 244: | Строка 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('table') && isMonthTable($el)) { | |||
return true; | |||
} | |||
if ($el.is(SKIP_TOP)) return true; | if ($el.is(SKIP_TOP)) return true; | ||
| Строка 276: | Строка 326: | ||
var chunks = []; | var chunks = []; | ||
var lead = buildLeadText(); | var lead = buildLeadText(); | ||
if (lead) chunks.push(lead); | if (lead) chunks.push(lead); | ||
$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); | ||
| Строка 307: | Строка 355: | ||
if (currentButton === a && window.speechSynthesis.speaking) { | if (currentButton === a && window.speechSynthesis.speaking) { | ||
window.speechSynthesis.cancel(); | window.speechSynthesis.cancel(); | ||
$(a).text(T.speak); | $(a).text($(a).data('lead') === 'full' ? T.speakAll : T.speak); | ||
currentButton = null; | currentButton = null; | ||
currentUtterance = null; | currentUtterance = null; | ||
| Строка 314: | Строка 362: | ||
var text; | var text; | ||
var mode = $(a).data('lead'); | |||
text = buildFullText(); | if (mode === 'lead-only') { | ||
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'); | ||
| Строка 329: | Строка 380: | ||
if (!text) { | if (!text) { | ||
resetAllButtons(); | |||
mw.notify(msg('noText'), { type: 'warn' }); | mw.notify(msg('noText'), { type: 'warn' }); | ||
return; | return; | ||
| Строка 335: | Строка 387: | ||
if (window.speechSynthesis.speaking) { | if (window.speechSynthesis.speaking) { | ||
window.speechSynthesis.cancel(); | window.speechSynthesis.cancel(); | ||
if (currentButton) $(currentButton).text(T.speak); | if (currentButton) $(currentButton).text( | ||
$(currentButton).data('lead') === 'full' ? T.speakAll : T.speak | |||
); | |||
} | } | ||
| Строка 353: | Строка 407: | ||
}; | }; | ||
currentUtterance.onend = function () { | currentUtterance.onend = function () { | ||
$(a).text(T.speak); | $(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; } | ||
} | } | ||
| Строка 369: | Строка 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) $root = $('#mw-content-text'); | ||
if (!$root.length) return; | if (!$root.length) return; | ||
// --- | // --- кнопки по краям: «озвучить всё» слева, «озвучить» справа --- | ||
if (!$root.find('.cyclo-tts-lead').length) { | if (!$root.find('.cyclo-tts-lead').length) { | ||
var $leadBar = $('<div class="cyclo-tts-lead" style="margin:.5em 0;"></div>'); | 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 $ | |||
var $fullBtn = $('<a href="#" style="cursor:pointer;"></a>') | |||
.text(T.speakAll) | .text(T.speakAll) | ||
.data('lead', | .data('lead', 'full'); | ||
$ | $fullBtn.on('click', onClick); | ||
$leadBar.append($ | |||
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); | ||
} | } | ||
| Строка 413: | Строка 481: | ||
addButtons(); | addButtons(); | ||
mw.hook('userjs.languageChanged').add(function () { | mw.hook('userjs.languageChanged').add(function () { | ||
LANG = detectLang(); | LANG = detectLang(); | ||
T = I18N[LANG] || I18N.ru; | T = I18N[LANG] || I18N.ru; | ||
$('.cyclo-tts-start a').text(T.speak); | $('.cyclo-tts-start a').text(T.speak); | ||
$('.cyclo-tts-lead a').text(T.speakAll); | $('.cyclo-tts-lead a').each(function () { | ||
var $btn = $(this); | |||
if ($btn.data('lead') === 'full') $btn.text(T.speakAll); | |||
else $btn.text(T.speak); | |||
}); | |||
}); | }); | ||
}); | }); | ||
}); | }); | ||
})(); | })(); | ||