From fcef18048a530f56fd67fa0caba58fd611ddb96f Mon Sep 17 00:00:00 2001 From: LU XIANGRUI <1078666705@qq.com> Date: Wed, 18 Nov 2026 17:12:54 +0900 Subject: [PATCH] fix(web): HTML preview follows File Types associations (#4144) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The browser bar, Built-in Preview and Open in Browser were gated on a fixed extension list, and the built-in server chose Content-Type by extension, so a file associated with HTML in Settings › File Types (or via Override File Type) had no preview, and one moved away from HTML kept it. The frontend now decides with hasFileType (override, user patterns, then built-in extensions not removed — the order of LanguageRegistry::detect), open tabs update when File Types change, and web_url serves a file the backend detects as HTML as text/html (also fixes .shtml being served as application/octet-stream). Co-authored-by: wildcatDownstairs <26499420+wildcatDownstairs@users.noreply.github.com> --- crates/ide-host/src/ops/web.rs | 13 +++- crates/ide-web/src/server.rs | 49 +++++++++++-- src/bindings.ts | 5 +- .../settings/__tests__/fileTypes.test.ts | 10 ++- src/features/settings/fileTypesRuntime.ts | 6 +- src/features/web/browsers.test.ts | 71 +++++++++++++++++++ src/features/web/browsers.ts | 16 ++++- src/features/web/index.ts | 11 ++- src/platform/fileTypes.ts | 31 ++++++++ 9 files changed, 192 insertions(+), 20 deletions(-) create mode 100644 src/features/web/browsers.test.ts diff --git a/crates/ide-host/src/ops/web.rs b/crates/ide-host/src/ops/web.rs index 00b117645..53ce1b88c 100644 --- a/crates/ide-host/src/ops/web.rs +++ b/crates/ide-host/src/ops/web.rs @@ -47,12 +47,19 @@ pub async fn serves_page(url: &str) -> bool { response.status().is_success() && html } -/// The built-in server's URL for `path` (started on first use). +/// The built-in server's URL for `path` (started on first use). A file whose language is +/// HTML (Settings › File Types can make it so) is served as a page, whatever its extension. #[command(trust = always)] pub async fn web_url(host: &Host, window: &str, path: IpcPath) -> IdeResult { // Under the window's project when it holds the file. - let root = host.project(window).ok().map(|p| p.root.clone()); - host.web.url_for(root.as_deref(), &path).await + let project = host.project(window).ok(); + let root = project.as_ref().map(|p| p.root.as_path()); + let languages = project.as_ref().map_or(&host.languages, |p| &p.languages); + if matches!(languages.detect(&path, None).as_str(), "html" | "django-html") { + host.web.page_url_for(root, &path).await + } else { + host.web.url_for(root, &path).await + } } #[cfg(test)] diff --git a/crates/ide-web/src/server.rs b/crates/ide-web/src/server.rs index 42feccc78..48019b478 100644 --- a/crates/ide-web/src/server.rs +++ b/crates/ide-web/src/server.rs @@ -1,8 +1,8 @@ use ide_core::{IdeError, IdeResult}; use percent_encoding::{AsciiSet, CONTROLS, percent_decode_str, utf8_percent_encode}; -use std::collections::HashMap; +use std::collections::{HashMap, HashSet}; use std::path::{Path, PathBuf}; -use std::sync::Arc; +use std::sync::{Arc, Mutex, PoisonError}; use std::time::Duration; use tokio::io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader}; use tokio::net::{TcpListener, TcpStream}; @@ -42,6 +42,9 @@ struct Root { dir: PathBuf, port: u16, serves: Serves, + /// Files handed out by [`WebServer::page_url_for`], as requested. They stay here until + /// the app quits, even if the file stops being HTML: only its content type depends on it. + pages: Mutex>, } /// What of its directory a root serves. @@ -87,6 +90,18 @@ impl WebServer { /// A project that is the home folder, or holds it, is no boundary to serve whole: its /// files are served like files outside a project. pub async fn url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult { + Ok(self.locate(root, file).await?.1) + } + + /// [`Self::url_for`] of a file that is an HTML page whatever its name (Settings › File + /// Types): it is served as HTML from now on. + pub async fn page_url_for(&self, root: Option<&Path>, file: &Path) -> IdeResult { + let (served, url) = self.locate(root, file).await?; + served.pages.lock().unwrap_or_else(PoisonError::into_inner).insert(file.to_path_buf()); + Ok(url) + } + + async fn locate(&self, root: Option<&Path>, file: &Path) -> IdeResult<(Arc, String)> { let (base, serves) = match root { Some(r) if file.starts_with(r) && file != r && self.holds_home(r).await != Some(true) => (r, Serves::All), _ => { @@ -102,7 +117,7 @@ impl WebServer { url.push('/'); url.push_str(&enc(&c.as_os_str().to_string_lossy())); } - Ok(url) + Ok((root, url)) } /// Whether `dir` is the home folder or lies above it; `None` when that cannot be told. @@ -153,6 +168,7 @@ impl WebServer { dir: dir.to_path_buf(), port, serves, + pages: Mutex::default(), }); tokio::spawn(accept(listener, root.clone())); tracing::info!("built-in web server on 127.0.0.1:{} for {}", root.port, dir.display()); @@ -320,7 +336,9 @@ async fn resolve(root: &Root, target: &str) -> Response { _ => NOT_FOUND, }; } - Response::File { path: real, len: meta.len(), mime: content_type(&file) } + let page = root.pages.lock().unwrap_or_else(PoisonError::into_inner).contains(&file); + let mime = if page { HTML } else { content_type(&file) }; + Response::File { path: real, len: meta.len(), mime } } /// `path` with every symlink resolved, if `root` serves it: it lies inside `real_root` @@ -343,10 +361,12 @@ fn dec(s: &str) -> Option { percent_decode_str(s).decode_utf8().ok().map(|s| s.into_owned()) } +const HTML: &str = "text/html; charset=utf-8"; + fn content_type(path: &Path) -> &'static str { let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); match ext.as_str() { - "html" | "htm" | "xhtml" => "text/html; charset=utf-8", + "html" | "htm" | "xhtml" => HTML, "css" => "text/css; charset=utf-8", "js" | "mjs" | "cjs" => "text/javascript; charset=utf-8", "json" | "map" | "webmanifest" => "application/json; charset=utf-8", @@ -395,6 +415,25 @@ mod tests { out } + #[tokio::test] + async fn a_page_is_html_whatever_its_name() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("site"); + std::fs::create_dir_all(&root).unwrap(); + std::fs::write(root.join("page.foo"), "

hi

").unwrap(); + std::fs::write(root.join("other.foo"), "

no

").unwrap(); + let server = server(); + + let plain = server.url_for(Some(&root), &root.join("page.foo")).await.unwrap(); + assert!(get(&plain, None).await.contains("application/octet-stream")); + + let page = server.page_url_for(Some(&root), &root.join("page.foo")).await.unwrap(); + assert_eq!(page, plain); + assert!(get(&page, None).await.contains("Content-Type: text/html")); + let other = page.replace("page.foo", "other.foo"); + assert!(get(&other, None).await.contains("application/octet-stream"), "only the named file"); + } + #[tokio::test] async fn serves_project_files() { let dir = tempfile::tempdir().unwrap(); diff --git a/src/bindings.ts b/src/bindings.ts index 6107f6103..f04ffc907 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -1810,7 +1810,10 @@ export const commands = { webServesPage: (url: string) => typedError(__TAURI_INVOKE("web_serves_page", { url })), /** Paths in an HTML document or stylesheet that name no existing file. */ webUnresolvedReferences: (doc: DocId) => typedError(__TAURI_INVOKE("web_unresolved_references", { doc })), - /** The built-in server's URL for `path` (started on first use). */ + /** + * The built-in server's URL for `path` (started on first use). A file whose language is + * HTML (Settings › File Types can make it so) is served as a page, whatever its extension. + */ webUrl: (path: IpcPath) => typedError(__TAURI_INVOKE("web_url", { path })), windowCloseContext: () => __TAURI_INVOKE("window_close_context"), /** Release the opening window's reservation after navigation or cancellation. */ diff --git a/src/features/settings/__tests__/fileTypes.test.ts b/src/features/settings/__tests__/fileTypes.test.ts index 0da59f0bd..03538a236 100644 --- a/src/features/settings/__tests__/fileTypes.test.ts +++ b/src/features/settings/__tests__/fileTypes.test.ts @@ -1,12 +1,18 @@ import { beforeEach, describe, expect, it } from "vitest"; import type { LanguageInfo_Serialize as LanguageInfo, Settings } from "@/platform/ipc"; import { useProject } from "@/platform/project"; -import { effectivePatterns, removePattern, userFileType, validateFileTypes, wildcardMatch } from "@/platform/fileTypes"; +import { + effectivePatterns, + overrideKey, + removePattern, + userFileType, + validateFileTypes, + wildcardMatch, +} from "@/platform/fileTypes"; import { DEFAULT_SETTINGS, validateSettings } from "../model/schema"; import { openSettings, stage, stagedValue, useSettingsDialog } from "../model/staging"; import { applyPatternEdit } from "../pages/FileTypes"; import { CODE_STYLE_KEYS, copyScheme } from "../pages/editor/codeStyleScheme"; -import { overrideKey } from "../fileTypesRuntime"; const lang = (id: string, extensions: string[], filenames: string[] = []): LanguageInfo => ({ id, diff --git a/src/features/settings/fileTypesRuntime.ts b/src/features/settings/fileTypesRuntime.ts index d3793e219..2e844e111 100644 --- a/src/features/settings/fileTypesRuntime.ts +++ b/src/features/settings/fileTypesRuntime.ts @@ -6,6 +6,7 @@ import { executeAction, registerActions } from "@/platform/actions"; import { call, commands, isTauri, type LanguageInfo_Serialize as LanguageInfo } from "@/platform/ipc"; import { + overrideKey, sampleFileName, userFileType, validateFileTypeOverrides, @@ -31,11 +32,6 @@ function loadLanguages(): Promise { })); } -/** Settings key of a file: project-relative inside the project, else absolute. */ -export function overrideKey(path: string, root: string | null): string { - return root && path.startsWith(root + "/") ? path.slice(root.length + 1) : path; -} - function currentOverrides(): Record { return validateFileTypeOverrides( (useProject.getState().settings?.files as { fileTypeOverrides?: unknown } | undefined)?.fileTypeOverrides, diff --git a/src/features/web/browsers.test.ts b/src/features/web/browsers.test.ts new file mode 100644 index 000000000..b6ad75c6b --- /dev/null +++ b/src/features/web/browsers.test.ts @@ -0,0 +1,71 @@ +import { afterEach, describe, expect, it } from "vitest"; +import type { ProjectInfo, Settings } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; +import { textEditorWrapperFor, useTextEditorWrappers } from "@/workbench/contributions"; +import { isHtmlPath, isWebPath } from "./browsers"; +import { activate } from "./index"; + +const types = (patterns: string[], removedPatterns: string[] = []) => ({ patterns, removedPatterns, hashbangs: [] }); +const setFiles = (files: object) => + useProject.setState({ project: { root: "/p" } as ProjectInfo, settings: { files } as Settings }); +const toFoo = { fileTypes: { html: types(["*.foo"]) } }; +const movedAway = { fileTypes: { html: types([], ["*.html"]), plaintext: types(["*.html"]) } }; + +afterEach(() => useProject.setState({ project: null, settings: null })); + +describe("HTML files follow File Types", () => { + it.each<[string, object, string, boolean]>([ + ["default .html", {}, "/p/a.html", true], + ["default .htm", {}, "/p/a.htm", true], + ["default .xhtml", {}, "/p/a.xhtml", true], + ["default .shtml", {}, "/p/a.shtml", true], + ["upper-case default", {}, "/p/A.HTML", true], + ["no association", {}, "/p/a.foo", false], + ["a name without a dot", {}, "/p/html", false], + ["added extension", toFoo, "/p/a.foo", true], + ["added extension, other case", toFoo, "/p/A.FOO", true], + ["added file name", { fileTypes: { html: types(["PAGE"]) } }, "/p/PAGE", true], + ["added glob", { fileTypes: { html: types(["page.*"]) } }, "/p/page.txt", true], + ["extension given to another language", { fileTypes: { plaintext: types(["*.foo"]) } }, "/p/a.foo", false], + ["*.html moved to another language", movedAway, "/p/a.html", false], + ["*.html removed", { fileTypes: { html: types([], ["*.html"]) } }, "/p/a.html", false], + ["*.html removed keeps the others", { fileTypes: { html: types([], ["*.html"]) } }, "/p/a.htm", true], + ["override to HTML", { fileTypeOverrides: { "docs/a.txt": "html" } }, "/p/docs/a.txt", true], + ["override outside the project", { fileTypeOverrides: { "/x/a.txt": "html" } }, "/x/a.txt", true], + ["override to Django Template", { fileTypeOverrides: { "a.html": "django-html" } }, "/p/a.html", true], + ["override away from HTML", { fileTypeOverrides: { "a.html": "plaintext" } }, "/p/a.html", false], + ["override beats a pattern", { ...toFoo, fileTypeOverrides: { "a.foo": "plaintext" } }, "/p/a.foo", false], + ])("%s", (_name, files, path, expected) => { + setFiles(files); + expect(isHtmlPath(path)).toBe(expected); + expect(isWebPath(path)).toBe(expected); + }); + + it("keeps SVG files openable in a browser", () => { + setFiles({}); + expect(isHtmlPath("/p/a.svg")).toBe(false); + expect(isWebPath("/p/A.SVG")).toBe(true); + }); + + it("updates open tabs only when File Types change", () => { + const off = activate(); + const wrappers = () => useTextEditorWrappers.getState().wrappers; + try { + setFiles({}); + const before = wrappers(); + expect(textEditorWrapperFor(before, "/p/a.foo")).toBeUndefined(); + + setFiles({ autoSave: true }); + expect(wrappers()).toBe(before); + + setFiles(toFoo); + expect(wrappers()).not.toBe(before); + expect(textEditorWrapperFor(wrappers(), "/p/a.foo")?.id).toBe("web.html"); + + setFiles(movedAway); + expect(textEditorWrapperFor(wrappers(), "/p/a.html")).toBeUndefined(); + } finally { + off(); + } + }); +}); diff --git a/src/features/web/browsers.ts b/src/features/web/browsers.ts index 438bcf26a..291cb0ba3 100644 --- a/src/features/web/browsers.ts +++ b/src/features/web/browsers.ts @@ -1,14 +1,24 @@ /** Installed browsers, the built-in server's URLs, and per-file preview state. */ import { create } from "zustand"; import { executeAction } from "@/platform/actions"; +import { hasFileType } from "@/platform/fileTypes"; import { call, commands, isTauri, type Browser } from "@/platform/ipc"; +import { useProject } from "@/platform/project"; import { hasIcon } from "@/ui"; import { notifications } from "@/workbench/contributions"; +/** A Django template is an HTML file the banner in `djangoTemplates.ts` retyped: it keeps the preview. */ +const HTML_LANGUAGES = ["html", "django-html"]; +const HTML_EXTENSIONS = new Set(["html", "htm", "xhtml", "shtml"]); + +/** Files that get the browser bar and the built-in preview: HTML by Settings › File Types. */ +export function isHtmlPath(path: string): boolean { + const { settings, project } = useProject.getState(); + return hasFileType(path, HTML_LANGUAGES, HTML_EXTENSIONS, settings?.files, project?.root ?? null); +} + /** Files a browser can show (Open In › Browser). */ -export const isWebPath = (path: string) => /\.(html?|xhtml|shtml|svg)$/i.test(path); -/** Files that get the browser bar and the built-in preview. */ -export const isHtmlPath = (path: string) => /\.(html?|xhtml|shtml)$/i.test(path); +export const isWebPath = (path: string) => isHtmlPath(path) || /\.svg$/i.test(path); export const useBrowsers = create<{ list: Browser[] }>(() => ({ list: [] })); diff --git a/src/features/web/index.ts b/src/features/web/index.ts index 0462c367e..1342e5e5d 100644 --- a/src/features/web/index.ts +++ b/src/features/web/index.ts @@ -7,13 +7,14 @@ */ import { registerActions } from "@/platform/actions"; import { getContext } from "@/platform/context"; -import { basename } from "@/platform/project"; +import { basename, useProject } from "@/platform/project"; import { lazyComponent, type MenuItem } from "@/ui"; import { maybeEditorService, registerEditorBanner, registerMenuGroup, registerTextEditorWrapper, + useTextEditorWrappers, } from "@/workbench/contributions"; import { registerEditorContribution } from "@/editor/api"; import { djangoContentWatcher, djangoTemplateBanner } from "./djangoTemplates"; @@ -64,9 +65,17 @@ function browserMenu(path: string): MenuItem { }; } +const fileTypesKey = ({ settings }: ReturnType) => + JSON.stringify([settings?.files?.fileTypes, settings?.files?.fileTypeOverrides]); + export function activate(): () => void { void loadBrowsers(); const disposers = [ + // Open tabs gain or lose the browser bar and preview when File Types change. + useProject.subscribe((s, prev) => { + if (s.settings !== prev.settings && fileTypesKey(s) !== fileTypesKey(prev)) + useTextEditorWrappers.setState((w) => ({ wrappers: new Map(w.wrappers) })); + }), registerEditorBanner(djangoTemplateBanner), registerEditorContribution({ id: "web.djangoContent", order: 57, extensions: djangoContentWatcher }), registerTextEditorWrapper({ diff --git a/src/platform/fileTypes.ts b/src/platform/fileTypes.ts index 4d78c7874..bc073c089 100644 --- a/src/platform/fileTypes.ts +++ b/src/platform/fileTypes.ts @@ -54,6 +54,11 @@ export function validateFileTypeOverrides(raw: unknown): Record return out; } +/** Settings key of a file: project-relative inside the project, else absolute. */ +export function overrideKey(path: string, root: string | null): string { + return root && path.startsWith(root + "/") ? path.slice(root.length + 1) : path; +} + /** Built-in file name patterns of a language definition: `*.ext` and file names. */ export function builtinPatterns(lang: Pick): string[] { return [...lang.extensions.map((e) => `*.${e}`), ...(lang.filenames ?? [])]; @@ -158,6 +163,32 @@ export function userFileType(assoc: FileTypeAssociations, fileName: string): str return glob?.id ?? ext?.id ?? null; } +/** + * Whether Settings › File Types leave `path` in one of `languages`, decided without asking the + * backend. Same order as `LanguageRegistry::detect`: Override File Type, the user's patterns, + * then the built-in `extensions` they did not remove. Hashbangs and first lines need the content. + */ +export function hasFileType( + path: string, + languages: readonly string[], + extensions: ReadonlySet, + files: { fileTypes?: unknown; fileTypeOverrides?: unknown } | undefined, + root: string | null, +): boolean { + const assoc = validateFileTypes(files?.fileTypes); + const name = path.slice(path.lastIndexOf("/") + 1); + const assigned = + validateFileTypeOverrides(files?.fileTypeOverrides)[overrideKey(path, root)] ?? userFileType(assoc, name); + if (assigned) return languages.includes(assigned); + const dot = name.lastIndexOf("."); + if (dot < 0) return false; + const pattern = `*${name.slice(dot).toLowerCase()}`; + return ( + extensions.has(pattern.slice(2)) && + !languages.some((l) => assoc[l]?.removedPatterns.some((p) => p.toLowerCase() === pattern)) + ); +} + /** File name standing for a language when picking its icon (`x.py`). */ export function sampleFileName(lang: Pick): string | null { if (lang.extensions[0]) return `file.${lang.extensions[0]}`;