MediaWiki:Gadget-speechSynthewiki.js: различия между версиями

Новая страница: «→* * Speech Synthewiki — гаджет озвучки статей браузером пользователя * Версия 0.3 — адаптация под MediaWiki 1.43 (+Vector 2022, MathML): →global mw, $: (function () { 'use strict'; var currentUtterance = null; var currentButton = null; var voicesReady = false; // ---------- утилиты ---------- function getRussianVoice() { var voices = window.spee...»
 
Нет описания правки
Строка 1: Строка 1:
/**
/**
  * Speech Synthewiki — гаджет озвучки статей браузером пользователя
  * Speech Synthewiki — гаджет озвучки статей браузером пользователя
  * Версия 0.3 — адаптация под MediaWiki 1.43 (+Vector 2022, MathML)
  * Версия 0.3.1 — адаптация под MediaWiki 1.43 (Vector 2022, MathML)
* Автор оригинала — Урахара (Циклопедия), CC BY-SA 4.0
* Адаптация: 2026
  */
  */
/* global mw, $ */
/* global mw, $ */
Строка 12: Строка 14:
     var voicesReady = false;
     var voicesReady = false;


     // ---------- утилиты ----------
     // ---------- служебные элементы, которые не озвучиваем ----------
    var SKIP_SELECTORS = [
        '#siteSub', '#contentSub', '#jump-to-nav', '.mw-jump-link',
        '.mw-indicators', '.catlinks', '.printfooter', '.mw-hidden-catlinks',
        '.noprint', '.metadata', '.mw-editsection',
        '.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'
    ].join(',');
 
    // ---------- голоса ----------
     function getRussianVoice() {
     function getRussianVoice() {
         var voices = window.speechSynthesis.getVoices() || [];
         var voices = window.speechSynthesis.getVoices() || [];
Строка 32: Строка 46:
     }
     }


     // Чистка клона блока от мусора (картинки, ссылки на файлы, сноски)
     // ---------- очистка клона от мусора ----------
     function cleanClone(cloned) {
     function cleanClone(cloned) {
         cloned.find([
         cloned.find([
Строка 60: Строка 74:
     }
     }


     // Озвучка формул MathML (1.43: math > semantics > annotation + presentation)
     // ---------- MathML → речь ----------
     function mathToSpeech($math) {
     function mathToSpeech($math) {
        var $clone = $math.clone();
         // Отсекаем TeX-аннотацию, чтобы не дублировать
         // Отсекаем TeX-аннотацию, чтобы не дублировать
        var $clone = $math.clone();
         $clone.find('annotation').remove();
         $clone.find('annotation').remove();


         var parts = [];
         var parts = [];


        // Порядок важен: сначала сложные конструкции
         $clone.find('msqrt').each(function () {
         $clone.find('msqrt').each(function () {
             parts.push(' корень из ' + $(this).text().trim() + ' ');
             parts.push(' корень из ' + $(this).text().trim() + ' ');
Строка 125: Строка 138:
     }
     }


     function buildSpeechText($header) {
    // ---------- сбор текста секции между двумя заголовками ----------
     function buildSpeechText($startNode, $stopNode) {
         var chunks = [];
         var chunks = [];
         var $node = $header.next();
         var $node = $startNode;
        // В 1.43 заголовки и контент могут лежать в разных обёртках,
 
        // поэтому идём по плоскому списку сиблингов в .mw-parser-output
         while ($node.length) {
         while ($node.length) {
             // Дошли до следующего заголовка — стоп
             if ($stopNode && $node[0] === $stopNode[0]) break;
             if ($node.is('h1, h2, h3, h4, h5, h6') ||
             if (!$stopNode && $node.is('h1, h2, h3, h4, h5, h6') && $node[0] !== $startNode[0]) break;
                $node.find('h1, h2, h3, h4, h5, h6').length && $node.is('.mw-heading')) {
            if (!$stopNode && $node.is('.mw-heading')) break;
                 break;
 
            var $cloned = cleanClone($node.clone());
 
            $cloned.find(SKIP_SELECTORS).remove();
            if ($cloned.is(SKIP_SELECTORS)) {
                 $node = $node.next();
                continue;
             }
             }
            var $cloned = cleanClone($node.clone());


             $cloned.find('math').each(function () {
             $cloned.find('math').each(function () {
Строка 151: Строка 169:
             $node = $node.next();
             $node = $node.next();
         }
         }
        return chunks.join('\n');
    }
    // ---------- сбор текста преамбулы ----------
    function buildLeadText() {
        var $root = $('#mw-content-text .mw-parser-output');
        if (!$root.length) return '';
        // Первый заголовок — граница преамбулы
        var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6, .mw-heading').first();
        var stopEl = $firstHeader.length ? $firstHeader[0] : null;
        var chunks = [];
        $root.children().each(function () {
            if (stopEl && this === stopEl) return false;
            var $el = $(this);
            // Явно пропускаем заголовок страницы и служебные блоки
            if ($el.is('h1.firstHeading, #siteSub, #contentSub, .mw-indicators, .mw-jump-link, .printfooter, .catlinks')) {
                return true;
            }
            var $cloned = cleanClone($el.clone());
            $cloned.find(SKIP_SELECTORS).remove();
            if ($cloned.is(SKIP_SELECTORS)) return true;
            $cloned.find('math').each(function () {
                var spoken = mathToSpeech($(this));
                if (spoken) {
                    $(this).replaceWith(document.createTextNode(' формула: ' + spoken + ' '));
                } else {
                    $(this).remove();
                }
            });
            var t = $cloned.text().replace(/\s+/g, ' ').trim();
            if (t) chunks.push(t);
            return true;
        });
         return chunks.join('\n');
         return chunks.join('\n');
     }
     }
Строка 168: Строка 226:
         }
         }


         // Находим заголовок: кнопка вставлена перед .mw-editsection внутри .mw-heading
         var text;
         var $heading = $(a).closest('.mw-heading, h1, h2, h3, h4, h5, h6');
        if ($(a).data('lead')) {
        if (!$heading.length) {
            text = buildLeadText();
             $heading = $(a).parent().parent();
         } else {
            var $heading = $(a).closest('.mw-heading, h1, h2, h3, h4, h5, h6');
            var $realHeader = $heading.is('.mw-heading')
                ? $heading.children('h1,h2,h3,h4,h5,h6')
                : $heading;
            var $start = $realHeader.next();
             var $stop = $start.nextAll('.mw-heading, h1, h2, h3, h4, h5, h6').first();
            text = $start.length
                ? buildSpeechText($start, $stop.length ? $stop : null)
                : '';
         }
         }
        // В 1.43 заголовок может быть обёрнут в <div class="mw-heading">
        var $realHeader = $heading.is('.mw-heading') ? $heading.children('h1,h2,h3,h4,h5,h6') : $heading;


        var text = buildSpeechText($realHeader.length ? $realHeader : $heading);
         if (!text) {
         if (!text) {
             mw.notify('Под этим заголовком нет текста для озвучки', { type: 'warn' });
             mw.notify('Под этим заголовком нет текста для озвучки', { type: 'warn' });
Строка 224: Строка 288:
         if (!$root.length) return;
         if (!$root.length) return;


         // Кнопка в нулевую секцию (преамбулу) — если есть текст до первого заголовка
         // --- кнопка преамбулы (нулевая секция) ---
         var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6').first();
         var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6, .mw-heading').first();
         var hasLead = false;
         var hasLead = false;
         $root.children().each(function () {
         $root.children().each(function () {
             if (this === $firstHeader[0]) return false;
             if ($firstHeader.length && this === $firstHeader[0]) return false;
             if ($(this).is('p, ul, ol, dl, table, blockquote') && $(this).text().trim()) {
             if ($(this).is('p, ul, ol, dl, table, blockquote') && $(this).text().trim()) {
                 hasLead = true; return false;
                 hasLead = true;
                return false;
             }
             }
             return true;
             return true;
         });
         });
         if (hasLead && !$root.find('.cyclo-tts-lead').length) {
         if (hasLead && !$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;"></div>');
             var $leadBtn = $('<a href="#" style="cursor:pointer;">🔊 озвучить преамбулу</a>');
             var $leadBtn = $('<a href="#" style="cursor:pointer;">🔊 озвучить преамбулу</a>')
            $leadBtn.on('click', function (e) {
                .data('lead', true);
                e.preventDefault();
            $leadBtn.on('click', onClick);
                // Временно подставляем фиктивный заголовок перед первым элементом
                var $fake = $('<h2 style="display:none"></h2>').insertBefore($root.children().first());
                onClick.call($leadBtn[0], { preventDefault: function () {}, currentTarget: $leadBtn[0] });
                $fake.remove();
            });
             $leadBar.append($leadBtn);
             $leadBar.append($leadBtn);
             $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);
Строка 265: Строка 326:
     mw.loader.using(['jquery'], function () {
     mw.loader.using(['jquery'], function () {
         $(function () {
         $(function () {
            // Vector 2022 может подгружать контент позже
             if (window.speechSynthesis) {
             if (window.speechSynthesis) {
                 addButtons();
                 addButtons();