diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index 85bda44e..6d39fda9 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -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, diff --git a/PRD.md b/PRD.md index 8b5a28f3..3d26fd07 100644 --- a/PRD.md +++ b/PRD.md @@ -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. diff --git a/README.md b/README.md index f55eecc2..4fa95789 100644 --- a/README.md +++ b/README.md @@ -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). diff --git a/docs/superpowers/plans/2026-11-03-language-packs.md b/docs/superpowers/plans/2026-11-03-language-packs.md index 163a5ce1..e45042c6 100644 --- a/docs/superpowers/plans/2026-11-03-language-packs.md +++ b/docs/superpowers/plans/2026-11-03-language-packs.md @@ -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. Настройки и первый рабочий сценарий diff --git a/translations/ru.txt b/translations/ru.txt index 3807c4cc..9ee042e4 100644 --- a/translations/ru.txt +++ b/translations/ru.txt @@ -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=Обновить статью diff --git a/web/src/components/ExternalNoteNotice.tsx b/web/src/components/ExternalNoteNotice.tsx index 10743bf7..b5d93e11 100644 --- a/web/src/components/ExternalNoteNotice.tsx +++ b/web/src/components/ExternalNoteNotice.tsx @@ -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'; @@ -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(null); @@ -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); @@ -90,7 +92,7 @@ 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'); @@ -98,7 +100,7 @@ export default function ExternalNoteNotice() { setChangedPath(null); } } catch { - if (current()) setError('Не удалось загрузить статью. Проверьте соединение и повторите попытку.'); + if (current()) setError(uiText("webobsidian.external-reload-failed")); } finally { busyRef.current = false; setBusy(false); } @@ -107,9 +109,9 @@ export default function ExternalNoteNotice() { if (!path || changedPath !== path) return null; return <>
- Файл изменён вне браузера.{localChanges ? ' У вас есть локальные правки — сравните версии.' : ' Обновите статью, чтобы увидеть изменения.'} + {uiText("webobsidian.external-file-changed")}{localChanges ? uiText("webobsidian.external-compare-versions") : uiText("webobsidian.external-reload-hint")} {error && {error}}
diff --git a/web/src/lib/i18n/catalog.ts b/web/src/lib/i18n/catalog.ts index a4d0c790..4e20e8c5 100644 --- a/web/src/lib/i18n/catalog.ts +++ b/web/src/lib/i18n/catalog.ts @@ -951,5 +951,28 @@ export const catalog: Record = { "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" }; diff --git a/web/src/lib/i18n/pdfLabels.ts b/web/src/lib/i18n/pdfLabels.ts index c5853ee3..a70f3b9e 100644 --- a/web/src/lib/i18n/pdfLabels.ts +++ b/web/src/lib/i18n/pdfLabels.ts @@ -1,4 +1,4 @@ -import {getLanguageState,t,setLocalizedText} from './runtime'; +import {t,setLocalizedText} from './runtime'; const keys: Record = { "Управление PDF": "webobsidian.pdf-fcf7c01b99", "Свернуть/развернуть боковую панель": "webobsidian.pdf-8b9b1bbd66", @@ -30,10 +30,10 @@ const keys: Record = { "Две страницы (чётные)": "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); } diff --git a/web/src/lib/i18n/runtime.ts b/web/src/lib/i18n/runtime.ts index 92e59a5d..b7cac5c7 100644 --- a/web/src/lib/i18n/runtime.ts +++ b/web/src/lib/i18n/runtime.ts @@ -64,7 +64,7 @@ export function t(key: string, params: Record Object.hasOwn(params, name) ? String(params[name]) : match); } -export function setLocalizedText(node: Node, key: string, params: Record = {}, field = 'textContent', russian?: string, preserveDefault = false) { +export function setLocalizedText(node: Node, key: string, params: Record = {}, 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(''); @@ -78,7 +78,7 @@ export function setLocalizedText(node: Node, key: string, params: Record { 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; }; diff --git a/web/src/lib/livePreview.ts b/web/src/lib/livePreview.ts index 02d954d6..65661215 100644 --- a/web/src/lib/livePreview.ts +++ b/web/src/lib/livePreview.ts @@ -635,7 +635,7 @@ export function setLivePreviewNoteEmbedProvider(fn: (target: string,kind?:'wiki' function embedNotFound(el: HTMLElement, target: string) { el.classList.add('cm-embed-missing'); - setLocalizedText(el, "webobsidian.missing-file", {name:target}, "textContent", `«${target}» не может быть найдена.`); + setLocalizedText(el, "webobsidian.missing-file", {name:target}, "textContent"); } class CanvasEmbedWidget extends WidgetType{ @@ -678,7 +678,7 @@ class NoteEmbedWidget extends WidgetType { if (!res) { content.remove(); const at=this.target.indexOf('#'),fragment=at<0?'':this.target.slice(at+1),name=title.textContent||notePath.replace(/\.(md|markdown)$/i,'').split('/').pop()||''; - if(fragment){setLocalizedText(title,"webobsidian.missing-fragment",{fragment,name},"textContent",`Не удалось найти «${fragment}» в ${name}`);box.append(title)} + if(fragment){setLocalizedText(title,"webobsidian.missing-fragment",{fragment,name},"textContent");box.append(title)} box.classList.add('is-unresolved');return; } content.innerHTML = res.html; // sanitized upstream (rehype-sanitize) @@ -1755,8 +1755,7 @@ class FrontmatterWidget extends WidgetType { const header = document.createElement('div'); header.className = 'cm-props-header'; - const ru=/^ru(?:-|$)/i.test(navigator.language); - setLocalizedText(header,"webobsidian.properties-bc6c88",{},"textContent","Свойства"); + setLocalizedText(header,"webobsidian.properties-bc6c88",{},"textContent"); header.setAttribute('role','button');header.tabIndex=0;header.setAttribute('aria-expanded','true'); const toggleProperties=()=>{const collapsed=box.classList.toggle('is-collapsed');header.setAttribute('aria-expanded',String(!collapsed));view.requestMeasure()}; header.onclick=toggleProperties;header.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();toggleProperties()}}; @@ -1899,9 +1898,9 @@ class FrontmatterWidget extends WidgetType { commitChange(); }); const wrap=document.createElement('span');wrap.className='prop-date-wrap'; - const calendar=document.createElement('button');calendar.type='button';calendar.className='prop-date-calendar';calendar.innerHTML=propertyIconSvg(dt);setLocalizedText(calendar,'webobsidian.choose-date',{},'aria-label','Выбрать дату');calendar.disabled=this.ro; + const calendar=document.createElement('button');calendar.type='button';calendar.className='prop-date-calendar';calendar.innerHTML=propertyIconSvg(dt);setLocalizedText(calendar,'webobsidian.choose-date',{},'aria-label');calendar.disabled=this.ro; calendar.onclick=e=>{e.preventDefault();try{inp.showPicker()}catch{inp.focus()}}; - const link=document.createElement('button');link.type='button';link.className='prop-date-link';link.innerHTML=propertyIconSvg('link');setLocalizedText(link,'webobsidian.open-date-note',{},'aria-label','Открыть заметку даты');link.onclick=e=>{e.preventDefault();if(inp.value)openLink(inp.value.slice(0,10))}; + const link=document.createElement('button');link.type='button';link.className='prop-date-link';link.innerHTML=propertyIconSvg('link');setLocalizedText(link,'webobsidian.open-date-note',{},'aria-label');link.onclick=e=>{e.preventDefault();if(inp.value)openLink(inp.value.slice(0,10))}; wrap.append(calendar,inp,link);return wrap; } // text (default) @@ -2074,7 +2073,7 @@ class FrontmatterWidget extends WidgetType { }); const x = document.createElement('span'); x.className = 'prop-pill-x'; - x.innerHTML=propertyIconSvg('close');x.setAttribute('role','button');setLocalizedText(x,'webobsidian.remove-value',{},'aria-label','Удалить значение'); + x.innerHTML=propertyIconSvg('close');x.setAttribute('role','button');setLocalizedText(x,'webobsidian.remove-value',{},'aria-label'); x.addEventListener('mousedown', (e) => { e.preventDefault(); mutate((ps) => { @@ -2089,7 +2088,7 @@ class FrontmatterWidget extends WidgetType { } const add = document.createElement('span'); add.className = 'prop-pill-add'; - add.textContent = '';add.tabIndex=0;add.setAttribute('role','button');setLocalizedText(add,'webobsidian.add-item',{},'aria-label','Добавить значение'); + add.textContent = '';add.tabIndex=0;add.setAttribute('role','button');setLocalizedText(add,'webobsidian.add-item',{},'aria-label'); setLocalizedText(add, "plugins.bases.command-add-item", {}, "title"); add.addEventListener('mousedown', (e) => { e.preventDefault(); @@ -2116,7 +2115,7 @@ class FrontmatterWidget extends WidgetType { const addBtn = document.createElement('div'); addBtn.className = 'cm-props-add'; - setLocalizedText(addBtn,"webobsidian.-add-property-e2852e",{},"textContent","+ Добавить свойство"); + setLocalizedText(addBtn,"webobsidian.-add-property-e2852e",{},"textContent"); // Add a property with a name-suggester dropdown (existing vault keys), like Obsidian. const startAdd = async () => { diff --git a/web/src/lib/pdfFileActions.ts b/web/src/lib/pdfFileActions.ts index 29ae8f1d..5587243d 100644 --- a/web/src/lib/pdfFileActions.ts +++ b/web/src/lib/pdfFileActions.ts @@ -1,3 +1,4 @@ +import {t as uiText} from './i18n/runtime'; import {api} from './api'; import {useStore} from './store'; import {findNode} from './tree'; @@ -6,19 +7,19 @@ import type {PdfMenuItem} from './pdfMenu'; function renamePdf(path:string):Promise{ return new Promise(resolve=>{ - const dialog=document.createElement('dialog');dialog.className='pdf-rename-dialog';dialog.setAttribute('aria-label','Переименовать PDF'); + const dialog=document.createElement('dialog');dialog.className='pdf-rename-dialog';dialog.setAttribute('aria-label',uiText("webobsidian.rename-pdf")); const form=document.createElement('form'),label=document.createElement('label'),input=document.createElement('input'),ok=document.createElement('button'),cancel=document.createElement('button'),error=document.createElement('div'); - label.textContent='Новое имя';input.value=path.split('/').pop()!.replace(/\.pdf$/i,'');input.required=true;label.append(input); - ok.type='submit';ok.textContent='Переименовать';cancel.type='button';cancel.textContent='Отмена';error.setAttribute('role','alert');form.append(label,error,ok,cancel);dialog.append(form); + label.textContent=uiText("webobsidian.new-name");input.value=path.split('/').pop()!.replace(/\.pdf$/i,'');input.required=true;label.append(input); + ok.type='submit';ok.textContent=uiText("webobsidian.rename");cancel.type='button';cancel.textContent=uiText("dialogue.button-cancel");error.setAttribute('role','alert');form.append(label,error,ok,cancel);dialog.append(form); let pending=false; const done=()=>{dialog.remove();resolve()};cancel.onclick=()=>{if(!pending)done()};dialog.oncancel=e=>{e.preventDefault();if(!pending)done()}; form.onsubmit=async e=>{ e.preventDefault();if(pending)return;const value=input.value.trim(); - if(!value||/[\\/\u0000-\u001f]/.test(value)||value==='.'||value==='..'){error.textContent='Введите имя файла без пути';return} + if(!value||/[\\/\u0000-\u001f]/.test(value)||value==='.'||value==='..'){error.textContent=uiText("webobsidian.file-name-without-path");return} const name=/\.pdf$/i.test(value)?value:value+'.pdf',dir=path.includes('/')?path.slice(0,path.lastIndexOf('/')+1):''; if(dir+name===path){done();return} pending=true;ok.disabled=true;cancel.disabled=true; - try{await useStore.getState().renamePath(path,dir+name);done()}catch(reason){error.textContent=reason instanceof Error?reason.message:'Не удалось переименовать';pending=false;ok.disabled=false;cancel.disabled=false} + try{await useStore.getState().renamePath(path,dir+name);done()}catch(reason){error.textContent=reason instanceof Error?reason.message:uiText("webobsidian.rename-file-failed");pending=false;ok.disabled=false;cancel.disabled=false} }; (document.querySelector('.app')??document.body).append(dialog);dialog.showModal();input.focus();input.select(); }); @@ -27,24 +28,24 @@ function renamePdf(path:string):Promise{ /** Only the authenticated app supplies vault actions; public readers import none. */ export function pdfFileActions(target:string,origin:string,options:{resolvedPath?:string;linkKind?:'wiki'|'markdown';fragment?:string}={}):()=>Promise{ return async()=>{ - const path=options.resolvedPath??(options.linkKind==='markdown'?await api.resolve(target,origin,'markdown'):await api.resolveAttachment(target.split('#')[0],origin)).path;if(!path)throw Error('PDF не найден'); + const path=options.resolvedPath??(options.linkKind==='markdown'?await api.resolve(target,origin,'markdown'):await api.resolveAttachment(target.split('#')[0],origin)).path;if(!path)throw Error(uiText("webobsidian.pdf-not-found")); const st=useStore.getState(),locked=!!findNode(st.tree,path)?.locked; const fragment=options.fragment??(options.resolvedPath?'':target.includes('#')?target.slice(target.indexOf('#')+1):''); const url=pathToUrl(path)+(fragment?'#'+fragment:''); return [ - {label:'Открыть в новой вкладке',icon:'tab',run:()=>useStore.getState().openFile(path,{preview:false,...(fragment?{pdfFragment:fragment}:{})})}, - {label:'Открыть в области справа',icon:'split',run:()=>useStore.getState().openToSide(path,'right',fragment?{pdfFragment:fragment}:undefined)}, - {label:'Открыть в новом окне',icon:'window',run:()=>{window.open(url,'_blank','popup,noopener,noreferrer')}}, - {label:'Переименовать',icon:'rename',disabled:locked,run:()=>renamePdf(path)}, - {label:'Переместить файл в...',icon:'folder',disabled:locked,run:()=>useStore.getState().setMovePath(path)}, - {label:st.bookmarks.includes(path)?'Удалить из закладок':'Добавить в закладки...',icon:'bookmark',run:()=>useStore.getState().toggleBookmark(path)}, - {label:'Копировать путь',icon:'link',children:[ - {label:'Путь от корня хранилища',run:()=>navigator.clipboard.writeText(path)}, - {label:'Ссылка в браузере',run:()=>navigator.clipboard.writeText(new URL(url,location.origin).href)}, + {get label() {return uiText("webobsidian.pdf-71bf47a728");},icon:'tab',run:()=>useStore.getState().openFile(path,{preview:false,...(fragment?{pdfFragment:fragment}:{})})}, + {get label() {return uiText("interface.menu.open-to-the-right");},icon:'split',run:()=>useStore.getState().openToSide(path,'right',fragment?{pdfFragment:fragment}:undefined)}, + {get label() {return uiText("interface.menu.open-in-new-window");},icon:'window',run:()=>{window.open(url,'_blank','popup,noopener,noreferrer')}}, + {get label() {return uiText("webobsidian.rename");},icon:'rename',disabled:locked,run:()=>renamePdf(path)}, + {get label() {return uiText("webobsidian.move-file-to-ffc312");},icon:'folder',disabled:locked,run:()=>useStore.getState().setMovePath(path)}, + {label:st.bookmarks.includes(path)?uiText("webobsidian.remove-bookmark-7da720"):uiText("webobsidian.add-bookmark"),icon:'bookmark',run:()=>useStore.getState().toggleBookmark(path)}, + {get label() {return uiText("interface.menu.copy-path");},icon:'link',children:[ + {get label() {return uiText("webobsidian.vault-relative-path");},run:()=>navigator.clipboard.writeText(path)}, + {get label() {return uiText("webobsidian.browser-url");},run:()=>navigator.clipboard.writeText(new URL(url,location.origin).href)}, ]}, - {label:'Открыть в приложении по умолчанию',icon:'window',disabled:true,hint:'Команда операционной системы недоступна из браузера'}, - {label:'Показать в Проводнике',icon:'folder',disabled:true,hint:'Проводник на вашем компьютере недоступен для серверного файла'}, - {label:'Показать в файловом менеджере',icon:'folder',run:()=>useStore.getState().revealInTree(path)}, + {get label() {return uiText("webobsidian.open-default-application");},icon:'window',disabled:true,get hint() {return uiText("webobsidian.os-command-unavailable");}}, + {get label() {return uiText("webobsidian.show-system-explorer");},icon:'folder',disabled:true,get hint() {return uiText("webobsidian.server-file-unavailable-in-explorer");}}, + {get label() {return uiText("webobsidian.reveal-file");},icon:'folder',run:()=>useStore.getState().revealInTree(path)}, ]; }; } diff --git a/web/src/lib/pdfViewer.ts b/web/src/lib/pdfViewer.ts index 55e89bb4..1d6f5b35 100644 --- a/web/src/lib/pdfViewer.ts +++ b/web/src/lib/pdfViewer.ts @@ -199,7 +199,7 @@ export function createPdfViewer(src:string,name:string,onOpen?:()=>void,onEdit?: if(destroyed)return; if(error?.status===404||error?.name==='MissingPDFException'){ cleanup();root.classList.remove('pdf-fill-container');root.classList.add('pdf-missing');root.style.removeProperty('height');root.dataset.missing='true';root.setAttribute('role','note'); - const label=options.missingLabel??name;setLocalizedText(root,"webobsidian.missing-file",{name:label},"textContent",`«${label}» не может быть найдена.`); + const label=options.missingLabel??name;setLocalizedText(root,"webobsidian.missing-file",{name:label},"textContent"); if(onEdit){const edit=embedAction('Edit embed','source',onEdit);edit.classList.add('pdf-missing-edit');root.append(edit)}return; } cleanup();setLocalizedText(status, "webobsidian.-pdf-4dac1a", {}, "textContent"); diff --git a/web/tests/externalNoteNoticeBrowser.test.ts b/web/tests/externalNoteNoticeBrowser.test.ts index 555db1e6..eedeff9f 100644 --- a/web/tests/externalNoteNoticeBrowser.test.ts +++ b/web/tests/externalNoteNoticeBrowser.test.ts @@ -42,7 +42,7 @@ test('external note indicator detects remote edits and safely refreshes or compa remote={content:'external',version:'v2'};fs('other.md');await wait(450);check(!notice(),'unrelated file ignored'); fs('a.md');await wait(450);check(notice(),'external edit shows indicator'); check(useStore.getState().content==='base','notification never replaces visible text'); - remote={content:'latest external',version:'v3'};button('Обновить статью').click();await wait(200); + remote={content:'latest external',version:'v3'};button('Reload note').click();await wait(200); check(useStore.getState().content==='latest external','refresh re-reads latest server content'); check(a.baseVersion==='v3'&&!notice(),'refresh updates acknowledged version and clears banner'); check(writes===0,'refresh does not write files'); @@ -50,14 +50,14 @@ test('external note indicator detects remote edits and safely refreshes or compa check(!notice(),'own successful save does not show indicator'); remote={content:'changed while away',version:'v4'};window.dispatchEvent(new Event('focus'));await wait(450); check(notice(),'returning to tab checks missed filesystem events'); - fail=true;button('Обновить статью').click();await wait(150); + fail=true;button('Reload note').click();await wait(150); check(document.querySelector('[role="alert"]'),'refresh failure is visible'); check(useStore.getState().content==='my save'&¬ice(),'failed refresh preserves text and indicator');fail=false; - let resolve;pending=new Promise(r=>{resolve=r;});button('Обновить статью').click();await wait(50); + let resolve;pending=new Promise(r=>{resolve=r;});button('Reload note').click();await wait(50); useStore.getState().setContent('typed during refresh');resolve({...remote});pending=null;await wait(180); check(useStore.getState().content==='typed during refresh','typing during refresh is never overwritten'); - check(button('Сравнить изменения'),'local changes switch refresh to comparison'); - button('Сравнить изменения').click();await wait(250); + check(button('Compare changes'),'local changes switch refresh to comparison'); + button('Compare changes').click();await wait(250); check(document.querySelector('[role="dialog"]'),'existing comparison dialog opens'); check(useStore.getState().content==='typed during refresh'&&writes===1,'comparison does not write or discard local text'); check((await listDrafts('external-scope')).some(r=>r.content==='typed during refresh'),'local edits backed up before comparison'); @@ -81,7 +81,7 @@ test('external note indicator detects remote edits and safely refreshes or compa remote={content:'updated in real editor',version:'wired2'};poll();await wait(450); check(notice(),'real workspace shows notice even without a filesystem event'); check(document.querySelector('.cm-content').textContent.includes('base'),'real editor retains open text before refresh'); - button('Обновить статью').click();await wait(250); + button('Reload note').click();await wait(250); check(document.querySelector('.cm-content').textContent.includes('updated in real editor'),'real editor displays refreshed article'); check(!notice()&&writes===1,'real refresh clears notice without server write'); root3.unmount();for(const s of documentSessions.values())s.dispose();return true; diff --git a/web/tests/languageSettingsBrowser.test.ts b/web/tests/languageSettingsBrowser.test.ts index 023680f3..e909a368 100644 --- a/web/tests/languageSettingsBrowser.test.ts +++ b/web/tests/languageSettingsBrowser.test.ts @@ -1,6 +1,6 @@ import {test} from 'node:test'; import assert from 'node:assert/strict'; -import {mkdtemp, rm, writeFile} from 'node:fs/promises'; +import {mkdtemp, rm, writeFile, readFile} from 'node:fs/promises'; import {tmpdir} from 'node:os'; import {join} from 'node:path'; import {fileURLToPath} from 'node:url'; @@ -12,6 +12,7 @@ import {build} from 'esbuild'; test('browser: language file import, template, live labels and literal user titles', async () => { const dir = await mkdtemp(join(tmpdir(), 'webo-language-')); try { + const russianPack = await readFile(new URL('../../translations/ru.txt',import.meta.url),'utf8'); await build({stdin:{resolveDir:fileURLToPath(new URL('..',import.meta.url)),loader:'tsx',contents:` import React from 'react';import {createRoot} from 'react-dom/client'; import LanguageSettings from './src/components/LanguageSettings'; @@ -25,6 +26,7 @@ test('browser: language file import, template, live labels and literal user titl import {pdfLabel,bindPdfLabel} from './src/lib/i18n/pdfLabels'; import {initializeLanguage,t,useLanguage,setLocalizedText} from './src/lib/i18n/runtime'; import {exportLanguageTemplate} from './src/lib/i18n/pack'; + Object.defineProperty(navigator,'language',{configurable:true,value:'ru-RU'}); initializeLanguage();localStorage.clear(); let serverPack=null,failServer=false; api.getSettings=async()=>({ui:{languagePack:serverPack}}); @@ -42,6 +44,7 @@ test('browser: language file import, template, live labels and literal user titl const action=document.createElement('a');action.textContent='action';widget.append(action); const check=(value,message)=>{if(!value)throw Error(message)}; window.run=async()=>{ + check(pdfLabel('Увеличить')==='Zoom in','fresh install uses English PDF labels in a Russian browser'); await wait();check(exportLanguageTemplate().includes('[plugins.file-explorer.action-new-folder]'),'template contains compatible keys'); const title=document.querySelector('[data-testid=template-title]'); Object.getOwnPropertyDescriptor(HTMLInputElement.prototype,'value').set.call(title,'Settings');title.dispatchEvent(new Event('input',{bubbles:true}));await wait(); @@ -81,7 +84,12 @@ test('browser: language file import, template, live labels and literal user titl check(document.querySelector('#folder').textContent==='New folder','reset restores English'); check(!localStorage.getItem('webobsidian.language.v1'),'reset deletes saved pack'); check(serverPack===null,'reset deletes server pack'); - check(pdfButton.title==='Увеличить','PDF reset restores the original label for widgets created under a pack'); + check(pdfButton.title==='Zoom in','PDF reset restores English for widgets created under a pack'); + await load(${JSON.stringify(russianPack)}); + check(document.querySelector('#folder').textContent==='Новая папка','Russian is applied after explicitly importing a pack'); + check(pdfButton.title==='Увеличить масштаб','existing PDF widget follows the imported Russian pack'); + [...document.querySelectorAll('button')].find(b=>b.textContent===t('webobsidian.restore-default-language-a41d48')).click();await wait(); + check(pdfButton.title==='Zoom in'&&document.querySelector('#folder').textContent==='New folder','reset after Russian import restores English in a Russian browser'); return 'LANGUAGE_PASS'; }; `},bundle:true,jsx:'automatic',format:'iife',platform:'browser',define:{'import.meta.env.DEV':'false'},outfile:join(dir,'fixture.js'),logLevel:'silent'}); diff --git a/web/tests/markdownEmbedsBrowser.test.ts b/web/tests/markdownEmbedsBrowser.test.ts index 6d77f8a6..92996d67 100644 --- a/web/tests/markdownEmbedsBrowser.test.ts +++ b/web/tests/markdownEmbedsBrowser.test.ts @@ -56,7 +56,7 @@ test('standard Markdown embeds have native widgets, paths and source actions in check(!document.querySelector('img:not(.cm-widgetBuffer)'),mode+': binary embeds are not images'); check(document.querySelector('.file-embed').textContent==='config#one.yaml',mode+': generic file title decoded once'); check(useStore.getState().content===assets,mode+': rendering preserves source'); - if(mode==='live'){document.querySelector('.pdf-reader [aria-label="Редактировать блок"]').click();await wait();const v=getActiveEditor(),selection=v.state.selection.main;check(v.state.doc.sliceString(selection.from,selection.to)==='![doc](doc%20%23one.pdf#page=2&height=160)','PDF source action selects complete Markdown token')} + if(mode==='live'){document.querySelector('.pdf-reader [aria-label="Edit block"]').click();await wait();const v=getActiveEditor(),selection=v.state.selection.main;check(v.state.doc.sliceString(selection.from,selection.to)==='![doc](doc%20%23one.pdf#page=2&height=160)','PDF source action selects complete Markdown token')} window.debugStage=mode+': images';const pictures='# Images\\n\\n![ref][img]\\n\\n![literal|100](photo%2520one.svg)\\n\\n[img]: ';await mount(mode,pictures); await until(()=>document.querySelectorAll('img:not(.cm-widgetBuffer)').length===2&&[...document.querySelectorAll('img:not(.cm-widgetBuffer)')].every(i=>i.complete&&i.naturalWidth>0),mode+': reference and percent-literal images loaded'); const images=[...document.querySelectorAll('img:not(.cm-widgetBuffer)')];check(new URL(images[0].src).searchParams.get('path')==='photo (1)#one.svg'&&new URL(images[1].src).searchParams.get('path')==='photo%20one.svg',mode+': image filenames not confused'); diff --git a/web/tests/noteEmbedBrowser.test.ts b/web/tests/noteEmbedBrowser.test.ts index 1743f7ce..3c52fd8c 100644 --- a/web/tests/noteEmbedBrowser.test.ts +++ b/web/tests/noteEmbedBrowser.test.ts @@ -17,6 +17,7 @@ test('embedded notes expose an accessible open button in live, reading and HTML import Editor from './src/components/Editor';import Preview from './src/components/Preview'; import {useStore} from './src/lib/store';import {api} from './src/lib/api'; import './src/styles/obsidian.css'; + Object.defineProperty(navigator,'language',{configurable:true,value:'ru-RU'}); api.tags=async()=>({tags:[]});api.propertyTypes=async()=>({types:{}}); api.resolve=async target=>({path:target.endsWith('.md')?target:'Lab/'+target.split('#')[0]+'.md'}); api.read=async path=>({content:path==='Lab/Parent.md'?'![[#Section]]\\n\\n# Section\\nNested note body':'# Section\\nEmbedded note body',version:'fixture'}); @@ -36,6 +37,7 @@ test('embedded notes expose an accessible open button in live, reading and HTML const placeholders=[...document.querySelectorAll('.cm-note-embed.is-unresolved')]; check(placeholders.every(e=>!!e.querySelector('button[aria-label="Open embedded note"]')),mode+': unresolved note and heading retain source buttons'); check(placeholders[0].querySelector('.markdown-embed-title').textContent==='Missing'&&placeholders[1].textContent.includes('Section'),mode+': native missing-note and missing-heading labels'); + check(placeholders[1].textContent.includes('Could not find “Section” in Missing'),mode+': missing headings use English even with a Russian browser'); opened=[];placeholders[1].querySelector('button').click();await wait();check(JSON.stringify(opened)===JSON.stringify([['Missing#Section','wiki']]),mode+': unresolved heading opens its actual target'); check(useStore.getState().content===missing,mode+': unresolved note display and actions preserve source');root.render(
);await wait(); } diff --git a/web/tests/pdfFragmentsBrowser.test.ts b/web/tests/pdfFragmentsBrowser.test.ts index 13627e07..7de21247 100644 --- a/web/tests/pdfFragmentsBrowser.test.ts +++ b/web/tests/pdfFragmentsBrowser.test.ts @@ -45,7 +45,7 @@ test('PDF fragment targets highlight text and annotations, survive zoom and rema window.debugStage='multiple items';const multi=await mount('page=2&selection=0,7,1,7'); await until(()=>multi.querySelectorAll('.pdf-fragment-selection').length>=2,'multi-item text selection');check(multi.querySelector('.pdf-fragment-selection').textContent==='PDF page','first item offset is respected');discard(multi); window.debugStage='invalid';for(const fragment of ['page=2&selection=999,0,1000,3','page=2&selection=0,999,0,1000','page=2&selection=0,6,0,2','page=2&annotation=unknown','page=2&selection=0,0,0,NaN']){ - const bad=await mount(fragment);await until(()=>bad.querySelector('[data-page-number="2"] .textLayer'),'invalid fragment still renders page');await wait();check(!bad.querySelector('.pdf-fragment-selection,.pdf-fragment-annotation'),'invalid fragment creates no marker');check(!bad.textContent.includes('Не удалось'),'invalid fragment cannot break PDF');discard(bad); + const bad=await mount(fragment);await until(()=>bad.querySelector('[data-page-number="2"] .textLayer'),'invalid fragment still renders page');await wait();check(!bad.querySelector('.pdf-fragment-selection,.pdf-fragment-annotation'),'invalid fragment creates no marker');check(!bad.textContent.includes('Could not display PDF'),'invalid fragment cannot break PDF');discard(bad); } window.debugStage='offset';const offset=await mount('page=2&offset=40,600,1');await until(()=>offset.dataset.scale==='1','offset zoom is applied');await until(()=>offset.querySelector('[data-page-number="2"] .textLayer'),'offset page renders');check(offset.querySelector('input').value==='2','offset page');const pageRect=offset.querySelector('[data-page-number=\"2\"]').getBoundingClientRect(),scrollRect=offset.querySelector('.pdf-reader-scroll').getBoundingClientRect();check(Math.abs(pageRect.top+pageRect.height/4-scrollRect.top)<5,'offset positions the requested PDF y coordinate');check(Math.abs(pageRect.left+pageRect.width*40/600-scrollRect.left)<5,'offset positions the requested PDF x coordinate');discard(offset); const fitted=await mount('page=2&zoom=200&offset=,600,');check(fitted.dataset.scale==='page-width','offset without explicit zoom fits page width like native Obsidian');discard(fitted); diff --git a/web/tests/pdfMenusBrowser.test.ts b/web/tests/pdfMenusBrowser.test.ts index eca24495..91f5ad9d 100644 --- a/web/tests/pdfMenusBrowser.test.ts +++ b/web/tests/pdfMenusBrowser.test.ts @@ -22,7 +22,7 @@ test('PDF menus match native sidebar, spread, theme and file commands with keybo const root=document.querySelector('#root'),wait=()=>new Promise(r=>setTimeout(r,40)); const check=(ok,msg)=>{if(!ok)throw Error(msg)}; const until=async(fn,msg)=>{for(let i=0;i<300&&!fn();i++)await wait();check(fn(),msg+': '+document.body.textContent)}; - const actions=[];const reader=createPdfViewer('/sample.pdf#height=400','sample.pdf',()=>actions.push('open'),undefined,{fixedHeightIncludesToolbar:false,fileActions:async()=>[{label:'Открыть в новой вкладке',run:()=>actions.push('tab')},{label:'Переименовать',run:()=>actions.push('rename')}]});root.append(reader); + const actions=[];const reader=createPdfViewer('/sample.pdf#height=400','sample.pdf',()=>actions.push('open'),undefined,{fixedHeightIncludesToolbar:false,fileActions:async()=>[{label:'Open in new tab',run:()=>actions.push('tab')},{label:'Rename',run:()=>actions.push('rename')}]});root.append(reader); const menu=async action=>{reader.querySelector('[data-pdf-action="'+action+'"]').click();await until(()=>document.querySelector('.pdf-menu-panel'),'menu opens');return [...document.querySelectorAll('.pdf-menu-panel button')].map(b=>b.textContent.trim())}; const choose=label=>{const item=[...document.querySelectorAll('.pdf-menu-panel button')].find(b=>b.dataset.label===label);check(item,'menu item '+label);check(!item.disabled,'enabled '+label);item.click()}; @@ -31,21 +31,21 @@ test('PDF menus match native sidebar, spread, theme and file commands with keybo window.pointerCheck=opened=>{check(!!document.querySelector('.pdf-menu-panel')===opened,'real repeated SVG pointer click toggles menu');if(!opened){destroyPdfViewer(pointerReader);pointerBox.remove()}}; window.run=async()=>{const reviewFailures=[];const verifyReview=(ok,msg)=>{if(!ok)reviewFailures.push(msg)}; await until(()=>reader.dataset.ready==='true'&&reader.querySelector('.textLayer')?.textContent.includes('First PDF page'),'PDF loaded'); - check(reader.querySelector('[aria-label="Параметры боковой панели"]'),'native sidebar options button'); - check(JSON.stringify(await menu('sidebar-options'))===JSON.stringify(['Миниатюры','Оглавление','Показать страницу в оглавлении']),'native sidebar menu items'); - choose('Оглавление');await until(()=>reader.querySelector('.pdf-outline button'),'outline loaded'); + check(reader.querySelector('[aria-label="Sidebar options"]'),'native sidebar options button'); + check(JSON.stringify(await menu('sidebar-options'))===JSON.stringify(['Thumbnails','Outline','Reveal page in outline']),'native sidebar menu items'); + choose('Outline');await until(()=>reader.querySelector('.pdf-outline button'),'outline loaded'); reader.querySelector('.pdf-outline button').click();await until(()=>reader.querySelector('input').value==='A-2','outline navigates to labelled page'); - await menu('sidebar-options');choose('Показать страницу в оглавлении');check(document.activeElement.closest('.pdf-outline'),'reveal current outline entry'); - await menu('sidebar-options');choose('Миниатюры');check(!reader.querySelector('.pdf-thumbnails').hidden,'thumbnail mode restored'); - const labels=await menu('display-options');check(JSON.stringify(labels)===JSON.stringify(['Подогнать по ширине','Подогнать по высоте','Одна страница','Две страницы (нечётные)','Две страницы (чётные)','Адаптировать к теме']),'native display items'); - choose('Две страницы (нечётные)');await until(()=>reader.querySelector('.spread')?.querySelectorAll('.page').length===2,'odd spread contains two pages'); - await menu('display-options');check(document.querySelector('[data-label="Две страницы (нечётные)"]').getAttribute('aria-checked')==='true','spread checkmark');choose('Две страницы (чётные)');await until(()=>reader.querySelector('.spread')?.querySelectorAll('.page').length===1,'even spread starts with a single page'); - await menu('display-options');choose('Одна страница');check(!reader.querySelector('.spread'),'single page removes spreads'); - await menu('display-options');choose('Подогнать по высоте');await until(()=>reader.dataset.scale==='page-height','fit height command'); - await menu('display-options');choose('Подогнать по ширине');await until(()=>reader.dataset.scale==='page-width','fit width command'); - await menu('display-options');choose('Адаптировать к теме');check(reader.classList.contains('pdf-adapt-theme'),'theme command enabled'); - await menu('display-options');check(document.querySelector('[data-label="Адаптировать к теме"]').getAttribute('aria-checked')==='true','theme checkmark');choose('Адаптировать к теме');check(!reader.classList.contains('pdf-adapt-theme'),'theme command toggles'); - await menu('file-menu');choose('Переименовать');check(actions.join()==='rename','file command runs exactly once'); + await menu('sidebar-options');choose('Reveal page in outline');check(document.activeElement.closest('.pdf-outline'),'reveal current outline entry'); + await menu('sidebar-options');choose('Thumbnails');check(!reader.querySelector('.pdf-thumbnails').hidden,'thumbnail mode restored'); + const labels=await menu('display-options');check(JSON.stringify(labels)===JSON.stringify(['Fit width','Fit height','Single page','Two pages (odd)','Two pages (even)','Adapt to theme']),'native display items'); + choose('Two pages (odd)');await until(()=>reader.querySelector('.spread')?.querySelectorAll('.page').length===2,'odd spread contains two pages'); + await menu('display-options');check(document.querySelector('[data-label="Two pages (odd)"]').getAttribute('aria-checked')==='true','spread checkmark');choose('Two pages (even)');await until(()=>reader.querySelector('.spread')?.querySelectorAll('.page').length===1,'even spread starts with a single page'); + await menu('display-options');choose('Single page');check(!reader.querySelector('.spread'),'single page removes spreads'); + await menu('display-options');choose('Fit height');await until(()=>reader.dataset.scale==='page-height','fit height command'); + await menu('display-options');choose('Fit width');await until(()=>reader.dataset.scale==='page-width','fit width command'); + await menu('display-options');choose('Adapt to theme');check(reader.classList.contains('pdf-adapt-theme'),'theme command enabled'); + await menu('display-options');check(document.querySelector('[data-label="Adapt to theme"]').getAttribute('aria-checked')==='true','theme checkmark');choose('Adapt to theme');check(!reader.classList.contains('pdf-adapt-theme'),'theme command toggles'); + await menu('file-menu');choose('Rename');check(actions.join()==='rename','file command runs exactly once'); await menu('display-options');document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}));check(!document.querySelector('.pdf-menu-panel'),'Escape closes');check(document.activeElement===reader.querySelector('[data-pdf-action="display-options"]'),'focus restored'); await menu('display-options');const active=document.activeElement;document.dispatchEvent(new KeyboardEvent('keydown',{key:'ArrowDown',bubbles:true}));check(document.activeElement!==active,'keyboard moves through menu'); document.body.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true}));check(!document.querySelector('.pdf-menu-panel'),'outside pointer closes'); @@ -59,32 +59,32 @@ test('PDF menus match native sidebar, spread, theme and file commands with keybo Object.defineProperty(navigator,'clipboard',{configurable:true,value:{writeText:async text=>copied.push(text)}});window.open=(...args)=>{windows.push(args);return null}; const provider=pdfFileActions('sample.pdf#page=2','Notes/Parent.md'),fileItems=await provider(); const run=async label=>{const action=fileItems.find(i=>i.label===label);check(action&&!action.disabled,'available file command '+label);await action.run?.()}; - await run('Открыть в новой вкладке');check(opened[0].path==='Lab/sample.pdf'&&opened[0].options.preview===false,'file opens persistent app tab'); - await run('Открыть в области справа');check(splits[0].path==='Lab/sample.pdf'&&splits[0].side==='right','file opens right pane'); + await run('Open in new tab');check(opened[0].path==='Lab/sample.pdf'&&opened[0].options.preview===false,'file opens persistent app tab'); + await run('Open to the right');check(splits[0].path==='Lab/sample.pdf'&&splits[0].side==='right','file opens right pane'); check(opened[0].options.pdfFragment==='page=2'&&splits[0].options.pdfFragment==='page=2','file-menu tab and split preserve fragment'); - await run('Открыть в новом окне');check(windows[0][0]==='/note/Lab/sample.pdf#page=2','window uses app route'); - await run('Добавить в закладки...');check(useStore.getState().bookmarks.includes('Lab/sample.pdf'),'bookmark command'); - await run('Переместить файл в...');check(useStore.getState().movePath==='Lab/sample.pdf','move opens app folder picker'); - await run('Показать в файловом менеджере');check(revealed[0]==='Lab/sample.pdf','reveal exact resolved file'); - await fileItems.find(i=>i.label==='Копировать путь').children[0].run();check(copied[0]==='Lab/sample.pdf','copy vault path');await fileItems.find(i=>i.label==='Копировать путь').children[1].run();check(copied[1].endsWith('/note/Lab/sample.pdf#page=2'),'copy browser URL preserves PDF fragment'); - check(fileItems.find(i=>i.label==='Показать в Проводнике').disabled&&fileItems.find(i=>i.label==='Открыть в приложении по умолчанию').disabled,'OS-only commands explicitly unavailable in browser'); - const pendingRename=run('Переименовать');await until(()=>document.querySelector('.pdf-rename-dialog'),'rename dialog'); + await run('Open in new window');check(windows[0][0]==='/note/Lab/sample.pdf#page=2','window uses app route'); + await run('Add bookmark…');check(useStore.getState().bookmarks.includes('Lab/sample.pdf'),'bookmark command'); + await run('Move file to…');check(useStore.getState().movePath==='Lab/sample.pdf','move opens app folder picker'); + await run('Reveal in file explorer');check(revealed[0]==='Lab/sample.pdf','reveal exact resolved file'); + await fileItems.find(i=>i.label==='Copy path').children[0].run();check(copied[0]==='Lab/sample.pdf','copy vault path');await fileItems.find(i=>i.label==='Copy path').children[1].run();check(copied[1].endsWith('/note/Lab/sample.pdf#page=2'),'copy browser URL preserves PDF fragment'); + check(fileItems.find(i=>i.label==='Show in system file explorer').disabled&&fileItems.find(i=>i.label==='Open in default application').disabled,'OS-only commands explicitly unavailable in browser'); + const pendingRename=run('Rename');await until(()=>document.querySelector('.pdf-rename-dialog'),'rename dialog'); document.querySelector('.pdf-rename-dialog input').value='renamed';document.querySelector('.pdf-rename-dialog form').dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}));await pendingRename; check(renamed[0].from==='Lab/sample.pdf'&&renamed[0].to==='Lab/renamed.pdf','rename retains folder and PDF extension'); check(lookups[0].target==='sample.pdf'&&lookups[0].from==='Notes/Parent.md','file actions use embedding note origin'); - tree.children[0].children[0].locked=true;useStore.setState({tree});const locked=await provider();check(locked.find(i=>i.label==='Переименовать').disabled&&locked.find(i=>i.label==='Переместить файл в...').disabled,'locked PDF has no mutation commands'); + tree.children[0].children[0].locked=true;useStore.setState({tree});const locked=await provider();check(locked.find(i=>i.label==='Rename').disabled&&locked.find(i=>i.label==='Move file to…').disabled,'locked PDF has no mutation commands'); api.resolveAttachment=async(target,from)=>({path:from==='Lab/sample.pdf'?'Lab/Lab/sample.pdf':target}); root.style.height='600px';const reactRoot=createRoot(root);reactRoot.render(React.createElement(PdfFileView,{path:'Lab/sample.pdf'})); await until(()=>document.querySelector('.pdf-fill-container[data-ready="true"]'),'full PDF pane loaded'); check(Math.abs(document.querySelector('.pdf-fill-container').getBoundingClientRect().height-600)<3,'file viewer fills pane without growing to page height'); - const full=document.querySelector('.pdf-fill-container');full.querySelector('[data-pdf-action="display-options"]').click();choose('Подогнать по высоте');await wait();await wait();const pageHeight=full.querySelector('.page').getBoundingClientRect().height;root.style.height='450px';await wait();await wait();verifyReview(full.querySelector('.page').getBoundingClientRect().heightdocument.querySelector('.pdf-menu-panel'),'full file view has native menu');choose('Копировать путь');choose('Путь от корня хранилища');await wait();verifyReview(copied.at(-1)==='Lab/sample.pdf','canonical file actions must not resolve Lab/Lab/sample.pdf'); + const full=document.querySelector('.pdf-fill-container');full.querySelector('[data-pdf-action="display-options"]').click();choose('Fit height');await wait();await wait();const pageHeight=full.querySelector('.page').getBoundingClientRect().height;root.style.height='450px';await wait();await wait();verifyReview(full.querySelector('.page').getBoundingClientRect().heightdocument.querySelector('.pdf-menu-panel'),'full file view has native menu');choose('Copy path');choose('Vault-relative path');await wait();verifyReview(copied.at(-1)==='Lab/sample.pdf','canonical file actions must not resolve Lab/Lab/sample.pdf'); full.querySelector('[data-pdf-action="file-menu"]').click();await until(()=>document.querySelector('.pdf-menu-panel'),'full view menu before unmount'); reactRoot.unmount();check(!document.querySelector('.pdf-menu-panel'),'unmounting full PDF closes menu'); - const pendingCancel=run('Переименовать');await until(()=>document.querySelector('.pdf-rename-dialog'),'cancel rename dialog');document.querySelector('.pdf-rename-dialog button[type="button"]').click();await pendingCancel;check(renamed.length===1,'cancelled rename does not mutate file'); - useStore.setState({renamePath:async()=>{throw Error('Version conflict')}});const failed=run('Переименовать');await until(()=>document.querySelector('.pdf-rename-dialog'),'failed rename dialog');document.querySelector('.pdf-rename-dialog input').value='retry';document.querySelector('.pdf-rename-dialog form').dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}));await until(()=>document.querySelector('.pdf-rename-dialog [role="alert"]').textContent.includes('Version conflict'),'failed rename stays visible');document.querySelector('.pdf-rename-dialog button[type="button"]').click();await failed; + const pendingCancel=run('Rename');await until(()=>document.querySelector('.pdf-rename-dialog'),'cancel rename dialog');document.querySelector('.pdf-rename-dialog button[type="button"]').click();await pendingCancel;check(renamed.length===1,'cancelled rename does not mutate file'); + useStore.setState({renamePath:async()=>{throw Error('Version conflict')}});const failed=run('Rename');await until(()=>document.querySelector('.pdf-rename-dialog'),'failed rename dialog');document.querySelector('.pdf-rename-dialog input').value='retry';document.querySelector('.pdf-rename-dialog form').dispatchEvent(new Event('submit',{bubbles:true,cancelable:true}));await until(()=>document.querySelector('.pdf-rename-dialog [role="alert"]').textContent.includes('Version conflict'),'failed rename stays visible');document.querySelector('.pdf-rename-dialog button[type="button"]').click();await failed; let resolveMenu;const late=createPdfViewer('/sample.pdf','late.pdf',undefined,undefined,{fileActions:()=>new Promise(r=>{resolveMenu=r})});root.append(late);late.querySelector('[data-pdf-action="file-menu"]').click();destroyPdfViewer(late);late.remove();resolveMenu([{label:'Late command'}]);await wait();check(!document.querySelector('.pdf-menu-panel'),'cancelled file menu cannot appear after destroy'); let escapeResolve;const escapeReader=createPdfViewer('/sample.pdf','escape.pdf',undefined,undefined,{fileActions:()=>new Promise(r=>{escapeResolve=r})});root.append(escapeReader);escapeReader.querySelector('[data-pdf-action="file-menu"]').click();document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}));escapeResolve([{label:'Must remain closed'}]);await wait();verifyReview(!document.querySelector('.pdf-menu-panel'),'Escape must cancel pending file menu');destroyPdfViewer(escapeReader);escapeReader.remove(); diff --git a/web/tests/pdfViewerBrowser.test.ts b/web/tests/pdfViewerBrowser.test.ts index 2876ff6d..29255148 100644 --- a/web/tests/pdfViewerBrowser.test.ts +++ b/web/tests/pdfViewerBrowser.test.ts @@ -49,50 +49,50 @@ test('PDF embeds have working page, zoom and thumbnail controls in live, reading await until(()=>document.querySelector('.pdf-toolbar'),'own PDF toolbar mounted'); await until(()=>document.querySelector('.pdf-reader[data-ready="true"]'),'PDF document loaded'); check(auditSnapshot()===beforePdf,'PDF loading leaves outside tabs, titles, sidebar, selected items, inputs and buttons unchanged'); - const reader=document.querySelector('.pdf-reader'),page=reader.querySelector('input[aria-label="Номер страницы"]'); + const reader=document.querySelector('.pdf-reader'),page=reader.querySelector('input[aria-label="Page number"]'); check(reader.querySelector('.pdf-page-count').textContent.includes('2'),'page count'); check(reader.querySelector('.pdf-thumbnails').hidden,'thumbnails initially closed'); await until(()=>reader.querySelector('.textLayer')?.textContent.includes('First PDF page'),'selectable first-page text'); const visiblePage=reader.querySelector('.pdfViewer .page'); check(Math.abs(reader.getBoundingClientRect().height-visiblePage.getBoundingClientRect().height-reader.querySelector('.pdf-toolbar').getBoundingClientRect().height)<20,'embed height fits exactly one page plus toolbar'); reader.querySelector('[data-pdf-action="sidebar-options"]').click(); - check([...document.querySelectorAll('.pdf-menu-panel button')].find(b=>b.dataset.label==='Оглавление').disabled,'PDF without outline disables outline command'); + check([...document.querySelectorAll('.pdf-menu-panel button')].find(b=>b.dataset.label==='Outline').disabled,'PDF without outline disables outline command'); document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true})); const width=reader.querySelector('.pdfViewer .page').getBoundingClientRect().width; check(width>reader.getBoundingClientRect().width-60,'initially fit to width'); - reader.querySelector('[aria-label="Увеличить"]').click();await wait();await wait(); + reader.querySelector('[aria-label="Zoom in"]').click();await wait();await wait(); check(reader.querySelector('.pdfViewer .page').getBoundingClientRect().width>width,'zoom in increases page width'); check(Math.abs(reader.getBoundingClientRect().height-reader.querySelector('.pdfViewer .page').getBoundingClientRect().height-reader.querySelector('.pdf-toolbar').getBoundingClientRect().height)<20,'zoom updates height to one page'); - reader.querySelector('[aria-label="Уменьшить"]').click();await wait(); + reader.querySelector('[aria-label="Zoom out"]').click();await wait(); page.value='2';page.dispatchEvent(new Event('change',{bubbles:true})); await until(()=>reader.querySelector('.page[data-page-number="2"] .textLayer')?.textContent.includes('Second PDF page'),'page navigation renders page two'); await until(()=>Math.abs(reader.getBoundingClientRect().height-reader.querySelector('.page[data-page-number="2"]').getBoundingClientRect().height-reader.querySelector('.pdf-toolbar').getBoundingClientRect().height)<20,'height updates for a page with different dimensions'); - reader.querySelector('[aria-label="Свернуть/развернуть боковую панель"]').click(); + reader.querySelector('[aria-label="Toggle sidebar"]').click(); await until(()=>!reader.querySelector('.pdf-thumbnails').hidden&&reader.querySelectorAll('.pdf-thumbnails button').length===2,'thumbnail panel'); reader.querySelector('.pdf-thumbnails button').click();await until(()=>page.value==='1','thumbnail navigation'); - reader.querySelector('[data-pdf-action="display-options"]').click();[...document.querySelectorAll('.pdf-menu-panel button')].find(b=>b.dataset.label==='Подогнать по ширине').click();await wait(); + reader.querySelector('[data-pdf-action="display-options"]').click();[...document.querySelectorAll('.pdf-menu-panel button')].find(b=>b.dataset.label==='Fit width').click();await wait(); check(!reader.querySelector('iframe'),'native PDF UI replaced'); if(mode==='live'){ - check(reader.querySelector('[aria-label="Редактировать блок"]'),'PDF has edit-source button'); - useStore.setState({locked:true});await until(()=>!document.querySelector('[aria-label="Редактировать блок"]'),'locked PDF hides edit-source button'); - useStore.setState({locked:false});await until(()=>!!document.querySelector('[aria-label="Редактировать блок"]'),'unlock restores edit-source button'); - const edit=document.querySelector('[aria-label="Редактировать блок"]'); + check(reader.querySelector('[aria-label="Edit block"]'),'PDF has edit-source button'); + useStore.setState({locked:true});await until(()=>!document.querySelector('[aria-label="Edit block"]'),'locked PDF hides edit-source button'); + useStore.setState({locked:false});await until(()=>!!document.querySelector('[aria-label="Edit block"]'),'unlock restores edit-source button'); + const edit=document.querySelector('[aria-label="Edit block"]'); const before=useStore.getState().content;edit.click(); await until(()=>document.querySelector('.cm-content')?.textContent.includes('![[sample.pdf]]'),'edit button reveals exact embed source'); check(useStore.getState().content===before,'revealing source does not modify note'); await until(()=>document.querySelector('.pdf-reader[data-ready="true"] .textLayer')?.textContent.includes('First PDF page'),'PDF remains rendered while its embed source is selected'); check(document.querySelectorAll('.pdf-reader').length===1,'only one PDF viewer while editing source'); - }else check(!reader.querySelector('[aria-label="Редактировать блок"]'),'readonly views do not offer edit-source control'); + }else check(!reader.querySelector('[aria-label="Edit block"]'),'readonly views do not offer edit-source control'); root.render(
);await wait(); } for(const mode of ['live','reading','preview']){ useStore.setState({activePath:mode+'.md',content:'# PDF\\n\\n![[sample.pdf#page=2&height=400]]',viewMode:mode==='preview'?'reading':mode,locked:false}); root.render(mode==='preview'?:);await wait();await wait(); await until(()=>document.querySelector('.pdf-reader[data-ready="true"]'),'fragment PDF loaded'); - await until(()=>document.querySelector('.pdf-reader [aria-label="Номер страницы"]')?.value==='2',mode+': PDF opens requested page'); + await until(()=>document.querySelector('.pdf-reader [aria-label="Page number"]')?.value==='2',mode+': PDF opens requested page'); const expectedHeight=mode==='live'?400:400+document.querySelector('.pdf-reader .pdf-toolbar').getBoundingClientRect().height; check(Math.abs(document.querySelector('.pdf-reader').getBoundingClientRect().height-expectedHeight)<2,mode+': native explicit PDF height respected'); - document.querySelector('.pdf-reader [aria-label="Увеличить"]').click();await wait(); + document.querySelector('.pdf-reader [aria-label="Zoom in"]').click();await wait(); check(Math.abs(document.querySelector('.pdf-reader').getBoundingClientRect().height-expectedHeight)<2,mode+': explicit height survives zoom'); root.render(
);await wait(); } @@ -100,7 +100,7 @@ test('PDF embeds have working page, zoom and thumbnail controls in live, reading let opened;useStore.setState({activePath:'Host.md',content:'# Host\\n\\n![[Child]]',viewMode:mode==='preview'?'reading':mode,locked:false,openFile:async(path)=>{opened={path}}}); root.render(mode==='preview'?:);await wait();await wait(); await until(()=>document.querySelector('.pdf-reader[data-ready="true"]'),mode+': PDF inside embedded note has a viewer'); - await until(()=>document.querySelector('.pdf-reader [aria-label="Номер страницы"]')?.value==='2',mode+': nested PDF keeps page option'); + await until(()=>document.querySelector('.pdf-reader [aria-label="Page number"]')?.value==='2',mode+': nested PDF keeps page option'); document.querySelector('.pdf-reader [data-pdf-action="file-menu"]').click();await until(()=>document.querySelector('.pdf-menu-panel'),'nested PDF file menu');document.querySelector('.pdf-menu-panel button').click();await wait(); check(opened?.path==='Lab/sample.pdf'&&attachmentLookups.at(-1)?.from==='Lab/Child.md',mode+': nested PDF opens relative to its own note'); root.render(
);await wait(); @@ -109,17 +109,17 @@ test('PDF embeds have working page, zoom and thumbnail controls in live, reading await until(()=>document.querySelectorAll('.pdf-reader[data-ready="true"]').length===3,'three instances of the same PDF loaded'); const sameFile=[...document.querySelectorAll('.pdf-reader')]; for(const [index,reader] of sameFile.entries()){ - const expected=index===0?'1':'2';await until(()=>reader.querySelector('[aria-label="Номер страницы"]').value===expected,'same file instance '+index+' keeps its own page'); + const expected=index===0?'1':'2';await until(()=>reader.querySelector('[aria-label="Page number"]').value===expected,'same file instance '+index+' keeps its own page'); await until(()=>reader.querySelector('.page[data-page-number="'+expected+'"] .textLayer')?.textContent.includes(index===0?'First PDF page':'Second PDF page'),'same file instance '+index+' actually renders the requested page'); } root.render(
);await wait(); useStore.setState({activePath:'adjacent.md',content:'# PDFs\\n\\n![[one.pdf]]![[two.pdf]]',viewMode:'live',locked:false});root.render(); await until(()=>document.querySelectorAll('.pdf-reader[data-ready="true"]').length===2,'adjacent PDF viewers loaded'); - document.querySelectorAll('[aria-label="Редактировать блок"]')[1].click();await wait(); + document.querySelectorAll('[aria-label="Edit block"]')[1].click();await wait(); let selected=getActiveEditor().state.selection.main; check(getActiveEditor().state.doc.sliceString(selected.from,selected.to)==='![[two.pdf]]','second PDF button selects second source, not adjacent first'); await until(()=>document.querySelectorAll('.pdf-reader[data-ready="true"]').length===2,'adjacent previews remain visible'); - document.querySelectorAll('[aria-label="Редактировать блок"]')[1].click();await wait(); + document.querySelectorAll('[aria-label="Edit block"]')[1].click();await wait(); selected=getActiveEditor().state.selection.main; check(getActiveEditor().state.doc.sliceString(selected.from,selected.to)==='![[two.pdf]]','editing already-visible PDF source selects same source'); document.querySelector('#root').style.width='100%'; diff --git a/web/tests/publicEmbedsBrowser.test.ts b/web/tests/publicEmbedsBrowser.test.ts index 15feec8b..2a2b6d30 100644 --- a/web/tests/publicEmbedsBrowser.test.ts +++ b/web/tests/publicEmbedsBrowser.test.ts @@ -82,7 +82,7 @@ test('public SSR hydrates PDF and Canvas using only scoped share access, includi const reader=async()=>{ await until('!!document.querySelector(".pdf-reader[data-ready=true]")','public PDF loaded'); await until('!!document.querySelector(".canvas-embed[data-ready=true] .canvas-minimap")','public Canvas minimap loaded'); - await evaluate(\`(()=>{const root=document.querySelector('.pdf-reader'),page=root.querySelector('[aria-label="Номер страницы"]');if(page.value!=='2'||!root.querySelector('.pdf-page-count').textContent.includes('2'))throw Error('PDF fragment and count');if(Math.abs(root.getBoundingClientRect().height-438)>2)throw Error('PDF fixed Reading height');if(root.querySelector('[aria-label="Редактировать блок"]'))throw Error('Public reader has edit control');page.value='1';page.dispatchEvent(new Event('change'));if(!document.body.innerText.includes('After embeds'))throw Error('Following note content missing')})()\`); + await evaluate(\`(()=>{const root=document.querySelector('.pdf-reader'),page=root.querySelector('[aria-label="Page number"]');if(page.value!=='2'||!root.querySelector('.pdf-page-count').textContent.includes('2'))throw Error('PDF fragment and count');if(Math.abs(root.getBoundingClientRect().height-438)>2)throw Error('PDF fixed Reading height');if(root.querySelector('[aria-label="Edit block"]'))throw Error('Public reader has edit control');page.value='1';page.dispatchEvent(new Event('change'));if(!document.body.innerText.includes('After embeds'))throw Error('Following note content missing')})()\`); await until('document.querySelector(".pdf-reader .pdf-toolbar input").value==="1"','public PDF page control'); await evaluate('new Promise(r=>requestAnimationFrame(()=>requestAnimationFrame(r)))'); await evaluate("document.querySelector('.pdf-toolbar [data-pdf-action=zoom-in]').click()"); @@ -96,7 +96,7 @@ test('public SSR hydrates PDF and Canvas using only scoped share access, includi await win.loadURL(base+'/share/open');win.webContents.debugger.attach('1.3');await win.webContents.debugger.sendCommand('Emulation.setDeviceMetricsOverride',{width:1100,height:1200,deviceScaleFactor:1,mobile:false});await until('innerWidth===1100&&innerHeight===1200','explicit public viewport');await reader(); await evaluate('window.dispatchEvent(new PageTransitionEvent("pagehide",{persisted:true}));window.dispatchEvent(new PageTransitionEvent("pageshow",{persisted:true}))'); check(await evaluate('!!document.querySelector(".pdfViewer .page")'),'BFCache transition preserves PDF pages and workers'); - await evaluate('document.querySelector(".pdf-file-menu").click()');await until('!!document.querySelector(".pdf-menu-panel")','public file menu');check(await evaluate('!document.querySelector(".pdf-menu-panel [data-label=Переименовать]")'),'public menu excludes vault mutations');await evaluate('document.querySelector(".pdf-menu-panel button").click()');check(opened.some(url=>url.startsWith(base+'/public/shares/open/file?')&&url.includes('#page=2')),'PDF opens using public file URL'); + await evaluate('document.querySelector(".pdf-file-menu").click()');await until('!!document.querySelector(".pdf-menu-panel")','public file menu');check(await evaluate('!document.querySelector(".pdf-menu-panel [data-label=Rename]")'),'public menu excludes vault mutations');await evaluate('document.querySelector(".pdf-menu-panel button").click()');check(opened.some(url=>url.startsWith(base+'/public/shares/open/file?')&&url.includes('#page=2')),'PDF opens using public file URL'); if(process.env.WEBO_PUBLIC_CAPTURE)fs.writeFileSync(process.env.WEBO_PUBLIC_CAPTURE,(await win.webContents.capturePage()).toPNG()); await evaluate('document.querySelector(".canvas-embed .embed-title").click()'); await until('!!document.querySelector("#cv-world")','Canvas title opens full scoped board');