дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-03 08:43:07 +02:00
Порівняти коміти
| Автор | SHA1 | Дата | |
|---|---|---|---|
|
|
c3e0b8bd58 |
No files matched your search
@@ -34,7 +34,6 @@ on:
|
||||
- "src/editor/relatedProviders.ts"
|
||||
- "src/editor/core/cm/cornerInset.ts"
|
||||
- "src/editor/core/cm/iconArea.ts"
|
||||
- "src/editor/core/cm/inlineBg.ts"
|
||||
- "src/editor/core/cm/localAppearance.ts"
|
||||
- "src/editor/lsp/availability.ts"
|
||||
- "src/editor/lsp/diagnostics.ts"
|
||||
@@ -110,7 +109,7 @@ jobs:
|
||||
# ide-lsp/dap/run/sdk/tools.
|
||||
unused='^crates/(ide-agent|ide-analysis|ide-android|ide-cli|ide-clipboard|ide-coverage|ide-db|ide-docker|ide-fonts|ide-github|ide-mcp|ide-notebook|ide-profiler|ide-scaffold|ide-spell|ide-ssh|ide-vcs|ide-web)/'
|
||||
# The workflow's paths, less those handled per language below.
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|inlineBg|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
smoke='^(crates/|Cargo\.(toml|lock)$|src/features/(run|debugger|build|build-tools)/|src/platform/|src/workbench/|src/ui/|src/editor/(api|navigationProviders|refactorProviders|relatedProviders|core/cm/(cornerInset|iconArea|localAppearance)|lsp/(availability|diagnostics|files|hint|lsp|positions|snippet))\.ts$|src/bindings\.ts$|src/styles/tokens\.css$|src/test/setup\.ts$|src-tauri/icons/128x128\.png$|smoke/|vite\.config\.ts$|tsconfig\.json$|package\.json$|pnpm-(lock|workspace)\.yaml$|patches/|\.github/workflows/language-smoke\.yml$|\.github/tool-versions\.env$)'
|
||||
langs=""
|
||||
while read -r f; do
|
||||
case "$f" in
|
||||
|
||||
Створено
@@ -4166,7 +4166,6 @@ dependencies = [
|
||||
"ide-tools",
|
||||
"ide-vcs",
|
||||
"ide-vfs",
|
||||
"libsqlite3-sys",
|
||||
"parking_lot 0.12.5",
|
||||
"rustix",
|
||||
"semver",
|
||||
|
||||
@@ -115,7 +115,6 @@ reqwest = { version = "0.13", default-features = false, features = ["rustls-no-p
|
||||
rustls = { version = "0.23", default-features = false, features = ["ring", "std", "tls12", "logging"] }
|
||||
rustls-platform-verifier = "0.7"
|
||||
# Until SQLx releases its libsqlite3-sys 0.39 update (RUSTSEC-2026-0459).
|
||||
libsqlite3-sys = { version = "0.39", features = ["bundled"] }
|
||||
sqlx = { version = "0.9", git = "https://github.com/l0ng-ai/sqlx", rev = "9894985a1babc7e6bc0437da4fd43e3143184073", default-features = false, features = ["runtime-tokio", "tls-rustls-ring-webpki", "sqlite", "postgres", "mysql"] }
|
||||
tiberius = { version = "0.13", default-features = false, features = ["tds73", "rustls", "sql-browser-tokio"] }
|
||||
# Pure-Rust thin Oracle driver; pinned to the beta until it stabilizes.
|
||||
|
||||
@@ -15,7 +15,6 @@ ide-mcp.workspace = true
|
||||
ide-jsonrpc.workspace = true
|
||||
ide-vcs.workspace = true
|
||||
ide-tools = { path = "../ide-tools" }
|
||||
libsqlite3-sys.workspace = true
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
specta.workspace = true
|
||||
|
||||
@@ -247,71 +247,35 @@ pub fn codex_sessions(codex_home: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
sessions
|
||||
}
|
||||
|
||||
/// Whether `raw` is a YAML block-scalar header (`|`, `|-`, `|+`, `>`, `>-`, `>+`, with optional indent digit).
|
||||
fn is_yaml_block_header(raw: &str) -> bool {
|
||||
let mut chars = raw.chars();
|
||||
matches!(chars.next(), Some('|' | '>')) && chars.all(|c| matches!(c, '-' | '+') || c.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Unquotes a single-line YAML scalar value from Copilot's `workspace.yaml`.
|
||||
fn parse_yaml_inline_value(raw: &str) -> String {
|
||||
if raw.starts_with('"') {
|
||||
/// One scalar at the root of Copilot's `workspace.yaml`.
|
||||
///
|
||||
/// Copilot writes a flat mapping of scalar values. Most values are plain, while names can
|
||||
/// be JSON-compatible double-quoted YAML strings (including `\n`).
|
||||
fn yaml_scalar(line: &str) -> Option<(String, String)> {
|
||||
let (key, raw) = line.split_once(':')?;
|
||||
let key = key.trim();
|
||||
let raw = raw.trim();
|
||||
if key.is_empty() || raw.is_empty() || line.starts_with(char::is_whitespace) {
|
||||
return None;
|
||||
}
|
||||
let value = if raw.starts_with('"') {
|
||||
serde_json::from_str(raw).unwrap_or_else(|_| raw.trim_matches('"').to_owned())
|
||||
} else if raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2 {
|
||||
raw[1..raw.len() - 1].replace("''", "'")
|
||||
} else {
|
||||
raw.to_owned()
|
||||
}
|
||||
};
|
||||
Some((key.to_owned(), value))
|
||||
}
|
||||
|
||||
/// Metadata for one Copilot session, read without opening its potentially multi-gigabyte event log.
|
||||
/// Supports both inline scalars (`name: "Fix\nbug"`) and block scalars (`name: |-\n Fix\n bug`).
|
||||
fn copilot_metadata(path: &Path) -> Option<HashMap<String, String>> {
|
||||
let file = std::fs::File::open(path).ok()?;
|
||||
let mut lines = std::io::BufReader::new(file).lines().map_while(Result::ok).peekable();
|
||||
let mut metadata = HashMap::new();
|
||||
while let Some(line) = lines.next() {
|
||||
if line.is_empty() || line.starts_with(char::is_whitespace) || line.trim_start().starts_with('#') {
|
||||
continue;
|
||||
}
|
||||
let Some((key, raw)) = line.split_once(':') else { continue };
|
||||
let key = key.trim();
|
||||
let raw = raw.trim();
|
||||
if key.is_empty() {
|
||||
continue;
|
||||
}
|
||||
if is_yaml_block_header(raw) {
|
||||
let folded = raw.starts_with('>');
|
||||
let mut block = Vec::new();
|
||||
while let Some(next) = lines.peek() {
|
||||
if next.is_empty() || next.starts_with(' ') || next.starts_with('\t') {
|
||||
block.push(lines.next().unwrap_or_default());
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
while block.last().is_some_and(|l| l.trim().is_empty()) {
|
||||
block.pop();
|
||||
}
|
||||
let indent = block
|
||||
.iter()
|
||||
.filter(|l| !l.trim().is_empty())
|
||||
.map(|l| l.bytes().take_while(|&b| b == b' ').count())
|
||||
.min()
|
||||
.unwrap_or(0);
|
||||
let sep = if folded { " " } else { "\n" };
|
||||
let joined = block
|
||||
.iter()
|
||||
.map(|l| if l.len() >= indent { &l[indent..] } else { l.trim_start() })
|
||||
.collect::<Vec<_>>()
|
||||
.join(sep);
|
||||
if !joined.trim().is_empty() {
|
||||
metadata.insert(key.to_owned(), joined);
|
||||
}
|
||||
} else if !raw.is_empty() {
|
||||
metadata.insert(key.to_owned(), parse_yaml_inline_value(raw));
|
||||
}
|
||||
}
|
||||
let metadata = std::io::BufReader::new(file)
|
||||
.lines()
|
||||
.map_while(Result::ok)
|
||||
.filter_map(|line| yaml_scalar(&line))
|
||||
.collect::<HashMap<_, _>>();
|
||||
(!metadata.is_empty()).then_some(metadata)
|
||||
}
|
||||
|
||||
@@ -332,187 +296,11 @@ fn copilot_prompt(path: &Path) -> Option<String> {
|
||||
})
|
||||
}
|
||||
|
||||
struct SqliteDb(*mut libsqlite3_sys::sqlite3);
|
||||
|
||||
impl SqliteDb {
|
||||
fn open_readonly(path: &Path) -> Option<Self> {
|
||||
if !path.is_file() {
|
||||
return None;
|
||||
}
|
||||
let c_path = std::ffi::CString::new(path.to_str()?).ok()?;
|
||||
let mut raw: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
|
||||
let flags = libsqlite3_sys::SQLITE_OPEN_READONLY | libsqlite3_sys::SQLITE_OPEN_NOMUTEX;
|
||||
let rc = unsafe { libsqlite3_sys::sqlite3_open_v2(c_path.as_ptr(), &mut raw, flags, std::ptr::null()) };
|
||||
let guard = Self(raw);
|
||||
if rc != libsqlite3_sys::SQLITE_OK || raw.is_null() {
|
||||
return None;
|
||||
}
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_busy_timeout(raw, 200);
|
||||
}
|
||||
Some(guard)
|
||||
}
|
||||
|
||||
fn prepare(&self, sql: &str) -> Option<SqliteStmt> {
|
||||
let c_sql = std::ffi::CString::new(sql).ok()?;
|
||||
let mut stmt: *mut libsqlite3_sys::sqlite3_stmt = std::ptr::null_mut();
|
||||
let rc =
|
||||
unsafe { libsqlite3_sys::sqlite3_prepare_v2(self.0, c_sql.as_ptr(), -1, &mut stmt, std::ptr::null_mut()) };
|
||||
let guard = SqliteStmt(stmt);
|
||||
(rc == libsqlite3_sys::SQLITE_OK && !stmt.is_null()).then_some(guard)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SqliteDb {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_close(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct SqliteStmt(*mut libsqlite3_sys::sqlite3_stmt);
|
||||
|
||||
impl SqliteStmt {
|
||||
fn step(&self) -> bool {
|
||||
unsafe { libsqlite3_sys::sqlite3_step(self.0) == libsqlite3_sys::SQLITE_ROW }
|
||||
}
|
||||
|
||||
fn text(&self, col: std::ffi::c_int) -> Option<String> {
|
||||
unsafe {
|
||||
let ptr = libsqlite3_sys::sqlite3_column_text(self.0, col);
|
||||
if ptr.is_null() {
|
||||
return None;
|
||||
}
|
||||
let len = libsqlite3_sys::sqlite3_column_bytes(self.0, col);
|
||||
if len <= 0 {
|
||||
return None;
|
||||
}
|
||||
let bytes = std::slice::from_raw_parts(ptr, len as usize);
|
||||
std::str::from_utf8(bytes).ok().map(str::to_owned)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for SqliteStmt {
|
||||
fn drop(&mut self) {
|
||||
if !self.0.is_null() {
|
||||
unsafe {
|
||||
libsqlite3_sys::sqlite3_finalize(self.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Candidate VS Code Agent Host SQLite databases (`<user>/globalStorage/agent-host.db`),
|
||||
/// ordered oldest-first so a newer database wins when two editions share a session.
|
||||
fn vscode_agent_host_dbs(home: &Path) -> Vec<PathBuf> {
|
||||
let mut bases = vec![home.join("Library/Application Support"), home.join(".config"), home.join("AppData/Roaming")];
|
||||
let real_home = std::env::var_os("HOME").or_else(|| std::env::var_os("USERPROFILE"));
|
||||
if real_home.as_deref().is_some_and(|h| Path::new(h) == home) {
|
||||
for var in ["XDG_CONFIG_HOME", "APPDATA"] {
|
||||
if let Some(dir) = std::env::var_os(var).filter(|v| !v.is_empty()).map(PathBuf::from)
|
||||
&& !bases.contains(&dir)
|
||||
{
|
||||
bases.push(dir);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut dbs = Vec::new();
|
||||
for base in bases {
|
||||
for app in ["Code", "Code - Insiders"] {
|
||||
dbs.push(base.join(app).join("User/globalStorage/agent-host.db"));
|
||||
}
|
||||
}
|
||||
for server in [".vscode-server", ".vscode-server-insiders"] {
|
||||
dbs.push(home.join(server).join("data/User/globalStorage/agent-host.db"));
|
||||
}
|
||||
dbs.retain(|p| p.is_file());
|
||||
dbs.sort_by(|a, b| mtime(a).total_cmp(&mtime(b)));
|
||||
dbs
|
||||
}
|
||||
|
||||
fn is_generic_vscode_placeholder(title: &str, source: Option<&str>) -> bool {
|
||||
source != Some("user") && (title.eq_ignore_ascii_case("new session") || title.eq_ignore_ascii_case("new chat"))
|
||||
}
|
||||
|
||||
fn pick_vscode_chat_title(
|
||||
scs_title: Option<&str>,
|
||||
scs_source: Option<&str>,
|
||||
metadata_json: Option<&str>,
|
||||
payload_json: Option<&str>,
|
||||
) -> Option<String> {
|
||||
if let Some(t) = scs_title.map(str::trim).filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, scs_source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
for blob in [metadata_json, payload_json].into_iter().flatten() {
|
||||
let Ok(v) = serde_json::from_str::<serde_json::Value>(blob) else { continue };
|
||||
let summary = v.pointer("/data/summary").and_then(serde_json::Value::as_str).map(str::trim);
|
||||
let source = v.pointer("/data/titleSource").and_then(serde_json::Value::as_str);
|
||||
if let Some(t) = summary.filter(|t| !t.is_empty())
|
||||
&& !is_generic_vscode_placeholder(t, source)
|
||||
{
|
||||
return Some(t.to_owned());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
/// Session titles VS Code's Agent Host (`vscode-agent-host`) assigns to backing Copilot CLI
|
||||
/// sessions (`sdkSessionId` → summary or user rename), read from `agent-host.db` without writing.
|
||||
fn vscode_copilot_titles(home: Option<&Path>) -> HashMap<String, String> {
|
||||
const FULL_QUERY: &str = "\
|
||||
SELECT c.provider_data, scs.title, scs.title_source, c.metadata, s.payload \
|
||||
FROM chats_v2 c \
|
||||
LEFT JOIN session_chat_state scs \
|
||||
ON scs.session_uri = c.owner_session_uri AND scs.chat_uri = c.chat_uri \
|
||||
LEFT JOIN sessions_v2 s \
|
||||
ON s.session_uri = c.owner_session_uri \
|
||||
WHERE c.tombstoned = 0 \
|
||||
ORDER BY COALESCE(s.modified_time, 0) ASC, COALESCE(c.chat_order, 0) ASC";
|
||||
const FALLBACK_QUERY: &str = "\
|
||||
SELECT provider_data, NULL, NULL, metadata, NULL \
|
||||
FROM chats_v2 \
|
||||
WHERE tombstoned = 0";
|
||||
|
||||
let Some(home) = home else { return HashMap::new() };
|
||||
let mut titles = HashMap::new();
|
||||
for path in vscode_agent_host_dbs(home) {
|
||||
let Some(db) = SqliteDb::open_readonly(&path) else { continue };
|
||||
let Some(stmt) = db.prepare(FULL_QUERY).or_else(|| db.prepare(FALLBACK_QUERY)) else { continue };
|
||||
while stmt.step() {
|
||||
let Some(pdata) = stmt.text(0) else { continue };
|
||||
let Ok(pv) = serde_json::from_str::<serde_json::Value>(&pdata) else { continue };
|
||||
let Some(sdk_id) = pv.get("sdkSessionId").and_then(serde_json::Value::as_str).filter(|s| !s.is_empty())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let scs_title = stmt.text(1);
|
||||
let scs_source = stmt.text(2);
|
||||
let metadata = stmt.text(3);
|
||||
let payload = stmt.text(4);
|
||||
if let Some(title) = pick_vscode_chat_title(
|
||||
scs_title.as_deref(),
|
||||
scs_source.as_deref(),
|
||||
metadata.as_deref(),
|
||||
payload.as_deref(),
|
||||
) {
|
||||
titles.insert(sdk_id.to_owned(), title);
|
||||
}
|
||||
}
|
||||
}
|
||||
titles
|
||||
}
|
||||
|
||||
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by VS Code's
|
||||
/// Agent Host summary/rename (when started from VS Code), their recorded CLI name, or first prompt.
|
||||
/// Directories without an event log are unfinished sessions and are not listed.
|
||||
pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -> Vec<ExternalSession> {
|
||||
let mut pending: Vec<(ExternalSession, bool)> = std::fs::read_dir(copilot_home.join("session-state"))
|
||||
/// Copilot sessions of the project at `root`: `<config>/session-state/<id>`, titled by
|
||||
/// their recorded name or first prompt. Directories without an event log are unfinished
|
||||
/// sessions and are not listed.
|
||||
pub fn copilot_sessions(copilot_home: &Path, root: &Path) -> Vec<ExternalSession> {
|
||||
std::fs::read_dir(copilot_home.join("session-state"))
|
||||
.into_iter()
|
||||
.flatten()
|
||||
.flatten()
|
||||
@@ -528,28 +316,17 @@ pub fn copilot_sessions(copilot_home: &Path, home: Option<&Path>, root: &Path) -
|
||||
if !in_project(cwd.as_deref(), root) {
|
||||
return None;
|
||||
}
|
||||
let raw_name = metadata.get("name").map(String::as_str).map(str::trim).filter(|name| !name.is_empty());
|
||||
let cli_user_named = metadata.get("user_named").is_some_and(|v| v == "true")
|
||||
&& raw_name.is_some_and(|n| !n.eq_ignore_ascii_case("new session"));
|
||||
let title = raw_name
|
||||
let title = metadata
|
||||
.get("name")
|
||||
.map(String::as_str)
|
||||
.map(str::trim)
|
||||
.filter(|name| !name.is_empty())
|
||||
.map(short)
|
||||
.or_else(|| copilot_prompt(&events))
|
||||
.unwrap_or_else(|| format!("Copilot session {}", &session_id[..session_id.len().min(8)]));
|
||||
Some((
|
||||
ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) },
|
||||
cli_user_named,
|
||||
))
|
||||
Some(ExternalSession { provider: "copilot".to_owned(), session_id, title, cwd, updated_ms: mtime(&events) })
|
||||
})
|
||||
.collect();
|
||||
if !pending.is_empty() {
|
||||
let vscode_titles = vscode_copilot_titles(home);
|
||||
for (session, cli_user_named) in &mut pending {
|
||||
if !*cli_user_named && let Some(title) = vscode_titles.get(&session.session_id) {
|
||||
session.title = short(title);
|
||||
}
|
||||
}
|
||||
}
|
||||
pending.into_iter().map(|(s, _)| s).collect()
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
@@ -650,37 +427,13 @@ mod tests {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
assert!(claude_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(codex_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
assert!(copilot_sessions(&tmp.path().join("nope"), None, Path::new("/work")).is_empty());
|
||||
}
|
||||
|
||||
fn exec_sqlite(path: &Path, sql: &str) {
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
|
||||
let c_sql = std::ffi::CString::new(sql).unwrap();
|
||||
unsafe {
|
||||
let mut db: *mut libsqlite3_sys::sqlite3 = std::ptr::null_mut();
|
||||
assert_eq!(
|
||||
libsqlite3_sys::sqlite3_open_v2(
|
||||
c_path.as_ptr(),
|
||||
&mut db,
|
||||
libsqlite3_sys::SQLITE_OPEN_READWRITE | libsqlite3_sys::SQLITE_OPEN_CREATE,
|
||||
std::ptr::null(),
|
||||
),
|
||||
libsqlite3_sys::SQLITE_OK
|
||||
);
|
||||
assert_eq!(
|
||||
libsqlite3_sys::sqlite3_exec(db, c_sql.as_ptr(), None, std::ptr::null_mut(), std::ptr::null_mut()),
|
||||
libsqlite3_sys::SQLITE_OK
|
||||
);
|
||||
libsqlite3_sys::sqlite3_close(db);
|
||||
}
|
||||
assert!(copilot_sessions(&tmp.path().join("nope"), Path::new("/work")).is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lists_copilot_sessions_with_names_block_scalars_vscode_titles_and_prompt_fallbacks() {
|
||||
fn lists_copilot_sessions_with_names_and_prompt_fallbacks() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let copilot_home = tmp.path().join(".copilot");
|
||||
let session = copilot_home.join("session-state/copilot-1");
|
||||
let session = tmp.path().join("session-state/copilot-1");
|
||||
write(
|
||||
&session.join("events.jsonl"),
|
||||
&[
|
||||
@@ -694,71 +447,30 @@ mod tests {
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let block_scalar = copilot_home.join("session-state/copilot-block");
|
||||
write(&block_scalar.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
block_scalar.join("workspace.yaml"),
|
||||
"id: copilot-block\ncwd: /work/app\nname: |-\n check why excalidraw font\n is not displayed\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_renamed = copilot_home.join("session-state/copilot-vscode");
|
||||
write(
|
||||
&vscode_renamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "create a branch deng/session add Create Session"}})],
|
||||
);
|
||||
std::fs::write(
|
||||
vscode_renamed.join("workspace.yaml"),
|
||||
"id: copilot-vscode\ncwd: /work/app\nclient_name: vscode-agent-host\nname: create a branch deng/session add Create Session\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let vscode_placeholder = copilot_home.join("session-state/copilot-placeholder");
|
||||
write(&vscode_placeholder.join("events.jsonl"), &[json!({"type": "session.start", "data": {}})]);
|
||||
std::fs::write(
|
||||
vscode_placeholder.join("workspace.yaml"),
|
||||
"id: copilot-placeholder\ncwd: /work/app\nname: Greeting exchange\nuser_named: false\n",
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let unnamed = copilot_home.join("session-state/copilot-2");
|
||||
let unnamed = tmp.path().join("session-state/copilot-2");
|
||||
write(
|
||||
&unnamed.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "add a regression test"}})],
|
||||
);
|
||||
std::fs::write(unnamed.join("workspace.yaml"), "id: copilot-2\ncwd: /work/app\n").unwrap();
|
||||
|
||||
let empty = copilot_home.join("session-state/copilot-empty");
|
||||
let empty = tmp.path().join("session-state/copilot-empty");
|
||||
std::fs::create_dir_all(&empty).unwrap();
|
||||
std::fs::write(empty.join("workspace.yaml"), "id: copilot-empty\ncwd: /work/app\n").unwrap();
|
||||
|
||||
let other = copilot_home.join("session-state/copilot-other");
|
||||
let other = tmp.path().join("session-state/copilot-other");
|
||||
write(
|
||||
&other.join("events.jsonl"),
|
||||
&[json!({"type": "user.message", "data": {"content": "unrelated project"}})],
|
||||
);
|
||||
std::fs::write(other.join("workspace.yaml"), "id: copilot-other\ncwd: /other\n").unwrap();
|
||||
|
||||
exec_sqlite(
|
||||
&tmp.path().join(".config/Code/User/globalStorage/agent-host.db"),
|
||||
"CREATE TABLE sessions_v2 (session_uri TEXT PRIMARY KEY, payload TEXT, modified_time INTEGER);
|
||||
CREATE TABLE session_chat_state (session_uri TEXT, chat_uri TEXT, title TEXT, title_source TEXT);
|
||||
CREATE TABLE chats_v2 (chat_uri TEXT PRIMARY KEY, owner_session_uri TEXT, chat_order INTEGER, provider_data TEXT, metadata TEXT, tombstoned INTEGER);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs1', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs1', 'copilotcli:/vs1', 0, '{\"sdkSessionId\":\"copilot-vscode\"}', '{\"data\":{\"summary\":\"Session\",\"titleSource\":\"user\"}}', 0);
|
||||
INSERT INTO sessions_v2 VALUES ('copilotcli:/vs2', '{}', 100);
|
||||
INSERT INTO chats_v2 VALUES ('chat:/vs2', 'copilotcli:/vs2', 0, '{\"sdkSessionId\":\"copilot-placeholder\"}', '{\"data\":{\"summary\":\"New session\",\"titleSource\":\"auto\"}}', 0);",
|
||||
);
|
||||
|
||||
let sessions = copilot_sessions(&copilot_home, Some(tmp.path()), Path::new("/work"));
|
||||
assert_eq!(sessions.len(), 5);
|
||||
let sessions = copilot_sessions(tmp.path(), Path::new("/work"));
|
||||
assert_eq!(sessions.len(), 2);
|
||||
let mut by_id: HashMap<_, _> = sessions.into_iter().map(|s| (s.session_id.clone(), s)).collect();
|
||||
let named = by_id.remove("copilot-1").unwrap();
|
||||
assert_eq!((named.provider.as_str(), named.title.as_str()), ("copilot", "Fix parser and tests"));
|
||||
assert_eq!(named.cwd.as_deref(), Some("/work/app/api"));
|
||||
assert_eq!(by_id.remove("copilot-block").unwrap().title, "check why excalidraw font is not displayed");
|
||||
assert_eq!(by_id.remove("copilot-vscode").unwrap().title, "Session");
|
||||
assert_eq!(by_id.remove("copilot-placeholder").unwrap().title, "Greeting exchange");
|
||||
assert_eq!(by_id.remove("copilot-2").unwrap().title, "add a regression test");
|
||||
}
|
||||
|
||||
|
||||
@@ -1415,11 +1415,12 @@ impl AgentManager {
|
||||
if let Some(spec) = self.shared.spec("copilot")
|
||||
&& let Some(dir) = native::copilot::config_dir(&spec.env, home.as_deref())
|
||||
{
|
||||
out.extend(external::copilot_sessions(&dir, home.as_deref(), &root));
|
||||
out.extend(external::copilot_sessions(&dir, &root));
|
||||
}
|
||||
let known = self.imported_session_ids();
|
||||
out.retain(|s| !known.contains(&s.session_id));
|
||||
out.sort_by(|a, b| b.updated_ms.total_cmp(&a.updated_ms));
|
||||
out.truncate(50);
|
||||
out
|
||||
}
|
||||
|
||||
|
||||
@@ -730,7 +730,7 @@ impl CopilotShim {
|
||||
let history = match self.call("session.getMessages", json!({ "sessionId": session_id })).await {
|
||||
Ok(history) => history,
|
||||
Err(error) => {
|
||||
tracing::warn!("copilot session {session_id}: could not load history: {}", error.message);
|
||||
tracing::info!("copilot session {session_id}: could not load history: {}", error.message);
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
@@ -622,30 +622,6 @@ pub fn host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
apply_changes(std::env::vars_os().collect(), &child_env_changes(Some(dir))).into_iter()
|
||||
}
|
||||
|
||||
/// Whether `(key, value)` can go into a Windows environment block (`KEY=VALUE\0`
|
||||
/// entries, then a final `\0`). `CreateProcessW` / `NtCreateUserProcess` returns
|
||||
/// `ERROR_INVALID_PARAMETER` (os error 87) when an entry has an empty name or an
|
||||
/// interior NUL. That happens when a `REG_MULTI_SZ` user environment value is
|
||||
/// loaded into the process or re-read from the registry (#6806): the extra NUL
|
||||
/// is treated as an entry separator and leaves a fragment with no `=`.
|
||||
pub fn is_spawnable_env_pair(key: &OsStr, value: &OsStr) -> bool {
|
||||
!key.is_empty() && !contains_ascii(key, 0) && !contains_ascii(key, b'=') && !contains_ascii(value, 0)
|
||||
}
|
||||
|
||||
fn contains_ascii(s: &OsStr, byte: u8) -> bool {
|
||||
s.as_encoded_bytes().contains(&byte)
|
||||
}
|
||||
|
||||
/// [`host_vars`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars() -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars().filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`host_vars_in`] without pairs that a Windows PTY spawn would reject.
|
||||
pub fn spawnable_host_vars_in(dir: &Path) -> impl Iterator<Item = (OsString, OsString)> {
|
||||
host_vars_in(dir).filter(|(k, v)| is_spawnable_env_pair(k, v))
|
||||
}
|
||||
|
||||
/// [`std::env::var_os`] as a child should see it (see [`host_env`]), the login shell's value
|
||||
/// included when this process lacks the variable.
|
||||
pub fn host_var_os(key: impl AsRef<OsStr>) -> Option<OsString> {
|
||||
@@ -1264,35 +1240,6 @@ mod tests {
|
||||
assert!(host_vars_in(root).all(|(k, _)| k != "OPENIDEA_PROJECT_VAR"));
|
||||
}
|
||||
|
||||
fn os_from_bytes(bytes: &[u8]) -> OsString {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::ffi::OsStringExt;
|
||||
OsString::from_vec(bytes.to_vec())
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::ffi::OsStringExt;
|
||||
OsString::from_wide(&bytes.iter().copied().map(u16::from).collect::<Vec<_>>())
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn spawnable_env_pairs_reject_empty_keys_equals_and_interior_nuls() {
|
||||
let ok_key = OsString::from("PATH");
|
||||
let ok_val = OsString::from("/bin");
|
||||
assert!(is_spawnable_env_pair(&ok_key, &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new(""), &ok_val));
|
||||
assert!(!is_spawnable_env_pair(OsStr::new("FOO=BAR"), &ok_val));
|
||||
// A REG_MULTI_SZ value's interior NUL would split the environment block,
|
||||
// leaving a fragment with no `=` (#6806). An empty name is also rejected.
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b""), &os_from_bytes(b"132786")));
|
||||
assert!(!is_spawnable_env_pair(&ok_key, &os_from_bytes(b"1788051509\x00132786")));
|
||||
assert!(!is_spawnable_env_pair(&os_from_bytes(b"132786\x00"), &ok_val));
|
||||
assert!(spawnable_host_vars().all(|(k, v)| is_spawnable_env_pair(&k, &v)));
|
||||
assert!(spawnable_host_vars().any(|(k, _)| k == "PATH" || k == "Path"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn changes_apply_in_order() {
|
||||
let vars = apply_changes(
|
||||
|
||||
@@ -360,46 +360,9 @@ fn find_binary_in(
|
||||
}
|
||||
|
||||
/// [`find_binary`], plus Xcode's toolchain on macOS (`xcrun -f lldb-dap`): Xcode ships
|
||||
/// lldb-dap without putting it on `PATH`. Elsewhere lldb-dap may carry its LLVM version.
|
||||
/// lldb-dap without putting it on `PATH`.
|
||||
pub fn resolve_binary(command: &str, cwd: &Path) -> Option<PathBuf> {
|
||||
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd)).or_else(|| {
|
||||
(command == "lldb-dap" && !cfg!(windows))
|
||||
.then(|| versioned_lldb_dap(&search_dirs(cwd), Path::new("/usr/lib")))
|
||||
.flatten()
|
||||
})
|
||||
}
|
||||
|
||||
/// Debian and Ubuntu install LLVM's lldb-dap as `lldb-dap-18` (`lldb-vscode-14` before
|
||||
/// LLVM 18 renamed it; same protocol) on `PATH`, or only as `/usr/lib/llvm-18/bin/lldb-dap`.
|
||||
/// The newest LLVM wins.
|
||||
fn versioned_lldb_dap(dirs: &[PathBuf], lib: &Path) -> Option<PathBuf> {
|
||||
let version = |name: &str| -> Option<u32> {
|
||||
let v = name.strip_prefix("lldb-dap-").or_else(|| name.strip_prefix("lldb-vscode-"))?;
|
||||
v.parse().ok()
|
||||
};
|
||||
let mut found: Vec<(u32, PathBuf)> = Vec::new();
|
||||
for dir in dirs {
|
||||
for entry in std::fs::read_dir(dir).into_iter().flatten().flatten() {
|
||||
let path = entry.path();
|
||||
if let Some(v) = path.file_name().and_then(|n| n.to_str()).and_then(version)
|
||||
&& is_executable(&path, false)
|
||||
{
|
||||
found.push((v, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
for entry in std::fs::read_dir(lib).into_iter().flatten().flatten() {
|
||||
let Some(v) = entry.file_name().to_str().and_then(|n| n.strip_prefix("llvm-")?.parse::<u32>().ok()) else {
|
||||
continue;
|
||||
};
|
||||
for name in ["lldb-dap", "lldb-vscode"] {
|
||||
let path = entry.path().join("bin").join(name);
|
||||
if is_executable(&path, false) {
|
||||
found.push((v, path));
|
||||
}
|
||||
}
|
||||
}
|
||||
found.into_iter().max_by_key(|(v, _)| *v).map(|(_, p)| p)
|
||||
find_binary(command, cwd).or_else(|| xcrun_tool(command, cwd))
|
||||
}
|
||||
|
||||
/// `cwd`, inside a project, picks the project's Xcode (`DEVELOPER_DIR`).
|
||||
@@ -509,7 +472,7 @@ fn is_app_execution_alias(path: &Path) -> bool {
|
||||
|
||||
/// GDB's DAP interpreter (`-i dap`) shipped in GDB 14; older ones exit with
|
||||
/// "Interpreter `dap' unrecognized".
|
||||
pub(crate) const GDB_MIN_MAJOR: u32 = 14;
|
||||
const GDB_MIN_MAJOR: u32 = 14;
|
||||
|
||||
/// `(major, minor)` of the first version number in the output of `gdb --version`
|
||||
/// (`GNU gdb (GDB) 14.2`, `GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1`, `GNU gdb
|
||||
@@ -550,29 +513,24 @@ pub fn parse_gdb_version(output: &str) -> Option<(u32, u32)> {
|
||||
|
||||
/// Probe the already resolved and verified executable with its launch environment.
|
||||
async fn gdb_version(binary: &Path, spec: &AdapterSpec) -> IdeResult<Option<(u32, u32)>> {
|
||||
Ok(probe_gdb_version(binary, &spec.cwd, &spec.env).await)
|
||||
}
|
||||
|
||||
/// `(major, minor)` of `binary --version`, run in `cwd` with `env`; `None` when it doesn't say.
|
||||
pub(crate) async fn probe_gdb_version(binary: &Path, cwd: &Path, env: &[(String, String)]) -> Option<(u32, u32)> {
|
||||
let mut probe = Command::new(binary);
|
||||
if let Some(path) = adapter_path(env, cwd) {
|
||||
if let Some(path) = adapter_path(&spec.env, &spec.cwd) {
|
||||
probe.env("PATH", path);
|
||||
}
|
||||
probe.current_dir(cwd);
|
||||
probe.current_dir(&spec.cwd);
|
||||
ide_core::process::prepare(probe.as_std_mut());
|
||||
let probe = probe
|
||||
.arg("--version")
|
||||
.envs(env.iter().cloned())
|
||||
.envs(spec.env.iter().cloned())
|
||||
.stdin(Stdio::null())
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::null())
|
||||
.kill_on_drop(true)
|
||||
.output();
|
||||
let Ok(Ok(out)) = tokio::time::timeout(Duration::from_secs(15), probe).await else {
|
||||
return None;
|
||||
return Ok(None);
|
||||
};
|
||||
parse_gdb_version(&String::from_utf8_lossy(&out.stdout))
|
||||
Ok(parse_gdb_version(&String::from_utf8_lossy(&out.stdout)))
|
||||
}
|
||||
|
||||
/// Refuse old GDB versions and report whether launch must follow configurationDone.
|
||||
@@ -1068,28 +1026,6 @@ mod tests {
|
||||
assert!(builtin("nope").is_none());
|
||||
}
|
||||
|
||||
/// Debian/Ubuntu's versioned lldb-dap (and lldb-vscode before LLVM 18): the newest LLVM wins.
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn finds_versioned_lldb_dap() {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let exe = |p: &Path| {
|
||||
std::fs::create_dir_all(p.parent().unwrap()).unwrap();
|
||||
std::fs::write(p, "").unwrap();
|
||||
std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
};
|
||||
let (bin, lib) = (tmp.path().join("bin"), tmp.path().join("lib"));
|
||||
exe(&bin.join("lldb-vscode-14"));
|
||||
std::fs::write(bin.join("lldb-dap-99"), "").unwrap(); // not executable
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-vscode-14")));
|
||||
exe(&lib.join("llvm-18/bin/lldb-dap"));
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(lib.join("llvm-18/bin/lldb-dap")));
|
||||
exe(&bin.join("lldb-dap-19"));
|
||||
assert_eq!(versioned_lldb_dap(std::slice::from_ref(&bin), &lib), Some(bin.join("lldb-dap-19")));
|
||||
assert_eq!(versioned_lldb_dap(&[], &tmp.path().join("none")), None);
|
||||
}
|
||||
|
||||
/// The first version number of `gdb --version`'s first line, however the distro decorates it.
|
||||
#[test]
|
||||
fn parses_gdb_versions() {
|
||||
|
||||
@@ -22,7 +22,6 @@ mod jvm_memory;
|
||||
pub mod kotlin;
|
||||
pub mod kotlin_lsp;
|
||||
mod memory;
|
||||
pub mod native;
|
||||
mod session;
|
||||
mod stream_trace;
|
||||
mod swiftpm;
|
||||
|
||||
@@ -1,204 +0,0 @@
|
||||
//! C/C++ launches made for lldb-dap (CMake, Swift packages) fall back to CodeLLDB, then to
|
||||
//! GDB 14 or newer, when the host has no lldb-dap: Linux hosts rarely put one on `PATH`, and
|
||||
//! CodeLLDB is the debugger OpenIDEA can install itself.
|
||||
|
||||
use crate::LaunchConfig;
|
||||
use crate::adapter::{GDB_MIN_MAJOR, probe_gdb_version};
|
||||
use ide_core::{IdeError, IdeResult};
|
||||
use serde_json::{Map, Value, json};
|
||||
use std::path::PathBuf;
|
||||
|
||||
/// Prefix of the error when none of them is there; the UI offers to install CodeLLDB on it.
|
||||
pub const NO_NATIVE_DEBUGGER: &str = "No C/C++ debugger found";
|
||||
|
||||
/// `config` for the first of lldb-dap, CodeLLDB and GDB 14+ that `lookup` finds (it resolves a
|
||||
/// debugger command: a configured tool path, else the search path). Other launches pass through.
|
||||
pub async fn choose(
|
||||
mut config: LaunchConfig,
|
||||
lookup: impl Fn(&str) -> Option<PathBuf> + Send + 'static,
|
||||
) -> IdeResult<LaunchConfig> {
|
||||
if config.adapter != "lldb-dap" || config.request != "launch" {
|
||||
return Ok(config);
|
||||
}
|
||||
let found = tokio::task::spawn_blocking(move || {
|
||||
if lookup("lldb-dap").is_some() {
|
||||
return Found::LldbDap;
|
||||
}
|
||||
if lookup("codelldb").is_some() {
|
||||
return Found::CodeLldb;
|
||||
}
|
||||
lookup("gdb").map_or(Found::Nothing, Found::Gdb)
|
||||
})
|
||||
.await
|
||||
.map_err(|e| IdeError::internal(e.to_string()))?;
|
||||
let cwd = config.cwd.clone().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"));
|
||||
match found {
|
||||
Found::LldbDap => {}
|
||||
Found::CodeLldb => convert(&mut config, "codelldb")?,
|
||||
Found::Gdb(gdb) => match probe_gdb_version(&gdb, &cwd, &[]).await {
|
||||
Some((major, minor)) if major < GDB_MIN_MAJOR => return Err(missing(Some((major, minor)))),
|
||||
// Unknown versions are left to GDB itself, as a GDB launch does.
|
||||
_ => convert(&mut config, "gdb")?,
|
||||
},
|
||||
Found::Nothing => return Err(missing(None)),
|
||||
}
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
enum Found {
|
||||
LldbDap,
|
||||
CodeLldb,
|
||||
Gdb(PathBuf),
|
||||
Nothing,
|
||||
}
|
||||
|
||||
fn missing(gdb: Option<(u32, u32)>) -> IdeError {
|
||||
let found = match gdb {
|
||||
Some((major, minor)) => format!(
|
||||
"lldb-dap and CodeLLDB are not installed, and GDB {major}.{minor} cannot debug through DAP \
|
||||
(it needs GDB {GDB_MIN_MAJOR} or newer)"
|
||||
),
|
||||
None => "lldb-dap, CodeLLDB and GDB are not installed".to_owned(),
|
||||
};
|
||||
IdeError::unavailable(format!(
|
||||
"{NO_NATIVE_DEBUGGER}: {found}. Install CodeLLDB, or install lldb-dap or GDB {GDB_MIN_MAJOR} or newer on this host"
|
||||
))
|
||||
}
|
||||
|
||||
/// Rewrites an lldb-dap launch for `to` (`codelldb` or `gdb`). lldb-dap takes the environment as
|
||||
/// `KEY=VALUE` strings and the source map as pairs; the others take the run configuration's
|
||||
/// environment map (`config.env`), CodeLLDB its source map as an object, GDB none.
|
||||
fn convert(config: &mut LaunchConfig, to: &str) -> IdeResult<()> {
|
||||
let mut extra = match config.extra_json.as_deref().filter(|e| !e.trim().is_empty()).map(serde_json::from_str) {
|
||||
None => Map::new(),
|
||||
Some(Ok(Value::Object(extra))) => extra,
|
||||
Some(Ok(other)) => return Err(IdeError::invalid(format!("launch arguments are not an object: {other}"))),
|
||||
Some(Err(e)) => return Err(IdeError::invalid(format!("invalid launch JSON: {e}"))),
|
||||
};
|
||||
extra.remove("env");
|
||||
let source_map = extra.remove("sourceMap");
|
||||
if to == "codelldb" {
|
||||
if let Some(Value::Array(pairs)) = source_map {
|
||||
let map: Map<String, Value> = pairs
|
||||
.iter()
|
||||
.filter_map(|pair| match pair.as_array().map(Vec::as_slice) {
|
||||
Some([Value::String(from), to]) => Some((from.clone(), to.clone())),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
if !map.is_empty() {
|
||||
extra.insert("sourceMap".into(), Value::Object(map));
|
||||
}
|
||||
}
|
||||
// CodeLLDB evaluates as Rust unless told otherwise (ide-dap's default for it).
|
||||
let language = if extra.contains_key("swiftpm") { "swift" } else { "cpp" };
|
||||
extra.entry("sourceLanguages").or_insert_with(|| json!([language]));
|
||||
}
|
||||
config.adapter = to.to_owned();
|
||||
config.extra_json = (!extra.is_empty()).then(|| Value::Object(extra).to_string());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
fn cmake_launch() -> LaunchConfig {
|
||||
LaunchConfig {
|
||||
name: "hello".into(),
|
||||
adapter: "lldb-dap".into(),
|
||||
request: "launch".into(),
|
||||
program: Some("/home/dev/hello/build/hello".into()),
|
||||
args: vec![],
|
||||
cwd: Some(std::path::PathBuf::from("/").into()),
|
||||
env: BTreeMap::from([("A".into(), "1".into())]),
|
||||
extra_json: Some(json!({"env": ["A=1"], "sourceMap": [["/src", "/real/src"]]}).to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
fn extra(config: &LaunchConfig) -> Value {
|
||||
config.extra_json.as_deref().map_or(Value::Null, |e| serde_json::from_str(e).unwrap())
|
||||
}
|
||||
|
||||
fn only(names: &'static [&'static str]) -> impl Fn(&str) -> Option<PathBuf> + Send + 'static {
|
||||
move |c| names.contains(&c).then(|| PathBuf::from(format!("/usr/bin/{c}")))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn keeps_lldb_dap_when_it_is_there() {
|
||||
let config = choose(cmake_launch(), only(&["lldb-dap", "codelldb", "gdb"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "lldb-dap");
|
||||
assert_eq!(config.extra_json, cmake_launch().extra_json);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn falls_back_to_codelldb_with_its_launch_shape() {
|
||||
let config = choose(cmake_launch(), only(&["codelldb", "gdb"])).await.unwrap();
|
||||
assert_eq!(config.adapter, "codelldb");
|
||||
assert_eq!(config.env, cmake_launch().env, "the environment comes from the run configuration's map");
|
||||
assert_eq!(
|
||||
extra(&config),
|
||||
json!({"sourceMap": {"/src": "/real/src"}, "sourceLanguages": ["cpp"]}),
|
||||
"no KEY=VALUE env strings; the source map as an object; C++ evaluation"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_swift_package_evaluates_swift_under_codelldb() {
|
||||
let mut launch = cmake_launch();
|
||||
launch.extra_json = Some(json!({"env": [], "swiftpm": {"product": "app", "buildArgs": []}}).to_string());
|
||||
let config = choose(launch, only(&["codelldb"])).await.unwrap();
|
||||
assert_eq!(extra(&config)["sourceLanguages"], json!(["swift"]));
|
||||
assert_eq!(extra(&config)["swiftpm"]["product"], "app");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn without_any_debugger_says_what_to_install() {
|
||||
let e = choose(cmake_launch(), only(&[])).await.unwrap_err();
|
||||
assert_eq!(e.kind, ide_core::error::ErrorKind::Unavailable);
|
||||
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
|
||||
assert!(e.message.contains("Install CodeLLDB"), "{}", e.message);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn other_launches_pass_through() {
|
||||
let mut attach = cmake_launch();
|
||||
attach.request = "attach".into();
|
||||
assert_eq!(choose(attach, only(&[])).await.unwrap().adapter, "lldb-dap");
|
||||
let mut rust = cmake_launch();
|
||||
rust.adapter = "codelldb".into();
|
||||
assert_eq!(choose(rust, only(&[])).await.unwrap().adapter, "codelldb");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn fake_gdb(dir: &Path, version: &str) -> PathBuf {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let gdb = dir.join("gdb");
|
||||
std::fs::write(&gdb, format!("#!/bin/sh\necho '{version}'\n")).unwrap();
|
||||
std::fs::set_permissions(&gdb, std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
gdb
|
||||
}
|
||||
|
||||
/// Ubuntu 22.04's GDB 12 has no DAP interpreter: the error names its version (#7001).
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn an_old_gdb_is_named_in_the_error() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let gdb = fake_gdb(dir.path(), "GNU gdb (Ubuntu 12.1-0ubuntu1~22.04.2) 12.1");
|
||||
let e = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap_err();
|
||||
assert!(e.message.starts_with(NO_NATIVE_DEBUGGER), "{}", e.message);
|
||||
assert!(e.message.contains("GDB 12.1"), "{}", e.message);
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[tokio::test]
|
||||
async fn falls_back_to_a_gdb_with_dap() {
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let gdb = fake_gdb(dir.path(), "GNU gdb (GDB) 14.2");
|
||||
let config = choose(cmake_launch(), move |c| (c == "gdb").then(|| gdb.clone())).await.unwrap();
|
||||
assert_eq!(config.adapter, "gdb");
|
||||
assert_eq!(extra(&config), Value::Null, "GDB takes the environment map and has no source map");
|
||||
}
|
||||
}
|
||||
@@ -1134,27 +1134,21 @@ pub(crate) fn run_in_terminal(s: &Arc<Session>, args: &Value) -> Result<Value, S
|
||||
// CodeLLDB's launcher clears the terminal first; the console keeps the session's earlier output.
|
||||
cmd.args(rest.iter().filter(|a| *a != "--clear-screen"));
|
||||
let cwd = args.get("cwd").and_then(Value::as_str).filter(|c| !c.is_empty()).map_or(s.spec.cwd.as_path(), Path::new);
|
||||
// See #6806: do not inherit portable-pty's registry-built Windows env block.
|
||||
cmd.env_clear();
|
||||
for (k, v) in ide_core::process::spawnable_host_vars_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
for (k, v) in ide_core::process::host_env_fixes_in(cwd) {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
}
|
||||
}
|
||||
for (k, v) in ide_core::process::shell_env_in(cwd) {
|
||||
if ide_core::process::is_spawnable_env_pair(&k, &v) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
cmd.env(k, v);
|
||||
}
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.cwd(cwd);
|
||||
if let Some(env) = args.get("env").and_then(Value::as_object) {
|
||||
for (k, v) in env {
|
||||
match v.as_str() {
|
||||
Some(v)
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) =>
|
||||
{
|
||||
cmd.env(k, v)
|
||||
}
|
||||
Some(_) => {}
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -140,15 +140,6 @@ pub async fn debug_start(host: &Host, window: &str, config: LaunchConfig) -> Ide
|
||||
config = add_java_source_paths(config, &roots);
|
||||
}
|
||||
let root = config.cwd.clone().map(PathBuf::from).unwrap_or_default();
|
||||
// No lldb-dap on this host (most Linux hosts): CodeLLDB, else GDB 14+.
|
||||
if config.adapter == "lldb-dap" {
|
||||
let (root, settings) = (root.clone(), settings.clone());
|
||||
config = ide_dap::native::choose(config, move |command| {
|
||||
ide_sdk::apply::tool_command(&root, &settings, command)
|
||||
.or_else(|| ide_dap::adapter::resolve_binary(command, &root))
|
||||
})
|
||||
.await?;
|
||||
}
|
||||
let mut ruby_tools = Vec::new();
|
||||
if config.adapter == "rdbg" && config.request == "launch" {
|
||||
let project_root = host.project(window).map(|p| p.root.clone()).unwrap_or_else(|_| root.clone());
|
||||
|
||||
@@ -1,34 +1,19 @@
|
||||
use crate::project::Project;
|
||||
use ide_core::IdeResult;
|
||||
use ide_dap::LaunchConfig;
|
||||
use ide_workspace::roots::{RootKind, SourceFolder};
|
||||
use std::collections::{BTreeMap, HashSet};
|
||||
use ide_workspace::roots::RootKind;
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// The project's import roots, put on `PYTHONPATH` by runs, debug sessions and consoles.
|
||||
pub(super) fn paths(project: &Project) -> Vec<PathBuf> {
|
||||
import_roots(&project.root, project.content_roots(), &project.roots().roots)
|
||||
}
|
||||
|
||||
/// `root`, the content roots, then the Source and Test roots. A detected root that is itself a
|
||||
/// package (it holds `__init__.py`, like an Odoo addon or its `tests` folder) is left out:
|
||||
/// importing from it would give its modules a second top-level name, and a project with
|
||||
/// thousands of them made `PYTHONPATH` longer than a process environment can hold (#7083).
|
||||
/// Folders the user marked always count.
|
||||
fn import_roots(root: &Path, content_roots: Vec<PathBuf>, roots: &[SourceFolder]) -> Vec<PathBuf> {
|
||||
let mut paths = vec![root.to_path_buf()];
|
||||
paths.extend(content_roots);
|
||||
let mut seen: HashSet<PathBuf> = paths.iter().cloned().collect();
|
||||
for folder in roots {
|
||||
if !matches!(folder.kind, RootKind::Source | RootKind::Test) {
|
||||
continue;
|
||||
}
|
||||
let path = root.join(&folder.path);
|
||||
if folder.detected_from.is_some() && path.join("__init__.py").is_file() {
|
||||
continue;
|
||||
}
|
||||
if seen.insert(path.clone()) {
|
||||
paths.push(path);
|
||||
let mut paths = vec![project.root.clone()];
|
||||
paths.extend(project.content_roots());
|
||||
for root in project.roots().roots {
|
||||
if matches!(root.kind, RootKind::Source | RootKind::Test) {
|
||||
let path = project.root.join(root.path);
|
||||
if !paths.contains(&path) {
|
||||
paths.push(path);
|
||||
}
|
||||
}
|
||||
}
|
||||
paths
|
||||
@@ -135,38 +120,6 @@ pub(super) fn prepare_debug(
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn detected_package_folders_are_not_import_roots() {
|
||||
use ide_workspace::roots::{RootKind, SourceFolder};
|
||||
let dir = tempfile::tempdir().unwrap();
|
||||
let root = dir.path();
|
||||
for file in ["src/pkg/__init__.py", "addon/__init__.py", "addon/tests/__init__.py", "marked/__init__.py"] {
|
||||
let path = root.join(file);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
std::fs::write(path, "").unwrap();
|
||||
}
|
||||
std::fs::create_dir_all(root.join("tests")).unwrap();
|
||||
let folder = |path: &str, kind, detected: bool| SourceFolder {
|
||||
path: path.into(),
|
||||
kind,
|
||||
detected_from: detected.then(|| "pyproject.toml".into()),
|
||||
};
|
||||
let roots = [
|
||||
folder("src", RootKind::Source, true),
|
||||
folder("tests", RootKind::Test, true),
|
||||
folder("addon", RootKind::Source, true),
|
||||
folder("addon/tests", RootKind::Test, true),
|
||||
folder("marked", RootKind::Source, false),
|
||||
folder("build", RootKind::Excluded, true),
|
||||
folder("src", RootKind::Source, true),
|
||||
];
|
||||
assert_eq!(
|
||||
super::import_roots(root, vec![], &roots),
|
||||
[root.to_path_buf(), root.join("src"), root.join("tests"), root.join("marked")],
|
||||
"detected packages are left out, a folder the user marked stays, no duplicates"
|
||||
);
|
||||
}
|
||||
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -3405,17 +3405,10 @@ impl LspManager {
|
||||
if changes.is_empty() {
|
||||
continue;
|
||||
}
|
||||
// jdtls rebuilds a source file that changed on disk but keeps the diagnostics of the
|
||||
// open files it checked before: a reference to a class another tool adds after
|
||||
// rewriting the open file stays "cannot be resolved" until the file is reopened.
|
||||
// Sending the open files again makes it check them against the new sources.
|
||||
let recheck_open = jdtls && changes.iter().any(|(p, _)| p.extension().is_some_and(|e| e == "java"));
|
||||
let changes: Vec<Value> =
|
||||
changes.iter().map(|(p, c)| json!({ "uri": uri::path_to_uri(p), "type": *c as u8 })).collect();
|
||||
if let Err(e) = run.peer.notify("workspace/didChangeWatchedFiles", json!({ "changes": changes })) {
|
||||
tracing::debug!("{}: didChangeWatchedFiles: {e}", s.name);
|
||||
} else if recheck_open {
|
||||
self.resync_documents(&s, run.generation);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -482,31 +482,6 @@ async fn dart_file_watching_requires_an_explicit_registration() {
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn java_sources_changed_on_disk_send_the_open_files_to_jdtls_again() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let (_, main) = h.open("Main.java", "class Main { String s = Helper.greet(); }");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
let resent = || {
|
||||
s.notified("textDocument/didChange")
|
||||
.iter()
|
||||
.filter(|v| v["textDocument"]["uri"] == uri_of(&main) && v["contentChanges"][0]["text"].is_string())
|
||||
.count()
|
||||
};
|
||||
// Another tool adds the class the open file refers to.
|
||||
let helper = h.root.join("Helper.java");
|
||||
h.mgr.watched_files_changed(std::slice::from_ref(&helper), &[], &[], &[]);
|
||||
eventually(|| s.notified("workspace/didChangeWatchedFiles").len() == 1).await;
|
||||
eventually(|| resent() == 1).await;
|
||||
// Files that are not Java sources leave the open files alone.
|
||||
h.mgr.watched_files_changed(&[], &[h.root.join("notes.txt")], &[], &[]);
|
||||
h.mgr.watched_files_changed(&[], &[h.root.join("pom.xml")], &[], &[]);
|
||||
tokio::time::sleep(Duration::from_millis(200)).await;
|
||||
assert_eq!(resent(), 1);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
// ------------------------------------------------------------------ tests
|
||||
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
|
||||
@@ -636,24 +636,23 @@ impl ProcessManager {
|
||||
let mut cmd = CommandBuilder::new(&inv.program);
|
||||
cmd.args(&inv.args);
|
||||
cmd.cwd(cwd);
|
||||
// See #6806: do not inherit portable-pty's registry-built Windows env block.
|
||||
cmd.env_clear();
|
||||
if !env.clear {
|
||||
for (k, v) in ide_core::process::spawnable_host_vars_in(cwd) {
|
||||
cmd.env(k, v);
|
||||
if env.clear {
|
||||
cmd.env_clear();
|
||||
} else {
|
||||
for (k, v) in ide_core::process::host_env_fixes_in(cwd) {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
}
|
||||
}
|
||||
for (k, v) in ide_core::process::shell_env_in(cwd) {
|
||||
if ide_core::process::is_spawnable_env_pair(&k, &v) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
cmd.env(k, v);
|
||||
}
|
||||
}
|
||||
cmd.env("TERM", "xterm-256color");
|
||||
cmd.env("COLORTERM", "truecolor");
|
||||
for (k, v) in &env.vars {
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(k), std::ffi::OsStr::new(v)) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
cmd.env(k, v);
|
||||
}
|
||||
#[cfg(unix)]
|
||||
let wait_writable = ide_core::input::nonblocking(
|
||||
|
||||
@@ -344,18 +344,15 @@ impl TerminalManager {
|
||||
resolve_cwd(&options.cwd)
|
||||
};
|
||||
cmd.cwd(&cwd);
|
||||
// portable-pty starts from a base env that re-reads HKCU\Environment on
|
||||
// Windows. A REG_MULTI_SZ value's interior NULs split the environment
|
||||
// block and CreateProcessW fails with os error 87 (#6806). Build the
|
||||
// child's environment from sanitized host vars instead.
|
||||
cmd.env_clear();
|
||||
for (k, v) in ide_core::process::spawnable_host_vars_in(&cwd) {
|
||||
cmd.env(k, v);
|
||||
// In a project folder: the project's environment (its direnv `.envrc`) too.
|
||||
for (k, v) in ide_core::process::host_env_fixes_in(&cwd) {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
}
|
||||
}
|
||||
for (k, v) in env {
|
||||
if ide_core::process::is_spawnable_env_pair(std::ffi::OsStr::new(&k), std::ffi::OsStr::new(&v)) {
|
||||
cmd.env(k, v);
|
||||
}
|
||||
cmd.env(k, v);
|
||||
}
|
||||
apply_powershell_env(&shell, &mut cmd);
|
||||
|
||||
|
||||
@@ -1,90 +0,0 @@
|
||||
/**
|
||||
* Git log row colors: User, Date and Hash use the normal text color on a regular
|
||||
* commit, and are dimmed together with the subject on a merge commit.
|
||||
*/
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("dims the metadata columns only on merge commits", async ({ workbench: page }) => {
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(async () => {
|
||||
const root = "/dev/acme-api";
|
||||
const id = (i: number) => i.toString(16).padStart(40, "0");
|
||||
const commit = (i: number, parents: number[], summary: string) => ({
|
||||
id: id(i),
|
||||
shortId: id(i).slice(-8),
|
||||
parents: parents.map(id),
|
||||
refs: i === 0 ? ["HEAD", "main"] : [],
|
||||
author: `Author ${i}`,
|
||||
email: "[email protected]",
|
||||
timeMs: 1_700_000_000_000 - i * 60_000,
|
||||
summary,
|
||||
message: summary,
|
||||
});
|
||||
const commits = [
|
||||
commit(0, [1, 2], "Merge branch 'feature'"),
|
||||
commit(1, [3], "Regular change"),
|
||||
commit(2, [3], "Feature change"),
|
||||
commit(3, [], "Initial"),
|
||||
];
|
||||
const h = window.__ipc.handlers;
|
||||
h.vcs_log = ({ query }) => {
|
||||
const { skip, limit, range } = query as { skip: number; limit: number; range?: string };
|
||||
return range ? [] : commits.slice(skip, limit ? skip + limit : undefined);
|
||||
};
|
||||
h.vcs_log_refs = () => ({});
|
||||
h.vcs_branches = () => [];
|
||||
h.vcs_branch_info = () => ({
|
||||
head: "main",
|
||||
headCommit: id(0),
|
||||
upstream: null,
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
operation: null,
|
||||
});
|
||||
h.vcs_config_get = () => null;
|
||||
h.vcs_commit_files = () => [];
|
||||
h.vcs_log_details_batch = ({ revisions }) =>
|
||||
(revisions as string[]).map(() => ({
|
||||
message: "",
|
||||
containingBranches: [],
|
||||
signature: "N",
|
||||
signer: "",
|
||||
key: "",
|
||||
fingerprint: "",
|
||||
}));
|
||||
const storeModule = "/src/features/vcs/store.ts";
|
||||
const { useVcs } = await import(/* @vite-ignore */ storeModule);
|
||||
useVcs.setState({ available: true, root, repo: root, roots: [root], branchesLoaded: true });
|
||||
const contextModule = "/src/platform/context.ts";
|
||||
const { setContext } = await import(/* @vite-ignore */ contextModule);
|
||||
setContext("vcsAvailable", true);
|
||||
const optionsModule = "/src/features/vcs/logOptions.ts";
|
||||
const { useLogOptions } = await import(/* @vite-ignore */ optionsModule);
|
||||
useLogOptions.setState({ showHash: true, highlightMerges: true });
|
||||
const actionsModule = "/src/platform/actions.ts";
|
||||
const { executeAction } = await import(/* @vite-ignore */ actionsModule);
|
||||
await executeAction("vcs.showLog");
|
||||
});
|
||||
const list = page.getByRole("listbox", { name: "Commits" });
|
||||
await expect(list.getByRole("option")).toHaveCount(4);
|
||||
|
||||
const colors = (summary: string) =>
|
||||
list
|
||||
.getByRole("option")
|
||||
.filter({ hasText: summary })
|
||||
.evaluate((row) => {
|
||||
const color = (el: Element | null) => (el ? getComputedStyle(el).color : null);
|
||||
const subject = row.querySelector("[class*=subjectText]");
|
||||
const author = row.querySelector('[title^="Author "]');
|
||||
const hash = [...row.querySelectorAll("span")].find((s) => /^0+[0-9a-f]$/.test(s.textContent ?? ""));
|
||||
return { subject: color(subject), author: color(author), hash: color(hash ?? null) };
|
||||
});
|
||||
|
||||
const regular = await colors("Regular change");
|
||||
const merge = await colors("Merge branch 'feature'");
|
||||
expect(regular.author).toBe(regular.subject);
|
||||
expect(regular.hash).toBe(regular.subject);
|
||||
expect(merge.author).toBe(merge.subject);
|
||||
expect(merge.hash).toBe(merge.subject);
|
||||
expect(merge.author).not.toBe(regular.author);
|
||||
});
|
||||
@@ -110,132 +110,6 @@ test("follows explicit Markdown anchors before generated heading IDs", async ({
|
||||
await expect(heading).toBeInViewport();
|
||||
});
|
||||
|
||||
test("keeps unchanged preview blocks mounted while their source lines move", async ({ workbench: page }) => {
|
||||
const path = "/dev/acme-api/incremental-markdown.md";
|
||||
const workerCounts = await page.evaluateHandle(() => {
|
||||
const counts = { started: 0, stopped: 0 };
|
||||
const BrowserWorker = window.Worker;
|
||||
window.Worker = class extends BrowserWorker {
|
||||
private readonly tracksPreview: boolean;
|
||||
|
||||
constructor(url: string | URL, options?: WorkerOptions) {
|
||||
super(url, options);
|
||||
this.tracksPreview = String(url).includes("/preview.worker.ts");
|
||||
if (this.tracksPreview) counts.started++;
|
||||
}
|
||||
|
||||
terminate() {
|
||||
if (this.tracksPreview) counts.stopped++;
|
||||
super.terminate();
|
||||
}
|
||||
};
|
||||
return counts;
|
||||
});
|
||||
await page.evaluate(async (path) => {
|
||||
const backendPath = "/src/editor/core/backend.ts";
|
||||
const servicePath = "/src/workbench/contributions.ts";
|
||||
const { docBackend } = await import(backendPath);
|
||||
const { editorService } = await import(servicePath);
|
||||
docBackend().files.set(path, "Edit this paragraph.\n\nKeep this paragraph.\n");
|
||||
await editorService().openFile(path);
|
||||
}, path);
|
||||
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
const unchanged = preview.getByText("Keep this paragraph.", { exact: true });
|
||||
await expect(unchanged).toBeVisible();
|
||||
await expect(preview).toHaveAttribute("style", /--markdown-block-width:/);
|
||||
const widthChanges = await preview.evaluateHandle((el) => {
|
||||
const records: MutationRecord[] = [];
|
||||
const observer = new MutationObserver((changes) => records.push(...changes));
|
||||
observer.observe(el, { attributes: true, attributeFilter: ["style"], attributeOldValue: true });
|
||||
return { observer, records };
|
||||
});
|
||||
const previous = await unchanged.elementHandle();
|
||||
expect(await previous.evaluate((el) => el.parentElement?.getAttribute("data-line"))).toBe("2");
|
||||
|
||||
await page.evaluate(async (path) => {
|
||||
const editorApi = "/src/editor/api.ts";
|
||||
const { editorsFor } = await import(editorApi);
|
||||
const { view } = editorsFor(path)[0];
|
||||
view.dispatch({ changes: { from: 0, to: 20, insert: "The edited paragraph.\n\nA new paragraph." } });
|
||||
}, path);
|
||||
|
||||
await expect(preview.getByText("The edited paragraph.", { exact: true })).toBeVisible();
|
||||
const inserted = preview.getByText("A new paragraph.", { exact: true });
|
||||
await expect(inserted).toBeVisible();
|
||||
await expect(inserted.locator("..")).toHaveAttribute("data-in-viewport", "");
|
||||
expect(await unchanged.evaluate((el, previous) => el === previous, previous)).toBe(true);
|
||||
expect(await previous.evaluate((el) => el.parentElement?.getAttribute("data-line"))).toBe("4");
|
||||
const lostWidth = await widthChanges.evaluate(({ observer, records }) => {
|
||||
const changes = [...records, ...observer.takeRecords()];
|
||||
observer.disconnect();
|
||||
return changes.some((record) => !record.oldValue?.includes("--markdown-block-width:"));
|
||||
});
|
||||
expect(lostWidth).toBe(false);
|
||||
expect(await workerCounts.jsonValue()).toEqual({ started: 1, stopped: 0 });
|
||||
|
||||
await openFromTree(page, "App.tsx");
|
||||
await expect.poll(() => workerCounts.jsonValue()).toEqual({ started: 1, stopped: 1 });
|
||||
await page.getByRole("tab", { name: /incremental-markdown\.md/ }).click();
|
||||
await expect(unchanged).toBeVisible();
|
||||
expect(await unchanged.evaluate((el, previous) => el === previous, previous)).toBe(true);
|
||||
expect(await workerCounts.jsonValue()).toEqual({ started: 1, stopped: 1 });
|
||||
});
|
||||
|
||||
test("defers Mermaid while editing prose after leaving its fence", async ({ workbench: page }) => {
|
||||
const path = "/dev/acme-api/diagram.md";
|
||||
await page.evaluate(async (path) => {
|
||||
const backendPath = "/src/editor/core/backend.ts";
|
||||
const servicePath = "/src/workbench/contributions.ts";
|
||||
const { docBackend } = await import(backendPath);
|
||||
const { editorService } = await import(servicePath);
|
||||
docBackend().files.set(
|
||||
path,
|
||||
"# Diagram\n\n~~~mermaid\nflowchart TD\nA[Start] --> B[Finish]\n~~~\n\nAfter the diagram.\n",
|
||||
);
|
||||
await editorService().openFile(path);
|
||||
}, path);
|
||||
|
||||
const preview = page.getByRole("document", { name: "Markdown preview" });
|
||||
const drawing = preview.locator(".mermaid-output svg");
|
||||
await expect(drawing).toContainText("Finish");
|
||||
const originalDrawing = await drawing.elementHandle();
|
||||
|
||||
await page.evaluate(async (path) => {
|
||||
const api = "/src/editor/api.ts";
|
||||
const { editorsFor } = await import(api);
|
||||
const { view } = editorsFor(path)[0];
|
||||
const line = view.state.doc.line(5);
|
||||
const from = line.from + line.text.indexOf("Finish");
|
||||
view.focus();
|
||||
view.dispatch({
|
||||
changes: { from, to: from + "Finish".length, insert: "Revised end" },
|
||||
selection: { anchor: from + "Revised end".length },
|
||||
});
|
||||
}, path);
|
||||
await page.waitForFunction(async (path) => {
|
||||
const liveModule = "/src/features/viewers/markdown/live.ts";
|
||||
const { useLiveMarkdown } = await import(liveModule);
|
||||
return useLiveMarkdown.getState()[path]?.text.line(5).text.includes("Revised end");
|
||||
}, path);
|
||||
await expect(preview.locator("[data-mermaid] pre code")).toContainText("Finish");
|
||||
expect(await drawing.evaluate((svg, original) => svg === original, originalDrawing)).toBe(true);
|
||||
|
||||
await page.evaluate(async (path) => {
|
||||
const api = "/src/editor/api.ts";
|
||||
const { editorsFor } = await import(api);
|
||||
const { view } = editorsFor(path)[0];
|
||||
const line = view.state.doc.line(8);
|
||||
view.dispatch({ selection: { anchor: line.from } });
|
||||
view.dispatch({ changes: { from: line.from + "After ".length, insert: "editing " } });
|
||||
}, path);
|
||||
await expect(preview.getByText("After editing the diagram.", { exact: true })).toBeVisible();
|
||||
await expect(drawing).toContainText("Finish");
|
||||
|
||||
await preview.focus();
|
||||
await expect(drawing).toContainText("Revised end");
|
||||
});
|
||||
|
||||
test("copies fenced Markdown code with hover or keyboard in both preview layouts", async ({
|
||||
workbench: page,
|
||||
context,
|
||||
|
||||
@@ -1,8 +1,7 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension } from "./markdownMath";
|
||||
import { renderMath } from "./renderMarkdownMath";
|
||||
import { mathExtension, renderMath } from "./markdownMath";
|
||||
|
||||
const marked = new Marked({ gfm: true, breaks: false }).use(mathExtension());
|
||||
|
||||
|
||||
@@ -6,6 +6,9 @@
|
||||
* placeholders, which survive `DOMPurify` (with `data-math` allowed) and are
|
||||
* rendered synchronously into KaTeX DOM by `renderMath()` right after sanitization.
|
||||
*/
|
||||
import katex from "katex";
|
||||
import "katex/dist/katex.min.css";
|
||||
import "./markdownMath.css";
|
||||
import type { MarkedExtension, Tokens } from "marked";
|
||||
|
||||
interface MathToken extends Tokens.Generic {
|
||||
@@ -207,3 +210,20 @@ export function mathExtension(): MarkedExtension {
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */
|
||||
export function renderMath(root: ParentNode): void {
|
||||
root.querySelectorAll<HTMLElement>("[data-math]").forEach((el) => {
|
||||
const mode = el.getAttribute("data-math");
|
||||
el.removeAttribute("data-math");
|
||||
if (mode !== "inline" && mode !== "display") return;
|
||||
const tex = (el.textContent ?? "").trim();
|
||||
if (!tex) return;
|
||||
katex.render(tex, el, {
|
||||
displayMode: mode === "display",
|
||||
throwOnError: false,
|
||||
strict: false,
|
||||
trust: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
/** Markdown → sanitized HTML (marked + DOMPurify); loaded on demand by `markdown.ts`. */
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { mathExtension } from "./markdownMath";
|
||||
import { renderMath } from "./renderMarkdownMath";
|
||||
import { mathExtension, renderMath } from "./markdownMath";
|
||||
|
||||
/** DOMPurify's default link schemes plus `file:` and jdtls' `jdt:` (library classes). */
|
||||
const ALLOWED_URI = /^(?:(?:(?:f|ht)tps?|mailto|tel|file|jdt):|[^a-z]|[a-z+.-]+(?:[^a-z+.\-:]|$))/i;
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
import katex from "katex";
|
||||
import "katex/dist/katex.min.css";
|
||||
import "./markdownMath.css";
|
||||
|
||||
/** Renders every `[data-math]` placeholder inside `root` synchronously using KaTeX. */
|
||||
export function renderMath(root: ParentNode): void {
|
||||
root.querySelectorAll<HTMLElement>("[data-math]").forEach((el) => {
|
||||
const mode = el.getAttribute("data-math");
|
||||
el.removeAttribute("data-math");
|
||||
if (mode !== "inline" && mode !== "display") return;
|
||||
const tex = (el.textContent ?? "").trim();
|
||||
if (!tex) return;
|
||||
katex.render(tex, el, {
|
||||
displayMode: mode === "display",
|
||||
throwOnError: false,
|
||||
strict: false,
|
||||
trust: false,
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -754,7 +754,7 @@ export function AgentsView() {
|
||||
<div className={styles.empty}>{externalError}</div>
|
||||
) : (
|
||||
<div className={styles.external}>
|
||||
{external.slice(0, 50).map((s) => {
|
||||
{external.map((s) => {
|
||||
const key = externalKey(s.provider, s.sessionId);
|
||||
return (
|
||||
<div key={key} className={styles.row} title={s.cwd ?? s.sessionId}>
|
||||
|
||||
@@ -16,7 +16,7 @@ import {
|
||||
} from "./store";
|
||||
import styles from "./Agents.module.css";
|
||||
|
||||
/** At most this many matching sessions are shown at once, newest first. */
|
||||
/** The backend lists at most this many sessions, newest first. */
|
||||
const LISTED_MAX = 50;
|
||||
const ROW = 24;
|
||||
|
||||
@@ -74,7 +74,7 @@ function ImportSessionsDialog() {
|
||||
const [frozen, setFrozen] = useState<Row[] | null>(null);
|
||||
const abort = useRef<AbortController | null>(null);
|
||||
|
||||
const matched = useMemo<Row[]>(() => {
|
||||
const rows = useMemo<Row[]>(() => {
|
||||
const q = query.trim().toLowerCase();
|
||||
return external
|
||||
.map((s) => ({
|
||||
@@ -87,15 +87,8 @@ function ImportSessionsDialog() {
|
||||
updatedMs: s.updatedMs ?? 0,
|
||||
}))
|
||||
.filter((r) => !importing.has(r.key))
|
||||
.filter(
|
||||
(r) =>
|
||||
!q ||
|
||||
r.title.toLowerCase().includes(q) ||
|
||||
r.folder.toLowerCase().includes(q) ||
|
||||
r.sessionId.toLowerCase().includes(q),
|
||||
);
|
||||
.filter((r) => !q || r.title.toLowerCase().includes(q) || r.folder.toLowerCase().includes(q));
|
||||
}, [external, importing, query, root]);
|
||||
const rows = useMemo(() => matched.slice(0, LISTED_MAX), [matched]);
|
||||
const view = frozen ?? rows;
|
||||
|
||||
// The lead is drawn as selected: keep it on a selected row the list still shows, else on none.
|
||||
@@ -199,7 +192,7 @@ function ImportSessionsDialog() {
|
||||
? tx`Forking ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`
|
||||
: tx`Importing ${Math.min(progress.done + 1, progress.total)} of ${progress.total}…`}
|
||||
</span>
|
||||
) : shown && matched.length > LISTED_MAX ? (
|
||||
) : shown && external.length >= LISTED_MAX ? (
|
||||
<span className={styles.chooserHint}>
|
||||
<T>Only the 50 most recent sessions are shown.</T>
|
||||
</span>
|
||||
|
||||
@@ -11,8 +11,7 @@ import { useEffect, useLayoutEffect, useRef, useSyncExternalStore } from "react"
|
||||
import { Marked } from "marked";
|
||||
import DOMPurify from "dompurify";
|
||||
import { highlightInto } from "@/editor/lsp/markdown";
|
||||
import { mathExtension } from "@/editor/lsp/markdownMath";
|
||||
import { renderMath } from "@/editor/lsp/renderMarkdownMath";
|
||||
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { iconNode } from "@/ui/iconNode";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { openExternalUrl } from "@/platform/openUrl";
|
||||
|
||||
@@ -2955,29 +2955,16 @@ describe("import sessions dialog", () => {
|
||||
expect(box.getAttribute("aria-activedescendant")).toBe(row(/Add tests/).id);
|
||||
});
|
||||
|
||||
it("filters by title, folder, and session id, including past the first 50 sessions", async () => {
|
||||
const older = Array.from({ length: 55 }, (_, i) => ({
|
||||
provider: "copilot",
|
||||
sessionId: `older-${i}`,
|
||||
title: i === 53 ? "Storage team work summary" : `Routine sync ${i}`,
|
||||
cwd: "/work",
|
||||
updatedMs: 0,
|
||||
}));
|
||||
backend.external = [...sessions, third, ...older];
|
||||
it("filters by title and folder", async () => {
|
||||
backend.external = [...sessions, third];
|
||||
open();
|
||||
await listed("Login fix");
|
||||
expect(screen.queryByText("Storage team work summary")).toBeNull();
|
||||
fireEvent.change(screen.getByLabelText("Filter sessions"), { target: { value: "work/api" } });
|
||||
expect(screen.queryByText("Login fix")).toBeNull();
|
||||
expect(screen.getByText("Fix flaky test")).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText("Filter sessions"), { target: { value: "ADD" } });
|
||||
expect(screen.getByText("Add tests")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Fix flaky test")).toBeNull();
|
||||
fireEvent.change(screen.getByLabelText("Filter sessions"), { target: { value: "THREAD-1" } });
|
||||
expect(screen.getByText("Add tests")).toBeInTheDocument();
|
||||
fireEvent.change(screen.getByLabelText("Filter sessions"), { target: { value: "Storage team" } });
|
||||
expect(screen.getByText("Storage team work summary")).toBeInTheDocument();
|
||||
expect(screen.queryByText("Only the 50 most recent sessions are shown.")).toBeNull();
|
||||
});
|
||||
|
||||
it("does not import a session that the filter hides", async () => {
|
||||
@@ -3080,12 +3067,11 @@ describe("import sessions dialog", () => {
|
||||
cwd: null,
|
||||
updatedMs: 0,
|
||||
}));
|
||||
// The backend lists every session; the dialog shows the 50 newest matches.
|
||||
backend.external = many(51);
|
||||
backend.external = many(50);
|
||||
open();
|
||||
await waitFor(() => expect(screen.getByText("Only the 50 most recent sessions are shown.")).toBeInTheDocument());
|
||||
act(() => hideImportSessions());
|
||||
backend.external = many(50);
|
||||
backend.external = many(49);
|
||||
act(() => showImportSessions());
|
||||
await listed("Session 0");
|
||||
expect(screen.queryByText("Only the 50 most recent sessions are shown.")).toBeNull();
|
||||
|
||||
@@ -32,19 +32,6 @@ describe("missing debug adapters", () => {
|
||||
);
|
||||
});
|
||||
|
||||
it("offers CodeLLDB when a C/C++ launch finds no debugger on its host (#7001)", () => {
|
||||
const e = unavailable(
|
||||
"No C/C++ debugger found: lldb-dap and CodeLLDB are not installed, and GDB 12.1 cannot debug through DAP (it needs GDB 14 or newer). Install CodeLLDB, or install lldb-dap or GDB 14 or newer on this host",
|
||||
);
|
||||
expect(missingAdapter("lldb-dap", e)).toMatchObject({
|
||||
tool: "codelldb",
|
||||
title: "No C/C++ debugger found",
|
||||
action: "Install CodeLLDB and Debug",
|
||||
body: e.message,
|
||||
});
|
||||
expect(missingAdapter("lldb-dap", invalid(e.message))).toBeNull();
|
||||
});
|
||||
|
||||
it("offers the managed install of the missing php-debug adapter", () => {
|
||||
const e = unavailable(
|
||||
"debug adapter `php-debug` not found (`php-debug-adapter` is neither installed by OpenIDEA nor on PATH). Install PHP Debug (Xdebug) in Settings › Languages & Frameworks › Language Servers, and enable Xdebug",
|
||||
|
||||
@@ -27,13 +27,6 @@ const INSTALLABLE: Record<string, { tool: string; title: string }> = {
|
||||
*/
|
||||
const DELVE_TOO_OLD = /Version of Delve is too old for Go version go([\d.]+)/;
|
||||
|
||||
/**
|
||||
* A C/C++ launch found neither lldb-dap, CodeLLDB nor a GDB with DAP on its host (ide-dap
|
||||
* `native::NO_NATIVE_DEBUGGER`, typical of a Linux remote). CodeLLDB is the one OpenIDEA
|
||||
* installs; the same launch then falls back to it.
|
||||
*/
|
||||
const NO_NATIVE_DEBUGGER = "No C/C++ debugger found";
|
||||
|
||||
export interface MissingAdapter {
|
||||
tool: string;
|
||||
title: string;
|
||||
@@ -55,9 +48,6 @@ export function missingAdapter(adapter: string, e: unknown): MissingAdapter | nu
|
||||
action: "Reinstall and Debug",
|
||||
};
|
||||
}
|
||||
if (adapter === "lldb-dap" && e.kind === "unavailable" && e.message.startsWith(NO_NATIVE_DEBUGGER)) {
|
||||
return { tool: "codelldb", title: NO_NATIVE_DEBUGGER, body: e.message, action: "Install CodeLLDB and Debug" };
|
||||
}
|
||||
const entry = INSTALLABLE[adapter];
|
||||
if (!entry || e.kind !== "unavailable") return null;
|
||||
if (adapter === "debugpy" && e.message.startsWith("debugpy is not installed")) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import DOMPurify from "dompurify";
|
||||
import { Marked } from "marked";
|
||||
import { mathExtension } from "@/editor/lsp/markdownMath";
|
||||
import { renderMath } from "@/editor/lsp/renderMarkdownMath";
|
||||
import { mathExtension, renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { mimeText, object, own } from "./outputs";
|
||||
|
||||
export const OUTPUT_CSP =
|
||||
|
||||
@@ -217,8 +217,7 @@ function CommitRowView({
|
||||
key={cid}
|
||||
className={clsx(
|
||||
styles.columnCell,
|
||||
// Dimmed with the subject: merge commits and commits outside the cherry-pick selection.
|
||||
(merge || outsideUnpicked) && styles.muted,
|
||||
styles.muted,
|
||||
column.id === "author" && mine && styles.mine,
|
||||
column.id === "hash" && styles.hash,
|
||||
)}
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
import {
|
||||
Suspense,
|
||||
use,
|
||||
useDeferredValue,
|
||||
useEffect,
|
||||
useLayoutEffect,
|
||||
useMemo,
|
||||
@@ -62,16 +63,13 @@ import {
|
||||
} from "./live";
|
||||
import { subscribeTheme, themeKey } from "@/platform/themeWatch";
|
||||
import { hasMermaid, MERMAID_SELECTOR, renderMermaidIn } from "./mermaid";
|
||||
import { declaresMathMacros } from "@/editor/lsp/markdownMath";
|
||||
import { renderMath } from "@/editor/lsp/renderMarkdownMath";
|
||||
import { declaresMathMacros, renderMath } from "@/editor/lsp/markdownMath";
|
||||
import type { renderMathSvg } from "./mathSvg";
|
||||
import { modeOf, pinMarkdownMode, useMarkdownModes } from "./modes";
|
||||
import { MarkdownLayoutActions } from "./MarkdownLayoutActions";
|
||||
import {
|
||||
ANCHOR_PREFIX,
|
||||
createMarkdownMarkupRenderer,
|
||||
markdownMarkupHtml,
|
||||
type MarkdownMarkup,
|
||||
createMarkdownRenderer,
|
||||
headingLine,
|
||||
isRenderedFence,
|
||||
previewLineAtOffset,
|
||||
@@ -88,8 +86,6 @@ import { iconNode } from "@/ui/iconNode";
|
||||
import { isMarkdownPath } from "../fileKinds";
|
||||
import { attachPanZoom } from "../panZoom";
|
||||
import { createPreviewImageLoader } from "../previewImages";
|
||||
import { patchPreviewBlocks, hasPreviewBlocks } from "./previewBlocks";
|
||||
import { createPreviewWorker } from "./previewWorker";
|
||||
|
||||
/**
|
||||
* Line of the heading `anchor` in the Markdown file `path`, from an open editor's text (unsaved
|
||||
@@ -305,47 +301,27 @@ function loadSvgRenderer() {
|
||||
));
|
||||
}
|
||||
|
||||
const previewMarkupCache = new WeakMap<Text, MarkdownMarkup>();
|
||||
const parkedPreviews = new WeakMap<EditorView, { source: Text; root: HTMLElement; markup: MarkdownMarkup }>();
|
||||
let lastParse: { source: Text; html: string } | undefined;
|
||||
const parkedPreviews = new WeakMap<EditorView, { source: Text; root: HTMLElement; html: string }>();
|
||||
const previewGraphics = new WeakMap<HTMLElement, Map<string, HTMLElement[]>>();
|
||||
const highlightedCode = new WeakSet<HTMLElement>();
|
||||
const MATH_ATTRIBUTE = ' data-math="';
|
||||
|
||||
function previewMarkup(source: Text, render: (text: string) => MarkdownMarkup, view: EditorView | null | undefined) {
|
||||
function previewMarkup(source: Text, render: (text: string) => string, view: EditorView | null | undefined) {
|
||||
const parked = view && parkedPreviews.get(view);
|
||||
if (parked?.source === source) return parked.markup;
|
||||
let markup = previewMarkupCache.get(source);
|
||||
if (markup === undefined) {
|
||||
markup = render(source.toString());
|
||||
previewMarkupCache.set(source, markup);
|
||||
}
|
||||
return markup;
|
||||
if (parked?.source === source) return parked.html;
|
||||
if (lastParse?.source !== source) lastParse = { source, html: render(source.toString()) };
|
||||
return lastParse.html;
|
||||
}
|
||||
|
||||
function typesetPreview(content: HTMLElement, previous: HTMLElement, svg: typeof renderMathSvg | null) {
|
||||
const inputs = [...content.querySelectorAll<HTMLElement>("[data-math], [data-mermaid]")];
|
||||
// A declaration can change the meaning of a later formula with identical source.
|
||||
const declaresMacros = inputs.some((el) => el.hasAttribute("data-math") && declaresMathMacros(el.textContent ?? ""));
|
||||
const available = new Map<string, HTMLElement[]>();
|
||||
const available = previewGraphics.get(previous);
|
||||
const rendered = new Map<string, HTMLElement[]>();
|
||||
const retained = new Set<HTMLElement>();
|
||||
for (const [key, copies] of previewGraphics.get(previous) ?? []) {
|
||||
const kept = [];
|
||||
const detached = [];
|
||||
for (const copy of copies) {
|
||||
if (content.contains(copy)) {
|
||||
kept.push(copy);
|
||||
retained.add(copy);
|
||||
} else detached.push(copy);
|
||||
}
|
||||
if (kept.length) rendered.set(key, kept);
|
||||
if (detached.length) available.set(key, detached);
|
||||
}
|
||||
for (const input of inputs) {
|
||||
if (retained.has(input)) continue;
|
||||
if (input.hasAttribute("data-math") && (declaresMacros || input.childElementCount)) continue;
|
||||
const key = input.outerHTML;
|
||||
const found = available.get(key)?.pop();
|
||||
const found = available?.get(key)?.pop();
|
||||
if (found) input.replaceWith(found);
|
||||
const copies = rendered.get(key);
|
||||
if (copies) copies.push(found ?? input);
|
||||
@@ -406,7 +382,6 @@ function attachCodeCopy(pre: HTMLElement, source: string) {
|
||||
function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; sync: boolean }) {
|
||||
const shown = useEditorShown();
|
||||
const text = useLiveMarkdown((s) => s[path]?.text);
|
||||
const edit = useLiveMarkdown((s) => s[path]?.edit ?? null);
|
||||
const fontZoom = useLiveMarkdown((s) => s[path]?.fontZoom ?? 0);
|
||||
const fontSize = useMarkdownPreviewFontSize();
|
||||
const zoomScale = Number((Math.max(4, fontSize + fontZoom) / fontSize).toFixed(4));
|
||||
@@ -416,44 +391,18 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
const find = useLiveMarkdown((s) => s[path]?.find ?? null);
|
||||
const editorSelection = useLiveMarkdown((s) => s[path]?.editorSelection ?? "");
|
||||
const highlightSelection = useEditorPrefs().codeEditing.highlightSelection;
|
||||
const nextSource = text ?? Text.empty;
|
||||
const [render] = useState(createMarkdownMarkupRenderer);
|
||||
const deferred = useDeferredValue(text ?? Text.empty);
|
||||
const [render] = useState(createMarkdownRenderer);
|
||||
const slot = editorController().slotFor(tabId);
|
||||
const [rendered, setRendered] = useState(() => ({
|
||||
source: nextSource,
|
||||
markup: previewMarkup(nextSource, render, slot?.live),
|
||||
}));
|
||||
const { source: renderedSource, markup } = rendered;
|
||||
const worker = useRef<ReturnType<typeof createPreviewWorker> | null>(null);
|
||||
useEffect(
|
||||
() => () => {
|
||||
worker.current?.dispose();
|
||||
worker.current = null;
|
||||
},
|
||||
[path, shown],
|
||||
);
|
||||
useEffect(() => {
|
||||
if (!shown || (!worker.current && nextSource === renderedSource)) return;
|
||||
const parser = (worker.current ??= createPreviewWorker(render, setRendered, rendered));
|
||||
parser.queue(
|
||||
nextSource,
|
||||
edit?.after === nextSource ? edit : null,
|
||||
(source, block) => sync && sourceEditingBlock(slot?.live, source, block.line, block.endLine),
|
||||
);
|
||||
}, [nextSource, edit, rendered, renderedSource, render, shown, slot, sync]);
|
||||
|
||||
const html = useMemo(() => previewMarkup(deferred, render, slot?.live), [render, deferred, slot]);
|
||||
const sourceOffsets = useMemo(() => {
|
||||
if (!sync) return undefined;
|
||||
const offsets = [0];
|
||||
for (let n = 2; n <= renderedSource.lines; n++) offsets.push(renderedSource.line(n).from);
|
||||
offsets.push(renderedSource.length);
|
||||
for (let n = 2; n <= deferred.lines; n++) offsets.push(deferred.line(n).from);
|
||||
offsets.push(deferred.length);
|
||||
return offsets;
|
||||
}, [renderedSource, sync]);
|
||||
const hasMath =
|
||||
typeof markup === "string"
|
||||
? markup.includes(MATH_ATTRIBUTE)
|
||||
: markup.some((block) => block.html.includes(MATH_ATTRIBUTE));
|
||||
const renderSvg = hasMath ? use(loadSvgRenderer()) : null;
|
||||
}, [deferred, sync]);
|
||||
const renderSvg = html.includes(' data-math="') ? use(loadSvgRenderer()) : null;
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
const linkRequest = useRef(0);
|
||||
const blocks = useRef<ReturnType<typeof blocksOf>>([]);
|
||||
@@ -486,25 +435,18 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
const view = slot?.live;
|
||||
const parked = view && parkedPreviews.get(view);
|
||||
if (view) parkedPreviews.delete(view);
|
||||
const cached = parked?.markup === markup ? parked.root : null;
|
||||
const cached = parked?.html === html ? parked.root : null;
|
||||
if (cached !== root) {
|
||||
if (cached) {
|
||||
root.replaceChildren(...cached.children);
|
||||
const graphics = previewGraphics.get(cached);
|
||||
if (graphics) previewGraphics.set(root, graphics);
|
||||
} else {
|
||||
const previous = parked?.root ?? root;
|
||||
const previousContent = previous.firstElementChild;
|
||||
const patch =
|
||||
typeof markup !== "string" &&
|
||||
!markup.some((block) => block.html.includes(MATH_ATTRIBUTE) && declaresMathMacros(block.html));
|
||||
const content =
|
||||
patch && previousContent instanceof HTMLElement && hasPreviewBlocks(previousContent)
|
||||
? previousContent
|
||||
: newPreviewContent(patch ? "" : markdownMarkupHtml(markup));
|
||||
if (patch) patchPreviewBlocks(content, markup);
|
||||
previewGraphics.set(root, typesetPreview(content, previous, renderSvg));
|
||||
if (content.parentElement !== root) root.replaceChildren(content);
|
||||
const content = document.createElement("div");
|
||||
content.dataset.previewBlocks = "";
|
||||
content.innerHTML = html;
|
||||
previewGraphics.set(root, typesetPreview(content, parked?.root ?? root, renderSvg));
|
||||
root.replaceChildren(content);
|
||||
}
|
||||
}
|
||||
root.querySelectorAll("details").forEach((d, i) => {
|
||||
@@ -514,58 +456,27 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
blocks.current = blocksOf(root);
|
||||
invalidatePreviewIndex(root);
|
||||
return () => {
|
||||
if (view) parkedPreviews.set(view, { source: renderedSource, markup, root });
|
||||
if (view) parkedPreviews.set(view, { source: deferred, html, root });
|
||||
};
|
||||
}, [markup, renderedSource, slot, renderSvg]);
|
||||
}, [html, deferred, slot, renderSvg]);
|
||||
|
||||
const editingMarkdown = edit !== null;
|
||||
// Reuse cached diagrams before paint and keep their SVGs visible during source edits
|
||||
// Mermaid diagrams: before paint, so cached ones don't flash their source.
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || !shown || !hasMermaid(root)) return;
|
||||
const editor = slot?.live;
|
||||
let waiting = false;
|
||||
let pass: ReturnType<typeof renderMermaidIn> | undefined;
|
||||
if (!root || !hasMermaid(root)) return;
|
||||
const pass = renderMermaidIn(root, diagrams.current);
|
||||
let live = true;
|
||||
const shouldDefer = () =>
|
||||
!!editor &&
|
||||
editingMarkdown &&
|
||||
sync &&
|
||||
(editor.state.doc !== renderedSource || editor.contentDOM.ownerDocument.activeElement === editor.contentDOM);
|
||||
const draw = () => {
|
||||
pass?.cancel();
|
||||
waiting = false;
|
||||
const next = renderMermaidIn(root, diagrams.current, () => {
|
||||
if (!shouldDefer()) return false;
|
||||
waiting = true;
|
||||
return true;
|
||||
});
|
||||
pass = next;
|
||||
if (next.async) void next.done.then(() => live && pass === next && setDiagramsDrawn((n) => n + 1));
|
||||
};
|
||||
const resume = () => {
|
||||
if (!live) return;
|
||||
worker.current?.flush();
|
||||
if (waiting && !shouldDefer()) draw();
|
||||
};
|
||||
const afterBlur = () => queueMicrotask(resume);
|
||||
const off = useLiveMarkdown.subscribe((next, previous) => {
|
||||
if (next[path]?.caretSeq !== previous[path]?.caretSeq) queueMicrotask(resume);
|
||||
});
|
||||
editor?.dom.addEventListener("focusout", afterBlur);
|
||||
draw();
|
||||
if (pass.async) void pass.done.then(() => live && setDiagramsDrawn((n) => n + 1));
|
||||
return () => {
|
||||
live = false;
|
||||
pass?.cancel();
|
||||
off();
|
||||
editor?.dom.removeEventListener("focusout", afterBlur);
|
||||
pass.cancel();
|
||||
};
|
||||
}, [editingMarkdown, markup, path, renderedSource, shown, slot, sync, theme]);
|
||||
}, [html, theme]);
|
||||
|
||||
// Images and code highlighting after each render.
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || !shown) return;
|
||||
if (!root) return;
|
||||
let live = true;
|
||||
const size = (img: HTMLImageElement, intrinsic?: { w: number; h: number } | null) =>
|
||||
applyImageZoomWidth(img, intrinsic, img.closest<HTMLElement>(`.${IMAGE_ZOOM}`) ?? img);
|
||||
@@ -641,8 +552,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
const pre = code.parentElement!;
|
||||
const src = (code.textContent ?? "").replace(/\n+$/, "");
|
||||
if (isRenderedFence(pre)) attachCodeCopy(pre, src);
|
||||
if (code.closest(MERMAID_SELECTOR) || highlightedCode.has(code)) return;
|
||||
highlightedCode.add(code);
|
||||
if (code.closest(MERMAID_SELECTOR)) return;
|
||||
const lang = [...code.classList].find((c) => c.startsWith("language-"))?.slice("language-".length) ?? null;
|
||||
code.textContent = src;
|
||||
void highlightInto(code, src, lang);
|
||||
@@ -652,7 +562,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
images.dispose();
|
||||
for (const img of imgs) img.onload = null;
|
||||
};
|
||||
}, [markup, path, shown]);
|
||||
}, [html, path]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
@@ -669,7 +579,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
|
||||
useLayoutEffect(() => {
|
||||
follower.current?.align();
|
||||
}, [path, sync, markup, sourceOffsets, diagramsDrawn, fontZoom, fontSize]);
|
||||
}, [path, sync, html, sourceOffsets, diagramsDrawn, fontZoom, fontSize]);
|
||||
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
@@ -689,37 +599,16 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
},
|
||||
{ root, rootMargin: "100% 0px" },
|
||||
);
|
||||
const containerSelector = ":scope > [data-preview-blocks]";
|
||||
let container: Element | null = null;
|
||||
// The blocks to watch: the preview's content is replaced without a new `html` too (a parked
|
||||
// preview restored on a tab switch, a theme or diagram re-render).
|
||||
const observeBlocks = () => {
|
||||
const next = root.querySelector(containerSelector);
|
||||
if (next !== container) {
|
||||
container = next;
|
||||
replaced.disconnect();
|
||||
replaced.observe(root, { childList: true });
|
||||
if (container) replaced.observe(container, { childList: true });
|
||||
}
|
||||
visibility.disconnect();
|
||||
for (const block of container?.children ?? []) {
|
||||
if (block.hasAttribute("data-line")) visibility.observe(block);
|
||||
}
|
||||
for (const block of root.querySelectorAll(":scope > [data-preview-blocks] > [data-line]"))
|
||||
visibility.observe(block);
|
||||
};
|
||||
const replaced = new MutationObserver((records) => {
|
||||
if (records.some((record) => record.target === root)) {
|
||||
observeBlocks();
|
||||
return;
|
||||
}
|
||||
for (const record of records) {
|
||||
for (const block of record.removedNodes) {
|
||||
if (block instanceof Element) visibility.unobserve(block);
|
||||
}
|
||||
for (const block of record.addedNodes) {
|
||||
if (block instanceof Element && block.hasAttribute("data-line")) visibility.observe(block);
|
||||
}
|
||||
}
|
||||
});
|
||||
replaced.observe(root, { childList: true });
|
||||
observeBlocks();
|
||||
const replaced = new MutationObserver(observeBlocks);
|
||||
replaced.observe(root, { childList: true });
|
||||
|
||||
let timer: number | undefined;
|
||||
let restoredTop: number | undefined;
|
||||
@@ -814,7 +703,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
root.removeAttribute("data-constrain-blocks");
|
||||
follower.current?.resume();
|
||||
};
|
||||
}, [sync]);
|
||||
}, [html, sync]);
|
||||
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
@@ -823,7 +712,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
measure();
|
||||
root.addEventListener("toggle", measure, true);
|
||||
return () => root.removeEventListener("toggle", measure, true);
|
||||
}, [markup, diagramsDrawn, fontZoom, fontSize]);
|
||||
}, [html, diagramsDrawn, fontZoom, fontSize]);
|
||||
|
||||
// Restore Preview Only after a mode change or eviction from the kept tabs.
|
||||
useEffect(() => {
|
||||
@@ -864,14 +753,14 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
root.scrollTop = saved;
|
||||
scrolledTo.current = root.scrollTop;
|
||||
if (root.scrollTop >= saved) restoreRetry.current = null;
|
||||
}, [markup, diagramsDrawn, fontZoom, fontSize, path, sync]);
|
||||
}, [html, diagramsDrawn, fontZoom, fontSize, path, sync]);
|
||||
|
||||
// Preview only: go where the hidden editor's caret was sent (Structure, Go to Symbol…).
|
||||
useLayoutEffect(() => {
|
||||
const root = ref.current;
|
||||
if (!root || !shown || caretSeq === seenCaret.current) return;
|
||||
// First-open navigation can arrive before the destination’s Markdown is rendered.
|
||||
if (!sync && renderedSource !== text) return;
|
||||
// First-open navigation can arrive before the destination's deferred Markdown is rendered.
|
||||
if (!sync && deferred !== text) return;
|
||||
seenCaret.current = caretSeq;
|
||||
if (sync) return;
|
||||
if (find && find.currentMatchIndex >= 0) {
|
||||
@@ -893,7 +782,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
restoreRetry.current = null;
|
||||
}
|
||||
setShownLine(path, caretLine);
|
||||
}, [caretSeq, caretLine, shown, sync, path, find, renderedSource, text]);
|
||||
}, [caretSeq, caretLine, shown, sync, path, find, deferred, text]);
|
||||
|
||||
// Search (⌘F) and selection occurrence highlights in the preview.
|
||||
useLayoutEffect(() => {
|
||||
@@ -963,7 +852,7 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
document.removeEventListener("selectionchange", applySelection);
|
||||
root.removeEventListener("toggle", applyAll, true);
|
||||
};
|
||||
}, [markup, path, shown, sync, find, editorSelection, highlightSelection]);
|
||||
}, [html, path, shown, sync, find, editorSelection, highlightSelection]);
|
||||
|
||||
useEffect(() => {
|
||||
const root = ref.current;
|
||||
@@ -1114,23 +1003,3 @@ function MarkdownPreview({ path, tabId, sync }: { path: string; tabId: string; s
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function newPreviewContent(html: string): HTMLElement {
|
||||
const content = document.createElement("div");
|
||||
content.dataset.previewBlocks = "";
|
||||
if (html) content.innerHTML = html;
|
||||
return content;
|
||||
}
|
||||
|
||||
function sourceEditingBlock(
|
||||
editor: EditorView | null | undefined,
|
||||
rendered: Text,
|
||||
line: number,
|
||||
endLine: number,
|
||||
): boolean {
|
||||
if (!editor) return false;
|
||||
if (editor.state.doc !== rendered) return true;
|
||||
if (editor.contentDOM.ownerDocument.activeElement !== editor.contentDOM) return false;
|
||||
const caret = editor.state.doc.lineAt(editor.state.selection.main.head).number - 1;
|
||||
return caret >= line && caret < endLine;
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { BlockType, EditorView, type BlockInfo } from "@codemirror/view";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { _emitEditorEvent, editorContributions, type EditorDocContext } from "@/editor/api";
|
||||
import { editorContributions, type EditorDocContext } from "@/editor/api";
|
||||
import { installMarkdownSourceScroll, registerMarkdownLiveSource, useLiveMarkdown } from "./live";
|
||||
|
||||
const ctx: EditorDocContext = { doc: 1, path: "/p/README.md", language: "markdown", uiMode: null, readOnly: false };
|
||||
@@ -33,14 +33,6 @@ describe("Markdown source scroll", () => {
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
it("releases parsed preview source when the document closes", () => {
|
||||
const other = { ...useLiveMarkdown.getState()[ctx.path]!, previewTop: 52 };
|
||||
useLiveMarkdown.setState({ "/p/other.md": other });
|
||||
expect(useLiveMarkdown.getState()[ctx.path]?.text).toBe(view.state.doc);
|
||||
_emitEditorEvent({ type: "docClosed", doc: ctx.doc, path: ctx.path });
|
||||
expect(useLiveMarkdown.getState()).toEqual({ "/p/other.md": other });
|
||||
});
|
||||
|
||||
function sourceBlock(lineNumber: number, top: number, height: number): BlockInfo {
|
||||
const { from, to, length } = view.state.doc.line(lineNumber);
|
||||
return {
|
||||
|
||||
@@ -7,13 +7,12 @@ import { StateEffect, Text, type EditorState } from "@codemirror/state";
|
||||
import { Decoration, Direction, EditorView, ViewPlugin, type DecorationSet, type ViewUpdate } from "@codemirror/view";
|
||||
import { SearchCursor, getSearchQuery } from "@codemirror/search";
|
||||
import { create } from "zustand";
|
||||
import { onEditorEvent, registerEditorContribution, useEditorRegistry } from "@/editor/api";
|
||||
import { registerEditorContribution, useEditorRegistry } from "@/editor/api";
|
||||
import { MAX_COUNT, findExcluded, findOpen, findScope } from "@/editor/core/cm/find";
|
||||
import { fontZoom, resetConfiguredEditorsFontZoom, stepConfiguredEditorsFontZoom } from "@/editor/core/cm/prefs";
|
||||
import { editorPrefs } from "@/platform/editorSettings";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { isMarkdownRevision } from "../fileKinds";
|
||||
import type { MarkdownEdit } from "./previewEdits";
|
||||
|
||||
export interface LiveMarkdownFind {
|
||||
search: string;
|
||||
@@ -28,7 +27,6 @@ export interface LiveMarkdownFind {
|
||||
|
||||
export interface LiveMarkdown {
|
||||
text: Text;
|
||||
edit?: MarkdownEdit | null;
|
||||
/** 0-based source line at the top of the editor, including progress through the line. */
|
||||
topLine: number;
|
||||
/** Whether the scrolling editor has reached its bottom. */
|
||||
@@ -253,7 +251,6 @@ function livePlugin(path: string) {
|
||||
class {
|
||||
decorations: DecorationSet = Decoration.none;
|
||||
private timer: ReturnType<typeof setTimeout> | undefined;
|
||||
private pendingEdit: MarkdownEdit | null = null;
|
||||
private scrolled = false;
|
||||
private destroyed = false;
|
||||
private previewSel = "";
|
||||
@@ -281,7 +278,6 @@ function livePlugin(path: string) {
|
||||
this.decorations = previewSelectionDecorations(view, this.previewSel);
|
||||
publish(path, {
|
||||
text: view.state.doc,
|
||||
edit: null,
|
||||
fontZoom: view.state.field(fontZoom, false) ?? 0,
|
||||
find: findStateOf(view.state),
|
||||
editorSelection: editorSelectionOf(view.state),
|
||||
@@ -292,8 +288,7 @@ function livePlugin(path: string) {
|
||||
if (next === this.previewSel) return;
|
||||
this.previewSel = next;
|
||||
queueMicrotask(() => {
|
||||
if (!this.destroyed && this.previewSel === next)
|
||||
this.view.dispatch({ effects: setPreviewSelectionEffect.of(next) });
|
||||
if (this.previewSel === next) this.view.dispatch({ effects: setPreviewSelectionEffect.of(next) });
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -343,21 +338,8 @@ function livePlugin(path: string) {
|
||||
if (u.selectionSet) this.publishCaret();
|
||||
return;
|
||||
}
|
||||
const pending = this.pendingEdit;
|
||||
this.pendingEdit = {
|
||||
before: pending?.before ?? u.startState.doc,
|
||||
after: u.state.doc,
|
||||
changes: pending ? pending.changes.compose(u.changes) : u.changes,
|
||||
};
|
||||
clearTimeout(this.timer);
|
||||
this.timer = setTimeout(() => this.publishText(), TEXT_DELAY);
|
||||
}
|
||||
|
||||
private publishText() {
|
||||
const text = this.view.state.doc;
|
||||
const edit = this.pendingEdit;
|
||||
this.pendingEdit = null;
|
||||
publish(path, { text, edit: edit?.after === text ? edit : null });
|
||||
this.timer = setTimeout(() => publish(path, { text: this.view.state.doc }), TEXT_DELAY);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
@@ -366,7 +348,7 @@ function livePlugin(path: string) {
|
||||
this.unsubscribe();
|
||||
this.view.scrollDOM.removeEventListener("scroll", this.onScroll);
|
||||
// Flush the latest edit for a preview that outlives this view.
|
||||
this.publishText();
|
||||
publish(path, { text: this.view.state.doc });
|
||||
}
|
||||
},
|
||||
{ decorations: (v) => v.decorations },
|
||||
@@ -374,7 +356,7 @@ function livePlugin(path: string) {
|
||||
}
|
||||
|
||||
export function registerMarkdownLiveSource(): () => void {
|
||||
const unregister = registerEditorContribution({
|
||||
return registerEditorContribution({
|
||||
id: "viewers.markdownLive",
|
||||
// The document's language: contributions are rebuilt when File Types change it.
|
||||
extensions: (ctx) =>
|
||||
@@ -382,18 +364,4 @@ export function registerMarkdownLiveSource(): () => void {
|
||||
? [livePlugin(ctx.path)]
|
||||
: [],
|
||||
});
|
||||
const unsubscribe = onEditorEvent((event) => {
|
||||
if (event.type !== "docClosed") return;
|
||||
const { path } = event;
|
||||
useLiveMarkdown.setState((state) => {
|
||||
if (!state[path]) return state;
|
||||
const next = { ...state };
|
||||
delete next[path];
|
||||
return next;
|
||||
}, true);
|
||||
});
|
||||
return () => {
|
||||
unsubscribe();
|
||||
unregister();
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { renderMath } from "@/editor/lsp/renderMarkdownMath";
|
||||
import { renderMath } from "@/editor/lsp/markdownMath";
|
||||
import { renderMathSvg } from "./mathSvg";
|
||||
import { renderMarkdown } from "./render";
|
||||
|
||||
|
||||
@@ -143,27 +143,6 @@ describe("mermaid in the markdown preview", () => {
|
||||
expect(ids.size).toBe(2);
|
||||
});
|
||||
|
||||
it("keeps the old SVG without rendering an edited diagram until it is released", async () => {
|
||||
const original = preview(SEQ);
|
||||
const previous: Node[] = [];
|
||||
await renderMermaidIn(original, previous).done;
|
||||
const editedSource = SEQ.replace("test", "edited");
|
||||
const edited = preview(editedSource);
|
||||
|
||||
const held = renderMermaidIn(edited, previous, () => true);
|
||||
await held.done;
|
||||
expect(held.async).toBe(false);
|
||||
expect(m.render).toHaveBeenCalledTimes(1);
|
||||
expect(edited.querySelector(".mermaid-output svg text")?.textContent).toBe("sequenceDiagram");
|
||||
|
||||
const released = renderMermaidIn(edited, previous, () => false);
|
||||
await released.done;
|
||||
expect(m.render.mock.calls.map(([, source]) => source)).toEqual([
|
||||
original.querySelector("pre code")!.textContent!.trimEnd(),
|
||||
edited.querySelector("pre code")!.textContent!.trimEnd(),
|
||||
]);
|
||||
});
|
||||
|
||||
it("leaves a diagram it already drew in place on the next pass", async () => {
|
||||
const root = preview(SEQ);
|
||||
await renderMermaidIn(root, []).done;
|
||||
|
||||
@@ -291,7 +291,7 @@ export interface MermaidPass {
|
||||
* output per block index of the same preview (updated in place) and stands in
|
||||
* while a changed diagram renders. Cached results are applied synchronously.
|
||||
*/
|
||||
export function renderMermaidIn(root: HTMLElement, previous: Node[] = [], defer?: () => boolean): MermaidPass {
|
||||
export function renderMermaidIn(root: HTMLElement, previous: Node[] = []): MermaidPass {
|
||||
const blocks = [...root.querySelectorAll<HTMLElement>(MERMAID_SELECTOR)];
|
||||
let live = true;
|
||||
if (!blocks.length) return { async: false, done: Promise.resolve(), cancel: () => {} };
|
||||
@@ -318,14 +318,10 @@ export function renderMermaidIn(root: HTMLElement, previous: Node[] = [], defer?
|
||||
return;
|
||||
}
|
||||
drawn.delete(block);
|
||||
if (defer?.()) {
|
||||
if (!block.querySelector(`:scope > .${OUTPUT_CLASS}`)) show(block, null, previous[i]);
|
||||
return;
|
||||
}
|
||||
show(block, null, previous[i]);
|
||||
let result = rendering.get(k);
|
||||
if (!result) {
|
||||
result = enqueue(source, key, () => live && !defer?.());
|
||||
result = enqueue(source, key, () => live);
|
||||
rendering.set(k, result);
|
||||
}
|
||||
pending.push(
|
||||
|
||||
@@ -1,17 +0,0 @@
|
||||
import { parseMarkdownBlocks, type MarkdownBlock } from "./render";
|
||||
|
||||
export interface PreviewParseRequest {
|
||||
id: number;
|
||||
source: string;
|
||||
fenceMarker: string;
|
||||
}
|
||||
|
||||
export interface PreviewParseResult {
|
||||
id: number;
|
||||
blocks: MarkdownBlock[];
|
||||
}
|
||||
|
||||
self.onmessage = (event: MessageEvent<PreviewParseRequest>) => {
|
||||
const { id, source, fenceMarker } = event.data;
|
||||
self.postMessage({ id, blocks: parseMarkdownBlocks(source, fenceMarker) } satisfies PreviewParseResult);
|
||||
};
|
||||
@@ -1,51 +0,0 @@
|
||||
import { markdownMarkupHtml, type MarkdownBlock } from "./render";
|
||||
|
||||
type MountedBlock = { html: string; node: HTMLElement };
|
||||
const mounted = new WeakMap<HTMLElement, MountedBlock[]>();
|
||||
|
||||
export function hasPreviewBlocks(content: HTMLElement): boolean {
|
||||
return mounted.has(content);
|
||||
}
|
||||
|
||||
export function patchPreviewBlocks(content: HTMLElement, blocks: readonly MarkdownBlock[]): void {
|
||||
const previous = mounted.get(content);
|
||||
if (!previous) {
|
||||
content.innerHTML = markdownMarkupHtml(blocks);
|
||||
mounted.set(
|
||||
content,
|
||||
blocks.map(({ html }, index) => ({ html, node: content.children[index] as HTMLElement })),
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const available = new Map<string, MountedBlock[]>();
|
||||
for (let index = previous.length - 1; index >= 0; index--) {
|
||||
const block = previous[index]!;
|
||||
const copies = available.get(block.html);
|
||||
if (copies) copies.push(block);
|
||||
else available.set(block.html, [block]);
|
||||
}
|
||||
|
||||
const next = blocks.map(({ line, endLine, html }) => {
|
||||
const block = available.get(html)?.pop() ?? newBlock(html);
|
||||
const start = String(line);
|
||||
const end = String(endLine);
|
||||
if (block.node.dataset.line !== start) block.node.dataset.line = start;
|
||||
if (block.node.dataset.endLine !== end) block.node.dataset.endLine = end;
|
||||
return block;
|
||||
});
|
||||
|
||||
for (const copies of available.values()) for (const block of copies) block.node.remove();
|
||||
let cursor = content.firstElementChild;
|
||||
for (const { node } of next) {
|
||||
if (node === cursor) cursor = node.nextElementSibling;
|
||||
else content.insertBefore(node, cursor);
|
||||
}
|
||||
mounted.set(content, next);
|
||||
}
|
||||
|
||||
function newBlock(html: string): MountedBlock {
|
||||
const node = document.createElement("div");
|
||||
node.innerHTML = html;
|
||||
return { html, node };
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import type { ChangeSet, Text } from "@codemirror/state";
|
||||
import { ANCHOR_PREFIX, slugify, type MarkdownBlock, type MarkdownMarkup } from "./render";
|
||||
|
||||
export interface MarkdownEdit {
|
||||
before: Text;
|
||||
after: Text;
|
||||
changes: ChangeSet;
|
||||
}
|
||||
|
||||
export interface RenderedMarkdown {
|
||||
source: Text;
|
||||
markup: MarkdownMarkup;
|
||||
}
|
||||
|
||||
const prose = /^[\p{L}\p{N}\p{M}\n .,!?:;"'\u2019\u2013\u2014-]*$/u;
|
||||
const heading = /^(#{1,6}) +(.+)$/u;
|
||||
const headingId = new RegExp(`^<h[1-6] id="${ANCHOR_PREFIX}([^"]*)"`);
|
||||
|
||||
export function changedPreviewBlock(preview: RenderedMarkdown, edit: MarkdownEdit) {
|
||||
if (typeof preview.markup === "string" || preview.source !== edit.before || edit.changes.empty) return null;
|
||||
|
||||
let from = edit.before.length;
|
||||
let to = 0;
|
||||
edit.changes.iterChangedRanges((fromA, toA) => {
|
||||
from = Math.min(from, fromA);
|
||||
to = Math.max(to, toA);
|
||||
});
|
||||
|
||||
const first = edit.before.lineAt(from).number - 1;
|
||||
const blocks = preview.markup;
|
||||
const index = blocks.findIndex((block) => block.line <= first && first < block.endLine);
|
||||
const block = blocks[index];
|
||||
if (!block || to > edit.before.line(block.endLine).to) return null;
|
||||
if (
|
||||
(block.line > 0 && edit.before.line(block.line).length !== 0) ||
|
||||
(block.endLine < edit.before.lines && edit.before.line(block.endLine + 1).length !== 0)
|
||||
) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const lineDelta = edit.after.lines - edit.before.lines;
|
||||
const endLine = block.endLine + lineDelta;
|
||||
if (endLine <= block.line) return null;
|
||||
|
||||
const before = blockText(edit.before, block.line, block.endLine);
|
||||
const after = blockText(edit.after, block.line, endLine);
|
||||
const prefix = block.html.startsWith("<p>")
|
||||
? paragraphPrefix(before, after)
|
||||
: (diagramPrefix(block.html, before, after) ?? headingPrefix(blocks, index, before, after));
|
||||
if (!prefix) return null;
|
||||
|
||||
const boundary = "\n".repeat(Math.min(2, edit.after.lines - endLine));
|
||||
return { blocks, index, line: block.line, endLine, lineDelta, prefix, text: after + boundary };
|
||||
}
|
||||
|
||||
function blockText(doc: Text, line: number, endLine: number): string {
|
||||
return doc.sliceString(doc.line(line + 1).from, doc.line(endLine).to);
|
||||
}
|
||||
|
||||
const paragraphBoundary = /[[\]<>]|\n[ \t]*\n|^ {0,3}(?:\$\$|\x60{3,}|~{3,})/m;
|
||||
|
||||
function paragraphPrefix(before: string, after: string): string | null {
|
||||
if (!/^\p{L}/u.test(before) || !/^\p{L}/u.test(after)) return null;
|
||||
if (paragraphBoundary.test(before) || paragraphBoundary.test(after)) return null;
|
||||
return "<p>";
|
||||
}
|
||||
|
||||
export const MERMAID_BLOCK = '<div data-mermaid="">';
|
||||
const MATH_BLOCK = '<div data-math="display">';
|
||||
const FENCE = /^ {0,3}(\x60{3,}|~{3,})[ \t]*(mermaid|math)(?:[ \t].*)?$/i;
|
||||
const INLINE_DISPLAY = /^ {0,3}(\$\$|\\\[).*(\$\$|\\\])[ \t]*$/;
|
||||
|
||||
function diagramPrefix(markup: string, before: string, after: string): string | null {
|
||||
const prefix = markup.startsWith(MERMAID_BLOCK) ? MERMAID_BLOCK : markup.startsWith(MATH_BLOCK) ? MATH_BLOCK : null;
|
||||
if (!prefix) return null;
|
||||
|
||||
if (prefix === MATH_BLOCK && !before.includes("\n") && !after.includes("\n")) {
|
||||
const previous = INLINE_DISPLAY.exec(before);
|
||||
const next = INLINE_DISPLAY.exec(after);
|
||||
return previous && next && previous[1] === next[1] && previous[2] === next[2] ? prefix : null;
|
||||
}
|
||||
|
||||
const previous = before.split("\n");
|
||||
const next = after.split("\n");
|
||||
const start = previous[0]!;
|
||||
const end = previous.at(-1)!;
|
||||
if (previous.length < 2 || next.length < 2 || start !== next[0] || end !== next.at(-1)) return null;
|
||||
|
||||
const fence = FENCE.exec(start);
|
||||
if (fence) {
|
||||
const delimiter = fence[1]!;
|
||||
const closing = new RegExp(`^ {0,3}${delimiter[0]}{${delimiter.length},}[ \t]*$`);
|
||||
const language = fence[2]!.toLowerCase();
|
||||
return closing.test(end) && (language === "mermaid" ? prefix === MERMAID_BLOCK : prefix === MATH_BLOCK)
|
||||
? prefix
|
||||
: null;
|
||||
}
|
||||
if (prefix === MATH_BLOCK) {
|
||||
const marker = start.trim();
|
||||
if ((marker === "$$" && end.trim() === "$$") || (marker === "\\[" && end.trim() === "\\]")) return prefix;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function headingPrefix(blocks: readonly MarkdownBlock[], index: number, before: string, after: string): string | null {
|
||||
const previous = heading.exec(before);
|
||||
const next = heading.exec(after);
|
||||
if (!previous || !next || previous[1] !== next[1] || !prose.test(previous[2]!) || !prose.test(next[2]!)) return null;
|
||||
const oldSlug = slugify(previous[2]!);
|
||||
const newSlug = slugify(next[2]!);
|
||||
const depth = previous[1]!.length;
|
||||
if (!oldSlug || !newSlug || !blocks[index]!.html.startsWith(`<h${depth} id="${ANCHOR_PREFIX}${oldSlug}">`))
|
||||
return null;
|
||||
|
||||
const collides = (id: string, slug: string) =>
|
||||
id === slug || (id.startsWith(slug + "-") && /^\d+$/.test(id.slice(slug.length + 1)));
|
||||
for (let i = 0; i < blocks.length; i++) {
|
||||
if (i === index) continue;
|
||||
const id = headingId.exec(blocks[i]!.html)?.[1];
|
||||
if (id && (collides(id, oldSlug) || collides(id, newSlug))) return null;
|
||||
}
|
||||
return `<h${depth} id="${ANCHOR_PREFIX}${newSlug}">`;
|
||||
}
|
||||
@@ -1,267 +0,0 @@
|
||||
import { ChangeSet, Text } from "@codemirror/state";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { createPreviewWorker } from "./previewWorker";
|
||||
import {
|
||||
createMarkdownMarkupRenderer,
|
||||
markdownFenceMarker,
|
||||
renderMarkdown,
|
||||
markdownMarkupHtml,
|
||||
parseMarkdownBlocks,
|
||||
type MarkdownBlock,
|
||||
} from "./render";
|
||||
import type { PreviewParseRequest, PreviewParseResult } from "./preview.worker";
|
||||
|
||||
class TestWorker {
|
||||
onmessage?: (event: MessageEvent<PreviewParseResult>) => void;
|
||||
onerror?: () => void;
|
||||
onmessageerror?: () => void;
|
||||
postMessage = vi.fn<(request: PreviewParseRequest) => void>();
|
||||
terminate = vi.fn();
|
||||
|
||||
reply(id: number, blocks: MarkdownBlock[]) {
|
||||
this.onmessage?.(new MessageEvent("message", { data: { id, blocks } }));
|
||||
}
|
||||
}
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
it("keeps only the latest edit waiting for the active preview parse", () => {
|
||||
const worker = new TestWorker();
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
vi.fn(function () {
|
||||
return worker;
|
||||
}),
|
||||
);
|
||||
const publish = vi.fn();
|
||||
const render = vi.fn((input: string | readonly MarkdownBlock[]) => input);
|
||||
const preview = createPreviewWorker(render, publish, { source: Text.empty, markup: [] });
|
||||
const first = Text.of(["first"]);
|
||||
const skipped = Text.of(["skipped"]);
|
||||
const latest = Text.of(["latest"]);
|
||||
const firstBlocks = [{ line: 2, endLine: 4, html: "<p>first</p>" }];
|
||||
const latestBlocks = [{ line: 5, endLine: 6, html: "<p>latest</p>" }];
|
||||
|
||||
preview.queue(first);
|
||||
preview.queue(skipped);
|
||||
preview.queue(latest);
|
||||
|
||||
expect(worker.postMessage.mock.calls).toEqual([[{ id: 1, source: "first", fenceMarker: markdownFenceMarker }]]);
|
||||
worker.reply(1, firstBlocks);
|
||||
worker.reply(1, firstBlocks);
|
||||
worker.reply(2, latestBlocks);
|
||||
preview.queue(latest);
|
||||
|
||||
expect(worker.postMessage.mock.calls).toEqual([
|
||||
[{ id: 1, source: "first", fenceMarker: markdownFenceMarker }],
|
||||
[{ id: 2, source: "latest", fenceMarker: markdownFenceMarker }],
|
||||
]);
|
||||
expect(render.mock.calls).toEqual([[firstBlocks], [latestBlocks]]);
|
||||
expect(publish.mock.calls).toEqual([
|
||||
[{ source: first, markup: firstBlocks }],
|
||||
[{ source: latest, markup: latestBlocks }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("falls back to rendering the latest waiting edit when the worker fails", () => {
|
||||
const worker = new TestWorker();
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
vi.fn(function () {
|
||||
return worker;
|
||||
}),
|
||||
);
|
||||
const publish = vi.fn();
|
||||
const render = vi.fn((input: string | readonly MarkdownBlock[]) => input);
|
||||
const preview = createPreviewWorker(render, publish, { source: Text.empty, markup: [] });
|
||||
const latest = Text.of(["latest"]);
|
||||
preview.queue(Text.of(["old"]));
|
||||
preview.queue(latest);
|
||||
|
||||
worker.onerror?.();
|
||||
|
||||
expect(worker.terminate.mock.calls).toEqual([[]]);
|
||||
expect(render.mock.calls).toEqual([["latest"]]);
|
||||
expect(publish.mock.calls).toEqual([[{ source: latest, markup: "latest" }]]);
|
||||
});
|
||||
|
||||
it("sends only the changed paragraph and keeps the other sanitized blocks", () => {
|
||||
const worker = new TestWorker();
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
vi.fn(function () {
|
||||
return worker;
|
||||
}),
|
||||
);
|
||||
const publish = vi.fn();
|
||||
const render = createMarkdownMarkupRenderer();
|
||||
const original = Text.of(["A first paragraph.", "", "The second paragraph.", "", "A last paragraph."]);
|
||||
const markup = render(original.toString());
|
||||
if (typeof markup === "string") throw new Error("Expected separate Markdown blocks");
|
||||
const preview = createPreviewWorker(render, publish, { source: original, markup });
|
||||
const changes = ChangeSet.of({ from: original.line(3).from + 4, insert: "edited " }, original.length);
|
||||
const after = changes.apply(original);
|
||||
|
||||
preview.queue(after, { before: original, after, changes });
|
||||
expect(worker.postMessage.mock.calls).toEqual([
|
||||
[{ id: 1, source: "The edited second paragraph.\n\n", fenceMarker: markdownFenceMarker }],
|
||||
]);
|
||||
worker.reply(1, [{ line: 0, endLine: 1, html: "<p>The edited second paragraph.</p>\n" }]);
|
||||
|
||||
const [result] = publish.mock.calls[0]!;
|
||||
expect(result.source).toBe(after);
|
||||
expect(result.markup[0]).toBe(markup[0]);
|
||||
expect(result.markup[2]).toBe(markup[2]);
|
||||
expect(markdownMarkupHtml(result.markup)).toBe(renderMarkdown(after.toString()));
|
||||
});
|
||||
|
||||
it("composes skipped edits when another paragraph update is pending", () => {
|
||||
const worker = new TestWorker();
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
vi.fn(function () {
|
||||
return worker;
|
||||
}),
|
||||
);
|
||||
const render = createMarkdownMarkupRenderer();
|
||||
const publish = vi.fn();
|
||||
const original = Text.of(["A paragraph.", "", "Another paragraph."]);
|
||||
const preview = createPreviewWorker(render, publish, { source: original, markup: render(original.toString()) });
|
||||
|
||||
const insert = (before: Text, position: number, text: string) => {
|
||||
const changes = ChangeSet.of({ from: position, insert: text }, before.length);
|
||||
const after = changes.apply(before);
|
||||
preview.queue(after, { before, after, changes });
|
||||
return after;
|
||||
};
|
||||
const first = insert(original, 2, "new ");
|
||||
const second = insert(first, 6, "plain ");
|
||||
const latest = insert(second, 12, "text ");
|
||||
worker.reply(1, [{ line: 0, endLine: 1, html: "<p>A new paragraph.</p>\n" }]);
|
||||
worker.reply(2, [{ line: 0, endLine: 1, html: "<p>A new plain text paragraph.</p>\n" }]);
|
||||
|
||||
expect(worker.postMessage.mock.calls).toEqual([
|
||||
[{ id: 1, source: "A new paragraph.\n\n", fenceMarker: markdownFenceMarker }],
|
||||
[{ id: 2, source: "A new plain text paragraph.\n\n", fenceMarker: markdownFenceMarker }],
|
||||
]);
|
||||
expect(publish.mock.calls.map(([result]) => result.source)).toEqual([first, latest]);
|
||||
});
|
||||
|
||||
it("uses the whole document when an edited paragraph can resolve a reference", () => {
|
||||
const worker = new TestWorker();
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
vi.fn(function () {
|
||||
return worker;
|
||||
}),
|
||||
);
|
||||
const render = createMarkdownMarkupRenderer();
|
||||
const original = Text.of(["A link to [example].", "", "[example]: https://example.org"]);
|
||||
const preview = createPreviewWorker(render, vi.fn(), { source: original, markup: render(original.toString()) });
|
||||
const from = original.line(1).text.indexOf("example");
|
||||
const changes = ChangeSet.of({ from, to: from + 7, insert: "other" }, original.length);
|
||||
const after = changes.apply(original);
|
||||
|
||||
preview.queue(after, { before: original, after, changes });
|
||||
|
||||
expect(worker.postMessage.mock.calls).toEqual([
|
||||
[{ id: 1, source: "A link to [other].\n\n[example]: https://example.org", fenceMarker: markdownFenceMarker }],
|
||||
]);
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a title", "# A plain title", "plain", "different"],
|
||||
["a paragraph with more source lines", "Plain text\ncontinues here.", "continues", "continues\nslowly"],
|
||||
["inline math", "Plain text with $x$.", "$x$", "$x_i^{2}$"],
|
||||
["one-line display math", "$$x+1$$", "x+1", "x_i+2"],
|
||||
["display math", "$$\nx+1\n$$", "x+1", "\\frac{1}{2}"],
|
||||
["bracket display math", "\\[\nx+1\n\\]", "x+1", "x_{2}+3"],
|
||||
["fenced math", "~~~math\nx+1\n~~~", "x+1", "x_i^2"],
|
||||
["Mermaid", "~~~mermaid\nflowchart TD\nA --> B\n~~~", "A --> B", "A --> C[label]"],
|
||||
])("reparses only %s and matches a full render", (_, block, originalText, replacement) => {
|
||||
const worker = new TestWorker();
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
vi.fn(function () {
|
||||
return worker;
|
||||
}),
|
||||
);
|
||||
const render = createMarkdownMarkupRenderer();
|
||||
const publish = vi.fn();
|
||||
const original = Text.of((block + "\n\nOther content.").split("\n"));
|
||||
const preview = createPreviewWorker(render, publish, { source: original, markup: render(original.toString()) });
|
||||
const from = block.indexOf(originalText);
|
||||
const changes = ChangeSet.of({ from, to: from + originalText.length, insert: replacement }, original.length);
|
||||
const after = changes.apply(original);
|
||||
|
||||
preview.queue(after, { before: original, after, changes });
|
||||
|
||||
const expected = block.replace(originalText, replacement) + "\n\n";
|
||||
expect(worker.postMessage.mock.calls).toEqual([[{ id: 1, source: expected, fenceMarker: markdownFenceMarker }]]);
|
||||
worker.reply(1, parseMarkdownBlocks(expected));
|
||||
|
||||
const [result] = publish.mock.calls[0]!;
|
||||
expect(result.source).toBe(after);
|
||||
expect(markdownMarkupHtml(result.markup)).toBe(renderMarkdown(after.toString()));
|
||||
});
|
||||
|
||||
it.each([
|
||||
["a duplicate title", "# Same title\n\n# Same title", "Same", "New"],
|
||||
["a title that would duplicate another", "# My title\n\n# New title", "My", "New"],
|
||||
["a removed diagram fence", "~~~mermaid\nflowchart TD\nA --> B\n~~~", "B\n~~~", "B"],
|
||||
])("falls back to the whole document for %s", (_, source, originalText, replacement) => {
|
||||
const worker = new TestWorker();
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
vi.fn(function () {
|
||||
return worker;
|
||||
}),
|
||||
);
|
||||
const render = createMarkdownMarkupRenderer();
|
||||
const original = Text.of((source + "\n\nOther content.").split("\n"));
|
||||
const preview = createPreviewWorker(render, vi.fn(), { source: original, markup: render(original.toString()) });
|
||||
const from = source.indexOf(originalText);
|
||||
const changes = ChangeSet.of({ from, to: from + originalText.length, insert: replacement }, original.length);
|
||||
const after = changes.apply(original);
|
||||
|
||||
preview.queue(after, { before: original, after, changes });
|
||||
|
||||
expect(worker.postMessage.mock.calls).toEqual([
|
||||
[{ id: 1, source: after.toString(), fenceMarker: markdownFenceMarker }],
|
||||
]);
|
||||
});
|
||||
|
||||
it("holds the Mermaid preview block and sends only the latest source when editing ends", () => {
|
||||
const worker = new TestWorker();
|
||||
vi.stubGlobal(
|
||||
"Worker",
|
||||
vi.fn(function () {
|
||||
return worker;
|
||||
}),
|
||||
);
|
||||
const render = createMarkdownMarkupRenderer();
|
||||
const publish = vi.fn();
|
||||
const original = Text.of(["~~~mermaid", "flowchart TD", "A --> B", "~~~", "", "Other content."]);
|
||||
const preview = createPreviewWorker(render, publish, { source: original, markup: render(original.toString()) });
|
||||
let editing = true;
|
||||
const hold = () => editing;
|
||||
const replace = (before: Text, next: string) => {
|
||||
const row = before.line(3);
|
||||
const changes = ChangeSet.of({ from: row.from, to: row.to, insert: next }, before.length);
|
||||
const after = changes.apply(before);
|
||||
preview.queue(after, { before, after, changes }, hold);
|
||||
return after;
|
||||
};
|
||||
|
||||
const first = replace(original, "A --> C");
|
||||
const latest = replace(first, "A --> D[label]");
|
||||
expect(worker.postMessage.mock.calls).toEqual([]);
|
||||
expect(publish.mock.calls).toEqual([]);
|
||||
|
||||
editing = false;
|
||||
preview.flush();
|
||||
const editedBlock = "~~~mermaid\nflowchart TD\nA --> D[label]\n~~~\n\n";
|
||||
expect(worker.postMessage.mock.calls).toEqual([[{ id: 1, source: editedBlock, fenceMarker: markdownFenceMarker }]]);
|
||||
worker.reply(1, parseMarkdownBlocks(editedBlock));
|
||||
expect(publish.mock.calls.map(([result]) => result.source)).toEqual([latest]);
|
||||
});
|
||||
@@ -1,119 +0,0 @@
|
||||
import type { Text } from "@codemirror/state";
|
||||
import { markdownFenceMarker, sanitizeMarkdownBlock, type createMarkdownMarkupRenderer } from "./render";
|
||||
import { changedPreviewBlock, MERMAID_BLOCK, type MarkdownEdit, type RenderedMarkdown } from "./previewEdits";
|
||||
import type { PreviewParseRequest, PreviewParseResult } from "./preview.worker";
|
||||
|
||||
type HoldMermaid = (source: Text, block: { line: number; endLine: number }) => boolean;
|
||||
type PreviewJob = { source: Text; edit: MarkdownEdit | null; holdMermaid?: HoldMermaid };
|
||||
|
||||
export function createPreviewWorker(
|
||||
render: ReturnType<typeof createMarkdownMarkupRenderer>,
|
||||
publish: (preview: RenderedMarkdown) => void,
|
||||
initial: RenderedMarkdown,
|
||||
) {
|
||||
let parser: Worker | null = null;
|
||||
let active: {
|
||||
id: number;
|
||||
source: Text;
|
||||
replacement: ReturnType<typeof changedPreviewBlock>;
|
||||
} | null = null;
|
||||
let pending: PreviewJob | null = null;
|
||||
let displayed = initial;
|
||||
let id = 0;
|
||||
|
||||
const commit = (preview: RenderedMarkdown) => {
|
||||
displayed = preview;
|
||||
publish(preview);
|
||||
};
|
||||
const failed = () => {
|
||||
const source = pending?.source ?? active?.source;
|
||||
parser?.terminate();
|
||||
parser = null;
|
||||
active = pending = null;
|
||||
if (source) commit({ source, markup: render(source.toString()) });
|
||||
};
|
||||
const send = () => {
|
||||
if (active || !pending) return;
|
||||
const { source, edit, holdMermaid } = pending;
|
||||
if (source === displayed.source) {
|
||||
pending = null;
|
||||
return;
|
||||
}
|
||||
const replacement = edit ? changedPreviewBlock(displayed, edit) : null;
|
||||
if (replacement?.prefix === MERMAID_BLOCK && holdMermaid?.(source, replacement)) return;
|
||||
|
||||
pending = null;
|
||||
if (!parser) {
|
||||
commit({ source, markup: render(source.toString()) });
|
||||
return;
|
||||
}
|
||||
active = { id: ++id, source, replacement };
|
||||
try {
|
||||
parser.postMessage({
|
||||
id,
|
||||
source: replacement?.text ?? source.toString(),
|
||||
fenceMarker: markdownFenceMarker,
|
||||
} satisfies PreviewParseRequest);
|
||||
} catch {
|
||||
failed();
|
||||
}
|
||||
};
|
||||
|
||||
try {
|
||||
parser = new Worker(new URL("./preview.worker.ts", import.meta.url), { type: "module" });
|
||||
parser.onmessage = ({ data }: MessageEvent<PreviewParseResult>) => {
|
||||
if (!active || active.id !== data.id) return;
|
||||
const { source, replacement } = active;
|
||||
active = null;
|
||||
if (!pending || pending.source !== displayed.source) {
|
||||
if (replacement) {
|
||||
const { blocks, index, line, endLine, lineDelta, prefix } = replacement;
|
||||
const block = sanitizeMarkdownBlock(data.blocks, line, endLine, prefix);
|
||||
if (block) {
|
||||
const markup = blocks.slice();
|
||||
markup[index] = block;
|
||||
if (lineDelta) {
|
||||
for (let i = index + 1; i < markup.length; i++) {
|
||||
const next = markup[i]!;
|
||||
markup[i] = { ...next, line: next.line + lineDelta, endLine: next.endLine + lineDelta };
|
||||
}
|
||||
}
|
||||
commit({ source, markup });
|
||||
} else {
|
||||
pending ??= { source, edit: null };
|
||||
}
|
||||
} else {
|
||||
commit({ source, markup: render(data.blocks) });
|
||||
}
|
||||
}
|
||||
send();
|
||||
};
|
||||
parser.onerror = failed;
|
||||
parser.onmessageerror = failed;
|
||||
} catch {
|
||||
parser = null;
|
||||
}
|
||||
return {
|
||||
queue(source: Text, edit: MarkdownEdit | null = null, holdMermaid?: HoldMermaid) {
|
||||
if (source === active?.source) {
|
||||
pending = null;
|
||||
} else if (source !== pending?.source) {
|
||||
const previous = pending?.edit;
|
||||
const combined =
|
||||
previous && edit && previous.after === edit.before
|
||||
? { before: previous.before, after: edit.after, changes: previous.changes.compose(edit.changes) }
|
||||
: edit;
|
||||
pending = { source, edit: combined, holdMermaid };
|
||||
} else {
|
||||
pending.holdMermaid = holdMermaid;
|
||||
}
|
||||
send();
|
||||
},
|
||||
flush: send,
|
||||
dispose() {
|
||||
parser?.terminate();
|
||||
parser = null;
|
||||
active = pending = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
import { readFileSync } from "node:fs";
|
||||
import { resolve } from "node:path";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { renderMath } from "@/editor/lsp/renderMarkdownMath";
|
||||
import { renderMath } from "@/editor/lsp/markdownMath";
|
||||
import {
|
||||
createMarkdownRenderer,
|
||||
frontMatter,
|
||||
|
||||
@@ -19,31 +19,25 @@ const escapeHtml = (s: string) =>
|
||||
s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">").replace(/"/g, """);
|
||||
|
||||
const FENCE_ATTR = "data-markdown-fence";
|
||||
export const markdownFenceMarker = Array.from(crypto.getRandomValues(new Uint32Array(4)), (value) =>
|
||||
value.toString(36),
|
||||
).join("-");
|
||||
const fenceMarker = Array.from(crypto.getRandomValues(new Uint32Array(4)), (value) => value.toString(36)).join("-");
|
||||
const fenceStart = `<pre ${FENCE_ATTR}="${fenceMarker}">`;
|
||||
const defaultRenderer = new Renderer();
|
||||
|
||||
export const isRenderedFence = (pre: HTMLElement): boolean => pre.hasAttribute(FENCE_ATTR);
|
||||
|
||||
const marked = previewParser(markdownFenceMarker);
|
||||
|
||||
function previewParser(marker: string): Marked {
|
||||
const fenceStart = `<pre ${FENCE_ATTR}="${marker}">`;
|
||||
return new Marked({
|
||||
gfm: true,
|
||||
breaks: false,
|
||||
renderer: {
|
||||
code(token) {
|
||||
const { text, lang, codeBlockStyle } = token;
|
||||
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() === "mermaid")
|
||||
return `<div data-mermaid="">${fenceStart}<code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
|
||||
if (codeBlockStyle === "indented") return false;
|
||||
return defaultRenderer.code(token).replace("<pre>", fenceStart);
|
||||
},
|
||||
const marked = new Marked({
|
||||
gfm: true,
|
||||
breaks: false,
|
||||
renderer: {
|
||||
code(token) {
|
||||
const { text, lang, codeBlockStyle } = token;
|
||||
if (lang?.trim().split(/\s+/)[0]?.toLowerCase() === "mermaid")
|
||||
return `<div data-mermaid="">${fenceStart}<code class="language-mermaid">${escapeHtml(text)}</code></pre></div>\n`;
|
||||
if (codeBlockStyle === "indented") return false;
|
||||
return defaultRenderer.code(token).replace("<pre>", fenceStart);
|
||||
},
|
||||
}).use(mathExtension(), footnoteExtension(ANCHOR_PREFIX));
|
||||
}
|
||||
},
|
||||
}).use(mathExtension(), footnoteExtension(ANCHOR_PREFIX));
|
||||
|
||||
// Own instance: hooks must not leak into the hover / documentation renderer.
|
||||
let purifier: ReturnType<typeof DOMPurify> | null = null;
|
||||
@@ -60,7 +54,7 @@ function purify(): ReturnType<typeof DOMPurify> {
|
||||
p.addHook("uponSanitizeAttribute", (node, data) => {
|
||||
if (data.attrName === FENCE_ATTR) {
|
||||
// Keep provenance without exposing the marker in the preview DOM
|
||||
data.keepAttr = node.tagName === "PRE" && data.attrValue === markdownFenceMarker;
|
||||
data.keepAttr = node.tagName === "PRE" && data.attrValue === fenceMarker;
|
||||
if (data.keepAttr) data.attrValue = "";
|
||||
return;
|
||||
}
|
||||
@@ -172,14 +166,13 @@ function trackContainers(raw: string, open: string[]) {
|
||||
}
|
||||
}
|
||||
|
||||
export type MarkdownBlock = { line: number; endLine: number; html: string };
|
||||
export type MarkdownMarkup = string | readonly MarkdownBlock[];
|
||||
type MarkdownBlock = { line: number; endLine: number; html: string };
|
||||
|
||||
function lexBlocks(body: string, parser: Marked): TokensList {
|
||||
function lexBlocks(body: string): TokensList {
|
||||
// Marked repeatedly scans the remaining input for block boundaries. Keep the bytes of
|
||||
// standalone embedded images out of those scans and restore their URLs before rendering.
|
||||
const prefix = "openidea-embedded-image-";
|
||||
if (!body.includes(";base64,") || body.includes(prefix)) return parser.lexer(body);
|
||||
if (!body.includes(";base64,") || body.includes(prefix)) return marked.lexer(body);
|
||||
const urls: string[] = [];
|
||||
const compact = body.replace(
|
||||
/^!\[\]\((data:image\/[\w.+-]+;base64,[A-Za-z0-9+/]{256,}={0,2})\)(?=[ \t]*\r?$)/gm,
|
||||
@@ -188,25 +181,24 @@ function lexBlocks(body: string, parser: Marked): TokensList {
|
||||
return ``;
|
||||
},
|
||||
);
|
||||
const tokens = parser.lexer(compact);
|
||||
const tokens = marked.lexer(compact);
|
||||
let restored = 0;
|
||||
for (const token of tokens) {
|
||||
if (restored === urls.length) break;
|
||||
if (!token.raw.includes(prefix)) continue;
|
||||
const image = token.type === "paragraph" && token.tokens?.length === 1 && token.tokens[0];
|
||||
if (!image || image.type !== "image" || image.href !== prefix + restored || token.raw.trimEnd() !== image.raw)
|
||||
return parser.lexer(body);
|
||||
return marked.lexer(body);
|
||||
image.href = urls[restored++]!;
|
||||
}
|
||||
return restored === urls.length ? tokens : parser.lexer(body);
|
||||
return restored === urls.length ? tokens : marked.lexer(body);
|
||||
}
|
||||
|
||||
/** Top-level source ranges; an open HTML container groups its enclosed blocks. */
|
||||
export function parseMarkdownBlocks(text: string, marker = markdownFenceMarker): MarkdownBlock[] {
|
||||
const parser = marker === markdownFenceMarker ? marked : previewParser(marker);
|
||||
function blocks(text: string): MarkdownBlock[] {
|
||||
const front = frontMatter(text);
|
||||
const body = front ? text.split("\n").slice(front.lines).join("\n") : text;
|
||||
const tokens = lexBlocks(body, parser);
|
||||
const tokens = lexBlocks(body);
|
||||
const slugs = new Map<string, number>();
|
||||
let line = front?.lines ?? 0;
|
||||
const out = front ? [{ line: 0, endLine: front.lines, html: frontMatterTable(front.fields) }] : [];
|
||||
@@ -219,7 +211,7 @@ export function parseMarkdownBlocks(text: string, marker = markdownFenceMarker):
|
||||
line += countLines(token.raw);
|
||||
if (token.type === "space" || token.type === "footnoteDefinition") continue;
|
||||
const list = Object.assign([token], { links: tokens.links }) as TokensList;
|
||||
let body = parser.parser(list);
|
||||
let body = marked.parser(list);
|
||||
if (token.type === "table") {
|
||||
body = body.replace(/^<table>/, '<table data-markdown-table="">');
|
||||
}
|
||||
@@ -236,7 +228,7 @@ export function parseMarkdownBlocks(text: string, marker = markdownFenceMarker):
|
||||
group = null;
|
||||
}
|
||||
if (group) out.push(group);
|
||||
const footnotes = renderFootnotes(parser, tokens);
|
||||
const footnotes = renderFootnotes(marked, tokens);
|
||||
if (footnotes) out.push({ line: countLines(text), endLine: countLines(text) + 1, html: footnotes });
|
||||
return out;
|
||||
}
|
||||
@@ -284,7 +276,7 @@ export function headingLine(text: string, anchor: string): number | null {
|
||||
}
|
||||
|
||||
export function renderMarkdown(text: string): string {
|
||||
return sanitizeWhole(parseMarkdownBlocks(text));
|
||||
return sanitizeWhole(blocks(text));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -292,19 +284,10 @@ export function renderMarkdown(text: string): string {
|
||||
* earlier render are reused, so an edit sanitizes only the blocks it changed. Same output.
|
||||
*/
|
||||
export function createMarkdownRenderer(): (text: string) => string {
|
||||
const render = createMarkdownMarkupRenderer();
|
||||
return (text) => markdownMarkupHtml(render(text));
|
||||
}
|
||||
|
||||
export function markdownMarkupHtml(markup: MarkdownMarkup): string {
|
||||
return typeof markup === "string" ? markup : markup.map((b) => wrap(b.line, b.endLine, b.html)).join("");
|
||||
}
|
||||
|
||||
export function createMarkdownMarkupRenderer(): (source: string | readonly MarkdownBlock[]) => MarkdownMarkup {
|
||||
// Sanitized wrapper contents by unsanitized block HTML; `null` for a block that leaks.
|
||||
let cache = new Map<string, string | null>();
|
||||
return (source) => {
|
||||
const all = typeof source === "string" ? parseMarkdownBlocks(source) : source;
|
||||
return (text) => {
|
||||
const all = blocks(text);
|
||||
const misses = [...new Set(all.map((b) => b.html).filter((html) => !cache.has(html)))];
|
||||
for (const html of misses) if (PARSER_STATE.test(html)) cache.set(html, null);
|
||||
if (misses.length && !all.some((b) => cache.get(b.html) === null)) sanitizeApart(misses, cache);
|
||||
@@ -316,7 +299,7 @@ export function createMarkdownMarkupRenderer(): (source: string | readonly Markd
|
||||
cache = kept;
|
||||
const parts = all.map((b) => cache.get(b.html));
|
||||
if (parts.some((part) => typeof part !== "string")) return sanitizeWhole(all);
|
||||
return all.map((b, i) => ({ ...b, html: parts[i]! }));
|
||||
return all.map((b, i) => wrap(b.line, b.endLine, parts[i]!)).join("");
|
||||
};
|
||||
}
|
||||
|
||||
@@ -370,21 +353,6 @@ function sanitizeApart(blocks: readonly string[], cache: Map<string, string | nu
|
||||
if (apart < blocks.length) cache.set(blocks[apart]!, null);
|
||||
}
|
||||
|
||||
export function sanitizeMarkdownBlock(
|
||||
blocks: readonly MarkdownBlock[],
|
||||
line: number,
|
||||
endLine: number,
|
||||
prefix: string,
|
||||
): MarkdownBlock | null {
|
||||
const block = blocks[0];
|
||||
if (blocks.length !== 1 || block?.line !== 0 || block.endLine !== endLine - line || !block.html.startsWith(prefix))
|
||||
return null;
|
||||
const sanitized = new Map<string, string | null>();
|
||||
sanitizeApart([block.html], sanitized);
|
||||
const html = sanitized.get(block.html);
|
||||
return html?.startsWith(prefix) ? { line, endLine, html } : null;
|
||||
}
|
||||
|
||||
export type LinkTarget =
|
||||
| { kind: "external"; url: string }
|
||||
| { kind: "anchor"; id: string }
|
||||
|
||||
@@ -1804,8 +1804,6 @@
|
||||
"Install a plugin folder with": "安裝外掛資料夾:",
|
||||
"Install and Debug": "安裝並偵錯",
|
||||
"Reinstall and Debug": "重新安裝並偵錯",
|
||||
"No C/C++ debugger found": "找不到 C/C++ 偵錯器",
|
||||
"Install CodeLLDB and Debug": "安裝 CodeLLDB 並偵錯",
|
||||
"Installed": "已安裝",
|
||||
"Installed packages": "已安裝的軟體包",
|
||||
"Installed plugins": "已安裝的外掛",
|
||||
|
||||
@@ -2372,8 +2372,6 @@
|
||||
"Install a plugin folder with": "安装插件文件夹:",
|
||||
"Install and Debug": "安装并调试",
|
||||
"Reinstall and Debug": "重新安装并调试",
|
||||
"No C/C++ debugger found": "未找到 C/C++ 调试器",
|
||||
"Install CodeLLDB and Debug": "安装 CodeLLDB 并调试",
|
||||
"Installed": "已安装",
|
||||
"Installed packages": "已安装的软件包",
|
||||
"Installed plugins": "已安装的插件",
|
||||
|
||||
Reference in new issue
Заблокувати користувача