From bceb731a83af90bfeb41fdde37a99c6f8f935db0 Mon Sep 17 00:00:00 2001 From: macros0 Date: Mon, 2 Nov 2026 19:35:12 +0300 Subject: [PATCH 1/2] fix: match code colors and Canvas layout, add Obsidian favicon --- IMPLEMENTATION_PLAN.md | 32 +++++++ PRD.md | 8 +- docs/INSTALLATION_CT102.md | 15 +++ package-lock.json | 1 + web/index.html | 1 + web/package.json | 1 + web/src/assets/obsidian.svg | 51 +++++++++++ web/src/components/CanvasView.tsx | 34 +++---- web/src/components/Editor.tsx | 7 +- web/src/components/Icon.tsx | 1 + web/src/components/Preview.tsx | 4 +- web/src/lib/nativeCodeLanguages.ts | 49 ++++++++++ web/src/styles/obsidian.css | 24 +++-- web/tests/canvasTextLayoutBrowser.test.ts | 107 ++++++++++++++++++++++ web/tests/nativeCodeColorsBrowser.test.ts | 61 ++++++++++++ 15 files changed, 360 insertions(+), 36 deletions(-) create mode 100644 web/src/assets/obsidian.svg create mode 100644 web/src/lib/nativeCodeLanguages.ts create mode 100644 web/tests/canvasTextLayoutBrowser.test.ts create mode 100644 web/tests/nativeCodeColorsBrowser.test.ts diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index b540a995..c3decf7e 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -1,5 +1,37 @@ # IMPLEMENTATION PLAN — WebObsidian +## Native code colors, Canvas and favicon fork PR — 2026-11-02 + +Cập nhật lần cuối: 2026-11-02. + +- [x] Match native fenced JavaScript, Python and YAML token boundaries and colors with lazy stream grammars. Keep Markdown, frontmatter and the standalone code viewer palettes independent. Verify both themes and Live, Reading and Source modes without source changes. +- [x] Review all pending changes against fork main. Add a failing browser assertion for neutral Canvas borders and narrow the colored-card selector to the actual `--c:` property. +- [x] Run fresh full tests, typecheck, workspace/desktop builds and disposable integration smoke. Prepare all pending source, tests and documentation for a PR against `macros0/webobsidian:main`. + +Nhật ký tiến độ — 2026-11-02. Independent review identified the Canvas height variable colliding with the existing broad colored-card selector. The correction is included in this PR and has not been deployed to CT102. + +Final validation — 2026-11-02. Fresh full run passed 390 server tests (10 Windows capability skips) and all 520 web tests. Typecheck, workspace build, desktop typecheck/build, disposable integration smoke and all three MCP tests passed. The earlier PDF Chrome-startup `bad port` failure passed in isolation and in the final full run. Independent review approved the selector correction with no remaining findings. + +## Obsidian site icon — 2026-11-02 + +- [x] Add the official Obsidian gradient SVG as the browser favicon, verify the production HTML resolves the icon, and deploy the tested assets to CT102. + +Nhật ký tiến độ — 2026-11-02. Use the original asset from https://obsidian.md/images/obsidian-logo-gradient.svg. Vite fingerprints the icon URL for browser cache refresh. + +Verification — production build, SVG/XML and exact asset bytes passed. Deployed `favicon-a88455468a4a` with healthy container, matching served assets and unchanged settings. Backup `/opt/webobsidian/backups/favicon-a88455468a4a-20261102T162308Z`. + +## Compact Canvas text layout — 2026-11-02 + +Cập nhật lần cuối: 2026-11-02. + +- [x] Reproduce compact two-line card clipping in a browser, remove reading-view boundary margins and verify long-card scrolling and unchanged document bytes. Match native selection controls, compact toolbar dimensions, text typography and neutral card borders. Check zoom/reset and Edit through the selection toolbar. + +Nhật ký tiến độ — 2026-11-02. Browser reproduction confirms a 70px card has 96px of scroll content because of paragraph margins. Scope the layout correction to Canvas text cards under FR-12. + +Verification — 2026-11-02. All 520 web tests passed after the text layout correction. After the native toolbar and border changes, all three focused Canvas browser tests and the production web build (including TypeScript) passed. Native toolbar dimensions and neutral border colors were checked against the installed Obsidian application resources. Plugin controls were excluded at the owner's request. Deployment records follow below. + +- [x] Follow-up with the actual 250×60 card dimensions. The original 300×70 fixture missed residual overflow. Use native height-dependent vertical padding, keep small boards at 100% on opening, and verify zoom without document changes. All three focused browser tests and the production build pass. Deployed `canvas-layout-332337470529` with healthy container, matching served asset hashes and unchanged settings. Backup `/opt/webobsidian/backups/canvas-layout-332337470529-20261102T120623Z`. Browser UI inspection reported page zoom at 90%. Direct screenshot capture failed in computer-use, so final visual verification in the user's Comet remains manual. + ## Native embed parity fork PR — 2026-11-01 diff --git a/PRD.md b/PRD.md index b2e9ef75..eb16a19f 100644 --- a/PRD.md +++ b/PRD.md @@ -88,7 +88,8 @@ > deployment is outside this integration task. > Product Requirements Document -> Phiên bản: 1.23 · Cập nhật: 2026-09-30 · Trạng thái: Draft +> Phiên bản: 1.24 · Cập nhật: 2026-11-02 · Trạng thái: Draft +> Changelog 1.24 (FR-2, FR-12): fenced JavaScript, Python and YAML use the native editor token palette in Live, Reading and Source modes. Canvas uses compact native selection controls, height-dependent text padding and an initial fit capped at 100%. The browser tab uses the official Obsidian gradient icon. > Changelog 1.23 (FR-23 — chọn giá trị cho thuộc tính đóng: nút `▾` + danh sách giá trị, issue #61): trên > trang task, `status:` là **text tự do** nên đổi trạng thái phải gõ đúng id — mà gõ sai thì không vô hại: > board chỉ map id canonical (`open`/`in-progress`/`blocked`/`done`) + vài alias, mọi giá trị khác thành @@ -672,9 +673,10 @@ chúng bằng đường có mũi tên, dùng cho brainstorm, moodboard, sơ đ `ceil(15/scale)` đơn vị canvas). Giữ **Alt** (⌃ trên macOS) để kéo tự do (tắt snap); giữ **Shift** để khoá trục. - **Format trong text card**: phím tắt như editor chính (`obsidianKeymap`) — ⌘B đậm, ⌘I nghiêng, ⌘K thêm link, ⌘L task, `⌘/` comment (toggle marker); menu chuột phải mở **đúng tại con trỏ** và tự dịch vào trong màn hình. -- **Căn lề text** (mở rộng ngoài JSON Canvas spec): `TextNode.textAlign` = `left|center|right`, chọn qua nút trong - selection menu (khi chọn text node) hoặc submenu "Align" menu chuột phải; áp cho cả textarea lẫn nội dung render. +- **Căn lề text** (mở rộng ngoài JSON Canvas spec): `TextNode.textAlign` = `left|center|right`, chọn qua + submenu "Align" menu chuột phải; áp cho cả textarea lẫn nội dung render. *Lưu ý: Obsidian thật bỏ qua field này khi mở lại.* +- **Selection toolbar parity (2026-11-02)**: a single text card shows Remove, Set color, Zoom to selection and Edit in a compact native-style toolbar. Text cards use readable 16px default typography, native neutral borders and no outer paragraph margins. Vertical padding shrinks with card height using the native Canvas rule so two lines fit a 250×60 card. Opening a small board fits at up to 100%. Zoom changes viewport state only. - **Lưu**: autosave debounce (~900ms) như editor, ghi qua `PUT /api/files/content` (store `content`/`save`, `.canvas` đã nằm trong `TEXT_RE`). Không thêm endpoint mới. - **Tạo canvas mới**: context menu cây thư mục ("New canvas") + command palette; tên `Untitled.canvas` không diff --git a/docs/INSTALLATION_CT102.md b/docs/INSTALLATION_CT102.md index 3a0a2b1b..9bc447b1 100644 --- a/docs/INSTALLATION_CT102.md +++ b/docs/INSTALLATION_CT102.md @@ -92,6 +92,21 @@ package/lockfile, manifests всех пяти workspaces и `server/dist`, `serv ## Проверка состояния +### Установленная версия — иконка сайта, 2 ноября 2026 + +- Build `favicon-a88455468a4a`, image ID `sha256:0ca49dacd783e37b7ec1799404e6442386538cc93e6ddf5b3feeb4e4ea80667c`. +- Добавлена официальная SVG-иконка Obsidian во вкладке браузера. Проверены production build, Linux smoke, healthy, SPA/asset hashes и совпадение настроек с backup. +- Резервная копия `/opt/webobsidian/backups/favicon-a88455468a4a-20261102T162308Z`, предыдущий образ `webobsidian:canvas-layout-332337470529` сохранён. +- Локальный пакет `build/favicon-release/`. + +### Установленная версия — Canvas, 2 ноября 2026 + +- Build `canvas-layout-332337470529`, image ID `sha256:6650bcfac3e895d2e37a4b9d3b269d7944823f3a55ffbcb7fab36d85509f159d`. +- Исправлены отступы двухстрочной карточки 250×60, шрифт, рамка и штатная панель выбранной карточки. Начальный fit маленькой доски ограничен 100%. +- Три браузерных теста Canvas, production web build и изолированный Linux smoke прошли. Healthy, build ID, отдаваемые SPA/JS/CSS и совпадение настроек с резервной копией проверены. +- Резервная копия `/opt/webobsidian/backups/canvas-layout-332337470529-20261102T120623Z`. Предыдущий образ `webobsidian:canvas-layout-c31c06e2314e` сохранён. +- Локальный пакет `build/canvas-layout-final-release/`. Исходники развёрнуты как снимок рабочей копии. Commit и push не выполнялись. + ### Установленная версия: цвет литералов и многострочные кавычки Live — 29 октября 2026 - Build: `cc8b061-worktree-a14ad1ae6b77`; source SHA256 diff --git a/package-lock.json b/package-lock.json index 51c69cfe..ed487315 100644 --- a/package-lock.json +++ b/package-lock.json @@ -12015,6 +12015,7 @@ "@codemirror/lang-yaml": "^6.1.3", "@codemirror/language": "^6.10.6", "@codemirror/language-data": "^6.5.2", + "@codemirror/legacy-modes": "^6.5.5", "@codemirror/merge": "6.12.3", "@codemirror/search": "^6.7.0", "@codemirror/state": "^6.4.1", diff --git a/web/index.html b/web/index.html index 9bf0f0c1..6d41d263 100644 --- a/web/index.html +++ b/web/index.html @@ -2,6 +2,7 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/web/src/components/CanvasView.tsx b/web/src/components/CanvasView.tsx index eadb806a..a7c1e96a 100644 --- a/web/src/components/CanvasView.tsx +++ b/web/src/components/CanvasView.tsx @@ -1149,7 +1149,7 @@ export default function CanvasView() { return; } const pad = 80; - const scale = Math.min(4, Math.max(0.1, Math.min((r.width - pad) / bb.width, (r.height - pad) / bb.height, 1.5))); + const scale = Math.max(0.1, Math.min((r.width - pad) / bb.width, (r.height - pad) / bb.height, 1)); const tx = r.width / 2 - (bb.x + bb.width / 2) * scale; const ty = r.height / 2 - (bb.y + bb.height / 2) * scale; setView({ tx, ty, scale }); @@ -1248,10 +1248,10 @@ export default function CanvasView() { })(); const onlyEdges = sel.edges.size > 0 && sel.nodes.size === 0; const selEdgeHasLabel = onlyEdges && data.edges.some((e) => sel.edges.has(e.id) && e.label); - // Text-card alignment state (only when ≥1 selected node is a text card). - const selTextNodes = data.nodes.filter((n) => sel.nodes.has(n.id) && n.type === 'text') as TextNode[]; - const selHasText = selTextNodes.length > 0; - const curAlign: TextAlign = selTextNodes[0]?.textAlign ?? 'left'; + // Native Edit action applies to a single selected text card. + const singleTextNode = sel.nodes.size === 1 && sel.edges.size === 0 + ? data.nodes.find((n) => sel.nodes.has(n.id) && n.type === 'text') + : undefined; // Current color of the selection (first selected node/edge) → highlight its swatch. const selColor: string | undefined = (() => { const n = data.nodes.find((x) => sel.nodes.has(x.id)); @@ -1440,7 +1440,7 @@ export default function CanvasView() {
beginNodeDrag(e, n.id)} onPointerEnter={() => setHoverNode(n.id)} onPointerLeave={() => setHoverNode((h) => (h === n.id ? null : h))} @@ -1481,7 +1481,7 @@ export default function CanvasView() { style={{ textAlign: (n as TextNode).textAlign ?? 'left' }} /> ) : ( -
+
{(n as TextNode).text.trim() ? : Empty card — double-click to edit}
) @@ -1528,22 +1528,12 @@ export default function CanvasView() { - {selHasText && ( - <> - - {(['left', 'center', 'right'] as const).map((a) => ( - - ))} - + {singleTextNode && ( + )} {onlyEdges && ( <> diff --git a/web/src/components/Editor.tsx b/web/src/components/Editor.tsx index 6c66970b..6374ac25 100644 --- a/web/src/components/Editor.tsx +++ b/web/src/components/Editor.tsx @@ -8,7 +8,7 @@ import { editorStructure, outlineMarkdown, persistentFolding } from '../lib/edit 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 {nativeFencedCodeLanguages,nativeFencedCodeHighlightStyle} from '../lib/nativeCodeLanguages'; import { syntaxHighlighting } from '@codemirror/language'; import { obsidianHighlightStyle, literalAngleColors } from '../lib/highlight'; import { useStore, documentSessions } from '../lib/store'; @@ -220,13 +220,14 @@ export default function Editor() { editorStructure, persistentFolding(documentScope,activePath??''), // GFM base so Strikethrough/Table/TaskList nodes exist (Obsidian dialect); - // codeLanguages lazy-loads grammars for fenced blocks (Obsidian: Prism). + // Fence grammars follow the native editor's tokenization and palette. // YAML front matter (--- … ---) is parsed as YAML; the rest stays Markdown. - yamlFrontmatter({ content: markdown({ base: markdownLanguage, codeLanguages: languages,extensions:[outlineMarkdown] }) }), + yamlFrontmatter({ content: markdown({ base: markdownLanguage, codeLanguages: nativeFencedCodeLanguages,extensions:[outlineMarkdown] }) }), suggesterPlugin, // Obsidian token palette via CSS vars (works in both themes); markdown // structure styling is owned by the Live Preview decorations. syntaxHighlighting(obsidianHighlightStyle), + syntaxHighlighting(nativeFencedCodeHighlightStyle), literalAngleColors, EditorView.lineWrapping, ...(isMd ? selectionToolbar : []), diff --git a/web/src/components/Icon.tsx b/web/src/components/Icon.tsx index bf994f72..ef2cb21e 100644 --- a/web/src/components/Icon.tsx +++ b/web/src/components/Icon.tsx @@ -33,6 +33,7 @@ const PATHS: Record = { 'arrow-left-right': '', minus: '', // Lucide text-alignment icons (Canvas text-card alignment). + 'zoom-to-selection': '', 'align-left': '', 'align-center': '', 'align-right': '', diff --git a/web/src/components/Preview.tsx b/web/src/components/Preview.tsx index 53953074..a4c96398 100644 --- a/web/src/components/Preview.tsx +++ b/web/src/components/Preview.tsx @@ -18,8 +18,8 @@ import {addNoteEmbedOpenButtons} from '../lib/noteEmbed'; import {useVaultPreferences} from '../lib/vaultPreferences'; import {findRenderedNoteFragment} from '../lib/noteFragments'; -/** Syntax-highlight a `` block with the SAME CodeMirror - * grammars Live Preview uses (token classes styled by the Obsidian palette). */ +/** Syntax-highlight static preview code with catalog grammars and the scoped + * token palette. The editor's native stream grammars are configured separately. */ async function highlightCodeEl(codeEl: HTMLElement): Promise { const cls = [...codeEl.classList].find((c) => c.startsWith('language-')); if (!cls) return; diff --git a/web/src/lib/nativeCodeLanguages.ts b/web/src/lib/nativeCodeLanguages.ts new file mode 100644 index 00000000..54e707aa --- /dev/null +++ b/web/src/lib/nativeCodeLanguages.ts @@ -0,0 +1,49 @@ +import {HighlightStyle,LanguageDescription,LanguageSupport,StreamLanguage,type StreamParser} from '@codemirror/language'; +import {languages} from '@codemirror/language-data'; +import {Tag} from '@lezer/highlight'; + +// Native Obsidian's editor uses the legacy stream grammars for these fences. +// Their token boundaries differ from modern Lezer (notably definitions, Python +// builtins/interpolation and YAML scalars). Keep their palette independent of +// Markdown, frontmatter and the standalone code-file viewer. +const roles={ + normal:'var(--text-normal)',comment:'var(--text-faint)',tag:'var(--color-red)', + number:'var(--color-purple)',string:'var(--color-green)',operator:'var(--color-red)', + variable:'var(--color-cyan)',builtin:'var(--color-yellow)',keyword:'var(--color-pink)', + error:'var(--text-error, var(--color-red))', +}; +type Role=keyof typeof roles; +const tags=Object.fromEntries(Object.keys(roles).map(role=>[role,Tag.define()])) as Record; +const tokens:Record={ + def:'normal',atom:'normal',comment:'comment',meta:'comment',tag:'tag', + number:'number',string:'string','string-2':'string','string.special':'string',qualifier:'string',operator:'operator', + variable:'variable','variable-2':'variable','variable-3':'variable','variableName.local':'variable',self:'variable',link:'variable', + builtin:'builtin',property:'builtin',attribute:'builtin',type:'builtin',keyword:'keyword',error:'error', +}; + +export const nativeFencedCodeHighlightStyle=HighlightStyle.define( + (Object.entries(roles) as [Role,string][]).map(([role,color])=>({tag:tags[role],color})), +); + +function nativeLanguage(parser:StreamParser):LanguageSupport{ + const tokenTable=Object.fromEntries(Object.entries(tags).map(([role,tag])=>['nativeCode'+role,tag])); + return new LanguageSupport(StreamLanguage.define({ + ...parser,tokenTable, + token(stream,state){ + const style=parser.token(stream,state); + return style?style.split(/\s+/).map(token=>'nativeCode'+(tokens[token]??'normal')).join(' '):null; + }, + })); +} + +const loadNative:RecordPromise)|undefined>={ + JavaScript:async()=>nativeLanguage((await import('@codemirror/legacy-modes/mode/javascript')).javascript), + Python:async()=>nativeLanguage((await import('@codemirror/legacy-modes/mode/python')).python), + YAML:async()=>nativeLanguage((await import('@codemirror/legacy-modes/mode/yaml')).yaml), +}; + +export const nativeFencedCodeLanguages=languages.map(description=>{ + const load=loadNative[description.name]; + return load?LanguageDescription.of({name:description.name,alias:description.alias, + extensions:description.extensions,filename:description.filename,load}):description; +}); diff --git a/web/src/styles/obsidian.css b/web/src/styles/obsidian.css index 7c421342..5f73008f 100644 --- a/web/src/styles/obsidian.css +++ b/web/src/styles/obsidian.css @@ -2135,6 +2135,7 @@ button.task-due:hover .task-due-caret { opacity: 1; } Canvas (FR-12) — JSON Canvas infinite board, parity with Obsidian Canvas ========================================================================== */ .canvas-view { + --canvas-node-border: #c0c0c0; flex: 1; position: relative; overflow: hidden; @@ -2148,6 +2149,7 @@ button.task-due:hover .task-due-caret { opacity: 1; } user-select: none; cursor: grab; } +.theme-dark .canvas-view { --canvas-node-border: #7e7e7e; } /* Fill the viewport (not 0×0): a zero-size transformed box makes mobile Safari clip scaled descendants that sit left/above the origin → nodes lost a left strip. */ .canvas-world { position: absolute; left: 0; top: 0; width: 100%; height: 100%; overflow: visible; transform-origin: 0 0; } @@ -2180,9 +2182,11 @@ button.task-due:hover .task-due-caret { opacity: 1; } outline-offset: 1px; z-index: 5; } +.canvas-node:not(.canvas-group) { border-color: var(--canvas-node-border); } +.canvas-node:not(.canvas-group).selected { border-color: var(--interactive-accent); } /* Colored node (Obsidian parity): even 2px colored border + light tinted fill. Scoped to non-group nodes so it doesn't override the group's own styling. */ -.canvas-node:not(.canvas-group)[style*="--c"] { +.canvas-node:not(.canvas-group)[style*="--c:"] { border-color: var(--c); border-width: 3px; background: color-mix(in srgb, var(--c) 10%, var(--background-primary)); @@ -2201,6 +2205,14 @@ button.task-due:hover .task-due-caret { opacity: 1; } } .canvas-text-body .markdown-preview, .canvas-file-body .markdown-preview { padding: 0; } .canvas-text-body .preview-inner, .canvas-file-body .preview-inner { padding: 0; max-width: none; } +/* Native Canvas reduces vertical whitespace for short cards. */ +.canvas-text-body { + min-height: 0; font-family: var(--font-text); font-size: var(--font-text-size); + padding: clamp(0px, calc(var(--canvas-node-height, 100px) * .1 - 3px), 16px) 16px; +} +.canvas-text-body > .markdown-preview { overflow: visible; } +.canvas-text-body .preview-inner > div > :first-child { margin-top: 0; } +.canvas-text-body .preview-inner > div > :last-child { margin-bottom: 0; } .canvas-placeholder { color: var(--text-faint); font-style: italic; } .canvas-text-edit { @@ -2212,9 +2224,9 @@ button.task-due:hover .task-due-caret { opacity: 1; } background: transparent; color: var(--text-normal); font-family: inherit; - font-size: 14px; + font-size: var(--font-text-size); line-height: 1.5; - padding: 8px 12px; + padding: clamp(0px, calc(var(--canvas-node-height, 100px) * .1 - 3px), 16px) 16px; box-sizing: border-box; } @@ -2413,13 +2425,13 @@ button.task-due:hover .task-due-caret { opacity: 1; } display: flex; flex-direction: column; align-items: center; gap: 4px; } .canvas-menu-row { - display: flex; align-items: center; gap: 2px; + display: flex; align-items: center; gap: 1px; background: var(--background-primary); border: 1px solid var(--background-modifier-border); - border-radius: var(--radius-m); box-shadow: 0 2px 10px rgba(0,0,0,.25); padding: 4px; + border-radius: var(--radius-s); box-shadow: 0 2px 10px rgba(0,0,0,.07); padding: 2px; } .canvas-menu-btn { display: flex; align-items: center; justify-content: center; - width: 30px; height: 30px; border: 0; border-radius: var(--radius-s); + width: 32px; height: 28px; padding: 6px 8px; border: 0; border-radius: var(--radius-s); background: transparent; color: var(--text-muted); cursor: pointer; } .canvas-menu-btn:hover { background: var(--background-modifier-border); color: var(--text-normal); } diff --git a/web/tests/canvasTextLayoutBrowser.test.ts b/web/tests/canvasTextLayoutBrowser.test.ts new file mode 100644 index 00000000..e3c0f585 --- /dev/null +++ b/web/tests/canvasTextLayoutBrowser.test.ts @@ -0,0 +1,107 @@ +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('Canvas compact text cards show both lines and long cards scroll inside their bounds', async () => { + const dir = await mkdtemp(join(tmpdir(), 'webo-canvas-text-')); + 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 CanvasView from './src/components/CanvasView'; +import {useStore} from './src/lib/store'; +import './src/styles/obsidian.css'; +const check = (ok, message) => { if (!ok) throw Error(message); }; +const wait = () => new Promise(resolve => setTimeout(resolve, 50)); +const nodes = [ + {id:'short',type:'text',x:0,y:0,width:250,height:60,text:'Загрузка сообщений проактива'}, + {id:'long',type:'text',x:400,y:0,width:300,height:100,text:Array(30).fill('Строка текста').join('\\n')}, + {id:'colored',type:'text',x:800,y:0,width:250,height:100,text:'Colored card',color:'4'}, +]; +const original = JSON.stringify({nodes, edges:[]}); +useStore.setState({activePath:'test.canvas',content:original,dirty:false}); +window.run = async () => { + document.body.classList.add('theme-dark'); + const host = document.createElement('div'); + host.style.cssText = 'width:1200px;height:800px'; + document.body.append(host); + const root = createRoot(host); + root.render(); + for (let i=0;i<100 && host.querySelectorAll('.canvas-text-body p').length<2;i++) await wait(); + await document.fonts.ready; + const bodies = [...host.querySelectorAll('.canvas-text-body')]; + const short = bodies[0], long = bodies[1]; + check(short && long, 'both cards rendered'); + check(getComputedStyle(short.closest('.canvas-node')).borderTopWidth === '1px', 'neutral cards keep the native thin border'); + check(getComputedStyle(bodies[2].closest('.canvas-node')).borderTopWidth === '3px', 'colored cards retain their colored border'); + check(host.querySelector('.canvas-zoom-pct').textContent === '100%', 'opening a small board preserves normal scale'); + const paragraph = short.querySelector('p'); + check(paragraph?.textContent.includes('проактива'), 'second line rendered'); + check(short.scrollHeight <= short.clientHeight + 1, + 'two-line card has unnecessary scrolling: '+JSON.stringify({height:short.clientHeight,scroll:short.scrollHeight})); + const bodyRect = short.getBoundingClientRect(), textRect = paragraph.getBoundingClientRect(); + check(textRect.top >= bodyRect.top && textRect.bottom <= bodyRect.bottom, 'both lines visible within card'); + check(long.scrollHeight > long.clientHeight, 'long card scrolls'); + long.scrollTop = 100; + check(long.scrollTop > 0, 'long card content remains reachable'); + check(useStore.getState().content === original && !useStore.getState().dirty, 'viewing preserves canvas bytes'); + const card = short.closest('.canvas-node'); + const point = card.getBoundingClientRect(); + card.dispatchEvent(new PointerEvent('pointerdown', {bubbles:true,button:0,pointerId:1,clientX:point.x+10,clientY:point.y+10})); + host.querySelector('.canvas-view').dispatchEvent(new PointerEvent('pointerup', {bubbles:true,button:0,pointerId:1,clientX:point.x+10,clientY:point.y+10})); + await wait(); + const menu = host.querySelector('.canvas-menu'); + check(menu?.querySelector('[title="Edit"]'), 'selection toolbar includes the native Edit action'); + check(JSON.stringify([...menu.querySelectorAll('.canvas-menu-row button')].map(button => button.title)) === + JSON.stringify(['Remove','Set color','Zoom to selection','Edit']), 'single text selection shows the four native actions'); + check(menu.querySelector('.canvas-menu-row').getBoundingClientRect().height === 34, 'native compact toolbar height'); + menu.querySelector('[title="Zoom to selection"]').click(); + await wait(); + check(short.scrollHeight <= short.clientHeight + 1, 'selection zoom leaves both text lines visible'); + host.querySelector('[title="Reset zoom (100%)"]').click(); + await wait(); + check(useStore.getState().content === original && !useStore.getState().dirty, 'zoom and reset preserve document bytes'); + check(short.scrollHeight <= short.clientHeight + 1, 'zoom leaves both text lines visible'); + menu.querySelector('[title="Edit"]').click(); + await wait(); + check(card.querySelector('textarea')?.value === nodes[0].text, 'Edit opens the selected text'); + root.unmount(); + return true; +};`, + }, + bundle: true, format: 'iife', platform: 'browser', + 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 w=new BrowserWindow({show:false,width:1440,height:1000,webPreferences:{backgroundThrottling:false}}); + await w.loadFile(${JSON.stringify(join(dir, 'index.html'))}); + const result=await w.webContents.executeJavaScript('window.run().catch(e=>({failure:e.stack}))'); + if(result?.failure)throw Error(result.failure); + console.log('CANVAS_TEXT_LAYOUT_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, /CANVAS_TEXT_LAYOUT_PASS/); + } finally { + assert.ok(dir.startsWith(join(tmpdir(), 'webo-canvas-text-'))); + await rm(dir, {recursive:true, force:true}); + } +}); diff --git a/web/tests/nativeCodeColorsBrowser.test.ts b/web/tests/nativeCodeColorsBrowser.test.ts new file mode 100644 index 00000000..530bd719 --- /dev/null +++ b/web/tests/nativeCodeColorsBrowser.test.ts @@ -0,0 +1,61 @@ +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'; + +const samples=[ + {lang:'js',code:['function calculateVelocity(distance, time) {',' if (time <= 0) throw new Error("Time must be positive");',' const velocity = distance / time;',' console.log(`Speed: ${velocity} m/s`);',' return velocity;','}'],tokens:[ + [0,'function','pink'],[0,'calculateVelocity','normal'],[0,'distance','normal'],[0,'time','normal'], + [1,'time','cyan'],[1,'0','purple'],[1,'Error','cyan'],[1,'Time must be positive','green'], + [2,'velocity','normal'],[2,'distance','cyan'],[2,'/','red'],[3,'console','cyan'],[3,'log','yellow'],[3,'velocity','cyan'],[3,'${','green'],[4,'velocity','cyan'], + ]}, + {lang:'python',code:['class Node:',' def __init__(self, key: str, value: int):',' self.key = key',' self.value = value',' def __repr__(self) -> str:',' return f"Node({self.key!r}, {self.value})"'],tokens:[ + [0,'class','pink'],[0,'Node','normal'],[1,'__init__','normal'],[1,'self','cyan'],[1,'key','cyan'],[1,'str','yellow'],[1,'int','yellow'],[2,'self','cyan'],[2,'key','yellow'],[3,'value','yellow'],[4,'__repr__','normal'],[4,'->','red'],[4,'str','yellow'],[5,'return','pink'],[5,'Node(','green'],[5,'{','normal'],[5,'self','cyan'],[5,'key','yellow'],[5,'!','red'],[5,'!r','cyan',1], + ]}, + {lang:'yml',code:['# YAML','server:',' host: 127.0.0.1',' port: 8080',' ssl:',' enabled: true'],tokens:[ + [0,'# YAML','faint'],[1,'server','normal'],[1,':','faint'],[2,'host','normal'],[2,'127.0.0.1','purple'],[3,'8080','purple'],[4,'ssl','normal'],[5,'enabled','normal'],[5,'true','pink'], + ]}, +]; + +test('fenced JS, Python and YAML tokens match native editor colors in both themes',async()=>{ + const dir=await mkdtemp(join(tmpdir(),'webo-native-code-colors-')); + 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} from './src/lib/store'; + import {api} from './src/lib/api';import {getActiveEditor} from './src/lib/activeEditor'; + import {forceParsing} from '@codemirror/language';import './src/styles/obsidian.css'; + api.tags=async()=>({tags:[]});api.propertyTypes=async()=>({types:{}}); + const samples=${JSON.stringify(samples)},root=createRoot(document.querySelector('#root')),wait=()=>new Promise(r=>setTimeout(r,80)),issues=[]; + const expected=role=>{const el=document.createElement('span');el.style.color=role==='normal'?'var(--text-normal)':role==='faint'?'var(--text-faint)':'var(--color-'+role+')';document.body.append(el);const value=getComputedStyle(el).color;el.remove();return value}; + let mounted=0;window.run=async()=>{ + for(const mode of ['live','reading','source'])for(const theme of ['theme-dark','theme-light'])for(const sample of samples){ + document.body.className=theme;const nl=String.fromCharCode(10),fence=String.fromCharCode(96).repeat(3),prefix='# Host'+nl+nl+fence+sample.lang+nl; + const source=prefix+sample.code.join(nl)+nl+fence+nl+nl+'Outside text'; + useStore.setState({activePath:'Colors.md',content:source,viewMode:mode,dirty:false,locked:false,showInlineTitle:false,save:async()=>{}});root.render();await wait();await wait(); + const view=getActiveEditor();forceParsing(view,source.length,1000);await wait();await document.fonts.ready; + for(const [line,word,role,offset] of sample.tokens){ + const at=prefix.length+sample.code.slice(0,line).reduce((n,s)=>n+s.length+1,0)+sample.code[line].indexOf(word)+(offset??Math.floor(word.length/2)); + const {node}=view.domAtPos(at),el=node.nodeType===Node.TEXT_NODE?node.parentElement:node; + const color=getComputedStyle(el).color,want=expected(role); + if(color!==want)issues.push(mode+'/'+theme+'/'+sample.lang+' line '+line+' '+word+': '+color+' expected '+role+' '+want); + } + const at=source.indexOf('Outside text')+2,{node}=view.domAtPos(at),el=node.nodeType===Node.TEXT_NODE?node.parentElement:node; + if(getComputedStyle(el).color!==expected('normal'))issues.push('Code palette leaks into ordinary text'); + if(view.state.doc.toString()!==source||useStore.getState().content!==source)issues.push('Source changed'); + } + root.unmount();if(issues.length)throw Error(JSON.stringify(issues));return 'NATIVE_CODE_COLORS_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:1000,height:1100,webPreferences:{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:1100,deviceScaleFactor:1,mobile:false});console.log(await win.webContents.executeJavaScript('window.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:45_000});assert.match(stdout,/NATIVE_CODE_COLORS_PASS/); + }finally{assert.ok(dir.startsWith(join(tmpdir(),'webo-native-code-colors-')));await rm(dir,{recursive:true,force:true})} +}); From 30e0411d88d811fb7165d3c727b95b2819319611 Mon Sep 17 00:00:00 2001 From: macros0 Date: Mon, 2 Nov 2026 19:47:11 +0300 Subject: [PATCH 2/2] test: wait for stable toolbar overflow before opening menu --- IMPLEMENTATION_PLAN.md | 6 ++++++ web/tests/toolbarViewportBrowser.test.ts | 12 +++++++++++- 2 files changed, 17 insertions(+), 1 deletion(-) diff --git a/IMPLEMENTATION_PLAN.md b/IMPLEMENTATION_PLAN.md index c3decf7e..5d28e16d 100644 --- a/IMPLEMENTATION_PLAN.md +++ b/IMPLEMENTATION_PLAN.md @@ -1,5 +1,11 @@ # IMPLEMENTATION PLAN — WebObsidian +## PR #16 hosted CI — 2026-11-02 + +- [x] Stabilize the toolbar viewport fixture after resize before opening its overflow menu. Preserve all zoom, mobile keyboard, selection and bounds assertions. The viewport, overflow and navigation browser tests pass locally. + +Nhật ký tiến độ — 2026-11-02. Hosted CI passed dependency audit and Docker build. Its web suite passed 519/520 tests, with the viewport fixture clicking More during the asynchronous overflow update at a 960×600 CSS viewport. Require stable measured geometry and command inventory before the click. + ## Native code colors, Canvas and favicon fork PR — 2026-11-02 Cập nhật lần cuối: 2026-11-02. diff --git a/web/tests/toolbarViewportBrowser.test.ts b/web/tests/toolbarViewportBrowser.test.ts index cc48391a..18077c0b 100644 --- a/web/tests/toolbarViewportBrowser.test.ts +++ b/web/tests/toolbarViewportBrowser.test.ts @@ -34,7 +34,17 @@ test('browser zoom and keyboard viewport keep toolbar, draft status, menus and p window.checkDesktop=async(sidebar=220)=>{ document.querySelector('#pane').style.width='calc(100vw - '+(sidebar+12)+'px)';document.querySelector('#pane').style.marginLeft=sidebar+'px'; const bar=document.querySelector('.format-toolbar > .toolbar-surface'); - await settle(()=>Array.from(bar.children).filter(n=>!n.classList.contains('toolbar-measure')).every(n=>n.getBoundingClientRect().right<=bar.getBoundingClientRect().right+1)); + await document.fonts.ready; + // ResizeObserver can replace the overflow contents even while both the old + // and new rows fit. Wait for stable geometry and commands before opening More. + let previousLayout,stableSamples=0; + await settle(()=>{ + const children=Array.from(bar.children).filter(n=>!n.classList.contains('toolbar-measure')); + const bounds=bar.getBoundingClientRect(); + const layout=JSON.stringify([bounds.toJSON(),children.map(n=>[n.getAttribute('aria-label'),n.getBoundingClientRect().toJSON()])]); + stableSamples=layout===previousLayout?stableSamples+1:0;previousLayout=layout; + return stableSamples>=2&&children.every(n=>n.getBoundingClientRect().right<=bounds.right+1); + }); check(inside(bar),'desktop toolbar bounds '+JSON.stringify({sidebar,viewport:[innerWidth,innerHeight],visual:{width:visualViewport.width,height:visualViewport.height},rect:bar.getBoundingClientRect().toJSON()})); const more=bar.querySelector('[aria-label="More"]');if(more){more.click();await settle(()=>!!document.querySelector('[role="menu"]'));check(inside(document.querySelector('[role="menu"]')),'zoom menu bounds');document.dispatchEvent(new KeyboardEvent('keydown',{key:'Escape',bubbles:true}));} check(view.state.selection.main.to===5,'zoom keeps selection');