Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions IMPLEMENTATION_PLAN.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,17 @@
# IMPLEMENTATION PLAN — WebObsidian

## Consistent English defaults — 2026-11-03

- [x] Remove Russian PDF defaults and browser-language editor fallbacks. Localize
remaining hardcoded PDF file actions and external-change notices. Verify fresh
startup/reset in a Russian browser, imported Russian text, and catalogue coverage.

Verification — 2026-11-03. All 521 web tests and 391 server tests passed,
along with full typecheck, production build and integration smoke. Fresh/reset
PDF controls and missing-heading notices use English in a ru-RU browser.
Explicit Russian import updates existing controls and reset restores English.
The authored Russian import file now covers all 975 catalogue entries.

## Browser language packs — 2026-11-03

- [x] Add an English UI catalog, compatible .txt import, blank template download,
Expand Down
7 changes: 5 additions & 2 deletions PRD.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,11 @@ is saved in the authenticated server settings and shared by browsers of this
WebObsidian instance. A local cache supplies startup/offline labels. Imports validate parameters and preserve
the current pack on failure. Compatible strings update React and existing editor
widgets immediately. Document names, text, command IDs and saved custom labels
retain their literal values. Existing browser-language editor messages and PDF
defaults are supported until a pack is chosen. Public server-rendered pages,
retain their literal values. A fresh installation and an explicit language reset
use English throughout the application, including PDF controls, file menus,
external-change notices and editor messages, regardless of browser language.
Imported language packs provide translated strings with English fallbacks.
Public server-rendered pages,
native Electron menus and third-party plugin strings are outside this first
version. Users obtain official dictionaries themselves and explicitly upload
their chosen file. Successful imports save only compatible strings on the server.
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,8 @@ stack runs from a single `docker compose up`.

Open **Settings → Language** to import a UTF-8 `.txt` language file or download a
blank template. The selected translation is saved on the server and shared by
your browsers. Missing translations use the app's English text.
your browsers. Fresh installations and language resets use English regardless
of browser language. Missing translations use the app's English text.

This fork provides an independently authored Russian translation for manual import.
[Download the Russian language file](translations/ru.txt).
Expand Down
2 changes: 1 addition & 1 deletion docs/superpowers/plans/2026-11-03-language-packs.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@

- [x] В `web/src/lib/i18n/runtime.ts` предоставить функцию `t(key, params?)` для обычного TypeScript и подписку для React. Один источник состояния обслуживает компоненты и DOM-виджеты. Для отсутствующего перевода использовать английскую строку из каталога. Параметры подставлять как текст. Для сообщений с количеством явно проверить выбор поддерживаемых словоформ, в том числе поведение при частичном пакете.
- [x] Сохранять только применимые строки, версию формата и сведения об активном пакете одной записью в локальном хранилище браузера. Прочитать её до первого рендера в `web/src/main.tsx`. Предусмотреть повторный импорт и возврат к стандартному языку с удалением пакета. При повреждённой сохранённой записи приложение открывается. Если запись нового пакета не удалась, оставить прежний и показать ошибку.
- [x] В `web/tests/languageRuntime.test.ts` проверить первый запуск, повторную загрузку, сброс, ошибку записи и замену пакета A пакетом B. Для нынешних русскоязычных сообщений предпросмотра сохранить поведение до первого явного выбора языка. Проверить отдельно режим по умолчанию и английский резерв для неполного импортированного пакета.
- [x] Проверить первый запуск, повторную загрузку, сброс, ошибку записи и замену пакета A пакетом B. По уточнению пользователя новая установка и сброс языка используют английский, включая сообщения редактора и PDF, независимо от языка браузера. Русский появляется после явного импорта. Проверить отдельно неполный импортированный пакет и английский резерв.

## 4. Настройки и первый рабочий сценарий

Expand Down
92 changes: 92 additions & 0 deletions translations/ru.txt
Original file line number Diff line number Diff line change
Expand Up @@ -3809,3 +3809,95 @@ translation=Вы используете
[webobsidian.your-webobsidian-login-password-5aa6d5]
original=Your WebObsidian login password.
translation=Ваш пароль для входа в WebObsidian.

[webobsidian.rename-pdf]
original=Rename PDF
translation=Переименовать PDF

[webobsidian.new-name]
original=New name
translation=Новое имя

[webobsidian.rename]
original=Rename
translation=Переименовать

[webobsidian.file-name-without-path]
original=Enter a file name without a path
translation=Введите имя файла без пути

[webobsidian.rename-file-failed]
original=Could not rename file
translation=Не удалось переименовать

[webobsidian.pdf-not-found]
original=PDF not found
translation=PDF не найден

[webobsidian.add-bookmark]
original=Add bookmark…
translation=Добавить в закладки...

[webobsidian.vault-relative-path]
original=Vault-relative path
translation=Путь от корня хранилища

[webobsidian.browser-url]
original=Browser URL
translation=Ссылка в браузере

[webobsidian.open-default-application]
original=Open in default application
translation=Открыть в приложении по умолчанию

[webobsidian.os-command-unavailable]
original=This operating-system command is unavailable in the browser
translation=Команда операционной системы недоступна из браузера

[webobsidian.show-system-explorer]
original=Show in system file explorer
translation=Показать в Проводнике

[webobsidian.server-file-unavailable-in-explorer]
original=Your computer’s file explorer cannot access a server file
translation=Проводник на вашем компьютере недоступен для серверного файла

[webobsidian.reveal-file]
original=Reveal in file explorer
translation=Показать в файловом менеджере

[webobsidian.external-text-changed]
original=The text changed during the check. Select “Compare changes” again.
translation=Текст изменился во время проверки. Нажмите «Сравнить изменения» ещё раз.

[webobsidian.external-local-edits]
original=Local edits were made. Compare changes before reloading.
translation=Появились локальные правки. Сравните изменения перед обновлением.

[webobsidian.external-reload-failed]
original=Could not load the note. Check the connection and try again.
translation=Не удалось загрузить статью. Проверьте соединение и повторите попытку.

[webobsidian.external-file-changed]
original=The file changed outside this browser.
translation=Файл изменён вне браузера.

[webobsidian.external-compare-versions]
original= You have local edits. Compare the versions.
translation= У вас есть локальные правки — сравните версии.

[webobsidian.external-reload-hint]
original= Reload the note to see the changes.
translation= Обновите статью, чтобы увидеть изменения.

[webobsidian.external-checking]
original=Checking…
translation=Проверка…

[webobsidian.external-compare]
original=Compare changes
translation=Сравнить изменения

[webobsidian.external-reload]
original=Reload note
translation=Обновить статью
12 changes: 7 additions & 5 deletions web/src/components/ExternalNoteNotice.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import {t as uiText,useLanguage} from '../lib/i18n/runtime';
import { useEffect, useRef, useState } from 'react';
import { api } from '../lib/api';
import { acceptResolvedDocument, documentSessions, draftScopeEpoch, isDraftScopeCurrent, useStore } from '../lib/store';
Expand All @@ -6,6 +7,7 @@ import ConflictResolver from './ConflictResolver';

/** Notify about a new server version without replacing the reader's open text. */
export default function ExternalNoteNotice() {
useLanguage();
const path = useStore(s => s.activePath);
const dirty = useStore(s => s.dirty);
const [changedPath, setChangedPath] = useState<string | null>(null);
Expand Down Expand Up @@ -79,7 +81,7 @@ export default function ExternalNoteNotice() {
const comparison = await loadConflict(session.record());
if (!current()) return;
if (session.revision !== revision || session.baseVersion !== version) {
setError('Текст изменился во время проверки. Нажмите «Сравнить изменения» ещё раз.');
setError(uiText("webobsidian.external-text-changed"));
return;
}
setConflict(comparison);
Expand All @@ -90,15 +92,15 @@ export default function ExternalNoteNotice() {
if (!current()) return;
if (session.revision !== revision || session.baseVersion !== version || useStore.getState().dirty ||
session.state !== 'saved') {
setError('Появились локальные правки. Сравните изменения перед обновлением.');
setError(uiText("webobsidian.external-local-edits"));
return;
}
if (!remote.version) throw new Error('Missing content version');
acceptResolvedDocument(path, remote.content, remote.version);
setChangedPath(null);
}
} catch {
if (current()) setError('Не удалось загрузить статью. Проверьте соединение и повторите попытку.');
if (current()) setError(uiText("webobsidian.external-reload-failed"));
} finally {
busyRef.current = false; setBusy(false);
}
Expand All @@ -107,9 +109,9 @@ export default function ExternalNoteNotice() {
if (!path || changedPath !== path) return null;
return <>
<div className="external-note-notice" role="status">
<span>Файл изменён вне браузера.{localChanges ? ' У вас есть локальные правки — сравните версии.' : ' Обновите статью, чтобы увидеть изменения.'}</span>
<span>{uiText("webobsidian.external-file-changed")}{localChanges ? uiText("webobsidian.external-compare-versions") : uiText("webobsidian.external-reload-hint")}</span>
<button className="btn secondary" disabled={busy} onClick={() => void refresh()}>
{busy ? 'Проверка…' : localChanges ? 'Сравнить изменения' : 'Обновить статью'}
{busy ? uiText("webobsidian.external-checking") : localChanges ? uiText("webobsidian.external-compare") : uiText("webobsidian.external-reload")}
</button>
{error && <span role="alert">{error}</span>}
</div>
Expand Down
25 changes: 24 additions & 1 deletion web/src/lib/i18n/catalog.ts
Original file line number Diff line number Diff line change
Expand Up @@ -951,5 +951,28 @@ export const catalog: Record<string,string> = {
"webobsidian.could-not-save-settings-7768c8": "Could not save settings",
"webobsidian.file-exceeds-the-10-mib-preview-limit-9ab369": "File exceeds the 10 MiB preview limit.",
"webobsidian.this-file-contains-binary-data-23c5d8": "This file contains binary data.",
"webobsidian.upload-failed-ad0d06": "Upload failed"
"webobsidian.upload-failed-ad0d06": "Upload failed",
"webobsidian.rename-pdf": "Rename PDF",
"webobsidian.new-name": "New name",
"webobsidian.rename": "Rename",
"webobsidian.file-name-without-path": "Enter a file name without a path",
"webobsidian.rename-file-failed": "Could not rename file",
"webobsidian.pdf-not-found": "PDF not found",
"webobsidian.add-bookmark": "Add bookmark…",
"webobsidian.vault-relative-path": "Vault-relative path",
"webobsidian.browser-url": "Browser URL",
"webobsidian.open-default-application": "Open in default application",
"webobsidian.os-command-unavailable": "This operating-system command is unavailable in the browser",
"webobsidian.show-system-explorer": "Show in system file explorer",
"webobsidian.server-file-unavailable-in-explorer": "Your computer’s file explorer cannot access a server file",
"webobsidian.reveal-file": "Reveal in file explorer",
"webobsidian.external-text-changed": "The text changed during the check. Select “Compare changes” again.",
"webobsidian.external-local-edits": "Local edits were made. Compare changes before reloading.",
"webobsidian.external-reload-failed": "Could not load the note. Check the connection and try again.",
"webobsidian.external-file-changed": "The file changed outside this browser.",
"webobsidian.external-compare-versions": " You have local edits. Compare the versions.",
"webobsidian.external-reload-hint": " Reload the note to see the changes.",
"webobsidian.external-checking": "Checking…",
"webobsidian.external-compare": "Compare changes",
"webobsidian.external-reload": "Reload note"
};
6 changes: 3 additions & 3 deletions web/src/lib/i18n/pdfLabels.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import {getLanguageState,t,setLocalizedText} from './runtime';
import {t,setLocalizedText} from './runtime';
const keys: Record<string,string> = {
"Управление PDF": "webobsidian.pdf-fcf7c01b99",
"Свернуть/развернуть боковую панель": "webobsidian.pdf-8b9b1bbd66",
Expand Down Expand Up @@ -30,10 +30,10 @@ const keys: Record<string,string> = {
"Две страницы (чётные)": "webobsidian.pdf-012f37de0b",
"Адаптировать к теме": "webobsidian.pdf-229344e7a2"
};
export function pdfLabel(source: string) {return getLanguageState().name && keys[source] ? t(keys[source]) : source;}
export function pdfLabel(source: string) {return keys[source] ? t(keys[source]) : source;}
export function bindPdfLabel(node: Node, source: string, field: string) {
const original = Object.hasOwn(keys,source) ? source : Object.keys(keys).find(label => t(keys[label]) === source);
if (original) setLocalizedText(node,keys[original],{},field,original,true);
if (original) setLocalizedText(node,keys[original],{},field);
else if (field === 'textContent') node.textContent=source;
else if (node instanceof Element) node.setAttribute(field,source);
}
4 changes: 2 additions & 2 deletions web/src/lib/i18n/runtime.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ export function t(key: string, params: Record<string, string | number | undefine
return text.replace(/\{\{\s*([^{}]+?)\s*\}\}/g, (match, name) =>
Object.hasOwn(params, name) ? String(params[name]) : match);
}
export function setLocalizedText(node: Node, key: string, params: Record<string, string | number | undefined | null> = {}, field = 'textContent', russian?: string, preserveDefault = false) {
export function setLocalizedText(node: Node, key: string, params: Record<string, string | number | undefined | null> = {}, field = 'textContent') {
// Bind the text leaf so subsequent updates preserve controls appended by widgets.
if (field === 'textContent' && node.nodeType !== 3 && node.ownerDocument) {
const text = node.ownerDocument.createTextNode('');
Expand All @@ -78,7 +78,7 @@ export function setLocalizedText(node: Node, key: string, params: Record<string,
const update = () => {
const target = ref.deref();
if (!target) return;
const value = russian && !state.name && (preserveDefault || typeof navigator !== 'undefined' && /^ru(?:-|$)/i.test(navigator.language)) ? russian : t(key, params);
const value = t(key, params);
if (field !== 'textContent' && target instanceof Element) target.setAttribute(field, value);
else target.textContent = value;
};
Expand Down
Loading
Loading