diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index 3b4aafc1..4e63a8f3 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -1,5 +1,45 @@ # IMPLEMENTATION PLAN — WebObsidian +CI follow-up 2026-10-30: the fork-main PR reproduced a hidden Electron selection-pixel timing race. The fixture now isolates its profile, disables background throttling, waits for the exact viewport and measured selection coverage, then waits up to four seconds for the selected compositor frame. All original theme, width, selected-pixel, unselected-background and margin assertions remain intact; no runtime/CSS changes are involved. + +The next CI run passed the complete test suite and exposed a smoke-startup race: `/healthz` was ready before the asynchronous initial index scan, so missing-file resolution correctly returned `503` rather than `404`. The smoke fixture now waits on authenticated `/api/index/status` availability and initial-scan completion before its existing resolver assertions. + +## Editor indentation and folding — 2026-10-30 + +- [x] Add four-column tab stops, literal Tab insertion and list/selection indentation with Shift-Tab outdent. +- [x] Add clickable folding for headings and nested indentation, including individual indented code statements; preserve code text literally and stop at the enclosing fence. +- [x] Indent/outdent a folded parent together with its hidden descendants; keep folding visual and support undo. +- [x] Add fenced-code indentation guides, standard folding shortcuts and command-palette fold/unfold actions. +- [x] Verify structural boundaries, readonly protection, mixed indentation and actual Editor keyboard/click behavior in Live Preview and Source. + +Progress 2026-10-30: structural unit tests and the actual React Editor browser regression passed; web typecheck passed. Full tests/build recorded in the task result. + +Follow-up 2026-10-30: the original ABAP screenshot requires folding inside fenced code, not only the enclosing block. Removed the code-interior exclusion, bounded nested folds by code syntax nodes, and added independent fold/unfold clicks for both ABAP calls in Live Preview and Source. Seven structural unit tests and the browser regression passed before full verification. + +Original comparison 2026-10-30: inspected installed Obsidian 1.14.5 in an isolated synthetic vault. Measurements in `tests/fixtures/rendering/obsidian-folding.json` confirm inline controls at the first non-whitespace character (no left gutter), no generic paragraph or enclosing code-fence folds, and saved fold state after reopening. Four typed spaces remain four spaces; both tabs and spaces participate in indentation folding. Web now follows those rules and saves view state in browser storage scoped by vault and path, without storing note text. Browser regressions cover document recreation, vault isolation and a deep heading restored after asynchronous hydration of a 5,000-line note. + +## Draft recovery usability — 2026-10-30 + +- [x] Replace the persistent draft counter with an actionable unsaved-text recovery list; hide empty lists and ordinary live autosaves. +- [x] Explain browser copies and provide Review text, Download copy and Remove browser copy actions with vault-safe removal confirmation. +- [x] Explain deleted originals and require an explicit separate copy to recover their text. +- [x] Extend real-browser coverage for recovery, removal, deleted originals, normal autosaves and mobile keyboard/zoom positioning. + +Progress 2026-10-30: recovery/viewport browser regressions, web typecheck, full `npm test` (288 server + 417 web passed; 10 server skips) and production build passed. Independent code review reported no actionable findings. + +## Remote MCP, indexing and editor recovery integration — 2026-10-30 + +- [x] Integrate authenticated remote MCP alongside local stdio and scoped keys. +- [x] Integrate cached indexing, reconciliation/hash audits and automatic search refresh. +- [x] Integrate module-based plugins, draft recovery, conflict resolution and adaptive toolbar layouts. +- [x] Preserve data-safety and authentication fixes with regression coverage. + +The upstream contribution retains one consolidated commit and source attribution. +Runtime sources and configuration match the reviewed integrated source tree; +upstream repository routing is applied separately in documentation and desktop metadata. +The viewport regression waits for exact expected dimensions before its unchanged zoom +and toolbar assertions, avoiding reads of the previous asynchronous layout. + ## Review fixes — 2026-10-30 - [x] R1: CLI default recovery password, including old installations. diff --git a/scripts/integration-smoke.mjs b/scripts/integration-smoke.mjs index 8c92a293..361aaf0e 100644 --- a/scripts/integration-smoke.mjs +++ b/scripts/integration-smoke.mjs @@ -64,6 +64,20 @@ try { const request = (url, options = {}) => fetch(`${base}${url}`, { ...options, headers: { cookie, 'content-type': 'application/json', ...options.headers }, }); + // /healthz means the process is listening. Resolver assertions require the + // asynchronous initial index scan to finish before a missing file is a 404. + let indexStatus; + const indexDeadline = Date.now() + 10_000; + do { + const response = await request('/api/index/status'); + assert.equal(response.status, 200); + indexStatus = await response.json(); + if (indexStatus.initialScanComplete && indexStatus.available) break; + if (server.exitCode !== null) throw new Error(`server exited during indexing: ${output}`); + await delay(25); + } while (Date.now() < indexDeadline); + assert.ok(indexStatus?.initialScanComplete && indexStatus.available, + `initial index did not become ready: ${JSON.stringify(indexStatus)}\n${output}`); const settings = await (await request('/api/settings')).json(); assert.equal(settings.vault.trashRetentionDays, 0); const locked = await (await request('/api/files/content?path=notes/locked.md')).json(); diff --git a/server/src/services/git.integration.test.ts b/server/src/services/git.integration.test.ts index d4e21e75..1e1dfda7 100644 --- a/server/src/services/git.integration.test.ts +++ b/server/src/services/git.integration.test.ts @@ -5,6 +5,8 @@ import path from 'node:path'; import { execFile } from 'node:child_process'; import { promisify } from 'node:util'; import { simpleGit } from 'simple-git'; +import { mutateFileText, withVaultMutation } from './vault.js'; +import { checkVersion, contentVersion } from './noteversion.js'; const exec = promisify(execFile); const T = 20_000; // generous per-test timeout — these shell out to real git @@ -12,7 +14,7 @@ const T = 20_000; // generous per-test timeout — these shell out to real git // Full git settings; vault.path is set per test to a fresh temp repo. const { settings } = vi.hoisted(() => ({ settings: { - vault: { path: '', trash: '.trash' }, + vault: { path: '', trash: '.trash', allowedRoots: [] as string[] }, git: { enabled: true, autoSync: false, @@ -86,6 +88,109 @@ afterEach(async () => { }); describe.skipIf(!gitOnPath)('git integration (real repo)', () => { + it('a queued push keeps its vault and remote settings together across a vault switch', async () => { + await git.init(); + await fs.writeFile(path.join(work, 'Note.md'), 'vault A'); + await git.commitAll(); + const next = await fs.mkdtemp(path.join(os.tmpdir(), 'wo-next-vault-')); + const nextRemote = await fs.mkdtemp(path.join(os.tmpdir(), 'wo-next-remote-')); + let entered!: () => void, release!: () => void; + const started = new Promise(r => { entered = r; }); + const gate = new Promise(r => { release = r; }); + const mutation = withVaultMutation(async () => { entered(); await gate; }); + let pushing: Promise | undefined; + try { + await exec('git', ['init', '--bare', '-b', 'main', nextRemote]); + await started; + pushing = git.push(); + // Let the push join the occupied vault queue before changing settings. + await new Promise(r => setTimeout(r, 100)); + settings.vault.path = next; + settings.git.remote = nextRemote; + release(); await mutation; await pushing; + expect((await exec('git', ['-C', work, 'remote', 'get-url', 'origin'])).stdout.trim()).toBe(bare); + expect((await exec('git', ['--git-dir', bare, 'show', 'main:Note.md'])).stdout).toBe('vault A'); + expect((await exec('git', ['--git-dir', nextRemote, 'for-each-ref'])).stdout).toBe(''); + } finally { + release(); await mutation; await pushing?.catch(() => {}); + await fs.rm(next, { recursive: true, force: true }); + await fs.rm(nextRemote, { recursive: true, force: true }); + } + }, T); + async function remoteNoteUpdate() { + await git.init(); + await fs.writeFile(path.join(work, 'Note.md'), 'base'); + expect((await git.sync()).ok).toBe(true); + const peer = await fs.mkdtemp(path.join(os.tmpdir(), 'wo-peer-')); + try { + await exec('git', ['clone', bare, peer]); + await fs.writeFile(path.join(peer, 'Note.md'), 'remote'); + await exec('git', ['-C', peer, 'add', '.']); + await exec('git', ['-C', peer, 'commit', '-m', 'remote edit']); + await exec('git', ['-C', peer, 'push']); + } finally { await fs.rm(peer, { recursive: true, force: true }); } + } + + function saveLocal() { + return mutateFileText('Note.md', current => { + if (!checkVersion(current, contentVersion('base')).ok) { + throw Object.assign(new Error('version_conflict'), { status: 409 }); + } + return { content: 'local', result: undefined }; + }); + } + + it.each(['pull', 'sync'] as const)('%s waits for an accepted save and cannot overwrite it mid-write', async operation => { + await remoteNoteUpdate(); + let entered!: () => void, release!: () => void; + const started = new Promise(r => { entered = r; }); + const gate = new Promise(r => { release = r; }); + const open = fs.open.bind(fs); + const spy = vi.spyOn(fs, 'open').mockImplementation(async (...args: Parameters) => { + if (String(args[0]).includes('Note.md.tmp-')) { entered(); await gate; } + return open(...args); + }); + const saving = saveLocal(); + let pulling: Promise | undefined; + try { + await started; + pulling = (operation === 'pull' ? git.pull().then(() => 'pulled') + : git.sync().then(result => result.ok ? 'pulled' : 'rejected')).catch(() => 'rejected'); + const result = await Promise.race([pulling, new Promise(r => setTimeout(() => r('waiting'), 1000))]); + expect(result).toBe('waiting'); + release(); await saving; + expect(await pulling).toBe('rejected'); // Git protects the now-dirty local note. + expect(await fs.readFile(path.join(work, 'Note.md'), 'utf8')).toBe('local'); + expect((await exec('git', ['-C', work, 'show', 'HEAD:Note.md'])).stdout).toBe(operation === 'sync' ? 'local' : 'base'); + expect((await git.status()).conflicted).toEqual([]); + } finally { release(); await saving; await pulling; spy.mockRestore(); } + }, T); + + it.each(['pull', 'sync'] as const)('a save queued behind %s checks the pulled version and reports a conflict', async operation => { + settings.git.lfsPatterns = ['*.png']; + await remoteNoteUpdate(); + let entered!: () => void, release!: () => void; + const started = new Promise(r => { entered = r; }); + const gate = new Promise(r => { release = r; }); + const read = fs.readFile.bind(fs); + const spy = vi.spyOn(fs, 'readFile').mockImplementation((async (...args: Parameters) => { + if (String(args[0]) === path.join(work, '.gitattributes')) { entered(); await gate; } + return read(...args); + }) as typeof fs.readFile); + const pulling = (operation === 'pull' ? git.pull().then(() => 'pulled') + : git.sync().then(result => result.ok ? 'pulled' : 'rejected')).catch(() => 'rejected'); + let saving: Promise | undefined; + try { + await started; + saving = saveLocal().then(() => 'saved', error => error.status); + const result = await Promise.race([saving, new Promise(r => setTimeout(() => r('waiting'), 100))]); + expect(result).toBe('waiting'); + release(); + expect(await pulling).toBe('pulled'); + expect(await saving).toBe(409); + expect(await fs.readFile(path.join(work, 'Note.md'), 'utf8')).toBe('remote'); + } finally { release(); await pulling; await saving; spy.mockRestore(); } + }, T); it('uses the temporary global Git configuration for simple-git child processes', async () => { const origin = await simpleGit({ baseDir: work }).raw(['config', '--global', '--show-origin', '--get', 'user.name']); expect(origin.replace(/\\/g, '/').includes(cfgHome.replace(/\\/g, '/'))).toBe(true); diff --git a/server/src/services/git.ts b/server/src/services/git.ts index 9ecac39e..7213e1b0 100644 --- a/server/src/services/git.ts +++ b/server/src/services/git.ts @@ -1,11 +1,16 @@ import { promises as fs } from 'node:fs'; import path from 'node:path'; +import { AsyncLocalStorage } from 'node:async_hooks'; import { simpleGit, type SimpleGit, type StatusResult } from 'simple-git'; -import { getSettings } from './settings.js'; -import { getVaultRoot } from './vault.js'; +import { getSettings as loadSettings } from './settings.js'; +import { getVaultRoot, withVaultMutation } from './vault.js'; import { redactUrlCreds } from '../lib/redact.js'; /** GitHub-native sync with Git LFS support (PRD FR-4). */ +const operationSettings = new AsyncLocalStorage>>(); +async function getSettings() { + return operationSettings.getStore() ?? loadSettings(); +} export interface GitStatus { enabled: boolean; @@ -38,10 +43,10 @@ async function git(): Promise { // `commit` collide on `.git/index.lock` ("Another git process seems to be // running") — and a command killed mid-write leaves that lock behind, which then // wedges EVERY later op (the "completely dead" state). Funnelling all mutating -// ops through one async queue removes the race; clearing a stale lock at the head +// ops through the vault mutation queue removes the race with both Git commands +// and version-checked saves; clearing a stale lock at the head // of each op heals a leftover from a crash or an external Obsidian-git process. // --------------------------------------------------------------------------- -let gitQueue: Promise = Promise.resolve(); /** A lock a live git process holds is gone within a second for a notes vault; one * older than this is orphaned. Generous enough that even an external LFS commit @@ -67,21 +72,26 @@ async function clearStaleLocks(): Promise { /** Run `fn` with exclusive access to the vault repo, after self-healing any stale * lock. Ops queue (never overlap); a rejecting op doesn't poison the queue. */ -function withGitLock(fn: () => Promise): Promise { - const result = gitQueue.then(async () => { - await clearStaleLocks(); - return fn(); +async function withGitLock(fn: () => Promise): Promise { + // Hold the same canonical-root lock as compare-and-set + atomic file writes + // for the ENTIRE operation (including all of sync's commit/pull/push steps). + // Capture the vault before waiting, as ordinary file mutations do. + const settings = structuredClone(await loadSettings()); + return withVaultMutation(async () => { + // A settings switch between the two captures must never pair one vault + // with another vault's remote. Once admitted, use this snapshot throughout. + if (path.resolve(settings.vault.path) !== await getVaultRoot()) { + throw Object.assign(new Error('Vault changed; retry the Git operation'), { status: 409 }); + } + return operationSettings.run(settings, async () => { + await clearStaleLocks(); + return fn(); + }); }); - gitQueue = result.then( - () => undefined, - () => undefined, - ); - return result; } // Public, serialized git operations. Each delegates to its private *Impl below; -// callers that already hold the lock (e.g. syncImpl) call the *Impl directly to -// avoid re-entering the queue and dead-locking. +// callers that already hold the lock (e.g. syncImpl) call the *Impl directly. export const status = (): Promise => withGitLock(statusImpl); export const pull = (): Promise => withGitLock(pullImpl); export const push = (): Promise => withGitLock(pushImpl); @@ -457,7 +467,7 @@ async function recoverMerge(g: SimpleGit): Promise { /** Convenience: stage+commit+pull+push in one go. Reports conflicts. Runs entirely * inside the git queue (via the exported `sync` wrapper), so it calls the unlocked - * *Impl helpers directly — re-entering withGitLock here would dead-lock. */ + * *Impl helpers directly so the transaction retains its settings snapshot. */ async function syncImpl(message?: string): Promise<{ ok: boolean; log: string[] }> { const log: string[] = []; const g = await git(); diff --git a/tests/fixtures/rendering/obsidian-folding.json b/tests/fixtures/rendering/obsidian-folding.json new file mode 100644 index 00000000..9ec88e1a --- /dev/null +++ b/tests/fixtures/rendering/obsidian-folding.json @@ -0,0 +1,154 @@ +{ + "observations": [ + { + "name": "spaces", + "text": "parent\n child\n grandchild\nsibling", + "indicators": [ + { + "line": 1, + "offset": 0, + "left": 376, + "top": 159.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + }, + { + "line": 2, + "offset": 4, + "left": 412, + "top": 183.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + } + ], + "gutter": false + }, + { + "name": "tabs", + "text": "parent\n\tchild\n\t\tgrandchild\nsibling", + "indicators": [ + { + "line": 1, + "offset": 0, + "left": 376, + "top": 159.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + }, + { + "line": 2, + "offset": 1, + "left": 412, + "top": 183.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + } + ], + "gutter": false + }, + { + "name": "abapSpaces", + "text": "```abap\nroot\n call( EXPORTING start\n IMPORTING begin ).\n\n call( EXPORTING end\n IMPORTING finish ).\n```", + "indicators": [ + { + "line": 2, + "offset": 0, + "left": 392, + "top": 180.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + }, + { + "line": 3, + "offset": 4, + "left": 423.5, + "top": 201.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + }, + { + "line": 6, + "offset": 4, + "left": 423.5, + "top": 264.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + } + ], + "gutter": false + }, + { + "name": "abapTabs", + "text": "```abap\nroot\n\tcall( EXPORTING start\n\t\tIMPORTING begin ).\n\n\tcall( EXPORTING end\n\t\tIMPORTING finish ).\n```", + "indicators": [ + { + "line": 2, + "offset": 0, + "left": 392, + "top": 180.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + }, + { + "line": 3, + "offset": 1, + "left": 423.5, + "top": 201.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + }, + { + "line": 6, + "offset": 1, + "left": 423.5, + "top": 264.046875, + "position": "absolute", + "right": "0px", + "topStyle": "0px" + } + ], + "gutter": false + } + ], + "folded": { + "folds": [ + { + "from": 2, + "to": 3 + } + ], + "lines": 8 + }, + "beforeReopen": 1, + "afterReopen": 1, + "keyboard": { + "typed": [ + { + "spacesTyped": 1, + "text": "parent\n child" + }, + { + "spacesTyped": 2, + "text": "parent\n child" + }, + { + "spacesTyped": 3, + "text": "parent\n child" + }, + { + "spacesTyped": 4, + "text": "parent\n child" + } + ], + "afterTab": "parent\n\t child" + } +} \ No newline at end of file diff --git a/web/src/components/CommandPalette.tsx b/web/src/components/CommandPalette.tsx index 0d2586c4..7f61f99f 100644 --- a/web/src/components/CommandPalette.tsx +++ b/web/src/components/CommandPalette.tsx @@ -1,6 +1,7 @@ import {pluginCommands,usePluginRevision} from '../lib/plugins/registry'; import {commands as editorToolbarCommands,captureContext,executeCommand} from '../lib/toolbar/registry'; import {getActiveEditor} from '../lib/activeEditor'; +import {foldAll,unfoldAll,foldCode,unfoldCode} from '@codemirror/language'; import { useEffect, useMemo, useState } from 'react'; import { useStore } from '../lib/store'; import { api, type TreeNode } from '../lib/api'; @@ -84,6 +85,12 @@ export default function CommandPalette() { { id: 'reading', title: 'View: Reading mode', run: () => setViewMode('reading') }, { id: 'live', title: 'View: Live edit', run: () => setViewMode('live') }, { id: 'source', title: 'View: Source', run: () => setViewMode('source') }, + ...([ + ['fold-more','Fold more',foldCode],['fold-less','Fold less',unfoldCode], + ['fold-all','Fold all headings and lists',foldAll],['unfold-all','Unfold all headings and lists',unfoldAll], + ] as const).map(([id,title,command])=>({id,title,run:()=>{ + const view=getActiveEditor();if(view){command(view);view.focus();} + }})), { id: 'reindex', title: 'Rebuild search index', run: async () => { notify('Rebuilding search index…', 0); try { diff --git a/web/src/components/ConflictResolver.tsx b/web/src/components/ConflictResolver.tsx index b5320038..1fd4972b 100644 --- a/web/src/components/ConflictResolver.tsx +++ b/web/src/components/ConflictResolver.tsx @@ -78,9 +78,10 @@ export default function ConflictResolver({ session, onClose }: { setBusy(false); } }; - return

Resolve: {session.source.path}

Result is editable. Keep your changes or use the server version for individual highlighted sections.

+ return

Review recovered text: {session.source.path}

+ {remote===null?

Original file was deleted. This browser copy has not restored it. Save a copy if you want to keep this text, or close this review and remove the browser copy if the deletion was intentional.

:

Compare this browser copy with the file in your vault. Edit the result below, then save it to the original file or save a separate copy. Nothing changes in your vault until you save.

}
Base version
{session.source.baseContent}
Local version
{session.source.content}
Server version{remote === null ? ' (deleted)' : ''}
{remote}
{(!canDiff(session.result) || /\.canvas$/i.test(session.source.path)) &&

Whole-document editor. For Canvas, choose a complete valid document or save a copy.

} -
- {error &&

{error}

}
; +
+ {error &&

{error}

}
; } diff --git a/web/src/components/DraftRecovery.tsx b/web/src/components/DraftRecovery.tsx index 9a257d45..285724c3 100644 --- a/web/src/components/DraftRecovery.tsx +++ b/web/src/components/DraftRecovery.tsx @@ -27,14 +27,37 @@ export default function DraftRecovery(){ },[authed]); const session=path?documentSessions.get(path):undefined; const compare=async(record:DraftRecord)=>{const epoch=draftScopeEpoch();try{const result=await loadConflict(record);if(mounted.current&&isDraftScopeCurrent(record.scopeId,epoch))setConflict(result);}catch(e){if(mounted.current&&epoch===draftScopeEpoch())setError(String(e));}}; - const discard=async(record:DraftRecord)=>{const epoch=draftScopeEpoch();try{if(!await confirmDialog('Delete this local draft?'))return;assertDraftScope(record.scopeId,epoch);await deleteDraftIfRevision(record,record.revision);await refresh();}catch(e){if(epoch===draftScopeEpoch())setError(String(e));}}; + const discard=async(record:DraftRecord)=>{const epoch=draftScopeEpoch();try{ + if(!await confirmDialog('Remove this browser copy?',{confirmLabel:'Remove copy',danger:true,detail:'This does not delete or change the file in your vault. Only this recovery copy will be removed.'}))return; + assertDraftScope(record.scopeId,epoch); + const removed=await deleteDraftIfRevision(record,record.revision);await refresh(); + if(!removed&&isDraftScopeCurrent(record.scopeId,epoch))setError('This copy changed while you were reviewing it. Review the latest text before removing it.'); + }catch(e){if(epoch===draftScopeEpoch())setError(String(e));}}; if(!authed)return null; + // A live editor's ordinary autosave is already represented by its save status. + // Only detached copies and failed/conflicting saves need a recovery action. + const recoverable=records.filter(record=>{ + const live=documentSessions.get(record.path); + return !live||live.key.writerId!==record.writerId||['conflict','error','saved'].includes(live.state); + }); + if(!session&&!dirty&&!error&&!recoverable.length&&!expanded)return null; return <>
- {session?.localError?'Local save failed':session?({modified:'Modified',saving:'Saving…',local:'Saved locally',saved:'Saved on server',conflict:'Conflict',error:'Save failed'}[session.state]):dirty?'Modified':error?'Local drafts unavailable':''} + {session?.localError?'Browser backup failed':session?({modified:'Saving changes…',saving:'Saving to vault…',local:'Backed up in this browser · saving to vault…',saved:'Saved to vault',conflict:'Changes need review',error:'Not saved to vault'}[session.state]):dirty?'Saving changes…':error?'Recovery copies unavailable':''} {session?.localError&&} {session?.state==='conflict'&&} - + {(recoverable.length>0||expanded)&&} {error&&!expanded&&{error}} - {expanded&&
{error&&

{error}

}{records.map(r=>
{r.path} {new Date(r.updatedAt).toLocaleString()}
)}
}
+ {expanded&&
+

Unsaved text recovery

+

These browser copies may contain text that was not saved to your vault. You do not need to manage this list during normal editing.

+

Review a copy to recover text you need, or remove it if you no longer need it. Reviewing does not change or restore a file.

+ {error&&

{error}

} + {!recoverable.length&&

No text needs recovery. Your current edits are saved automatically.

} + {recoverable.map(r=>
+ {r.path}Browser copy · {new Date(r.updatedAt).toLocaleString()} +

{r.state==='conflict'?'This copy could not be saved because the file changed. Review both versions.':r.state==='recovery'?'You left a recovery in progress. Review it to continue.':'This copy was kept for recovery. Review it before deciding whether to keep the text.'}

+
+
)} +
} {conflict&&{setConflict(null);void refresh();}}/>}; } diff --git a/web/src/components/Editor.tsx b/web/src/components/Editor.tsx index a7eb5969..b535bd94 100644 --- a/web/src/components/Editor.tsx +++ b/web/src/components/Editor.tsx @@ -1,16 +1,17 @@ import {captureContext,executeCommand,commands as toolbarCommands} from '../lib/toolbar/registry'; -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState, useSyncExternalStore } from 'react'; import DocOutline from './DocOutline'; import { Compartment, EditorState, Prec } from '@codemirror/state'; import { EditorView, keymap, highlightActiveLine, drawSelection, rectangularSelection, crosshairCursor } from '@codemirror/view'; -import { defaultKeymap, simplifySelection, history, historyKeymap, indentWithTab } from '@codemirror/commands'; +import { defaultKeymap, simplifySelection, history, historyKeymap } from '@codemirror/commands'; +import { editorStructure, outlineMarkdown, persistentFolding } from '../lib/editorStructure'; import { search, searchKeymap } from '@codemirror/search'; import { markdown, markdownLanguage } from '@codemirror/lang-markdown'; import { yamlFrontmatter } from '@codemirror/lang-yaml'; import { languages } from '@codemirror/language-data'; import { syntaxHighlighting } from '@codemirror/language'; import { obsidianHighlightStyle, literalAngleColors } from '../lib/highlight'; -import { useStore } from '../lib/store'; +import { useStore, documentSessions } from '../lib/store'; import type { TreeNode } from '../lib/api'; import { obsidianKeymap } from '../lib/editorCommands'; import Icon from './Icon'; @@ -54,6 +55,11 @@ import { humanizeTitle } from '../lib/title'; import { deleteEmbeddedImage } from '../lib/imageDelete'; const titleOf = (path: string | null) => (path ? humanizeTitle(path) : ''); +const subscribeDocumentScope = (listener:()=>void) => { + window.addEventListener('draft-status',listener); + window.addEventListener('draft-scope-change',listener); + return ()=>{window.removeEventListener('draft-status',listener);window.removeEventListener('draft-scope-change',listener);}; +}; // Reading mode = the same Live Preview editor, made read-only via this compartment. const readonlyExt = (reading: boolean) => @@ -69,6 +75,7 @@ export default function Editor() { const readonlyComp = useRef(new Compartment()).current; const applyingExternal = useRef(false); const activePath = useStore((s) => s.activePath); + const documentScope=useSyncExternalStore(subscribeDocumentScope,()=>activePath?documentSessions.get(activePath)?.key.scopeId??'':'',()=> ''); const content = useStore((s) => s.content); const setContent = useStore((s) => s.setContent); const save = useStore((s) => s.save); @@ -201,11 +208,13 @@ export default function Editor() { ), // In-document Find/Replace (⌘F / ⌘⇧F open the panel; ⌘G next). search({ top: true }), - keymap.of([{ key: 'Escape', run: simplifySelection }, ...defaultKeymap, ...historyKeymap, ...searchKeymap, indentWithTab]), + keymap.of([{ key: 'Escape', run: simplifySelection }, ...defaultKeymap, ...historyKeymap, ...searchKeymap]), + editorStructure, + persistentFolding(documentScope,activePath??''), // GFM base so Strikethrough/Table/TaskList nodes exist (Obsidian dialect); // codeLanguages lazy-loads grammars for fenced blocks (Obsidian: Prism). // YAML front matter (--- … ---) is parsed as YAML; the rest stays Markdown. - yamlFrontmatter({ content: markdown({ base: markdownLanguage, codeLanguages: languages }) }), + yamlFrontmatter({ content: markdown({ base: markdownLanguage, codeLanguages: languages,extensions:[outlineMarkdown] }) }), suggesterPlugin, // Obsidian token palette via CSS vars (works in both themes); markdown // structure styling is owned by the Live Preview decorations. @@ -250,7 +259,7 @@ export default function Editor() { v.destroy(); }; // eslint-disable-next-line react-hooks/exhaustive-deps - }, [activePath]); + }, [activePath,documentScope]); // Sync the editor doc when `content` changes from OUTSIDE the editor — e.g. the // active note's content arrives asynchronously after reload/hydrate, or is diff --git a/web/src/lib/editorStructure.ts b/web/src/lib/editorStructure.ts new file mode 100644 index 00000000..4f1b7c19 --- /dev/null +++ b/web/src/lib/editorStructure.ts @@ -0,0 +1,200 @@ +import { EditorState, EditorSelection, Prec, countColumn, type StateCommand } from '@codemirror/state'; +import { Decoration, EditorView, ViewPlugin, WidgetType, keymap, type DecorationSet } from '@codemirror/view'; +import { indentLess, indentMore, insertTab } from '@codemirror/commands'; +import { codeFolding, foldable, foldEffect, unfoldEffect, forceParsing, foldKeymap, foldNodeProp, foldService, foldedRanges, indentUnit, syntaxTree } from '@codemirror/language'; + +// Obsidian uses heading/indent services rather than generic Markdown node folds. +export const outlineMarkdown = {props:[foldNodeProp.add(()=>()=>null)]}; + +class FoldIndicator extends WidgetType { + constructor(readonly collapsed:boolean){super();} + eq(other:FoldIndicator){return this.collapsed===other.collapsed;} + toDOM(view:EditorView){ + const wrap=document.createElement('span');wrap.className='cm-fold-indicator'+(this.collapsed?' is-collapsed':''); + wrap.append('\u200b'); + const button=document.createElement('button');button.className='cm-outline-collapse'; + button.type='button';button.setAttribute('aria-label',this.collapsed?'Expand section':'Collapse section'); + button.setAttribute('aria-expanded',String(!this.collapsed));button.title=this.collapsed?'Expand section':'Collapse section'; + button.textContent=this.collapsed?'▸':'▾';wrap.append(button); + button.addEventListener('mousedown',e=>e.preventDefault()); + button.addEventListener('click',e=>{ + e.preventDefault();e.stopPropagation(); + const line=view.state.doc.lineAt(view.posAtDOM(wrap));let current:{from:number;to:number}|undefined; + foldedRanges(view.state).between(line.from,line.to,(from,to)=>{if(!current)current={from,to};}); + const range=current??foldable(view.state,line.from,line.to); + if(range)view.dispatch({effects:(current?unfoldEffect:foldEffect).of(range)}); + });return wrap; + } + ignoreEvent(){return false;} +} +function indicators(view:EditorView):DecorationSet { + const ranges=[]; + for(const line of view.viewportLineBlocks){ + let collapsed=false;foldedRanges(view.state).between(line.from,line.to,()=>{collapsed=true;}); + if(collapsed||foldable(view.state,line.from,line.to)){ + const start=line.from+(view.state.doc.lineAt(line.from).text.match(/^[\t ]*/)?.[0].length??0); + ranges.push(Decoration.widget({widget:new FoldIndicator(collapsed),side:-1}).range(start)); + } + }return Decoration.set(ranges,true); +} +const inlineFolding=ViewPlugin.fromClass(class { + decorations:DecorationSet; + constructor(view:EditorView){this.decorations=indicators(view);} + update(u:import('@codemirror/view').ViewUpdate){ + if(u.docChanged||u.viewportChanged||foldedRanges(u.startState)!==foldedRanges(u.state)||syntaxTree(u.startState)!==syntaxTree(u.state))this.decorations=indicators(u.view); + } +},{decorations:p=>p.decorations}); + +function fingerprint(state:EditorState){ + let hash=2166136261;const text=state.doc.toString(); + for(let n=0;n>>0).toString(16); +} +/** Browser/vault scoped view state only; Markdown and draft contents are untouched. */ +export function persistentFolding(scope:string,path:string){ + if(!scope||!path)return []; + const key='webobsidian-folds-v1:'+JSON.stringify([scope,path]); + return ViewPlugin.fromClass(class { + timer:ReturnType|undefined;restore:ReturnType;ready=false; + constructor(readonly view:EditorView){ + this.restore=setTimeout(()=>this.load(),0); + } + load(){ + const {view}=this; + try{ + const saved=JSON.parse(localStorage.getItem(key)??'null'); + if(saved?.hash!==fingerprint(view.state)||!Array.isArray(saved.folds)){this.ready=true;return;} + const valid=saved.folds.filter((row:{line:number})=>Number.isInteger(row.line)&&row.line>=1&&row.line<=view.state.doc.lines); + // Heading folding needs the section after its header as well. Parse + // the complete saved document before asking for structural ranges. + const upto=valid.length?view.state.doc.length:0; + if(!forceParsing(view,upto,50)){this.restore=setTimeout(()=>this.load(),50);return;} + const effects=[]; + for(const row of valid){ + const line=view.state.doc.line(row.line),range=foldable(view.state,line.from,line.to); + if(range)effects.push(foldEffect.of(range)); + } + this.ready=true; + if(effects.length)view.dispatch({effects}); + }catch{this.ready=true;/* Storage is optional; folding remains usable. */} + } + save(){ + clearTimeout(this.timer); + const folds:{line:number}[]=[]; + foldedRanges(this.view.state).between(0,this.view.state.doc.length,from=>{folds.push({line:this.view.state.doc.lineAt(from).number});}); + try{localStorage.setItem(key,JSON.stringify({hash:fingerprint(this.view.state),folds}));}catch{} + } + update(u:import('@codemirror/view').ViewUpdate){ + if(u.docChanged||foldedRanges(u.startState)!==foldedRanges(u.state)){ + this.ready=true;clearTimeout(this.restore); + clearTimeout(this.timer);this.timer=setTimeout(()=>this.save(),200); + } + } + destroy(){clearTimeout(this.restore);if(this.ready)this.save();} + }); +} + +function shiftOutline(target: Parameters[0], less: boolean): boolean { + const {state}=target; + if(state.readOnly)return false; + let expanded=false; + const ranges=state.selection.ranges.map(range=>{ + let end=range.to; + const last=state.doc.lineAt(range.to); + const lineEnd=!range.empty&&range.to===last.from?range.to-1:last.to; + foldedRanges(state).between(state.doc.lineAt(range.from).from,lineEnd,(from,to)=>{ + if(state.doc.lineAt(from).from<=lineEnd){end=Math.max(end,to);expanded=true;} + }); + return EditorSelection.range(range.from,end); + }); + const command=less?indentLess:indentMore; + if(!expanded)return command(target); + const selected=state.update({selection:EditorSelection.create(ranges)}).state; + return command({state:selected,dispatch:tr=>target.dispatch(state.update({ + changes:tr.changes,selection:state.selection.map(tr.changes),userEvent:'indent',scrollIntoView:true, + }))}); +} +export const outdentOutline: StateCommand = target=>shiftOutline(target,true); + +function codeBlockAt(state: EditorState, pos: number) { + const line=state.doc.lineAt(pos); + const contentStart=line.from+(line.text.match(/^[\t ]*/)?.[0].length??0); + for(let node=syntaxTree(state).resolve(contentStart,1);node;node=node.parent!) { + if(node.name==='FencedCode'||node.name==='CodeBlock')return node; + } + return null; +} +const inCode=(state:EditorState,pos:number)=>codeBlockAt(state,pos)!==null; + +/** Fold indentation both in prose and code, bounded by the enclosing code block. */ +export function indentFold(state: EditorState, start: number, end: number): {from:number;to:number}|null { + const line=state.doc.lineAt(start); + const code=codeBlockAt(state,start); + if(!line.text.trim()||(!code&&/^\s*#{1,6}\s/.test(line.text)))return null; + let lastLine=state.doc.lines; + if(code){ + lastLine=state.doc.lineAt(code.to).number; + if(code.name==='FencedCode'){ + const marks=code.getChildren('CodeMark'); + if(marks.some(mark=>state.doc.lineAt(mark.from).number===line.number))return null; + const closing=marks.length>1?marks[marks.length-1]:null; + if(closing)lastLine=state.doc.lineAt(closing.from).number-1; + } + } + const depth=countColumn(line.text.match(/^[\t ]*/)?.[0]??'',state.tabSize); + let to=end; + for(let n=line.number+1;n<=lastLine;n++) { + const child=state.doc.line(n); + if(!child.text.trim())continue; + const indent=countColumn(child.text.match(/^[\t ]*/)?.[0]??'',state.tabSize); + if(indent<=depth)break; + to=child.to; + } + return to>end?{from:end,to}:null; +} + +/** A caret inserts a literal tab; list items and selections move by one level. */ +export const tabIndent: StateCommand = target => { + if(target.state.readOnly)return false; + const list=target.state.selection.ranges.some(range=>{ + const line=target.state.doc.lineAt(range.head); + return !inCode(target.state,line.from)&&/^[\t ]*(?:[-*+]|\d+[.)])\s/.test(line.text); + }); + let folded=false; + for(const range of target.state.selection.ranges)foldedRanges(target.state).between(target.state.doc.lineAt(range.head).from,target.state.doc.lineAt(range.head).to,()=>{folded=true;}); + return list||folded||target.state.selection.ranges.some(r=>!r.empty)?shiftOutline(target,false):insertTab(target); +}; + +function guides(view: EditorView): DecorationSet { + const ranges=[]; + const seen=new Set(); + for(const visible of view.visibleRanges) { + for(let n=view.state.doc.lineAt(visible.from).number;n<=view.state.doc.lines;n++) { + const line=view.state.doc.line(n); + if(line.from>visible.to)break; + if(seen.has(n))continue;seen.add(n); + // Live Preview already owns guides on lists and indented code. Add the + // guides inside fenced blocks, where language syntax must remain literal. + const ws=line.text.match(/^[\t ]+/)?.[0]; + let fenced=false; + for(let node=syntaxTree(view.state).resolve(line.from,1);node;node=node.parent!)if(node.name==='FencedCode')fenced=true; + if(ws&&fenced)ranges.push(Decoration.mark({class:'cm-code-indent-guide'}).range(line.from,line.from+ws.length)); + } + } + return Decoration.set(ranges,true); +} +const codeGuides=ViewPlugin.fromClass(class { + decorations: DecorationSet; + constructor(view: EditorView){this.decorations=guides(view);} + update(update: import('@codemirror/view').ViewUpdate){ + if(update.docChanged||update.viewportChanged||syntaxTree(update.startState)!==syntaxTree(update.state))this.decorations=guides(update.view); + } +},{decorations:plugin=>plugin.decorations}); + +export const editorStructure = [ + EditorState.tabSize.of(4),indentUnit.of('\t'), + Prec.high(foldService.of(indentFold)), + codeFolding(),inlineFolding, + Prec.high(keymap.of([{key:'Tab',run:tabIndent,shift:outdentOutline},...foldKeymap])), + codeGuides, +]; diff --git a/web/src/lib/store.ts b/web/src/lib/store.ts index 4a13836c..c7888c3d 100644 --- a/web/src/lib/store.ts +++ b/web/src/lib/store.ts @@ -841,6 +841,7 @@ export const useStore = create()( const recent = isFolder ? s.recent : [path, ...s.recent.filter((p) => p !== path)].slice(0, 20); return { tabs, activePath: path, content, locked, lockReason, unlockMode, dirty: false, recent, ...pushHistory(s, path) }; }); + refreshSaveStatus(); }, keepTab: (path) => set((s) => ({ diff --git a/web/src/styles/obsidian.css b/web/src/styles/obsidian.css index ce1931b7..53dcb5aa 100644 --- a/web/src/styles/obsidian.css +++ b/web/src/styles/obsidian.css @@ -713,6 +713,14 @@ body.wo-col-resizing .sidebar, body.wo-col-resizing .right-sidebar { transition: absolutely positioned 1px rule spanning the full line height, offset 0.85em. */ .cm-s-obsidian .cm-line { position: relative; } .cm-s-obsidian .cm-indent { display: inline-block; } +.cm-s-obsidian .cm-code-indent-guide { + background-image:repeating-linear-gradient(to right,transparent 0,transparent calc(4ch - 1px),rgba(var(--mono-rgb-100),0.14) calc(4ch - 1px),rgba(var(--mono-rgb-100),0.14) 4ch); +} +.cm-s-obsidian .cm-fold-indicator { display:inline-block; position:relative; z-index:1; width:0; } +.cm-s-obsidian .cm-outline-collapse { position:absolute; top:0; right:0; height:100%; padding:0 5px 0 0; border:0; background:transparent; color:var(--text-muted); font:inherit; line-height:inherit; cursor:pointer; opacity:0; } +.cm-s-obsidian .cm-line:hover .cm-outline-collapse,.cm-s-obsidian .cm-fold-indicator.is-collapsed .cm-outline-collapse,.cm-s-obsidian .cm-outline-collapse:focus-visible { opacity:1; } +@media(hover:none) { .cm-s-obsidian .cm-outline-collapse { opacity:1; } } +.cm-s-obsidian .cm-foldPlaceholder { background:transparent; border:0; color:var(--text-faint); margin-left:8px; cursor:pointer; } .cm-s-obsidian .cm-indent::before { content: '\200B'; display: block; width: 1px; color: transparent; border-right: 1px solid rgba(var(--mono-rgb-100), 0.12); @@ -2537,7 +2545,16 @@ body.workplace-fullscreen-focus .workspace { position:fixed; inset:0; z-index:50 .toolbar-measure-colors { gap:1px; } .draft-status { position:fixed; bottom:24px; right:12px; z-index:90; display:flex; gap:8px; align-items:center; background:var(--background-secondary); color:var(--text-normal); padding:4px 8px; border-radius:6px; } .draft-list { position:absolute; right:0; bottom:100%; width:min(600px,90vw); max-height:60vh; overflow:auto; background:var(--background-primary); padding:12px; border:1px solid var(--background-modifier-border); } -.draft-list > div { padding:8px 0; border-bottom:1px solid var(--background-modifier-border); } +.draft-list { border-radius:10px; box-shadow:0 8px 28px #0003; text-align:left; } +.draft-list header { display:flex; justify-content:space-between; align-items:center; gap:12px; } +.draft-list h2 { font-size:16px; margin:0; } +.draft-list p { font-size:13px; line-height:1.5; margin:8px 0; } +.draft-list-help,.draft-recovery-item small { color:var(--text-muted); } +.draft-recovery-item { padding:14px 0; border-top:1px solid var(--background-modifier-border); overflow-wrap:anywhere; } +.draft-recovery-item strong,.draft-recovery-item small { display:block; } +.draft-recovery-item small { margin-top:4px; } +.draft-recovery-actions { display:flex; flex-wrap:wrap; gap:8px; margin-top:10px; } +.draft-deleted-notice { padding:12px; border-left:3px solid var(--text-warning,var(--text-accent)); background:var(--background-secondary); } .draft-dialog-bg { position:fixed; inset:0; background:#0008; z-index:10010; display:grid; place-items:center; } .draft-dialog { width:min(1100px,96vw); max-height:94dvh; overflow:auto; padding:18px; background:var(--background-primary); color:var(--text-normal); border-radius:8px; } .draft-dialog pre { white-space:pre-wrap; max-height:25vh; overflow:auto; } diff --git a/web/tests/draftRecoveryBrowser.test.ts b/web/tests/draftRecoveryBrowser.test.ts index 2c736219..a57a50f6 100644 --- a/web/tests/draftRecoveryBrowser.test.ts +++ b/web/tests/draftRecoveryBrowser.test.ts @@ -14,7 +14,8 @@ test('browser: recovery after reload and repeated version conflict', async () => await build({ stdin: { resolveDir: fileURLToPath(new URL('..', import.meta.url)), loader: 'tsx', contents: ` import React from 'react';import {createRoot} from 'react-dom/client'; import DraftRecovery from './src/components/DraftRecovery';import {api,ApiError} from './src/lib/api'; - import {useStore,documentSessions,resetDraftScope} from './src/lib/store';import {putDraft,listDrafts} from './src/lib/drafts/storage'; + import {useStore,documentSessions,resetDraftScope} from './src/lib/store';import {putDraft,listDrafts,deleteDraftIfRevision} from './src/lib/drafts/storage'; + import {useConfirm} from './src/lib/confirm'; import {EditorView} from '@codemirror/view';import './src/styles/obsidian.css'; const source={scopeId:'recovery-scope',path:'a.md',writerId:'old-tab',schemaVersion:1,revision:1,updatedAt:Date.now(),baseVersion:'v1',baseContent:'base',content:'mine',kind:'text',state:'dirty'}; window.run=async()=>{await putDraft(source);return true; @@ -26,17 +27,39 @@ test('browser: recovery after reload and repeated version conflict', async () => api.write=async(path,content,version)=>{calls.push({path,content,version});if(calls.length===1){remoteVersion='v3';throw new ApiError('version_conflict',409);}return {ok:true,version:'v4'};}; document.body.innerHTML='
';useStore.setState({authed:true,activePath:null});const root=createRoot(document.querySelector('#root'));root.render();await wait(); const button=text=>Array.from(document.querySelectorAll('button')).find(b=>b.textContent.includes(text)); - button('Local drafts').click();await wait();button('Recover / Compare').click();await wait(); + check(button('Recover unsaved text').textContent.includes('(1)'),'recovery count describes actionable copies'); + button('Recover unsaved text').click();await wait(); + check(document.querySelector('.draft-list').textContent.includes('You do not need to manage this list during normal editing.'),'purpose is explained'); + button('Review text').click();await wait(); check(!!document.querySelector('[aria-label="Resolve conflict"]'),'resolver opens'); const editor=EditorView.findFromDOM(document.querySelector('.conflict-editor .cm-editor'));editor.dispatch({changes:{from:0,to:editor.state.doc.length,insert:'merged'}});await wait(); button('Save result').click();await wait();check(document.querySelector('[role="alert"]').textContent.includes('changed again'),'repeat conflict explained'); check(document.querySelector('.conflict-editor').textContent.includes('merged'),'manual result kept'); button('Save result').click();await wait();check(calls.length===2&&calls[0].version==='v2'&&calls[1].version==='v3','reviewed server version used');check(calls[1].content==='merged','result saved'); - check((await listDrafts('recovery-scope')).length===0,'confirmed revisions cleared');root.unmount(); + check((await listDrafts('recovery-scope')).length===0,'confirmed revisions cleared'); + button('Close').click();await wait();check(!button('Recover unsaved text'),'empty recovery list stays out of the way'); + // Removing a browser copy never issues a server write or deletion. + await putDraft({...source,path:'unneeded.md'});await wait();button('Recover unsaved text').click();await wait(); + const writesBefore=calls.length;button('Remove browser copy').click();await wait(); + check(useConfirm.getState().req.detail.includes('does not delete or change the file'),'removal explains its scope'); + useConfirm.getState().req.resolve(true);await wait();check(calls.length===writesBefore,'removal does not write to server'); + check((await listDrafts('recovery-scope')).length===0,'browser copy removed'); + // Deleted files are not silently restored; only an explicit new copy can be saved. + await putDraft({...source,path:'deleted.md'});api.read=async()=>{throw new ApiError('not_found',404)};await wait();button('Review text').click();await wait(); + check(document.querySelector('.draft-dialog').textContent.includes('Original file was deleted'),'deleted original is explained'); + check(button('Save result').disabled,'cannot save over deleted original'); + check(!button('Save a copy').disabled,'explicit recovery as a new copy is available'); + check(calls.length===writesBefore,'reviewing a deleted original does not restore it'); + button('Later').click();await wait(); + for(const record of await listDrafts('recovery-scope'))await deleteDraftIfRevision(record,record.revision); + root.unmount(); // A successful write followed by a failed refresh/cleanup must keep the live journal. resetDraftScope();api.draftScope=async()=>({scopeId:'review-scope'});let failRead=false; api.read=async()=>{if(failRead)throw Error('offline refresh');return {content:'base',version:'v1'}}; - await useStore.getState().openFile('live.md');useStore.getState().setContent('mine');const live=documentSessions.get('live.md');await live.flush();live.state='conflict'; + await useStore.getState().openFile('live.md');useStore.getState().setContent('mine');const live=documentSessions.get('live.md');await live.flush(); + const editing=createRoot(document.querySelector('#root'));editing.render();await wait(); + check(!button('Recover unsaved text'),'normal active autosave is not a recovery task');editing.unmount(); + live.state='conflict'; const second=createRoot(document.querySelector('#root'));second.render();await wait(); button('Resolve conflict').click();await wait(); const originalDelete=IDBObjectStore.prototype.delete;let failDelete=true; @@ -48,8 +71,8 @@ test('browser: recovery after reload and repeated version conflict', async () => useStore.getState().setContent('after successful merge');await documentSessions.get('live.md').flush(); check((await listDrafts('review-scope')).some(r=>r.content==='after successful merge'),'next edit is recoverable'); // Scope reset invalidates an already pending compare. - useStore.setState({dirty:false});button('Local drafts').click();await wait(); - let release;api.read=()=>new Promise(r=>{release=r});button('Recover / Compare').click();await wait(); + await putDraft({...source,scopeId:'review-scope',path:'leftover.md',writerId:'older-tab'});await wait();useStore.setState({dirty:false});button('Recover unsaved text').click();await wait(); + let release;api.read=()=>new Promise(r=>{release=r});button('Review text').click();await wait(); resetDraftScope();api.draftScope=async()=>({scopeId:'other-scope'});release({content:'other vault',version:'other'});await wait(); check(!document.querySelector('[aria-label="Resolve conflict"]'),'stale compare cannot reopen after vault switch'); second.unmount();return true; diff --git a/web/tests/editorSelectionBrowser.test.ts b/web/tests/editorSelectionBrowser.test.ts index de915549..f1981c9d 100644 --- a/web/tests/editorSelectionBrowser.test.ts +++ b/web/tests/editorSelectionBrowser.test.ts @@ -30,7 +30,7 @@ test('Live code block selection paints over the block background, including wrap selection:{anchor:doc.indexOf('first code')}, extensions:[markdown(), drawSelection(), highlightActiveLine(), EditorView.lineWrapping, livePreviewState, livePreviewPlugin, livePreviewTheme]})}); - view.focus(); await settle(); + view.focus(); await document.fonts.ready; await settle(); const lines = [...view.contentDOM.querySelectorAll('.HyperMD-codeblock-bg')]; const point = (line, bottom=false) => { const r = line.getBoundingClientRect(); @@ -49,10 +49,18 @@ test('Live code block selection paints over the block background, including wrap clientWidth:view.scrollDOM.clientWidth, backgroundPixel, wrappedHeight:lines[2].getBoundingClientRect().height, lineHeight:lines[1].getBoundingClientRect().height}; }; - window.selectCode = async () => { + window.selectCode = async (points) => { view.dispatch({selection:{anchor:doc.indexOf('first code'), head:doc.indexOf('last code line')+'last code line'.length}}); - await settle(); - if (!view.dom.querySelector('.cm-selectionBackground')) throw Error('Selection did not render'); + // Wait for CodeMirror's measured selection rectangles, not just for a + // decoration node to exist. Hidden Linux surfaces can paint later. + const deadline=performance.now()+4000; + let covered=false; + do { + await settle(); + const rects=[...view.dom.querySelectorAll('.cm-selectionBackground')].map(el=>el.getBoundingClientRect()); + covered=['wrapped','empty','active'].every(key=>rects.some(r=>points[key].x>=r.left&&points[key].x=r.top&&points[key].y'); await writeFile(join(dir, 'runner.cjs'), ` const {app,BrowserWindow}=require('electron'); + app.setPath('userData',${JSON.stringify(join(dir,'profile'))}); app.whenReady().then(async()=>{ - const win=new BrowserWindow({show:false,width:1000,height:800,webPreferences:{sandbox:true,contextIsolation:true,nodeIntegration:false}}); + const win=new BrowserWindow({show:false,width:1000,height:800,webPreferences:{sandbox:true,contextIsolation:true,nodeIntegration:false,backgroundThrottling:false}}); await win.loadFile(${JSON.stringify(join(dir, 'index.html'))}); win.webContents.debugger.attach('1.3'); await win.webContents.debugger.sendCommand('Emulation.setDeviceMetricsOverride', {width:1000,height:800,deviceScaleFactor:1,mobile:false}); + const deadline=Date.now()+4000; + let size; + do { + size=await win.webContents.executeJavaScript('[innerWidth,innerHeight]'); + if(size[0]===1000&&size[1]===800)break; + await new Promise(resolve=>setTimeout(resolve,10)); + }while(Date.now()Array.from((await win.webContents.capturePage({x:p.x,y:p.y,width:1,height:1})).toBitmap()).slice(0,3); + const pixel=async(p)=>Array.from((await win.webContents.capturePage({x:p.x,y:p.y,width:1,height:1},{stayHidden:true,stayAwake:true})).toBitmap()).slice(0,3); const before={}; for(const key of ['wrapped','empty','active','outside','leftMargin','rightMargin']) before[key]=await pixel(points[key]); - await win.webContents.executeJavaScript('window.selectCode()'); - const after={}; for(const key of ['wrapped','empty','active','outside','leftMargin','rightMargin']) after[key]=await pixel(points[key]); + await win.webContents.executeJavaScript('window.selectCode('+JSON.stringify(points)+')'); + // DOM geometry is necessary but the compositor may still hold the + // previous frame. Keep the pixel regression strict, with a bounded + // wait for the selected frame rather than accepting a stale capture. + let after={};const paintDeadline=Date.now()+4000; + do { + for(const key of ['wrapped','empty','active','outside','leftMargin','rightMargin']) after[key]=await pixel(points[key]); + if(['wrapped','empty','active'].every(key=>JSON.stringify(after[key])!==JSON.stringify(before[key])))break; + await new Promise(resolve=>setTimeout(resolve,16)); + }while(Date.now() EditorState.create({doc, selection:{anchor}, extensions:[markdown({extensions:[outlineMarkdown]}), editorStructure]}); +test('fold controls match measured original Obsidian for spaces, tabs and ABAP',()=>{ + const original=JSON.parse(readFileSync(new URL('../../tests/fixtures/rendering/obsidian-folding.json',import.meta.url),'utf8')); + for(const sample of original.observations){ + const s=state(sample.text),actual=[]; + for(let n=1;n<=s.doc.lines;n++){const line=s.doc.line(n);if(foldable(s,line.from,line.to))actual.push({line:n,offset:line.text.match(/^[\t ]*/)![0].length});} + assert.deepEqual(actual,sample.indicators.map((row:{line:number;offset:number})=>({line:row.line,offset:row.offset})),sample.name); + assert.equal(s.doc.toString(),sample.text,'folding does not normalize pasted whitespace'); + } +}); +test('indent folding stops at siblings and keeps intervening blank lines', () => { + const s=state('parent\n\tchild\n\n\t\tgrandchild\nsibling'); + assert.deepEqual(indentFold(s,0,s.doc.line(1).to),{from:6,to:s.doc.line(4).to}); + assert.deepEqual(indentFold(s,s.doc.line(2).from,s.doc.line(2).to),{from:s.doc.line(2).to,to:s.doc.line(4).to}); + assert.equal(indentFold(s,s.doc.line(5).from,s.doc.line(5).to),null); +}); +test('changing indent on a folded parent moves its hidden descendants and preserves the fold',()=>{ + let s=state('- parent\n\t- child\nnext'); + s=s.update({effects:foldEffect.of({from:8,to:s.doc.line(2).to})}).state; + const target={get state(){return s;},dispatch:(tr:ReturnType)=>{s=tr.state;}}; + tabIndent(target);assert.equal(s.doc.toString(),'\t- parent\n\t\t- child\nnext'); + assert.equal(foldedRanges(s).size,1); + outdentOutline(target);assert.equal(s.doc.toString(),'- parent\n\t- child\nnext'); + assert.equal(foldedRanges(s).size,1); +}); +test('tabs use four columns and spaces may form nested text too',()=>{ + const s=state('parent\n child\n\t\tgrandchild\n sibling\nnext'); + assert.equal(s.tabSize,4); + assert.equal(indentFold(s,s.doc.line(2).from,s.doc.line(2).to)?.to,s.doc.line(3).to); +}); +test('Obsidian folds headings and indentation without extra whole-code or paragraph folds',()=>{ + const s=state('# Title\nbody\n## Child\nchild body\n# Next\n```abap\nparent\n\tchild\n```'); + assert.equal(foldable(s,0,s.doc.line(1).to)?.to,s.doc.line(4).to); + assert.equal(foldable(s,s.doc.line(6).from,s.doc.line(6).to),null); + const plain=state('first line\nsecond line');assert.equal(foldable(plain,0,plain.doc.line(1).to),null); + assert.deepEqual(indentFold(s,s.doc.line(7).from,s.doc.line(7).to),{from:s.doc.line(7).to,to:s.doc.line(8).to}); +}); +test('ABAP call continuation folds independently of the next call and the enclosing code fence',()=>{ + const s=state('```abap\nZCL_3409_BADI_PRP-GET_INSURED_INFO\n\tzcl_3409_helper=>convert_date( EXPORTING iv_date = start_dt\n\t\tIMPORTING ev_date = begin ).\n\n\tzcl_3409_helper=>convert_date( EXPORTING iv_date = finish_dt\n\t\tIMPORTING ev_date = end ).\n```\n\toutside'); + assert.deepEqual(indentFold(s,s.doc.line(3).from,s.doc.line(3).to),{from:s.doc.line(3).to,to:s.doc.line(4).to}); + assert.deepEqual(indentFold(s,s.doc.line(6).from,s.doc.line(6).to),{from:s.doc.line(6).to,to:s.doc.line(7).to}); + assert.deepEqual(indentFold(s,s.doc.line(2).from,s.doc.line(2).to),{from:s.doc.line(2).to,to:s.doc.line(7).to}); + assert.equal(indentFold(s,s.doc.line(8).from,s.doc.line(8).to),null); +}); +test('nested code folding treats heading/list-looking text literally and cannot consume an indented closing fence',()=>{ + const s=state(' ~~~text\n# literal heading\n\tchild\n- literal list\n\tchild\n ~~~\n\toutside'); + assert.deepEqual(indentFold(s,s.doc.line(2).from,s.doc.line(2).to),{from:s.doc.line(2).to,to:s.doc.line(3).to}); + assert.deepEqual(indentFold(s,s.doc.line(4).from,s.doc.line(4).to),{from:s.doc.line(4).to,to:s.doc.line(5).to}); +}); +test('Tab inserts a tab at a text caret and indents a list item; readonly text cannot change',()=>{ + let s=state('ab',1); + const target=()=>({state:s,dispatch:(tr:ReturnType)=>{s=tr.state;}}); + tabIndent(target());assert.equal(s.doc.toString(),'a\tb'); + s=state('- parent\n- child',16); + tabIndent(target());assert.equal(s.doc.toString(),'- parent\n\t- child'); + s=EditorState.create({doc:'text',extensions:[editorStructure,EditorState.readOnly.of(true)]}); + assert.equal(tabIndent(target()),false);assert.equal(s.doc.toString(),'text'); +}); diff --git a/web/tests/editorStructureBrowser.test.ts b/web/tests/editorStructureBrowser.test.ts new file mode 100644 index 00000000..e4e2f452 --- /dev/null +++ b/web/tests/editorStructureBrowser.test.ts @@ -0,0 +1,117 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { mkdtemp, writeFile, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { createRequire } from 'node:module'; +import { execFile } from 'node:child_process'; +import { promisify } from 'node:util'; +import { build } from 'esbuild'; + +test('real editor: Tab, Shift-Tab, visible folding and undo work in live and source modes',async()=>{ + const dir=await mkdtemp(join(tmpdir(),'webo-structure-')); + try { + await build({stdin:{resolveDir:fileURLToPath(new URL('..',import.meta.url)),loader:'tsx',contents:` + import React from 'react';import {createRoot} from 'react-dom/client'; + import Editor from './src/components/Editor';import {useStore,documentSessions} from './src/lib/store'; + import {DocumentSession} from './src/lib/drafts/session'; + import {api} from './src/lib/api';import {getActiveEditor} from './src/lib/activeEditor'; + import {foldCode,unfoldAll,foldedRanges,forceParsing} from '@codemirror/language'; + import {undo} from '@codemirror/commands';import './src/styles/obsidian.css'; + api.tags=async()=>({tags:[]});api.propertyTypes=async()=>({types:{}}); + const wait=()=>new Promise(r=>setTimeout(r,100));const check=(v,m)=>{if(!v)throw Error(m)}; + const fence=String.fromCharCode(96).repeat(3); + const doc=['# Title','body','','- parent','\\t- child','\\t\\t- grandchild','- sibling','','plain','\\tchild','','code',fence+'abap','ZCL_3409_BADI_PRP-GET_INSURED_INFO','\\tzcl_3409_helper=>convert_date( EXPORTING iv_date = start_dt','\\t\\tIMPORTING ev_date = begin ).','','\\tzcl_3409_helper=>convert_date( EXPORTING iv_date = finish_dt','\\t\\tIMPORTING ev_date = end ).',fence,'','# Next','end'].join('\\n'); + let root; + window.prepare=async (mode,scope='structure-test')=>{ + root?.unmount();document.body.className='theme-dark';document.body.innerHTML='
'; + documentSessions.set(mode+'.md',new DocumentSession({scopeId:scope,path:mode+'.md',writerId:'fixture',content:doc,version:'base'},{put:async()=>{},remove:async()=>true,write:async()=>({version:'new'})})); + useStore.setState({activePath:mode+'.md',content:doc,dirty:false,viewMode:mode,showInlineTitle:false,locked:false,save:async()=>{}}); + root=createRoot(document.querySelector('#root'));root.render();await wait();await wait(); + const v=getActiveEditor();check(v,'editor mounted'); + check(!v.dom.querySelector('.cm-foldGutter'),'no separate gutter');check(v.contentDOM.querySelector('.cm-fold-indicator'),'inline controls visible'); + check(v.dom.querySelector('.cm-code-indent-guide'),'code indentation guides visible'); + v.dispatch({selection:{anchor:v.state.doc.line(4).from}});v.focus();await wait(); + }; + window.foldParent=async()=>{ + const v=getActiveEditor();check(foldCode(v),'parent folds');await wait(); + check(foldedRanges(v.state).size===1,'parent fold retained');check(v.state.doc.toString()===doc,'fold does not edit Markdown'); + check(v.dom.querySelector('.cm-foldPlaceholder'),'collapsed placeholder visible'); + }; + window.indented=async()=>{ + const v=getActiveEditor();await wait();check(v.state.doc.line(4).text==='\\t- parent','Tab indents parent'); + check(v.state.doc.line(5).text==='\\t\\t- child','Tab indents hidden child'); + check(foldedRanges(v.state).size===1,'Tab preserves fold'); + }; + window.outdented=async()=>{ + const v=getActiveEditor();await wait();check(v.state.doc.toString()===doc,'Shift-Tab restores whole subtree'); + undo(v);check(v.state.doc.line(5).text==='\\t\\t- child','undo reverts one complete outdent');undo(v); + check(v.state.doc.toString()===doc,'undo restores original');unfoldAll(v);await wait(); + const heading=v.contentDOM.querySelector('.cm-outline-collapse'); + check(heading,'clickable fold arrow');const r=heading.getBoundingClientRect(); + heading.dispatchEvent(new MouseEvent('click',{bubbles:true,clientX:r.left+3,clientY:r.top+3,button:0}));await wait(); + check(foldedRanges(v.state).size>0,'arrow click folds section');unfoldAll(v);await wait(); + check(v.state.doc.toString()===doc,'click folding does not change text'); + }; + window.nestedCode=async()=>{ + const v=getActiveEditor();unfoldAll(v);v.dispatch({selection:{anchor:v.state.doc.line(15).from}});await wait(); + const clickLine=async n=>{ + const line=v.state.doc.line(n),block=v.lineBlockAt(line.from),y=v.documentTop+block.top+block.height/2; + const marker=Array.from(v.contentDOM.querySelectorAll('.cm-fold-indicator')).find(e=>v.state.doc.lineAt(v.posAtDOM(e)).number===n)?.querySelector('button'); + check(marker,'nested ABAP fold arrow on line '+n);const r=marker.getBoundingClientRect(); + const parentPos=v.posAtDOM(marker.parentElement);check(parentPos-line.from===line.text.match(/^[\\t ]*/)[0].length,'arrow at start of text after indentation'); + marker.dispatchEvent(new MouseEvent('click',{bubbles:true,clientX:r.left+3,clientY:y,button:0}));await wait(); + }; + await clickLine(15); + check(foldedRanges(v.state).size===1,'first call continuation folds'); + check(!v.contentDOM.textContent.includes('IMPORTING ev_date = begin'),'first continuation hidden'); + check(v.contentDOM.textContent.includes('IMPORTING ev_date = end'),'sibling continuation stays visible'); + check(v.contentDOM.textContent.includes('ZCL_3409'),'enclosing block stays open'); + await clickLine(15);check(foldedRanges(v.state).size===0,'same arrow unfolds continuation'); + check(v.contentDOM.textContent.includes('IMPORTING ev_date = begin'),'continuation restored'); + await clickLine(18);const folds=[];foldedRanges(v.state).between(0,v.state.doc.length,(from,to)=>folds.push([from,to]));check(!v.contentDOM.textContent.includes('IMPORTING ev_date = end'),'second continuation folds independently '+JSON.stringify({folds,line18:v.state.doc.line(18).to,line19:v.state.doc.line(19).to,text:v.contentDOM.textContent})); + await clickLine(18);check(foldedRanges(v.state).size===0,'second continuation unfolds'); + check(v.state.doc.toString()===doc,'fold/unfold round trip preserves original code'); + }; + window.persistence=async mode=>{ + let v=getActiveEditor();v.dispatch({selection:{anchor:v.state.doc.line(15).from}});foldCode(v);await wait(); + check(foldedRanges(v.state).size===1,'fold before reopening'); + await window.prepare(mode);v=getActiveEditor();check(foldedRanges(v.state).size===1,'fold restored after editor recreation'); + check(v.contentDOM.querySelector('.cm-fold-indicator.is-collapsed'),'collapsed inline indicator restored'); + await window.prepare(mode,'other-vault');check(foldedRanges(getActiveEditor().state).size===0,'folds isolated by vault'); + await window.prepare(mode);check(foldedRanges(getActiveEditor().state).size===1,'original vault folds retained'); + unfoldAll(getActiveEditor()); + }; + window.longHydration=async()=>{ + const text='# Start\\n'+'text\\n'.repeat(5000)+'# Deep\\nbody\\n## Child\\nbody\\n# End'; + api.draftScope=async()=>({scopeId:'structure-test'});api.read=async()=>({content:text,version:'long-version'}); + useStore.setState({dirty:false,viewMode:'source'});await useStore.getState().openFile('long.md');await wait();await wait(); + let v=getActiveEditor();check(forceParsing(v,text.length,1000),'parse deep heading for initial fold'); + v.dispatch({selection:{anchor:v.state.doc.line(5002).from}});check(foldCode(v),'deep heading folds');await wait(); + check(foldedRanges(v.state).size===1,'one deep fold before reload'); + root.unmount();documentSessions.delete('long.md');useStore.setState({content:'',activePath:'long.md',dirty:false}); + root=createRoot(document.querySelector('#root'));root.render();await wait(); + check(!documentSessions.has('long.md'),'editor first mounts before document hydration'); + await useStore.getState().openFile('long.md'); + const end=performance.now()+3000;do{await wait();v=getActiveEditor();}while(foldedRanges(v.state).size!==1&&performance.now()'); + await writeFile(join(dir,'runner.cjs'),`const {app,BrowserWindow}=require('electron');app.setPath('userData',${JSON.stringify(join(dir,'profile'))});app.whenReady().then(async()=>{ + const w=new BrowserWindow({show:false,width:1100,height:1000,webPreferences:{backgroundThrottling:false}});w.webContents.on('console-message',(_event,level,message)=>{if(level>=2)console.error(message)});await w.loadFile(${JSON.stringify(join(dir,'index.html'))}); + const evaluate=async code=>{const result=await w.webContents.executeJavaScript('(async()=>{try{return await '+code+'}catch(e){return {failure:e.stack||String(e)}}})()');if(result?.failure)throw Error(result.failure);}; + for(const mode of ['live','source']){ + await evaluate('window.prepare('+JSON.stringify(mode)+')');await evaluate('window.foldParent()'); + w.webContents.sendInputEvent({type:'keyDown',keyCode:'Tab'});w.webContents.sendInputEvent({type:'keyUp',keyCode:'Tab'}); + await evaluate('window.indented()'); + w.webContents.sendInputEvent({type:'keyDown',keyCode:'Tab',modifiers:['shift']});w.webContents.sendInputEvent({type:'keyUp',keyCode:'Tab',modifiers:['shift']}); + await evaluate('window.outdented()');await evaluate('window.nestedCode()');await evaluate('window.persistence('+JSON.stringify(mode)+')'); + }await evaluate('window.longHydration()');console.log('STRUCTURE_PASS');w.destroy();app.quit();}).catch(e=>{console.error(e);app.exit(1)});`); + const env={...process.env};delete env.ELECTRON_RUN_AS_NODE; + const {stdout}=await promisify(execFile)(createRequire(import.meta.url)('electron'),[...(process.platform==='linux'?['--ozone-platform=headless']:[]),join(dir,'runner.cjs')],{env,windowsHide:true,timeout:60000}); + assert.match(stdout,/STRUCTURE_PASS/); + }finally{await rm(dir,{recursive:true,force:true});} +}); diff --git a/web/tests/toolbarViewportBrowser.test.ts b/web/tests/toolbarViewportBrowser.test.ts index 5031a765..4dc0062c 100644 --- a/web/tests/toolbarViewportBrowser.test.ts +++ b/web/tests/toolbarViewportBrowser.test.ts @@ -45,12 +45,14 @@ test('browser zoom and keyboard viewport keep toolbar, draft status, menus and p const bar=document.querySelector('.fixed-format-toolbar .toolbar-surface');check(inside(bar),'fixed toolbar outside viewport');check(Array.from(bar.children).filter(n=>!n.classList.contains('toolbar-measure')).every(n=>n.getBoundingClientRect().right<=bar.getBoundingClientRect().right+1),'fixed handle counted in overflow'); }; window.setupMobile=async()=>{ - fake=new EventTarget();Object.assign(fake,{width:390,height:844,offsetLeft:0,offsetTop:0,scale:1});Object.defineProperty(window,'visualViewport',{configurable:true,value:fake});await window.setup(true); + fake=new EventTarget();Object.assign(fake,{width:390,height:844,offsetLeft:0,offsetTop:0,scale:1});Object.defineProperty(window,'visualViewport',{configurable:true,value:fake}); + await putDraft({scopeId:'viewport',path:'kbd.md',writerId:'old',revision:1,schemaVersion:1,updatedAt:Date.now(),baseVersion:'v1',baseContent:'base',content:'mine',kind:'text',state:'dirty'}); + await window.setup(true);await settle(()=>!!document.querySelector('.draft-status')); }; window.conflictKeyboard=async()=>{ await putDraft({scopeId:'viewport',path:'kbd.md',writerId:'old',revision:1,schemaVersion:1,updatedAt:Date.now(),baseVersion:'v1',baseContent:'base',content:'mine',kind:'text',state:'dirty'}); api.read=async()=>({content:'remote',version:'v2'});await wait(); - const button=text=>Array.from(document.querySelectorAll('button')).find(b=>b.textContent.includes(text));button('Local drafts').click();await settle(()=>!!button('Recover / Compare'));button('Recover / Compare').click();await settle(()=>!!document.querySelector('.draft-dialog')); + const button=text=>Array.from(document.querySelectorAll('button')).find(b=>b.textContent.includes(text));button('Recover unsaved text').click();await settle(()=>!!button('Review text'));button('Review text').click();await settle(()=>!!document.querySelector('.draft-dialog')); check(inside(document.querySelector('.draft-dialog')),'conflict dialog hidden by keyboard'); const copy=document.querySelector('[aria-label="Recovered copy path"]');copy.focus();document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}));await wait(); check(!document.querySelector('.draft-dialog'),'Escape postpones safely'); @@ -72,8 +74,8 @@ test('browser zoom and keyboard viewport keep toolbar, draft status, menus and p app.whenReady().then(async()=>{const w=new BrowserWindow({show:false,width:1440,height:900,webPreferences:{backgroundThrottling:false}});await w.loadFile(${JSON.stringify(join(dir,'index.html'))}); w.webContents.debugger.attach('1.3'); // Hidden Ozone windows have no reliable native surface (sometimes 1x1). - // Preserve each zoom's effective CSS viewport explicitly and assert it. - const viewport=async(width,height)=>{await w.webContents.debugger.sendCommand('Emulation.setDeviceMetricsOverride',{width,height,deviceScaleFactor:1,mobile:false});const actual=await w.webContents.executeJavaScript('[innerWidth,innerHeight]');const factor=w.webContents.getZoomFactor();const expected=[Math.round(width/factor),Math.round(height/factor)];if(actual[0]!==expected[0]||actual[1]!==expected[1])throw Error('Viewport mismatch '+JSON.stringify({actual,expected,factor}));}; + // Preserve each zoom's effective CSS viewport and wait for its asynchronous layout. + const viewport=async(width,height)=>{await w.webContents.debugger.sendCommand('Emulation.setDeviceMetricsOverride',{width,height,deviceScaleFactor:1,mobile:false});const factor=w.webContents.getZoomFactor();const expected=[Math.round(width/factor),Math.round(height/factor)];const deadline=Date.now()+4000;let actual;do{actual=await w.webContents.executeJavaScript('[innerWidth,innerHeight]');if(actual[0]===expected[0]&&actual[1]===expected[1])return;await new Promise(resolve=>setTimeout(resolve,10));}while(Date.now()0.01)throw Error('Zoom mismatch');results.zoom.push({factor,...r});}} w.webContents.setZoomFactor(1);await viewport(1440,900);await w.webContents.executeJavaScript('window.fixed()');await w.webContents.debugger.sendCommand('Emulation.setDeviceMetricsOverride',{width:390,height:844,deviceScaleFactor:1,mobile:true});await w.webContents.debugger.sendCommand('Emulation.setTouchEmulationEnabled',{enabled:true});