Замечание: Возможно, после публикации вам придётся очистить кэш своего браузера, чтобы увидеть изменения.

  • Firefox / Safari: Удерживая клавишу Shift, нажмите на панели инструментов Обновить либо нажмите Ctrl+F5 или Ctrl+R (⌘+R на Mac)
  • Google Chrome: Нажмите Ctrl+Shift+R (⌘+Shift+R на Mac)
  • Edge: Удерживая Ctrl, нажмите Обновить либо нажмите Ctrl+F5
  • Opera: Нажмите Ctrl+F5.
/**
 * Speech Synthewiki — гаджет озвучки статей браузером пользователя
 * Версия 0.3.2 — MediaWiki 1.43; скины Vector 2022 / Vector 2010 / Monobook
 * Автор оригинала — Урахара (Циклопедия), CC BY-SA 4.0
 */
/* global mw, $ */

(function () {
    'use strict';

    var currentUtterance = null;
    var currentButton = null;
    var voicesReady = false;

    // ---------- служебные элементы, которые не озвучиваем ----------
    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',
        // наш UI
        '.cyclo-tts-start', '.cyclo-tts-lead',
        // правка секции: 1.43 + старый класс
        '.mw-editsection', '.editsection',
        // оглавление: Vector 2022, Vector 2010, Monobook
        '#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(',');

    // Селекторы, которые пропускаем целиком на уровне прямых детей контента
    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(',');

    // ---------- голоса ----------
    function getRussianVoice() {
        var voices = window.speechSynthesis.getVoices() || [];
        return voices.find(function (v) {
            return /^ru/i.test(v.lang) || /рус/i.test(v.name);
        }) || null;
    }

    function ensureVoices(cb) {
        if (voicesReady) { cb(); return; }
        var v = window.speechSynthesis.getVoices();
        if (v && v.length) { voicesReady = true; cb(); return; }
        var handler = function () {
            voicesReady = true;
            window.speechSynthesis.removeEventListener('voiceschanged', handler);
            cb();
        };
        window.speechSynthesis.addEventListener('voiceschanged', handler);
    }

    // ---------- очистка клона от мусора ----------
    function cleanClone(cloned) {
        cloned.find([
            '.thumb', '.thumbinner', '.thumbcaption', '.magnify',
            '.floatnone', '.floatleft', '.floatright',
            'ul.gallery', 'div.gallery', 'li.gallerybox', 'div.thumb',
            '.gallerycaption', 'sup.reference', '.metadata', '.noprint',
            'img', 'a.image', 'style', 'script'
        ].join(',')).remove();

        cloned.contents().each(function () {
            if (this.nodeType === 3) {
                if (/(Файл|File|Image|Изображение|Медиа):/i.test(this.nodeValue)) {
                    this.nodeValue = '';
                }
            } else if (this.nodeType === 1) {
                var $el = $(this);
                var href = $el.attr('href') || '';
                if ($el.is('a') && /\.(jpg|jpeg|png|gif|bmp|svg|webp|ogg|mp3|wav|pdf|djvu)(\?|$)/i.test(href)) {
                    $el.remove();
                } else if ($el.hasClass('image') || $el.hasClass('internal') || href.indexOf('Файл:') !== -1) {
                    $el.remove();
                }
            }
        });
        return cloned;
    }

    // ---------- MathML → речь ----------
    function mathToSpeech($math) {
        var $clone = $math.clone();
        $clone.find('annotation').remove(); // убираем TeX-дубль

        var parts = [];

        $clone.find('msqrt').each(function () {
            parts.push(' корень из ' + $(this).text().trim() + ' ');
            $(this).remove();
        });

        $clone.find('mfrac').each(function () {
            var $ch = $(this).children();
            parts.push(' дробь ' + $ch.eq(0).text().trim() + ' на ' + $ch.eq(1).text().trim() + ' ');
            $(this).remove();
        });

        $clone.find('msup').each(function () {
            var $ch = $(this).children();
            var base = $ch.eq(0).text().trim();
            var exp = $ch.eq(1).text().trim();
            if (exp === '2') parts.push(base + ' в квадрате ');
            else if (exp === '3') parts.push(base + ' в кубе ');
            else parts.push(base + ' в степени ' + exp + ' ');
            $(this).remove();
        });

        $clone.find('msub').each(function () {
            var $ch = $(this).children();
            parts.push($ch.eq(0).text().trim() + ' с индексом ' + $ch.eq(1).text().trim() + ' ');
            $(this).remove();
        });

        var rest = $clone.text().trim()
            .replace(/×/g, ' умножить ')
            .replace(/÷/g, ' разделить ')
            .replace(/≠/g, ' не равно ')
            .replace(/≈/g, ' приблизительно равно ')
            .replace(/≤/g, ' меньше или равно ')
            .replace(/≥/g, ' больше или равно ')
            .replace(/±/g, ' плюс минус ')
            .replace(/∞/g, ' бесконечность ')
            .replace(/√/g, ' корень из ')
            .replace(/π/g, ' пи ')
            .replace(/∑/g, ' сумма ')
            .replace(/∏/g, ' произведение ')
            .replace(/∫/g, ' интеграл ')
            .replace(/∂/g, ' частная производная ')
            .replace(/∇/g, ' набла ')
            .replace(/∈/g, ' принадлежит ')
            .replace(/∉/g, ' не принадлежит ')
            .replace(/∩/g, ' пересечение ')
            .replace(/∪/g, ' объединение ')
            .replace(/⊂/g, ' подмножество ')
            .replace(/⊃/g, ' надмножество ');
        if (rest) parts.push(rest);

        return parts.join(' ').trim();
    }

    // ---------- сбор текста секции между двумя заголовками ----------
    function buildSpeechText($startNode, $stopNode) {
        var chunks = [];
        var $node = $startNode;

        while ($node.length) {
            if ($stopNode && $node[0] === $stopNode[0]) break;
            if (!$stopNode && $node.is('h1, h2, h3, h4, h5, h6') && $node[0] !== $startNode[0]) break;
            if (!$stopNode && $node.is('.mw-heading')) break;

            var $cloned = cleanClone($node.clone());

            $cloned.find(SKIP_SELECTORS).remove();
            if ($cloned.is(SKIP_SELECTORS)) {
                $node = $node.next();
                continue;
            }

            $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);
            $node = $node.next();
        }
        return chunks.join('\n');
    }

    // ---------- сбор текста преамбулы ----------
    function buildLeadText() {
        var $root = $('#mw-content-text .mw-parser-output');
        if (!$root.length) $root = $('#mw-content-text');
        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);

            // Заголовок страницы, служебное, наш UI и TOC — пропускаем целиком
            if ($el.is(SKIP_TOP)) return true;
            if ($el.find('#toctitle, .toctitle').length) 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');
    }

    // ---------- обработчик клика ----------
    function onClick(event) {
        event.preventDefault();
        var a = event.currentTarget;

        // Повторный клик по активной кнопке — стоп
        if (currentButton === a && window.speechSynthesis.speaking) {
            window.speechSynthesis.cancel();
            $(a).text('озвучить');
            currentButton = null;
            currentUtterance = null;
            return;
        }

        var text;
        if ($(a).data('lead')) {
            text = buildLeadText();
        } 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();
            if (!$start.length) {
                // крайний случай: контент вложен в обёртку заголовка
                $start = $realHeader.parent().next();
            }
            var $stop = $start.nextAll('.mw-heading, h1, h2, h3, h4, h5, h6').first();
            text = $start.length
                ? buildSpeechText($start, $stop.length ? $stop : null)
                : '';
        }

        if (!text) {
            mw.notify('Под этим заголовком нет текста для озвучки', { type: 'warn' });
            return;
        }

        // Остановить предыдущее
        if (window.speechSynthesis.speaking) {
            window.speechSynthesis.cancel();
            if (currentButton) $(currentButton).text('озвучить');
        }

        currentUtterance = new SpeechSynthesisUtterance(text);
        currentUtterance.lang = 'ru-RU';
        currentUtterance.rate = 1.0;
        currentUtterance.pitch = 1.0;
        currentUtterance.volume = 1.0;

        ensureVoices(function () {
            var v = getRussianVoice();
            if (v) currentUtterance.voice = v;

            currentUtterance.onstart = function () {
                $(a).text('стоп');
                currentButton = a;
            };

            currentUtterance.onend = function () {
                $(a).text('озвучить');
                if (currentButton === a) { currentButton = null; currentUtterance = null; }
            };

            currentUtterance.onerror = function (ev) {
                if (ev.error !== 'interrupted' && ev.error !== 'canceled') {
                    $(a).text('озвучить');
                    if (currentButton === a) { currentButton = null; currentUtterance = null; }
                }
            };

            window.speechSynthesis.speak(currentUtterance);
        });
    }

    // ---------- вставка кнопок ----------
    function addButtons() {
        var $root = $('#mw-content-text .mw-parser-output');
        if (!$root.length) $root = $('#mw-content-text'); // fallback: Monobook / старые скины
        if (!$root.length) return;

        // --- кнопка преамбулы (нулевая секция) ---
        var $firstHeader = $root.find('h1, h2, h3, h4, h5, h6, .mw-heading').first();
        var hasLead = false;
        $root.children().each(function () {
            if ($firstHeader.length && this === $firstHeader[0]) return false;
            var $el = $(this);
            // наш UI и TOC не считаем контентом
            if ($el.is('.cyclo-tts-lead, .cyclo-tts-start, #toc, .toc, .vector-toc, .mw-toc, #mw-panel-toc')) return true;
            if ($el.is('p, ul, ol, dl, table, blockquote') && $el.text().trim()) {
                hasLead = true;
                return false;
            }
            return true;
        });

        if (hasLead && !$root.find('.cyclo-tts-lead').length) {
            var $leadBar = $('<div class="cyclo-tts-lead" style="margin:.5em 0;"></div>');
            var $leadBtn = $('<a href="#" style="cursor:pointer;">🔊 озвучить всё</a>')
                .data('lead', true);
            $leadBtn.on('click', onClick);
            $leadBar.append($leadBtn);
            $root.prepend($leadBar);
        }

        // --- кнопки у каждого заголовка ---
        $root.find('.mw-heading, h1, h2, h3, h4, h5, h6').each(function () {
            var $h = $(this);
            if ($h.hasClass('cyclo-tts-start')) return;

            // не вешаем на заголовок TOC (все скины)
            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;

            // правка секции: 1.43 + старый класс 2010/Monobook
            var $edit = $h.find('.mw-editsection, .editsection').first();
            if (!$edit.length) return;
            if ($edit.prev().hasClass('cyclo-tts-start')) return;

            var $span = $('<span class="mw-editsection cyclo-tts-start">[<a href="#" style="cursor:pointer;">озвучить</a>]</span> ');
            $span.on('click', 'a', onClick);
            $edit.before($span);
        });
    }

    // ---------- запуск ----------
    mw.loader.using(['jquery'], function () {
        $(function () {
            if (window.speechSynthesis) {
                addButtons();
            } else {
                console.warn('[Speech Synthewiki] Браузер не поддерживает speechSynthesis');
            }
        });
    });
})();