Visual Studio Code, rebuilt in Rust
Rust
//! releaseNotesEditor.ts and update.contribution.ts `ShowReleaseNotesAction`: a release's notes in one webview
//! editor, "Release Notes: <version>", with upstream's styles and the "Show release notes after an update" checkbox.
//! The notes are the body of the GitHub release `v<version>` under product.json `releaseNotesUrl` (port/notes.md
//! "Update feed"), where upstream reads code.visualstudio.com/raw/v<major>_<minor>.md.
// No `kb(...)` labels, tryouts, highlights video, code-setting links, TOC navigation or code block
// tokens: they serve vscode-docs markup, which a GitHub release body does not have.
use std::path::Path;
use anyhow::ensure;
use gpui::{Context, Task, Window};
use serde_json::{Value, json};
use super::Workbench;
use super::markdown_document::{Sanitizer, highlight_markdown_code, render_markdown_document};
use super::webview_panels::{WEBVIEW_PANEL_SCHEME, WebviewPanel};
use crate::commands::Outcome;
use crate::editor::TextDocument;
/// The `openWebview` view type of the release notes editor.
const RELEASE_NOTES_VIEW_TYPE: &str = "releaseNotes";
const HANDLE: &str = "release-notes";
const EDITOR_SOURCE: &str = include_str!(concat!(env!("VSCODE_SRC"), "/src/vs/workbench/contrib/update/browser/releaseNotesEditor.ts"));
const MARKDOWN_SOURCE: &str = include_str!(concat!(env!("VSCODE_SRC"), "/src/vs/workbench/contrib/markdown/browser/markdownDocumentRenderer.ts"));
/// renderReleaseNotesMarkdown's `sanitizerConfig` (the port has no `code-setting` links).
const SANITIZER: Sanitizer = Sanitizer { link_protocols: Some(&["http", "https", "command"]), media_protocols: &["http", "https"], allow_relative_media: true };
impl Workbench {
pub(super) fn register_release_notes_commands(&mut self) {
self.commands.register("update.showCurrentReleaseNotes", |workbench, args, window, cx| {
let product_version = crate::product::display_version();
let version = args.first().and_then(Value::as_str).map_or(product_version, str::to_owned);
let shown = workbench.show_release_notes(release_notes_url(), version, window, cx);
// `ShowReleaseNotesAction.run`: the notes that cannot be shown open in the browser.
cx.spawn(async move |_, cx| {
if shown.await.is_err() {
let _ = cx.update(|cx| cx.open_url(release_notes_url()));
}
})
.detach();
Outcome::done()
});
self.commands.register("developer.showCurrentFileAsReleaseNotes", |workbench, _, window, cx| {
let Some((file, folder)) = workbench.editors.active().map(|editor| {
let document = editor.document();
(document.lines.join("\n"), document.path.parent().unwrap_or(Path::new("/")).to_owned())
}) else {
return Outcome::error("Cannot open the current file as Release Notes");
};
let text = file.find('#').map_or("", |start| &file[start..]).to_owned();
let version = crate::product::display_version();
let base = format!("https://file+.vscode-resource.vscode-cdn.net{}/", super::media_preview::encode_path(&folder));
let roots = json!([{ "scheme": "file", "path": folder }]);
workbench.open_release_notes(&version, &text, &base, roots, window, cx);
Outcome::done()
});
}
/// `ReleaseNotesManager.show`: fetches the version's notes from the releases URL, then shows them; fails when
/// they cannot be read.
pub(super) fn show_release_notes(&mut self, releases: &str, version: String, window: &mut Window, cx: &mut Context<Self>) -> Task<anyhow::Result<()>> {
let releases = releases.to_owned();
let fetch = cx.background_executor().spawn({
let (releases, version) = (releases.clone(), version.clone());
async move { fetch_release_notes(&releases, &version) }
});
cx.spawn_in(window, async move |workbench, cx| {
let text = fetch.await?;
let base = format!("{}/", releases.trim_end_matches('/'));
workbench.update_in(cx, |workbench, window, cx| workbench.open_release_notes(&version, &text, &base, json!([]), window, cx))
})
}
/// `showContent`: one release notes editor, opened in the active group or revealed there with the new notes.
fn open_release_notes(&mut self, version: &str, text: &str, base: &str, roots: Value, window: &mut Window, cx: &mut Context<Self>) {
let title = format!("Release Notes: {version}");
let html = release_notes_page(text, base, self.setting("update.showReleaseNotes") == true, |code, lang| highlight_markdown_code(&self.languages, &self.theme, code, lang), &self.tokens_css());
let options = json!({ "enableScripts": true, "localResourceRoots": roots, "enableCommandUris": ["workbench.action.openSettings"] });
if let Some(panel) = self.webview_panel_mut(HANDLE) {
(panel.title, panel.html, panel.content_options) = (title, html, options);
if let Some(webview) = &panel.webview {
webview.set_local_resource_roots(super::webview_panels::local_resource_roots(&panel.content_options));
}
panel.update_content();
self.reveal_webview_panel(HANDLE, &json!({ "viewColumn": -1 }), window, cx);
} else {
let path = std::path::PathBuf::from(format!("webview-panel/webview-{RELEASE_NOTES_VIEW_TYPE}-{HANDLE}"));
let document = TextDocument::from_text(WEBVIEW_PANEL_SCHEME, &path, "", "utf8".into(), None, &self.languages, &self.settings.lock().unwrap());
let mut panel = WebviewPanel::new(HANDLE.into(), WEBVIEW_PANEL_SCHEME.into(), path, RELEASE_NOTES_VIEW_TYPE, title, &Value::Null, options, false, None);
panel.html = html;
panel.find_enabled = true;
self.webview_panels.panels.push(panel);
self.leave_locked_group(WEBVIEW_PANEL_SCHEME, &document.path);
self.editors.open(document, false);
}
self.editors_changed(cx);
self.focus_webview_panel(HANDLE, window, cx);
}
/// Whether the editor is the release notes editor (its tab icon is `Codicon.vscode`).
pub(super) fn is_release_notes(&self, path: &Path) -> bool {
self.webview_panels.panels.iter().any(|panel| panel.is_release_notes() && panel.path == path)
}
/// The page's messages: `releaseNotesReady` asks for the checkbox's state, `showReleaseNotes` sets it.
pub(super) fn handle_release_notes_message(&mut self, message: &Value) {
match message["type"].as_str() {
Some("releaseNotesReady") => self.update_release_notes_checkbox(),
Some("showReleaseNotes") if message["value"].is_boolean() => self.update_setting("update.showReleaseNotes", message["value"].clone()),
_ => {}
}
}
/// `updateCheckboxWebview`.
fn update_release_notes_checkbox(&mut self) {
let value = self.setting("update.showReleaseNotes") == true;
if let Some(webview) = self.webview_panel_mut(HANDLE).and_then(|panel| panel.webview.as_mut()) {
webview.send("message", json!({ "message": json!({ "type": "showReleaseNotes", "value": value }).to_string(), "buffers": [] }));
}
}
}
impl WebviewPanel {
pub(super) fn is_release_notes(&self) -> bool {
self.handle == HANDLE
}
}
fn release_notes_url() -> &'static str {
crate::product::get("releaseNotesUrl").as_str().unwrap_or_default()
}
/// The GitHub API's release `v<version>` of a releases URL: `https://github.com/<owner>/<repo>/releases` becomes
/// `https://api.github.com/repos/<owner>/<repo>/releases/tags/v<version>`; another host keeps its path.
fn release_api_url(releases_url: &str, version: &str) -> String {
format!("{}/tags/v{version}", releases_url.trim_end_matches('/').replacen("https://github.com/", "https://api.github.com/repos/", 1))
}
/// `loadReleaseNotes`: the release's body, which must start with `# ` as upstream's notes do, else under the
/// release's name as that heading.
fn fetch_release_notes(releases_url: &str, version: &str) -> anyhow::Result<String> {
let (status, body) = crate::update::fetch_feed(&release_api_url(releases_url, version))?;
ensure!(status == 200, "Failed to fetch release notes");
let release: Value = serde_json::from_slice(&body)?;
let notes = release["body"].as_str().unwrap_or_default();
ensure!(!notes.trim().is_empty(), "Invalid release notes");
if notes.strip_prefix('#').is_some_and(|rest| rest.starts_with(char::is_whitespace)) {
return Ok(notes.to_owned());
}
let name = release["name"].as_str().filter(|name| !name.is_empty()).map_or_else(|| format!("v{version}"), str::to_owned);
Ok(format!("# {name}\n\n{notes}"))
}
/// `renderBody`: upstream's page, its styles read from the shipped source, and the checkbox after the `h1`.
fn release_notes_page(markdown: &str, base: &str, show_release_notes: bool, highlight: impl Fn(&str, &str) -> String, tokens_css: &str) -> String {
let nonce = format!("{:x}", std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |elapsed| elapsed.as_nanos()));
let styles = release_notes_styles();
let body = render_markdown_document(markdown, &SANITIZER, highlight);
let label = json!("Show release notes after an update").to_string().replace('<', "\\u003c");
format!(
r#"<!DOCTYPE html>
<html>
<head>
<base href="{base}" >
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src https: data:; media-src https:; style-src 'nonce-{nonce}' https://code.visualstudio.com; script-src 'nonce-{nonce}';">
<style nonce="{nonce}">{styles}</style>
<style id="release-notes-tokenization" nonce="{nonce}">{tokens_css}</style>
</head>
<body>
{body}
<script nonce="{nonce}">
const vscode = acquireVsCodeApi();
const container = document.createElement('p');
container.style.display = 'flex';
container.style.alignItems = 'center';
const input = document.createElement('input');
input.type = 'checkbox';
input.id = 'showReleaseNotes';
input.checked = {show_release_notes};
container.appendChild(input);
const label = document.createElement('label');
label.htmlFor = 'showReleaseNotes';
label.textContent = {label};
container.appendChild(label);
const beforeElement = document.querySelector("body > h1")?.nextElementSibling;
if (beforeElement) {{
document.body.insertBefore(container, beforeElement);
}} else {{
document.body.appendChild(container);
}}
window.addEventListener('message', event => {{
if (event.data.type === 'showReleaseNotes') {{
input.checked = event.data.value;
}}
}});
input.addEventListener('change', event => {{
vscode.postMessage({{ type: 'showReleaseNotes', value: input.checked }}, '*');
}});
vscode.postMessage({{ type: 'releaseNotesReady' }});
</script>
</body>
</html>"#
)
}
/// The `<style>` of `renderBody` with `DEFAULT_MARKDOWN_STYLES` in place.
fn release_notes_styles() -> String {
let between = |source: &'static str, start: &str, end: &str| -> &'static str {
let from = source.find(start).expect("upstream source has the marker") + start.len();
&source[from..from + source[from..].find(end).expect("upstream source has the end marker")]
};
let markdown = between(MARKDOWN_SOURCE, "DEFAULT_MARKDOWN_STYLES = `", "`");
between(EDITOR_SOURCE, "<style nonce=\"${nonce}\">", "</style>").replace("${DEFAULT_MARKDOWN_STYLES}", markdown)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_github_releases_url_reads_the_releases_api() {
assert_eq!(release_api_url("https://github.com/rokartur/vsrustium/releases", "1.148.0"), "https://api.github.com/repos/rokartur/vsrustium/releases/tags/v1.148.0");
assert_eq!(release_api_url("http://127.0.0.1:8080/o/r/releases/", "1.148.0-insider"), "http://127.0.0.1:8080/o/r/releases/tags/v1.148.0-insider");
}
#[test]
fn the_page_has_upstreams_styles_the_notes_and_the_checkbox() {
let page = release_notes_page("# VSRustium 1.148.0\n\n## Fixes\n\n", "https://github.com/rokartur/vsrustium/releases/", true, |code, _| code.to_owned(), "");
assert!(page.contains("<base href=\"https://github.com/rokartur/vsrustium/releases/\" >"));
assert!(page.contains("max-width: 980px;") && page.contains("padding: 10px 20px;"), "renderBody's and DEFAULT_MARKDOWN_STYLES' rules");
assert!(!page.contains("${"), "no template placeholder left");
assert!(page.contains(">VSRustium 1.148.0</h1>"));
assert!(page.contains("src=\"images/a.png\""), "relative media resolves against the base");
assert!(page.contains("input.checked = true;") && page.contains("\"Show release notes after an update\""));
}
}