diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index 75daf289..b540a995 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -2346,3 +2346,13 @@ Verification and scope: `docs/superpowers/plans/2026-10-30-drafts-conflicts-adap ## Remote MCP (2026-10-30) Implementation and validation ledger: [remote MCP plan](docs/superpowers/plans/2026-10-30-remote-mcp.md). Local stdio compatibility, shared operations, HTTP auth, packaging and docs are tracked there. Public HTTPS deployment and live Perplexity Pro smoke are separate acceptance steps. + +## Rendering polygon parity (2026-11-02) + +- [x] Import the vault note font size and match property presentation, partial list indentation, task ticks and inline-link geometry. +- [x] Preserve bounded inert HTML formatting; match code fences, display math, Mermaid colors and source-edit actions. +- [x] Keep embedded-note navigation and native missing-reference presentation; resolve same-note heading/block links and compact missing PDF embeds. +- [x] Match consecutive image spacing and use validated YouTube player settings for authored privacy-domain iframes while keeping other frames isolated. +- [x] Verify mouse hover, keyboard activation and unchanged note source against isolated native Obsidian fixtures; update the running server with backups and asset/runtime verification. + +Validation details and explicit browser/native limitations: [polygon parity](docs/superpowers/plans/2026-11-02-render-polygon-parity.md), [marker/media follow-up](docs/superpowers/plans/2026-11-02-marker-media-parity.md). The implementation passed 390 server tests (10 Windows skips), 517 web tests, typecheck, full build, local integration smoke and isolated Linux deployment smoke before the PR integration checks. Bases remain outside this parity pass. diff --git a/docs/superpowers/plans/2026-11-02-marker-media-parity.md b/docs/superpowers/plans/2026-11-02-marker-media-parity.md new file mode 100644 index 00000000..360907ff --- /dev/null +++ b/docs/superpowers/plans/2026-11-02-marker-media-parity.md @@ -0,0 +1,23 @@ +# Marker and media follow-up parity + +Scope: follow-up screenshots of heading hashes, inline code in callout titles, consecutive images, embedded-note open icon, repeated PDF instances and external HTML frames. Preserve note bytes and established embed interactions. + +Native evidence: isolated Obsidian 1.14.5 with copied polygon and attachments. Active heading hashes are text-faint (dark 102,102,102), callout title code is text-normal (dark 218,218,218). Consecutive 300px images touch exactly (first y250.046875 + height168.75 = second y418.796875). Single and combined page=3/rect PDF references show page3 with the page3 rectangle; raw rect does not introduce a crop in native. + +Root causes and fixes: +- Nested CodeMirror syntax highlighting painted heading hashes with its meta orange despite the outer formatting mark. Scope faint color to formatting-header descendants. +- Inline code inherited its callout title color; explicitly use text-normal, matching native code behavior. +- Live Preview image base theme added 6px top/bottom margins. Remove margins, align wrapper to top; adjacent rows have zero gap and an authored blank row remains visible. +- Authored YouTube iframe was treated as a generic opaque-origin frame. Canonicalize verified YouTube hosts/11-character IDs and reuse existing trusted player permissions/referrer policy. Support privacy-host embed URLs in both provider resolvers and preserve that host. Unknown frames remain opaque; all note-supplied privileged attributes are discarded. + +Confirmed browser boundary: obsidian.md sends X-Frame-Options SAMEORIGIN. Native app permits its loading; web styling cannot override that remote restriction. No proxy or framing-header bypass introduced. + +Unreproduced reports: native fresh same-file PDF refs render correct page3, whereas screenshot left shows page1 and right page3; requested which embed is pictured. Embedded-note icon has two complete arrows in both original screenshot and fresh pixel crop, independently reviewed. SVG geometry, four-corner hit-testing, quoted blocks at 12/16/19px, wide editor/outline and three modes pass; no speculative icon or PDF runtime modification. + +Checks: failing tests recorded before marker/image/YouTube fixes; focused browser tests pass. Real headless Chrome A/B shows old policy black, new policy native-equivalent unavailable-video message. Typecheck/build/integration pass. Independent review found no material issue in provider trust boundaries or style changes. Final full regression and deployment results are recorded with the release. + +Final pre-deployment regression: 390 server tests passed (10 Windows skips), 517 web tests passed, 907 total passing; no failures. Typecheck, full build and local integration smoke passed. + +Post-package record: full copied native polygon was also opened at its exact third PDF source line (page=3&rect); page3 rectangle and footer rendered. No code change needed. Deployed marker-media-b093484ffadd with backup /opt/webobsidian/backups/marker-media-b093484ffadd-20261102T062541Z; HTTPS plus seven asset hashes and both module hashes verified, YouTube policy verified inside running container, original note and fixtures unchanged. + +Pre-merge review caught an additional code-fence edge case: a longer outer fence can contain literal shorter fences, and an unclosed block has no closing delimiter. Use the syntax node's CodeMark boundaries for concealment rather than a line-prefix regex. A real browser regression fails before the fix and passes afterward for backticks, tildes and unclosed blocks in both Live and Reading, with unchanged source. This correction is additional to the deployed marker/media snapshot. diff --git a/docs/superpowers/plans/2026-11-02-render-polygon-parity.md b/docs/superpowers/plans/2026-11-02-render-polygon-parity.md new file mode 100644 index 00000000..fee7fd42 --- /dev/null +++ b/docs/superpowers/plans/2026-11-02-render-polygon-parity.md @@ -0,0 +1,48 @@ +# Rendering polygon parity + +**Goal:** Match the user's rendering test page against native Obsidian 1.14.5 while preserving note bytes. + +**Observed:** Native uses `.obsidian/appearance.json` baseFontSize 19, while the web default remains 16. Native preserves mixed inline color/weight, bounded padding/radius, legacy font color and custom mark colors; the current whole-style regex discards them. Native kbd has a visible keyboard-key shape. Sub/sup shorthand and backslash-parenthesized math remain literal in native, so they must not be invented as supported features. + +**Design:** Read typed appearance font size through existing vault preferences, apply only to note text and public content, and remeasure the editor on preference changes. Normalize a small inert inline CSS allowlist before the shared HTML sanitizer; preserve legacy color visually without allowing arbitrary style, URLs or event attributes. Add scoped kbd styling. Match native callout title line height (1.3) and paragraph margins (1em); the measured 19px single-paragraph box is 115.2px rather than the current 81px Live box. Other page sections are compared using native and browser captures; missing references are compared as missing; later, the user explicitly authorized creating test attachments without overwriting existing notes. Native captures use a copied fixture and a fresh profile. Native MathJax uses 19px for inline and display math at 19px note text; scope KaTeX to 1em to remove its extra default 1.21x scaling. Browser fixtures must include a doctype; quirks mode disables KaTeX and alters table inheritance. + +- [x] Capture native/browser results for the user-provided test source. +- [x] Add failing appearance and inline HTML parity tests, including unsafe CSS and outside-vault configuration guards. +- [x] Implement font-size import, scoped note typography and safe inline HTML formatting. +- [x] Verify real Live/Reading/Preview computed styles, editable-source actions and unchanged source; rerun full regressions/builds and independent review. +- [x] Update the running server with backup and verify external/runtime hashes. + +Validation: 385 server tests passed (10 Windows skips), 514 web tests passed; final focused typography/math and renderer-security checks passed (11). Typecheck, full build and integration smoke passed. Native/browser captures compare all eleven sections; note source hashes remain unchanged. Reviewer approved inline CSS, appearance boundaries and callout folding scope. + +Deployed: `render-polygon-004c430aa93a`; backup `/opt/webobsidian/backups/render-polygon-004c430aa93a-20261101T214149Z`. External HTTPS and 7 assets verified; all 4 server runtime hashes match the release. Live vault font is 19 from Obsidian; original polygon SHA-256 unchanged; settings unchanged. + + +## Second pass: reported differences and loaded attachments + +Native reference: isolated Obsidian 1.14.5 vault, original polygon copied without edits, 19px note font. Browser references: real Editor Live/Reading and Preview, all eleven sections. Keep Bases out of scope. + +- [x] Native property icons, metadata font/row scale, plain alias/cssclass values, idle date/number fields. +- [x] Partial two-space list indentation vs full four-space indentation; native dark checkbox tick. +- [x] Reset inline widget hanging indent; real click and keyboard link activation. +- [x] Callout fold arrow after title; full callout source action and unboxed raw quote editing. +- [x] Multiline display math independent of viewport parsing; source actions for math/Mermaid. +- [x] Late code fences use complete literal ranges; hidden fences add no empty rows; native language casing and right-aligned flair. +- [x] Native Mermaid palette from installed reference initialization/styles; muted Live footnote markers. +- [x] Empty/missing note embeds retain native title, accent border and open button; compact quote spacing. +- [x] Same-note fragment resolution handles heading/block links through the actual server resolver. +- [x] Genuine PDF 404 collapses to native missing-file placeholder, with complete fragment label. +- [x] Review-discovered Math source button Enter interception reproduced and fixed with real CDP keyboard input. +- [x] Generate four attachments (PNG, MP3, MP4, seven-page PDF), inspect all PDF pages, load copied fixtures in native and browser. Preserve existing root notes. +- [x] Native audio full note width and 42px height; deterministic WebM fixture removes MediaRecorder/GPU test flakiness without dropping playback checks. +- [x] Verify callout source button hovering body/title/away, math/Mermaid/PDF hover buttons and loaded attachment actions. +- [x] Complete final full tests/typecheck/build/integration and review, install absent test attachments exclusively, deploy with backup, verify runtime/assets and unchanged user note bytes. + +Browser test fixture `tests/fixtures/embeds/clip.webm` is generated from FFmpeg's synthetic testsrc (240x120, 10fps, 0.6s, libvpx yuv420p). No external/user media; fetched through the existing blob-store test route and still checked for nonzero duration and working play/pause. + + +Second-pass validation before deployment: 386 server tests passed (10 Windows skips), all 515 web tests passed, full typecheck/build and cross-platform integration smoke passed. Real CDP mouse hovering title/body/away and math/Mermaid blocks, keyboard Enter, loaded media play/pause and source preservation verified. Native vs loaded browser image sizes agree (640x360, 300x168.75, 300x150); native audio is full column width/42px, video is 640x360; note titles 19px/28.5px and open controls 24px. PDF full/page=3/rect references load seven-page document, page is correct and viewer height tracks page. Native rect reference behaves like page=3 too; no new rect semantics introduced. All seven authored PDF pages visually inspected. Reviewer rechecked hover cleanup, source-button keyboard isolation and scoped media styles: no material findings. + +Deployment uses current render-polygon image as immutable base; only services/fileReferences.js and services/markdownContext.js differ semantically on the server. Other changed server source in this working tree was already included in the preceding release. Source package includes all current worktree changes; test fixture installation has exclusive create/no overwrite and protected source hashes. + + +Post-deployment record (documentation updated after packaging): `polygon-details-82dcfb595877`, image `sha256:9377d1be410374bc94c122b11dcd3d176a8a8c5e01baa8d0cbf69a6ca28ce4f9`; backup `/opt/webobsidian/backups/polygon-details-82dcfb595877-20261101T230342Z`. HTTPS health and seven assets verified, both new runtime module hashes match. Installed four fixtures under `Тесты/Attachments` without overwrites; production resolver resolves all four and same-note block correctly. Polygon SHA remains `7c02fe81836f071ee0e9648b9225f21eb37d8f7da14dd9d8f7787971b33c4658`; both existing linked note hashes and app settings unchanged. Deployment's isolated Linux integration smoke passed too. diff --git a/scripts/integration-smoke.mjs b/scripts/integration-smoke.mjs index b6b08437..5fc61f9b 100644 --- a/scripts/integration-smoke.mjs +++ b/scripts/integration-smoke.mjs @@ -89,6 +89,10 @@ try { assert.equal(resolved.path, 'notes/attachments/document.pdf'); const localNote = await (await request('/api/resolve?target=neighbor&from=notes/editable.md')).json(); assert.equal(localNote.path, 'notes/neighbor.md', 'note embeds resolve beside their source before basename fallback'); + for(const target of ['#^quote-block-target','#11. Section']){ + const self=await(await request('/api/resolve?target='+encodeURIComponent(target)+'&from=notes/editable.md')).json(); + assert.equal(self.path,'notes/editable.md','fragment-only links retain the actual current note identity'); + } const secondNote = await (await request('/api/resolve?target=neighbor&from=second/root.md')).json(); assert.equal(secondNote.path, 'second/neighbor.md'); const document = await request(relative); diff --git a/server/src/routes/publicEmbeds.test.ts b/server/src/routes/publicEmbeds.test.ts index c2c23cca..731b95c2 100644 --- a/server/src/routes/publicEmbeds.test.ts +++ b/server/src/routes/publicEmbeds.test.ts @@ -13,6 +13,7 @@ vi.mock('../services/vault.js',()=>({exists:async(p:string)=>fixture.files.has(p vi.mock('../services/shares.js',()=>({getActiveShare:async(id:string)=>fixture.enabled&&id==='token'?{id,path:'Folder/Host.md',enabled:true,...(fixture.locked?{passwordHash:'protected'}:{})}:fixture.children.find(s=>s.id===id&&s.enabled)??null,listShares:async()=>[{id:'token',path:'Folder/Host.md',enabled:fixture.enabled,createdAt:'fixture',...(fixture.locked?{passwordHash:'protected'}:{})},...fixture.children]})); vi.mock('../services/fileindex.js',()=>({resolveFile:()=>null,indexedFilePaths:()=>[...fixture.files.keys()]})); vi.mock('../services/linkpreview.js',()=>({embedLinkPreviews:async(html:string)=>html})); +vi.mock('../services/vaultPreferences.js',()=>({getVaultPreferences:async()=>({values:{baseFontSize:19}})})); import {sharePageRouter} from './sharepage.js'; let server:Server,base:string; @@ -28,6 +29,7 @@ it('adds a separate read-only module while retaining SSR PDF and Canvas fallback const r=await fetch(base+'/share/token');const html=await r.text();expect(r.status).toBe(200); expect(html).toMatch(/type="module"[^>]+src="\/assets\/public-embeds-test.js"/); expect(html).toContain('data-public-share="token"'); + expect(html).toContain('--font-text-size:19px'); expect(html).toContain('class="pdf-embed"');expect(html).toContain('class="canvas-embed"'); expect(html).not.toContain('/api/files'); }); diff --git a/server/src/routes/sharepage.ts b/server/src/routes/sharepage.ts index 23610125..b1f09fdd 100644 --- a/server/src/routes/sharepage.ts +++ b/server/src/routes/sharepage.ts @@ -16,6 +16,7 @@ import {renderPublicCanvasHtml} from '../services/publicCanvasRendering.js'; import { embedLinkPreviews } from '../services/linkpreview.js'; import { publicMarkdownScript } from '../services/publicMarkdown.js'; import { canvasDescription, canvasFirstImage, canvasViewerScript } from '../services/rendercanvas.js'; +import {getVaultPreferences} from '../services/vaultPreferences.js'; const __dirname = path.dirname(fileURLToPath(import.meta.url)); @@ -58,6 +59,7 @@ function page(opts: { /** Skip the narrow markdown-preview column (used by the full-width canvas view). */ bare?: boolean; shareId?:string; + baseFontSize?:number; }): string { const inner = opts.bare ? opts.body @@ -76,7 +78,7 @@ ${opts.body} ${opts.head ?? ''} -
+
${inner}
@@ -179,6 +181,7 @@ document.getElementById('unlock-form').addEventListener('submit', async (e) => { css, bare: isCanvas, shareId:share.id, + baseFontSize:(await getVaultPreferences()).values.baseFontSize, body: isCanvas ? `
${escapeHtml(title)}
\n${html}\n${canvasViewerScript(res.locals.cspNonce)}\n${publicMarkdownScript(res.locals.cspNonce)}\n${await embedsScript(res.locals.cspNonce)}` : `
${escapeHtml(title)}
\n${html}\n${publicMarkdownScript(res.locals.cspNonce)}\n${await embedsScript(res.locals.cspNonce)}`, @@ -196,5 +199,5 @@ sharePageRouter.get('/:id/canvas',asyncHandler(async(req,res)=>{ if(!target||!/\.canvas$/i.test(target)){error(404,'This canvas is not available.');return} const title=target.split('/').pop()!.replace(/\.canvas$/i,''); const html=await renderPublicCanvasHtml(await vault.readFileText(target),target,share,child=>isUnlocked(req,child),resolveSharedAttachments); - res.type('html').send(page({title,css,bare:true,shareId:share.id,noindex:true,body:`
${escapeHtml(title)}
\n${html}\n${canvasViewerScript(res.locals.cspNonce)}\n${publicMarkdownScript(res.locals.cspNonce)}\n${await embedsScript(res.locals.cspNonce)}`})); + res.type('html').send(page({title,css,bare:true,shareId:share.id,baseFontSize:(await getVaultPreferences()).values.baseFontSize,noindex:true,body:`
${escapeHtml(title)}
\n${html}\n${canvasViewerScript(res.locals.cspNonce)}\n${publicMarkdownScript(res.locals.cspNonce)}\n${await embedsScript(res.locals.cspNonce)}`})); })); diff --git a/server/src/services/embeds.ts b/server/src/services/embeds.ts index 7dfda3e4..6a727d95 100644 --- a/server/src/services/embeds.ts +++ b/server/src/services/embeds.ts @@ -30,6 +30,8 @@ const youtube: Matcher = (u) => { let layout: ExternalEmbed['layout'] = 'video'; if (host === 'youtu.be') { id = seg[0] ?? null; + } else if (host === 'youtube-nocookie.com' && seg[0] === 'embed' && seg.length === 2) { + id = seg[1]; } else if (host === 'youtube.com') { if (seg[0] === 'watch') id = u.searchParams.get('v'); else if (seg[0] === 'shorts') { @@ -38,7 +40,8 @@ const youtube: Matcher = (u) => { } else if (seg[0] === 'embed' || seg[0] === 'live' || seg[0] === 'v') id = seg[1] ?? null; } if (!id || !YT_ID.test(id)) return null; - return { provider: 'youtube', src: `https://www.youtube.com/embed/${id}`, title: 'YouTube video', layout }; + const domain = host === 'youtube-nocookie.com' ? 'www.youtube-nocookie.com' : 'www.youtube.com'; + return { provider: 'youtube', src: `https://${domain}/embed/${id}`, title: 'YouTube video', layout }; }; const instagram: Matcher = (u) => { diff --git a/server/src/services/fileReferences.test.ts b/server/src/services/fileReferences.test.ts index 1529a13b..c1ce3dd3 100644 --- a/server/src/services/fileReferences.test.ts +++ b/server/src/services/fileReferences.test.ts @@ -1,6 +1,13 @@ import {describe,it,expect} from 'vitest'; import {parseFileReferences,resolveReference} from './fileReferences.js'; describe('file reference identity',()=>{ + it('resolves only fragment-only links to an existing source identity',()=>{ + const files=['Тесты/Polygon.md','Target.md']; + expect(resolveReference('#^quote','Тесты/Polygon.md',files,'wiki')).toBe('Тесты/Polygon.md'); + expect(resolveReference('#11. Heading','Тесты/Polygon.md',files,'markdown')).toBe('Тесты/Polygon.md'); + expect(resolveReference('#^quote','Missing.md',files,'wiki')).toBeNull(); + expect(resolveReference('','Тесты/Polygon.md',files,'wiki')).toBeNull(); + }); it('resolves encoded punctuation once and leaves encoded hash in filename',()=>{const refs=parseFileReferences('![](Media/shot%20%231%20%28a%29.png)');expect(refs).toHaveLength(1);expect(resolveReference(refs[0].target,'note.md',['Media/shot #1 (a).png'])).toBe('Media/shot #1 (a).png');}); it('ignores code and keeps exact target positions',()=>{const text='`[[ignored]]`\n```\n[x](ignored.md)\n```\n[[target#H|Alias]] ![x]()';const refs=parseFileReferences(text);expect(refs.map(r=>text.slice(r.from,r.to))).toEqual(['target#H','a%20b.png']);}); it('prefers source-local identities for duplicate basenames',()=>{expect(resolveReference('target','b/source.md',['a/target.md','b/target.md'])).toBe('b/target.md');}); diff --git a/server/src/services/fileReferences.ts b/server/src/services/fileReferences.ts index 2a91e48d..2af2b504 100644 --- a/server/src/services/fileReferences.ts +++ b/server/src/services/fileReferences.ts @@ -30,7 +30,9 @@ export function parseFileReferences(content:string,canvas=false):FileReference[] return refs.sort((a,b)=>a.from-b.from); } export function resolveReference(target:string,sourcePath:string,paths:string[],kind:FileReference['kind']='markdown'):string|null{ - const raw=target.split('#')[0];if(!raw||/^[a-z][a-z\d+.-]*:/i.test(raw)||raw.startsWith('//'))return null; + const raw=target.split('#')[0]; + if(!raw)return target.startsWith('#')&&paths.includes(sourcePath)?sourcePath:null; + if(/^[a-z][a-z\d+.-]*:/i.test(raw)||raw.startsWith('//'))return null; if(kind==='wiki'){const literal=resolveReference(raw.split('/').map(s=>encodeURIComponent(s)).join('/'),sourcePath,paths,'markdown');if(literal)return literal;} let decoded:string;try{decoded=decodeURIComponent(raw);}catch{decoded=raw;} const candidates=[...(decoded.startsWith('/')?[]:[path.posix.normalize(path.posix.join(path.posix.dirname(sourcePath),decoded))]),path.posix.normalize(decoded.replace(/^\/+/ ,''))]; diff --git a/server/src/services/htmlPolicy.ts b/server/src/services/htmlPolicy.ts index eb4d9969..05a3047f 100644 --- a/server/src/services/htmlPolicy.ts +++ b/server/src/services/htmlPolicy.ts @@ -1,2 +1,52 @@ +import type {Root,RootContent} from 'hast'; + /** Only inert color declarations; whitespace is valid CSS, not a reason to lose color. */ export const COLOR_STYLE_RE = /^\s*(?:(?:color|background-color)\s*:\s*#(?:[\da-fA-F]{8}|[\da-fA-F]{6}|[\da-fA-F]{3})\s*;?\s*){1,2}$/i; + +const COLOR_VALUE_RE=/^(?:#(?:[\da-f]{3,4}|[\da-f]{6}|[\da-f]{8})|[a-z]{1,32}|(?:rgba?|hsla?)\([\d\s.,%/+\-]+\))$/i; +const inlineTags=new Set(['span','mark','kbd']); +function boundedSpacing(value:string):boolean{ + const parts=value.split(/\s+/);return parts.length<=4&&parts.every(part=>{ + const m=/^((?:\d+(?:\.\d+)?|\.\d+))(px|em|rem)?$/i.exec(part);if(!m)return false; + const n=Number(m[1]),unit=m[2]?.toLowerCase();return unit?n<=(unit==='px'?64:4):n===0; + }); +} + +/** Keep inert typography only. No URLs, custom properties, layout or !important. */ +export function sanitizeInlineStyle(source:string):string{ + // Keep toolbar-owned hex spans stable; its source editing uses this grammar. + if(COLOR_STYLE_RE.test(source))return source; + const declarations=new Map(); + for(const declaration of source.split(';')){ + const at=declaration.indexOf(':');if(at<0)continue; + let property=declaration.slice(0,at).trim().toLowerCase();const value=declaration.slice(at+1).trim(); + if(property==='background')property='background-color'; + const allowed=['color','background-color'].includes(property)?COLOR_VALUE_RE.test(value): + property==='font-weight'?/^(?:normal|bold|bolder|lighter|[1-9]00)$/i.test(value): + property==='font-style'?/^(?:normal|italic|oblique)$/i.test(value): + ['padding','border-radius'].includes(property)&&boundedSpacing(value); + if(allowed)declarations.set(property,value); + } + return [...declarations].map(([key,value])=>`${key}: ${value}`).join('; '); +} + +/** Runs before the shared sanitizer. Legacy font color becomes a bounded span. */ +export function rehypeInlineStyles(){ + return (tree:Root)=>{ + const visit=(node:Root|RootContent)=>{ + if(node.type==='element'){ + const properties=node.properties; + if(node.tagName==='font'){ + node.tagName='span'; + const color=typeof properties.color==='string'&&COLOR_VALUE_RE.test(properties.color)?`color: ${properties.color}; `:''; + properties.style=color+(typeof properties.style==='string'?properties.style:'');delete properties.color; + } + if(inlineTags.has(node.tagName)){ + const style=typeof properties.style==='string'?sanitizeInlineStyle(properties.style):''; + if(style)properties.style=style;else delete properties.style; + } + } + if('children' in node)node.children.forEach(visit); + };visit(tree); + }; +} diff --git a/server/src/services/markdownContext.ts b/server/src/services/markdownContext.ts index 221d40cc..7390e0fc 100644 --- a/server/src/services/markdownContext.ts +++ b/server/src/services/markdownContext.ts @@ -6,6 +6,14 @@ import { inlineFootnoteRanges } from './markdownDialect.js'; const parser = unified().use(remarkParse).use(remarkGfm); export interface SourceRange { from: number; to: number } +/** Complete literal ranges, independent of the editor's incremental parse window. */ +export function markdownLiteralRanges(source:string): (SourceRange&{kind:'code'|'inlineCode'|'html'})[]{ + const ranges:(SourceRange&{kind:'code'|'inlineCode'|'html'})[]=[]; + const visit=(node:Node)=>{if(node.type==='code'||node.type==='inlineCode'||node.type==='html'){ + const from=node.position?.start.offset,to=node.position?.end.offset; + if(from!==undefined&&to!==undefined)ranges.push({from,to,kind:node.type});return; + }node.children?.forEach(visit)};visit(parser.parse(source) as Node);return ranges; +} interface Node { type: string; value?: string; diff --git a/server/src/services/markdownRendering.ts b/server/src/services/markdownRendering.ts index 13a5bb87..a00a0c48 100644 --- a/server/src/services/markdownRendering.ts +++ b/server/src/services/markdownRendering.ts @@ -9,7 +9,7 @@ import remarkRehype from 'remark-rehype'; import rehypeRaw from 'rehype-raw'; import rehypeSanitize, { defaultSchema } from 'rehype-sanitize'; import rehypeStringify from 'rehype-stringify'; -import { COLOR_STYLE_RE } from './htmlPolicy.js'; +import {rehypeInlineStyles} from './htmlPolicy.js'; import { editableFrontmatter } from './frontmatterPolicy.js'; const VIDEO_EXT_RE = /\.(mp4|webm|ogv|mov|mkv)$/i; @@ -33,7 +33,9 @@ export const markdownSchema = { ['dataWebFrame'],['dataWebFrameWidth'],['dataWebFrameHeight'],['dataWebFrameFullscreen'], ], div: [...(defaultSchema.attributes?.div ?? []).filter(x=>!(Array.isArray(x)&&x[0]==='align')&&x!=='align'), ['align','left','center','right','justify'], ['className'], ['dataCallout'], ['dataCalloutFold']], - span: [...(defaultSchema.attributes?.span ?? []), ['className'], ['dataTex'], ['dataTexDisplay'], ['dataCalloutIcon'], ['style', COLOR_STYLE_RE]], + span: [...(defaultSchema.attributes?.span ?? []), ['className'], ['dataTex'], ['dataTexDisplay'], ['dataCalloutIcon'], ['style']], + mark: [...(defaultSchema.attributes?.mark??[]),['style']], + kbd: [...(defaultSchema.attributes?.kbd??[]),['style']], li: [...(defaultSchema.attributes?.li ?? []), ['className'], ['dataTask']], input: [['type'], ['checked'], ['disabled'], ['className'], ['dataTask']], img: [...(defaultSchema.attributes?.img ?? []), ['src'], ['alt'], ['dataEmbed']], @@ -172,6 +174,7 @@ const makeProcessor = (strictLineBreaks = false) => unified() .use(remarkRehype, { allowDangerousHtml: true }) .use(rehypeRaw) .use(rehypePrepareWebFrames as any) + .use(rehypeInlineStyles) .use(rehypeSanitize, markdownSchema as any) .use(rehypeBlockIds) .use(rehypeRestoreWebFrames as any) diff --git a/server/src/services/publicNoteTransclusion.test.ts b/server/src/services/publicNoteTransclusion.test.ts index ec8e1b39..3ac12310 100644 --- a/server/src/services/publicNoteTransclusion.test.ts +++ b/server/src/services/publicNoteTransclusion.test.ts @@ -55,3 +55,20 @@ it('preserves CRLF block targets, ordered lists and quotes without leaking betwe expect(html).toMatch(/]*data-block-id="ordered"/);expect(html).toMatch(/]*data-block-id="item"/);expect(html).toMatch(/]*data-block-id="quote"/);expect(html).toMatch(/]*data-block-id="heading"/); expect(await renderNoteHtml('Normal paragraph',p=>p)).not.toContain('data-block-id'); }); + + +it('preserves inert inline HTML styles and legacy font color from native notes',async()=>{ + const html=await renderNoteHtml('Red\n\nGreen\n\nBlue\n\nMarked',p=>p); + expect(html).toContain('font-weight: bold');expect(html).toContain('padding: 2px 6px');expect(html).toContain('border-radius: 4px');expect(html).toContain('royalblue');expect(html).toContain('#ffbe0b');expect(html).toContain('#e63946'); +}); + +it('keeps safe declarations without retaining layout injection, resource URLs or handlers',async()=>{ + const html=await renderNoteHtml('Safe\n\nBad',p=>p); + expect(html).toContain('color: red');expect(html).not.toMatch(/position:|z-index:|url\(|expression\(|99999|onclick|onmouseover/); +}); + +it('does not turn CSS escapes, variables, comments or important overrides into trusted inline styles',async()=>{ + const html=await renderNoteHtml('Untrusted\n\nSafe',p=>p); + expect(html).not.toMatch(/var\(|private|invalid.example|!important|calc\(|\/\*\*\//); + expect(html).toContain('color: rgb(42, 157, 143)');expect(html).toContain('background-color: rgba(10,20,30,.5)');expect(html).toContain('font-style: italic');expect(html).toContain('border-radius: 0 4px'); +}); diff --git a/server/src/services/vaultPreferences.test.ts b/server/src/services/vaultPreferences.test.ts index e713e3de..830b4a36 100644 --- a/server/src/services/vaultPreferences.test.ts +++ b/server/src/services/vaultPreferences.test.ts @@ -47,3 +47,24 @@ it('reports blocked uploads instead of claiming a fallback rule for malformed at await expect(getAttachmentFolderSetting()).rejects.toThrow(/app.json|attachmentFolderPath/); } }); + + +it('imports fresh appearance font size without treating it as an app setting or changing files',async()=>{ + await app({baseFontSize:40});const file=path.join(root,'.obsidian','appearance.json'); + const {getVaultPreferences}=await import('./vaultPreferences.js');expect((await getVaultPreferences()).values).toHaveProperty('baseFontSize',16); + await fs.writeFile(file,JSON.stringify({baseFontSize:19,accentColor:'unchanged'}));const before=await fs.readFile(file,'utf8'); + const r=await getVaultPreferences();expect(r.values).toHaveProperty('baseFontSize',19);expect(r.sources).toHaveProperty('baseFontSize','obsidian');expect(await fs.readFile(file,'utf8')).toBe(before); + await fs.writeFile(file,JSON.stringify({baseFontSize:22}));expect((await getVaultPreferences()).values).toHaveProperty('baseFontSize',22); + for(const value of [-1,10000,'19']){await fs.writeFile(file,JSON.stringify({baseFontSize:value}));const r=await getVaultPreferences();expect(r.values).toHaveProperty('baseFontSize',16);expect(r.warnings.join(' ')).toMatch(/baseFontSize/)} + await fs.writeFile(file,'{invalid');const invalid=await getVaultPreferences();expect(invalid.warnings.join(' ')).toMatch(/appearance.json/);expect(invalid.blocked?.attachmentUpload).toBeUndefined(); +}); + +it('refuses appearance configuration resolving outside the captured vault',async()=>{ + await app({});const original=fs.realpath.bind(fs),file=path.join(root,'.obsidian','appearance.json'); + const realpath=vi.spyOn(fs,'realpath').mockImplementation((async p=>String(p)===file?path.resolve(root,'..','outside-appearance.json'):original(p)) as typeof fs.realpath); + try{ + const result=await(await import('./vaultPreferences.js')).getVaultPreferences(); + expect(result.values.baseFontSize).toBe(16);expect(result.warnings.join(' ')).toMatch(/appearance.json.*outside the vault/); + expect(result.blocked?.attachmentUpload).toBeUndefined(); + }finally{realpath.mockRestore()} +}); diff --git a/server/src/services/vaultPreferences.ts b/server/src/services/vaultPreferences.ts index 811dcb48..0fec4874 100644 --- a/server/src/services/vaultPreferences.ts +++ b/server/src/services/vaultPreferences.ts @@ -7,19 +7,19 @@ const preferenceSchemas = { attachmentFolderPath:z.string(),alwaysUpdateLinks:z.boolean(),newFileLocation:z.enum(['root','current','folder']),newFileFolderPath:z.string(), useMarkdownLinks:z.boolean(),newLinkFormat:z.enum(['shortest','relative','absolute']),userIgnoreFilters:z.array(z.string()), trashOption:z.enum(['local','system','none']),promptDelete:z.boolean(),deleteUnlinkedAttachments:z.enum(['ask','always','never']), - showUnsupportedFiles:z.boolean(),readableLineLength:z.boolean(),mobileToolbarCommands:z.array(z.string()),deleteMode:z.enum(['trash','permanent']), + showUnsupportedFiles:z.boolean(),readableLineLength:z.boolean(),baseFontSize:z.number().finite().min(6).max(100),mobileToolbarCommands:z.array(z.string()),deleteMode:z.enum(['trash','permanent']), }; export type VaultPreferences = {[K in keyof typeof preferenceSchemas]:z.infer<(typeof preferenceSchemas)[K]>}; export type PreferenceSource = 'obsidian'|'webobsidian'|'default'; export interface VaultPreferencesResult {values:VaultPreferences;sources:Record;warnings:string[];vaultPath:string;blocked?:{attachmentUpload?:string}} export const defaultVaultPreferences:VaultPreferences = { attachmentFolderPath:'./attachments',alwaysUpdateLinks:false,newFileLocation:'root',newFileFolderPath:'',useMarkdownLinks:false,newLinkFormat:'shortest', - userIgnoreFilters:[],trashOption:'local',promptDelete:true,deleteUnlinkedAttachments:'ask',showUnsupportedFiles:false,readableLineLength:true,mobileToolbarCommands:[],deleteMode:'trash', + userIgnoreFilters:[],trashOption:'local',promptDelete:true,deleteUnlinkedAttachments:'ask',showUnsupportedFiles:false,readableLineLength:true,baseFontSize:16,mobileToolbarCommands:[],deleteMode:'trash', }; -async function readAppSettings(vaultPath:string):Promise<{raw:Record;exists:boolean}>{ +async function readAppSettings(vaultPath:string,name:'app.json'|'appearance.json'='app.json'):Promise<{raw:Record;exists:boolean}>{ try{ - const file=path.join(vaultPath,'.obsidian','app.json'); + const file=path.join(vaultPath,'.obsidian',name); const real=await fs.realpath(file);const root=await fs.realpath(vaultPath);const relative=path.relative(root,real); if(relative.startsWith('..'+path.sep)||relative==='..'||path.isAbsolute(relative))throw Error('configuration resolves outside the vault'); const parsed:unknown=JSON.parse(await fs.readFile(real,'utf8')); @@ -27,7 +27,7 @@ async function readAppSettings(vaultPath:string):Promise<{raw:Record,exists:true}; }catch(error){ if((error as NodeJS.ErrnoException).code==='ENOENT')return {raw:{},exists:false}; - throw Object.assign(Error(`Could not read .obsidian/app.json: ${error instanceof Error?error.message:String(error)}`),{status:400}); + throw Object.assign(Error(`Could not read .obsidian/${name}: ${error instanceof Error?error.message:String(error)}`),{status:400}); } } function attachmentRule(app:{raw:Record;exists:boolean},attachmentDir:string):string{ @@ -62,11 +62,19 @@ export async function getVaultPreferences(capturedVaultPath?:string):Promise{ const html=renderPreparedMarkdown(''); expect(html).toMatch(/{ + const html=renderPreparedMarkdown(''); + expect(html).toContain('src="https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ"'); + expect(html).toContain('sandbox="allow-scripts allow-same-origin allow-popups allow-presentation"'); + expect(html).toContain('referrerpolicy="strict-origin-when-cross-origin"'); + expect(html).toContain('width="560"');expect(html).toContain('height="315"'); + expect(html).not.toMatch(/srcdoc|onload|parent.bad/); +}); + +it.each(['https://www.youtube-nocookie.com.evil.invalid/embed/dQw4w9WgXcQ','https://youtube-nocookie.com/not-an-embed/dQw4w9WgXcQ','https://example.org/embed/dQw4w9WgXcQ'])('keeps untrusted lookalike player %s opaque',src=>{ + const html=renderPreparedMarkdown(``); + expect(html).toContain('sandbox="allow-forms allow-scripts allow-presentation"');expect(html).not.toContain('allow-same-origin'); +}); diff --git a/server/src/services/webFrames.ts b/server/src/services/webFrames.ts index 01c726d0..54ce0a1c 100644 --- a/server/src/services/webFrames.ts +++ b/server/src/services/webFrames.ts @@ -1,4 +1,5 @@ /** Raw web frames are reconstructed after sanitization with an opaque origin. */ +import {resolveExternalEmbed,EMBED_SANDBOX} from './embeds.js'; export const WEB_FRAME_SANDBOX='allow-forms allow-scripts allow-presentation'; interface HNode{ @@ -46,9 +47,12 @@ export function rehypeRestoreWebFrames(){ const p=child.properties??{}; if(child.type==='element'&&child.tagName==='a'&&p.dataWebFrame==='1'){ const src=webUrl(p.href);if(!src)return []; - return [{type:'element',tagName:'iframe',properties:{className:['web-embed'],src, + // Rebuild known player URLs from validated IDs, using the same permissions + // as URL-based YouTube embeds. Arbitrary authored frames stay opaque. + const resolved=resolveExternalEmbed(src),player=resolved?.provider==='youtube'?resolved:null; + return [{type:'element',tagName:'iframe',properties:{className:['web-embed'],src:player?.src??src, title:typeof p.title==='string'?p.title:'Embedded web page',width:dimension(p.dataWebFrameWidth),height:dimension(p.dataWebFrameHeight), - sandbox:WEB_FRAME_SANDBOX,referrerPolicy:'no-referrer',loading:'lazy', + sandbox:player?EMBED_SANDBOX:WEB_FRAME_SANDBOX,referrerPolicy:player?'strict-origin-when-cross-origin':'no-referrer',loading:'lazy', allowFullScreen:p.dataWebFrameFullscreen==='1'},children:[]}]; } visit(child);return [child]; diff --git a/tests/fixtures/embeds/clip.webm b/tests/fixtures/embeds/clip.webm new file mode 100644 index 00000000..021e0a0a Binary files /dev/null and b/tests/fixtures/embeds/clip.webm differ diff --git a/web/src/components/Editor.tsx b/web/src/components/Editor.tsx index 01f8b05e..6c66970b 100644 --- a/web/src/components/Editor.tsx +++ b/web/src/components/Editor.tsx @@ -1,5 +1,5 @@ import {captureContext,executeCommand,commands as toolbarCommands} from '../lib/toolbar/registry'; -import { useEffect, useRef, useState, useSyncExternalStore } from 'react'; +import { useEffect, useRef, useState, useSyncExternalStore, type CSSProperties } from 'react'; import DocOutline from './DocOutline'; import { Compartment, EditorState, Prec } from '@codemirror/state'; import { EditorView, keymap, highlightActiveLine, drawSelection, rectangularSelection, crosshairCursor } from '@codemirror/view'; @@ -26,6 +26,7 @@ import { htmlBlockField, markdownEmbedField, mermaidField, + displayMathField, htmlRenderedState, htmlPreviewField, calloutFoldState, @@ -76,6 +77,7 @@ export default function Editor() { const host = useRef(null); const view = useRef(null); const [editorView, setEditorView] = useState(null); + useEffect(()=>{view.current?.requestMeasure()},[preferences.values.baseFontSize]); const readonlyComp = useRef(new Compartment()).current; const applyingExternal = useRef(false); const activePath = useStore((s) => s.activePath); @@ -239,6 +241,7 @@ export default function Editor() { htmlBlockField, markdownEmbedField, mermaidField, + displayMathField, htmlRenderedState, htmlPreviewField, calloutFoldState, @@ -339,7 +342,7 @@ export default function Editor() { )}
-
+
{viewMode !== 'source' && activePath && /\.(md|markdown)$/i.test(activePath) && ( )} diff --git a/web/src/components/Preview.tsx b/web/src/components/Preview.tsx index 25bd31d9..53953074 100644 --- a/web/src/components/Preview.tsx +++ b/web/src/components/Preview.tsx @@ -1,6 +1,7 @@ +import {mermaidConfig} from '../lib/mermaidConfig'; import {pdfFileActions} from '../lib/pdfFileActions'; import {processPluginMarkdown,usePluginRevision} from '../lib/plugins/registry'; -import { useEffect, useRef, useState } from 'react'; +import { useEffect, useRef, useState, type CSSProperties } from 'react'; import { highlightCode, classHighlighter } from '@lezer/highlight'; import { LanguageDescription } from '@codemirror/language'; import { languages } from '@codemirror/language-data'; @@ -56,10 +57,7 @@ const loadKatex = () => let mermaidP: Promise | null = null; const loadMermaid = () => (mermaidP ??= import('mermaid').then((m) => { - m.default.initialize({ - startOnLoad: false, - theme: document.querySelector('.theme-dark') ? 'dark' : 'default', - }); + m.default.initialize(mermaidConfig); return m.default; })); let mmdSeq = 0; @@ -281,7 +279,7 @@ export default function Preview({ source }: { source?: string }) { const showTitle = showInlineTitle && !!title && !(h1 && h1[1].trim().toLowerCase() === title.trim().toLowerCase()); return ( -
+
{showTitle &&
{title}
}
diff --git a/web/src/lib/embeds.ts b/web/src/lib/embeds.ts index 397bef9a..d6c67d14 100644 --- a/web/src/lib/embeds.ts +++ b/web/src/lib/embeds.ts @@ -30,6 +30,8 @@ const youtube: Matcher = (u) => { let layout: ExternalEmbed['layout'] = 'video'; if (host === 'youtu.be') { id = seg[0] ?? null; + } else if (host === 'youtube-nocookie.com' && seg[0] === 'embed' && seg.length === 2) { + id = seg[1]; } else if (host === 'youtube.com') { if (seg[0] === 'watch') id = u.searchParams.get('v'); else if (seg[0] === 'shorts') { @@ -38,7 +40,8 @@ const youtube: Matcher = (u) => { } else if (seg[0] === 'embed' || seg[0] === 'live' || seg[0] === 'v') id = seg[1] ?? null; } if (!id || !YT_ID.test(id)) return null; - return { provider: 'youtube', src: `https://www.youtube.com/embed/${id}`, title: 'YouTube video', layout }; + const domain = host === 'youtube-nocookie.com' ? 'www.youtube-nocookie.com' : 'www.youtube.com'; + return { provider: 'youtube', src: `https://${domain}/embed/${id}`, title: 'YouTube video', layout }; }; const instagram: Matcher = (u) => { diff --git a/web/src/lib/livePreview.ts b/web/src/lib/livePreview.ts index 2e4f8059..b6640ca4 100644 --- a/web/src/lib/livePreview.ts +++ b/web/src/lib/livePreview.ts @@ -6,17 +6,20 @@ import { ViewUpdate, WidgetType, } from '@codemirror/view'; +import {mermaidConfig} from './mermaidConfig'; import { frontmatterTitle } from './title'; +import {propertyIconSvg} from './propertyPresentation'; import {createPdfViewer,destroyPdfViewer} from './pdfViewer'; import {pdfFileActions} from './pdfFileActions'; import {createNoteEmbedOpenButton,addNoteEmbedOpenButtons} from './noteEmbed'; import {mountPdfEmbeds} from './pdfEmbeds'; import {createCanvasEmbed,destroyCanvasEmbed,mountCanvasEmbeds} from './canvasEmbed'; -import {embedTokenAt,imageLabelEnd,revealEmbedSource,imageActions,mountImageActions} from './embedActions'; +import {embedAction,embedTokenAt,imageLabelEnd,revealEmbedSource,imageActions,mountImageActions} from './embedActions'; import { renderMarkdownBody, renderPreparedMarkdown,isGenericFileEmbed } from '../../../server/src/services/markdownRendering'; import { StateField, StateEffect, type EditorState, type Range, type Text } from '@codemirror/state'; -import { syntaxTree } from '@codemirror/language'; -import { markdownImages,markdownEmbedTarget,type MarkdownImage,isEscaped, preserveLiteralTags, findObsidianComments, stripObsidianComments, footnoteRanges, type SourceRange } from '../../../server/src/services/markdownContext'; +import { syntaxTree,LanguageDescription } from '@codemirror/language'; +import {languages} from '@codemirror/language-data'; +import { markdownLiteralRanges,markdownImages,markdownEmbedTarget,type MarkdownImage,isEscaped, preserveLiteralTags, findObsidianComments, stripObsidianComments, footnoteRanges, type SourceRange } from '../../../server/src/services/markdownContext'; import { editableFrontmatter } from '../../../server/src/services/frontmatterPolicy'; import { CALLOUT_SLOT, CALLOUT_RE, calloutDefaultTitle, calloutIconSvg } from './callouts'; import { openLightbox } from './imageLightbox'; @@ -161,19 +164,11 @@ class WikilinkWidget extends WidgetType { if (yamlEmbed) a.className += ' internal-embed file-embed mod-generic'; a.textContent = yamlEmbed ? (this.kind==='markdown'?decodeLinkTarget(this.target.split('#')[0]):this.target.split('#')[0]).split('/').pop()! : this.label; if (this.aria) a.setAttribute('aria-label', this.aria); - a.onmousedown = (e) => { - e.preventDefault(); - if(!yamlEmbed)openLink(this.target,this.kind); - }; - if(yamlEmbed){ - a.href='#'; - a.onclick=e=>{e.preventDefault();e.stopPropagation();openLink(this.target,this.kind)}; - } + a.href='#';a.onmousedown=e=>{e.preventDefault();e.stopPropagation()}; + a.onclick=e=>{e.preventDefault();e.stopPropagation();openLink(this.target,this.kind)}; return a; } - ignoreEvent() { - return this.embed&&isGenericFileEmbed(this.target); - } + ignoreEvent() {return true;} } class MdLinkWidget extends WidgetType { @@ -184,7 +179,7 @@ class MdLinkWidget extends WidgetType { return o.label === this.label && o.href === this.href; } toDOM() { - const external = /^https?:\/\//i.test(this.href); + const external = /^(?:https?:|obsidian:)\/\//i.test(this.href); const a = document.createElement('a'); a.className = 'cm-md-link' + (external ? ' external-link' : ' internal-link'); // Parse in link-label context: standalone Markdown would turn "1. Title" @@ -197,17 +192,11 @@ class MdLinkWidget extends WidgetType { for (const code of a.querySelectorAll('code')) code.classList.add('cm-code'); a.title = this.href; if (external) a.appendChild(externalLinkIcon()); - a.onmousedown = (e) => { - e.preventDefault(); - if (external) window.open(this.href, '_blank', 'noopener'); - else if (this.href.startsWith('#')) { /* in-note anchor — no-op */ } - else openLink(this.href, 'markdown'); - }; + a.href=external?this.href:'#';a.onmousedown=e=>{e.preventDefault();e.stopPropagation()}; + a.onclick=e=>{e.preventDefault();e.stopPropagation();if(external)window.open(this.href,'_blank','noopener');else openLink(this.href,'markdown')}; return a; } - ignoreEvent() { - return false; - } + ignoreEvent() {return true;} } class BareUrlWidget extends WidgetType { @@ -506,8 +495,8 @@ class PdfEmbedWidget extends WidgetType { wrap.className = 'cm-embed-pdf pdf-embed'; const name = (this.kind==='markdown'?decodeLinkTarget(this.path):this.path).split('/').pop() ?? this.path; const edit=this.canEditSource?()=>revealEmbedSource(view,wrap,this.sourceVisible):undefined; - const target=this.path+(this.src.includes('#')?this.src.slice(this.src.indexOf('#')):''); - wrap.append(createPdfViewer(this.src,name,()=>{void (this.kind==='markdown'?useStore.getState().openWikilink(target,'markdown',this.origin):useStore.getState().openAttachment(target,this.origin))},edit,{fixedHeightIncludesToolbar:!this.reading,fileActions:pdfFileActions(target,this.origin,{linkKind:this.kind})})); + const target=this.path+(this.path.includes('#')?'':this.src.includes('#')?this.src.slice(this.src.indexOf('#')):''); + wrap.append(createPdfViewer(this.src,name,()=>{void (this.kind==='markdown'?useStore.getState().openWikilink(target,'markdown',this.origin):useStore.getState().openAttachment(target,this.origin))},edit,{fixedHeightIncludesToolbar:!this.reading,fileActions:pdfFileActions(target,this.origin,{linkKind:this.kind}),missingLabel:target})); return wrap; } destroy(dom:HTMLElement){const reader=dom.querySelector('.pdf-reader');if(reader)destroyPdfViewer(reader)} @@ -547,17 +536,6 @@ class CalloutHeadWidget extends WidgetType { t.textContent = this.defaultTitle; span.appendChild(t); } - if (this.fold) { - const ch = document.createElement('span'); - ch.className = 'cm-callout-fold' + (this.folded ? ' is-folded' : ''); - ch.innerHTML = - ''; - ch.addEventListener('mousedown', (e) => { - e.preventDefault(); - view.dispatch({ effects: toggleCalloutFold.of(this.titleFrom) }); - }); - span.appendChild(ch); - } return span; } ignoreEvent(e: Event) { @@ -565,6 +543,19 @@ class CalloutHeadWidget extends WidgetType { } } +class CalloutFoldWidget extends WidgetType { + constructor(readonly folded:boolean,readonly from:number){super()} + eq(o:CalloutFoldWidget){return o.folded===this.folded&&o.from===this.from} + toDOM(view:EditorView){const ch=document.createElement('span');ch.className='cm-callout-fold'+(this.folded?' is-folded':'');ch.setAttribute('role','button');ch.setAttribute('aria-label','Toggle callout');ch.setAttribute('aria-expanded',String(!this.folded));ch.tabIndex=0;ch.innerHTML='';const toggle=()=>view.dispatch({effects:toggleCalloutFold.of(this.from)});ch.onmousedown=e=>{e.preventDefault();toggle()};ch.onkeydown=e=>{if(e.key==='Enter'||e.key===' '){e.preventDefault();toggle()}};return ch} + ignoreEvent(){return true} +} +class CalloutSourceWidget extends WidgetType { + constructor(readonly from:number,readonly to:number){super()} + eq(o:CalloutSourceWidget){return o.from===this.from&&o.to===this.to} + toDOM(view:EditorView){const wrap=document.createElement('span');wrap.className='cm-callout-source';const button=embedAction('Edit callout','source',()=>{if(view.state.readOnly)return;view.dispatch({selection:{anchor:this.from,head:this.to},effects:EditorView.scrollIntoView(this.from),userEvent:'select'});view.focus()});button.classList.add('cm-callout-edit');wrap.append(button);return wrap} + ignoreEvent(){return true} +} + /* ---------------- math (KaTeX, lazy-loaded like Obsidian's MathJax) ---------------- */ let katexPromise: Promise | null = null; @@ -577,29 +568,32 @@ function ensureKatex() { return katexPromise; } +function addBlockSourceAction(root:HTMLElement,view:EditorView,range:SourceRange){ + const actions=document.createElement('span');actions.className='cm-block-actions'; + const button=embedAction('Edit block','source',()=>{if(view.state.readOnly)return;view.dispatch({selection:{anchor:range.from,head:range.to},effects:EditorView.scrollIntoView(range.from),userEvent:'select'});view.focus()});button.classList.add('cm-block-edit');actions.append(button);root.append(actions); +} class MathWidget extends WidgetType { - constructor(readonly tex: string, readonly display: boolean) { + constructor(readonly tex: string, readonly display: boolean,readonly source?:SourceRange,readonly canEditSource=false) { super(); } eq(o: MathWidget) { - return o.tex === this.tex && o.display === this.display; + return o.tex === this.tex && o.display === this.display&&o.source?.from===this.source?.from&&o.source?.to===this.source?.to&&o.canEditSource===this.canEditSource; } - toDOM() { + toDOM(view:EditorView) { const span = document.createElement('span'); span.className = 'cm-math-rendered' + (this.display ? ' math-block' : ' math-inline'); span.textContent = this.tex; // shown until KaTeX loads void ensureKatex().then((katex) => { try { katex.render(this.tex, span, { throwOnError: false, displayMode: this.display }); + if(this.display&&this.source&&this.canEditSource)addBlockSourceAction(span,view,this.source);if(span.isConnected)view.requestMeasure(); } catch { /* keep raw tex */ } }); return span; } - ignoreEvent() { - return false; - } + ignoreEvent(event:Event) {return !!(event.target as HTMLElement|null)?.closest?.('.cm-block-actions');} } class HrWidget extends WidgetType { @@ -614,6 +608,20 @@ class HrWidget extends WidgetType { } } +function buildDisplayMath(state:EditorState):DecorationSet{ + if(!state.field(livePreviewState,false))return Decoration.none; + const doc=state.doc,readonly=state.field(livePreviewReadonly,false)??false,literal=[...documentLiteralRanges(state),...documentComments(state)],ranges:Range[]=[]; + const fm=doc.toString().match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/)?.[0].length??0; + for(let n=1;n<=doc.lines;n++){ + const line=doc.line(n);if(line.fromline.from>=r.from&&line.fromdoc.lines)continue; + const from=line.from,to=doc.line(end).to,touched=!readonly&&state.selection.ranges.some(r=>r.from<=to&&r.to>=from); + if(!touched){const tex=doc.sliceString(line.to+1,doc.line(end).from).trim();ranges.push(Decoration.replace({widget:new MathWidget(tex,true,{from,to},!readonly),block:true}).range(from,to))}n=end; + }return Decoration.set(ranges,true); +} +export const displayMathField=StateField.define({create:buildDisplayMath,update(value,tr){return tr.docChanged||tr.selection||tr.effects.some(e=>e.is(setLivePreviewEnabled)||e.is(setLivePreviewReadonly))?buildDisplayMath(tr.state):value.map(tr.changes)},provide:field=>EditorView.decorations.from(field)}); + /* ---------------- note embeds (transclusion, like Obsidian ![[note]]) ---------------- */ // Injected from Editor.tsx: resolves a wikilink target and returns rendered, @@ -625,7 +633,7 @@ export function setLivePreviewNoteEmbedProvider(fn: (target: string,kind?:'wiki' function embedNotFound(el: HTMLElement, target: string) { el.classList.add('cm-embed-missing'); - el.textContent = `"${target}" could not be found.`; + el.textContent = /^ru(?:-|$)/i.test(navigator.language)?`«${target}» не может быть найдена.`:`“${target}” could not be found.`; } class CanvasEmbedWidget extends WidgetType{ @@ -666,9 +674,10 @@ class NoteEmbedWidget extends WidgetType { void noteEmbedProvider(this.target,this.kind).then((res) => { if(destroyed)return; if (!res) { - box.textContent = ''; - embedNotFound(box, this.target); - return; + 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){const ru=/^ru(?:-|$)/i.test(navigator.language);title.textContent=ru?`Не удалось найти «${fragment}» в ${name}`:`Could not find “${fragment}” in ${name}`;box.append(title)} + box.classList.add('is-unresolved');return; } content.innerHTML = res.html; // sanitized upstream (rehype-sanitize) content.dataset.embedSource=res.path??origin; @@ -705,10 +714,7 @@ let mermaidPromise: Promise | null = null; function ensureMermaid() { if (!mermaidPromise) { mermaidPromise = import('mermaid').then((m) => { - m.default.initialize({ - startOnLoad: false, - theme: document.querySelector('.theme-dark') ? 'dark' : 'default', - }); + m.default.initialize(mermaidConfig); return m.default; }); } @@ -717,23 +723,23 @@ function ensureMermaid() { let mermaidSeq = 0; class MermaidWidget extends WidgetType { - constructor(readonly code: string) { + constructor(readonly code: string,readonly source:SourceRange,readonly canEditSource:boolean) { super(); } eq(o: MermaidWidget) { - return o.code === this.code; + return o.code === this.code&&o.source.from===this.source.from&&o.source.to===this.source.to&&o.canEditSource===this.canEditSource; } ignoreEvent() { return true; } - toDOM() { + toDOM(view:EditorView) { const div = document.createElement('div'); div.className = 'mermaid cm-mermaid'; div.textContent = '…'; void ensureMermaid() .then((mermaid) => mermaid.render(`cm-mmd-${++mermaidSeq}`, this.code)) .then(({ svg }) => { - div.innerHTML = svg; + div.innerHTML = svg;if(this.canEditSource)addBlockSourceAction(div,view,this.source);if(div.isConnected)view.requestMeasure(); }) .catch((err) => { div.classList.add('mod-error'); @@ -774,7 +780,7 @@ function buildMermaid(state: EditorState): DecorationSet { } if (!touched) { const code = end > n + 1 ? doc.sliceString(doc.line(n + 1).from, doc.line(end - 1).to) : ''; - ranges.push(Decoration.replace({ widget: new MermaidWidget(code), block: true }).range(from, to)); + ranges.push(Decoration.replace({ widget: new MermaidWidget(code,{from,to},!ro), block: true }).range(from, to)); } n = end; } @@ -978,7 +984,7 @@ function buildCalloutFolds(state: EditorState): DecorationSet { break; } } - if (!touched) ranges.push(Decoration.replace({ block: true }).range(line.to, to)); + if (!touched) ranges.push(Decoration.replace({ block: true, inclusiveStart:false }).range(line.to, to)); n = last; continue; } @@ -1036,25 +1042,17 @@ function documentComments(state: EditorState): SourceRange[] { return ranges; } +const literalRangeCache=new WeakMap>(); +function documentLiteralRanges(state:EditorState){let ranges=literalRangeCache.get(state.doc);if(!ranges){ranges=markdownLiteralRanges(state.doc.toString());literalRangeCache.set(state.doc,ranges)}return ranges} const multilineCodeCache = new WeakMap(); function liveMultilineCodeRanges(state: EditorState): (SourceRange & { size: number })[] { if (state.field(livePreviewReadonly, false)) return []; const cached = multilineCodeCache.get(state.doc); if (cached) return cached; const source = state.doc.toString(); - const blocks: SourceRange[] = []; - const owned: SourceRange[] = [...documentComments(state)]; - const frontmatter = source.match(/^---\r?\n[\s\S]*?\r?\n---(?:\r?\n|$)/); - if (frontmatter) owned.push({ from: 0, to: frontmatter[0].length }); - syntaxTree(state).iterate({ enter(node) { - if (node.name === 'FencedCode' || node.name === 'CodeBlock') { - blocks.push({from:node.from,to:node.to}); return false; - } - if (node.name === 'HTMLTag' || node.name === 'HTMLBlock') { - const raw = source.slice(node.from, node.to); - if (HTML_TAG_START_RE.test(raw) || raw.startsWith(' B[Browser]',fence].join(nl),'[^named]: Footnote'].join(nl+nl); + for(const mode of ['live','reading']){ + await show(long,mode);let v=getActiveEditor(); + const scroll=async at=>{v.dispatch({selection:{anchor:Math.max(0,at-1)},effects:EditorView.scrollIntoView(at,{y:'start',yMargin:10})});for(let i=0;i<12;i++)await wait()}; + await scroll(long.indexOf(code));check(!!v.dom.querySelector('.HyperMD-codeblock-bg[data-lang]'),mode+': late code fence retains block styling and language flair');const codeLines=[...v.dom.querySelectorAll('.HyperMD-codeblock-bg')];check(codeLines.reduce((n,e)=>n+e.getBoundingClientRect().height,0)<80,mode+': hidden fences add no empty code rows');check(v.dom.querySelector('[data-lang]')?.dataset.lang==='JavaScript',mode+': native language label casing'); + await scroll(long.indexOf(math));check(!!v.dom.querySelector('.cm-math-rendered.math-block .katex'),mode+': multiline math renders beyond initial viewport'); + if(mode==='live'){ + const button=v.dom.querySelector('.math-block .cm-block-edit');check(!!button,mode+': display math has source action'); + if(button){await trustedPress(v.dom.querySelector('.math-block'),'hover');await wait();check(getComputedStyle(button.parentElement).opacity==='1','math source action appears on hover '+hoverDetails(v.dom.querySelector('.math-block')));await trustedPress(button,'keyboard');await wait();const r=v.state.selection.main;check(v.state.doc.sliceString(r.from,r.to)===math,'math Enter selects complete TeX source');await scroll(long.indexOf(math));} + } + await scroll(long.indexOf(fence+'mermaid'));check(!!v.dom.querySelector('.cm-mermaid svg'),mode+': Mermaid renders'); + if(mode==='live'){ + const button=v.dom.querySelector('.cm-mermaid .cm-block-edit');check(!!button,mode+': Mermaid has source action'); + if(button){await trustedPress(v.dom.querySelector('.cm-mermaid'),'hover');await wait();check(getComputedStyle(button.parentElement).opacity==='1','Mermaid source action appears on hover '+hoverDetails(v.dom.querySelector('.cm-mermaid')));await trustedPress(button,'pointer');await wait();const r=v.state.selection.main;check(v.state.doc.sliceString(r.from,r.to).startsWith(fence+'mermaid')&&v.state.doc.sliceString(r.from,r.to).endsWith(fence),'Mermaid pointer selects complete fenced source');await scroll(long.indexOf(fence+'mermaid'));} + } + const shape=v.dom.querySelector('.cm-mermaid .node rect');if(shape)check(getComputedStyle(shape).fill==='rgb(236, 236, 255)'&&getComputedStyle(v.dom.querySelector('.cm-mermaid > svg')).filter==='invert(1) hue-rotate(180deg) saturate(1.25)',mode+': native Mermaid dark palette filter'); + if(mode==='live'){await scroll(long.indexOf('[^named]'));const ref=v.dom.querySelector('.cm-footref');check(ref&&getComputedStyle(ref).color==='rgb(179, 179, 179)','Live footnote markers use muted text');} + check(useStore.getState().content===long,mode+': long-page rendering preserves source'); + } + root.unmount();if(issues.length)throw Error(JSON.stringify(issues));return 'POLYGON_DETAILS_PASS'; + }; + `},bundle:true,format:'iife',platform:'browser',tsconfigRaw:{compilerOptions:{useDefineForClassFields:false,jsx:'react-jsx'}},loader:{'.woff2':'file','.woff':'file','.ttf':'file'},define:{'import.meta.env.DEV':'false'},outfile:join(dir,'fixture.js'),logLevel:'silent'}); + await writeFile(join(dir,'index.html'),'
'); + 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:900,height:1100,webPreferences:{backgroundThrottling:false}});win.webContents.on('console-message',(_e,l,m)=>{if(l>=2)console.error(m)});await win.loadFile(${JSON.stringify(join(dir,'index.html'))});win.webContents.debugger.attach('1.3');await win.webContents.debugger.sendCommand('Emulation.setDeviceMetricsOverride',{width:900,height:1100,deviceScaleFactor:1,mobile:false});await win.webContents.debugger.sendCommand('Emulation.setFocusEmulationEnabled',{enabled:true});let finished=false;const run=win.webContents.executeJavaScript('window.run()').then(v=>{finished=true;return v},e=>{finished=true;throw e});run.catch(()=>{});while(!finished){const input=await win.webContents.executeJavaScript('window.pendingInput??null');if(input){if(input.kind==='keyboard'){await win.webContents.debugger.sendCommand('Input.dispatchKeyEvent',{type:'keyDown',key:'Enter',code:'Enter',windowsVirtualKeyCode:13,text:'\\r',unmodifiedText:'\\r'});await win.webContents.debugger.sendCommand('Input.dispatchKeyEvent',{type:'keyUp',key:'Enter',code:'Enter',windowsVirtualKeyCode:13})}else{await win.webContents.debugger.sendCommand('Input.dispatchMouseEvent',{type:'mouseMoved',x:input.x,y:input.y});if(input.kind!=='hover'){await win.webContents.debugger.sendCommand('Input.dispatchMouseEvent',{type:'mousePressed',x:input.x,y:input.y,button:'left',clickCount:1});await win.webContents.debugger.sendCommand('Input.dispatchMouseEvent',{type:'mouseReleased',x:input.x,y:input.y,button:'left',clickCount:1})}}await win.webContents.executeJavaScript('window.finishInput()')}await new Promise(r=>setTimeout(r,25))}console.log(await run);win.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:60_000});assert.match(stdout,/POLYGON_DETAILS_PASS/); + }finally{assert.ok(dir.startsWith(join(tmpdir(),'webo-polygon-details-')));await rm(dir,{recursive:true,force:true})} +}); diff --git a/web/tests/vaultLinksBrowser.test.ts b/web/tests/vaultLinksBrowser.test.ts index 6004ef3e..489ffdbe 100644 --- a/web/tests/vaultLinksBrowser.test.ts +++ b/web/tests/vaultLinksBrowser.test.ts @@ -47,8 +47,8 @@ window.run=async()=>{ const calls=[];const expected=[['shot%20one','wiki'],['shot%20one.md','markdown'],['shot%20%231.md','markdown']]; setLivePreviewLinkHandler((target,kind='wiki')=>calls.push([target,kind])); const lp=new EditorView({state:EditorState.create({doc:source,extensions:[livePreviewState,livePreviewReadonly,livePreviewPlugin]}),parent:document.querySelector('#editor')});await wait(); - const widgets=[...document.querySelectorAll('.cm-wikilink,.cm-md-link')];check(widgets.length===3,'LP link widgets render');for(const anchor of widgets)anchor.dispatchEvent(new MouseEvent('mousedown',{bubbles:true,cancelable:true})); - check(JSON.stringify(calls)===JSON.stringify(expected),'LP click preserves syntax and encoded target: '+JSON.stringify(calls));lp.destroy();calls.length=0; + const widgets=[...document.querySelectorAll('.cm-wikilink,.cm-md-link')];check(widgets.length===3,'LP link widgets render');for(const anchor of widgets){anchor.dispatchEvent(new MouseEvent('mousedown',{bubbles:true,cancelable:true}));anchor.click();} + check(JSON.stringify(calls)===JSON.stringify(expected),'LP click preserves syntax and encoded target: '+JSON.stringify(calls));calls.length=0;for(const anchor of widgets)anchor.click();check(JSON.stringify(calls)===JSON.stringify(expected),'keyboard-generated click opens links exactly once');lp.destroy();calls.length=0; useStore.setState({openWikilink:(target,kind='wiki')=>calls.push([target,kind])}); const previewRoot=createRoot(document.querySelector('#root'));previewRoot.render();await wait();await wait(); const anchors=[...document.querySelectorAll('.preview-inner a[data-wikilink],.preview-inner a[data-link-kind="markdown"]')];check(anchors.length===3,'Preview link anchors render');for(const anchor of anchors)anchor.dispatchEvent(new MouseEvent('click',{bubbles:true,cancelable:true})); diff --git a/web/tests/vaultPreferencesBrowser.test.ts b/web/tests/vaultPreferencesBrowser.test.ts index 82ee1029..379cf8bc 100644 --- a/web/tests/vaultPreferencesBrowser.test.ts +++ b/web/tests/vaultPreferencesBrowser.test.ts @@ -22,11 +22,11 @@ window.run=async()=>{ const check=(v,m)=>{if(!v)throw Error(m)};const wait=(ms=150)=>new Promise(r=>setTimeout(r,ms)); let saved={vault:{path:'/fixture/vault',deleteMode:'trash',followObsidianDeletion:false,trashRetentionDays:0},ui:{},git:{},auth:{}}; const initialToolbar=getDefaultToolbarConfig();initialToolbar.layouts.mobile.items=[];saved.ui.editingToolbar=initialToolbar; - let fail=true,puts=0;let readable=true;let failReload=false;let uploadsBlocked=false; + let fontSize=19;let fail=true,puts=0;let readable=true;let failReload=false;let uploadsBlocked=false; api.getSettings=async()=>{if(failReload)throw Error('fixture reload failed');return structuredClone(saved)};api.putSettings=async(patch)=>{puts++;if(fail)throw Error('fixture settings write failed');saved={...saved,vault:{...saved.vault,...patch.vault},ui:{...saved.ui,...patch.ui}};return structuredClone(saved)}; api.indexStatus=async()=>({phase:'ready',available:true,initialScanComplete:true,generation:'fixture',revision:1,indexedNotes:1,pendingPaths:0,watcherMode:'polling'}); api.tags=async()=>({tags:[]});api.propertyTypes=async()=>({types:{}}); - window.fetch=async()=>new Response(JSON.stringify({values:{...defaultVaultPreferences,readableLineLength:readable,mobileToolbarCommands:['editor:toggle-bold','unknown:plugin'],trashOption:'none',deleteMode:saved.vault.followObsidianDeletion?'permanent':saved.vault.deleteMode},sources:{...Object.fromEntries(Object.keys(defaultVaultPreferences).map(k=>[k,'default'])),readableLineLength:'obsidian',deleteMode:'webobsidian'},warnings:[],blocked:uploadsBlocked?{attachmentUpload:'Invalid app.json. Uploads blocked.'}:{},vaultPath:saved.vault.path}),{status:200,headers:{'content-type':'application/json'}}); + window.fetch=async()=>new Response(JSON.stringify({values:{...defaultVaultPreferences,baseFontSize:fontSize,readableLineLength:readable,mobileToolbarCommands:['editor:toggle-bold','unknown:plugin'],trashOption:'none',deleteMode:saved.vault.followObsidianDeletion?'permanent':saved.vault.deleteMode},sources:{...Object.fromEntries(Object.keys(defaultVaultPreferences).map(k=>[k,'default'])),readableLineLength:'obsidian',deleteMode:'webobsidian'},warnings:[],blocked:uploadsBlocked?{attachmentUpload:'Invalid app.json. Uploads blocked.'}:{},vaultPath:saved.vault.path}),{status:200,headers:{'content-type':'application/json'}}); const render=()=>{document.body.innerHTML='
';const r=createRoot(document.querySelector('#root'));r.render();return r}; useStore.setState({settingsOpen:true,save:async()=>{},activePath:'note.md',content:'Note body',viewMode:'source',dirty:false}); let root=render();await wait();await wait(); @@ -45,6 +45,7 @@ window.run=async()=>{ check(document.body.textContent.includes('Effective vault preferences'),'effective sources are visible');check(document.body.textContent.includes('obsidian'),'Obsidian source is shown'); uploadsBlocked=true;await getVaultPreferences();await wait();const attachmentRow=Array.from(document.querySelectorAll('.vault-preferences-table tr')).find(r=>r.firstElementChild?.textContent==='attachmentFolderPath');check(attachmentRow.textContent.includes('Unavailable — uploads blocked'),'invalid attachment rule is not displayed as active fallback');check(!attachmentRow.textContent.includes('./attachments'),'blocked attachment fallback hidden');uploadsBlocked=false; root.unmount();useStore.setState({settingsOpen:false});document.body.innerHTML='
';root=createRoot(document.querySelector('#root'));root.render(<>);await wait();await getVaultPreferences();await wait(); + check(getComputedStyle(document.querySelector('.cm-content')).fontSize==='19px'&&getComputedStyle(document.querySelector('.markdown-preview')).fontSize==='19px','appearance font applies to mounted note views');fontSize=22;await getVaultPreferences();await wait();check(getComputedStyle(document.querySelector('.cm-content')).fontSize==='22px'&&getComputedStyle(document.querySelector('.markdown-preview')).fontSize==='22px','appearance changes update both views'); const narrow=document.querySelector('.preview-inner').getBoundingClientRect().width;check(document.querySelector('.markdown-source-view').classList.contains('is-readable-line-width'),'readable editor'); readable=false;await getVaultPreferences();await wait();check(!document.querySelector('.markdown-source-view').classList.contains('is-readable-line-width'),'external app change updates mounted editor');check(document.querySelector('.preview-inner').getBoundingClientRect().width>narrow,'external app change expands reading width'); document.querySelector('#root').style.width='340px';await wait();check(document.querySelector('.preview-inner').getBoundingClientRect().width<=340,'narrow reading view fits'); diff --git a/web/tests/workspaceNoteFragmentsBrowser.test.ts b/web/tests/workspaceNoteFragmentsBrowser.test.ts index 7ea78b83..d4593357 100644 --- a/web/tests/workspaceNoteFragmentsBrowser.test.ts +++ b/web/tests/workspaceNoteFragmentsBrowser.test.ts @@ -24,7 +24,7 @@ test('workspace note source buttons reveal headings and native block references const filler=Array.from({length:45},(_,i)=>'Filler paragraph '+i).join('\\n\\n'); const files={'Host.md':'# Host\\n\\n![[Target#Parent#Section]]\\n\\n![[Target#^task]]\\n\\n![[Target#^callout]]\\n\\n![[Target#^quote]]','Target.md':'# Target\\n\\n'+filler+'\\n\\n## Parent\\n\\n### **Section**\\n\\nSECTION_BODY\\n\\n'+filler+'\\n\\n- [x] TASK_BODY ^task\\n\\n'+filler+'\\n\\n> [!note] Title\\n> CALLOUT_BODY ^callout\\n\\n'+filler+'\\n\\n> QUOTE_BODY ^quote\\n\\n'+filler}; api.tags=async()=>({tags:[]});api.propertyTypes=async()=>({types:{}});api.draftScope=async()=>({scopeId:'fixture-note-fragments'}); - api.resolve=async(target,from,kind)=>{let path=target.split('#')[0];if(kind==='markdown')path=decodeURIComponent(path);path=path.replace(/^\\//,'');if(!path)path=from??useStore.getState().activePath;return {path:path.endsWith('.md')?path:path+'.md'}}; + let writes=0;api.read=async path=>({content:files[path]??'',version:'fixture'});api.write=async()=>{writes++;return {ok:true}};api.putUiState=async()=>({ok:true}); const root=createRoot(document.querySelector('#root')); const wait=()=>new Promise(r=>setTimeout(r,50)),check=(ok,msg)=>{if(!ok)throw Error(msg)}; @@ -53,6 +53,7 @@ test('workspace note source buttons reveal headings and native block references } await useStore.getState().openWikilink('Target#Parent#Section');await wait(); if(mode!=='preview')await until(()=>getActiveEditor().state.selection.main.head===noteFragmentRange(files['Target.md'],'Parent#Section').from,mode+': repeated same-file reference'); + await useStore.getState().openWikilink('#^quote');await until(()=>useStore.getState().noteNavigation?.fragment==='^quote'&&(mode==='preview'||getActiveEditor()?.state.selection.main.head===noteFragmentRange(files['Target.md'],'^quote').from),mode+': fragment-only source navigation'); root.render(
);await wait(); } useStore.setState({activePath:'Host.md',content:files['Host.md'],viewMode:'live',noteNavigation:null});root.render();await wait();history.replaceState(null,'','/note/Host.md');initUrlSync(); @@ -77,15 +78,16 @@ test('workspace note source buttons reveal headings and native block references }; `},bundle:true,format:'iife',platform:'browser',tsconfigRaw:{compilerOptions:{useDefineForClassFields:false,jsx:'react-jsx'}}, loader:{'.woff2':'file','.woff':'file','.ttf':'file'},define:{'import.meta.env.DEV':'false'},outfile:join(dir,'fixture.js'),logLevel:'silent'}); + await build({entryPoints:[fileURLToPath(new URL('../../server/src/services/fileReferences.ts',import.meta.url))],outfile:join(dir,'resolver.cjs'),bundle:true,platform:'node',format:'cjs',logLevel:'silent'}); await writeFile(join(dir,'index.html'),'
'); await writeFile(join(dir,'runner.cjs'),` const {app,BrowserWindow}=require('electron'),http=require('node:http'),fs=require('node:fs'),path=require('node:path'); - const dir=${JSON.stringify(dir)}; + const dir=${JSON.stringify(dir)},resolveReference=require(${JSON.stringify(join(dir,'resolver.cjs'))}).resolveReference; app.setPath('userData',${JSON.stringify(join(dir,'profile'))}); app.whenReady().then(async()=>{ const win=new BrowserWindow({show:false,width:800,height:1200,webPreferences:{backgroundThrottling:false}}); win.webContents.on('console-message',(_e,_level,message)=>{if(_level>=2)console.error(message)}); - const server=http.createServer((req,res)=>{const url=new URL(req.url,'http://fixture'),name=url.pathname.startsWith('/note/')||url.pathname==='/'?'index.html':path.basename(url.pathname);try{res.setHeader('Content-Type',name.endsWith('.js')?'text/javascript':name.endsWith('.css')?'text/css':name.endsWith('.html')?'text/html':'application/octet-stream');res.end(fs.readFileSync(path.join(dir,name)))}catch{res.writeHead(404).end()}});await new Promise(r=>server.listen(0,'127.0.0.1',r)); + const server=http.createServer((req,res)=>{const url=new URL(req.url,'http://fixture');if(url.pathname==='/api/resolve'){res.setHeader('Content-Type','application/json');res.end(JSON.stringify({path:resolveReference(url.searchParams.get('target')??'',url.searchParams.get('from')??'',['Host.md','Target.md'],url.searchParams.get('kind')==='markdown'?'markdown':'wiki')}));return}const name=url.pathname.startsWith('/note/')||url.pathname==='/'?'index.html':path.basename(url.pathname);try{res.setHeader('Content-Type',name.endsWith('.js')?'text/javascript':name.endsWith('.css')?'text/css':name.endsWith('.html')?'text/html':'application/octet-stream');res.end(fs.readFileSync(path.join(dir,name)))}catch{res.writeHead(404).end()}});await new Promise(r=>server.listen(0,'127.0.0.1',r)); await win.loadURL('http://127.0.0.1:'+server.address().port); win.webContents.focus(); await win.webContents.executeJavaScript('window.run().catch(e=>{console.error(e.stack);throw e})');