Skip to content

feat: Добавлена настройка "Язык субтитров по умолчанию"#1584

Open
I3eka wants to merge 5 commits intoilyhalight:devfrom
I3eka:feature/default-subtitles
Open

feat: Добавлена настройка "Язык субтитров по умолчанию"#1584
I3eka wants to merge 5 commits intoilyhalight:devfrom
I3eka:feature/default-subtitles

Conversation

@I3eka
Copy link

@I3eka I3eka commented Mar 8, 2026

Описание:

Описание изменений

Данный PR вносит изменения в раздел «Настройки субтитров», добавляя возможность выбора приоритетного языка для субтитров. Эта настройка позволяет автоматически применять выбранный язык при открытии видео, независимо от выбранного языка голосового перевода.

Мотивация

В текущей версии расширения, при использовании функций «Автоперевод видео» и «Субтитры при открытии», язык субтитров жестко привязан к целевому языку голосового перевода.

Такое поведение ограничивает удобство использования, особенно в сценариях изучения иностранных языков.
Пример сценария: Пользователь просматривает видео на английском языке и использует закадровую озвучку на своем родном языке для понимания сложного контекста, но при этом хочет видеть оригинальные английские субтитры для восприятия текста. Ранее для этого требовалось переключать язык субтитров вручную при каждом запуске видео.

Детали реализации

  1. Интерфейс: В меню настроек (раздел "Субтитры") добавлен выпадающий список «Язык субтитров по умолчанию».
  2. Логика работы:
    • При значении «Авто» (по умолчанию): сохраняется прежнее поведение, язык субтитров соответствует языку перевода.
    • При выборе конкретного языка: расширение игнорирует язык голосового перевода и при загрузке видео пытается найти и включить субтитры на выбранном пользователем языке.
  3. Хранилище: Добавлен новый параметр responseLanguageSubtitles в конфигурацию.
  4. Локализация:
    • Добавлены переводы для новой настройки.
    • Обновлены файлы hashes.json и типы TypeScript с помощью скрипта npm run localize в соответствии с CONTRIBUTING.md.

Скриншоты

image image

Тестирование

  • Проверена работоспособность на платформе YouTube.
  • Проверен режим «Авто» (функционал работает без изменений).
  • Проверен выбор конкретного языка (субтитры загружаются на выбранном языке, независимо от текущего языка озвучки).

Copilot AI review requested due to automatic review settings March 8, 2026 07:03
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR adds a new “Default subtitles language” setting to decouple subtitle language selection from the voice translation target language, improving usability for language-learning and similar scenarios.

Changes:

  • Introduces a new persisted config value: responseLanguageSubtitles (empty string = “Auto” / legacy behavior).
  • Adds a new subtitles-language select control to the Settings UI and wires it to storage/events.
  • Updates subtitles enabling/selection logic (and a subtitles cache validation check) to prefer the configured subtitles language.

Reviewed changes

Copilot reviewed 69 out of 69 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
src/videoHandler/modules/translation.ts Uses responseLanguageSubtitles when validating cached subtitles before caching translation results.
src/videoHandler/modules/subtitles.ts Enables subtitles using responseLanguageSubtitles as the target subtitle language (fallbacks to previous behavior).
src/videoHandler/modules/init.ts Adds responseLanguageSubtitles default value to initial storage read.
src/ui/views/settings.ts Adds the “Default subtitles language” select to the Subtitles settings section and persists it.
src/types/views/settings.ts Extends settings view event map with select:subtitlesLanguage.
src/types/storage.ts Adds storage key + StorageData.responseLanguageSubtitles.
src/types/localization.ts Adds VOTSubtitlesLanguage to localization phrase typings.
src/localization/locales/*.json Adds localized strings for VOTSubtitlesLanguage across locales.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment on lines +1073 to +1079
const targetSubtitleLang = this.data?.responseLanguageSubtitles || videoData.responseLanguage;
if (
!cachedSubs?.some(
(item) =>
item.source === "yandex" &&
item.translatedFromLanguage === videoData.detectedLanguage &&
item.language === videoData.responseLanguage,
item.language === targetSubtitleLang,
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

targetSubtitleLang can legitimately be set to the detected/original language (e.g. user wants original subtitles while voice translation is to another language). In that case the cache validation below will never match because it requires translatedFromLanguage === videoData.detectedLanguage, so subtitles cache gets deleted and this.subtitles cleared even though valid subtitles in targetSubtitleLang may exist. Consider relaxing the predicate to accept any subtitle track in targetSubtitleLang (or explicitly handle the targetSubtitleLang === detectedLanguage case), otherwise switching default subtitles language to the original language will cause unnecessary cache invalidation / subtitle resets.

Copilot uses AI. Check for mistakes.
Comment on lines +547 to +550
items:[
{
label: localizationProvider.get("langs.auto" as any),
value: "",
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Formatting: items:[ is inconsistent with the surrounding object literal style in this file (e.g. items: ...). Keeping the spacing consistent improves readability and reduces diffs from auto-formatters.

Copilot uses AI. Check for mistakes.
"select:translationTextService": [item: TranslateService];
"select:buttonPosition": [item: Position];
"select:menuLanguage": [item: LangOverride];
"select:subtitlesLanguage":[item: string];
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Type formatting: missing whitespace after the colon in the event key ("select:subtitlesLanguage":[...]). Align with the spacing used by the other entries in this map for consistency.

Copilot uses AI. Check for mistakes.
autoHideButtonDelay: number;
useAudioDownload: boolean;
compatVersion: CompatibilityVersion;
responseLanguageSubtitles: string;
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

responseLanguageSubtitles is typed as a plain string, which allows persisting invalid/unsupported language codes. Other language-related settings use stricter unions (e.g. LanguageSelectKey, ResponseLang). Consider typing this as "" | Exclude<LanguageSelectKey, "auto"> (or similar) to match the actual values stored by the Settings UI and to keep the setting type-safe across the codebase.

Copilot uses AI. Check for mistakes.
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 70 out of 70 changed files in this pull request and generated 3 comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment on lines +143 to +145
subtitlesDownloadFormatSelect?: Select<SubtitleFormat>;
subtitlesLanguageSelectLabel?: Label;
subtitlesLanguageSelect?: Select<string>;
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

subtitlesLanguageSelect is declared as Select<string>, but it's instantiated as Select<"" | Exclude<LanguageSelectKey, "auto">>. This loses type-safety for the setting value (and can become a TS incompatibility depending on Select's generic variance). Consider typing the field consistently as Select<"" | Exclude<LanguageSelectKey, "auto">> (or a shared alias) so bindPersistedSetting/events stay correctly typed.

Copilot uses AI. Check for mistakes.
Comment on lines +1063 to +1088
return (
targetSubtitleLang === videoData.detectedLanguage ||
item.translatedFromLanguage === videoData.detectedLanguage
);
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Subtitles cache invalidation uses a cache key built from videoData.responseLanguage, but validates cached entries against targetSubtitleLang (which may come from responseLanguageSubtitles). This mismatch can cause repeated cache deletions / refetching when the user sets a fixed subtitle language. Consider incorporating the effective subtitles target language into the subtitles cache key (and into loadSubtitles/callers), or changing the invalidation check to validate against the same language used to build subsCacheKey.

Copilot uses AI. Check for mistakes.
Comment on lines +1076 to +1088
!cachedSubs?.some((item) => {
if (
item.source !== "yandex" ||
item.language !== targetSubtitleLang
) {
return false;
}
// If user wants original subtitles (target == detected), accept it.
// Otherwise ensure it is translated from the correct source.
return (
targetSubtitleLang === videoData.detectedLanguage ||
item.translatedFromLanguage === videoData.detectedLanguage
);
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cache validation here only considers item.source === "yandex". With the new default subtitles language setting, a valid matching subtitle track might come from a site source (e.g., YouTube captions) and still satisfy the user's selected targetSubtitleLang. As written, the code will delete the subtitles cache even if a non-Yandex track matches the requested language. Consider broadening the predicate to accept any source that matches targetSubtitleLang (and only apply the translatedFromLanguage check when relevant).

Copilot uses AI. Check for mistakes.
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 70 out of 70 changed files in this pull request and generated 1 comment.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

Comment on lines +1064 to +1076
)
!cachedSubs?.some((item) => {
if (item.source !== "yandex" || item.language !== responseLang) {
return false;
Copy link

Copilot AI Mar 8, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

subsCacheKey is computed using this.videoData.responseLanguage, but the matching predicate now compares cached subtitle items against the responseLang argument. If videoData.responseLanguage can change while this translation is in-flight (e.g., user changes the target language in the UI), these two values can diverge and cause the code to delete the subtitles cache for a different language than the one being validated. Consider deriving both the cache key and the match check from the same stable pair for this request (e.g., requestLang/responseLang args or reqLang/resLang), rather than mixing mutable this.videoData state with the function parameter.

Copilot uses AI. Check for mistakes.
Copy link

Copilot AI left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 70 out of 70 changed files in this pull request and generated no new comments.


💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

You can also share your feedback on Copilot code review. Take the survey.

@I3eka I3eka changed the base branch from master to dev March 8, 2026 08:35
@I3eka I3eka force-pushed the feature/default-subtitles branch from ad1de1c to 9560c63 Compare March 8, 2026 08:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants