Skip to content

Commit f88bc49

Browse files
authored
feat(project): htmlPreview 命令决定 HTML 文件预览的站点根目录与每个请求服务的内容 (#42)
* feat(project): htmlPreview 命令决定 HTML 文件预览站点的根目录与每个请求服务的内容 新增 htmlPreview.site 与 htmlPreview.resolveRequest:站点根目录与 markdown.resolveReference 的范围一致;请求按字面和解析符号链接后都必须留在根目录内,隐藏路径与密钥、证书文件拒绝,文档本身由编辑器文本服务。 * feat(project): htmlPreview.site 同时给出文档按扩展名应服务的内容类型 * test(project): htmlPreview 命令改由共享 fixture html-preview-v1.json 描述,契约登记内嵌 HTML 预览 分发器测试读 rust/fixtures/editor/html-preview-v1.json:工作区里的页面、隐藏目录里的页面、工作区之外的页面三组用例,以及相对路径的 invalid_request。桌面端测试读同一份 fixture。 application-boundary.md 新增 Embedded HTML preview 一节;External HTML preview 改为当前桌面端的行为:先保存未保存的修改再用系统浏览器打开,范围含 .xhtml 和 .svg。
1 parent 1dbc244 commit f88bc49

10 files changed

Lines changed: 859 additions & 17 deletions

File tree

‎rust/contracts/application-boundary.md‎

Lines changed: 20 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -175,11 +175,26 @@ resources are released. A cancelled UI waiter cannot cancel another window's wai
175175

176176
### External HTML preview
177177

178-
Both products open an existing local `.html` / `.htm` document in the system's
179-
configured web browser, independently of the file type's default editor. The
180-
browser reads the saved file; this action does not save buffers or start a web
181-
server. File URLs preserve Unicode and reserved characters. Browser discovery
182-
and launch belong to platform adapters, and launch failures are shown to the user.
178+
The desktop app opens an existing local `.html`, `.htm`, `.xhtml` or `.svg`
179+
document in the system's configured web browser, independently of the file
180+
type's default editor. The browser reads the file on disk, so the document's
181+
unsaved changes are saved first; this action does not start a web server. File
182+
URLs preserve Unicode and reserved characters. Browser discovery and launch
183+
belong to platform adapters, and launch failures are shown to the user.
184+
185+
### Embedded HTML preview
186+
187+
Where the platform has a web engine, `.html`, `.htm` and `.xhtml` documents open
188+
as editable text with their page beside it, in the editor, split and preview
189+
modes of SVG documents. The page shows the editor's current text, unsaved edits
190+
included, and loads its other files as a static site whose root and requests
191+
`htmlPreview.site` and `htmlPreview.resolveRequest` decide. The page runs the
192+
document's scripts, so the host serves only what those commands answer, never
193+
writes through the site, keeps none of the page's storage once the preview
194+
closes, and opens navigation away from the site with the link policy of
195+
`markdown.resolveReference`. Where the page cannot be opened, HTML documents are
196+
text alone and other previews are unaffected. The behavior fixture is
197+
[`html-preview-v1.json`](../fixtures/editor/html-preview-v1.json).
183198

184199
## Document Lifecycle Contract
185200

‎rust/contracts/rust-core-api.md‎

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -553,6 +553,8 @@ or removing a command fails until the table changes in the same commit.
553553
| `markdown.render` | Renders and sanitizes shared Markdown |
554554
| `markdown.outline` | Outlines the headings of shared Markdown as a document-symbol tree |
555555
| `markdown.resolveReference` | Decides what a link or an image of a rendered Markdown document points at |
556+
| `htmlPreview.site` | Names the folder an HTML file is previewed from and the file's address in it |
557+
| `htmlPreview.resolveRequest` | Decides what one request of an HTML preview serves |
556558
| `keymap.parseContext` | Compile a bounded boolean shortcut context (from `lithe-core-rules`) |
557559
| `keymap.evaluateContext` | Evaluate a precompiled shortcut context (from `lithe-core-rules`) |
558560
| `keymap.analyzeConflicts` | Find conflicts among the final layered shortcut bindings (from `lithe-core-rules`) |
@@ -5596,6 +5598,61 @@ the preview's.
55965598

55975599
Shared examples: `rust/fixtures/editor/markdown-outline-v1.json`.
55985600

5601+
## HTML file preview
5602+
5603+
An HTML file is previewed as a static site, so a page loads its stylesheets,
5604+
scripts, images, fonts, media and neighbouring pages the way a static web server
5605+
would serve them. Both commands accept:
5606+
5607+
```json
5608+
{
5609+
"documentPath": "/workspace/site/index.html",
5610+
"workspaceRoot": "/workspace"
5611+
}
5612+
```
5613+
5614+
`workspaceRoot` is optional and sets the site's root exactly as it sets the
5615+
scope of `markdown.resolveReference`: the workspace for a document inside it,
5616+
otherwise the document's folder. `htmlPreview.site` returns
5617+
`{ "root": "/workspace", "address": "site/index.html", "mime": "text/html; charset=utf-8" }`;
5618+
`address` is the document's path from the root with each segment
5619+
percent-encoded, which the frontend appends to the address it serves the site
5620+
from, and `mime` is the content type the document is served as, by its
5621+
extension like the site's other files. A `documentPath` that is not absolute is
5622+
`invalid_request`.
5623+
5624+
`htmlPreview.resolveRequest` adds `"path"`, the requested path from the root as
5625+
the web engine reports it: percent-decoded, `/`-separated, without query or
5626+
fragment, and empty for the root. Core does not decode it again. The response is
5627+
tagged by `kind`:
5628+
5629+
| kind | fields | the frontend serves |
5630+
| --- | --- | --- |
5631+
| `document` | — | The editor's text of the document as the site's `mime`, so unsaved edits show |
5632+
| `file` | `path`, `mime` | The canonical file `path`, read without following another link, as `mime` |
5633+
| `directory` | — | A page that sends the browser on to the folder's `index.html` |
5634+
| `denied` | — | HTTP 403 |
5635+
| `none` | — | HTTP 404 |
5636+
5637+
The path resolves lexically from the root and must stay inside it before and
5638+
after Core resolves symbolic links; a segment holding `\`, `:` or NUL is
5639+
`none`. A path that reaches the document, under any name, is `document`. A
5640+
hidden name (one starting with `.`) is `denied`, except the leading folders the
5641+
document's own folder shares, so a page inside `.github/pages` can load its
5642+
neighbours but not `.git/config`. A file with a key or certificate extension
5643+
(`jks`, `key`, `keystore`, `p12`, `pem`, `pfx`) is `denied`. Otherwise an
5644+
existing regular file is `file`, a folder whose `index.html` is a regular file
5645+
inside the root is `directory`, and anything else is `none`. `mime` comes from
5646+
the file's extension, with text types in UTF-8 and
5647+
`application/octet-stream` for an unknown one.
5648+
5649+
The page runs the document's scripts, so frontends trust nothing it requests:
5650+
they serve only what this command answers, never write through the site, and
5651+
handle top-level navigation away from it with the link policy of
5652+
`markdown.resolveReference`.
5653+
5654+
Shared examples: `rust/fixtures/editor/html-preview-v1.json`.
5655+
55995656
### Structured logging of recoverable LSP maintenance warnings
56005657

56015658
`lsp.pollEvents` log observations may carry the existing `error` object even at

‎rust/crates/core/src/protocol/command.rs‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,11 @@ pub enum CoreCommand {
131131
/// Decides what a link or an image of a rendered Markdown document points at
132132
/// (`markdown.resolveReference`).
133133
MarkdownResolveReference,
134+
/// Finds the site an HTML file is previewed as and the document's address in it
135+
/// (`htmlPreview.site`).
136+
HtmlPreviewSite,
137+
/// Decides what one request of an HTML preview's site serves (`htmlPreview.resolveRequest`).
138+
HtmlPreviewResolveRequest,
134139
/// Editor reducers: workbench state, text edits, find, navigation and preferences (`editor.*`).
135140
Editor(EditorCommand),
136141
/// Applies one transition to the rearrangeable workbench chrome: stripe, title bar and status bar
@@ -1191,6 +1196,8 @@ impl CoreCommand {
11911196
"markdown.render" => Some(Self::MarkdownRender),
11921197
"markdown.outline" => Some(Self::MarkdownOutline),
11931198
"markdown.resolveReference" => Some(Self::MarkdownResolveReference),
1199+
"htmlPreview.site" => Some(Self::HtmlPreviewSite),
1200+
"htmlPreview.resolveRequest" => Some(Self::HtmlPreviewResolveRequest),
11941201
"keymap.parseContext" => Some(Self::Keymap(KeymapCommand::ParseContext)),
11951202
"keymap.evaluateContext" => Some(Self::Keymap(KeymapCommand::EvaluateContext)),
11961203
"keymap.analyzeConflicts" => Some(Self::Keymap(KeymapCommand::AnalyzeConflicts)),

‎rust/crates/core/src/runtime/dispatcher.rs‎

Lines changed: 41 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,9 @@
44
//! child module named after it; the remaining small families dispatch here.
55
66
use crate::project::{
7-
self, DocumentLifecycleRequest, FileReadRequest, FileWriteRequest, MarkdownOutlineRequest,
8-
MarkdownReferenceRequest, MarkdownRenderRequest,
7+
self, DocumentLifecycleRequest, FileReadRequest, FileWriteRequest, HtmlPreviewRequest,
8+
HtmlPreviewSiteRequest, MarkdownOutlineRequest, MarkdownReferenceRequest,
9+
MarkdownRenderRequest,
910
};
1011
use crate::protocol::{CoreCommand, CoreError, CoreRequest, CoreResponse, ErrorCode, GitCommand};
1112
use lithe_github::{NormalizeResponseRequest, ParseRemoteRequest, RequestPlanRequest};
@@ -492,6 +493,44 @@ fn execute_parsed(mut parsed: CoreRequest, document: Option<&str>) -> CoreRespon
492493
Err(error) => CoreResponse::failure(id, error),
493494
}
494495
}
496+
CoreCommand::HtmlPreviewSite => {
497+
let site = serde_json::from_value::<HtmlPreviewSiteRequest>(parsed.payload)
498+
.map_err(|error| {
499+
CoreError::new(
500+
ErrorCode::InvalidRequest,
501+
"Invalid HTML preview site request",
502+
)
503+
.with_details(error.to_string())
504+
})
505+
.and_then(|request| {
506+
project::html_preview_site(request).ok_or_else(|| {
507+
CoreError::new(
508+
ErrorCode::InvalidRequest,
509+
"HTML preview document must be an absolute file path",
510+
)
511+
})
512+
});
513+
match site {
514+
Ok(site) => CoreResponse::success(
515+
id,
516+
serde_json::to_value(site).expect("HTML preview site should encode"),
517+
),
518+
Err(error) => CoreResponse::failure(id, error),
519+
}
520+
}
521+
CoreCommand::HtmlPreviewResolveRequest => {
522+
match serde_json::from_value::<HtmlPreviewRequest>(parsed.payload).map_err(|error| {
523+
CoreError::new(ErrorCode::InvalidRequest, "Invalid HTML preview request")
524+
.with_details(error.to_string())
525+
}) {
526+
Ok(request) => CoreResponse::success(
527+
id,
528+
serde_json::to_value(project::resolve_html_preview_request(request))
529+
.expect("HTML preview resource should encode"),
530+
),
531+
Err(error) => CoreResponse::failure(id, error),
532+
}
533+
}
495534
CoreCommand::Lsp(command) => lsp::dispatch(command, id, parsed.payload),
496535
CoreCommand::NetworkProxyPolicy => {
497536
match serde_json::from_value::<lithe_network::NetworkProxyPolicyRequest>(parsed.payload)

‎rust/crates/core/src/runtime/request_trace.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,6 +156,7 @@ pub(crate) fn is_hot(method: &str) -> bool {
156156
| "markdown.render"
157157
| "markdown.outline"
158158
| "markdown.resolveReference"
159+
| "htmlPreview.resolveRequest"
159160
| "workspace.classifyVisibility"
160161
| "workspace.visibilityDefaults"
161162
| "lsp.syncDocument"

‎rust/crates/core/src/tests/project.rs‎

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -998,6 +998,100 @@ fn markdown_resolve_reference_command_answers_links_and_resources() {
998998
);
999999
}
10001000

1001+
#[test]
1002+
fn html_preview_commands_match_shared_fixture() {
1003+
let fixture: Value = serde_json::from_str(include_str!(
1004+
"../../../../fixtures/editor/html-preview-v1.json"
1005+
))
1006+
.expect("HTML preview fixture should decode");
1007+
let top = temporary_root("html-preview");
1008+
let _ = fs::remove_dir_all(&top);
1009+
struct Cleanup(std::path::PathBuf);
1010+
impl Drop for Cleanup {
1011+
fn drop(&mut self) {
1012+
let _ = fs::remove_dir_all(&self.0);
1013+
}
1014+
}
1015+
let _cleanup = Cleanup(top.clone());
1016+
let root = top.join("workspace");
1017+
let under = |relative: &str| {
1018+
relative
1019+
.split('/')
1020+
.filter(|name| !name.is_empty())
1021+
.fold(root.clone(), |path, name| path.join(name))
1022+
};
1023+
for entry in fixture["files"].as_array().expect("fixture files") {
1024+
let entry = entry.as_str().expect("file entry");
1025+
let path = under(entry);
1026+
if entry.ends_with('/') {
1027+
fs::create_dir_all(&path).expect("fixture folder should be creatable");
1028+
} else {
1029+
fs::create_dir_all(path.parent().expect("file folder"))
1030+
.expect("fixture folder should be creatable");
1031+
fs::write(&path, "x").expect("fixture file should write");
1032+
}
1033+
}
1034+
let call = |command: &str, payload: Value| -> Value {
1035+
let request = serde_json::json!({ "id": "html", "command": command, "payload": payload });
1036+
serde_json::from_str(&execute_json(
1037+
&serde_json::to_string(&request).expect("HTML preview request should encode"),
1038+
))
1039+
.expect("HTML preview response should be JSON")
1040+
};
1041+
1042+
for case in fixture["cases"].as_array().expect("fixture cases") {
1043+
let name = case["name"].as_str().expect("case name");
1044+
let mut payload = serde_json::json!({
1045+
"documentPath": under(case["document"].as_str().expect("case document")).to_string_lossy()
1046+
});
1047+
if case["inWorkspace"] == true {
1048+
payload["workspaceRoot"] = Value::from(root.to_string_lossy().into_owned());
1049+
}
1050+
let site = call("htmlPreview.site", payload.clone());
1051+
assert_eq!(site["ok"], true, "{name}: {site}");
1052+
let want = &case["site"];
1053+
assert_eq!(
1054+
site["data"]["root"],
1055+
under(want["root"].as_str().expect("site root"))
1056+
.to_string_lossy()
1057+
.as_ref(),
1058+
"{name}"
1059+
);
1060+
assert_eq!(site["data"]["address"], want["address"], "{name}");
1061+
assert_eq!(site["data"]["mime"], want["mime"], "{name}");
1062+
1063+
for request in case["requests"].as_array().expect("case requests") {
1064+
let path = request["path"].as_str().expect("request path");
1065+
payload["path"] = Value::from(path);
1066+
let response = call("htmlPreview.resolveRequest", payload.clone());
1067+
assert_eq!(response["ok"], true, "{name}: {path}: {response}");
1068+
let mut want = serde_json::json!({ "kind": request["kind"] });
1069+
if let Some(file) = request["file"].as_str() {
1070+
want["path"] = Value::from(
1071+
fs::canonicalize(under(file))
1072+
.expect("canonical fixture file")
1073+
.to_string_lossy()
1074+
.into_owned(),
1075+
);
1076+
want["mime"] = request["mime"].clone();
1077+
}
1078+
assert_eq!(response["data"], want, "{name}: {path}");
1079+
}
1080+
}
1081+
1082+
for document in fixture["invalidDocuments"]
1083+
.as_array()
1084+
.expect("invalid documents")
1085+
{
1086+
let response = call(
1087+
"htmlPreview.site",
1088+
serde_json::json!({ "documentPath": document }),
1089+
);
1090+
assert_eq!(response["ok"], false, "{document}: {response}");
1091+
assert_eq!(response["error"]["code"], "invalid_request", "{document}");
1092+
}
1093+
}
1094+
10011095
#[test]
10021096
fn search_matches_shared_fixture_semantics() {
10031097
let fixture = fixture();

0 commit comments

Comments
 (0)