MediaWiki:Gadget-speechSynthewiki.js: различия между версиями
Ланселот (обсуждение | вклад) Нет описания правки |
Ланселот (обсуждение | вклад) Нет описания правки |
||
| (не показано 5 промежуточных версий этого же участника) | |||
| Строка 1: | Строка 1: | ||
/** | /** | ||
* Speech Synthewiki — гаджет озвучки статей браузером | * Speech Synthewiki — гаджет озвучки статей браузером для скина Vector-10 | ||
* Версия 0.3. | * Версия 0.3.1 (absurdoversion, beta) — ещё надо поработать над озвучкой формул | ||
* | * Кнопки по языку интерфейса пользователя, пока поддержка 4 языков | ||
* Лицензия: MIT (opensource.org/license/mit) ==> 2026, absurdopedia.wiki | |||
/* | */ | ||
/*****************************************************************/ | |||
// ИСПОЛЬЗОВАНИЕ | |||
// Возле каждого раздела статьи появляется ссылка «озвучить» | |||
// Нажимаешь → читает весь текст под этим заголовком | |||
// Если хочешь остановить — жмёшь «стоп» (кнопка меняется) | |||
// Когда раздел заканчивается — воспроизведение останавливается | |||
// Кнопка «озвучить всё» озвучивает всю статью | |||
// Исключается шаблон «Месяц» (таблица с 10+ месяцами подряд) | |||
/*****************************************************************/ | |||
(function () { | (function () { | ||
| Строка 12: | Строка 22: | ||
var currentButton = null; | var currentButton = null; | ||
var voicesReady = false; | var voicesReady = false; | ||
// ---------- разрешённые пространства имён ---------- | |||
var ALLOWED_NS = [0, 4, 100, 114, 116, 118, 120]; | |||
// ---------- локализация ---------- | // ---------- локализация ---------- | ||
| Строка 60: | Строка 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] || ''; | ||
| Строка 90: | Строка 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; | |||
} | |||
// ---------- голоса ---------- | // ---------- голоса ---------- | ||
| Строка 109: | Строка 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; | |||
} | } | ||
| Строка 118: | Строка 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 () { | ||
| Строка 231: | Строка 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; | ||
| Строка 236: | Строка 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; | ||
| Строка 255: | Строка 313: | ||
if (t) chunks.push(t); | if (t) chunks.push(t); | ||
return true; | return true; | ||
}); | |||
return chunks.join('\n'); | |||
} | |||
// ---------- сбор текста всей статьи ---------- | |||
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); | |||
}); | }); | ||
| Строка 267: | Строка 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; | ||
| Строка 274: | Строка 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'); | ||
| Строка 289: | Строка 380: | ||
if (!text) { | if (!text) { | ||
resetAllButtons(); | |||
mw.notify(msg('noText'), { type: 'warn' }); | mw.notify(msg('noText'), { type: 'warn' }); | ||
return; | return; | ||
| Строка 295: | Строка 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 | |||
); | |||
} | } | ||
| Строка 313: | Строка 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; } | ||
} | } | ||
| Строка 329: | Строка 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) { | |||
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>') | |||
var $ | |||
.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); | ||
} | } | ||
| Строка 386: | Строка 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); | |||
}); | |||
}); | }); | ||
}); | }); | ||
}); | }); | ||
})(); | })(); | ||