// ==UserScript== // @name Перевод Modrinth // @namespace http://tampermonkey.net/ // @version 2.8 // @license MIT // @description Перевод для Modrinth // @author MrVovchick // @match https://modrinth.com/* // @grant none // @downloadURL none // ==/UserScript== (function() { 'use strict'; const translations = { // ... (ваш существующий словарь переводов остаётся без изменений) 'The place for Minecraft': 'Место для Майнкрафта', 'mods': 'моды', 'plugins': 'плагины', 'data packs': 'дата-паки', 'shaders': 'шейдеры', 'resource packs': 'ресурс-паки', 'modpacks': 'модпаки', 'servers': 'серверы', 'Mods': 'Моды', ' Discover, play, and share Minecraft content through our open-source platform built for the community. ': 'Открывайте, играйте и делитесь контентом Майнкрафта с помощью нашей платформы с открытым исходным кодом, созданной для сообщества.', ' Discover ': ' Открыть ', ' Go to dashboard ': 'Перейти к панели инструментов', 'Discover content': 'Открыть контент', 'Resource Packs': 'Ресурс-паки', 'Data Packs': 'Дата-паки', 'Shaders': 'Шейдеры', 'Modpacks': 'Модпаки', 'Plugins': 'Плагины', 'Discover over 50,000 creations': 'Откройте для себя более 50 000 творений', ' From magical biomes to cursed dungeons, you can be sure to find content to bring your gameplay to the next level. ': 'От волшебных биомов до проклятых подземелий - вы обязательно найдете контент, который выведет ваш игровой процесс на новый уровень.', 'For Players': 'Для игроков', 'Find what you want, quickly and easily': 'Найдите то, что вам нужно, легко и быстро', 'Sort by': 'Сортировать по', 'Relevance': 'Актуальности', 'Downloads': 'Загрузкам', 'Follows': 'Подписчикам', 'Updated': 'Обновлениям', 'Newest': 'Новинкам', ' Modrinth\'s lightning-fast search and powerful filters let you find what you want as you type. ': ' Молниеносный поиск и мощные фильтры Modrinth позволят вам найти то, что вы хотите, по мере ввода текста. ', 'Notifications': 'Уведомления', 'Follow projects you love': 'Следите за проектами, которые вам нравятся', 'Get notified every time your favorite projects update and stay in the loop': 'Получайте уведомления о каждом обновлении ваших любимых проектов и будьте в курсе всех событий.', 'Play with your favorite launcher': 'Играйте в любимом лаунчере', ' Modrinth\'s open-source API lets launchers add deep integration with Modrinth. You can use Modrinth through ': ' API Modrinth с открытым исходным кодом позволяет лаунчеру осуществлять глубокую интеграцию с Modrinth. Вы можете использовать Modrinth через ', 'our own app': 'наше приложение', ' and some of the most popular launchers like ATLauncher, MultiMC, and Prism Launcher. ': ' и некоторые из самых популярных лаунчеров, таких как ATLauncher, MultiMC и Prism Launcher. ', 'For Creators': 'Для создателей', 'Share your content with the world': 'Поделитесь своим контентом со всем миром', ' Give an online home to your creations and reach a massive audience of dedicated players ': ' Дайте онлайн-доступ к своим творениям и охватите огромную аудиторию преданных игроков. ', 'Discovery': 'Открытия', ' Get your project discovered by thousands of users through search, our home page, Discord server, and more ways to come in the future! ': ' Пусть о вашем проекте узнают тысячи пользователей через поиск, нашу домашнюю страницу, сервер Discord и другие способы, которые появятся в будущем! ', 'Team Management': 'Управление командой', 'Invite your teammates and manage roles and permissions with ease': 'Приглашайте членов своей команды и легко управляйте ролями и разрешениями.', 'Monetization': 'Монетизация', 'Get paid ad revenue from your project pages and withdraw your funds at any time': 'Получайте доход от рекламы на страницах вашего проекта и выводите средства в любое время', 'Diverse Ecosystem': 'Разнообразная экосистема', ' Integrate with your build tools through Minotaur for automatic uploads right when you release a new version ': ' Интеграция с инструментами сборки через Minotaur для автоматической загрузки при выпуске новой версии. ', 'Data and Statistics': 'Данные и статистика', 'Get detailed reports on page views, download counts, and revenue': 'Получайте подробные отчеты о просмотрах страниц, количестве загрузок и доходах', 'Constantly Evolving': 'Постоянно развивается', ' Get the best modding experience possible with constant updates from the Modrinth team ': ' Получите лучший опыт моддинга благодаря постоянным обновлениям от команды Modrinth. ', ' Read more about ': ' Подробнее о ', ' Visit the blog ': 'Посетить блог', 'About': 'О сайте', 'Products': 'Продукты', 'Resources': 'Ресурсы', 'Legal': 'Юридическая тема', ' Host a server ': 'Хостинг сервера', 'Get Modrinth App': 'Получить Modrinth', ' New project ': ' Новый проект ', ' New collection ': ' Новая коллекция ', ' New organization ': ' Новая организация ', ' Profile ': ' Профиль ', ' Saved projects ': 'Сохранённые проекты', ' My серверы ': 'Мои серверы', ' My servers ': 'Мои серверы', ' My ': 'Мои ', ' Settings ': ' Настройки ', ' Projects ': 'Проекты', ' Organizations ': ' Организации ', ' Revenue ': 'Доходы', ' Analytics ': 'Аналитика', ' Sign out ': ' Выйти ', 'All': 'Всё', 'A Modrinth creator.': 'Создатель из Modrinth.', ' Manage projects': ' Управление проектами ', ' Copy ID': 'Копировать ID', ' Edit': 'Редактировать', 'Game version': 'Версия игры', 'Show all versions': 'Показать все версии', 'Loader': 'Загрузчик', 'Show fewer': 'Показать меньше', 'Show more': 'Показать больше', 'Categories': 'Категории', 'Adventure': 'Приключения', 'Cursed': 'Проклятие', 'Decoration': 'Украшения', 'Economy': 'Экономика', 'Equipment': 'Оборудование', 'Food': 'Еда', 'Game Mechanics': 'Игровая механика', 'Library': 'Библиотека', 'Magic': 'Магия', 'Management': 'Управление', 'Minigame': 'Мини-игра', 'Mobs': 'Мобы', 'Optimization': 'Оптимизация', 'Social': 'Социальный', 'Storage': 'Хранение', 'Technology': 'Технология', 'Transportation': 'Транспорт', 'Utility': 'Утилита', 'World Generation': 'Генерация мира', 'Environment': 'Среда', 'Client': 'Клиент', 'Server': 'Сервер', 'License': 'Лицензия', 'Open source': 'Открытый код', 'Resolutions': 'Разрешение', 'View: ': 'Вид: ', 'LiteЗагрузчик': 'LiteLoader', 'Combat': 'Бой', 'Modded': 'Модификация', 'Realistic': 'Реалистичность', 'Simplistic': 'Простота', 'Themed': 'Тематика', 'Tweaks': 'Твики', 'Vanilla-like': 'Ванилла', 'Features': 'Особенности', 'Audio': 'Аудио', 'Blocks': 'Блоки', 'Core': 'Основа-', 'Entities': 'Объекты', 'Fonts': 'Шрифты', 'GUI': 'Интерфейс', 'Items': 'Предметы', 'Locale': 'Локализация', 'Models': 'Модели', '8x or lower': '8x или ниже', '512x or higher': '512x или выше', 'Cartoon': 'Мультфильм', 'Fantasy': 'Фантастика', 'Semi-realistic': 'Полуреалистичный', 'Atmosphere': 'Атмосфера', 'Bloom': 'Блум', 'Colored Lighting': 'Цветное освещение', 'Foliage': 'Листва', 'Path Tracing': 'Трассировка пути', 'Reflections': 'Отражения', 'Shadows': 'Тени', 'Performance impact': 'Влияние на производительность', 'High': 'Высокое', 'Low': 'Среднее', 'Medium': 'Минимальное', 'Potato': 'Незаметное', 'Screenshot': 'Скриншот', 'Vanilla': 'Ванилла', 'Platform': 'Платформа', 'Challenging': 'Вызов', 'Kitchen Sink': 'Кухонная мойка', 'Lightweight': 'Лёгкий', 'Multiplayer': 'Мультиплеер', 'Quests': 'Квесты', ' Download Modrinth ': ' Скачать Modrinth ', ' The Modrinth App is a unique, open source launcher that allows you to play your favorite mods, and keep them up to date, all in one neat little package. ': ' Приложение Modrinth - это уникальный лаунчер с открытым исходным кодом, который позволяет играть в любимые моды и поддерживать их в актуальном состоянии, и все это в одном небольшом пакете.', ' Download the Modrinth App ': ' Загрузить приложение Modrinth ', ' More Download Options ': 'Другие варианты загрузки', ' Unlike any launcher ': ' В отличие от любой другого лаунчера, ', ' you\'ve used before ': 'который вы уже использовали', 'Installed': 'Скачанные', ' App for Windows': ' для Windows', 'Mod management': 'Управление модами', ' Modrinth makes it easy to manage all your mods in one place. You can install, uninstall, and update mods with a single click. ': ' Modrinth позволяет легко управлять всеми вашими модами в одном месте. Вы можете устанавливать, удалять и обновлять моды одним щелчком мыши. ', 'Share Modpacks': 'Поделитесь модпаками', ' Build, share, and play modpacks with any of the thousands of mods and modpacks hosted here on Modrinth. ': ' Создавайте, делитесь и играйте в модпаки с любым из тысяч модов и модпаков, размещенных здесь, на Modrinth. ', 'Performant': 'Производительность', ' The Modrinth App performs better than many of the leading mod managers, using just 150mb of RAM! ': ' Приложение Modrinth работает лучше многих ведущих менеджеров модов, используя всего 150 Мб оперативной памяти! ', 'Play with your favorite mods': 'Играйте с любимыми модами', 'Use the Modrinth App to download and play with your favorite mods and modpacks.': 'Используйте приложение приложение Modrinth, чтобы загружать и играть с любимыми модами и модпаками.', 'Website Integration': 'Интеграция сайта', ' The Modrinth App is fully integrated with the website, so you can access all your favorite projects from the app! ': ' Приложение Modrinth полностью интегрировано с сайтом, так что вы можете получить доступ ко всем своим любимым проектам из приложения! ', 'Name': 'Имя', 'Version': 'Версия', 'Actions': 'Действия', 'Download options': 'Варианты загрузки', 'Download the Modrinth App': 'Скачать приложение Modrinth', ' Our desktop app is available across all platforms, ': ' Наше настольное приложение доступно для всех платформ, ', ' choose your desired version. ': ' выберите нужную версию. ', 'Offline mode': 'Оффлайн режим', 'Follow projects': 'Следите за проектами', 'Search mods': 'Поиск модов', 'Search resource packs': 'Поиск ресурс-паков', 'Search datapacks': 'Поиск дата-паков', 'Search shaders': 'Поиск шейдеров', 'Search modpacks': 'Поиск модпаков', 'Search plugins': 'Поиск плагинов', 'Gallery view': 'Вид галереи', ' Download ': 'Скачать', 'Compatibility': 'Совместимость', 'Platforms': 'Платформы', 'Links': 'Ссылки', 'Creators': 'Создатели', 'Details': 'Детали', 'Save': 'Сохранить', 'Report': 'Репорт', 'Follow': 'Подписаться', 'More options': 'Дополнительные опции', 'Supported environments': 'Поддерживаемые среды', 'Profile information': 'Информация о профиле', 'Your profile information is publicly viewable on Modrinth and through the ': 'Информация о вашем профиле доступна для публичного просмотра на Modrinth и через ', ' Upload image ': ' Загрузить изображение ', 'Profile picture': 'Изображение профиля', 'Username': 'Имя пользователя', 'A unique case-insensitive name to identify your profile.': 'Уникальное имя, не зависящее от регистра, для идентификации вашего профиля.', 'Bio': 'Биография', 'A short description to tell everyone a little bit about you.': 'Краткое описание, которое расскажет о вас немного.', ' Visit your profile': ' Посетите свой профиль', ' Save changes': 'Сохранить изменения ', }; // Функция для проверки границ слова function isWholeWord(text, word, index) { const before = index > 0 ? text[index - 1] : ''; const after = index + word.length < text.length ? text[index + word.length] : ''; const wordBoundaryRegex = /[^a-zA-Zа-яА-Я0-9]/; // Регулярное выражение для границ слова return ( (index === 0 || wordBoundaryRegex.test(before)) && (index + word.length === text.length || wordBoundaryRegex.test(after)) ); } function translateText(node) { // Обработка текстовых узлов с частичным совпадением if (node.nodeType === Node.TEXT_NODE) { let text = node.textContent; let newText = text; for (const [en, ru] of Object.entries(translations)) { const regex = new RegExp(en.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'); let match; while ((match = regex.exec(text)) !== null) { if (isWholeWord(text, en, match.index)) { newText = newText.substring(0, match.index) + ru + newText.substring(match.index + en.length); // Обновляем индекс после замены regex.lastIndex = match.index + ru.length; } } } if (newText !== text) { node.textContent = newText; } } // Обработка элементов else if (node.nodeType === Node.ELEMENT_NODE) { // Обработка атрибутов title и placeholder ['title', 'placeholder'].forEach(attr => { if (node.hasAttribute(attr)) { let value = node.getAttribute(attr); let newValue = value; for (const [en, ru] of Object.entries(translations)) { const regex = new RegExp(en.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'); let match; while ((match = regex.exec(value)) !== null) { if (isWholeWord(value, en, match.index)) { newValue = newValue.substring(0, match.index) + ru + newValue.substring(match.index + en.length); // Обновляем индекс после замены regex.lastIndex = match.index + ru.length; } } } if (newValue !== value) { node.setAttribute(attr, newValue); } } }); // Специальная обработка для заголовка if (node.classList && node.classList.contains('main-header')) { const spans = node.querySelectorAll('span'); spans.forEach(span => { let html = span.innerHTML; let newHtml = html; for (const [en, ru] of Object.entries(translations)) { const regex = new RegExp(en.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'); let match; while ((match = regex.exec(html)) !== null) { // Проверяем, что это отдельное слово (не часть другого слова) const before = html.substring(0, match.index); const after = html.substring(match.index + en.length); const beforeChar = match.index > 0 ? html[match.index - 1] : ''; const afterChar = match.index + en.length < html.length ? html[match.index + en.length] : ''; const wordBoundaryRegex = /[^a-zA-Zа-яА-Я0-9]/; if ((match.index === 0 || wordBoundaryRegex.test(beforeChar)) && (match.index + en.length === html.length || wordBoundaryRegex.test(afterChar))) { newHtml = before + ru + after; // Обновляем html для следующей итерации html = newHtml; // Обновляем индекс после замены regex.lastIndex = match.index + ru.length; } } } if (newHtml !== html) { span.innerHTML = newHtml; } }); } // Рекурсивная обработка дочерних элементов node.childNodes.forEach(translateText); } } function translateDocument() { translateText(document.body); // Специальная обработка для анимированного заголовка const header = document.querySelector('.main-header'); if (header) { let html = header.innerHTML; let newHtml = html; for (const [en, ru] of Object.entries(translations)) { const regex = new RegExp(en.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'g'); let match; while ((match = regex.exec(html)) !== null) { // Проверяем, что это отдельное слово (не часть другого слова) const before = html.substring(0, match.index); const after = html.substring(match.index + en.length); const beforeChar = match.index > 0 ? html[match.index - 1] : ''; const afterChar = match.index + en.length < html.length ? html[match.index + en.length] : ''; const wordBoundaryRegex = /[^a-zA-Zа-яА-Я0-9]/; if ((match.index === 0 || wordBoundaryRegex.test(beforeChar)) && (match.index + en.length === html.length || wordBoundaryRegex.test(afterChar))) { newHtml = before + ru + after; // Обновляем html для следующей итерации html = newHtml; // Обновляем индекс после замены regex.lastIndex = match.index + ru.length; } } } if (newHtml !== html) { header.innerHTML = newHtml; } } } const observer = new MutationObserver(function(mutations) { mutations.forEach(function(mutation) { mutation.addedNodes.forEach(function(node) { if (node.nodeType === Node.ELEMENT_NODE) { translateText(node); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); // Запускаем перевод после небольшой задержки, чтобы страница успела загрузиться setTimeout(translateDocument, 1000); })();