diff --git a/.agents/notes/implemented/architecture/2026-11-14-web-view-previews.md b/.agents/notes/implemented/architecture/2026-11-14-web-view-previews.md index 6b8da822b5..c5044e6b3f 100644 --- a/.agents/notes/implemented/architecture/2026-11-14-web-view-previews.md +++ b/.agents/notes/implemented/architecture/2026-11-14-web-view-previews.md @@ -1,13 +1,15 @@ -# Agent 笔记:编辑区的 web view 预览(Markdown、图片、SVG、PDF) +# Agent 笔记:编辑区的 web view 预览(Markdown、图片、SVG、PDF、HTML) 状态:已实现 ## 先说结论 Viva 桌面端在系统有 web 引擎时(macOS 的 WKWebView、Windows 的 WebView2),Markdown 预览、图片查看器、 -SVG 图片和 PDF 都显示在编辑区内嵌的 web view(网页视图)里。页面和它用到的脚本、字体全部编进应用二进制, +SVG 图片、PDF 和 HTML 文件都显示在编辑区内嵌的 web view(网页视图)里。页面和它用到的脚本、字体全部编进应用二进制, 经应用自己的 `lithe-preview` 协议提供,不访问网络。页面能读到用户的哪个文件由宿主决定:Markdown 的链接和图片 -按 Core 的 `markdown.resolveReference` 解析,查看器只能读它显示的那一个文件或缓冲区。Linux 没有 web 引擎, +按 Core 的 `markdown.resolveReference` 解析,查看器只能读它显示的那一个文件或缓冲区。HTML 文件是例外: +它运行用户自己的脚本,所以走单独的 `lithe-site` 协议和临时(ephemeral,什么都不落盘)存储,能读哪些文件由 +Core 的 `htmlPreview.resolveRequest` 逐个请求决定。Linux 没有 web 引擎, 继续使用 Viva 原生的 Markdown 渲染和 Go 自绘的图片画布,两边遵循同一套图片查看规则。 ## 问题 @@ -40,6 +42,23 @@ SVG 只能当文本看,PDF 只能交给外部应用。 - **SVG 跟随编辑**。SVG 文件按 Markdown 的方式打开:源码与图片两栏,标签栏末尾切换源码 / 两者 / 仅图片。 编辑后最多每 150 毫秒把文本交给页面一次,地址带上编辑版本号,避免引擎画出缓存的旧图;更新时保持用户的 缩放和滚动位置。改成画不出来的内容时保留上一张图,只有从未画成功过才显示失败提示。超过 4 MiB 不绘制。 +- **HTML 文件按静态网站预览**(`webpreview/site.go`、`workbench/html_preview.go`)。HTML 文件和 SVG 一样 + 两栏打开,标签栏末尾切换源码 / 两者 / 仅预览。规则如下: + - 站点根目录由 Core 的 `htmlPreview.site` 决定:文件在工作区里时是工作区,否则是文件所在目录。页面地址是 + `lithe-site://site/<相对路径>`,所以相对路径、模块脚本、`fetch` 都像在本地 Web 服务器上一样同源工作。 + - 每个请求都问 Core 的 `htmlPreview.resolveRequest`:文件本身用编辑器当前文本回答(未保存的修改也能看到), + 其他文件按 Core 给的规范路径和内容类型读出;以 `.` 开头的路径分量(`.env`、`.git`)和私钥扩展名返回 403, + 目录返回一个跳到 `index.html` 的小页面。单个文件最大 64 MiB,编辑器文本超过 8 MiB 时不预览。 + 所有回答都去掉 `Access-Control-Allow-Origin` 默认值,所以页面里嵌入的远程 iframe 读不到工作区文件。 + - 编辑后最多每 150 毫秒交一次文本。主框架正显示这个文件、没在加载、又拿到过旧文本时,宿主执行一段重新加载脚本: + 先让页面报出滚动位置,加载完成后滚回原处。判断不依赖“开始加载”事件,因为 Windows 不报告它。 + - 主框架只留在站点内。用户点到站外的链接交给 Core 的链接解析(`followDocumentLink`),网页和邮件地址用系统 + 应用打开;脚本发起的站外跳转直接取消。页面打开的窗口在站内时替换当前页,站外时交给系统浏览器,每秒最多一次, + 因为 Windows 不告诉宿主这个窗口是不是用户点出来的。iframe 可以加载网页、`data:` 和 `blob:`。 + - 页面不是我们的页面:它从不进入“就绪”状态,宿主不给它发主题等任何消息;它发来的消息只接受重新加载脚本报的 + 滚动位置。工具栏只有后退、前进、重新加载和“在浏览器中打开”。 + - 站点页打不开(例如 WebView2 太旧,不支持临时存储)时只关掉 HTML 预览,HTML 文件从此只显示源码, + Markdown、图片等其他预览不受影响。 - **Markdown 目录画在页面里**。web 页的目录是页面右侧的大纲栏(`assets/markdown.js`):页面从渲染结果的 标题建树,按层级缩进,可以折叠,当前章节随页面滚动高亮,选中标题时像用户滚动页面一样回报 `scrolled`, 宿主照常把源码带到那一行。标签栏的“目录”按钮只发 `outline{open}` 打开或关闭;用户在页面里按 Escape 关闭时, @@ -55,7 +74,9 @@ SVG 只能当文本看,PDF 只能交给外部应用。 切回来时原样显示。隐藏的页面最多保留 6 个,超出时关闭隐藏最久的那个,标签再次显示时重新打开。 窗口的 web host 还没准备好、系统没有 web 引擎、或者某个页面打开失败后,编辑区改用原生预览。 - **不写发行目录**。页面从二进制读取;回答用户文件时带 `Cache-Control: no-store`。页面不使用临时 - (ephemeral)配置,因为 WebView2 的每个临时页面都会留下一份配置目录。WebView2 的配置目录由 Viva 放在 + (ephemeral)配置,因为 WebView2 的每个临时页面都会留下一份配置目录。HTML 站点页是唯一的例外:它运行 + 用户的脚本,Cookie、本地存储、缓存和 Service Worker 必须和我们自己的页面、和下一个站点分开,并随页面关闭消失, + 所以它是临时页面,代价是 Windows 上每打开一次留下一份配置目录(同样在用户缓存目录里)。WebView2 的配置目录由 Viva 放在 用户缓存目录(`%LOCALAPPDATA%\<应用>\WebView2`),WKWebView 的数据在用户的 `~/Library`,都不在 app bundle 或安装目录里,不影响代码签名和 Sparkle 增量更新。 @@ -80,6 +101,13 @@ SVG 只能当文本看,PDF 只能交给外部应用。 所以改为页面自己画,宿主只发开关。 - **目录始终浮在正文上方**:宽预览里会挡住正文右侧;有背景图时页面底色透明,浮层下的文字会和目录叠在一起。 拒绝,改为宽预览让出位置、窄预览才浮起并用不透明的弹层底色。 +- **HTML 文件也用 `lithe-preview` 协议**:用户脚本会和我们的页面同源,能读写它们的存储、调用它们的路由,拒绝。 + 单独的 `lithe-site` 协议让两者在浏览器眼里是不同的源。 +- **HTML 站点页使用持久存储**:用户脚本写下的 Cookie 和本地存储会在不同站点、不同次打开之间共享并留在磁盘上, + 拒绝。 +- **在本机起一个 HTTP 服务器提供站点**:本机任何进程都能按端口读到工作区文件,还要处理端口占用,拒绝。 +- **像旧 macOS 预览那样让主框架跳到远程网页**:Viva 的预览没有地址栏,远程页面在主框架里还会拿到页面桥接, + 暂不做;完整浏览器以后作为插件交付。 - **隐藏的页面立即关闭,或者全部常驻**:立即关闭会在每次切标签时丢掉滚动位置并重新排版;全部常驻会让每个 打开过的预览都占一个 web 进程的内存。折中为最多保留 6 个隐藏页面。 @@ -98,6 +126,11 @@ SVG 和 PDF 可以在编辑区直接查看;页面能读到什么完全由宿 - Markdown 目录有两种外观:web 页是可折叠、跟随当前章节的大纲,Linux 原生页是按级别缩进的弹出列表。 标题树和折叠只存在于页面脚本,属于视图呈现,不进 Core;两边的标题都来自同一份渲染结果或源码标题。 - Linux 仍然看不到 HTML 和富内容,SVG 只能看源码,PDF 只能交给外部应用。 +- HTML 预览比旧 macOS 的内嵌浏览器小:没有地址栏、页面缩放、页内查找、开发者工具、JavaScript 对话框、 + 下载、打印和 `Range` 请求(音视频不能拖动进度);后退和前进按钮一直可点,因为 Viva 不报告能否后退。 + 这些需要时在 Viva fork 里补接口再接入,不在应用层绕过。 +- Windows 上的站点地址是 `https://lithe-site.viva-app.invalid/site/...`,Viva 把路径第一段当作主机名去掉, + 所以页面里以 `/` 开头的绝对路径(`/css/a.css`)在 Windows 上找不到文件,macOS 正常;需要在 Viva fork 修复。 - Windows 上 WebView2 能否解码 TIFF、HEIC,以及自定义协议下的 PDF 查看器是否可用,还没有真机验证; 解码失败时会落到“无法显示”和“用外部应用打开”。 @@ -106,7 +139,10 @@ SVG 和 PDF 可以在编辑区直接查看;页面能读到什么完全由宿 - `scripts/desktop/desktop-go.sh test ./internal/webpreview ./internal/workbench -count=1`:覆盖页面只回答 干净路径和内嵌文件、跳转拦截、图片只按 Core 解析结果提供、远程图片共享下载与失败重试、Markdown 页随编辑 渲染与双向滚动、隐藏页面上限、web view 打不开时回落原生、图片查看器的工具栏与缩放、PDF 查看器、 - SVG 跟随编辑与失败保留,以及没有 web 引擎时的 Go 画布。 + SVG 跟随编辑与失败保留,以及没有 web 引擎时的 Go 画布。HTML 预览由 `TestSite*`(请求按 Core 回答、 + 主框架留在站内、窗口节流、编辑后重新加载并滚回原处、只接受滚动位置消息)、 + `TestHTMLPreviewSharedFixture`(Core 命令按共享 fixture `editor/html-preview-v1.json` 回答)和 `TestHTMLFile*`(两栏、跟随编辑、工具栏、站外链接、 + 打不开时只关 HTML 预览)覆盖。 - `scripts/desktop/verify/verify-runtime-bundle-immutability.sh`:确认打开预览不会改写发行目录。 - `TestMarkdownWebPageRendersCoreHTMLAndScrollsWithTheSource` 覆盖目录按钮与页面之间的 `outline` 消息, `TestMarkdownContentsIndentsHeadingsByLevel` 覆盖原生弹出列表按级别缩进且行不重叠, @@ -124,4 +160,6 @@ SVG 和 PDF 可以在编辑区直接查看;页面能读到什么完全由宿 - `desktop/internal/workbench/viewer_web.go` - `desktop/internal/workbench/viewer_image.go` - `desktop/internal/workbench/svg_preview.go` +- `desktop/internal/workbench/html_preview.go` - `desktop/internal/core/markdown.go` +- `desktop/internal/core/html_preview.go` diff --git a/.agents/notes/implemented/feature/2026-10-22-html-preview-embedded-browser.md b/.agents/notes/implemented/feature/2026-10-22-html-preview-embedded-browser.md index 21ba2bc3fd..6e7799a0d7 100644 --- a/.agents/notes/implemented/feature/2026-10-22-html-preview-embedded-browser.md +++ b/.agents/notes/implemented/feature/2026-10-22-html-preview-embedded-browser.md @@ -2,7 +2,7 @@ 状态:已实现 -> Viva 迁移状态(2026-11-08):本文记录旧 macOS 客户端的 HTML 预览与安全约束。Viva 目前只有文本编辑器,尚未接入 HTML 预览;下列功能和旧 WebKit 测试不能当作 Viva 已完成或已验证,迁移时仍需逐项满足安全与交互要求。 +> Viva 迁移状态(2026-11-14):本文记录旧 macOS 客户端的 HTML 预览与安全约束。Viva 桌面端已经有 HTML 预览(`lithe-site` 协议上的静态站点、Core 决定每个请求、访问规则沿用本文的隐藏文件与私钥拒绝),决策见 [编辑区的 web view 预览](../architecture/2026-11-14-web-view-previews.md);但它比本文的浏览器小:没有地址栏、缩放、页内查找、开发者工具、JavaScript 对话框、下载、打印,主框架不跳到远程网页。下列这些功能和旧 WebKit 测试不能当作 Viva 已完成或已验证。 ## 先说结论 diff --git a/desktop/internal/core/html_preview.go b/desktop/internal/core/html_preview.go new file mode 100644 index 0000000000..ba985d5fad --- /dev/null +++ b/desktop/internal/core/html_preview.go @@ -0,0 +1,50 @@ +package core + +import "context" + +// HTMLPreviewSite is where the static site an HTML file is previewed as lies: Root is the folder +// the page may load from, Address the file's path from it as a relative URL, its segments +// percent-encoded, and MIME the content type the file is served as. +type HTMLPreviewSite struct { + Root string `json:"root"` + Address string `json:"address"` + MIME string `json:"mime"` +} + +// HTMLPreviewSite asks Core for the site of the HTML file at documentPath: the workspace when the +// file lies in workspaceRoot, which may be empty, and the file's folder otherwise. +func (c *Client) HTMLPreviewSite(ctx context.Context, documentPath, workspaceRoot string) (HTMLPreviewSite, error) { + var response HTMLPreviewSite + err := c.Execute(ctx, "htmlPreview.site", htmlPreviewDocument{documentPath, workspaceRoot}, &response) + return response, err +} + +// HTMLPreviewResource is what one request of an HTML file's site serves. Kind is "document", the +// file itself, served from the editor's text; "file" with the canonical Path to read without +// following another link and the MIME to serve it as; "directory", a folder whose index.html the +// page goes on to; "denied", a hidden file or a key the site refuses (HTTP 403); or "none", which +// is not served (HTTP 404). +type HTMLPreviewResource struct { + Kind string `json:"kind"` + Path string `json:"path,omitempty"` + MIME string `json:"mime,omitempty"` +} + +// ResolveHTMLPreviewRequest asks Core what the request for path, from the root of the site of the +// HTML file at documentPath, serves. path is as the web engine reports it: percent-decoded, +// without a query, and empty for the root. The answer is checked on the file system, so it runs +// off the window thread. +func (c *Client) ResolveHTMLPreviewRequest(ctx context.Context, documentPath, workspaceRoot, path string) (HTMLPreviewResource, error) { + var response HTMLPreviewResource + err := c.Execute(ctx, "htmlPreview.resolveRequest", struct { + htmlPreviewDocument + Path string `json:"path"` + }{htmlPreviewDocument{documentPath, workspaceRoot}, path}, &response) + return response, err +} + +// htmlPreviewDocument names the HTML file a preview command is about. +type htmlPreviewDocument struct { + DocumentPath string `json:"documentPath"` + WorkspaceRoot string `json:"workspaceRoot,omitempty"` +} diff --git a/desktop/internal/core/html_preview_test.go b/desktop/internal/core/html_preview_test.go new file mode 100644 index 0000000000..52f882ec8d --- /dev/null +++ b/desktop/internal/core/html_preview_test.go @@ -0,0 +1,93 @@ +package core + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/1lck/Lithe-IDEA/desktop/internal/contractfixture" +) + +// TestHTMLPreviewSharedFixture: Core names the site of an HTML file and answers the site's +// requests as the shared fixture describes, for a page in the workspace, in a hidden folder and +// outside the workspace. +func TestHTMLPreviewSharedFixture(t *testing.T) { + data, err := os.ReadFile(contractfixture.CoreFixture("editor/html-preview-v1.json")) + if err != nil { + t.Fatal(err) + } + var fixture struct { + Files []string + Cases []struct { + Name string + Document string + InWorkspace bool + Site struct{ Root, Address, MIME string } + Requests []struct{ Path, Kind, File, MIME string } + } + InvalidDocuments []string + } + if err := json.Unmarshal(data, &fixture); err != nil { + t.Fatal(err) + } + if len(fixture.Cases) == 0 { + t.Fatal("the fixture has no cases") + } + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + under := func(relative string) string { return filepath.Join(root, filepath.FromSlash(relative)) } + for _, entry := range fixture.Files { + path := under(entry) + if strings.HasSuffix(entry, "/") { + if err := os.MkdirAll(path, 0o700); err != nil { + t.Fatal(err) + } + continue + } + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + } + + client := NewClient() + for _, c := range fixture.Cases { + t.Run(c.Name, func(t *testing.T) { + document, workspace := under(c.Document), "" + if c.InWorkspace { + workspace = root + } + site, err := client.HTMLPreviewSite(testContext(t), document, workspace) + if err != nil { + t.Fatal(err) + } + if want := (HTMLPreviewSite{Root: under(c.Site.Root), Address: c.Site.Address, MIME: c.Site.MIME}); site != want { + t.Fatalf("the site is %+v, want %+v", site, want) + } + for _, request := range c.Requests { + got, err := client.ResolveHTMLPreviewRequest(testContext(t), document, workspace, request.Path) + if err != nil { + t.Fatal(err) + } + want := HTMLPreviewResource{Kind: request.Kind} + if request.File != "" { + want.Path, want.MIME = under(request.File), request.MIME + } + if got != want { + t.Errorf("%q is %+v, want %+v", request.Path, got, want) + } + } + }) + } + for _, document := range fixture.InvalidDocuments { + if _, err := client.HTMLPreviewSite(testContext(t), document, ""); err == nil { + t.Errorf("%q was given a site", document) + } + } +} diff --git a/desktop/internal/i18n/shared.generated.go b/desktop/internal/i18n/shared.generated.go index 354cb731a9..8bd5ce68ad 100644 --- a/desktop/internal/i18n/shared.generated.go +++ b/desktop/internal/i18n/shared.generated.go @@ -713,6 +713,11 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.history.restore": "Restore", "desktop.history.show": "Show Local History", "desktop.history.title": "Local History", + "desktop.htmlPreview.back": "Back", + "desktop.htmlPreview.failed": "This HTML file can't be previewed.", + "desktop.htmlPreview.forward": "Forward", + "desktop.htmlPreview.reload": "Reload", + "desktop.htmlPreview.tooLarge": "This HTML file is too large to preview.", "desktop.ideApi.allowConfigure": "Allow configuration", "desktop.ideApi.allowConfigureHelp": "Lets the client change the project's build options.", "desktop.ideApi.allowExecute": "Allow execution", @@ -3214,6 +3219,11 @@ var sharedCatalogs = map[string]map[string]string{ "desktop.history.restore": "恢复", "desktop.history.show": "显示本地历史", "desktop.history.title": "本地历史", + "desktop.htmlPreview.back": "后退", + "desktop.htmlPreview.failed": "无法预览此 HTML 文件。", + "desktop.htmlPreview.forward": "前进", + "desktop.htmlPreview.reload": "重新加载", + "desktop.htmlPreview.tooLarge": "此 HTML 文件过大,无法预览。", "desktop.ideApi.allowConfigure": "允许配置", "desktop.ideApi.allowConfigureHelp": "允许客户端修改项目的构建选项。", "desktop.ideApi.allowExecute": "允许执行", diff --git a/desktop/internal/webpreview/site.go b/desktop/internal/webpreview/site.go new file mode 100644 index 0000000000..f281751160 --- /dev/null +++ b/desktop/internal/webpreview/site.go @@ -0,0 +1,258 @@ +package webpreview + +import ( + "context" + "encoding/json" + "net/url" + "strconv" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/vivaui/viva/app" +) + +// The site page shows an HTML file as the web engine draws it, with what it loads from its site: +// the folder Core names for the file (htmlPreview.site), the workspace when the file lies in one. +// Core decides each request of the page (htmlPreview.resolveRequest): the file itself, served +// from the editor's text so that unsaved edits show, a file of the site, a folder's index.html, +// or a refusal of a hidden file or a key. The page is the user's, not one of ours: its scripts +// run, it is sent none of the host's messages, and of what it posts the host takes only the +// scroll position its own reload script reports. +// +// The site has a scheme of its own, lithe-site, and the page is ephemeral: what it keeps (cookies, +// storage, caches, service workers) stays in memory, apart from the other previews and from the +// next site, and goes when the page closes. A platform without such a store refuses the page. +// +// The main frame stays on the site. A link the user follows elsewhere goes to Follow; a window the +// page opens loads in place of the page when it is on the site, and otherwise goes to Follow at +// most once per popupInterval, since Windows does not say whether the user asked for it. Frames +// may also load web pages and data and blob addresses. +// +// Each text SetDocument gives is shown at once when the main frame shows the file: the page +// loads again and is scrolled back where it was. + +const ( + // SiteScheme is the scheme the site page is served from. + SiteScheme = "lithe-site" + // SiteOrigin is the root of the site; Windows serves it as + // https://lithe-site.viva-app.invalid/site/, and reports navigations in this form. + SiteOrigin = SiteScheme + "://site/" + // SitePage is an HTML file with its site. + SitePage = "site" + + // siteFileBytes bounds one file of the site; a larger one is answered 413. + siteFileBytes = 64 << 20 + // popupInterval is the least time between two windows handed to Follow. + popupInterval = time.Second +) + +// directoryPage sends the browser on to the index.html of the folder it was served for. The +// engine does not say whether the address ended in a slash, so the page adds one when it did not. +var directoryPage = []byte(``) + +// reloadScript loads the page again, first posting where it is scrolled so that the host scrolls +// it back once it has loaded. It turns the engine's own restoring off: it comes late and would +// undo the host's. +const reloadScript = `(function(){try{history.scrollRestoration='manual'}catch(e){}try{window.viva.postMessage(JSON.stringify({type:'position',x:scrollX,y:scrollY}))}catch(e){}location.reload()})()` + +// siteState is what the site page follows of its main frame. +type siteState struct { + // shown is the decoded path, from the root, of the site page the main frame shows, and onSite + // says the main frame shows one. loading says a page committed and has not finished loading. + shown string + onSite bool + loading bool + // version counts the texts SetDocument gave and served is the one the file was last served. + version, served int + // reloading says the host reloaded the page and it has not finished loading again; scroll is + // where it was scrolled, for the page at scrollPath, once it said so. + reloading bool + scroll *sitePosition + scrollPath string + // popup is when a window was last handed to Follow. + popup time.Time +} + +// sitePosition is where the page was scrolled, in CSS pixels. +type sitePosition struct{ x, y float64 } + +// sitePath is the decoded path, from the root, that an address of the site names, without its +// query or fragment. ok is false for an address off the site. +func sitePath(address string) (string, bool) { + rest, ok := strings.CutPrefix(address, SiteOrigin) + if !ok { + return "", false + } + rest, _, _ = strings.Cut(rest, "#") + rest, _, _ = strings.Cut(rest, "?") + decoded, err := url.PathUnescape(rest) + if err != nil { + return "", false + } + return decoded, true +} + +// documentPath is the decoded path of the file from the root. +func (p *Page) documentPath() string { + decoded, _ := sitePath(SiteOrigin + p.config.Address) + return decoded +} + +// serveSite answers one request of the site page. The file asked for by its own path is served +// at once, from the text SetDocument gave last; every other request is put to Core on its own +// goroutine. +func (p *Page) serveSite(request app.WebRequest, respond func(app.WebResponse)) { + route := strings.TrimPrefix(request.Path, "/") + if route == p.documentPath() && p.document != nil { + p.site.served = p.site.version + respond(private(p.documentMIME, p.document)) + return + } + resolve := p.config.Request + if resolve == nil { + respond(notFound()) + return + } + document, mime := p.document, p.documentMIME + go func() { + ctx, cancel := context.WithTimeout(p.ctx, resolveTimeout) + resource, err := resolve(ctx, route) + cancel() + if err != nil { + if p.ctx.Err() == nil { + p.log("request", err) + } + respond(notFound()) + return + } + respond(p.siteResponse(resource, document, mime)) + }() +} + +// siteResponse is the answer to a request Core resolved to resource; document is the file's text +// when the request was made. +func (p *Page) siteResponse(resource core.HTMLPreviewResource, document []byte, mime string) app.WebResponse { + switch resource.Kind { + case "document": + if document == nil { + return notFound() + } + return private(mime, document) + case "file": + data, err := readFile(resource.Path, siteFileBytes, false) + if err != nil { + return failed(err) + } + return private(resource.MIME, data) + case "directory": + return private("text/html; charset=utf-8", directoryPage) + case "denied": + return app.WebResponse{Status: 403, Data: []byte("forbidden")} + } + return notFound() +} + +// navigateSite keeps the main frame on the site: a navigation elsewhere the user started goes to +// Follow and the frame stays where it is. A frame may also load a web page, a data or a blob +// address. +func (p *Page) navigateSite(navigation app.WebNavigation) bool { + if navigation.URL == "about:blank" || navigation.URL == "about:srcdoc" { + return true + } + if _, ok := sitePath(navigation.URL); ok { + return true + } + if !navigation.MainFrame { + scheme, _, _ := strings.Cut(navigation.URL, ":") + switch strings.ToLower(scheme) { + case "http", "https", "data", "blob": + return true + } + return false + } + if navigation.UserGesture && p.config.Follow != nil { + p.config.Follow(navigation.URL) + } + return false +} + +// newWindow loads a window the page opens on the site in place of the page, and hands one +// elsewhere to Follow, at most once per popupInterval. The engine opens no window. +func (p *Page) newWindow(address string) bool { + if _, ok := sitePath(address); ok { + if p.view != nil { + p.view.Load(address) + } + return false + } + if address == "" || strings.HasPrefix(address, "about:") || p.config.Follow == nil { + return false + } + now := p.clock() + if !p.site.popup.IsZero() && now.Sub(p.site.popup) < popupInterval { + return false + } + p.site.popup = now + p.config.Follow(address) + return false +} + +// siteLoaded follows the main frame: which page it shows and whether it is loading. A page the +// host reloaded is scrolled back once it has loaded, and a page of the file that was served an +// older text than the last one loads again. +func (p *Page) siteLoaded(load app.WebLoad) { + s := &p.site + switch load.Phase { + case app.WebLoadCommitted: + s.shown, s.onSite = sitePath(load.URL) + s.loading = true + case app.WebLoadFinished: + s.shown, s.onSite = sitePath(load.URL) + s.loading = false + if s.reloading && s.scroll != nil && s.onSite && s.scrollPath == s.shown && p.view != nil { + p.view.Eval("scrollTo(" + strconv.FormatFloat(s.scroll.x, 'f', -1, 64) + "," + strconv.FormatFloat(s.scroll.y, 'f', -1, 64) + ")") + } + s.reloading, s.scroll = false, nil + p.refresh() + } +} + +// siteMessage takes in what the site page posted: only the position the reload script reports, +// while the host reloads the page. +func (p *Page) siteMessage(text string) { + var position struct { + Type string `json:"type"` + X float64 `json:"x"` + Y float64 `json:"y"` + } + if !p.site.reloading || json.Unmarshal([]byte(text), &position) != nil || position.Type != "position" { + return + } + p.site.scroll = &sitePosition{x: position.X, y: position.Y} + p.site.scrollPath = p.site.shown +} + +// refresh loads the file's page again when the main frame shows it, has finished loading, and +// was served an older text than the last one. +func (p *Page) refresh() { + s := &p.site + if p.view == nil || s.loading || s.reloading || !s.onSite || s.shown != p.documentPath() || s.served == s.version { + return + } + p.reloadSite() +} + +// reloadSite loads the main frame's page again, keeping where it is scrolled. +func (p *Page) reloadSite() { + p.site.reloading, p.site.scroll = true, nil + p.view.Eval(reloadScript) +} + +// clock is the time a window is handed to Follow at. +func (p *Page) clock() time.Time { + if p.now != nil { + return p.now() + } + return time.Now() +} diff --git a/desktop/internal/webpreview/site_test.go b/desktop/internal/webpreview/site_test.go new file mode 100644 index 0000000000..ebc4cd7c1f --- /dev/null +++ b/desktop/internal/webpreview/site_test.go @@ -0,0 +1,271 @@ +package webpreview + +import ( + "context" + "errors" + "os" + "path/filepath" + "slices" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/vivaui/viva/app" + "github.com/vivaui/viva/gfx" +) + +// fakeView stands in for the engine's page and keeps what the host asked of it. +type fakeView struct { + loads, evals []string + reloads, backs, forwards int + closed bool +} + +func (f *fakeView) ID() gfx.NativeViewID { return 1 } +func (f *fakeView) Load(url string) { f.loads = append(f.loads, url) } +func (f *fakeView) Reload() { f.reloads++ } +func (f *fakeView) Back() { f.backs++ } +func (f *fakeView) Forward() { f.forwards++ } +func (f *fakeView) Eval(script string) { f.evals = append(f.evals, script) } +func (f *fakeView) PostMessage(string) {} +func (f *fakeView) Close() { f.closed = true } +func (f *fakeView) count(script string) int { return countOf(f.evals, script) } + +func countOf(list []string, item string) int { + n := 0 + for _, entry := range list { + if entry == item { + n++ + } + } + return n +} + +// sitePage is a site page of the file at site/page one.html, on a fake engine page. +func sitePage(t *testing.T, request func(ctx context.Context, path string) (core.HTMLPreviewResource, error)) (*Page, *fakeView) { + t.Helper() + p := testPage(t, Config{Page: SitePage, Address: "site/page%20one.html", Request: request}) + view := &fakeView{} + p.view = view + return p, view +} + +// siteRequest serves one path of the site page and waits for the answer. +func siteRequest(t *testing.T, p *Page, route string) app.WebResponse { + t.Helper() + answers := make(chan app.WebResponse, 1) + p.serveSite(app.WebRequest{Path: "/" + route}, func(response app.WebResponse) { answers <- response }) + select { + case response := <-answers: + return response + case <-time.After(waitLimit): + t.Fatalf("no answer for %q within %s", route, waitLimit) + return app.WebResponse{} + } +} + +const documentAddress = SiteOrigin + "site/page%20one.html" + +// TestSiteServesWhatCoreResolvesAndTheFileFromTheEditor: the file asked for by its own path is +// the editor's last text, without asking Core; every other request is served as Core resolves +// it, with the type Core names, never sniffed or cached. +func TestSiteServesWhatCoreResolvesAndTheFileFromTheEditor(t *testing.T) { + style := filepath.Join(t.TempDir(), "style.css") + if err := os.WriteFile(style, []byte("body{}"), 0o600); err != nil { + t.Fatal(err) + } + var asked []string + p, _ := sitePage(t, func(_ context.Context, path string) (core.HTMLPreviewResource, error) { + asked = append(asked, path) + switch path { + case "site/style.css": + return core.HTMLPreviewResource{Kind: "file", Path: style, MIME: "text/css; charset=utf-8"}, nil + case "site/./page one.html": + return core.HTMLPreviewResource{Kind: "document"}, nil + case "site/docs/": + return core.HTMLPreviewResource{Kind: "directory"}, nil + case ".env": + return core.HTMLPreviewResource{Kind: "denied"}, nil + case "site/broken": + return core.HTMLPreviewResource{}, errors.New("core failed") + } + return core.HTMLPreviewResource{Kind: "none"}, nil + }) + if response := siteRequest(t, p, "site/page one.html"); status(response) != 404 { + t.Fatalf("the file was served %d before the editor gave its text", status(response)) + } + p.SetDocument([]byte("

draft

"), "text/html; charset=utf-8") + asked = nil + + page := siteRequest(t, p, "site/page one.html") + if status(page) != 200 || string(page.Data) != "

draft

" || page.MIME != "text/html; charset=utf-8" || + page.Headers["Cache-Control"] != "no-store" || page.Headers["X-Content-Type-Options"] != "nosniff" { + t.Fatalf("the file was served %d %q as %q with %v", status(page), page.Data, page.MIME, page.Headers) + } + if len(asked) != 0 { + t.Fatalf("Core was asked %v for the file's own path", asked) + } + if css := siteRequest(t, p, "site/style.css"); status(css) != 200 || string(css.Data) != "body{}" || css.MIME != "text/css; charset=utf-8" { + t.Fatalf("the style sheet was served %d %q as %q", status(css), css.Data, css.MIME) + } + if other := siteRequest(t, p, "site/./page one.html"); string(other.Data) != "

draft

" { + t.Fatalf("the file under another name was served %q", other.Data) + } + if folder := siteRequest(t, p, "site/docs/"); status(folder) != 200 || string(folder.Data) != string(directoryPage) { + t.Fatalf("a folder was served %d %q", status(folder), folder.Data) + } + for route, want := range map[string]int{".env": 403, "site/missing.js": 404, "site/broken": 404} { + if got := status(siteRequest(t, p, route)); got != want { + t.Fatalf("%q was served %d, want %d", route, got, want) + } + } +} + +// TestSiteKeepsTheMainFrameOnTheSite: the main frame and frames load the site, frames also web +// pages; a link the user follows elsewhere goes to Follow, and a script's navigation nowhere. +func TestSiteKeepsTheMainFrameOnTheSite(t *testing.T) { + var followed []string + p := testPage(t, Config{Page: SitePage, Address: "index.html", Follow: func(address string) { followed = append(followed, address) }}) + for _, allowed := range []app.WebNavigation{ + {URL: SiteOrigin + "other.html", MainFrame: true}, + {URL: SiteOrigin + "index.html#part", MainFrame: true}, + {URL: "about:blank", MainFrame: true}, + {URL: "https://example.com/embed", MainFrame: false}, + {URL: "data:text/html,hi", MainFrame: false}, + {URL: SiteOrigin + "frame.html", MainFrame: false}, + } { + if !p.navigateSite(allowed) { + t.Fatalf("%+v was refused", allowed) + } + } + for _, refused := range []app.WebNavigation{ + {URL: "https://example.com/", MainFrame: true}, + {URL: "https://example.com/", MainFrame: true, UserGesture: true}, + {URL: "file:///etc/passwd", MainFrame: false}, + {URL: Origin + "markdown.html", MainFrame: false}, + } { + if p.navigateSite(refused) { + t.Fatalf("%+v was allowed", refused) + } + } + if !slices.Equal(followed, []string{"https://example.com/"}) { + t.Fatalf("Follow was given %v", followed) + } +} + +// TestSiteWindowsLoadInPlaceOrGoToFollowAtMostOncePerInterval: a window the page opens on the +// site loads in place of the page, and one elsewhere goes to Follow, at most once per +// popupInterval. +func TestSiteWindowsLoadInPlaceOrGoToFollowAtMostOncePerInterval(t *testing.T) { + var followed []string + p := testPage(t, Config{Page: SitePage, Address: "index.html", Follow: func(address string) { followed = append(followed, address) }}) + view := &fakeView{} + p.view = view + clock := time.Date(2026, 11, 14, 12, 0, 0, 0, time.UTC) + p.now = func() time.Time { return clock } + + if p.newWindow(SiteOrigin+"next.html") || !slices.Equal(view.loads, []string{SiteOrigin + "next.html"}) { + t.Fatalf("a window on the site loaded %v", view.loads) + } + if p.newWindow("https://example.com/a") || p.newWindow("https://example.com/b") || p.newWindow("about:blank") { + t.Fatal("the engine was let open a window") + } + clock = clock.Add(popupInterval) + p.newWindow("https://example.com/c") + if !slices.Equal(followed, []string{"https://example.com/a", "https://example.com/c"}) { + t.Fatalf("Follow was given %v", followed) + } +} + +// TestSiteShowsEachTextAndKeepsItsScroll: a text the editor gives reloads the page while it +// shows the file and has loaded, at most one reload at a time, and the page is scrolled back to +// where it reported it was; a page of the site that is not the file is not reloaded, and the +// file shown again after a text it was not served loads again. +func TestSiteShowsEachTextAndKeepsItsScroll(t *testing.T) { + p, view := sitePage(t, nil) + p.SetDocument([]byte("v1"), "text/html; charset=utf-8") + siteRequest(t, p, "site/page one.html") + p.siteLoaded(app.WebLoad{Phase: app.WebLoadCommitted, URL: documentAddress}) + p.SetDocument([]byte("v2"), "text/html; charset=utf-8") + if len(view.evals) != 0 { + t.Fatalf("the page was reloaded before it had loaded: %v", view.evals) + } + // v2 came after the page was served v1, so the page loads again once it has loaded. + p.siteLoaded(app.WebLoad{Phase: app.WebLoadFinished, URL: documentAddress}) + if view.count(reloadScript) != 1 { + t.Fatalf("the page was not reloaded for the text it was not served: %v", view.evals) + } + p.receive(`{"type":"position","x":0,"y":120}`) + p.SetDocument([]byte("v3"), "text/html; charset=utf-8") + if view.count(reloadScript) != 1 { + t.Fatal("the page was reloaded again while it reloads") + } + siteRequest(t, p, "site/page one.html") + p.siteLoaded(app.WebLoad{Phase: app.WebLoadCommitted, URL: documentAddress}) + p.siteLoaded(app.WebLoad{Phase: app.WebLoadFinished, URL: documentAddress}) + if view.count("scrollTo(0,120)") != 1 || view.count(reloadScript) != 1 { + t.Fatalf("the page was not scrolled back once, or reloaded for the text it was served: %v", view.evals) + } + + // A position the page posts while the host does not reload it is not taken. + p.receive(`{"type":"position","x":0,"y":900}`) + p.siteLoaded(app.WebLoad{Phase: app.WebLoadFinished, URL: documentAddress}) + if view.count("scrollTo(0,900)") != 0 { + t.Fatal("the page scrolled to a position it posted on its own") + } + + // Another page of the site is not reloaded for the file's text. + p.siteLoaded(app.WebLoad{Phase: app.WebLoadCommitted, URL: SiteOrigin + "site/other.html"}) + p.siteLoaded(app.WebLoad{Phase: app.WebLoadFinished, URL: SiteOrigin + "site/other.html"}) + p.SetDocument([]byte("v4"), "text/html; charset=utf-8") + if view.count(reloadScript) != 1 { + t.Fatal("another page of the site was reloaded for the file's text") + } + // Back on the file, served v3 from the engine's history, the page loads v4. + p.siteLoaded(app.WebLoad{Phase: app.WebLoadCommitted, URL: documentAddress + "#part"}) + p.siteLoaded(app.WebLoad{Phase: app.WebLoadFinished, URL: documentAddress + "#part"}) + if view.count(reloadScript) != 2 { + t.Fatalf("the file shown again with an old text was not reloaded: %v", view.evals) + } + + // The reload button keeps the scroll too; Back and Forward go to the engine. + siteRequest(t, p, "site/page one.html") + p.siteLoaded(app.WebLoad{Phase: app.WebLoadFinished, URL: documentAddress}) + p.Reload() + p.Back() + p.Forward() + if view.count(reloadScript) != 3 || view.reloads != 0 || view.backs != 1 || view.forwards != 1 { + t.Fatalf("the buttons did %v, %d reloads, %d backs, %d forwards", view.evals, view.reloads, view.backs, view.forwards) + } +} + +// TestSitePageTakesNoMessageButItsPosition: the page's scripts are the user's, so what they post +// is neither handed to the host nor makes the page ready to be sent the host's messages. +func TestSitePageTakesNoMessageButItsPosition(t *testing.T) { + var received []Message + p := testPage(t, Config{Page: SitePage, Address: "index.html", OnMessage: func(message Message) { received = append(received, message) }}) + p.view = &fakeView{} + p.receive(`{"type":"ready"}`) + p.receive(`{"type":"link","href":"https://example.com"}`) + if p.Ready() || len(received) != 0 { + t.Fatalf("the page is ready %v after posting, the host got %+v", p.Ready(), received) + } +} + +func TestSitePathDecodesAddressesOfTheSiteOnly(t *testing.T) { + for address, want := range map[string]string{ + SiteOrigin: "", + SiteOrigin + "a%20b/c.html?x=1#y": "a b/c.html", + SiteOrigin + "docs/": "docs/", + SiteOrigin + "%E4%B8%AD%E6%96%87.htm": "中文.htm", + } { + if got, ok := sitePath(address); !ok || got != want { + t.Fatalf("sitePath(%q) = %q, %v; want %q", address, got, ok, want) + } + } + for _, address := range []string{Origin + "file", "https://lithe-site.viva-app.invalid/site/x", SiteOrigin + "%zz"} { + if _, ok := sitePath(address); ok { + t.Fatalf("sitePath(%q) is on the site", address) + } + } +} diff --git a/desktop/internal/webpreview/webpreview.go b/desktop/internal/webpreview/webpreview.go index 704c95a3af..2d0059190f 100644 --- a/desktop/internal/webpreview/webpreview.go +++ b/desktop/internal/webpreview/webpreview.go @@ -1,5 +1,6 @@ // Package webpreview opens the pages the editor area shows in a web view: the rendered page of a -// Markdown file, the viewer of an image or an SVG file, and a PDF document. +// Markdown file, the viewer of an image or an SVG file, a PDF document, and an HTML file with its +// site (site.go). // // The pages and the scripts they use are embedded in the application and served through the // "lithe-preview" scheme, one scheme server per page. What a page is served of the user's files @@ -9,8 +10,9 @@ // opens the link elsewhere; a page opens no window and downloads nothing. // // Nothing is written: the pages are read from the binary, the user's files are read and answered -// with Cache-Control: no-store, and the pages are not ephemeral, since an ephemeral WebView2 page -// leaves a profile folder behind for each page. +// with Cache-Control: no-store, and these pages are not ephemeral, since an ephemeral WebView2 +// page leaves a profile folder behind for each page. The site page is the exception: it runs the +// user's own scripts, so what they keep must stay apart from every other page. // // Note: the decision is recorded in // .agents/notes/implemented/architecture/2026-11-14-web-view-previews.md @@ -54,6 +56,18 @@ const ( PDFPage = "file" ) +// webView is the engine's page; *app.WebView is one, and tests stand in for it. +type webView interface { + ID() gfx.NativeViewID + Load(url string) + Reload() + Back() + Forward() + Eval(script string) + PostMessage(text string) + Close() +} + const ( // fileRoute serves the viewer's file; a name may follow it, for the PDF viewer's title. fileRoute = "file" @@ -108,7 +122,7 @@ type Message struct { type Config struct { // Host opens the web view. Host *app.WebHost - // Page is MarkdownPage, ImagePage or PDFPage. + // Page is MarkdownPage, ImagePage, PDFPage or SitePage. Page string // File is the file a viewer shows: an image for ImagePage without a document, a PDF for // PDFPage. FileLimit bounds what is read of it. @@ -123,20 +137,29 @@ type Config struct { // Follow receives the address of a navigation the user started away from the page, such as // a link in a PDF, on the window's thread. The page stays where it is. Follow func(address string) + // Address is the HTML file's address from the root of its site, as Core gives it + // (core.HTMLPreviewSite), for SitePage. + Address string + // Request answers what a request of the site page serves, from its decoded path from the + // root (core.Client.ResolveHTMLPreviewRequest); nil serves the file alone. + Request func(ctx context.Context, path string) (core.HTMLPreviewResource, error) // Log reports a failure of the page's resources; nil logs to slog. Log func(stage string, err error) } // Page is one open page. type Page struct { - view *app.WebView + view webView config Config ctx context.Context cancel context.CancelFunc ready bool - // document and documentMIME are what documentRoute serves. + // document and documentMIME are what documentRoute serves, or the site page's file. document []byte documentMIME string + // site is what the site page follows of its main frame; now, when set, is its clock. + site siteState + now func() time.Time } // Open opens a page. It fails with app.ErrUnsupported where the platform has no web engine. @@ -145,19 +168,27 @@ func Open(config Config) (*Page, error) { return nil, errors.New("webpreview: no web host") } switch config.Page { - case MarkdownPage, ImagePage, PDFPage: + case MarkdownPage, ImagePage, PDFPage, SitePage: default: return nil, errors.New("webpreview: unknown page " + config.Page) } ctx, cancel := context.WithCancel(context.Background()) p := &Page{config: config, ctx: ctx, cancel: cancel} - view, err := config.Host.Open(app.WebViewConfig{ + web := app.WebViewConfig{ URL: p.address(), Scheme: &app.WebScheme{Name: SchemeName, ServeAsync: p.serve}, OnMessage: p.receive, Navigate: p.navigate, BridgeMainFrameOnly: true, - }) + } + if config.Page == SitePage { + web.Scheme = &app.WebScheme{Name: SiteScheme, ServeAsync: p.serveSite} + web.Navigate = p.navigateSite + web.NewWindow = p.newWindow + web.OnLoad = p.siteLoaded + web.Ephemeral = true + } + view, err := config.Host.Open(web) if err != nil { cancel() return nil, err @@ -169,7 +200,8 @@ func Open(config Config) (*Page, error) { // ID names the page for ui.Element.NativeView. func (p *Page) ID() gfx.NativeViewID { return p.view.ID() } -// Ready reports whether the page's script takes messages. +// Ready reports whether the page's script takes messages. The site page's scripts are the +// user's, so it never is. func (p *Page) Ready() bool { return p.ready } // Send posts a message to the page as JSON. It is dropped until the page is ready: the host sends @@ -186,9 +218,39 @@ func (p *Page) Send(message any) { p.view.PostMessage(string(text)) } -// SetDocument replaces the buffer an SVG viewer is served; the page loads it when told to. +// SetDocument replaces the buffer an SVG viewer is served, which the page loads when told to, or +// the site page's file, which the page shows at once when it shows the file. func (p *Page) SetDocument(data []byte, mime string) { p.document, p.documentMIME = data, mime + if p.config.Page == SitePage { + p.site.version++ + p.refresh() + } +} + +// Reload loads the page again; the site page keeps where it is scrolled. +func (p *Page) Reload() { + if p.view == nil { + return + } + if p.config.Page == SitePage { + p.reloadSite() + return + } + p.view.Reload() +} + +// Back and Forward move through the page's history. +func (p *Page) Back() { + if p.view != nil { + p.view.Back() + } +} + +func (p *Page) Forward() { + if p.view != nil { + p.view.Forward() + } } // FileURL is the address of the viewer's file, ending in its name. @@ -196,10 +258,14 @@ func (p *Page) FileURL() string { return Origin + fileRoute + "/" + url.PathEscape(filepath.Base(p.config.File)) } -// address is where the page is loaded from: the page itself, or the file for the PDF page. +// address is where the page is loaded from: the page itself, or the file for the PDF page and +// the site page. func (p *Page) address() string { - if p.config.Page == PDFPage { + switch p.config.Page { + case PDFPage: return p.FileURL() + case SitePage: + return SiteOrigin + p.config.Address } return Origin + p.config.Page } @@ -217,6 +283,10 @@ func (p *Page) Close() { // receive decodes what the page posted and hands it to the host. func (p *Page) receive(text string) { + if p.config.Page == SitePage { + p.siteMessage(text) + return + } var message Message if err := json.Unmarshal([]byte(text), &message); err != nil || message.Type == "" { return diff --git a/desktop/internal/workbench/browser_preview.go b/desktop/internal/workbench/browser_preview.go index 75410798f7..b62b463f28 100644 --- a/desktop/internal/workbench/browser_preview.go +++ b/desktop/internal/workbench/browser_preview.go @@ -8,8 +8,9 @@ import ( "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" ) -// HTML and SVG files are text the editor edits; what they look like is shown by the system -// browser, as IntelliJ IDEA's "Open in Browser" does. The file on disk is opened, so unsaved +// HTML and SVG files are text the editor edits; where the system has a web engine, what they look +// like is also shown beside the text (html_preview.go, svg_preview.go). "Open in Browser" shows +// the file in the system browser, as IntelliJ IDEA's does. The file on disk is opened, so unsaved // changes are saved first. // browserExtensions are the files a browser shows. diff --git a/desktop/internal/workbench/documents.go b/desktop/internal/workbench/documents.go index a28e127637..3e4b2ddf8b 100644 --- a/desktop/internal/workbench/documents.go +++ b/desktop/internal/workbench/documents.go @@ -110,11 +110,13 @@ type document struct { // debugGutter is the debugger's breakpoints and paused line the view was given // (debug_gutter.go). debugGutter debugGutter - // markdown is the rendered page of a Markdown file and svg the picture of an SVG file, each - // made the first time it is shown, and pageMode how the file's tab shows them: source, both - // side by side, or the page alone (markdown_preview.go, svg_preview.go). + // markdown is the rendered page of a Markdown file, svg the picture of an SVG file and html + // the page of an HTML file, each made the first time it is shown, and pageMode how the file's + // tab shows them: source, both side by side, or the page alone (markdown_preview.go, + // svg_preview.go, html_preview.go). markdown *markdownPreviewState svg *svgPreviewState + html *htmlPreviewState pageMode pageMode // virtual marks a read-only document a plugin provides for a URI that names no // file (a class inside a jar). path then holds the URI: the document is never diff --git a/desktop/internal/workbench/editor_view.go b/desktop/internal/workbench/editor_view.go index 24984249d6..ff88b75c0d 100644 --- a/desktop/internal/workbench/editor_view.go +++ b/desktop/internal/workbench/editor_view.go @@ -61,8 +61,8 @@ func (a *App) editorNode(c ui.C, n *splitNode) ui.Box { // editorGroup declares one group of the editor: a strip of its tabs over a body that shows // the selected file or terminal. The group is recorded for the drag, which aims at the strip // and the body. A group that shows an open file ends its strip with the soft wrap switch, after -// the Contents button and the switch of a Markdown file's view, or the switch of an SVG file's -// view where its picture can be shown. +// the Contents button and the switch of a Markdown file's view, or the switch of an SVG or an +// HTML file's view where its picture or page can be shown. func (a *App) editorGroup(c ui.C, id string) ui.Box { u := &a.term place := newGroupPlace(id) @@ -82,7 +82,7 @@ func (a *App) editorGroup(c ui.C, id string) ui.Box { if isMarkdownDocument(doc) { a.markdownContentsButton(c, p, doc) a.pageModeSwitch(c, doc) - } else if isSVGDocument(doc) && a.previewWeb() { + } else if (isSVGDocument(doc) && a.previewWeb()) || a.htmlPreviewable(doc) { a.pageModeSwitch(c, doc) } if doc != nil { @@ -103,8 +103,8 @@ func (a *App) editorGroup(c ui.C, id string) ui.Box { } // groupBody declares the body of group id: the control of the file it shows (a Markdown file -// with its rendered page, an SVG file with its picture), of the Diff tab, of the viewer tab, the -// LSP Logs tab or the terminal. +// with its rendered page, an SVG file with its picture, an HTML file with its page), of the Diff +// tab, of the viewer tab, the LSP Logs tab or the terminal. func (a *App) groupBody(c ui.C, id string, doc *document) { if isMarkdownDocument(doc) { a.markdownDocument(c, a.project, id, doc) @@ -114,6 +114,10 @@ func (a *App) groupBody(c ui.C, id string, doc *document) { a.svgDocument(c, a.project, id, doc) return } + if a.htmlPreviewable(doc) { + a.htmlDocument(c, a.project, id, doc) + return + } if doc != nil { a.documentView(c, id, doc) return diff --git a/desktop/internal/workbench/html_preview.go b/desktop/internal/workbench/html_preview.go new file mode 100644 index 0000000000..d9152319fb --- /dev/null +++ b/desktop/internal/workbench/html_preview.go @@ -0,0 +1,244 @@ +package workbench + +import ( + "context" + "path/filepath" + "strings" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/icons" + "github.com/1lck/Lithe-IDEA/desktop/internal/webpreview" + "github.com/vivaui/viva/ui" +) + +// Where the system has a web engine, an HTML file opens as text with its page beside it, and the +// tab strip's switch shows the source, both, or the page alone, as for an SVG file. The page is +// the site page of package webpreview: Core names the folder it is served from, the workspace +// when the file lies in one (htmlPreview.site), and decides each request of the page +// (htmlPreview.resolveRequest), so the page loads its scripts, styles and pictures as from a +// local web server and is refused hidden files and keys. The file itself is served the editor's +// text, given at most once per htmlPreviewDelay: the page loads it again at once, scrolled where +// it was. A link the user follows off the site opens as a Markdown link does +// (followDocumentLink): a web or mail address in the system's application. +// +// The bar over the page moves back and forward through its history, loads it again, and opens +// the file in the system browser. Without a web engine, or where the page cannot be opened, an +// HTML file is text alone, and the editor's menu still opens it in the browser +// (browser_preview.go). + +const ( + // htmlPreviewMaxBytes is the largest text the page is given. + htmlPreviewMaxBytes = 8 << 20 + // htmlPreviewDelay is the least time between two texts of an edited file, so that typing does + // not load the page again at every key. + htmlPreviewDelay = 150 * time.Millisecond +) + +// htmlPreviewWait calls done, from another goroutine, once htmlPreviewDelay passed. Tests replace +// it to end the wait when they choose. +var htmlPreviewWait = func(done func()) { time.AfterFunc(htmlPreviewDelay, done) } + +// htmlKernel is what the page of an HTML file asks Core: the file's site, and what each request +// of the site serves. +type htmlKernel interface { + HTMLPreviewSite(ctx context.Context, documentPath, workspaceRoot string) (core.HTMLPreviewSite, error) + ResolveHTMLPreviewRequest(ctx context.Context, documentPath, workspaceRoot, path string) (core.HTMLPreviewResource, error) +} + +// htmlPreviewState is the page of one HTML file. +type htmlPreviewState struct { + // path is the file the page is of; a file that moves starts over. + path string + // site is the file's site once Core named it; asked says the question was put, failed that + // Core could not answer it. + site *core.HTMLPreviewSite + asked, failed bool + entry *previewPage + // given is the editor revision the page was last given, -1 for none. + given int + // waiting says a change waits out htmlPreviewDelay; due says the wait is over. + waiting, due bool + // too says the text is over htmlPreviewMaxBytes. + too bool +} + +// isHTMLDocument reports whether d is an HTML file, by its name. +func isHTMLDocument(d *document) bool { + if d == nil || d.virtual { + return false + } + switch strings.ToLower(filepath.Ext(d.path)) { + case ".html", ".htm", ".xhtml": + return true + } + return false +} + +// htmlPreviewable reports whether d is an HTML file whose page can be shown: the web host is +// ready, no page failed to open, and Core answers for its site. +func (a *App) htmlPreviewable(d *document) bool { + if !isHTMLDocument(d) || !a.previewWeb() || a.previews.siteFailed { + return false + } + _, ok := a.kernel.(htmlKernel) + return ok +} + +// htmlState is d's page state, made the first time it is shown and again when the file moved. +func (a *App) htmlState(d *document) *htmlPreviewState { + if d.html == nil || d.html.path != d.path { + d.html = &htmlPreviewState{path: d.path, given: -1} + } + return d.html +} + +// htmlDocument declares the body of group for HTML file d in the file's mode: the source, the +// page, or the two in equal halves. +func (a *App) htmlDocument(c ui.C, p *project, group string, d *document) { + switch d.pageMode { + case pageSource: + a.documentView(c, group, d) + return + case pageOnly: + d.group = group + a.htmlPage(c, p, d) + return + } + ui.Row(c).Fill().Children(func() { + ui.Column(c.Part("source")).Grow(1).Basis(0).FillHeight().Clip().Children(func() { + a.documentView(c, group, d) + }) + ui.Row(c).Width(1).FillHeight().Shrink(0).Background(a.colors.Line) + ui.Column(c.Part("page")).Grow(1).Basis(0).FillHeight().Clip().Children(func() { + a.htmlPage(c, p, d) + }) + }) +} + +// htmlPage declares d's page under the viewer's bar, once Core named its site. +func (a *App) htmlPage(c ui.C, p *project, d *document) { + s := a.htmlState(d) + a.askHTMLSite(p, d, s) + var entry *previewPage + if s.site != nil { + entry = a.htmlWebPage(p, d, s) + } + if entry != nil { + a.giveHTML(d, s) + } + language := a.language() + ui.Column(c.Part("html")).Fill().Background(a.colors.Editor).Clip().Children(func() { + a.viewerToolbar(c, viewerBar{name: filepath.Base(d.path), actions: func() { a.htmlActions(c, p, d, s, entry) }}) + switch { + case s.failed: + a.panelMessage(c, i18n.Shared(language, "desktop.htmlPreview.failed"), a.colors.Subtle) + case entry == nil: + // Core has not named the site yet. + case s.too: + a.panelMessage(c, i18n.Shared(language, "desktop.htmlPreview.tooLarge"), a.colors.Subtle) + default: + a.showPreviewPage(c, entry) + } + }) +} + +// htmlActions declares the buttons of d's page on the viewer's bar: back, forward and load +// again while the page is shown, and open in the system browser. +func (a *App) htmlActions(c ui.C, p *project, d *document, s *htmlPreviewState, entry *previewPage) { + language := a.language() + if entry != nil && !entry.closed && !s.too { + if a.viewerIconButton(c.Part("back"), i18n.Shared(language, "desktop.htmlPreview.back"), icons.ChevronLeft) { + entry.view.Back() + } + if a.viewerIconButton(c.Part("forward"), i18n.Shared(language, "desktop.htmlPreview.forward"), icons.ChevronRight) { + entry.view.Forward() + } + if a.viewerIconButton(c.Part("reload"), i18n.Shared(language, "desktop.htmlPreview.reload"), icons.RefreshCw) { + entry.view.Reload() + } + } + if a.viewerIconButton(c.Part("browser"), i18n.Shared(language, "desktop.editorMenu.openInBrowser"), icons.ExternalLink) { + c.After(func() { a.openInBrowser(p, d) }) + } +} + +// askHTMLSite asks Core for the site of d's page the first time the page is shown. +func (a *App) askHTMLSite(p *project, d *document, s *htmlPreviewState) { + kernel, ok := a.kernel.(htmlKernel) + if !ok || s.asked { + return + } + s.asked = true + path, root := d.path, p.root + a.background(p, kernelCallTimeout, func(ctx context.Context) func(*App) { + site, err := kernel.HTMLPreviewSite(ctx, path, root) + return func(a *App) { + if d.html != s { + return + } + if err != nil { + s.failed = true + a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("html_preview_site", err)) + return + } + s.site = &site + } + }) +} + +// htmlWebPage is the page of d, opened the first time it is shown once Core named its site, and +// again after it was closed. It is nil where the page cannot be opened. +func (a *App) htmlWebPage(p *project, d *document, s *htmlPreviewState) *previewPage { + if s.entry != nil && !s.entry.closed { + return s.entry + } + kernel, ok := a.kernel.(htmlKernel) + if !ok { + return nil + } + // A page opened again is given the text again. + s.entry, s.given = nil, -1 + path, root := d.path, p.root + var entry *previewPage + entry = a.openPreviewPage(webpreview.Config{ + Page: webpreview.SitePage, + Address: s.site.Address, + Request: func(ctx context.Context, route string) (core.HTMLPreviewResource, error) { + return kernel.ResolveHTMLPreviewRequest(ctx, path, root, route) + }, + Follow: func(address string) { + if entry != nil && s.entry == entry { + a.followDocumentLink(p, path, address, nil) + } + }, + }, func() bool { + return a.project == p && p.docs.find(d.id) == d && d.html == s && s.entry == entry && a.htmlPreviewable(d) + }) + s.entry = entry + return entry +} + +// giveHTML gives the page d's text when it changed since the page was last given it, at once the +// first time and otherwise once htmlPreviewDelay passed since the change was seen. +func (a *App) giveHTML(d *document, s *htmlPreviewState) { + revision := d.view.Revision() + if revision == s.given || s.waiting { + return + } + if s.given >= 0 && !s.due { + s.waiting = true + htmlPreviewWait(func() { + a.post(func(*App) { s.waiting, s.due = false, true }) + }) + return + } + s.due = false + text := d.view.TextSnapshot() + s.given = revision + if s.too = text.Len() > htmlPreviewMaxBytes; s.too { + return + } + s.entry.view.SetDocument([]byte(text.String()), s.site.MIME) +} diff --git a/desktop/internal/workbench/html_preview_test.go b/desktop/internal/workbench/html_preview_test.go new file mode 100644 index 0000000000..0542fa18e1 --- /dev/null +++ b/desktop/internal/workbench/html_preview_test.go @@ -0,0 +1,192 @@ +package workbench + +import ( + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/1lck/Lithe-IDEA/desktop/internal/core" + "github.com/1lck/Lithe-IDEA/desktop/internal/i18n" + "github.com/1lck/Lithe-IDEA/desktop/internal/webpreview" +) + +const testHTML = `

Board

` + +// openHTML opens a project whose site folder holds an HTML file of text, its style sheet and a +// hidden file, and returns the file's document. +func openHTML(t *testing.T, h *harness, text string) *document { + t.Helper() + root := t.TempDir() + for name, content := range map[string]string{ + "site/board.html": text, + "site/style.css": "h1{}", + ".env": "TOKEN=1", + } { + path := filepath.Join(root, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + h.open(root) + path := filepath.Join(root, "site", "board.html") + h.app.openFile(h.app.project, path) + h.settle() + d := h.app.project.docs.byPath(path) + if d == nil { + t.Fatal("the HTML file did not open") + } + h.settle() + h.settle() + return d +} + +// heldHTMLWaits makes the HTML pages' waits end only when the test calls the returned function. +func heldHTMLWaits(t *testing.T) func() int { + t.Helper() + var held []func() + previous := htmlPreviewWait + htmlPreviewWait = func(done func()) { held = append(held, done) } + t.Cleanup(func() { htmlPreviewWait = previous }) + return func() int { + ended := len(held) + for _, done := range held { + done() + } + held = nil + return ended + } +} + +// TestHTMLFileShowsItsPageBesideTheSource: an HTML file opens as text with its page beside it, on +// the site page of the workspace Core names, given the editor's text as an HTML document; the +// page's requests are put to Core for the file, an edit is given after the wait, the bar moves +// through the page's history and loads it again, a link followed off the site opens as Core +// resolves it, and the tab strip's switch shows either side alone. +func TestHTMLFileShowsItsPageBesideTheSource(t *testing.T) { + endWaits := heldHTMLWaits(t) + var opened []string + previous := openURL + openURL = func(address string) error { opened = append(opened, address); return nil } + t.Cleanup(func() { openURL = previous }) + + h := newHarness(t, &testKernel{Client: core.NewClient()}) + pages := fakePreviews(h) + d := openHTML(t, h, testHTML) + if len(*pages) != 1 || d.html == nil || d.html.site == nil { + t.Fatalf("the HTML file opened %d web pages", len(*pages)) + } + page := (*pages)[0] + if page.config.Page != webpreview.SitePage || page.config.Address != "site/board.html" || page.config.Request == nil { + t.Fatalf("the file's page is %q at %q", page.config.Page, page.config.Address) + } + if editorRect(h, d).Width == 0 { + t.Fatal("the source is not shown beside the page") + } + if len(page.documents) != 1 || string(page.documents[0]) != testHTML || page.mimes[0] != "text/html; charset=utf-8" { + t.Fatalf("the page was given %q as %q", page.documents, page.mimes) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + for route, kind := range map[string]string{"site/board.html": "document", "site/style.css": "file", ".env": "denied", "site/missing.js": "none"} { + resource, err := page.config.Request(ctx, route) + if err != nil || resource.Kind != kind { + t.Fatalf("%q is %+v (%v), want %s", route, resource, err, kind) + } + } + + h.app.post(func(a *App) { a.insertForTest(d, "") }) + h.settle() + h.settle() + if len(page.documents) != 1 { + t.Fatal("an edit was given before the wait ended") + } + if ended := endWaits(); ended != 1 { + t.Fatalf("%d waits ended, want 1", ended) + } + h.settle() + h.settle() + if len(page.documents) != 2 || !strings.Contains(string(page.documents[1]), "") { + t.Fatalf("after the wait the page was given %d texts", len(page.documents)) + } + + language := h.app.language() + for _, key := range []string{"desktop.htmlPreview.back", "desktop.htmlPreview.forward", "desktop.htmlPreview.reload"} { + h.click(center(h.hitLabeled(i18n.Shared(language, key)))) + h.settle() + } + if page.backs != 1 || page.forwards != 1 || page.reloads != 1 { + t.Fatalf("the bar went back %d, forward %d and reloaded %d times", page.backs, page.forwards, page.reloads) + } + if !controlShown(h, i18n.Shared(language, "desktop.editorMenu.openInBrowser")) { + t.Fatal("the bar does not open the file in the browser") + } + + page.config.Follow("https://example.com/docs") + h.await("the followed link", func() bool { return len(opened) == 1 }) + if opened[0] != "https://example.com/docs" { + t.Fatalf("opened %v", opened) + } + + h.click(center(h.hitLabeled(i18n.Shared(language, "editor.markdownPreviewView")))) + h.settle() + if editorRect(h, d).Width != 0 || !controlShown(h, i18n.Shared(language, "desktop.htmlPreview.reload")) { + t.Fatal("the page alone still shows the source, or not the bar") + } + h.click(center(h.hitLabeled(i18n.Shared(language, "editor.markdownSourceView")))) + h.settle() + if editorRect(h, d).Width == 0 || controlShown(h, i18n.Shared(language, "desktop.htmlPreview.reload")) || page.closed || len(*pages) != 1 { + t.Fatalf("the source alone shows the page, or the hidden page closed %v", page.closed) + } +} + +// TestHTMLFileIsTextWhereItsPageCannotOpen: where the engine cannot open an HTML file's page, HTML +// files are text alone from then on, without the switch of their view, and the other previews +// still open. +func TestHTMLFileIsTextWhereItsPageCannotOpen(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + pages := fakePreviews(h) + open := h.app.previews.open + h.app.previews.open = func(config webpreview.Config) (previewView, error) { + if config.Page == webpreview.SitePage { + return nil, errors.New("no ephemeral store") + } + return open(config) + } + d := openHTML(t, h, testHTML) + language := h.app.language() + if !h.app.previews.siteFailed || h.app.previews.failed || len(*pages) != 0 { + t.Fatalf("the page that failed marked the site %v and the previews %v", h.app.previews.siteFailed, h.app.previews.failed) + } + if editorRect(h, d).Width == 0 || controlShown(h, i18n.Shared(language, "editor.markdownPreviewView")) { + t.Fatal("the HTML file is not text alone") + } + + svg := filepath.Join(h.app.project.root, "icon.svg") + if err := os.WriteFile(svg, []byte(testSVG), 0o600); err != nil { + t.Fatal(err) + } + h.app.openFile(h.app.project, svg) + h.settle() + h.settle() + if len(*pages) != 1 || (*pages)[0].config.Page != webpreview.ImagePage { + t.Fatalf("an SVG file opened %d pages once the HTML page failed", len(*pages)) + } +} + +// TestHTMLFileIsTextWithoutAWebEngine: where no page can be opened, an HTML file is text alone, +// without the switch of its view. +func TestHTMLFileIsTextWithoutAWebEngine(t *testing.T) { + h := newHarness(t, &testKernel{Client: core.NewClient()}) + d := openHTML(t, h, testHTML) + if d.html != nil || editorRect(h, d).Width == 0 || controlShown(h, i18n.Shared(h.app.language(), "editor.markdownPreviewView")) { + t.Fatal("without a web engine the HTML file is not text alone") + } +} diff --git a/desktop/internal/workbench/markdown_preview.go b/desktop/internal/workbench/markdown_preview.go index eb0b6b482f..42136eb61f 100644 --- a/desktop/internal/workbench/markdown_preview.go +++ b/desktop/internal/workbench/markdown_preview.go @@ -46,8 +46,8 @@ const ( markdownContentsIndent = 12 ) -// pageMode is how the tab of a file with a page shows it, a Markdown file or an SVG file -// (svg_preview.go): its source, the page, or both. The zero mode, both side by side, is how a +// pageMode is how the tab of a file with a page shows it, a Markdown, an SVG (svg_preview.go) +// or an HTML file (html_preview.go): its source, the page, or both. The zero mode, both side by side, is how a // file opens. type pageMode uint8 diff --git a/desktop/internal/workbench/markdown_web_test.go b/desktop/internal/workbench/markdown_web_test.go index 2124a5a796..df4750a4c9 100644 --- a/desktop/internal/workbench/markdown_web_test.go +++ b/desktop/internal/workbench/markdown_web_test.go @@ -26,7 +26,10 @@ type fakePreview struct { ready bool sent []any documents [][]byte + mimes []string closed bool + // reloads, backs and forwards count what the host asked of the page's history. + reloads, backs, forwards int } func (f *fakePreview) ID() gfx.NativeViewID { return f.id } @@ -42,10 +45,15 @@ func (f *fakePreview) Send(message any) { } } -func (f *fakePreview) SetDocument(data []byte, _ string) { +func (f *fakePreview) SetDocument(data []byte, mime string) { f.documents = append(f.documents, data) + f.mimes = append(f.mimes, mime) } +func (f *fakePreview) Reload() { f.reloads++ } +func (f *fakePreview) Back() { f.backs++ } +func (f *fakePreview) Forward() { f.forwards++ } + // load is the page finishing loading: it is ready and says so. func (f *fakePreview) load() { f.ready = true diff --git a/desktop/internal/workbench/preview_pages.go b/desktop/internal/workbench/preview_pages.go index 3601c28706..71585a3844 100644 --- a/desktop/internal/workbench/preview_pages.go +++ b/desktop/internal/workbench/preview_pages.go @@ -11,15 +11,17 @@ import ( ) // The editor area shows some files in a web view of the system's engine, through the pages of -// package webpreview: the rendered page of a Markdown file (markdown_web.go), and the viewer of -// an image, an SVG or a PDF file (viewer_web.go). +// package webpreview: the rendered page of a Markdown file (markdown_web.go), the viewer of an +// image, an SVG or a PDF file (viewer_web.go), and an HTML file with its site (html_preview.go). // // A page lives while what it shows is open. A paint that does not declare it hides it, as when // its tab is not selected, and the page keeps its place and its layout, so the tab shows it as it // was when it is selected again. Past previewPagesKept hidden pages, the one shown longest ago // closes, and opens again when its tab comes back. Before the window's web host is ready, where // the system has no web engine (Linux), and once a page could not be opened, the editor shows its -// native preview instead. +// native preview instead. An HTML file's page needs more of the engine than the others (a store +// of its own that keeps nothing); where it cannot be opened, HTML files alone are text from then +// on. // // Note: the decision is recorded in // .agents/notes/implemented/architecture/2026-11-14-web-view-previews.md @@ -34,6 +36,9 @@ type previewView interface { Send(message any) SetDocument(data []byte, mime string) FileURL() string + Reload() + Back() + Forward() Close() } @@ -42,8 +47,9 @@ type previewPages struct { list []*previewPage // frame counts the paints; a page's shown is the paint that declared it last. frame uint64 - // failed says a page could not be opened: the previews are native from then on. - failed bool + // failed says a page could not be opened: the previews are native from then on. siteFailed + // says an HTML file's page could not: HTML files are text from then on. + failed, siteFailed bool // remote fetches the web images of every Markdown page, native or not. remote *webpreview.Remote // open opens a page; nil is webpreview.Open. Tests replace it. @@ -106,7 +112,11 @@ func (a *App) openPreviewPage(config webpreview.Config, alive func() bool) *prev } view, err := open(config) if err != nil { - a.previews.failed = true + if config.Page == webpreview.SitePage { + a.previews.siteFailed = true + } else { + a.previews.failed = true + } a.emit(operationFailedLevel, operationFailedEvent, operationFailedFields("web_preview_open", err)) return nil } diff --git a/desktop/internal/workbench/viewer_image.go b/desktop/internal/workbench/viewer_image.go index acd6ee9874..634ab1930c 100644 --- a/desktop/internal/workbench/viewer_image.go +++ b/desktop/internal/workbench/viewer_image.go @@ -87,6 +87,8 @@ type viewerBar struct { // zoom is the image's, nil for a file without one; zoomTo takes what its buttons ask. zoom *imageZoom zoomTo func(zoomRequest) + // actions declares the buttons of what the bar is over, after the zoom; nil has none. + actions func() // path is the file the actions open in the system's application and reveal, close closes // its tab; a bar without path has neither. path string @@ -106,6 +108,9 @@ func (a *App) viewerToolbar(c ui.C, bar viewerBar) { if bar.zoom != nil && bar.zoom.known() { a.viewerZoom(c, *bar.zoom, bar.zoomTo) } + if bar.actions != nil { + bar.actions() + } if bar.path == "" { return } diff --git a/docs/viva-migration.md b/docs/viva-migration.md index ff4f9ca944..0a0575a22a 100644 --- a/docs/viva-migration.md +++ b/docs/viva-migration.md @@ -363,7 +363,7 @@ | `editor-line-operations` | 行注释、复制、删除与上下移动 | 必须迁移 | 本分支新增 | 完成 | — | | `vim-mode` | Vim 模式与命令状态 | 必须迁移 | 缺/实现 | 完成 | `workbench/vim_mode.go` | | `lsp-status-logs` | LSP 状态栏控制与按服务器查看日志 | 必须迁移 | 实现/缺 | 部分 | — | -| `embedded-viewers` | HTML、SVG、媒体、PDF 与二进制预览 | 必须迁移 | 实现/实现 | 未开始 | — | +| `embedded-viewers` | HTML、SVG、媒体、PDF 与二进制预览 | 必须迁移 | 实现/实现 | 部分 | `workbench/viewer_web.go`、`svg_preview.go`、`html_preview.go`;音视频播放未做 | ### 设置(3) @@ -525,7 +525,7 @@ MCP 管理随 Agent 对话失去消费者后,本轮整块删除,后续重新 | 单实例与项目窗口注册 | Windows `tauri_plugin_single_instance`、`project_window_registry.rs`;macOS `MacProcessLifecycle.swift` | 必须迁移 | 未找到;`workspace-open-switch` 当前只保留一个项目 | | 崩溃报告收集 | macOS `MacCrashReportCollector.swift` | 平台专属(macOS) | 未找到(`signal_guard_darwin.go` 仅为信号保护) | | Git Shelf(搁置) | macOS `ShelveService.swift`;Windows `shelf_storage.rs` | 必须迁移 | 未找到 | -| HTML 预览打印/缩放 | macOS `HTMLPreviewPrint.swift`、`HTMLPreviewZoom.swift` | 放弃(依赖 WebKit,Viva 无嵌入网页;2026-11-10 确认) | 未找到 | +| HTML 预览打印/缩放 | macOS `HTMLPreviewPrint.swift`、`HTMLPreviewZoom.swift` | 放弃(2026-11-10 确认;当时 Viva 无嵌入网页。2026-11-14 起 Viva 有 HTML 预览,但 web view 没有打印和页面缩放接口,需要时先在 Viva fork 补接口) | 未找到 | | 开发版配置迁入(Dev 取 Stable 配置) | macOS `MacDevelopmentProfileMigration.swift`;Windows `profile_migration.rs` | 放弃(内部并行试用用;新客户端与旧 Lithe 的关系见下文数据清单开头) | 未找到 | ## 旧客户端数据来源清单 diff --git a/scripts/desktop/build-desktop-core.sh b/scripts/desktop/build-desktop-core.sh index 88466b3df6..de781b4a33 100755 --- a/scripts/desktop/build-desktop-core.sh +++ b/scripts/desktop/build-desktop-core.sh @@ -28,9 +28,11 @@ native_path() { } PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" -# Lithe-core-rust #41 (branch feat/markdown-outline, not yet merged): markdown.outline outlines -# the headings of Markdown source as a document-symbol tree for the Structure tool window. It is -# on top of #40, squash-merged into main: the update.delta.cleanup_failed event, which the +# Lithe-core-rust #42, squash-merged into main: htmlPreview.site names the +# folder an HTML file is previewed from as a static site, and htmlPreview.resolveRequest decides +# what each request of the preview serves. It is on top of #41, squash-merged into main: +# markdown.outline outlines the headings of Markdown source as a document-symbol tree for the +# Structure tool window. It is on top of #40, squash-merged into main: the update.delta.cleanup_failed event, which the # desktop logs when it cannot remove the application a delta update rebuilt in the temporary # directory. It is on top of #39, squash-merged into main: plugins.installed.lifecycle keeps one # enabled plugin per language server language; installed versions carry languageServers, and @@ -79,7 +81,7 @@ PINNED_CORE_REPOSITORY="https://github.com/Lithe-IDEA/Lithe-core-rust.git" # the contract, plugin guides, reference and SDKs live only in shared/plugins; on top of #16 (reported Git queries folded in the console), # #15 (git.write cherryPick, revert and reset fields), #14 (word-level changed ranges of diff # rows), #13, #8, #7, #6 and #4. -PINNED_CORE_REVISION="b0e19d5d03e6ff438c4476ceb2bbfb238e782bb3" +PINNED_CORE_REVISION="f88bc49562fbc5066dfb8783054611ee4e80e348" PROFILE="debug" while [[ $# -gt 0 ]]; do case "$1" in diff --git a/shared/i18n/locales/en-US.json b/shared/i18n/locales/en-US.json index 57b424f4e8..b93ef16bee 100644 --- a/shared/i18n/locales/en-US.json +++ b/shared/i18n/locales/en-US.json @@ -11131,7 +11131,12 @@ "desktop.viewer.imageFailed": "Could not load this image", "desktop.viewer.close": "Close", "desktop.viewer.tooLarge": "This file is too large to show here. Open it in the system's default application.", - "desktop.svg.tooLarge": "This SVG file is too large to preview." + "desktop.svg.tooLarge": "This SVG file is too large to preview.", + "desktop.htmlPreview.back": "Back", + "desktop.htmlPreview.forward": "Forward", + "desktop.htmlPreview.reload": "Reload", + "desktop.htmlPreview.tooLarge": "This HTML file is too large to preview.", + "desktop.htmlPreview.failed": "This HTML file can't be previewed." }, "overrides": { "windows": { diff --git a/shared/i18n/locales/zh-CN.json b/shared/i18n/locales/zh-CN.json index 8b921995ef..377f6ef216 100644 --- a/shared/i18n/locales/zh-CN.json +++ b/shared/i18n/locales/zh-CN.json @@ -11131,7 +11131,12 @@ "desktop.viewer.imageFailed": "无法载入此图片", "desktop.viewer.close": "关闭", "desktop.viewer.tooLarge": "此文件过大,无法在此显示,请用系统默认应用打开。", - "desktop.svg.tooLarge": "此 SVG 文件过大,无法预览。" + "desktop.svg.tooLarge": "此 SVG 文件过大,无法预览。", + "desktop.htmlPreview.back": "后退", + "desktop.htmlPreview.forward": "前进", + "desktop.htmlPreview.reload": "重新加载", + "desktop.htmlPreview.tooLarge": "此 HTML 文件过大,无法预览。", + "desktop.htmlPreview.failed": "无法预览此 HTML 文件。" }, "overrides": { "macos": { diff --git a/shared/i18n/messages.json b/shared/i18n/messages.json index 89a221898d..951d22b90b 100644 --- a/shared/i18n/messages.json +++ b/shared/i18n/messages.json @@ -105850,6 +105850,41 @@ "platforms": [ "desktop" ] + }, + { + "id": "desktop.htmlPreview.back", + "description": "HTML preview bar: button that goes back in the page's history", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.htmlPreview.forward", + "description": "HTML preview bar: button that goes forward in the page's history", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.htmlPreview.reload", + "description": "HTML preview bar: button that loads the page again", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.htmlPreview.tooLarge", + "description": "HTML preview beside the editor: shown instead of the page when the text is too large", + "platforms": [ + "desktop" + ] + }, + { + "id": "desktop.htmlPreview.failed", + "description": "HTML preview beside the editor: shown instead of the page when the folder it is served from could not be found", + "platforms": [ + "desktop" + ] } ] } diff --git a/shared/platform-feature-matrix/features/embedded-viewers.json b/shared/platform-feature-matrix/features/embedded-viewers.json index 3428e1b6ec..501f938f0f 100644 --- a/shared/platform-feature-matrix/features/embedded-viewers.json +++ b/shared/platform-feature-matrix/features/embedded-viewers.json @@ -18,7 +18,13 @@ "desktop/internal/webpreview/assets/image.js", "desktop/internal/workbench/viewer_test.go", "desktop/internal/workbench/svg_preview_test.go", - "desktop/internal/webpreview/webpreview_test.go" + "desktop/internal/webpreview/webpreview_test.go", + "desktop/internal/workbench/html_preview.go", + "desktop/internal/webpreview/site.go", + "desktop/internal/core/html_preview.go", + "desktop/internal/workbench/html_preview_test.go", + "desktop/internal/webpreview/site_test.go", + "desktop/internal/core/html_preview_test.go" ] }, "windows": { @@ -36,11 +42,17 @@ "desktop/internal/webpreview/assets/image.js", "desktop/internal/workbench/viewer_test.go", "desktop/internal/workbench/svg_preview_test.go", - "desktop/internal/webpreview/webpreview_test.go" + "desktop/internal/webpreview/webpreview_test.go", + "desktop/internal/workbench/html_preview.go", + "desktop/internal/webpreview/site.go", + "desktop/internal/core/html_preview.go", + "desktop/internal/workbench/html_preview_test.go", + "desktop/internal/webpreview/site_test.go", + "desktop/internal/core/html_preview_test.go" ] }, "owner": "Editor", - "verification": "分别打开 HTML、SVG、图片、PDF 和二进制文件,验证缩放、错误和源文件返回。 两端将 .html 默认打开程序改成文本编辑器,再点击 HTML 浏览器按钮,确认仍打开默认网页浏览器中的磁盘文件;覆盖中文、空格、# 文件名和无默认浏览器失败提示。 在 Windows 的 Web Viewer 标签中浏览几页后,用 Navigate 菜单或 Ctrl+Alt+←/→ 确认先在网页历史中后退/前进,到达网页历史起点后再次后退回到之前的代码位置。 在 macOS 的 HTML 预览中验证内嵌浏览器:后退/前进/刷新(Shift 强制刷新)、地址栏输入本地路径和网址、−/+/百分比和 ⌘+/⌘−/⌘0 页面缩放(跳转页面后保持)、内容溢出时常驻纵横滚动条、锚点与相对链接在预览内跳转、module 脚本与 fetch 可读取工作区文件、alert/confirm/prompt 与文件选择弹窗、开发者工具可开关;本地隐藏文件和密钥文件不能被页面读取。Windows 的 iframe 预览尚无对应能力。 在 macOS 的 HTML 预览中继续验证:页面有焦点时按 ⌘F 打开查找条,输入文字后页面内选中并高亮匹配项,⌘G / ⇧⌘G 与 Return / ⇧Return 前进后退并回绕,没有匹配时显示“No matches”,Esc 关闭后键盘回到页面;用默认键位,页面有焦点时按 ⌘F / ⌘G / ⇧⌘G 打开并驱动的是预览的查找条而不是编辑器的查找(应用键位监听器对页面的缩放、查找、打印按键让路);分屏时焦点在编辑器里按 ⌘F / ⌘G / ⌘P 仍由编辑器处理。右键点击链接、图片和页面空白处:可以复制链接地址和检查元素,没有“在新窗口打开”,页面空白处的菜单有 Print… 与 Export as PDF…;⌘P 打开作为窗口 sheet 的打印面板,导出 PDF 得到整页的单页 PDF,取消保存面板不写文件。摄像头和麦克风:在 Info.plist 带 NSCameraUsageDescription 与 NSMicrophoneUsageDescription 的构建里,页面调用 getUserMedia 弹出写明页面名称和设备的确认框(默认按钮是 Don’t Allow),页面每次加载后的第一次调用都会询问(同一页面里再次调用是否再询问取决于 WebKit 是否复用已批准的授权,记录实测结果);允许后地址栏右侧出现红色摄像头 / 麦克风指示,点击可暂停(变灰)或停止,页面里的轨道随之静音或结束;没有这两项说明的构建里 navigator.mediaDevices 不存在,页面拿不到设备也不会弹出系统权限框。Lithe 自己的页面(Markdown 预览、Monaco 编辑器和 diff、发行说明)调用 getUserMedia 一律被拒绝且不弹窗,源码扫描测试保证每个 WKWebView 都有人回答摄像头 / 麦克风请求、授权只出现在 WebMediaCapture.swift。地理位置和剪贴板读取使用 WebKit 自带的确认,未单独验证。 自动回归:./scripts/macos/test/test-macos.sh --filter HTMLPreview(真实 WKWebView 覆盖查找、打印、导出 PDF、右键菜单、WebAssembly、经真实应用键位监听器的页面快捷键放行,以及 WebKit 模拟摄像头 / 麦克风下的授权、静音与停止),界面尚未在运行的应用里手动验收。 Viva 新桌面端:分别打开 PNG、JPEG、GIF、WebP、BMP、TIFF、HEIC 图片,确认 34 点工具栏显示文件名、“宽 × 高 · 大小”和 −/百分比/+ 缩放,打开时按留 24 点边距适配且不放大小图,缩放范围为适配比例与 25% 中较小者到 400%、每步 25%,点击百分比回到 100%,Ctrl/⌘ 加滚轮围绕指针缩放,16 点棋盘格背景随深浅主题变化;解码失败显示“无法显示”与“用外部应用打开”,超过 64 MiB 显示过大提示。打开 PDF 确认用系统 web 引擎内置的 PDF 查看器显示并可翻页、缩放,页内链接交给系统浏览器;没有 web 引擎时提示用外部应用打开。打开 SVG 确认左侧源码、右侧图片,标签栏末尾三态切换源码 / 两者 / 仅图片;编辑后约 150 毫秒更新图片且保持缩放与滚动位置,改成无法绘制的内容时保留上一张图片,从未绘制成功时显示失败;超过 4 MiB 不绘制。Windows 需实机确认 WebView2 能否解码 TIFF/HEIC(不能时应落到失败提示)以及自定义协议下的 PDF 查看器。自动回归:scripts/desktop/desktop-go.sh test ./internal/workbench ./internal/webpreview -run 'Viewer|SVG|ImageFit|ImageCanvas|Checkerboard|Serves|Navigation|ReadFile' -count=1。", + "verification": "分别打开 HTML、SVG、图片、PDF 和二进制文件,验证缩放、错误和源文件返回。 两端将 .html 默认打开程序改成文本编辑器,再点击 HTML 浏览器按钮,确认仍打开默认网页浏览器中的磁盘文件;覆盖中文、空格、# 文件名和无默认浏览器失败提示。 在 Windows 的 Web Viewer 标签中浏览几页后,用 Navigate 菜单或 Ctrl+Alt+←/→ 确认先在网页历史中后退/前进,到达网页历史起点后再次后退回到之前的代码位置。 在 macOS 的 HTML 预览中验证内嵌浏览器:后退/前进/刷新(Shift 强制刷新)、地址栏输入本地路径和网址、−/+/百分比和 ⌘+/⌘−/⌘0 页面缩放(跳转页面后保持)、内容溢出时常驻纵横滚动条、锚点与相对链接在预览内跳转、module 脚本与 fetch 可读取工作区文件、alert/confirm/prompt 与文件选择弹窗、开发者工具可开关;本地隐藏文件和密钥文件不能被页面读取。Windows 的 iframe 预览尚无对应能力。 在 macOS 的 HTML 预览中继续验证:页面有焦点时按 ⌘F 打开查找条,输入文字后页面内选中并高亮匹配项,⌘G / ⇧⌘G 与 Return / ⇧Return 前进后退并回绕,没有匹配时显示“No matches”,Esc 关闭后键盘回到页面;用默认键位,页面有焦点时按 ⌘F / ⌘G / ⇧⌘G 打开并驱动的是预览的查找条而不是编辑器的查找(应用键位监听器对页面的缩放、查找、打印按键让路);分屏时焦点在编辑器里按 ⌘F / ⌘G / ⌘P 仍由编辑器处理。右键点击链接、图片和页面空白处:可以复制链接地址和检查元素,没有“在新窗口打开”,页面空白处的菜单有 Print… 与 Export as PDF…;⌘P 打开作为窗口 sheet 的打印面板,导出 PDF 得到整页的单页 PDF,取消保存面板不写文件。摄像头和麦克风:在 Info.plist 带 NSCameraUsageDescription 与 NSMicrophoneUsageDescription 的构建里,页面调用 getUserMedia 弹出写明页面名称和设备的确认框(默认按钮是 Don’t Allow),页面每次加载后的第一次调用都会询问(同一页面里再次调用是否再询问取决于 WebKit 是否复用已批准的授权,记录实测结果);允许后地址栏右侧出现红色摄像头 / 麦克风指示,点击可暂停(变灰)或停止,页面里的轨道随之静音或结束;没有这两项说明的构建里 navigator.mediaDevices 不存在,页面拿不到设备也不会弹出系统权限框。Lithe 自己的页面(Markdown 预览、Monaco 编辑器和 diff、发行说明)调用 getUserMedia 一律被拒绝且不弹窗,源码扫描测试保证每个 WKWebView 都有人回答摄像头 / 麦克风请求、授权只出现在 WebMediaCapture.swift。地理位置和剪贴板读取使用 WebKit 自带的确认,未单独验证。 自动回归:./scripts/macos/test/test-macos.sh --filter HTMLPreview(真实 WKWebView 覆盖查找、打印、导出 PDF、右键菜单、WebAssembly、经真实应用键位监听器的页面快捷键放行,以及 WebKit 模拟摄像头 / 麦克风下的授权、静音与停止),界面尚未在运行的应用里手动验收。 Viva 新桌面端:分别打开 PNG、JPEG、GIF、WebP、BMP、TIFF、HEIC 图片,确认 34 点工具栏显示文件名、“宽 × 高 · 大小”和 −/百分比/+ 缩放,打开时按留 24 点边距适配且不放大小图,缩放范围为适配比例与 25% 中较小者到 400%、每步 25%,点击百分比回到 100%,Ctrl/⌘ 加滚轮围绕指针缩放,16 点棋盘格背景随深浅主题变化;解码失败显示“无法显示”与“用外部应用打开”,超过 64 MiB 显示过大提示。打开 PDF 确认用系统 web 引擎内置的 PDF 查看器显示并可翻页、缩放,页内链接交给系统浏览器;没有 web 引擎时提示用外部应用打开。打开 SVG 确认左侧源码、右侧图片,标签栏末尾三态切换源码 / 两者 / 仅图片;编辑后约 150 毫秒更新图片且保持缩放与滚动位置,改成无法绘制的内容时保留上一张图片,从未绘制成功时显示失败;超过 4 MiB 不绘制。Windows 需实机确认 WebView2 能否解码 TIFF/HEIC(不能时应落到失败提示)以及自定义协议下的 PDF 查看器。打开工作区里的 HTML 文件,确认左侧源码、右侧页面,标签栏末尾三态切换源码 / 两者 / 仅预览;页面按工作区为根加载相对路径的样式、脚本、图片和 module 脚本,fetch 能读工作区文件,fetch('/.env') 与私钥文件得到 403;编辑后约 150 毫秒页面重新加载并回到原来的滚动位置,未保存的修改也显示;工具栏的后退、前进、重新加载可用,“在浏览器中打开”先保存再用系统浏览器打开磁盘文件;页面里点到站外的 https 链接和 mailto 用系统应用打开、页面停在原处,脚本自动跳到站外的导航被取消,window.open 到站外每秒最多打开一次;页面里的 Cookie 和 localStorage 关闭预览后不保留,也不和其他 HTML 文件共享;超过 8 MiB 显示过大提示。Windows 需实机确认:WebView2 101 以下打不开时只有 HTML 文件改为源码、其他预览不受影响;以 / 开头的绝对路径目前找不到文件(Viva 限制)。自动回归:scripts/desktop/desktop-go.sh test ./internal/workbench ./internal/webpreview ./internal/core -run 'Viewer|SVG|HTML|Site|ImageFit|ImageCanvas|Checkerboard|Serves|Navigation|ReadFile' -count=1。", "legacy": { "revision": "5a54c41aa37a4e6e6b68918a4b05765b9dd07a36", "macos": { @@ -87,5 +99,5 @@ "verificationStatus": "pending" } }, - "notes": "Viva:图片、PDF 与二进制文件以查看器标签打开,SVG 以源码加图片的双栏打开。有系统 web 引擎(macOS WKWebView、Windows WebView2)时,图片和 SVG 显示在内嵌的图片页,规则与旧 macOS 查看器一致(工具栏、适配、缩放步长与范围、棋盘格);PDF 用引擎自带的 PDF 查看器。Linux 没有 web 引擎:图片由 Viva 自行解码绘制(PNG、JPEG、GIF,同一套缩放规则),PDF 提示用外部应用打开,SVG 只显示源码。音频、视频仍提示用外部应用打开,其他二进制文件显示前 64 KiB 的十六进制。尚未接入 HTML 浏览器预览和媒体播放。legacy 是迁移前基线,不代表当前实现。" + "notes": "Viva:图片、PDF 与二进制文件以查看器标签打开,SVG 以源码加图片的双栏打开。有系统 web 引擎(macOS WKWebView、Windows WebView2)时,图片和 SVG 显示在内嵌的图片页,规则与旧 macOS 查看器一致(工具栏、适配、缩放步长与范围、棋盘格);PDF 用引擎自带的 PDF 查看器。Linux 没有 web 引擎:图片由 Viva 自行解码绘制(PNG、JPEG、GIF,同一套缩放规则),PDF 提示用外部应用打开,SVG 只显示源码。音频、视频仍提示用外部应用打开,其他二进制文件显示前 64 KiB 的十六进制。HTML 文件以源码加页面的双栏打开,页面在单独的 lithe-site 协议和临时存储里按静态站点加载,每个请求由 Core 的 htmlPreview.resolveRequest 决定;比旧 macOS 内嵌浏览器少地址栏、缩放、查找、开发者工具、JavaScript 对话框、下载和打印,主框架不跳到远程网页。尚未接入媒体播放。legacy 是迁移前基线,不代表当前实现。" }