mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-22 19:49:35 -10:00
Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c6beb1cfb9 | ||
|
|
6d788cb6f8 | ||
|
|
662c32eb05 | ||
|
|
82ff84e69e | ||
|
|
7ec0d3dbec | ||
|
|
466556603d | ||
|
|
3b2deb6ad8 | ||
|
|
f2429a8c14 | ||
|
|
f3e80ba020 | ||
|
|
f767bd2e7c | ||
|
|
51174842cc | ||
|
|
e4ece2bd8d | ||
|
|
a5093c0cd1 | ||
|
|
9a0256c7d4 | ||
|
|
78b478ee38 |
No files matched your search
@@ -3,6 +3,7 @@ use crate::Host;
|
||||
use ide_command::command;
|
||||
use ide_core::{IdeError, IdeResult, RequestId};
|
||||
use ide_vfs::FileEntry;
|
||||
use ide_workspace::DeletionUndo;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[command(trust = always)]
|
||||
@@ -163,14 +164,27 @@ pub fn fs_set_writable(host: &Host, window: &str, path: PathBuf, writable: bool)
|
||||
/// Moving to the trash can take a while (large trees): kept off the main thread.
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()> {
|
||||
// Local History keeps the contents so deleted files can be restored.
|
||||
let project = host.project(window).ok();
|
||||
let history = project.as_ref().map(|p| p.history.clone());
|
||||
delete_with_history(host, window, path, false).await.map(|_| ())
|
||||
}
|
||||
|
||||
/// Moves an item to the Trash and returns the snapshot for Project View Undo.
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_delete_with_undo(host: &Host, window: &str, path: PathBuf) -> IdeResult<DeletionUndo> {
|
||||
delete_with_history(host, window, path, true).await
|
||||
}
|
||||
|
||||
async fn delete_with_history(host: &Host, window: &str, path: PathBuf, undoable: bool) -> IdeResult<DeletionUndo> {
|
||||
let project = if undoable { Some(host.project(window)?) } else { host.project(window).ok() };
|
||||
host.blocking(move || {
|
||||
let paths = ide_workspace::file_ops::deletion_paths(&path)?;
|
||||
if let Some(h) = history {
|
||||
for p in &paths {
|
||||
h.record_deletion(p, DELETE_SNAPSHOT_LIMIT);
|
||||
let mut undo = DeletionUndo::default();
|
||||
if let Some(p) = &project {
|
||||
if undoable {
|
||||
undo = p.history.capture_deletion_undo(&paths, DELETE_SNAPSHOT_LIMIT);
|
||||
} else {
|
||||
for pth in &paths {
|
||||
p.history.record_deletion(pth, DELETE_SNAPSHOT_LIMIT);
|
||||
}
|
||||
}
|
||||
}
|
||||
ide_workspace::file_ops::delete(&path)?;
|
||||
@@ -178,11 +192,17 @@ pub async fn fs_delete(host: &Host, window: &str, path: PathBuf) -> IdeResult<()
|
||||
if let Some(p) = project {
|
||||
let _ = p.with_backend_of(&path, |r| r.files_deleted(&paths));
|
||||
}
|
||||
Ok(())
|
||||
Ok(undo)
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_undo_delete(host: &Host, window: &str, undo: DeletionUndo) -> IdeResult<Vec<ide_core::IpcPath>> {
|
||||
let project = host.project(window)?;
|
||||
host.blocking(move || Ok(project.history.restore_deletion_undo(undo))).await
|
||||
}
|
||||
|
||||
#[command(trust = always)]
|
||||
pub async fn fs_copy(host: &Host, window: &str, from: PathBuf, to: PathBuf) -> IdeResult<()> {
|
||||
let project = host.project(window).ok();
|
||||
@@ -280,9 +300,11 @@ ide_command::domain!(
|
||||
fs_create_file,
|
||||
fs_create_file_bytes,
|
||||
fs_delete,
|
||||
fs_delete_with_undo,
|
||||
fs_entry_kind,
|
||||
fs_read_dir,
|
||||
fs_read_text,
|
||||
fs_rename,
|
||||
fs_set_writable,
|
||||
fs_undo_delete,
|
||||
);
|
||||
@@ -241,6 +241,15 @@ impl PathFilter {
|
||||
(!rel.is_empty()).then_some(rel)
|
||||
}
|
||||
|
||||
/// Recent Files' stored form: the store key for a project file, the absolute
|
||||
/// path for one outside it (a scratch file). Loading joins it to the root,
|
||||
/// which leaves an absolute path as it is.
|
||||
pub(crate) fn recent_key(&self, path: &Path) -> Option<String> {
|
||||
self.store_key(path).or_else(|| {
|
||||
(path.is_absolute() && !path.starts_with(&self.root)).then(|| path.to_str().map(str::to_owned))?
|
||||
})
|
||||
}
|
||||
|
||||
fn excluded_rel(&self, rel: &str) -> bool {
|
||||
self.excludes.is_match(rel)
|
||||
}
|
||||
|
||||
+18
-15
@@ -400,15 +400,10 @@ impl ProjectIndex {
|
||||
|
||||
/// Boost for "recent files" ranking.
|
||||
/// Records a recently opened file; a virtual document's URI (library
|
||||
/// class) is kept verbatim, like IDEA lists library classes in Recent Files.
|
||||
/// class) is kept verbatim, and a file outside the project (a scratch file)
|
||||
/// by its absolute path.
|
||||
pub fn mark_recent(&self, path: &Path) {
|
||||
let path = match path.to_str() {
|
||||
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
|
||||
_ => match self.normalize(path) {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let Some(path) = self.recent_key(path) else { return };
|
||||
{
|
||||
let mut r = self.shared.recent.lock();
|
||||
r.retain(|p| p != &path);
|
||||
@@ -420,13 +415,7 @@ impl ProjectIndex {
|
||||
|
||||
/// Drops a file from Recent Files (Delete in the ⌘E popup).
|
||||
pub fn remove_recent(&self, path: &Path) {
|
||||
let path = match path.to_str() {
|
||||
Some(s) if ide_core::text::is_virtual_uri(s) => path.to_owned(),
|
||||
_ => match self.normalize(path) {
|
||||
Some(p) => p,
|
||||
None => return,
|
||||
},
|
||||
};
|
||||
let Some(path) = self.recent_key(path) else { return };
|
||||
{
|
||||
let mut r = self.shared.recent.lock();
|
||||
let before = r.len();
|
||||
@@ -473,6 +462,20 @@ impl ProjectIndex {
|
||||
&self.root
|
||||
}
|
||||
|
||||
/// How Recent Files stores `path`: a virtual URI verbatim, a project file normalized,
|
||||
/// and an existing file outside the root canonicalized. Excluded files under the root
|
||||
/// are left out.
|
||||
fn recent_key(&self, path: &Path) -> Option<PathBuf> {
|
||||
if path.to_str().is_some_and(ide_core::text::is_virtual_uri) {
|
||||
return Some(path.to_owned());
|
||||
}
|
||||
if let Some(p) = self.normalize(path) {
|
||||
return Some(p);
|
||||
}
|
||||
let p = dunce::canonicalize(path).ok().filter(|p| p.is_file())?;
|
||||
(!p.starts_with(&self.root)).then_some(p)
|
||||
}
|
||||
|
||||
/// Absolute path inside the root (or a content root), or `None` for paths outside the project.
|
||||
fn normalize(&self, path: &Path) -> Option<PathBuf> {
|
||||
let filter = self.shared.filter();
|
||||
|
||||
@@ -251,6 +251,26 @@ fn recent_files_skip_deleted_files_but_keep_virtual_documents() {
|
||||
assert_eq!(idx.recent_files(), vec![virt]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recent_files_keep_files_outside_the_project() {
|
||||
let fx = sample();
|
||||
let scratches = tempfile::tempdir().unwrap();
|
||||
let scratch = dunce::canonicalize(scratches.path()).unwrap().join("generated-requests.http");
|
||||
std::fs::write(&scratch, "GET http://localhost\n").unwrap();
|
||||
let app = fx.root.join("web/app.py");
|
||||
{
|
||||
let idx = fx.open();
|
||||
idx.mark_recent(&app);
|
||||
idx.mark_recent(&scratch);
|
||||
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()]);
|
||||
assert!(idx.wait_idle(WAIT));
|
||||
}
|
||||
let idx = fx.open();
|
||||
assert_eq!(idx.recent_files(), vec![scratch.clone(), app.clone()], "persisted by absolute path");
|
||||
idx.remove_recent(&scratch);
|
||||
assert_eq!(idx.recent_files(), vec![app]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn persistence_skips_unchanged_files_on_reopen() {
|
||||
let fx = sample();
|
||||
|
||||
@@ -591,7 +591,7 @@ impl Shared {
|
||||
let update_elapsed = update_started.elapsed();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Some(store) = &self.store {
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let recent: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
|
||||
let d = self.data.read();
|
||||
let snapshot_started = Instant::now();
|
||||
if let Err(e) = store.save_snapshot(&d, &filter, guard) {
|
||||
@@ -976,7 +976,7 @@ impl Shared {
|
||||
}
|
||||
}
|
||||
if save_recent && let Some(store) = &self.store {
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.store_key(p)).collect();
|
||||
let rels: Vec<String> = self.recent.lock().iter().filter_map(|p| filter.recent_key(p)).collect();
|
||||
if let Err(e) = store.save_recent(&rels) {
|
||||
tracing::warn!("index cache: saving recent files failed: {e}");
|
||||
}
|
||||
|
||||
@@ -23,6 +23,7 @@ pub(crate) mod configuration;
|
||||
mod extract_interface;
|
||||
mod formatter;
|
||||
mod generated;
|
||||
pub(crate) use generated::is_processor_output;
|
||||
mod hierarchy;
|
||||
pub(crate) mod jvm_inspect;
|
||||
mod move_refactoring;
|
||||
|
||||
@@ -25,6 +25,18 @@ pub(crate) struct GeneratedScan {
|
||||
pub roots: Vec<GeneratedRoot>,
|
||||
}
|
||||
|
||||
/// Whether `path` is in (or is) an annotation-processor output folder:
|
||||
/// `generated-sources/annotations` or `generated-test-sources/test-annotations`. jdtls
|
||||
/// runs the processors itself and writes there; javac (a Maven build) writes the same
|
||||
/// files, and jdtls must not take those as edits (#4128).
|
||||
pub(crate) fn is_processor_output(path: &Path) -> bool {
|
||||
let parts: Vec<_> = path.components().map(|c| c.as_os_str()).collect();
|
||||
parts.windows(2).any(|w| {
|
||||
(w[0] == "generated-sources" && w[1] == "annotations")
|
||||
|| (w[0] == "generated-test-sources" && w[1] == "test-annotations")
|
||||
})
|
||||
}
|
||||
|
||||
/// Generated Java source folders under `root` (a reactor or one module).
|
||||
pub(crate) fn scan(root: &Path) -> GeneratedScan {
|
||||
let mut modules = Vec::new();
|
||||
@@ -260,6 +272,20 @@ fn plugins_removed(build: &str) -> String {
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn recognizes_annotation_processor_output() {
|
||||
for (path, expected) in [
|
||||
("/p/m/target/generated-sources/annotations/com/x/FooMappingImpl.java", true),
|
||||
("/p/m/target/generated-sources/annotations", true),
|
||||
("/p/m/build-out/generated-test-sources/test-annotations/com/x/T.java", true),
|
||||
("/p/m/target/generated-sources/protobuf/java/com/x/Hello.java", false),
|
||||
("/p/m/src/main/java/annotations/Foo.java", false),
|
||||
("/p/m/target/classes/com/x/FooMappingImpl.class", false),
|
||||
] {
|
||||
assert_eq!(is_processor_output(Path::new(path)), expected, "{path}");
|
||||
}
|
||||
}
|
||||
|
||||
fn write(root: &Path, rel: &str, text: &str) {
|
||||
let path = root.join(rel);
|
||||
std::fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
|
||||
@@ -3057,7 +3057,12 @@ impl LspManager {
|
||||
for s in servers {
|
||||
let Some(run) = s.running() else { continue };
|
||||
let open = open.get(&(s.id, run.generation)).filter(|_| run.caps.read().sync != SyncKind::None);
|
||||
// jdtls owns its annotation-processor output; javac's copy of those files is not an edit.
|
||||
let jdtls = s.name == "jdtls";
|
||||
let send = |p: &PathBuf, change: Change| {
|
||||
if jdtls && jdtls::is_processor_output(p) {
|
||||
return false;
|
||||
}
|
||||
change == Change::Deleted
|
||||
|| !open
|
||||
.is_some_and(|paths| paths.contains(p) || canonical.get(p).is_some_and(|c| paths.contains(c)))
|
||||
|
||||
@@ -991,6 +991,33 @@ async fn files_changed_on_disk_reach_the_servers_of_their_language() {
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// jdtls runs the annotation processors itself and writes their output; a Maven build's
|
||||
/// copy of those files must not reach it as an edit, or jdtls recompiles javac's copy and
|
||||
/// overwrites its classes with broken ones (#4128).
|
||||
#[tokio::test(flavor = "multi_thread")]
|
||||
async fn jdtls_does_not_hear_of_annotation_processor_output() {
|
||||
let h = harness_for("java", "java", &[("jdtls", incremental_caps())], &[]);
|
||||
let (doc, _) = h.open("Open.java", "class Open {}");
|
||||
h.wait_status("jdtls", ServerStatus::Ready).await;
|
||||
let s = h.launcher.state("jdtls");
|
||||
let source = h.root.join("m/src/main/java/com/x/FooMapping.java");
|
||||
let generated = h.root.join("m/target/generated-sources/annotations/com/x/FooMappingImpl.java");
|
||||
let test_generated = h.root.join("m/target/generated-test-sources/test-annotations/com/x/T.java");
|
||||
h.mgr.watched_files_changed(
|
||||
&[test_generated],
|
||||
&[generated.clone(), source.clone()],
|
||||
std::slice::from_ref(&generated),
|
||||
&[h.root.join("m/target/generated-sources/annotations")],
|
||||
);
|
||||
eventually(|| !s.notified("workspace/didChangeWatchedFiles").is_empty()).await;
|
||||
h.mgr.hover(doc, Pos::new(0, 0), Default::default()).await.unwrap();
|
||||
assert_eq!(
|
||||
s.notified("workspace/didChangeWatchedFiles"),
|
||||
vec![json!({ "changes": [{ "uri": uri_of(&source), "type": 2 }] })]
|
||||
);
|
||||
h.mgr.shutdown_all().await;
|
||||
}
|
||||
|
||||
/// An external change to a document open on the server's current instance reaches it only
|
||||
/// through the reload's `didChange`: a watched-file change for it too would make a server
|
||||
/// that re-reads the file on one (csharp-ls) apply the reload and then the diff computed
|
||||
|
||||
@@ -4,7 +4,7 @@ use serde::{Deserialize, Serialize};
|
||||
use specta::Type;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fs;
|
||||
use std::io::Write;
|
||||
use std::io::{Read, Write};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize, Type)]
|
||||
@@ -30,6 +30,35 @@ pub struct HistoryEntry {
|
||||
pub size: u64,
|
||||
#[serde(default)]
|
||||
pub kind: HistoryKind,
|
||||
/// Exact on-disk bytes for Undo when document text omits a BOM or line endings.
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
#[specta(skip)]
|
||||
undo_blob: Option<UndoBlob>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize)]
|
||||
struct UndoBlob {
|
||||
id: String,
|
||||
size: u64,
|
||||
}
|
||||
|
||||
impl HistoryEntry {
|
||||
fn snapshot(path: &Path, text: &str, label: &str, timestamp_ms: f64) -> Self {
|
||||
Self {
|
||||
id: blake3::hash(text.as_bytes()).to_hex().to_string(),
|
||||
path: path.into(),
|
||||
timestamp_ms,
|
||||
label: label.to_owned(),
|
||||
size: text.len() as u64,
|
||||
kind: HistoryKind::Snapshot,
|
||||
undo_blob: None,
|
||||
}
|
||||
}
|
||||
|
||||
fn blobs(&self) -> impl Iterator<Item = (&str, u64)> {
|
||||
std::iter::once((self.id.as_str(), self.size))
|
||||
.chain(self.undo_blob.iter().map(|blob| (blob.id.as_str(), blob.size)))
|
||||
}
|
||||
}
|
||||
|
||||
/// Changes under a folder (Show History on a directory).
|
||||
@@ -42,6 +71,23 @@ pub struct DirectoryHistory {
|
||||
pub deleted: Vec<ide_core::IpcPath>,
|
||||
}
|
||||
|
||||
/// Paths and contents captured for one delete operation. Directory history is
|
||||
/// intentionally broader and can contain paths deleted in an earlier operation.
|
||||
#[derive(Clone, Debug, Default, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeletionUndo {
|
||||
directories: Vec<ide_core::IpcPath>,
|
||||
files: Vec<DeletedFile>,
|
||||
skipped: Vec<ide_core::IpcPath>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Serialize, Deserialize, Type)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub struct DeletedFile {
|
||||
path: ide_core::IpcPath,
|
||||
id: String,
|
||||
}
|
||||
|
||||
/// How much history is kept (Settings › Advanced › Local History).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Retention {
|
||||
@@ -108,22 +154,56 @@ fn valid_id(id: &str) -> bool {
|
||||
|
||||
fn valid_entry(e: &HistoryEntry) -> bool {
|
||||
match e.kind {
|
||||
HistoryKind::Snapshot => valid_id(&e.id),
|
||||
HistoryKind::Snapshot => valid_id(&e.id) && e.undo_blob.as_ref().is_none_or(|blob| valid_id(&blob.id)),
|
||||
HistoryKind::Label => e.id.is_empty(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Text of a file for an automatic snapshot: small, non-binary files only.
|
||||
fn read_snapshot_text(path: &Path) -> Option<String> {
|
||||
read_snapshot_disk_text(path).map(|text| document_text(&text).into_owned())
|
||||
}
|
||||
|
||||
fn read_snapshot_disk_text(path: &Path) -> Option<String> {
|
||||
let meta = fs::metadata(path).ok()?;
|
||||
if !meta.is_file() || meta.len() > AUTO_SNAPSHOT_LIMIT {
|
||||
return None;
|
||||
}
|
||||
let bytes = fs::read(path).ok()?;
|
||||
if bytes.iter().take(8192).any(|b| *b == 0) {
|
||||
let mut bytes = Vec::new();
|
||||
fs::File::open(path).ok()?.take(AUTO_SNAPSHOT_LIMIT + 1).read_to_end(&mut bytes).ok()?;
|
||||
if bytes.len() as u64 > AUTO_SNAPSHOT_LIMIT || bytes.iter().take(8192).any(|b| *b == 0) {
|
||||
return None;
|
||||
}
|
||||
String::from_utf8(bytes).ok().map(|text| document_text(&text).into_owned())
|
||||
String::from_utf8(bytes).ok()
|
||||
}
|
||||
|
||||
/// Directory junctions and similar reparse points must not be traversed.
|
||||
fn is_link(metadata: &fs::Metadata) -> bool {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::MetadataExt;
|
||||
metadata.file_attributes() & 0x400 != 0
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
metadata.file_type().is_symlink()
|
||||
}
|
||||
}
|
||||
|
||||
fn restore_deleted_bytes(path: &Path, bytes: &[u8]) -> IdeResult<()> {
|
||||
let parent = path.parent().ok_or_else(|| IdeError::invalid("missing parent for deleted file"))?;
|
||||
// Publish only a complete file, and never replace a new file at that path.
|
||||
let mut builder = tempfile::Builder::new();
|
||||
builder.prefix(".undo.openidea-tmp-");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
builder.permissions(fs::Permissions::from_mode(0o666));
|
||||
}
|
||||
let mut pending = builder.tempfile_in(parent)?;
|
||||
pending.write_all(bytes)?;
|
||||
pending.persist_noclobber(path).map_err(|error| error.error)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// `text` as a document holds it: without the UTF-8 BOM and with `\n` line endings. Saves
|
||||
@@ -191,55 +271,60 @@ impl LocalHistory {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self, path: &Path, content: &str, label: &str, force: bool) -> IdeResult<()> {
|
||||
let id = blake3::hash(content.as_bytes()).to_hex().to_string();
|
||||
let mut state = self.state.lock();
|
||||
if !force && state.last.get(path) == Some(&id) {
|
||||
return Ok(());
|
||||
/// Called with the history lock held, so prune cannot remove a blob before its entry exists.
|
||||
fn store_blob(&self, id: &str, bytes: &[u8]) -> IdeResult<()> {
|
||||
let blob = self.blob_path(id);
|
||||
if !blob.exists() {
|
||||
fs::create_dir_all(blob.parent().expect("blob has a parent"))?;
|
||||
ide_vfs::write_atomic(&blob, bytes)?;
|
||||
}
|
||||
self.store_locked(&mut state, path, id, content, label, now_ms())
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn store(&self, path: &Path, content: &str, label: &str, force: bool, original: Option<&str>) -> IdeResult<String> {
|
||||
let mut state = self.state.lock();
|
||||
let entry = HistoryEntry::snapshot(path, content, label, now_ms());
|
||||
if !force && state.last.get(path) == Some(&entry.id) {
|
||||
return Ok(entry.id);
|
||||
}
|
||||
self.store_locked(&mut state, entry, content, original)
|
||||
}
|
||||
|
||||
fn store_locked(
|
||||
&self,
|
||||
state: &mut HistoryState,
|
||||
path: &Path,
|
||||
id: String,
|
||||
mut entry: HistoryEntry,
|
||||
content: &str,
|
||||
label: &str,
|
||||
timestamp_ms: f64,
|
||||
) -> IdeResult<()> {
|
||||
let blob = self.blob_path(&id);
|
||||
if !blob.exists() {
|
||||
fs::create_dir_all(blob.parent().expect("blob has a parent"))?;
|
||||
ide_vfs::write_atomic(&blob, content.as_bytes())?;
|
||||
}
|
||||
let entry = HistoryEntry {
|
||||
id,
|
||||
path: path.into(),
|
||||
timestamp_ms,
|
||||
label: label.to_owned(),
|
||||
size: content.len() as u64,
|
||||
kind: HistoryKind::Snapshot,
|
||||
original: Option<&str>,
|
||||
) -> IdeResult<String> {
|
||||
self.store_blob(&entry.id, content.as_bytes())?;
|
||||
entry.undo_blob = if let Some(original) = original.filter(|text| *text != content) {
|
||||
let id = blake3::hash(original.as_bytes()).to_hex().to_string();
|
||||
self.store_blob(&id, original.as_bytes())?;
|
||||
Some(UndoBlob { id, size: original.len() as u64 })
|
||||
} else {
|
||||
None
|
||||
};
|
||||
self.append(state, entry)
|
||||
let undo_id = entry.undo_blob.as_ref().map_or_else(|| entry.id.clone(), |blob| blob.id.clone());
|
||||
self.append(state, entry)?;
|
||||
Ok(undo_id)
|
||||
}
|
||||
|
||||
/// Records a snapshot unless it equals the latest one recorded for `path`.
|
||||
pub fn record(&self, path: &Path, content: &str, label: &str) -> IdeResult<()> {
|
||||
self.store(path, content, label, false)
|
||||
self.store(path, content, label, false, None).map(|_| ())
|
||||
}
|
||||
|
||||
/// Records a snapshot even when the content did not change, so the event
|
||||
/// ("Deleted", "Before refactoring: Move") shows in the history.
|
||||
pub fn record_event(&self, path: &Path, content: &str, label: &str) -> IdeResult<()> {
|
||||
self.store(path, content, label, true)
|
||||
self.store(path, content, label, true, None).map(|_| ())
|
||||
}
|
||||
|
||||
/// Snapshots the file on disk (small text files only); `force` as in [`record_event`](Self::record_event).
|
||||
pub fn record_file(&self, path: &Path, label: &str, force: bool) -> IdeResult<bool> {
|
||||
match read_snapshot_text(path) {
|
||||
Some(text) => self.store(path, &text, label, force).map(|()| true),
|
||||
Some(text) => self.store(path, &text, label, force, None).map(|_| true),
|
||||
None => Ok(false),
|
||||
}
|
||||
}
|
||||
@@ -265,8 +350,8 @@ impl LocalHistory {
|
||||
(Some(modified), Some(oldest)) => modified.max(oldest - 1.0).min(now),
|
||||
_ => now,
|
||||
};
|
||||
let id = blake3::hash(text.as_bytes()).to_hex().to_string();
|
||||
self.store_locked(&mut state, path, id, &text, ORIGINAL, timestamp).map(|()| true)
|
||||
let entry = HistoryEntry::snapshot(path, &text, ORIGINAL, timestamp);
|
||||
self.store_locked(&mut state, entry, &text, None).map(|_| true)
|
||||
}
|
||||
|
||||
/// Snapshots `path`, or every file below it when it is a folder (at most `limit`
|
||||
@@ -290,6 +375,92 @@ impl LocalHistory {
|
||||
.count()
|
||||
}
|
||||
|
||||
/// Captures only paths that belong to this delete, including empty folders.
|
||||
/// The backup observes the same content limit as automatic history, but
|
||||
/// keeps exact bytes so a recreated file does not pick up new file defaults.
|
||||
pub fn capture_deletion_undo(&self, paths: &[PathBuf], limit: usize) -> DeletionUndo {
|
||||
let mut undo = DeletionUndo::default();
|
||||
let mut remaining = limit;
|
||||
for path in paths {
|
||||
self.capture_deleted_entry(path, &mut remaining, &mut undo);
|
||||
}
|
||||
undo
|
||||
}
|
||||
|
||||
fn capture_deleted_entry(&self, path: &Path, remaining: &mut usize, undo: &mut DeletionUndo) {
|
||||
if *remaining == 0 {
|
||||
undo.skipped.push(path.into());
|
||||
return;
|
||||
}
|
||||
*remaining -= 1;
|
||||
|
||||
let Ok(metadata) = fs::symlink_metadata(path) else {
|
||||
undo.skipped.push(path.into());
|
||||
return;
|
||||
};
|
||||
if is_link(&metadata) {
|
||||
undo.skipped.push(path.into());
|
||||
} else if metadata.is_dir() {
|
||||
if path.file_name().is_some_and(|name| name == ".git") {
|
||||
undo.skipped.push(path.into());
|
||||
return;
|
||||
}
|
||||
undo.directories.push(path.into());
|
||||
let Ok(entries) = fs::read_dir(path) else {
|
||||
undo.skipped.push(path.into());
|
||||
return;
|
||||
};
|
||||
for entry in entries {
|
||||
if *remaining == 0 {
|
||||
// Identify the unscanned subtree without enumerating the rest of it.
|
||||
undo.skipped.push(path.into());
|
||||
break;
|
||||
}
|
||||
if let Ok(entry) = entry {
|
||||
self.capture_deleted_entry(&entry.path(), remaining, undo);
|
||||
} else if !undo.skipped.iter().any(|entry| entry.as_ref() == path) {
|
||||
undo.skipped.push(path.into());
|
||||
}
|
||||
}
|
||||
} else if let Some(id) = read_snapshot_disk_text(path)
|
||||
.and_then(|raw| self.store(path, &document_text(&raw), DELETED, true, Some(&raw)).ok())
|
||||
{
|
||||
undo.files.push(DeletedFile { path: path.into(), id });
|
||||
} else {
|
||||
undo.skipped.push(path.into());
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns entries the caller should direct the user to recover from the
|
||||
/// system Trash. A newly occupied path and its subtree are left alone.
|
||||
pub fn restore_deletion_undo(&self, undo: DeletionUndo) -> Vec<ide_core::IpcPath> {
|
||||
let mut skipped = undo.skipped;
|
||||
let mut blocked: Vec<ide_core::IpcPath> = Vec::new();
|
||||
for path in undo.directories {
|
||||
if blocked.iter().any(|parent| path.starts_with(parent)) {
|
||||
continue;
|
||||
}
|
||||
if let Err(error) = fs::create_dir(&*path) {
|
||||
tracing::debug!("cannot restore deleted directory {}: {error}", path.display());
|
||||
skipped.push(path.clone());
|
||||
blocked.push(path);
|
||||
}
|
||||
}
|
||||
for file in undo.files {
|
||||
if blocked.iter().any(|parent| file.path.starts_with(parent)) {
|
||||
continue;
|
||||
}
|
||||
let restored = self.read_blob(&file.id).and_then(|bytes| restore_deleted_bytes(&file.path, &bytes));
|
||||
if let Err(error) = restored {
|
||||
tracing::debug!("cannot restore deleted file {}: {error}", file.path.display());
|
||||
skipped.push(file.path);
|
||||
}
|
||||
}
|
||||
skipped.sort();
|
||||
skipped.dedup();
|
||||
skipped
|
||||
}
|
||||
|
||||
/// The watcher saw `paths` disappear: files with history that are gone get a
|
||||
/// "Deleted" entry pointing at their last content (unless one was recorded already).
|
||||
pub fn note_removed(&self, paths: &[PathBuf]) -> IdeResult<()> {
|
||||
@@ -315,6 +486,7 @@ impl LocalHistory {
|
||||
label: DELETED.into(),
|
||||
size,
|
||||
kind: HistoryKind::Snapshot,
|
||||
undo_blob: None,
|
||||
};
|
||||
self.append(&mut state, entry)?;
|
||||
}
|
||||
@@ -334,6 +506,7 @@ impl LocalHistory {
|
||||
label: label.to_owned(),
|
||||
size: 0,
|
||||
kind: HistoryKind::Label,
|
||||
undo_blob: None,
|
||||
};
|
||||
let mut state = self.state.lock();
|
||||
self.append(&mut state, entry)
|
||||
@@ -379,15 +552,12 @@ impl LocalHistory {
|
||||
Ok(DirectoryHistory { entries, deleted })
|
||||
}
|
||||
|
||||
pub fn content(&self, id: &str) -> IdeResult<String> {
|
||||
fn read_blob(&self, id: &str) -> IdeResult<Vec<u8>> {
|
||||
if !valid_id(id) {
|
||||
return Err(IdeError::invalid(format!("invalid history id {id:?}")));
|
||||
}
|
||||
match fs::read(self.blob_path(id)) {
|
||||
Ok(bytes) => {
|
||||
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
|
||||
Ok(document_text(&text).into_owned())
|
||||
}
|
||||
Ok(bytes) => Ok(bytes),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
Err(IdeError::not_found(format!("history snapshot {id} not found")))
|
||||
}
|
||||
@@ -395,11 +565,24 @@ impl LocalHistory {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn content(&self, id: &str) -> IdeResult<String> {
|
||||
let bytes = self.read_blob(id)?;
|
||||
let text = String::from_utf8(bytes).unwrap_or_else(|e| String::from_utf8_lossy(e.as_bytes()).into());
|
||||
Ok(document_text(&text).into_owned())
|
||||
}
|
||||
|
||||
/// Bytes stored in blobs.
|
||||
pub fn stored_bytes(&self) -> u64 {
|
||||
let state = self.state.lock();
|
||||
let mut seen = HashSet::new();
|
||||
state.entries.iter().filter(|e| e.kind == HistoryKind::Snapshot && seen.insert(&e.id)).map(|e| e.size).sum()
|
||||
state
|
||||
.entries
|
||||
.iter()
|
||||
.filter(|e| e.kind == HistoryKind::Snapshot)
|
||||
.flat_map(HistoryEntry::blobs)
|
||||
.filter(|(id, _)| seen.insert(*id))
|
||||
.map(|(_, size)| size)
|
||||
.sum()
|
||||
}
|
||||
|
||||
/// Drops entries older than `max_age_days` calendar days and unreferenced blobs.
|
||||
@@ -430,7 +613,7 @@ impl LocalHistory {
|
||||
}
|
||||
ide_vfs::write_atomic(&self.index_path(), text.as_bytes())?;
|
||||
|
||||
let referenced: HashSet<&str> = kept.iter().map(|e| e.id.as_str()).collect();
|
||||
let referenced: HashSet<&str> = kept.iter().flat_map(HistoryEntry::blobs).map(|(id, _)| id).collect();
|
||||
for shard in fs::read_dir(self.dir.join("blobs"))?.flatten() {
|
||||
let Ok(files) = fs::read_dir(shard.path()) else { continue };
|
||||
let mut remaining = 0usize;
|
||||
@@ -467,8 +650,8 @@ fn retain(entries: Vec<HistoryEntry>, retention: Retention) -> Vec<HistoryEntry>
|
||||
};
|
||||
// Size bound: unique blob bytes, oldest snapshots dropped first.
|
||||
let mut refs: HashMap<String, (usize, u64)> = HashMap::new();
|
||||
for e in kept.iter().filter(|e| e.kind == HistoryKind::Snapshot) {
|
||||
refs.entry(e.id.clone()).or_insert((0, e.size)).0 += 1;
|
||||
for (id, size) in kept.iter().filter(|e| e.kind == HistoryKind::Snapshot).flat_map(HistoryEntry::blobs) {
|
||||
refs.entry(id.to_owned()).or_insert((0, size)).0 += 1;
|
||||
}
|
||||
let mut total: u64 = refs.values().map(|(_, size)| size).sum();
|
||||
if total <= retention.max_bytes {
|
||||
@@ -482,10 +665,12 @@ fn retain(entries: Vec<HistoryEntry>, retention: Retention) -> Vec<HistoryEntry>
|
||||
break;
|
||||
}
|
||||
drop[i] = true;
|
||||
let r = refs.get_mut(&kept[i].id).expect("counted");
|
||||
r.0 -= 1;
|
||||
if r.0 == 0 {
|
||||
total -= r.1;
|
||||
for (id, _) in kept[i].blobs() {
|
||||
let r = refs.get_mut(id).expect("counted");
|
||||
r.0 -= 1;
|
||||
if r.0 == 0 {
|
||||
total -= r.1;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut i = 0;
|
||||
@@ -578,6 +763,7 @@ mod tests {
|
||||
label: "Saved".into(),
|
||||
size,
|
||||
kind,
|
||||
undo_blob: None,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -660,6 +846,78 @@ mod tests {
|
||||
assert_eq!(h.stored_bytes(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_undo_captures_current_bytes_and_empty_folders() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let folder = root.join("subject");
|
||||
let empty = folder.join("empty-child/leaf");
|
||||
fs::create_dir_all(&empty).unwrap();
|
||||
let history = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let obsolete = folder.join("obsolete.txt");
|
||||
fs::write(&obsolete, "deleted before the folder").unwrap();
|
||||
history.capture_deletion_undo(std::slice::from_ref(&obsolete), 100);
|
||||
fs::remove_file(&obsolete).unwrap();
|
||||
let current = folder.join("current.txt");
|
||||
let original = b"\xEF\xBB\xBFheader\r\nbody\n";
|
||||
fs::write(¤t, original).unwrap();
|
||||
history.record(¤t, "header\nbody\n", "Saved").unwrap();
|
||||
let large = folder.join("sample.bin");
|
||||
fs::write(&large, vec![0; 2_300_000]).unwrap();
|
||||
|
||||
let undo = history.capture_deletion_undo(std::slice::from_ref(&folder), 100);
|
||||
let revisions = history.list(¤t).unwrap();
|
||||
assert!(revisions.iter().any(|entry| entry.label == DELETED));
|
||||
assert_eq!(revisions[0].id, revisions[1].id, "visible revisions share the normalized content");
|
||||
let blob = undo.files[0].id.clone();
|
||||
assert_ne!(blob, revisions[0].id);
|
||||
assert_eq!(
|
||||
history.stored_bytes(),
|
||||
("deleted before the folder".len() + "header\nbody\n".len() + original.len()) as u64
|
||||
);
|
||||
history.apply_retention(Retention::default()).unwrap();
|
||||
fs::remove_dir_all(&folder).unwrap();
|
||||
assert_eq!(history.restore_deletion_undo(undo), vec![large]);
|
||||
assert_eq!(fs::read(¤t).unwrap(), original);
|
||||
assert!(empty.is_dir());
|
||||
assert!(!obsolete.exists());
|
||||
history.clear().unwrap();
|
||||
assert!(!history.blob_path(&blob).exists(), "pruning removes the exact bytes too");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deletion_undo_preserves_new_files_and_reports_unavailable_entries() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let root = tmp.path().join("project");
|
||||
let folder = root.join("folder");
|
||||
fs::create_dir_all(&folder).unwrap();
|
||||
let history = LocalHistory::open(&tmp.path().join("history"), &root).unwrap();
|
||||
let file = folder.join("old.txt");
|
||||
fs::write(&file, "before deletion").unwrap();
|
||||
|
||||
let undo = history.capture_deletion_undo(std::slice::from_ref(&folder), 100);
|
||||
fs::remove_dir_all(&folder).unwrap();
|
||||
fs::create_dir_all(&folder).unwrap();
|
||||
fs::write(&file, "recreated").unwrap();
|
||||
assert_eq!(history.restore_deletion_undo(undo), vec![folder.clone()]);
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), "recreated");
|
||||
|
||||
let file_only = history.capture_deletion_undo(std::slice::from_ref(&file), 100);
|
||||
fs::write(&file, "new contents").unwrap();
|
||||
assert_eq!(history.restore_deletion_undo(file_only), vec![file.clone()]);
|
||||
assert_eq!(fs::read_to_string(&file).unwrap(), "new contents");
|
||||
|
||||
let limited = history.capture_deletion_undo(std::slice::from_ref(&folder), 1);
|
||||
assert_eq!(limited.skipped, vec![folder]);
|
||||
assert!(limited.files.is_empty());
|
||||
|
||||
let expired = history.capture_deletion_undo(std::slice::from_ref(&file), 100);
|
||||
fs::remove_file(&file).unwrap();
|
||||
history.clear().unwrap();
|
||||
assert_eq!(history.restore_deletion_undo(expired), vec![file.clone()]);
|
||||
assert!(!file.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn retention_keeps_working_days_and_bounds_size() {
|
||||
let id = |c: char| c.to_string().repeat(64);
|
||||
|
||||
@@ -25,7 +25,7 @@ pub use documents::{DetectLanguage, DocumentEncoding, DocumentInfo, DocumentLang
|
||||
pub use editorconfig::{EditorConfig, EditorConfigProps};
|
||||
pub use file_defaults::FileDefaults;
|
||||
pub use file_moves::{FileMove, FileMoves, UndoOutcome};
|
||||
pub use history::{DirectoryHistory, HistoryEntry, HistoryKind, LocalHistory, Retention};
|
||||
pub use history::{DeletionUndo, DirectoryHistory, HistoryEntry, HistoryKind, LocalHistory, Retention};
|
||||
pub use recent::{RecentProject, RecentProjectGroup, RecentProjects};
|
||||
pub use roots::{ProjectRoots, RootKind, SourceFolder};
|
||||
pub use settings::{SettingsScope, SettingsStore};
|
||||
|
||||
@@ -47,13 +47,19 @@ The Windows packages aren't code-signed yet, so Microsoft Defender SmartScreen m
|
||||
|
||||
## The window stays blank or stops responding on Linux
|
||||
|
||||
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal with the DMA-BUF renderer turned off, for example:
|
||||
WebKitGTK's DMA-BUF renderer fails on some Wayland setups. With the NVIDIA driver on Wayland, OpenIDEA turns the driver's explicit sync off for itself (`__NV_DISABLE_EXPLICIT_SYNC=1`), which avoids the failure and keeps the renderer. If the window stays blank, draws incorrectly, or stops reacting to the keyboard and mouse a few seconds after launch in another setup, quit OpenIDEA and start it from a terminal through XWayland first:
|
||||
|
||||
```sh
|
||||
GDK_BACKEND=x11 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
The page is still drawn on the GPU this way; at a fractional display scale the window may look less sharp. If that does not help, turn the DMA-BUF renderer off instead:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
The page is then drawn without the GPU, so dragging large panels can be slower. To keep the setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line to `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`.
|
||||
The page is then drawn without the GPU, so dragging large panels can be slower. To keep either setting for launches from the application menu with the deb or rpm package, copy `/usr/share/applications/OpenIDEA.desktop` to `~/.local/share/applications/` and change its `Exec=` line, for example to `Exec=env GDK_BACKEND=x11 openidea`.
|
||||
|
||||
## OpenIDEA exits at startup with a data directory error
|
||||
|
||||
|
||||
@@ -47,13 +47,19 @@ Windows 安装包目前还没有代码签名,Microsoft Defender SmartScreen
|
||||
|
||||
## Linux 上窗口空白或无响应
|
||||
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中关闭 DMA-BUF 渲染器启动,例如:
|
||||
在部分 Wayland 环境中,WebKitGTK 的 DMA-BUF 渲染器会出错。在使用 NVIDIA 驱动的 Wayland 会话中,OpenIDEA 会为自身关闭驱动的显式同步(`__NV_DISABLE_EXPLICIT_SYNC=1`),这样既能避开问题,又能保留该渲染器。如果在其他环境下窗口一片空白、显示异常,或启动几秒后键盘和鼠标都没有反应,先退出 OpenIDEA,再在终端中通过 XWayland 启动:
|
||||
|
||||
```sh
|
||||
GDK_BACKEND=x11 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
这样页面仍由 GPU 绘制;在非整数缩放比例下,窗口可能不够清晰。如果仍有问题,改为关闭 DMA-BUF 渲染器启动:
|
||||
|
||||
```sh
|
||||
WEBKIT_DISABLE_DMABUF_RENDERER=1 ./OpenIDEA_<version>_amd64.AppImage
|
||||
```
|
||||
|
||||
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上这个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并把其中的 `Exec=` 一行改成 `Exec=env WEBKIT_DISABLE_DMABUF_RENDERER=1 openidea`。
|
||||
这样页面不再用 GPU 绘制,拖动较大的面板可能变慢。使用 deb 或 rpm 包时,如果希望从应用菜单启动也带上其中一个设置,把 `/usr/share/applications/OpenIDEA.desktop` 复制到 `~/.local/share/applications/`,并修改其中的 `Exec=` 一行,例如改成 `Exec=env GDK_BACKEND=x11 openidea`。
|
||||
|
||||
## 启动时提示数据目录错误并退出
|
||||
|
||||
|
||||
@@ -248,6 +248,7 @@ fs_create_dir always project_host bin
|
||||
fs_create_file always project_host bindings sync
|
||||
fs_create_file_bytes always project_host bindings async
|
||||
fs_delete always project_host bindings async
|
||||
fs_delete_with_undo always project_host bindings async
|
||||
fs_entry_kind always project_host bindings async
|
||||
fs_open_with_system always desktop bindings async
|
||||
fs_probe always project_host bindings async
|
||||
@@ -258,6 +259,7 @@ fs_read_text always project_host bin
|
||||
fs_rename always project_host bindings async
|
||||
fs_resolve_reference always project_host bindings async
|
||||
fs_set_writable always project_host bindings sync
|
||||
fs_undo_delete always project_host bindings async
|
||||
gh_account_repos trusted desktop bindings async
|
||||
gh_api trusted desktop bindings async
|
||||
gh_availability trusted desktop bindings async
|
||||
|
||||
+47
-5
@@ -604,6 +604,8 @@ export const commands = {
|
||||
fsCreateFileBytes: (path: string, data: number[]) => typedError<null, IdeError>(__TAURI_INVOKE("fs_create_file_bytes", { path, data })),
|
||||
/** Moving to the trash can take a while (large trees): kept off the main thread. */
|
||||
fsDelete: (path: string) => typedError<null, IdeError>(__TAURI_INVOKE("fs_delete", { path })),
|
||||
/** Moves an item to the Trash and returns the snapshot for Project View Undo. */
|
||||
fsDeleteWithUndo: (path: string) => typedError<DeletionUndo, IdeError>(__TAURI_INVOKE("fs_delete_with_undo", { path })),
|
||||
fsEntryKind: (path: string) => typedError<EntryKind, IdeError>(__TAURI_INVOKE("fs_entry_kind", { path })),
|
||||
/**
|
||||
* Opens a project file with its default application (Office, PDF readers). The checks run here,
|
||||
@@ -631,6 +633,7 @@ export const commands = {
|
||||
* state). Returns whether the file is read-only now.
|
||||
*/
|
||||
fsSetWritable: (path: string, writable: boolean) => typedError<boolean, IdeError>(__TAURI_INVOKE("fs_set_writable", { path, writable })),
|
||||
fsUndoDelete: (undo: DeletionUndo) => typedError<IpcPath[], IdeError>(__TAURI_INVOKE("fs_undo_delete", { undo })),
|
||||
/** The repositories of the account gh is signed in to ("Get from Version Control" › GitHub); needs no project. */
|
||||
ghAccountRepos: () => typedError<GhAccountRepos, IdeError>(__TAURI_INVOKE("gh_account_repos")),
|
||||
/** A GitHub GraphQL / REST call through `gh api`; returns the response body. */
|
||||
@@ -662,9 +665,9 @@ export const commands = {
|
||||
/** Shows a GTK file chooser attached to `window`. `None` when the user cancels. */
|
||||
gtkPickPaths: (options: GtkPickOptions) => typedError<IpcPath[] | null, IdeError>(__TAURI_INVOKE("gtk_pick_paths", { options })),
|
||||
historyContent: (id: string) => typedError<string, IdeError>(__TAURI_INVOKE("history_content", { id })),
|
||||
historyList: (path: string) => typedError<HistoryEntry[], IdeError>(__TAURI_INVOKE("history_list", { path })),
|
||||
historyList: (path: string) => typedError<HistoryEntry_Serialize[], IdeError>(__TAURI_INVOKE("history_list", { path })),
|
||||
/** Show History on a folder: snapshots of the files under it (deleted ones included) and labels. */
|
||||
historyListDir: (path: string) => typedError<DirectoryHistory, IdeError>(__TAURI_INVOKE("history_list_dir", { path })),
|
||||
historyListDir: (path: string) => typedError<DirectoryHistory_Serialize, IdeError>(__TAURI_INVOKE("history_list_dir", { path })),
|
||||
/** Local History › Put Label…: a named point in the history of every file. */
|
||||
historyPutLabel: (label: string) => typedError<null, IdeError>(__TAURI_INVOKE("history_put_label", { label })),
|
||||
/**
|
||||
@@ -4737,6 +4740,11 @@ export type DeletedBranch = {
|
||||
unmerged: boolean,
|
||||
};
|
||||
|
||||
export type DeletedFile = {
|
||||
path: IpcPath,
|
||||
id: string,
|
||||
};
|
||||
|
||||
/** A deleted tag, enough to restore it (Restore in the tag-deleted notification). */
|
||||
export type DeletedTag = {
|
||||
name: string,
|
||||
@@ -4744,6 +4752,16 @@ export type DeletedTag = {
|
||||
target: string,
|
||||
};
|
||||
|
||||
/**
|
||||
* Paths and contents captured for one delete operation. Directory history is
|
||||
* intentionally broader and can contain paths deleted in an earlier operation.
|
||||
*/
|
||||
export type DeletionUndo = {
|
||||
directories: IpcPath[],
|
||||
files: DeletedFile[],
|
||||
skipped: IpcPath[],
|
||||
};
|
||||
|
||||
export type Dependency = {
|
||||
id: string,
|
||||
name: string,
|
||||
@@ -4980,9 +4998,20 @@ export type DirectoryCompareProgress = {
|
||||
export type DirectoryCompareStatus = "leftOnly" | "rightOnly" | "different" | "equal";
|
||||
|
||||
/** Changes under a folder (Show History on a directory). */
|
||||
export type DirectoryHistory = {
|
||||
export type DirectoryHistory = DirectoryHistory_Serialize | DirectoryHistory_Deserialize;
|
||||
|
||||
/** Changes under a folder (Show History on a directory). */
|
||||
export type DirectoryHistory_Deserialize = {
|
||||
/** Snapshots of files under the folder and labels, newest first. */
|
||||
entries: HistoryEntry[],
|
||||
entries: HistoryEntry_Deserialize[],
|
||||
/** Files with history that no longer exist on disk. */
|
||||
deleted: IpcPath[],
|
||||
};
|
||||
|
||||
/** Changes under a folder (Show History on a directory). */
|
||||
export type DirectoryHistory_Serialize = {
|
||||
/** Snapshots of files under the folder and labels, newest first. */
|
||||
entries: HistoryEntry_Serialize[],
|
||||
/** Files with history that no longer exist on disk. */
|
||||
deleted: IpcPath[],
|
||||
};
|
||||
@@ -6594,7 +6623,9 @@ export type Highlight = {
|
||||
|
||||
export type HighlightKind = "text" | "read" | "write";
|
||||
|
||||
export type HistoryEntry = {
|
||||
export type HistoryEntry = HistoryEntry_Serialize | HistoryEntry_Deserialize;
|
||||
|
||||
export type HistoryEntry_Deserialize = {
|
||||
/** Content hash (blake3 hex); identifies the stored blob. Empty for labels. */
|
||||
id: string,
|
||||
path: IpcPath,
|
||||
@@ -6605,6 +6636,17 @@ export type HistoryEntry = {
|
||||
kind?: HistoryKind,
|
||||
};
|
||||
|
||||
export type HistoryEntry_Serialize = {
|
||||
/** Content hash (blake3 hex); identifies the stored blob. Empty for labels. */
|
||||
id: string,
|
||||
path: IpcPath,
|
||||
timestampMs: number | null,
|
||||
/** e.g. "Saved", "External change", "Deleted", "Before refactoring: Move". */
|
||||
label: string,
|
||||
size: number,
|
||||
kind: HistoryKind,
|
||||
};
|
||||
|
||||
export type HistoryKind =
|
||||
/** A stored revision of `path`. */
|
||||
"snapshot" |
|
||||
|
||||
@@ -308,7 +308,7 @@
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0 -3px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.sideTabsResizer:focus-visible::after {
|
||||
background: color-mix(in srgb, var(--focus-ring) 55%, transparent);
|
||||
|
||||
@@ -62,7 +62,7 @@ export function SideTabsResizer({ side }: { side: "left" | "right" }) {
|
||||
handle.setPointerCapture(e.pointerId);
|
||||
const origin = e.clientX;
|
||||
const previous = pane.style.getPropertyValue(LIMIT_VAR);
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
let next: number | null = null;
|
||||
// Only this pane follows the pointer; every group takes the new width on release.
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
|
||||
@@ -241,6 +241,7 @@ describe("completion helpers", () => {
|
||||
it("finds identifier ends", () => {
|
||||
expect(identifierEnd("foo.barBaz(1)", 4)).toBe(10);
|
||||
expect(identifierEnd("x ", 1)).toBe(1);
|
||||
expect(identifierEnd("a𐐀\u0301;", 1)).toBe(4);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -704,15 +705,27 @@ describe("lookup commit characters", () => {
|
||||
});
|
||||
|
||||
describe("explicit completion", () => {
|
||||
function editor(labels: string[]) {
|
||||
function editor(labels: string[], doc = "pri|", serverItems = false) {
|
||||
const source: CompletionSource = (ctx) => {
|
||||
const word = ctx.matchBefore(/\w*/);
|
||||
return { from: word?.from ?? ctx.pos, options: labels.map((label) => ({ label })) };
|
||||
const from = word?.from ?? ctx.pos;
|
||||
const options = labels.map((label) =>
|
||||
serverItems
|
||||
? makeCompletion(item({ label, insertText: label, kind: "field" }), {
|
||||
doc: 1,
|
||||
path: "/p/a.ts",
|
||||
language: "typescript",
|
||||
pos: ctx.pos,
|
||||
text: ctx.state.doc,
|
||||
})
|
||||
: { label },
|
||||
);
|
||||
return { from, options };
|
||||
};
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "pri",
|
||||
selection: { anchor: 3 },
|
||||
doc: doc.replace("|", ""),
|
||||
selection: { anchor: doc.indexOf("|") },
|
||||
extensions: [completionExtension(), EditorState.languageData.of(() => [{ openideaCompletion: source }])],
|
||||
}),
|
||||
parent: document.body,
|
||||
@@ -720,13 +733,35 @@ describe("explicit completion", () => {
|
||||
return view;
|
||||
}
|
||||
|
||||
it("inserts a sole candidate right away (IDEA)", async () => {
|
||||
const view = editor(["println"]);
|
||||
it.each([
|
||||
["pri|", "println"],
|
||||
["pri|;", "println;"],
|
||||
])("inserts a sole candidate right away at the end of a prefix (%s)", async (doc, expected) => {
|
||||
const view = editor(["println"], doc);
|
||||
explicitCompletion(view);
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toBe("println"), { timeout: 2000 });
|
||||
await vi.waitFor(() => expect(view.state.doc.toString()).toBe(expected), { timeout: 2000 });
|
||||
view.destroy();
|
||||
});
|
||||
|
||||
it.each(["first|Name", "fir|Name", "first|𐐀Name"])(
|
||||
"leaves the lookup open inside an identifier (%s)",
|
||||
async (reference) => {
|
||||
const doc = `const person = { firstName: "Ada", lastName: "Lovelace" };\nconst value = person.${reference};`;
|
||||
const view = editor(["firstName"], doc, true);
|
||||
try {
|
||||
explicitCompletion(view);
|
||||
await vi.waitFor(() => expect(currentCompletions(view.state)).toHaveLength(1));
|
||||
await new Promise((resolve) => setTimeout(resolve, 150));
|
||||
expect(view.state.doc.toString()).toBe(doc.replace("|", ""));
|
||||
expect(currentCompletions(view.state)).toHaveLength(1);
|
||||
expect(runScopeHandlers(view, new KeyboardEvent("keydown", { key: "Tab" }), "editor")).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe(doc.replace(reference, "firstName"));
|
||||
} finally {
|
||||
view.destroy();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("keeps a sole candidate in the list when auto-insert is off", async () => {
|
||||
useProject.setState({ settings: { editor: { completion: { autoInsertSingle: false } } } as unknown as Settings });
|
||||
const view = editor(["println"]);
|
||||
|
||||
@@ -899,12 +899,18 @@ const lookupTracker = ViewPlugin.fromClass(
|
||||
if (options.length === 1 && editorPrefs().completion.autoInsertSingle) {
|
||||
const doc = u.state.doc;
|
||||
setTimeout(() => {
|
||||
const now = currentCompletions(view.state);
|
||||
const state = view.state;
|
||||
const now = currentCompletions(state);
|
||||
const { head } = state.selection.main;
|
||||
const line = state.doc.lineAt(head);
|
||||
const column = head - line.from;
|
||||
// Keep the lookup open so Tab can replace the remaining identifier.
|
||||
if (
|
||||
view.state.doc === doc &&
|
||||
completionStatus(view.state) === "active" &&
|
||||
state.doc === doc &&
|
||||
completionStatus(state) === "active" &&
|
||||
now.length === 1 &&
|
||||
now[0] === options[0]
|
||||
now[0] === options[0] &&
|
||||
identifierEnd(line.text, column) === column
|
||||
)
|
||||
acceptCompletion(view);
|
||||
}, AUTO_INSERT_DELAY);
|
||||
@@ -914,7 +920,7 @@ const lookupTracker = ViewPlugin.fromClass(
|
||||
},
|
||||
);
|
||||
|
||||
/** ⌃Space: explicit completion (a focused lookup; a sole candidate is inserted at once). */
|
||||
/** ⌃Space: explicit completion with a focused lookup. */
|
||||
export function explicitCompletion(view: EditorView): boolean {
|
||||
explicitPending.add(view);
|
||||
const started = startCompletion(view);
|
||||
|
||||
@@ -180,12 +180,15 @@ export function typeColumnText(
|
||||
return !detail || /^auto[- ]?import$/i.test(detail) ? source : `${detail} (${source})`;
|
||||
}
|
||||
|
||||
const WORD_CHAR = /[\p{L}\p{N}_$]/u;
|
||||
const WORD_CHAR = /[\p{L}\p{N}\p{M}_$]/u;
|
||||
|
||||
/** End of the identifier starting at `pos` in `line` (for ⇥ Replace without a server range). */
|
||||
export function identifierEnd(text: string, pos: number): number {
|
||||
let i = pos;
|
||||
while (i < text.length && WORD_CHAR.test(text[i]!)) i++;
|
||||
for (const char of text.slice(pos)) {
|
||||
if (!WORD_CHAR.test(char)) break;
|
||||
i += char.length;
|
||||
}
|
||||
return i;
|
||||
}
|
||||
|
||||
|
||||
@@ -38,7 +38,7 @@ export function ChangesResizer() {
|
||||
const start = pane.getBoundingClientRect().width;
|
||||
const origin = e.clientX;
|
||||
const previous = session.style.getPropertyValue(WIDTH_VAR);
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
let next: number | null = null;
|
||||
// Only this session follows the pointer; every task takes the new width on release.
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
|
||||
@@ -1253,7 +1253,7 @@
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0 -3px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.changesResizer:focus-visible::after {
|
||||
background: color-mix(in srgb, var(--focus-ring) 55%, transparent);
|
||||
|
||||
@@ -108,6 +108,13 @@
|
||||
border-color: var(--danger);
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
padding: var(--space-3) var(--space-3) 0;
|
||||
}
|
||||
|
||||
.recent {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(10, minmax(0, 1fr));
|
||||
|
||||
@@ -3,7 +3,7 @@ import { createRoot, type Root } from "react-dom/client";
|
||||
import type { EditorView } from "@codemirror/view";
|
||||
import { RgbaColorPicker } from "react-colorful";
|
||||
import { useTx } from "@/platform/i18n";
|
||||
import { IconButton, Popup } from "@/ui";
|
||||
import { Button, IconButton, Popup, T } from "@/ui";
|
||||
import { fromHex, toHex8, type Rgba } from "./colors";
|
||||
import styles from "./ColorPicker.module.css";
|
||||
|
||||
@@ -13,6 +13,7 @@ interface PickerRequest {
|
||||
value: Rgba;
|
||||
onChange?: (value: Rgba) => void;
|
||||
onCommit?: (value: Rgba) => void;
|
||||
onCancel?: () => void;
|
||||
}
|
||||
|
||||
let root: Root | null = null;
|
||||
@@ -63,28 +64,36 @@ function render() {
|
||||
}
|
||||
|
||||
export function openColorPicker(request: PickerRequest) {
|
||||
closeColorPicker();
|
||||
closeColorPicker(true);
|
||||
active = { ...request, initial: [...request.value] };
|
||||
sequence++;
|
||||
render();
|
||||
}
|
||||
|
||||
export function closeColorPicker() {
|
||||
function closeColorPicker(commit = false) {
|
||||
const previous = active;
|
||||
active = null;
|
||||
if (root) render();
|
||||
if (previous?.value.some((channel, index) => channel !== previous.initial[index])) rememberColor(previous.value);
|
||||
previous?.onCommit?.(previous.value);
|
||||
if (!previous) return;
|
||||
if (commit && previous.value.some((channel, index) => channel !== previous.initial[index])) {
|
||||
rememberColor(previous.value);
|
||||
previous.onCommit?.(previous.value);
|
||||
} else previous.onCancel?.();
|
||||
}
|
||||
|
||||
export function closeColorPickerFor(view: EditorView) {
|
||||
if (active?.view !== view) return;
|
||||
const cancel = active.onCancel;
|
||||
active = null;
|
||||
if (root) render();
|
||||
// Destruction and reconfiguration can happen during an editor update.
|
||||
if (cancel) queueMicrotask(cancel);
|
||||
}
|
||||
|
||||
export function disposeColorPicker() {
|
||||
const cancel = active?.onCancel;
|
||||
active = null;
|
||||
cancel?.();
|
||||
root?.unmount();
|
||||
host?.remove();
|
||||
root = null;
|
||||
@@ -140,14 +149,17 @@ function Picker({ id, request }: { id: number; request: PickerRequest }) {
|
||||
const t = useTx();
|
||||
const eyeDropper = (window as EyeDropperWindow).EyeDropper;
|
||||
useEffect(() => {
|
||||
const close = () => closeColorPickerFor(request.view);
|
||||
const close = () => {
|
||||
if (sequence === id) closeColorPicker();
|
||||
};
|
||||
request.view.scrollDOM.addEventListener("scroll", close);
|
||||
return () => request.view.scrollDOM.removeEventListener("scroll", close);
|
||||
}, [request.view]);
|
||||
}, [id, request.view]);
|
||||
|
||||
const update = (next: Rgba) => {
|
||||
if (sequence !== id || !active) return;
|
||||
setValue(next);
|
||||
if (sequence === id && active) active = { ...active, value: next };
|
||||
active = { ...active, value: next };
|
||||
request.onChange?.(next);
|
||||
};
|
||||
const channel = (index: 0 | 1 | 2, text: string) => {
|
||||
@@ -185,98 +197,113 @@ function Picker({ id, request }: { id: number; request: PickerRequest }) {
|
||||
anchor={request.anchor}
|
||||
placement="bottom-start"
|
||||
offset={4}
|
||||
onClose={closeColorPicker}
|
||||
onClose={(reason) => closeColorPicker(reason !== "escape")}
|
||||
aria-label={t("Color picker")}
|
||||
className={styles.popup}
|
||||
trapFocus
|
||||
closeOnDeactivate={false}
|
||||
>
|
||||
<div className={styles.pickerArea}>
|
||||
<RgbaColorPicker
|
||||
className={styles.control}
|
||||
color={{ r: value[0], g: value[1], b: value[2], a: value[3] }}
|
||||
onChange={({ r, g, b, a }) => update([r, g, b, a])}
|
||||
/>
|
||||
<div className={styles.sampleRow}>
|
||||
<IconButton
|
||||
icon="eyedropper"
|
||||
title="Pick screen color"
|
||||
size="small"
|
||||
disabled={!eyeDropper || sampling}
|
||||
onClick={() => void sampleScreen()}
|
||||
<form
|
||||
onSubmit={(event) => {
|
||||
event.preventDefault();
|
||||
if (!event.currentTarget.querySelector('[aria-invalid="true"]')) closeColorPicker(true);
|
||||
}}
|
||||
>
|
||||
<div className={styles.pickerArea}>
|
||||
<RgbaColorPicker
|
||||
className={styles.control}
|
||||
color={{ r: value[0], g: value[1], b: value[2], a: value[3] }}
|
||||
onChange={({ r, g, b, a }) => update([r, g, b, a])}
|
||||
/>
|
||||
<div className={styles.preview} role="img" aria-label={t("Current color")}>
|
||||
<span style={{ backgroundColor: `rgba(${value.join(", ")})` }} />
|
||||
<div className={styles.sampleRow}>
|
||||
<IconButton
|
||||
icon="eyedropper"
|
||||
title="Pick screen color"
|
||||
size="small"
|
||||
disabled={!eyeDropper || sampling}
|
||||
onClick={() => void sampleScreen()}
|
||||
/>
|
||||
<div className={styles.preview} role="img" aria-label={t("Current color")}>
|
||||
<span style={{ backgroundColor: `rgba(${value.join(", ")})` }} />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className={styles.fields}>
|
||||
<Field
|
||||
label="R"
|
||||
name="Red"
|
||||
value={String(value[0])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(0, v)}
|
||||
/>
|
||||
<Field
|
||||
label="G"
|
||||
name="Green"
|
||||
value={String(value[1])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(1, v)}
|
||||
/>
|
||||
<Field
|
||||
label="B"
|
||||
name="Blue"
|
||||
value={String(value[2])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(2, v)}
|
||||
/>
|
||||
<Field
|
||||
label="A%"
|
||||
name="Alpha percent"
|
||||
value={String(Math.round(value[3] * 100))}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(100)}
|
||||
onValid={alpha}
|
||||
/>
|
||||
<Field
|
||||
label={t("HEX")}
|
||||
name="Hexadecimal"
|
||||
value={toHex8(value).slice(1).toUpperCase()}
|
||||
maxLength={9}
|
||||
inputMode="text"
|
||||
isValid={(v) => fromHex(v) !== null}
|
||||
onValid={hex}
|
||||
/>
|
||||
</div>
|
||||
{recent.length > 0 && (
|
||||
<div className={styles.recent} role="group" aria-label={t("Recent colors")}>
|
||||
{recent.map((hex) => (
|
||||
<button
|
||||
key={hex}
|
||||
type="button"
|
||||
title={hex.toUpperCase()}
|
||||
aria-label={`${t("Recent color")} ${hex.toUpperCase()}`}
|
||||
aria-pressed={hex.toLowerCase() === toHex8(value)}
|
||||
className={styles.recentColor}
|
||||
onClick={() => {
|
||||
const next = fromHex(hex);
|
||||
if (next) update(next);
|
||||
}}
|
||||
>
|
||||
<span style={{ backgroundColor: hex }} />
|
||||
</button>
|
||||
))}
|
||||
<div className={styles.fields}>
|
||||
<Field
|
||||
label="R"
|
||||
name="Red"
|
||||
value={String(value[0])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(0, v)}
|
||||
/>
|
||||
<Field
|
||||
label="G"
|
||||
name="Green"
|
||||
value={String(value[1])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(1, v)}
|
||||
/>
|
||||
<Field
|
||||
label="B"
|
||||
name="Blue"
|
||||
value={String(value[2])}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(255)}
|
||||
onValid={(v) => channel(2, v)}
|
||||
/>
|
||||
<Field
|
||||
label="A%"
|
||||
name="Alpha percent"
|
||||
value={String(Math.round(value[3] * 100))}
|
||||
maxLength={3}
|
||||
inputMode="numeric"
|
||||
isValid={numeric(100)}
|
||||
onValid={alpha}
|
||||
/>
|
||||
<Field
|
||||
label={t("HEX")}
|
||||
name="Hexadecimal"
|
||||
value={toHex8(value).slice(1).toUpperCase()}
|
||||
maxLength={9}
|
||||
inputMode="text"
|
||||
isValid={(v) => fromHex(v) !== null}
|
||||
onValid={hex}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{recent.length > 0 && (
|
||||
<div className={styles.recent} role="group" aria-label={t("Recent colors")}>
|
||||
{recent.map((hex) => (
|
||||
<button
|
||||
key={hex}
|
||||
type="button"
|
||||
title={hex.toUpperCase()}
|
||||
aria-label={`${t("Recent color")} ${hex.toUpperCase()}`}
|
||||
aria-pressed={hex.toLowerCase() === toHex8(value)}
|
||||
className={styles.recentColor}
|
||||
onClick={() => {
|
||||
const next = fromHex(hex);
|
||||
if (next) update(next);
|
||||
}}
|
||||
>
|
||||
<span style={{ backgroundColor: hex }} />
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
<div className={styles.actions}>
|
||||
<Button size="small" onClick={() => closeColorPicker()}>
|
||||
<T>Cancel</T>
|
||||
</Button>
|
||||
<Button type="submit" variant="primary" size="small">
|
||||
<T>Apply</T>
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
@@ -1,8 +1,8 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { act } from "react";
|
||||
import { fireEvent } from "@testing-library/react";
|
||||
import { act, fireEvent, screen } from "@testing-library/react";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { history, undo, undoDepth } from "@codemirror/commands";
|
||||
import { vue } from "@codemirror/lang-vue";
|
||||
import { html } from "@codemirror/lang-html";
|
||||
import { colorPreviewGutter } from "./gutter";
|
||||
@@ -17,6 +17,75 @@ afterEach(() => {
|
||||
localStorage.removeItem("openidea.colorPicker.recent.v1");
|
||||
});
|
||||
|
||||
async function openCssPicker() {
|
||||
view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "color: #112233;",
|
||||
extensions: [
|
||||
history(),
|
||||
colorPreviewGutter({ doc: 1, path: "/p/a.css", language: "css", uiMode: null, readOnly: false }),
|
||||
],
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
const swatch = view.dom.querySelector(".cm-openidea-gutter-colors .cm-gutterElement span")!;
|
||||
await act(async () => fireEvent.mouseDown(swatch, { button: 0 }));
|
||||
return view;
|
||||
}
|
||||
|
||||
const changeHex = async (value: string) =>
|
||||
act(async () => fireEvent.change(screen.getByRole("textbox", { name: "Hexadecimal" }), { target: { value } }));
|
||||
|
||||
it("discards the preview on Escape and leaves other edits in the document and undo history", async () => {
|
||||
const view = await openCssPicker();
|
||||
await changeHex("445566");
|
||||
expect(view.contentDOM.textContent).toContain("#445566");
|
||||
expect(view.state.doc.toString()).toBe("color: #112233;");
|
||||
view.dispatch({ changes: { from: 0, insert: "/* note */ " }, userEvent: "input.type" });
|
||||
expect(view.contentDOM.textContent).toContain("#445566");
|
||||
await act(async () => fireEvent.keyDown(document, { key: "Escape" }));
|
||||
expect(view.state.doc.toString()).toBe("/* note */ color: #112233;");
|
||||
expect(undoDepth(view.state)).toBe(1);
|
||||
expect(undo(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("color: #112233;");
|
||||
expect(localStorage.getItem("openidea.colorPicker.recent.v1")).toBeNull();
|
||||
});
|
||||
|
||||
it.each([
|
||||
{ dismissal: "Apply", dismiss: () => fireEvent.click(screen.getByRole("button", { name: "Apply" })), commit: true },
|
||||
{ dismissal: "outside click", dismiss: () => fireEvent.pointerDown(document.body), commit: true },
|
||||
{
|
||||
dismissal: "Cancel",
|
||||
dismiss: () => fireEvent.click(screen.getByRole("button", { name: "Cancel" })),
|
||||
commit: false,
|
||||
},
|
||||
{ dismissal: "scroll", dismiss: (view: EditorView) => fireEvent.scroll(view.scrollDOM), commit: false },
|
||||
])("$dismissal closes the picker and preserves independent edits", async ({ dismiss, commit }) => {
|
||||
const view = await openCssPicker();
|
||||
view.dispatch({ changes: { from: 0, insert: "/* note */ " }, userEvent: "input.type" });
|
||||
await changeHex("aabbcc");
|
||||
await changeHex("445566");
|
||||
expect(view.contentDOM.textContent).toContain("#445566");
|
||||
await act(async () => dismiss(view));
|
||||
expect(screen.queryByRole("dialog", { name: "Color picker" })).not.toBeInTheDocument();
|
||||
expect(view.state.doc.toString()).toBe(`/* note */ color: ${commit ? "#445566" : "#112233"};`);
|
||||
expect(undoDepth(view.state)).toBe(commit ? 2 : 1);
|
||||
if (commit) {
|
||||
expect(undo(view)).toBe(true);
|
||||
expect(view.state.doc.toString()).toBe("/* note */ color: #112233;");
|
||||
}
|
||||
});
|
||||
|
||||
it("discards a preview whose color was changed by another edit", async () => {
|
||||
const view = await openCssPicker();
|
||||
await changeHex("445566");
|
||||
view.dispatch({ changes: { from: 7, to: 14, insert: "#aabbcc" }, userEvent: "input.type" });
|
||||
expect(view.contentDOM.textContent).toContain("#aabbcc");
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
|
||||
expect(view.state.doc.toString()).toBe("color: #aabbcc;");
|
||||
expect(undoDepth(view.state)).toBe(1);
|
||||
});
|
||||
|
||||
it("samples a screen color and offers it again as a recent color", async () => {
|
||||
vi.stubGlobal(
|
||||
"EyeDropper",
|
||||
@@ -39,9 +108,10 @@ it("samples a screen color and offers it again as a recent color", async () => {
|
||||
};
|
||||
await open();
|
||||
await act(async () => fireEvent.click(document.querySelector('button[aria-label="Pick screen color"]')!));
|
||||
expect(view.state.doc.toString()).toBe("color: #4c78ce;");
|
||||
expect(view.contentDOM.textContent).toContain("#4c78ce");
|
||||
|
||||
await act(async () => fireEvent.keyDown(document, { key: "Escape" }));
|
||||
await act(async () => fireEvent.click(screen.getByRole("button", { name: "Apply" })));
|
||||
expect(view.state.doc.toString()).toBe("color: #4c78ce;");
|
||||
expect(JSON.parse(localStorage.getItem("openidea.colorPicker.recent.v1")!)).toEqual(["#4c78ceff"]);
|
||||
|
||||
await open();
|
||||
@@ -96,14 +166,15 @@ it("updates a CSS literal from alpha and hex fields and ignores invalid input",
|
||||
|
||||
const field = (name: string) => document.querySelector<HTMLInputElement>(`input[aria-label="${name}"]`)!;
|
||||
await act(async () => fireEvent.change(field("Alpha percent"), { target: { value: "50" } }));
|
||||
expect(view.state.doc.toString()).toBe("color: #abcdef80;");
|
||||
expect(view.contentDOM.textContent).toContain("#abcdef80");
|
||||
expect(field("Hexadecimal").value).toBe("ABCDEF80");
|
||||
|
||||
await act(async () => fireEvent.change(field("Hexadecimal"), { target: { value: "00FF0080" } }));
|
||||
expect(view.state.doc.toString()).toBe("color: #00ff0080;");
|
||||
expect(view.contentDOM.textContent).toContain("#00ff0080");
|
||||
expect(field("Green").value).toBe("255");
|
||||
|
||||
await act(async () => fireEvent.change(field("Red"), { target: { value: "256" } }));
|
||||
expect(view.state.doc.toString()).toBe("color: #00ff0080;");
|
||||
expect(view.contentDOM.textContent).toContain("#00ff0080");
|
||||
expect(view.state.doc.toString()).toBe("color: #abcdef;");
|
||||
expect(field("Red").getAttribute("aria-invalid")).toBe("true");
|
||||
});
|
||||
@@ -2,8 +2,9 @@
|
||||
* Color preview gutter: a swatch on each line with a color literal (the first one), as IDEA's
|
||||
* color gutter icons. Picking a color replaces the literal in its own format.
|
||||
*/
|
||||
import type { Extension } from "@codemirror/state";
|
||||
import { GutterMarker, gutter, type EditorView } from "@codemirror/view";
|
||||
import { StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { Decoration, EditorView, GutterMarker, WidgetType, gutter } from "@codemirror/view";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { syntaxTree } from "@codemirror/language";
|
||||
import type { EditorDocContext } from "@/editor/api";
|
||||
import { findColors, formatColor, isMarkupLanguage, parseComputed, type ColorMatch, type Rgba } from "./colors";
|
||||
@@ -77,47 +78,114 @@ function lineColor(view: EditorView, pos: number, language: string): ColorMatch
|
||||
);
|
||||
}
|
||||
|
||||
/** Opens the color picker for `color` at `from`; each valid pick replaces the literal. */
|
||||
interface ColorEdit {
|
||||
id: symbol;
|
||||
from: number;
|
||||
to: number;
|
||||
original: string;
|
||||
preview: string;
|
||||
}
|
||||
|
||||
class ColorPreviewWidget extends WidgetType {
|
||||
constructor(readonly text: string) {
|
||||
super();
|
||||
}
|
||||
override eq(other: ColorPreviewWidget): boolean {
|
||||
return this.text === other.text;
|
||||
}
|
||||
override toDOM(view: EditorView): HTMLElement {
|
||||
const span = view.dom.ownerDocument.createElement("span");
|
||||
span.textContent = this.text;
|
||||
return span;
|
||||
}
|
||||
}
|
||||
|
||||
const setColorEdit = StateEffect.define<ColorEdit | null>();
|
||||
const colorEdit = StateField.define<ColorEdit | null>({
|
||||
create: () => null,
|
||||
update(edit, tr) {
|
||||
for (const effect of tr.effects) if (effect.is(setColorEdit)) return effect.value;
|
||||
if (!edit || !tr.docChanged) return edit;
|
||||
const from = tr.changes.mapPos(edit.from, 1);
|
||||
const to = tr.changes.mapPos(edit.to, -1);
|
||||
return from < to && tr.newDoc.sliceString(from, to) === edit.original ? { ...edit, from, to } : null;
|
||||
},
|
||||
provide: (field) =>
|
||||
EditorView.decorations.from(field, (edit) =>
|
||||
edit && edit.preview !== edit.original
|
||||
? Decoration.set(Decoration.replace({ widget: new ColorPreviewWidget(edit.preview) }).range(edit.from, edit.to))
|
||||
: Decoration.none,
|
||||
),
|
||||
});
|
||||
|
||||
/** Shows a local preview. The document and undo history change only when the choice is committed. */
|
||||
function pickColor(view: EditorView, from: number, color: ColorMatch, at: { x: number; y: number }) {
|
||||
const rgba = rgbaOf(color.text);
|
||||
if (!rgba) return;
|
||||
let current = color.text;
|
||||
const id = Symbol();
|
||||
const target = () => {
|
||||
const edit = view.state.field(colorEdit, false);
|
||||
return view.dom.isConnected && edit?.id === id ? edit : null;
|
||||
};
|
||||
openColorPicker({
|
||||
view,
|
||||
anchor: at,
|
||||
value: rgba,
|
||||
onChange: (next) => {
|
||||
if (!view.dom.isConnected || view.state.readOnly || view.state.sliceDoc(from, from + current.length) !== current)
|
||||
return;
|
||||
const text = formatColor(next, color);
|
||||
if (text === current) return;
|
||||
view.dispatch({ changes: { from, to: from + current.length, insert: text }, userEvent: "input.color" });
|
||||
current = text;
|
||||
const edit = target();
|
||||
if (!edit || view.state.readOnly) return;
|
||||
const preview = next.every((channel, index) => channel === rgba[index])
|
||||
? edit.original
|
||||
: formatColor(next, color);
|
||||
if (preview !== edit.preview) view.dispatch({ effects: setColorEdit.of({ ...edit, preview }) });
|
||||
},
|
||||
onCommit: (next) => {
|
||||
const edit = target();
|
||||
if (!edit) return;
|
||||
const effects = setColorEdit.of(null);
|
||||
const insert = formatColor(next, color);
|
||||
if (view.state.readOnly || insert === edit.original) view.dispatch({ effects });
|
||||
else
|
||||
view.dispatch({
|
||||
changes: { from: edit.from, to: edit.to, insert },
|
||||
effects,
|
||||
userEvent: "input.color",
|
||||
annotations: isolateHistory.of("full"),
|
||||
});
|
||||
},
|
||||
onCancel: () => {
|
||||
if (target()) view.dispatch({ effects: setColorEdit.of(null) });
|
||||
},
|
||||
});
|
||||
view.dispatch({
|
||||
effects: setColorEdit.of({ id, from, to: from + color.text.length, original: color.text, preview: color.text }),
|
||||
});
|
||||
}
|
||||
|
||||
export function colorPreviewGutter(ctx: EditorDocContext): Extension {
|
||||
return gutter({
|
||||
class: `${styles.gutter} cm-openidea-gutter-colors`,
|
||||
lineMarker: (view, block) => {
|
||||
const color = lineColor(view, block.from, ctx.language);
|
||||
return color ? new Swatch(color, !view.state.readOnly) : null;
|
||||
},
|
||||
lineMarkerChange: (update) => update.docChanged || update.startState.readOnly !== update.state.readOnly,
|
||||
domEventHandlers: {
|
||||
mousedown: (view, block, event) => {
|
||||
const e = event as MouseEvent;
|
||||
const swatch = e.target instanceof Element ? e.target.closest(`.${styles.swatch}`) : null;
|
||||
if (e.button !== 0 || !swatch || view.state.readOnly) return false;
|
||||
const line = view.state.doc.lineAt(block.from);
|
||||
return [
|
||||
colorEdit,
|
||||
gutter({
|
||||
class: `${styles.gutter} cm-openidea-gutter-colors`,
|
||||
lineMarker: (view, block) => {
|
||||
const color = lineColor(view, block.from, ctx.language);
|
||||
if (!color) return false;
|
||||
e.preventDefault();
|
||||
const rect = swatch.getBoundingClientRect();
|
||||
pickColor(view, line.from + color.from, color, { x: rect.left, y: rect.bottom });
|
||||
return true;
|
||||
return color ? new Swatch(color, !view.state.readOnly) : null;
|
||||
},
|
||||
},
|
||||
});
|
||||
lineMarkerChange: (update) => update.docChanged || update.startState.readOnly !== update.state.readOnly,
|
||||
domEventHandlers: {
|
||||
mousedown: (view, block, event) => {
|
||||
const e = event as MouseEvent;
|
||||
const swatch = e.target instanceof Element ? e.target.closest(`.${styles.swatch}`) : null;
|
||||
if (e.button !== 0 || !swatch || view.state.readOnly) return false;
|
||||
const line = view.state.doc.lineAt(block.from);
|
||||
const color = lineColor(view, block.from, ctx.language);
|
||||
if (!color) return false;
|
||||
e.preventDefault();
|
||||
const rect = swatch.getBoundingClientRect();
|
||||
pickColor(view, line.from + color.from, color, { x: rect.left, y: rect.bottom });
|
||||
return true;
|
||||
},
|
||||
},
|
||||
}),
|
||||
];
|
||||
}
|
||||
@@ -1,8 +1,7 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { EditorState } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { act } from "react";
|
||||
import { fireEvent } from "@testing-library/react";
|
||||
import { act, fireEvent, screen } from "@testing-library/react";
|
||||
const ipc = vi.hoisted(() => ({
|
||||
pluginLanguageVisuals: vi.fn(),
|
||||
pluginColorPresentations: vi.fn(async () => ({ status: "ok", data: ["red"] })),
|
||||
@@ -20,38 +19,52 @@ afterEach(() => {
|
||||
vi.useRealTimers();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
it("uses plugin presentations to replace precisely the reported range", async () => {
|
||||
vi.useFakeTimers();
|
||||
ipc.pluginLanguageVisuals.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: {
|
||||
version: 1,
|
||||
injections: [],
|
||||
gutterActions: [],
|
||||
colors: [
|
||||
["p", { range: { start: { line: 0, col: 1 }, end: { line: 0, col: 2 } }, red: 1, green: 0, blue: 0, alpha: 1 }],
|
||||
],
|
||||
},
|
||||
});
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "xyz",
|
||||
extensions: pluginColorPreview({ doc: 1, path: "/p/a", language: "text", uiMode: null, readOnly: false }),
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
const swatch = view.dom.querySelector<HTMLButtonElement>("button")!;
|
||||
await act(async () => swatch.click());
|
||||
const picker = document.querySelector<HTMLInputElement>('input[aria-label="Hexadecimal"]')!;
|
||||
await act(async () => fireEvent.change(picker, { target: { value: "00FF0080" } }));
|
||||
await act(async () => fireEvent.keyDown(document, { key: "Escape" }));
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
expect(view.state.doc.toString()).toBe("xredz");
|
||||
expect(ipc.pluginColorPresentations).toHaveBeenCalledWith(
|
||||
1,
|
||||
"p",
|
||||
expect.objectContaining({ red: 0, green: 1, blue: 0, alpha: 128 / 255 }),
|
||||
);
|
||||
});
|
||||
it.each(["Apply", "Escape"])(
|
||||
"uses plugin presentations to replace the reported range only on commit (%s)",
|
||||
async (dismissal) => {
|
||||
vi.useFakeTimers();
|
||||
ipc.pluginLanguageVisuals.mockResolvedValue({
|
||||
status: "ok",
|
||||
data: {
|
||||
version: 1,
|
||||
injections: [],
|
||||
gutterActions: [],
|
||||
colors: [
|
||||
[
|
||||
"p",
|
||||
{ range: { start: { line: 0, col: 1 }, end: { line: 0, col: 2 } }, red: 1, green: 0, blue: 0, alpha: 1 },
|
||||
],
|
||||
],
|
||||
},
|
||||
});
|
||||
const view = new EditorView({
|
||||
state: EditorState.create({
|
||||
doc: "xyz",
|
||||
extensions: pluginColorPreview({ doc: 1, path: "/p/a", language: "text", uiMode: null, readOnly: false }),
|
||||
}),
|
||||
parent: document.body,
|
||||
});
|
||||
views.push(view);
|
||||
await vi.advanceTimersByTimeAsync(300);
|
||||
const swatch = view.dom.querySelector<HTMLButtonElement>("button")!;
|
||||
await act(async () => swatch.click());
|
||||
const picker = document.querySelector<HTMLInputElement>('input[aria-label="Hexadecimal"]')!;
|
||||
await act(async () => fireEvent.change(picker, { target: { value: "00FF0080" } }));
|
||||
await act(async () => {
|
||||
if (dismissal === "Apply") fireEvent.click(screen.getByRole("button", { name: "Apply" }));
|
||||
else fireEvent.keyDown(document, { key: "Escape" });
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(0);
|
||||
if (dismissal === "Escape") {
|
||||
expect(view.state.doc.toString()).toBe("xyz");
|
||||
expect(ipc.pluginColorPresentations).not.toHaveBeenCalled();
|
||||
return;
|
||||
}
|
||||
expect(view.state.doc.toString()).toBe("xredz");
|
||||
expect(ipc.pluginColorPresentations).toHaveBeenCalledWith(
|
||||
1,
|
||||
"p",
|
||||
expect.objectContaining({ red: 0, green: 1, blue: 0, alpha: 128 / 255 }),
|
||||
);
|
||||
},
|
||||
);
|
||||
@@ -1,6 +1,7 @@
|
||||
/** Plugin colors use the shared picker and provider-supplied replacement strings. */
|
||||
import { RangeSet, StateEffect, StateField, type Extension } from "@codemirror/state";
|
||||
import { GutterMarker, ViewPlugin, gutter, type EditorView, type ViewUpdate } from "@codemirror/view";
|
||||
import { isolateHistory } from "@codemirror/commands";
|
||||
import { shownAgain, type EditorDocContext } from "@/editor/api";
|
||||
import { rangeToOffsets } from "@/editor/lsp/positions";
|
||||
import { pluginVisuals } from "@/editor/lsp/pluginVisuals";
|
||||
@@ -75,10 +76,14 @@ function pick(view: EditorView, ctx: EditorDocContext, plugin: string, color: Co
|
||||
void call(commands.pluginColorPresentations(ctx.doc, plugin, chosen))
|
||||
.then((list) => {
|
||||
const apply = (insert: string) => {
|
||||
if (view.state.doc === text && !view.state.readOnly)
|
||||
view.dispatch({ changes: { from, to, insert }, userEvent: "input.color" });
|
||||
if (view.dom.isConnected && view.state.doc === text && !view.state.readOnly)
|
||||
view.dispatch({
|
||||
changes: { from, to, insert },
|
||||
userEvent: "input.color",
|
||||
annotations: isolateHistory.of("full"),
|
||||
});
|
||||
};
|
||||
if (view.state.doc !== text) return;
|
||||
if (!view.dom.isConnected || view.state.doc !== text) return;
|
||||
if (list.length === 1) apply(list[0]!);
|
||||
else if (list.length)
|
||||
showContextMenu(
|
||||
|
||||
@@ -67,7 +67,7 @@
|
||||
right: -3px;
|
||||
width: 6px;
|
||||
height: 100%;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.rowNumber {
|
||||
display: flex;
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import type { DataSource } from "@/platform/ipc";
|
||||
|
||||
const backend = vi.hoisted(() => ({
|
||||
save: vi.fn(),
|
||||
password: vi.fn(),
|
||||
sshSecret: vi.fn(),
|
||||
sources: vi.fn(),
|
||||
connected: vi.fn(),
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
return {
|
||||
...actual,
|
||||
commands: {
|
||||
...actual.commands,
|
||||
dbSaveSources: backend.save,
|
||||
dbSetPassword: backend.password,
|
||||
dbSetSshSecret: backend.sshSecret,
|
||||
dbSources: backend.sources,
|
||||
dbConnected: backend.connected,
|
||||
},
|
||||
};
|
||||
});
|
||||
import { DatabaseDialogs } from "./Dialogs";
|
||||
import { useDatabase } from "./store";
|
||||
|
||||
const ok = <T,>(data: T) => ({ status: "ok" as const, data });
|
||||
const mysql: DataSource = { id: "my", name: "MySQL", driver: "mysql", user: "manage" };
|
||||
const tunnelled: DataSource = {
|
||||
...mysql,
|
||||
ssh: { enabled: true, host: "bastion", port: 22, user: "u", auth: "password", saveSecret: false },
|
||||
} as DataSource;
|
||||
|
||||
function ask(kind: "password" | "sshSecret", source: DataSource) {
|
||||
const resolve = vi.fn();
|
||||
useDatabase.setState({
|
||||
sources: [source],
|
||||
dialog: kind === "password" ? { kind, source, resolve } : { kind, source, prompt: "password required", resolve },
|
||||
});
|
||||
render(<DatabaseDialogs />);
|
||||
return resolve;
|
||||
}
|
||||
|
||||
function answer(secret: string) {
|
||||
fireEvent.change(document.querySelector("input[type=password]")!, { target: { value: secret } });
|
||||
fireEvent.click(screen.getByRole("checkbox", { name: "Save password" }));
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
for (const m of Object.values(backend)) m.mockReset();
|
||||
backend.save.mockResolvedValue(ok(null));
|
||||
backend.password.mockResolvedValue(ok(null));
|
||||
backend.sshSecret.mockResolvedValue(ok(null));
|
||||
backend.sources.mockImplementation(async () => ok(backend.save.mock.calls.at(-1)?.[0] ?? [mysql]));
|
||||
backend.connected.mockResolvedValue(ok([]));
|
||||
});
|
||||
|
||||
describe("connect-time secret prompts", () => {
|
||||
it("turns on the data source's Save password when it is ticked in the prompt", async () => {
|
||||
const resolve = ask("password", mysql);
|
||||
answer("secret");
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(true));
|
||||
expect(backend.save).toHaveBeenCalledWith([{ ...mysql, savePassword: true }]);
|
||||
expect(backend.password).toHaveBeenCalledWith("my", "secret", true);
|
||||
});
|
||||
|
||||
it("only stores the password when the setting already matches", async () => {
|
||||
const resolve = ask("password", { ...mysql, savePassword: true });
|
||||
fireEvent.change(document.querySelector("input[type=password]")!, { target: { value: "secret" } });
|
||||
fireEvent.click(screen.getByRole("button", { name: "Connect" }));
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(true));
|
||||
expect(backend.save).not.toHaveBeenCalled();
|
||||
expect(backend.password).toHaveBeenCalledWith("my", "secret", true);
|
||||
});
|
||||
|
||||
it("turns on the SSH tunnel's Save password of the data source's own SSH settings", async () => {
|
||||
const resolve = ask("sshSecret", tunnelled);
|
||||
answer("ssh-secret");
|
||||
await waitFor(() => expect(resolve).toHaveBeenCalledWith(true));
|
||||
expect(backend.save).toHaveBeenCalledWith([{ ...tunnelled, ssh: { ...tunnelled.ssh, saveSecret: true } }]);
|
||||
expect(backend.sshSecret).toHaveBeenCalledWith("my", "ssh-secret", true);
|
||||
});
|
||||
});
|
||||
@@ -4,7 +4,7 @@ import { call, commands, type DataSource } from "@/platform/ipc";
|
||||
import { Checkbox, Dialog, Input, lazyComponent, T } from "@/ui";
|
||||
import { sshLabel } from "./model";
|
||||
import { SourceDialog, snowflakeSecretLabel } from "./SourceDialog";
|
||||
import { closeDialog, useDatabase } from "./store";
|
||||
import { closeDialog, saveSource, sourceById, useDatabase } from "./store";
|
||||
import styles from "./Database.module.css";
|
||||
import { isImeKey } from "@/platform/ime";
|
||||
import { tx } from "@/platform/i18n";
|
||||
@@ -27,7 +27,9 @@ function PasswordDialog({ source, resolve }: { source: DataSource; resolve: (ok:
|
||||
resolve(ok);
|
||||
};
|
||||
const submit = async () => {
|
||||
await call(commands.dbSetPassword(source.id ?? "", password, save));
|
||||
// The checkbox is the data source's Save password setting: saved passwords are read only when it is on.
|
||||
if (save !== !!source.savePassword) await saveSource({ ...source, savePassword: save }, password);
|
||||
else await call(commands.dbSetPassword(source.id ?? "", password, save));
|
||||
done(true);
|
||||
};
|
||||
return (
|
||||
@@ -81,7 +83,12 @@ function SshSecretDialog({
|
||||
resolve(ok);
|
||||
};
|
||||
const submit = async () => {
|
||||
await call(commands.dbSetSshSecret(source.id ?? "", secret, save));
|
||||
// As for the password: the data source's own SSH settings read a saved secret only when Save is on.
|
||||
// An SSH configuration keeps its own setting.
|
||||
const stored = sourceById(source.id);
|
||||
if (stored?.ssh && !stored.ssh.config?.trim() && save !== !!stored.ssh.saveSecret)
|
||||
await saveSource({ ...stored, ssh: { ...stored.ssh, saveSecret: save } }, undefined, secret);
|
||||
else await call(commands.dbSetSshSecret(source.id ?? "", secret, save));
|
||||
done(true);
|
||||
};
|
||||
return (
|
||||
|
||||
@@ -574,7 +574,7 @@ export function Grid(props: GridProps) {
|
||||
const startResize = (e: MouseEvent, col: number) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
const startX = e.clientX;
|
||||
const start = widths[col] ?? 100;
|
||||
const move = (ev: globalThis.MouseEvent) => {
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
showServiceView,
|
||||
} from "@/workbench/contributions";
|
||||
import { registerFileNavigation } from "./fileNavigation";
|
||||
import { registerUrlNavigation } from "./urlNavigation";
|
||||
import { registerVariableNavigation } from "./variableNavigation";
|
||||
import { HTTP_LANGUAGE, httpEditorExtension, refreshRequests, requestAtCaret } from "./editor";
|
||||
import { HttpClientHeaderActions, HttpClientView } from "./HttpClientView";
|
||||
@@ -143,6 +144,7 @@ export function activate(): () => void {
|
||||
registerSpringEndpointProvider(),
|
||||
registerFeignNavigation(),
|
||||
registerVariableNavigation(),
|
||||
registerUrlNavigation(),
|
||||
registerFileNavigation(),
|
||||
useProject.subscribe((s, prev) => {
|
||||
if (s.project?.root !== prev.project?.root) resetHttpClient();
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import { ConstantPool, type ConstantFiles } from "./constants";
|
||||
import { controllersOf } from "./endpoints";
|
||||
import { parseSource } from "./source";
|
||||
|
||||
function project(files: Record<string, string>): ConstantFiles & { reads: string[] } {
|
||||
const reads: string[] = [];
|
||||
return {
|
||||
reads,
|
||||
filesNamed: vi.fn(async (name: string) => Object.keys(files).filter((p) => p.endsWith(`/${name}`))),
|
||||
read: async (path) => {
|
||||
reads.push(path);
|
||||
return files[path] ?? null;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function paths(text: string, files: ConstantFiles) {
|
||||
const file = parseSource(text);
|
||||
const pool = new ConstantPool(files);
|
||||
await pool.load([file]);
|
||||
return controllersOf(file, pool.resolverFor(file)).flatMap((c) =>
|
||||
c.endpoints.map((e) => `${e.httpMethod} ${e.paths}`),
|
||||
);
|
||||
}
|
||||
|
||||
const defines = {
|
||||
"/p/common/src/main/java/com/acme/common/AppServiceDefine.java": `package com.acme.common;
|
||||
public interface AppServiceDefine {
|
||||
String API_WEBAPI_PREFIX = "/api";
|
||||
}`,
|
||||
"/p/cockpit/src/main/java/com/acme/cockpit/CockpitApiDefine.java": `package com.acme.cockpit;
|
||||
public interface CockpitApiDefine {
|
||||
String API_COCKPIT_PREFIX = "/cockpit";
|
||||
String PATH_MAP = "/map";
|
||||
}`,
|
||||
};
|
||||
|
||||
describe("mapping constants of other classes", () => {
|
||||
it("joins constants of interfaces in other files and modules", async () => {
|
||||
const files = project(defines);
|
||||
const text = `package com.acme.cockpit.web;
|
||||
import com.acme.common.AppServiceDefine;
|
||||
import com.acme.cockpit.CockpitApiDefine;
|
||||
@RestController
|
||||
@RequestMapping(AppServiceDefine.API_WEBAPI_PREFIX + CockpitApiDefine.API_COCKPIT_PREFIX)
|
||||
public class CockpitMapController {
|
||||
@GetMapping(CockpitApiDefine.PATH_MAP + "/layers")
|
||||
public MapLayerVO layers(@RequestParam(required = false) String type) { return null; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /api/cockpit/map/layers"]);
|
||||
});
|
||||
|
||||
it("follows static imports, superclasses and constants built from other classes", async () => {
|
||||
const files = project({
|
||||
...defines,
|
||||
"/p/web/src/main/java/com/acme/web/Routes.java": `package com.acme.web;
|
||||
import com.acme.common.AppServiceDefine;
|
||||
public final class Routes {
|
||||
public static final String ORDERS = AppServiceDefine.API_WEBAPI_PREFIX + "/orders";
|
||||
}`,
|
||||
"/p/web/src/main/java/com/acme/web/BaseController.java": `package com.acme.web;
|
||||
public abstract class BaseController {
|
||||
protected static final String ITEMS = "/items";
|
||||
}`,
|
||||
});
|
||||
const text = `package com.acme.web;
|
||||
import static com.acme.web.Routes.ORDERS;
|
||||
@RestController
|
||||
@RequestMapping(ORDERS)
|
||||
public class OrderController extends BaseController {
|
||||
@GetMapping(ITEMS + "/{id}")
|
||||
public Item item(@PathVariable String id) { return null; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /api/orders/items/{id}"]);
|
||||
});
|
||||
|
||||
it("prefers the imported package when several classes share the name", async () => {
|
||||
const files = project({
|
||||
"/p/a/src/main/java/com/a/Paths.java": `package com.a;\npublic interface Paths { String ROOT = "/a"; }`,
|
||||
"/p/b/src/main/java/com/b/Paths.java": `package com.b;\npublic interface Paths { String ROOT = "/b"; }`,
|
||||
});
|
||||
const text = `package com.app;
|
||||
import com.b.Paths;
|
||||
@RestController
|
||||
class C {
|
||||
@GetMapping(Paths.ROOT)
|
||||
String get() { return ""; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /b"]);
|
||||
});
|
||||
|
||||
it("looks each class up once, and leaves out a constant no project file declares", async () => {
|
||||
const files = project(defines);
|
||||
const text = `@RestController
|
||||
class C {
|
||||
@GetMapping(Missing.PATH)
|
||||
String a() { return ""; }
|
||||
@GetMapping(CockpitApiDefine.PATH_MAP)
|
||||
String b() { return ""; }
|
||||
@PostMapping(CockpitApiDefine.PATH_MAP + "/x")
|
||||
String c() { return ""; }
|
||||
}`;
|
||||
expect(await paths(text, files)).toEqual(["GET /", "GET /map", "POST /map/x"]);
|
||||
expect(files.reads).toEqual(["/p/cockpit/src/main/java/com/acme/cockpit/CockpitApiDefine.java"]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,172 @@
|
||||
/**
|
||||
* Constants that mapping paths take from other classes: `Paths.API + "/orders"`,
|
||||
* statically imported ones and those of a superclass. Their classes are found by
|
||||
* file name in the index, read and kept until a Java / Kotlin file changes.
|
||||
*/
|
||||
import { call, commands } from "@/platform/ipc";
|
||||
import { Constants, type ExternalConstant } from "./endpoints";
|
||||
import { allClasses, parseSource, type Expr, type SourceFile } from "./source";
|
||||
|
||||
export interface ConstantFiles {
|
||||
/** The project's files called `name`. */
|
||||
filesNamed(name: string): Promise<string[]>;
|
||||
read(path: string): Promise<string | null>;
|
||||
}
|
||||
|
||||
const EXTENSIONS = [".java", ".kt"];
|
||||
/** Classes looked up per pool, and how many hops from a controller to a constant's class. */
|
||||
const MAX_CLASSES = 256;
|
||||
const MAX_DEPTH = 3;
|
||||
/** Qualifiers Spring and the JDK own: never project classes. */
|
||||
const LIBRARY = new Set(["MediaType", "RequestMethod", "HttpMethod", "HttpHeaders", "HttpStatus", "String", "Integer"]);
|
||||
|
||||
const isClassName = (s: string | undefined): s is string => !!s && /^[A-Z]/.test(s);
|
||||
const simpleType = (t: string) => t.replace(/<.*$/, "").replace(/\(.*$/, "").trim().split(".").pop() ?? "";
|
||||
|
||||
/** `C` of `a.b.C.NAME` / `a.b.C.*` (a static import; the parser drops the `static`). */
|
||||
function staticImportClass(imp: string): string | null {
|
||||
const parts = imp.split(".");
|
||||
const owner = parts[parts.length - 2];
|
||||
return parts.length >= 3 && isClassName(owner) ? owner : null;
|
||||
}
|
||||
|
||||
/** Classes whose constants `file` can use without naming the class. */
|
||||
function inheritedClasses(file: SourceFile): string[] {
|
||||
const out = new Set<string>();
|
||||
for (const imp of file.imports) {
|
||||
const c = staticImportClass(imp);
|
||||
if (c) out.add(c);
|
||||
}
|
||||
for (const c of allClasses(file)) if (c.superclass) out.add(simpleType(c.superclass));
|
||||
return [...out].filter(isClassName);
|
||||
}
|
||||
|
||||
function qualifiers(expr: Expr, out: Set<string>) {
|
||||
for (let i = 0; i + 2 < expr.length; i++) {
|
||||
const [a, dot, b] = [expr[i]!, expr[i + 1]!, expr[i + 2]!];
|
||||
if (a.kind === "id" && dot.kind === "p" && dot.text === "." && b.kind === "id" && isClassName(a.text))
|
||||
out.add(a.text);
|
||||
}
|
||||
}
|
||||
|
||||
/** Classes `file` takes constants from: qualifiers in annotations and constant initializers, and the inherited ones. */
|
||||
export function referencedClasses(file: SourceFile): string[] {
|
||||
const out = new Set(inheritedClasses(file));
|
||||
const classes = allClasses(file);
|
||||
for (const c of classes) {
|
||||
for (const a of [...c.annotations, ...c.methods.flatMap((m) => m.annotations)])
|
||||
for (const expr of a.args.values()) qualifiers(expr, out);
|
||||
for (const f of c.fields) if (f.init) qualifiers(f.init, out);
|
||||
}
|
||||
for (const f of file.fields) if (f.init) qualifiers(f.init, out);
|
||||
const own = new Set(classes.map((c) => c.name));
|
||||
return [...out].filter((c) => !own.has(c) && !LIBRARY.has(c));
|
||||
}
|
||||
|
||||
export class ConstantPool {
|
||||
/** Class name → constants of its file; `null` when no project file declares it. */
|
||||
private readonly classes = new Map<string, Constants | null>();
|
||||
private readonly pending = new Map<string, Promise<SourceFile | null>>();
|
||||
private readonly resolving = new Set<string>();
|
||||
|
||||
constructor(private readonly files: ConstantFiles) {}
|
||||
|
||||
/** Resolves the constants `file` takes from classes loaded so far. */
|
||||
resolverFor(file: SourceFile): ExternalConstant {
|
||||
const inherited = inheritedClasses(file);
|
||||
return (qualifier, name) => {
|
||||
for (const owner of qualifier ? [qualifier] : inherited) {
|
||||
const key = `${owner}.${name}`;
|
||||
const constants = this.classes.get(owner);
|
||||
if (!constants || this.resolving.has(key)) continue;
|
||||
this.resolving.add(key);
|
||||
try {
|
||||
const v = constants.named(name);
|
||||
if (v != null) return v;
|
||||
} finally {
|
||||
this.resolving.delete(key);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
}
|
||||
|
||||
/** Loads the classes `files` take constants from, and theirs in turn; true when one of them is now known. */
|
||||
async load(files: readonly SourceFile[]): Promise<boolean> {
|
||||
let added = false;
|
||||
let round = [...files];
|
||||
for (let depth = 0; depth < MAX_DEPTH && round.length; depth++) {
|
||||
const next: SourceFile[] = [];
|
||||
for (const file of round)
|
||||
for (const name of referencedClasses(file)) {
|
||||
if (this.classes.has(name) && !this.pending.has(name)) continue;
|
||||
if (!this.pending.has(name) && this.classes.size >= MAX_CLASSES) continue;
|
||||
const isNew = !this.pending.has(name);
|
||||
const loaded = await this.lookup(name, file);
|
||||
if (!loaded) continue;
|
||||
added = true;
|
||||
if (isNew) next.push(loaded);
|
||||
}
|
||||
round = next;
|
||||
}
|
||||
return added;
|
||||
}
|
||||
|
||||
private lookup(name: string, from: SourceFile): Promise<SourceFile | null> {
|
||||
const running = this.pending.get(name);
|
||||
if (running) return running;
|
||||
this.classes.set(name, null);
|
||||
const promise = this.find(name, from)
|
||||
.then((file) => {
|
||||
if (file) {
|
||||
const constants = new Constants(file, this.resolverFor(file));
|
||||
// Nested classes too: `Outer.Inner.NAME` names `Inner`.
|
||||
for (const c of allClasses(file))
|
||||
if (c.name === name || !this.classes.get(c.name)) this.classes.set(c.name, constants);
|
||||
}
|
||||
return file;
|
||||
})
|
||||
.catch(() => null)
|
||||
.finally(() => this.pending.delete(name));
|
||||
this.pending.set(name, promise);
|
||||
return promise;
|
||||
}
|
||||
|
||||
/** The file declaring class `name`, preferring the package `from` imports it from, then its own package. */
|
||||
private async find(name: string, from: SourceFile): Promise<SourceFile | null> {
|
||||
const imported = from.imports.find((i) => i.endsWith(`.${name}`) || i.includes(`.${name}.`));
|
||||
const pkg = imported ? imported.slice(0, imported.indexOf(`.${name}`)) : from.packageName;
|
||||
for (const ext of EXTENSIONS) {
|
||||
const paths = (await this.files.filesNamed(`${name}${ext}`)).map((p) => p.replace(/\\/g, "/"));
|
||||
if (!paths.length) continue;
|
||||
const suffix = `/${pkg.replace(/\./g, "/")}/${name}${ext}`;
|
||||
const path = paths.find((p) => p.endsWith(suffix)) ?? paths[0]!;
|
||||
const text = await this.files.read(path);
|
||||
if (text != null) return parseSource(text);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const projectFiles: ConstantFiles = {
|
||||
filesNamed: async (name) => (await call(commands.findFilesNamed(name))).map(String),
|
||||
read: async (path) => {
|
||||
try {
|
||||
return await call(commands.fsReadText(path));
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
let shared: ConstantPool | null = null;
|
||||
|
||||
/** The project's pool, shared by the route index and the editors. */
|
||||
export function constantPool(): ConstantPool {
|
||||
return (shared ??= new ConstantPool(projectFiles));
|
||||
}
|
||||
|
||||
/** Forgets the loaded classes (a Java / Kotlin file changed, or the project closed). */
|
||||
export function resetConstantPool() {
|
||||
shared = null;
|
||||
}
|
||||
@@ -19,6 +19,7 @@ import { useProject } from "@/platform/project";
|
||||
import { isVirtualUri } from "@/platform/virtualDocs";
|
||||
import { gutterIconMarkup, showContextMenu, type MenuItem } from "@/ui";
|
||||
import { notifications, type MenuGroupContext } from "@/workbench/contributions";
|
||||
import { constantPool } from "./constants";
|
||||
import { springAt, springControllers, type Controller, type Endpoint } from "./endpoints";
|
||||
import { bodyLookup, findHost, renderRequest, skeleton, type SourceReader } from "./request";
|
||||
import { parseSource } from "./source";
|
||||
@@ -39,6 +40,11 @@ export const sourceReader: SourceReader = {
|
||||
filesNamed: (name) => call(commands.findFilesNamed(name)),
|
||||
};
|
||||
|
||||
/** Controllers of `text`, with the other classes' constants loaded so far. */
|
||||
function controllersIn(text: string): Controller[] {
|
||||
return springControllers(text, (file) => constantPool().resolverFor(file));
|
||||
}
|
||||
|
||||
/** One request per endpoint (`paths[i]` picks another path of the mapping). */
|
||||
export interface Target {
|
||||
endpoint: Endpoint;
|
||||
@@ -109,7 +115,7 @@ function controllerItems(sourcePath: string, text: string, c: Controller): MenuI
|
||||
|
||||
/** Editor context menu items for the caret at `offset`: the generate actions (a path choice for several paths). */
|
||||
export function springMenuItems(sourcePath: string, text: string, offset: number): MenuItem[] {
|
||||
const { controller, endpoint } = springAt(springControllers(text), offset);
|
||||
const { controller, endpoint } = springAt(controllersIn(text), offset);
|
||||
const items: MenuItem[] = [];
|
||||
if (endpoint)
|
||||
items.push(
|
||||
@@ -136,7 +142,7 @@ export async function generateAtCaret(scope: "endpoint" | "controller"): Promise
|
||||
const e = activeEditor();
|
||||
if (!e || !SPRING_LANGUAGES.has(e.ctx.language)) return;
|
||||
const text = e.view.state.doc.toString();
|
||||
const { controller, endpoint } = springAt(springControllers(text), e.view.state.selection.main.head);
|
||||
const { controller, endpoint } = springAt(controllersIn(text), e.view.state.selection.main.head);
|
||||
const endpoints = scope === "endpoint" ? (endpoint ? [endpoint] : []) : (controller?.endpoints ?? []);
|
||||
if (!endpoints.length) {
|
||||
notifications().notify({
|
||||
@@ -178,7 +184,7 @@ function computeMarks(state: EditorState): Mark[] {
|
||||
const doc = state.doc;
|
||||
const marks: Mark[] = [];
|
||||
const lineStart = (offset: number) => doc.lineAt(Math.min(offset, doc.length)).from;
|
||||
for (const c of springControllers(doc.toString())) {
|
||||
for (const c of controllersIn(doc.toString())) {
|
||||
if (c.endpoints.length)
|
||||
marks.push({
|
||||
pos: lineStart(c.offset),
|
||||
@@ -239,9 +245,18 @@ export function springEditorExtension(ctx: EditorDocContext): Extension {
|
||||
const same =
|
||||
cur.length === found.length && cur.every((m, i) => m.pos === found[i]!.pos && m.key === found[i]!.key);
|
||||
if (!same) this.view.dispatch({ effects: setMarks.of(found) });
|
||||
// Paths built from other classes' constants: load those classes, then mark again.
|
||||
if (found.length) {
|
||||
const pool = constantPool();
|
||||
void pool.load([parseSource(this.view.state.doc.toString())]).then((loaded) => {
|
||||
if (loaded && pool === constantPool() && !this.destroyed) this.schedule(0);
|
||||
});
|
||||
}
|
||||
}, delay);
|
||||
}
|
||||
destroyed = false;
|
||||
destroy() {
|
||||
this.destroyed = true;
|
||||
clearTimeout(this.timer);
|
||||
}
|
||||
},
|
||||
@@ -250,7 +265,7 @@ export function springEditorExtension(ctx: EditorDocContext): Extension {
|
||||
// Only files that have mappings (the gutter found some) are parsed again here.
|
||||
if (!view.state.field(marksField, false)?.length) return [];
|
||||
const text = view.state.doc.toString();
|
||||
const { controller, endpoint } = springAt(springControllers(text), view.state.selection.main.head);
|
||||
const { controller, endpoint } = springAt(controllersIn(text), view.state.selection.main.head);
|
||||
const out: ContributedIntention[] = [];
|
||||
if (endpoint)
|
||||
out.push({
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
/**
|
||||
* Spring Web request mappings of a Java / Kotlin source: `@RequestMapping` /
|
||||
* `@GetMapping`… methods of `@RestController` / `@Controller` classes, with
|
||||
* the class-level mapping applied. Constants are resolved within the file.
|
||||
* the class-level mapping applied. Constants are resolved within the file, and
|
||||
* through an {@link ExternalConstant} in other classes (`constants.ts`).
|
||||
*/
|
||||
import {
|
||||
allClasses,
|
||||
@@ -86,12 +87,27 @@ const MEDIA_TYPES: Record<string, string> = {
|
||||
TEXT_XML: "text/xml",
|
||||
};
|
||||
|
||||
/** The value of constant `name` of another class (`qualifier`, or an inherited / statically imported one when absent). */
|
||||
export type ExternalConstant = (qualifier: string | undefined, name: string) => string | null;
|
||||
|
||||
/** Evaluates string-valued annotation arguments within one file. */
|
||||
export class Constants {
|
||||
private readonly fields = new Map<string, Expr>();
|
||||
constructor(file: SourceFile) {
|
||||
for (const f of [...file.fields, ...allClasses(file).flatMap((c) => c.fields)])
|
||||
private readonly classes: Set<string>;
|
||||
constructor(
|
||||
file: SourceFile,
|
||||
private readonly external?: ExternalConstant,
|
||||
) {
|
||||
const classes = allClasses(file);
|
||||
for (const f of [...file.fields, ...classes.flatMap((c) => c.fields)])
|
||||
if (f.init && !this.fields.has(f.name)) this.fields.set(f.name, f.init);
|
||||
this.classes = new Set(classes.map((c) => c.name));
|
||||
}
|
||||
|
||||
/** The value of this file's constant `name`. */
|
||||
named(name: string): string | null {
|
||||
const init = this.fields.get(name);
|
||||
return init ? this.value(init, false, new Set([name])) : null;
|
||||
}
|
||||
|
||||
/** Every element of an array (`{a, b}`, `[a, b]`, `arrayOf(a, b)`) or the single value; unresolvable ones dropped. */
|
||||
@@ -133,7 +149,8 @@ export class Constants {
|
||||
(m, a: string | undefined, b: string | undefined) => {
|
||||
const name = (a ?? b)!;
|
||||
const init = seen.has(name) ? undefined : this.fields.get(name);
|
||||
return init ? (this.value(init, false, new Set([...seen, name])) ?? m) : m;
|
||||
if (init) return this.value(init, false, new Set([...seen, name])) ?? m;
|
||||
return seen.has(name) ? m : (this.external?.(undefined, name) ?? m);
|
||||
},
|
||||
);
|
||||
if (part.length === 1 && part[0]!.kind === "num") return part[0]!.text;
|
||||
@@ -144,11 +161,20 @@ export class Constants {
|
||||
const last = names[names.length - 1]!;
|
||||
const qualifier = names[names.length - 2];
|
||||
if (qualifier === "MediaType") return MEDIA_TYPES[last.replace(/_VALUE$/, "")] ?? null;
|
||||
// `Other.NAME` of a class declared elsewhere.
|
||||
if (qualifier && !this.classes.has(qualifier)) {
|
||||
const v = this.external?.(qualifier, last);
|
||||
if (v != null) return v;
|
||||
}
|
||||
const init = this.fields.get(last);
|
||||
if (init && !seen.has(last)) {
|
||||
seen.add(last);
|
||||
return this.value(init, enums, seen);
|
||||
}
|
||||
if (!qualifier && !enums) {
|
||||
const v = this.external?.(undefined, last);
|
||||
if (v != null) return v;
|
||||
}
|
||||
return enums ? last : null;
|
||||
}
|
||||
}
|
||||
@@ -267,8 +293,8 @@ function endpoint(cls: ClassDecl, method: ClassDecl["methods"][number], c: Const
|
||||
};
|
||||
}
|
||||
|
||||
export function controllersOf(file: SourceFile): Controller[] {
|
||||
const constants = new Constants(file);
|
||||
export function controllersOf(file: SourceFile, external?: ExternalConstant): Controller[] {
|
||||
const constants = new Constants(file, external);
|
||||
const out: Controller[] = [];
|
||||
for (const cls of allClasses(file)) {
|
||||
if (!cls.annotations.some((a) => CONTROLLER.has(a.name))) continue;
|
||||
@@ -279,10 +305,11 @@ export function controllersOf(file: SourceFile): Controller[] {
|
||||
}
|
||||
|
||||
/** Controllers of a Java / Kotlin source, with their endpoints. */
|
||||
export function springControllers(text: string): Controller[] {
|
||||
export function springControllers(text: string, external?: (file: SourceFile) => ExternalConstant): Controller[] {
|
||||
// Cheap guard: most files are not controllers.
|
||||
if (!/@(?:[\w.]+\.)?(?:Rest)?Controller\b/.test(text)) return [];
|
||||
return controllersOf(parseSource(text));
|
||||
const file = parseSource(text);
|
||||
return controllersOf(file, external?.(file));
|
||||
}
|
||||
|
||||
/** The controller and endpoint whose declaration holds `offset`. */
|
||||
|
||||
@@ -3,6 +3,7 @@ import { call, commands, onIdeEvent, type ProjectInfo } from "@/platform/ipc";
|
||||
import { ipcPath, isSameOrInside } from "@/platform/paths";
|
||||
import { projectFolder, relativePath, useProject } from "@/platform/project";
|
||||
import { registerEndpointProvider, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { constantPool, resetConstantPool } from "./constants";
|
||||
import { controllersOf } from "./endpoints";
|
||||
import { controllerMethods, type ControllerMethod } from "./feign";
|
||||
import { parseSource } from "./source";
|
||||
@@ -38,6 +39,7 @@ export function isRouteSource(path: string): boolean {
|
||||
/** Forgets the index, so the next search rescans the project. */
|
||||
export function clearRouteIndex() {
|
||||
cached = null;
|
||||
resetConstantPool();
|
||||
}
|
||||
|
||||
/** The project's routes, scanned once per project and kept in memory. */
|
||||
@@ -67,6 +69,7 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
|
||||
const sources = await call(commands.springRouteSources());
|
||||
const routes: EndpointEntry[] = [];
|
||||
const controllers: ControllerTarget[] = [];
|
||||
const parsed = [];
|
||||
for (const source of sources) {
|
||||
const path = ipcPath(source.path);
|
||||
const folder = project ? projectFolder(project, path)?.root : root;
|
||||
@@ -74,9 +77,14 @@ async function scan(root: string, project: ProjectInfo | null): Promise<RouteInd
|
||||
const base = ipcPath(folder).replace(/\/$/, "");
|
||||
if (!isSameOrInside(path, base)) continue;
|
||||
if (!source.text.includes("Controller")) continue;
|
||||
const file = parseSource(source.text);
|
||||
parsed.push({ source, path, base, file: parseSource(source.text) });
|
||||
}
|
||||
// Mapping paths built from other classes' constants need those classes first.
|
||||
const pool = constantPool();
|
||||
await pool.load(parsed.map((p) => p.file));
|
||||
for (const { source, path, base, file } of parsed) {
|
||||
controllers.push(...controllerMethods(source.text, file).map((method) => ({ ...method, path })));
|
||||
for (const controller of controllersOf(file)) {
|
||||
for (const controller of controllersOf(file, pool.resolverFor(file))) {
|
||||
for (const endpoint of controller.endpoints) {
|
||||
const at = lineCol(source.text, endpoint.offset);
|
||||
// A mapping without a path answers nothing to look up by URL; the method
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Text } from "@codemirror/state";
|
||||
import { describe, expect, it } from "vitest";
|
||||
import type { EndpointEntry } from "@/workbench/contributions";
|
||||
import { endpointsFor, requestPathAt } from "./urlNavigation";
|
||||
|
||||
const entry = (method: string, url: string, methodName = "handler"): EndpointEntry => ({
|
||||
method,
|
||||
url,
|
||||
controller: "C",
|
||||
methodName,
|
||||
path: "/p/C.java",
|
||||
rel: "C.java",
|
||||
line: 3,
|
||||
col: 4,
|
||||
});
|
||||
|
||||
describe("request URL navigation", () => {
|
||||
const doc = Text.of([
|
||||
"### 读取本区配置",
|
||||
"GET http://localhost:19210/api/cockpit/config?x=1",
|
||||
"Content-Type: application/json",
|
||||
"",
|
||||
"###",
|
||||
"POST {{host}}/api/orders/{{id}}/items",
|
||||
"http://localhost:8080/health",
|
||||
"GET /relative/path",
|
||||
]);
|
||||
const at = (line: number, col: number) => doc.line(line).from + col;
|
||||
|
||||
it("finds the method and the path of the URL under the caret", () => {
|
||||
const get = requestPathAt(doc, at(2, 30));
|
||||
expect(get).toMatchObject({ method: "GET", path: "/api/cockpit/config" });
|
||||
expect(doc.sliceString(get!.from, get!.to)).toBe("/api/cockpit/config");
|
||||
expect(requestPathAt(doc, at(6, 20))).toMatchObject({ method: "POST", path: "/api/orders/{{id}}/items" });
|
||||
expect(requestPathAt(doc, at(7, 5))).toMatchObject({ method: "GET", path: "/health" });
|
||||
expect(requestPathAt(doc, at(8, 8))).toMatchObject({ method: "GET", path: "/relative/path" });
|
||||
expect(requestPathAt(doc, at(1, 5))).toBeNull();
|
||||
expect(requestPathAt(doc, at(3, 5))).toBeNull();
|
||||
expect(requestPathAt(doc, at(2, 1))).toBeNull();
|
||||
});
|
||||
|
||||
it("matches the endpoint by method, path variables and a context path", () => {
|
||||
const endpoints = [
|
||||
entry("GET", "/api/cockpit/config", "getConfig"),
|
||||
entry("POST", "/api/cockpit/config", "saveConfig"),
|
||||
entry("POST", "/api/orders/{id}/items", "addItem"),
|
||||
entry("GET", "/files/**", "file"),
|
||||
entry("*", "/any", "any"),
|
||||
];
|
||||
const names = (method: string, path: string) => endpointsFor(endpoints, method, path).map((e) => e.methodName);
|
||||
expect(names("GET", "/api/cockpit/config")).toEqual(["getConfig"]);
|
||||
expect(names("POST", "/api/orders/{{id}}/items")).toEqual(["addItem"]);
|
||||
expect(names("POST", "/api/orders/42/items")).toEqual(["addItem"]);
|
||||
expect(names("GET", "/files/a/b.txt")).toEqual(["file"]);
|
||||
expect(names("DELETE", "/any")).toEqual(["any"]);
|
||||
expect(names("GET", "/app/api/cockpit/config")).toEqual(["getConfig"]);
|
||||
expect(names("PUT", "/api/cockpit/config")).toEqual([]);
|
||||
expect(names("GET", "/api/cockpit")).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Navigate › Declaration (⌘-click, ⌘B) on a request URL in a `.http` file: the
|
||||
* handler of the endpoint the request reaches (a Spring mapping, a plugin's
|
||||
* endpoint), matched by method and path.
|
||||
*/
|
||||
import type { Text } from "@codemirror/state";
|
||||
import { docOf } from "@/editor/lsp/lsp";
|
||||
import { registerNavigationProvider, type NavigationMatch } from "@/editor/navigationProviders";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { searchEndpoints, type EndpointEntry } from "@/workbench/contributions";
|
||||
import { HTTP_LANGUAGE } from "./editor";
|
||||
import { METHODS } from "./language";
|
||||
|
||||
/** The request line holding `offset`: its method and the path part of the URL, as document offsets. */
|
||||
export function requestPathAt(
|
||||
doc: Text,
|
||||
offset: number,
|
||||
): { method: string; path: string; from: number; to: number } | null {
|
||||
const line = doc.lineAt(offset);
|
||||
const m = new RegExp(`^(\\s*(?:(${METHODS.join("|")})\\s+)?)(\\S+)`).exec(line.text);
|
||||
if (!m) return null;
|
||||
const url = m[3]!;
|
||||
// The scheme and host, or a `{{host}}` variable standing for them.
|
||||
const origin = /^(?:https?:\/\/[^/\s?#]+|\{\{[^}]+\}\}(?=\/))/.exec(url)?.[0];
|
||||
if (origin === undefined && !(m[2] && url.startsWith("/"))) return null;
|
||||
const start = line.from + m[1]!.length;
|
||||
if (offset < start || offset > start + url.length) return null;
|
||||
const path = url.slice(origin?.length ?? 0).replace(/[?#].*$/, "");
|
||||
// No path (`http://host`): the whole URL is the link.
|
||||
const from = path ? start + (origin?.length ?? 0) : start;
|
||||
return { method: m[2] ?? "GET", path: path || "/", from, to: path ? from + path.length : start + url.length };
|
||||
}
|
||||
|
||||
const segments = (p: string) => p.split("/").filter(Boolean);
|
||||
|
||||
/** How `request` segments match mapping `pattern` segments: `{var}`, `*` and `**` in the mapping, `{{var}}` in the request. */
|
||||
function matches(request: string[], pattern: string[]): boolean {
|
||||
if (!pattern.length) return !request.length;
|
||||
const [p, ...rest] = pattern;
|
||||
if (p === "**") return request.some((_, i) => matches(request.slice(i), rest)) || matches([], rest);
|
||||
if (!request.length) return false;
|
||||
const [r, ...more] = request;
|
||||
const variable = /^\{[^}]*\}$/.test(p!) || p === "*" || /^\{\{[^}]+\}\}$/.test(r!);
|
||||
return (variable || decodeURIComponent(r!) === p) && matches(more, rest);
|
||||
}
|
||||
|
||||
/** Endpoints `method` `path` reaches: the exact path, else after a context path (`/app` + mapping). */
|
||||
export function endpointsFor(endpoints: readonly EndpointEntry[], method: string, path: string): EndpointEntry[] {
|
||||
const request = segments(path);
|
||||
const sameMethod = endpoints.filter((e) => e.method === method || e.method === "*");
|
||||
const exact = sameMethod.filter((e) => matches(request, segments(e.url)));
|
||||
if (exact.length) return exact;
|
||||
for (let skip = 1; skip < request.length; skip++) {
|
||||
const found = sameMethod.filter((e) => matches(request.slice(skip), segments(e.url)));
|
||||
if (found.length) return found;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export async function urlTargets(doc: Text, offset: number): Promise<NavigationMatch | null> {
|
||||
const at = requestPathAt(doc, offset);
|
||||
if (!at) return null;
|
||||
const endpoints = await searchEndpoints(useProject.getState().project?.root ?? null);
|
||||
const found = endpointsFor(endpoints, at.method, at.path);
|
||||
if (!found.length) return null;
|
||||
return {
|
||||
from: at.from,
|
||||
to: at.to,
|
||||
targets: found.map((e) => ({
|
||||
path: e.path,
|
||||
range: { start: { line: e.line, col: e.col }, end: { line: e.line, col: e.col + e.methodName.length } },
|
||||
name: e.handler ?? `${e.controller}.${e.methodName}`,
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
export function registerUrlNavigation(): () => void {
|
||||
return registerNavigationProvider(async (view, offset) => {
|
||||
const doc = docOf(view);
|
||||
if (!doc || doc.virtual || doc.language !== HTTP_LANGUAGE) return null;
|
||||
return urlTargets(view.state.doc, offset);
|
||||
});
|
||||
}
|
||||
@@ -18,8 +18,8 @@ export interface ProjectFs {
|
||||
createFileBytes(path: string, data: Uint8Array): Promise<void>;
|
||||
createDir(path: string): Promise<void>;
|
||||
rename(from: string, to: string): Promise<void>;
|
||||
/** Moves to the trash when possible. */
|
||||
delete(path: string): Promise<void>;
|
||||
/** Moves to the trash when possible and returns a restore function reporting skipped paths. */
|
||||
delete(path: string): Promise<() => Promise<string[]>>;
|
||||
copy(from: string, to: string): Promise<void>;
|
||||
importLocal(from: string, to: string, upload?: LocalImport): Promise<string[]>;
|
||||
}
|
||||
@@ -37,8 +37,9 @@ export const tauriFs: ProjectFs = {
|
||||
createDir: async (path) => void (await call(commands.fsCreateDir(path))),
|
||||
rename: async (from, to) => void (await call(commands.fsRename(from, to))),
|
||||
delete: async (path) => {
|
||||
await call(commands.fsDelete(path));
|
||||
const undo = await call(commands.fsDeleteWithUndo(path));
|
||||
notifyFileOperation({ kind: "deleted", paths: [path] });
|
||||
return () => call(commands.fsUndoDelete(undo));
|
||||
},
|
||||
copy: async (from, to) => {
|
||||
await call(commands.fsCopy(from, to));
|
||||
@@ -238,8 +239,16 @@ export class MemoryFs implements ProjectFs {
|
||||
|
||||
async delete(path: string) {
|
||||
if (!this.nodes.has(path)) throw err("notFound", `${path} not found`);
|
||||
for (const p of [...this.nodes.keys()]) if (p === path || isInside(p, path)) this.nodes.delete(p);
|
||||
const deleted = [...this.nodes].filter(([p]) => p === path || isInside(p, path));
|
||||
for (const [p] of deleted) this.nodes.delete(p);
|
||||
this.emit({ removed: [path] });
|
||||
return async () => {
|
||||
if (this.nodes.has(path)) return [path];
|
||||
this.mkdirp(parentOf(path));
|
||||
for (const [p, node] of deleted) this.nodes.set(p, node);
|
||||
this.emit({ created: deleted.map(([p]) => p) });
|
||||
return [];
|
||||
};
|
||||
}
|
||||
|
||||
async copy(from: string, to: string) {
|
||||
|
||||
@@ -13,7 +13,7 @@ import { osClipboard } from "./clipboard";
|
||||
import { lastFileRefactoring, nextFileOperation, runFileRefactoring, undoFileRefactoring } from "./fileRefactor";
|
||||
import { openFileRefactorDialog, rememberedOptions } from "./FileRefactorDialogs";
|
||||
import { beginLocalImport, projectFs } from "./fs";
|
||||
import { call, commands, IpcError, isCancelled } from "@/platform/ipc";
|
||||
import { IpcError, isCancelled } from "@/platform/ipc";
|
||||
import { MEMBER_PREFIX, type ProjectNode } from "./model";
|
||||
import {
|
||||
isInside,
|
||||
@@ -501,33 +501,31 @@ export async function deleteSelection(nodes: ProjectNode[] = selectedNodes()) {
|
||||
const fs = projectFs(root);
|
||||
const parents = new Set<string>();
|
||||
const errors: string[] = [];
|
||||
const deleted: string[] = [];
|
||||
const deleted: NonNullable<typeof lastDelete>["items"] = [];
|
||||
for (const p of paths) {
|
||||
try {
|
||||
await fs.delete(p);
|
||||
const restore = await fs.delete(p);
|
||||
parents.add(parentOf(p));
|
||||
deleted.push(p);
|
||||
deleted.push({ path: p, restore });
|
||||
} catch (e) {
|
||||
errors.push(`${nameOf(p)}: ${errorMessage(e)}`);
|
||||
}
|
||||
}
|
||||
if (deleted.length) {
|
||||
const dirs = new Set(nodes.filter((n) => n.dir).map((n) => n.path));
|
||||
lastDelete = { paths: deleted, dirs: deleted.filter((p) => dirs.has(p)), seq: nextFileOperation() };
|
||||
}
|
||||
if (deleted.length && get().root === root) lastDelete = { root, items: deleted, seq: nextFileOperation() };
|
||||
if (errors.length)
|
||||
notifications().notify({ level: "error", title: "Some items could not be deleted", body: errors.join("\n") });
|
||||
await Promise.all([...parents].map((d) => loadDir(d, true)));
|
||||
if (next) revealPath(next, refocus);
|
||||
}
|
||||
|
||||
/** The last Delete in the Project view; Undo brings its files back from Local History. */
|
||||
let lastDelete: { paths: string[]; dirs: string[]; seq: number } | null = null;
|
||||
/** The last Delete in the Project view and the exact snapshots from that operation. */
|
||||
let lastDelete: { root: string; items: Array<{ path: string; restore: () => Promise<string[]> }>; seq: number } | null =
|
||||
null;
|
||||
|
||||
/** Undo in the Project view: reverts the latest delete or move / rename; false when there is none. */
|
||||
export function undoLastFileOperation(): boolean {
|
||||
const move = lastFileRefactoring();
|
||||
if (lastDelete && (!move || lastDelete.seq > move.seq)) {
|
||||
if (lastDelete && lastDelete.root === get().root && (!move || lastDelete.seq > move.seq)) {
|
||||
void undoDelete();
|
||||
return true;
|
||||
}
|
||||
@@ -536,43 +534,37 @@ export function undoLastFileOperation(): boolean {
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Restores the deleted files (and folders) from their last Local History snapshots. */
|
||||
/** Restores only entries captured before this Delete. */
|
||||
export async function undoDelete(): Promise<boolean> {
|
||||
const op = lastDelete;
|
||||
const { root } = get();
|
||||
if (!op || !root) return false;
|
||||
if (!op || get().root !== op.root) return false;
|
||||
lastDelete = null;
|
||||
const fs = projectFs(root);
|
||||
const failed: string[] = [];
|
||||
const failed = new Set<string>();
|
||||
const parents = new Set<string>();
|
||||
for (const p of op.paths) {
|
||||
let restored: string | undefined;
|
||||
for (const { path, restore } of op.items) {
|
||||
if (get().root !== op.root) break;
|
||||
try {
|
||||
const history = await call(commands.historyListDir(p));
|
||||
const gone = new Set(history.deleted);
|
||||
const latest = new Map<string, string>();
|
||||
for (const e of history.entries)
|
||||
if (e.kind === "snapshot" && e.id && gone.has(e.path) && !latest.has(e.path)) latest.set(e.path, e.id);
|
||||
const dir = op.dirs.includes(p);
|
||||
if (!latest.size && !dir) throw new Error("no Local History snapshot");
|
||||
if (dir) await fs.createDir(p);
|
||||
for (const [path, id] of latest) await call(commands.historyRestore(path, id));
|
||||
parents.add(parentOf(p));
|
||||
const skipped = await restore();
|
||||
for (const skippedPath of skipped) failed.add(skippedPath);
|
||||
if (!restored && !skipped.includes(path)) restored = path;
|
||||
} catch {
|
||||
failed.push(nameOf(p));
|
||||
failed.add(path);
|
||||
}
|
||||
parents.add(parentOf(path));
|
||||
}
|
||||
if (get().root !== op.root) return false;
|
||||
await Promise.all([...parents].map((d) => loadDir(d, true)));
|
||||
const restored = op.paths.find((p) => !failed.includes(nameOf(p)));
|
||||
if (restored) revealPath(restored, true);
|
||||
const names = failed.join(", ");
|
||||
if (failed.length)
|
||||
const names = [...failed].join("\n");
|
||||
if (failed.size)
|
||||
notifications().notify({
|
||||
level: "warning",
|
||||
title: "Some items could not be restored",
|
||||
body: tx`Not in Local History: ${names}. They are in the Trash.`,
|
||||
body: tx`Check the system Trash for these items. ${names}`,
|
||||
key: "project.undoDelete",
|
||||
});
|
||||
return !failed.length;
|
||||
return !failed.size;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
@@ -1,59 +1,40 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
const history = vi.hoisted(() => ({
|
||||
restored: [] as Array<[string, string]>,
|
||||
snapshots: [] as Array<{ id: string; path: string }>,
|
||||
}));
|
||||
|
||||
vi.mock("@/workbench/messages", () => ({
|
||||
confirm: async () => true,
|
||||
confirmChecked: async () => ({ checked: false }),
|
||||
ask: async () => ({ button: "cancel", checked: false }),
|
||||
}));
|
||||
|
||||
vi.mock("@/editor/refactor", () => ({
|
||||
fileUsages: async () => ({ status: "ok", usages: [] }),
|
||||
askUsagesDetected: async () => "cancel",
|
||||
viewUsages: () => {},
|
||||
}));
|
||||
vi.mock("@/platform/ipc", async (importOriginal) => {
|
||||
const real = await importOriginal<typeof import("@/platform/ipc")>();
|
||||
const ok = <T>(data: T) => Promise.resolve({ status: "ok" as const, data });
|
||||
return {
|
||||
...real,
|
||||
commands: {
|
||||
...real.commands,
|
||||
// Local History as the backend keeps it: deleted files' snapshots, newest first.
|
||||
historyListDir: (dir: string) => {
|
||||
const entries = history.snapshots
|
||||
.filter((s) => s.path === dir || s.path.startsWith(`${dir}/`))
|
||||
.map((s) => ({ ...s, timestampMs: 0, label: "Deleted", size: 1, kind: "snapshot" }));
|
||||
return ok({ entries, deleted: [...new Set(entries.map((e) => e.path))] });
|
||||
},
|
||||
historyRestore: (path: string, id: string) => {
|
||||
history.restored.push([path, id]);
|
||||
return fs.createFile(path).then(() => ok(null));
|
||||
},
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const { MemoryFs, setProjectFsForTests } = await import("./fs");
|
||||
const { currentModel, initProjectTree, loadDir } = await import("./store");
|
||||
const { deleteSelection, undoLastFileOperation } = await import("./operations");
|
||||
let fs: InstanceType<typeof MemoryFs>;
|
||||
|
||||
describe("Undo in the Project view", () => {
|
||||
beforeEach(() => {
|
||||
fs = new MemoryFs({ "/p/a.txt": "a", "/p/lib/x.ts": "x", "/p/lib/empty/": null }, "/p");
|
||||
let fs: InstanceType<typeof MemoryFs>;
|
||||
|
||||
beforeEach(async () => {
|
||||
fs = new MemoryFs(
|
||||
{
|
||||
"/p/lib/current.txt": "current",
|
||||
"/p/lib/obsolete.txt": "obsolete",
|
||||
"/p/lib/empty-child/leaf": null,
|
||||
"/p/a.txt": "a",
|
||||
},
|
||||
"/p",
|
||||
);
|
||||
setProjectFsForTests(fs, "/p");
|
||||
initProjectTree("/p", "proj");
|
||||
history.restored.length = 0;
|
||||
history.snapshots = [
|
||||
{ id: "new-a", path: "/p/a.txt" },
|
||||
{ id: "old-a", path: "/p/a.txt" },
|
||||
{ id: "x1", path: "/p/lib/x.ts" },
|
||||
];
|
||||
await loadDir("/p");
|
||||
await loadDir("/p/lib");
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
setProjectFsForTests(null);
|
||||
initProjectTree(null);
|
||||
@@ -61,19 +42,17 @@ describe("Undo in the Project view", () => {
|
||||
|
||||
const labels = (dir: string) => (currentModel().children.get(dir) ?? []).map((n) => n.label);
|
||||
|
||||
it("brings deleted files and folders back from their latest Local History snapshots", async () => {
|
||||
await loadDir("/p");
|
||||
expect(labels("/p")).toEqual(["lib", "a.txt"]);
|
||||
it("restores a batch exactly as it was before Delete", async () => {
|
||||
await deleteSelection([currentModel().byKey.get("/p/lib/obsolete.txt")!]);
|
||||
expect(fs.nodes.has("/p/lib/obsolete.txt")).toBe(false);
|
||||
await deleteSelection([currentModel().byKey.get("/p/a.txt")!, currentModel().byKey.get("/p/lib")!]);
|
||||
expect(labels("/p")).toEqual([]);
|
||||
|
||||
expect(undoLastFileOperation()).toBe(true);
|
||||
await vi.waitFor(() => expect(labels("/p")).toEqual(["lib", "a.txt"]));
|
||||
expect(history.restored).toEqual([
|
||||
["/p/a.txt", "new-a"],
|
||||
["/p/lib/x.ts", "x1"],
|
||||
]);
|
||||
// Undone once: nothing left to undo.
|
||||
expect(fs.nodes.has("/p/lib/current.txt")).toBe(true);
|
||||
expect(fs.nodes.has("/p/lib/empty-child/leaf")).toBe(true);
|
||||
expect(fs.nodes.has("/p/lib/obsolete.txt")).toBe(false);
|
||||
expect(undoLastFileOperation()).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -132,6 +132,23 @@ describe("recent files switcher", () => {
|
||||
).toEqual(["README.md"]);
|
||||
});
|
||||
|
||||
it("shows a scratch file under its root's label", () => {
|
||||
const labelled = [{ path: "/data/scratches", label: "Scratches" }];
|
||||
const items = filterRecentFiles(
|
||||
["/data/scratches/api/generated-requests.http", "/p/src/Main.kt", "/elsewhere/a.txt"],
|
||||
"",
|
||||
{
|
||||
root: "/p",
|
||||
labelled,
|
||||
},
|
||||
);
|
||||
expect(items.map((f) => [f.rel, f.dir])).toEqual([
|
||||
["Scratches/api/generated-requests.http", "Scratches/api"],
|
||||
["src/Main.kt", "src"],
|
||||
["/elsewhere/a.txt", "/elsewhere"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("preselects the previous file when the current one is first", () => {
|
||||
const items = filterRecentFiles(paths, "", { root: "/p" });
|
||||
expect(initialFileIndex(items, "/p/src/Main.kt", "")).toBe(1);
|
||||
|
||||
@@ -25,6 +25,7 @@ import {
|
||||
maybeEditorService,
|
||||
toolWindowService,
|
||||
useContributions,
|
||||
useProjectViewRoots,
|
||||
useFileDecoration,
|
||||
type OpenEditorTab,
|
||||
type ToolWindowContribution,
|
||||
@@ -91,6 +92,14 @@ function RecentFilesDialog() {
|
||||
const step = useRecentPopup((s) => s.step);
|
||||
const edited = useTracking((s) => s.edited);
|
||||
const root = useProject((s) => s.project?.root ?? null);
|
||||
const viewRoots = useProjectViewRoots((s) => s.roots);
|
||||
const labelled = useMemo(
|
||||
() =>
|
||||
[...viewRoots.values()].flatMap((r) =>
|
||||
r.scope === "scratches" && r.path ? [{ path: r.path, label: r.label }] : [],
|
||||
),
|
||||
[viewRoots],
|
||||
);
|
||||
const toolWindows = useContributions((s) => s.toolWindows);
|
||||
const [paths, setPaths] = useState<string[] | null>(null);
|
||||
// Switcher: the open editor tabs (files and others), when the editor service lists them.
|
||||
@@ -135,13 +144,13 @@ function RecentFilesDialog() {
|
||||
const files = useMemo(
|
||||
() =>
|
||||
tabs
|
||||
? switcherItems(paths ?? [], tabs, query, root).filter((f) => !removed.has(f.path))
|
||||
? switcherItems(paths ?? [], tabs, query, root, labelled).filter((f) => !removed.has(f.path))
|
||||
: filterRecentFiles(
|
||||
(paths ?? []).filter((p) => !removed.has(p)),
|
||||
query,
|
||||
{ root, edited, editedOnly },
|
||||
{ root, labelled, edited, editedOnly },
|
||||
),
|
||||
[paths, tabs, removed, query, root, edited, editedOnly],
|
||||
[paths, tabs, removed, query, root, labelled, edited, editedOnly],
|
||||
);
|
||||
const fileRows = useMemo(() => files.map((f) => ({ ...f, key: f.path })), [files]);
|
||||
const tools = useMemo(() => switcherToolWindows(toolWindows.values(), !!root, query), [toolWindows, root, query]);
|
||||
|
||||
@@ -18,10 +18,27 @@ export interface RecentFileItem {
|
||||
editor?: { input: EditorInput; icon: string };
|
||||
}
|
||||
|
||||
/** A folder outside the project shown by its label (the Scratches root): `Scratches/requests.http`. */
|
||||
export interface LabelledRoot {
|
||||
path: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
function displayPath(path: string, root: string | null, labelled: readonly LabelledRoot[] = []): string {
|
||||
if (root && path.startsWith(root + "/")) return path.slice(root.length + 1);
|
||||
const outside = labelled.find((r) => path.startsWith(r.path + "/"));
|
||||
return outside ? `${outside.label}/${path.slice(outside.path.length + 1)}` : path;
|
||||
}
|
||||
|
||||
export function filterRecentFiles(
|
||||
paths: readonly string[],
|
||||
query: string,
|
||||
opts: { root: string | null; edited?: ReadonlySet<string>; editedOnly?: boolean },
|
||||
opts: {
|
||||
root: string | null;
|
||||
labelled?: readonly LabelledRoot[];
|
||||
edited?: ReadonlySet<string>;
|
||||
editedOnly?: boolean;
|
||||
},
|
||||
): RecentFileItem[] {
|
||||
const out: RecentFileItem[] = [];
|
||||
const seen = new Set<string>();
|
||||
@@ -29,7 +46,7 @@ export function filterRecentFiles(
|
||||
if (seen.has(path)) continue;
|
||||
seen.add(path);
|
||||
if (opts.editedOnly && !opts.edited?.has(path)) continue;
|
||||
const rel = opts.root && path.startsWith(opts.root + "/") ? path.slice(opts.root.length + 1) : path;
|
||||
const rel = displayPath(path, opts.root, opts.labelled);
|
||||
const name = basename(rel);
|
||||
let indices: number[] = [];
|
||||
if (query.trim()) {
|
||||
@@ -70,6 +87,7 @@ export function switcherItems(
|
||||
tabs: readonly OpenEditorTab[],
|
||||
query: string,
|
||||
root: string | null,
|
||||
labelled: readonly LabelledRoot[] = [],
|
||||
): RecentFileItem[] {
|
||||
const fileTabs = new Map(tabs.filter(isFileTab).map((t) => [t.input.path!, t]));
|
||||
const ordered = [
|
||||
@@ -83,7 +101,7 @@ export function switcherItems(
|
||||
const out: RecentFileItem[] = [];
|
||||
for (const t of ordered) {
|
||||
if (isFileTab(t)) {
|
||||
out.push(...filterRecentFiles([t.input.path!], query, { root }));
|
||||
out.push(...filterRecentFiles([t.input.path!], query, { root, labelled }));
|
||||
continue;
|
||||
}
|
||||
let indices: number[] = [];
|
||||
|
||||
@@ -7,6 +7,14 @@
|
||||
white-space: pre;
|
||||
}
|
||||
|
||||
/* xterm places its input textarea and IME composition at the cursor. A program that leaves the
|
||||
cursor in the last column (pi, other TUIs drawing their own cursor) pushes them past the edge,
|
||||
and Chromium (WebView2) then scrolls the clipping pane to keep the caret in view: the whole
|
||||
terminal slides sideways while composing. `clip` keeps that overflow out of every ancestor. */
|
||||
.xterm {
|
||||
overflow: clip;
|
||||
}
|
||||
|
||||
/* An icon or fallback symbol wider than its cell stays over the next cell's background
|
||||
(domRowCache), while selected spans keep xterm's `.xterm-decoration-top` z-index (2). */
|
||||
.xterm .xterm-rows .openidea-terminal-icon:not(.xterm-decoration-top) {
|
||||
|
||||
@@ -252,7 +252,7 @@
|
||||
background: var(--bg-app);
|
||||
border-left: 1px solid var(--border);
|
||||
border-right: 1px solid var(--border);
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
touch-action: none;
|
||||
}
|
||||
.host :global(.cm-diffDivider:hover) {
|
||||
|
||||
@@ -53,7 +53,7 @@ import {
|
||||
languageFor,
|
||||
viewerBase,
|
||||
} from "./cm";
|
||||
import { applyChunk, arrowControls, chunkAt, hoverRevert, revertUnifiedChunk } from "./diffControls";
|
||||
import { applyChunk, arrowControls, chunkAt, hoverRevert, onHunkButtonClick, revertUnifiedChunk } from "./diffControls";
|
||||
import {
|
||||
HIGHLIGHT_OPTIONS,
|
||||
IGNORE_OPTIONS,
|
||||
@@ -681,16 +681,14 @@ export function DiffEditor({
|
||||
mergeControls: editableB
|
||||
? (type) => {
|
||||
const btn = document.createElement("button");
|
||||
btn.type = "button";
|
||||
if (type === "accept") {
|
||||
btn.hidden = true;
|
||||
return btn;
|
||||
}
|
||||
btn.textContent = "Revert";
|
||||
btn.title = "Revert this change";
|
||||
btn.onmousedown = (event) => {
|
||||
event.preventDefault();
|
||||
revertUnifiedChunk(view, view.posAtDOM(btn));
|
||||
};
|
||||
onHunkButtonClick(btn, () => revertUnifiedChunk(view, view.posAtDOM(btn)));
|
||||
return btn;
|
||||
}
|
||||
: false,
|
||||
|
||||
@@ -234,7 +234,7 @@
|
||||
overflow:hidden, so any rule drawn into the 8px gap would be clipped away. */
|
||||
inset-inline-start: -4px;
|
||||
width: 8px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
touch-action: none;
|
||||
z-index: 1;
|
||||
display: flex;
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { describe, expect, it, vi } from "vitest";
|
||||
import userEvent from "@testing-library/user-event";
|
||||
import { Chunk, MergeView, unifiedMergeView } from "@codemirror/merge";
|
||||
import { ChangeSet, Text } from "@codemirror/state";
|
||||
import { EditorView } from "@codemirror/view";
|
||||
import { applyChunk, arrowControls } from "../diffControls";
|
||||
import { applyChunk, arrowControls, hoverRevert } from "../diffControls";
|
||||
import {
|
||||
DEFAULT_DIFF_OPTIONS,
|
||||
parseDiffOptions,
|
||||
@@ -418,7 +419,12 @@ describe("diff options", () => {
|
||||
expect(a.replace(toA.from, toA.to, Text.of(toA.insert.split("\n"))).toString()).toBe("x\nnew\nnewer\ny\n");
|
||||
});
|
||||
|
||||
it("applies chunks in a merge view through the arrow controls", () => {
|
||||
it.each([
|
||||
["a-to-b", "right", "{Enter}"],
|
||||
["b-to-a", "left", " "],
|
||||
["a-to-b", "right", "click"],
|
||||
["b-to-a", "left", "click"],
|
||||
] as const)("applies a chunk %s to the %s (%j)", async (direction, side, activation) => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
let mv: MergeView | null = null;
|
||||
@@ -429,21 +435,53 @@ describe("diff options", () => {
|
||||
revertControls: "a-to-b",
|
||||
renderRevertControl: arrowControls(() => mv, { toA: true, toB: true }),
|
||||
});
|
||||
const holder = arrowControls(() => mv, { toA: true, toB: true })();
|
||||
expect([...holder.querySelectorAll("button")].map((b) => b.getAttribute("aria-label"))).toEqual([
|
||||
expect.stringContaining("right"),
|
||||
expect.stringContaining("left"),
|
||||
]);
|
||||
// "<<": the right side's text replaces the left chunk.
|
||||
holder.dataset.chunk = "0";
|
||||
holder.querySelectorAll("button")[1]!.dispatchEvent(new MouseEvent("mousedown", { bubbles: true }));
|
||||
expect(mv.a.state.doc.toString()).toBe("1\nright\n3\n");
|
||||
expect(mv.chunks).toHaveLength(0);
|
||||
mv.a.dispatch({ changes: { from: 2, to: 7, insert: "LEFT" } });
|
||||
applyChunk(mv, 0, "a");
|
||||
expect(mv.b.state.doc.toString()).toBe("1\nLEFT\n3\n");
|
||||
mv.destroy();
|
||||
parent.remove();
|
||||
try {
|
||||
const arrow = await vi.waitFor(() => {
|
||||
const button = parent.querySelector<HTMLButtonElement>(`.cm-diffArrow-${direction}`);
|
||||
expect(button).not.toBeNull();
|
||||
return button!;
|
||||
});
|
||||
expect(arrow.getAttribute("aria-label")).toContain(side);
|
||||
const user = userEvent.setup();
|
||||
if (activation === "click") {
|
||||
mv.b.focus();
|
||||
await user.click(arrow);
|
||||
expect(document.activeElement).toBe(mv.b.contentDOM);
|
||||
} else {
|
||||
arrow.focus();
|
||||
await user.keyboard(activation);
|
||||
}
|
||||
|
||||
const expected = direction === "a-to-b" ? "1\nleft\n3\n" : "1\nright\n3\n";
|
||||
expect(mv.a.state.doc.toString()).toBe(expected);
|
||||
expect(mv.b.state.doc.toString()).toBe(expected);
|
||||
expect(mv.chunks).toHaveLength(0);
|
||||
} finally {
|
||||
mv.destroy();
|
||||
parent.remove();
|
||||
}
|
||||
});
|
||||
|
||||
it("reverts a hovered chunk when its button is activated by the keyboard", async () => {
|
||||
const parent = document.createElement("div");
|
||||
document.body.appendChild(parent);
|
||||
const diff = new MergeView({
|
||||
a: { doc: "1\nleft\n3\n" },
|
||||
b: { doc: "1\nright\n3\n", extensions: hoverRevert((_view, index) => applyChunk(diff, index, "a")) },
|
||||
parent,
|
||||
});
|
||||
try {
|
||||
vi.spyOn(diff.b, "posAtCoords").mockReturnValue(2);
|
||||
diff.b.contentDOM.dispatchEvent(new MouseEvent("mousemove", { bubbles: true }));
|
||||
const button = parent.querySelector<HTMLButtonElement>(".cm-diffHoverRevert");
|
||||
expect(button).not.toBeNull();
|
||||
button!.focus();
|
||||
await userEvent.setup().keyboard("{Enter}");
|
||||
expect(diff.b.state.doc.toString()).toBe("1\nleft\n3\n");
|
||||
} finally {
|
||||
diff.destroy();
|
||||
parent.remove();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -712,7 +712,7 @@ describe("Unified Revert", () => {
|
||||
await waitFor(() => expect(button).not.toBeDisabled());
|
||||
fireEvent.click(button);
|
||||
} else {
|
||||
fireEvent.mouseDown(await screen.findByRole("button", { name: /^Revert$/ }));
|
||||
fireEvent.click(await screen.findByRole("button", { name: /^Revert$/ }));
|
||||
}
|
||||
await waitFor(() => expect(view.state.doc.toString()).toBe(original));
|
||||
} finally {
|
||||
|
||||
@@ -27,6 +27,18 @@ export function revertUnifiedChunk(view: EditorView, pos: number) {
|
||||
});
|
||||
}
|
||||
|
||||
export function onHunkButtonClick(button: HTMLButtonElement, apply: () => void) {
|
||||
button.addEventListener("mousedown", (event) => {
|
||||
// Keep editor focus and suppress MergeView's delegated one-directional revert.
|
||||
event.preventDefault();
|
||||
event.stopPropagation();
|
||||
});
|
||||
button.addEventListener("click", (event) => {
|
||||
event.stopPropagation();
|
||||
apply();
|
||||
});
|
||||
}
|
||||
|
||||
/** A ">>" / "<<" button; the chunk index comes from the nearest `data-chunk` (itself included). */
|
||||
export function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number) => void): HTMLButtonElement {
|
||||
const btn = document.createElement("button");
|
||||
@@ -36,11 +48,8 @@ export function arrowButton(dir: "a-to-b" | "b-to-a", run: (chunkIndex: number)
|
||||
btn.setAttribute("aria-label", label);
|
||||
btn.title = label;
|
||||
btn.innerHTML = iconMarkup(dir === "a-to-b" ? "diff-arrow-right" : "diff-arrow-left", 14) ?? "";
|
||||
btn.addEventListener("mousedown", (e) => {
|
||||
// Handled here rather than by MergeView's own (one-directional) revert handler.
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
const holder = (e.currentTarget as HTMLElement).closest<HTMLElement>("[data-chunk]");
|
||||
onHunkButtonClick(btn, () => {
|
||||
const holder = btn.closest<HTMLElement>("[data-chunk]");
|
||||
const index = Number(holder?.dataset.chunk);
|
||||
if (Number.isInteger(index)) run(index);
|
||||
});
|
||||
@@ -83,11 +92,7 @@ class RevertWidget extends WidgetType {
|
||||
btn.title = "Revert this change";
|
||||
btn.setAttribute("aria-label", "Revert this change");
|
||||
btn.innerHTML = `${iconMarkup("revert", 12) ?? ""}<span>Revert</span>`;
|
||||
btn.addEventListener("mousedown", (e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
this.onRevert(view, this.index);
|
||||
});
|
||||
onHunkButtonClick(btn, () => this.onRevert(view, this.index));
|
||||
return btn;
|
||||
}
|
||||
ignoreEvent() {
|
||||
|
||||
@@ -120,7 +120,7 @@ export function useColumnResize(target: ResizeTarget) {
|
||||
x: e.clientX,
|
||||
element: e.currentTarget,
|
||||
pointerId: e.pointerId,
|
||||
releaseCursor: lockDragCursor("ew-resize"),
|
||||
releaseCursor: lockDragCursor("col-resize"),
|
||||
};
|
||||
listeners.current = { blur, escape };
|
||||
e.currentTarget.setPointerCapture?.(e.pointerId);
|
||||
|
||||
@@ -352,7 +352,7 @@ const theme = EditorView.baseTheme({
|
||||
height: "4px",
|
||||
borderRadius: "2px",
|
||||
background: "var(--focus-ring, #3574f0)",
|
||||
cursor: "ns-resize",
|
||||
cursor: "row-resize",
|
||||
},
|
||||
".cm-reviewHandle[data-disabled]": { opacity: "0.4", cursor: "default" },
|
||||
".cm-reviewHandle-start": { top: "-2px" },
|
||||
|
||||
@@ -2501,5 +2501,6 @@
|
||||
"Cannot load Gradle configurations": "Cannot load Gradle configurations",
|
||||
"No resolvable Gradle configurations": "No resolvable Gradle configurations",
|
||||
"Restore Tool Windows": "Restore Tool Windows",
|
||||
"Configure {name}…": "Configure {name}…"
|
||||
"Configure {name}…": "Configure {name}…",
|
||||
"Check the system Trash for these items. {names}": "Check the system Trash for these items. {names}"
|
||||
}
|
||||
@@ -5848,7 +5848,6 @@
|
||||
"Syntax errors": "Errores de sintaxis",
|
||||
"Reports code the built-in parser cannot read, in files no language server checks (none is configured for the language, or it is not installed, stopped or crashed). A running language server reports syntax errors itself.": "Informa el código que el analizador integrado no puede leer, en archivos que ningún servidor de lenguaje verifica (no hay ninguno configurado para el lenguaje, o no está instalado, se detuvo o falló). Un servidor de lenguaje en ejecución informa los errores de sintaxis por sí mismo.",
|
||||
"Some items could not be restored": "Algunos elementos no se pudieron restaurar",
|
||||
"Not in Local History: {names}. They are in the Trash.": "No están en el historial local: {names}. Están en la Papelera.",
|
||||
"Show All Commits": "Mostrar todas las confirmaciones",
|
||||
"Pin": "Fijar",
|
||||
"Unpin": "Desfijar",
|
||||
|
||||
@@ -5547,7 +5547,6 @@
|
||||
"Editor and {title}": "Éditeur et {title}",
|
||||
"{title} Only": "{title} seul",
|
||||
"Some items could not be restored": "Certains éléments n'ont pas pu être restaurés",
|
||||
"Not in Local History: {names}. They are in the Trash.": "Absents de l'historique local : {names}. Ils se trouvent dans la corbeille.",
|
||||
"Browse for .env Files": "Rechercher des fichiers .env",
|
||||
"Django tests": "Tests Django",
|
||||
"Run Django tests with manage.py test": "Exécuter les tests Django avec manage.py test",
|
||||
|
||||
@@ -5916,7 +5916,6 @@
|
||||
"Syntax errors": "구문 오류",
|
||||
"Reports code the built-in parser cannot read, in files no language server checks (none is configured for the language, or it is not installed, stopped or crashed). A running language server reports syntax errors itself.": "언어 서버가 검사하지 않는 파일(해당 언어에 구성된 언어 서버가 없거나, 설치되지 않았거나, 중지되었거나, 충돌한 경우)에서 기본 제공 파서가 읽을 수 없는 코드를 보고합니다. 실행 중인 언어 서버는 구문 오류를 직접 보고합니다.",
|
||||
"Some items could not be restored": "일부 항목을 복원할 수 없습니다",
|
||||
"Not in Local History: {names}. They are in the Trash.": "로컬 기록에 없음: {names}. 해당 항목은 휴지통에 있습니다.",
|
||||
"Show All Commits": "모든 커밋 표시",
|
||||
"Pin": "고정",
|
||||
"Unpin": "고정 해제",
|
||||
|
||||
@@ -5759,7 +5759,6 @@
|
||||
"Syntax errors": "Błędy składni",
|
||||
"Reports code the built-in parser cannot read, in files no language server checks (none is configured for the language, or it is not installed, stopped or crashed). A running language server reports syntax errors itself.": "Zgłasza kod, którego wbudowany parser nie jest w stanie odczytać, w plikach niekontrolowanych przez żaden serwer językowy (brak skonfigurowanego serwera, serwer niezainstalowany, zatrzymany lub uległ awarii). Uruchomiony serwer językowy sam zgłasza błędy składniowe.",
|
||||
"Some items could not be restored": "Niektórych elementów nie udało się przywrócić",
|
||||
"Not in Local History: {names}. They are in the Trash.": "Brak w historii lokalnej: {names}. Znajdują się w Koszu.",
|
||||
"Show All Commits": "Pokaż wszystkie zatwierdzenia",
|
||||
"Pin": "Przypnij",
|
||||
"Unpin": "Odepnij",
|
||||
|
||||
@@ -5773,7 +5773,6 @@
|
||||
"Syntax errors": "Erros de sintaxe",
|
||||
"Reports code the built-in parser cannot read, in files no language server checks (none is configured for the language, or it is not installed, stopped or crashed). A running language server reports syntax errors itself.": "Relata código que o analisador integrado não consegue ler, em arquivos que nenhum servidor de linguagem verifica (nenhum está configurado para a linguagem, ou não está instalado, foi parado ou falhou). Um servidor de linguagem em execução relata erros de sintaxe por conta própria.",
|
||||
"Some items could not be restored": "Alguns itens não puderam ser restaurados",
|
||||
"Not in Local History: {names}. They are in the Trash.": "Não estão no histórico local: {names}. Eles estão na Lixeira.",
|
||||
"Show All Commits": "Mostrar todos os commits",
|
||||
"Pin": "Fixar",
|
||||
"Unpin": "Desafixar",
|
||||
|
||||
@@ -6685,7 +6685,7 @@
|
||||
"Syntax errors": "语法错误",
|
||||
"Reports code the built-in parser cannot read, in files no language server checks (none is configured for the language, or it is not installed, stopped or crashed). A running language server reports syntax errors itself.": "报告内置解析器无法解析的代码,仅针对没有语言服务器检查的文件(该语言未配置语言服务器,或未安装、已停止、已崩溃)。语言服务器运行时由它自己报告语法错误。",
|
||||
"Some items could not be restored": "部分项目无法恢复",
|
||||
"Not in Local History: {names}. They are in the Trash.": "本地历史中没有:{names}。它们在回收站中。",
|
||||
"Check the system Trash for these items. {names}": "请在系统回收站中查看这些项目。{names}",
|
||||
"Show All Commits": "显示所有提交",
|
||||
"Pin": "固定",
|
||||
"Unpin": "取消固定",
|
||||
|
||||
@@ -16,13 +16,14 @@
|
||||
outline: none;
|
||||
transition: background var(--dur) var(--ease);
|
||||
}
|
||||
/* Dividers use col-/row-resize: WebKit on macOS 26.2 shows the arrow for ew-/ns-resize. */
|
||||
.handle[aria-orientation="vertical"] {
|
||||
width: 1px;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.handle[aria-orientation="horizontal"] {
|
||||
height: 1px;
|
||||
cursor: ns-resize;
|
||||
cursor: row-resize;
|
||||
}
|
||||
.handle::after {
|
||||
content: "";
|
||||
|
||||
@@ -10,9 +10,9 @@ afterEach(() => {
|
||||
|
||||
describe("lockDragCursor", () => {
|
||||
it("holds the cursor until the drag ends", () => {
|
||||
const release = lockDragCursor("ew-resize");
|
||||
const release = lockDragCursor("col-resize");
|
||||
expect(html.getAttribute("data-drag-cursor")).toBe("");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("ew-resize");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("col-resize");
|
||||
|
||||
release();
|
||||
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
|
||||
@@ -20,27 +20,27 @@ describe("lockDragCursor", () => {
|
||||
});
|
||||
|
||||
it("ignores a repeated release", () => {
|
||||
const release = lockDragCursor("ns-resize");
|
||||
const release = lockDragCursor("row-resize");
|
||||
release();
|
||||
release();
|
||||
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
|
||||
});
|
||||
|
||||
it("restores an outer drag after a nested one ends", () => {
|
||||
const outer = lockDragCursor("ew-resize");
|
||||
const outer = lockDragCursor("col-resize");
|
||||
const inner = lockDragCursor("nwse-resize");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("nwse-resize");
|
||||
|
||||
inner();
|
||||
expect(html.getAttribute("data-drag-cursor")).toBe("");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("ew-resize");
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("col-resize");
|
||||
|
||||
outer();
|
||||
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
|
||||
});
|
||||
|
||||
it("releases when the pointer goes up outside the handle", () => {
|
||||
lockDragCursor("ew-resize");
|
||||
lockDragCursor("col-resize");
|
||||
document.dispatchEvent(new Event("pointerup", { bubbles: true }));
|
||||
expect(html.hasAttribute("data-drag-cursor")).toBe(false);
|
||||
expect(html.style.getPropertyValue("--drag-cursor")).toBe("");
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* default one mid-drag. `global.css` keys off `data-drag-cursor` instead and
|
||||
* wins over those cursors with `!important`.
|
||||
*/
|
||||
export type DragCursor = "ew-resize" | "ns-resize" | "nwse-resize";
|
||||
export type DragCursor = "col-resize" | "row-resize" | "ew-resize" | "ns-resize" | "nwse-resize";
|
||||
|
||||
const active = new Set<() => void>();
|
||||
let listening = false;
|
||||
|
||||
@@ -2,7 +2,7 @@ import { act, fireEvent, render, screen, within } from "@testing-library/react";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { commands, type Settings } from "@/platform/ipc";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { registerActions } from "@/platform/actions";
|
||||
import { getAction, registerActions } from "@/platform/actions";
|
||||
import { usePlatform } from "@/platform/platformInfo";
|
||||
import { MainMenu } from "./MainMenu";
|
||||
|
||||
@@ -60,6 +60,45 @@ afterEach(() => {
|
||||
|
||||
const titles = () => within(screen.getByRole("menubar"));
|
||||
|
||||
describe("main menu action focus", () => {
|
||||
it.each([
|
||||
{ style: "hamburger", narrow: false, row: false },
|
||||
{ style: "merged", narrow: false, row: false },
|
||||
{ style: "merged", narrow: true, row: false },
|
||||
{ style: "toolbar", narrow: false, row: true },
|
||||
])("restores the invoking field before Undo runs ($style, narrow=$narrow)", async ({ style, narrow, row }) => {
|
||||
if (narrow) available = 100;
|
||||
setStyle(style);
|
||||
const focusAtUndo = vi.fn(() => document.activeElement);
|
||||
vi.mocked(getAction("test.undo")!.run).mockImplementation(() => {
|
||||
focusAtUndo();
|
||||
});
|
||||
render(
|
||||
<>
|
||||
<input aria-label="Editor field" />
|
||||
<MainMenu row={row} />
|
||||
</>,
|
||||
);
|
||||
const field = screen.getByRole("textbox", { name: "Editor field" });
|
||||
field.focus();
|
||||
const open = (button: HTMLElement) => {
|
||||
fireEvent.pointerDown(button);
|
||||
button.focus();
|
||||
fireEvent.click(button);
|
||||
};
|
||||
if (style === "hamburger" || narrow) open(screen.getByRole("button", { name: "Main Menu" }));
|
||||
if (narrow) {
|
||||
const root = await screen.findByRole("menu", { name: "Main Menu" });
|
||||
fireEvent.click(within(root).getByRole("menuitem", { name: /Edit/ }));
|
||||
} else open(within(await screen.findByRole("menubar")).getByRole("menuitem", { name: "Edit" }));
|
||||
const undo = await screen.findByRole("menuitem", { name: "Undo" });
|
||||
expect(undo).toHaveFocus();
|
||||
fireEvent.click(undo);
|
||||
expect(focusAtUndo).toHaveReturnedWith(field);
|
||||
expect(field).toHaveFocus();
|
||||
});
|
||||
});
|
||||
|
||||
describe("main menu presentation", () => {
|
||||
it("keeps the hamburger default, expanding on click and collapsing on Escape", async () => {
|
||||
const expanded = vi.fn();
|
||||
|
||||
@@ -108,6 +108,17 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
|
||||
const persistent = (merged && fits) || row;
|
||||
const showTitles = persistent || (!merged && expanded);
|
||||
|
||||
const rememberFocus = (target: EventTarget | null) => {
|
||||
if (
|
||||
target instanceof HTMLElement &&
|
||||
target !== document.body &&
|
||||
target !== hamburger.current &&
|
||||
!bar?.contains(target) &&
|
||||
!target.closest('[role="menu"]')
|
||||
)
|
||||
previousFocus.current = target;
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
let disposed = false;
|
||||
if (merged || row)
|
||||
@@ -155,6 +166,13 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
|
||||
setOpen(null);
|
||||
setExpanded(false);
|
||||
};
|
||||
// MenuList runs the action synchronously after onDone, before Popup unmounts.
|
||||
const closeForAction = () => {
|
||||
const target = previousFocus.current;
|
||||
previousFocus.current = null;
|
||||
close();
|
||||
if (target?.isConnected) target.focus({ preventScroll: true });
|
||||
};
|
||||
const expand = async () => {
|
||||
const top = await loadMenus();
|
||||
if (!top.length) return;
|
||||
@@ -188,10 +206,13 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
|
||||
} else if (persistent) {
|
||||
if (bar?.contains(document.activeElement)) previousFocus.current?.focus();
|
||||
else {
|
||||
previousFocus.current = document.activeElement as HTMLElement;
|
||||
rememberFocus(document.activeElement);
|
||||
focusTitle(0);
|
||||
}
|
||||
} else void expand();
|
||||
} else {
|
||||
rememberFocus(document.activeElement);
|
||||
void expand();
|
||||
}
|
||||
});
|
||||
});
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
@@ -219,9 +240,13 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
|
||||
title={t("menu.mainMenu")}
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={expanded}
|
||||
onFocus={(event) => rememberFocus(event.relatedTarget)}
|
||||
onClick={() => {
|
||||
if (expanded) close();
|
||||
else void expand();
|
||||
else {
|
||||
rememberFocus(document.activeElement);
|
||||
void expand();
|
||||
}
|
||||
}}
|
||||
>
|
||||
<Icon name="main-menu" size={20} />
|
||||
@@ -238,7 +263,10 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
|
||||
aria-haspopup="menu"
|
||||
aria-expanded={open === i}
|
||||
className={clsx(styles.menuTitle, open === i && styles.menuTitleOpen)}
|
||||
onFocus={() => setFocused(i)}
|
||||
onFocus={(event) => {
|
||||
rememberFocus(event.relatedTarget);
|
||||
setFocused(i);
|
||||
}}
|
||||
onPointerDown={() => {
|
||||
pressedTitle.current = true;
|
||||
setTimeout(() => {
|
||||
@@ -252,6 +280,7 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
|
||||
if (open !== null) setOpen(i);
|
||||
}}
|
||||
onClick={() => {
|
||||
rememberFocus(document.activeElement);
|
||||
if (open === i) close();
|
||||
else setOpen(i);
|
||||
}}
|
||||
@@ -274,7 +303,7 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
|
||||
>
|
||||
<MenuList
|
||||
items={menuItems(menus[open].children)}
|
||||
onDone={close}
|
||||
onDone={closeForAction}
|
||||
aria-label={label(menus[open].id, menus[open].label)}
|
||||
/>
|
||||
</Popup>
|
||||
@@ -302,7 +331,7 @@ function MainMenuBar({ merged, row, onExpandedChange }: MainMenuProps & { merged
|
||||
autoFocus={false}
|
||||
className={menuStyles.popup}
|
||||
>
|
||||
<MenuList items={menuItems(menus)} onDone={close} aria-label={t("menu.mainMenu")} />
|
||||
<MenuList items={menuItems(menus)} onDone={closeForAction} aria-label={t("menu.mainMenu")} />
|
||||
</Popup>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
flex: none;
|
||||
align-items: center;
|
||||
position: relative;
|
||||
padding: 0 var(--window-tabs-right, 40px) var(--space-0-5) var(--window-tabs-left, 40px);
|
||||
padding: 0 var(--window-tabs-right, 40px) var(--island-gap) var(--window-tabs-left, 40px);
|
||||
min-width: 0;
|
||||
}
|
||||
.tabs {
|
||||
|
||||
@@ -179,17 +179,17 @@
|
||||
.undocked[data-slot^="left"] > .undockEdge {
|
||||
inset: 0 0 0 auto;
|
||||
width: var(--island-gap);
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.undocked[data-slot^="right"] > .undockEdge {
|
||||
inset: 0 auto 0 0;
|
||||
width: var(--island-gap);
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.undocked[data-slot^="bottom"] > .undockEdge {
|
||||
inset: 0 0 auto;
|
||||
height: var(--island-gap);
|
||||
cursor: ns-resize;
|
||||
cursor: row-resize;
|
||||
}
|
||||
.undockEdge:focus-visible {
|
||||
background: color-mix(in srgb, var(--accent) 45%, transparent);
|
||||
@@ -210,10 +210,10 @@
|
||||
grid-area: gap-bottom;
|
||||
}
|
||||
.gap[aria-orientation="vertical"] {
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.gap[aria-orientation="horizontal"] {
|
||||
cursor: ns-resize;
|
||||
cursor: row-resize;
|
||||
}
|
||||
/* A slightly wider hit area than the gap itself. */
|
||||
.gap::before {
|
||||
@@ -286,7 +286,7 @@
|
||||
flex: none;
|
||||
width: 0;
|
||||
outline: none;
|
||||
cursor: ew-resize;
|
||||
cursor: col-resize;
|
||||
}
|
||||
.stripeHandle::before {
|
||||
content: "";
|
||||
|
||||
@@ -269,7 +269,7 @@ function StripeHandle({
|
||||
const origin = e.clientX;
|
||||
const icons = parseFloat(getComputedStyle(stripe).getPropertyValue("--stripe-icon-button")) || 30;
|
||||
const start = names ? width : icons;
|
||||
const releaseCursor = lockDragCursor("ew-resize");
|
||||
const releaseCursor = lockDragCursor("col-resize");
|
||||
let next = { names, width, px: start };
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
@@ -945,7 +945,7 @@ function SplitHandle({ anchor, hidden }: { anchor: ToolWindowAnchor; hidden: boo
|
||||
e.preventDefault();
|
||||
el.setPointerCapture(e.pointerId);
|
||||
const origin = stacked ? e.clientY : e.clientX;
|
||||
const releaseCursor = lockDragCursor(stacked ? "ns-resize" : "ew-resize");
|
||||
const releaseCursor = lockDragCursor(stacked ? "row-resize" : "col-resize");
|
||||
let ratio: number | null = null;
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
@@ -1018,7 +1018,7 @@ function UndockEdge({ anchor }: { anchor: ToolWindowAnchor }) {
|
||||
e.preventDefault();
|
||||
el.setPointerCapture(e.pointerId);
|
||||
const origin = vertical ? e.clientX : e.clientY;
|
||||
const releaseCursor = lockDragCursor(vertical ? "ew-resize" : "ns-resize");
|
||||
const releaseCursor = lockDragCursor(vertical ? "col-resize" : "row-resize");
|
||||
let next = m.size;
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
@@ -1201,7 +1201,7 @@ function GapHandle({
|
||||
const el = e.currentTarget;
|
||||
el.setPointerCapture(e.pointerId);
|
||||
const origin = vertical ? e.clientX : e.clientY;
|
||||
const releaseCursor = lockDragCursor(vertical ? "ew-resize" : "ns-resize");
|
||||
const releaseCursor = lockDragCursor(vertical ? "col-resize" : "row-resize");
|
||||
let next = m.size;
|
||||
const move = (ev: globalThis.PointerEvent) => {
|
||||
if (!(ev.buttons & 1)) return end();
|
||||
|
||||
Reference in new issue
Block a user