Порівняти коміти

..
Автор SHA1 Повідомлення Дата
l0ng-ai 2d1057538b chore: refresh PR head 2026-11-06 00:08:16 +08:00
l0ng-ai df67920512 Merge main 2026-11-06 00:01:25 +08:00
l0ng-ai 2780259998 feat(database): submit and revert table edits from the keyboard
The table editor's Submit and Revert were toolbar buttons only, with no
shortcut, no Keymap entry and nothing in Find Action. They are now the
db.submitChanges and db.revertChanges actions, enabled while a table
editor has focus and pending edits, bound to ⌘↩ / Ctrl+Enter and
⌥⌘Z / Ctrl+Alt+Z in the IntelliJ keymaps (unbound in Eclipse, where
⌥⌘Z is Surround With). They don't take focus from a text field, so ⌘↩
still applies the edit in the Value panel and the large-value dialog,
and still runs Execute in query consoles.
2026-11-06 00:00:15 +08:00
33 змінених файлів з 69 додано та 576 видалено

No files matched your search

Створено
-1
Переглянути файл
@@ -4121,7 +4121,6 @@ dependencies = [
name = "ide-build"
version = "0.1.37"
dependencies = [
"blake3",
"dirs 6.0.0",
"dunce",
"ide-core",
-1
Переглянути файл
@@ -6,7 +6,6 @@ edition.workspace = true
license.workspace = true
[dependencies]
blake3.workspace = true
dunce.workspace = true
ide-core.workspace = true
zip.workspace = true
+6 -57
Переглянути файл
@@ -2,49 +2,18 @@
use super::*;
use std::fs;
use std::hash::{Hash, Hasher};
use std::io::Read;
use std::time::SystemTime;
/// `(byte length, mtime, blake3 hex)`; the hash is recorded for files inside the project only.
type Stamp = (u64, SystemTime, Option<String>);
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct LaunchFingerprint {
version: u32,
parameters: String,
/// Per input: a [`Stamp`] for regular files, `None` for
/// directories and inputs that cannot be resolved. The content hash catches external
/// edits that preserve both length and mtime (timestamp-preserving tools, coarse
/// timestamp granularity), which `(length, mtime)` alone would miss. Only files inside
/// the project are hashed; toolchain inputs such as the JDK's `lib/modules` keep the stamp.
files: BTreeMap<PathBuf, Option<Stamp>>,
}
/// `blake3` hex of a file's bytes, streamed in chunks so memory stays bounded. An
/// unreadable file records a sentinel so one permission problem does not drop the whole
/// fingerprint (that would just force a normal rebuild).
fn content_hash(path: &Path) -> IdeResult<String> {
let mut file = match fs::File::open(path) {
Ok(file) => file,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok("missing".into()),
Err(e) => return Err(e.into()),
};
let mut hasher = blake3::Hasher::new();
let mut buffer = [0; 64 * 1024];
loop {
let count = file.read(&mut buffer)?;
if count == 0 {
break;
}
hasher.update(&buffer[..count]);
}
Ok(hasher.finalize().to_hex().to_string())
files: BTreeMap<PathBuf, Option<(u64, SystemTime)>>,
}
fn scan(
root: &Path,
path: &Path,
files: &mut BTreeMap<PathBuf, Option<Stamp>>,
files: &mut BTreeMap<PathBuf, Option<(u64, SystemTime)>>,
ancestors: &mut HashSet<PathBuf>,
cancel: &CancellationToken,
) -> IdeResult<()> {
@@ -67,12 +36,11 @@ fn scan(
// Directory mtimes change on irrelevant JDT writes. File paths detect additions/deletions.
files.insert(path.to_path_buf(), None);
for entry in fs::read_dir(path)? {
scan(root, &entry?.path(), files, ancestors, cancel)?;
scan(&entry?.path(), files, ancestors, cancel)?;
}
ancestors.remove(&canonical);
} else if meta.is_file() {
let hash = if path.starts_with(root) { Some(content_hash(path)?) } else { None };
files.insert(path.to_path_buf(), Some((meta.len(), meta.modified()?, hash)));
files.insert(path.to_path_buf(), Some((meta.len(), meta.modified()?)));
} else {
return Err(IdeError::internal("unsupported launch input file"));
}
@@ -177,11 +145,11 @@ pub fn launch_fingerprint(
.map_err(|e| IdeError::internal(e.to_string()))?;
let mut files = BTreeMap::new();
for path in inputs {
scan(root, &path, &mut files, &mut HashSet::new(), cancel)?;
scan(&path, &mut files, &mut HashSet::new(), cancel)?;
}
// Store project inputs relative to the project, including each file's relative path.
let files = files.into_iter().map(|(p, stamp)| (p.strip_prefix(root).unwrap_or(&p).to_path_buf(), stamp)).collect();
Ok(Some(LaunchFingerprint { version: 2, parameters, files }))
Ok(Some(LaunchFingerprint { version: 1, parameters, files }))
}
#[cfg(test)]
@@ -263,25 +231,6 @@ mod tests {
}
}
/// An external tool that keeps the byte length and the mtime (timestamp-preserving
/// writes, coarse-granularity filesystems) still changes the content: the fingerprint
/// must differ via the content hash, not via `(length, mtime)`.
#[test]
fn external_edit_preserving_length_and_mtime_still_invalidates() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let source = root.join("lib/src/main/kotlin/Channel.kt");
let before = fingerprint(root, &model);
assert!(before.is_some());
let mtime = fs::metadata(&source).unwrap().modified().unwrap();
// Same 5-byte length, different content.
write(root, "lib/src/main/kotlin/Channel.kt", "valve");
fs::File::options().write(true).open(&source).unwrap().set_modified(mtime).unwrap();
let after = fingerprint(root, &model);
assert_ne!(before, after, "a same-length, same-mtime content change must invalidate the fingerprint");
}
#[test]
fn profile_options_jdk_goal_and_wrapper_invalidate_without_using_class_outputs() {
let dir = tempfile::tempdir().unwrap();
-23
Переглянути файл
@@ -242,29 +242,6 @@ mod tests {
assert!(build().is_err());
assert_eq!(fs::read_to_string(root.join("calls")).unwrap().lines().count(), 5);
}
/// An external tool (e.g. an AI code editor) rewrites a source file with the same byte
/// length and preserves its mtime. The `(length, mtime)` fingerprint reads that as
/// "unchanged" and would reuse the stale snapshot; the content hash must catch it.
#[test]
fn external_edit_preserving_length_and_mtime_rebuilds_the_snapshot() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path();
let model = fixture(root);
let cache = root.join("cache");
let cancel = CancellationToken::new();
let mut session = Session::new(cache.clone());
let first = session.build(root, &model, root, false, None, &cancel).unwrap();
assert_eq!(fs::read_to_string(first.snapshot.join("0/Main.class")).unwrap(), "first");
let source = root.join("src/main/kotlin/Main.kt");
let mtime = fs::metadata(&source).unwrap().modified().unwrap();
fs::write(&source, "other").unwrap(); // 5 bytes, same length as "first"
fs::File::options().write(true).open(&source).unwrap().set_modified(mtime).unwrap();
let rebuilt = session.build(root, &model, root, false, None, &cancel).unwrap();
assert_ne!(rebuilt.snapshot, first.snapshot, "a same-length, same-mtime content change must rebuild");
assert_eq!(fs::read_to_string(rebuilt.snapshot.join("0/Main.class")).unwrap(), "other");
}
#[test]
fn session_drop_removes_superseded_snapshots_and_preserves_records_across_reopen() {
let dir = tempfile::tempdir().unwrap();
+3 -5
Переглянути файл
@@ -306,9 +306,8 @@ impl PluginApi {
// allowed, and installing it later approves nothing by itself.
let pin = self.shared.pins.read().get(&(self.id().to_owned(), cap.clone())).cloned().ok_or_else(|| {
HostError::Failed(format!(
"{cap}: `{program}` was not found on PATH when this permission was allowed. \
Restarting doesn't approve a program installed later: once `{program}` is on PATH, \
clear {cap} in Settings › Plugins and select it again"
"{cap}: `{program}` was not found when this permission was allowed; \
install it, then allow {cap} again in Settings › Plugins"
))
})?;
pin.verify().map(Path::to_path_buf).map_err(|e| HostError::Denied(format!("{cap}: {e}")))
@@ -832,8 +831,7 @@ mod tests {
// Allowed while the program was missing: say how to fix it rather than "not granted".
let err = api.approved_program("lint").unwrap_err().to_string();
assert!(
err.contains("was not found on PATH when this permission was allowed")
&& err.contains("clear process:lint in Settings › Plugins and select it again"),
err.contains("was not found when this permission was allowed") && err.contains("allow process:lint again"),
"{err}"
);
-63
Переглянути файл
@@ -120,7 +120,6 @@ impl TerminalManager {
for (k, v) in env {
cmd.env(k, v);
}
apply_powershell_env(&shell, &mut cmd);
let child = pair
.slave
@@ -634,18 +633,6 @@ fn terminal_env(user: &BTreeMap<String, String>) -> BTreeMap<String, String> {
env
}
/// Older pwsh versions can crash while formatting a localized update banner
/// (PowerShell/PowerShell#28131). Keep explicit preferences in the final environment.
fn apply_powershell_env(shell: &str, cmd: &mut CommandBuilder) {
let name = shell.rsplit(['/', '\\']).next().unwrap_or(shell);
if cfg!(windows)
&& (name.eq_ignore_ascii_case("pwsh") || name.eq_ignore_ascii_case("pwsh.exe"))
&& cmd.get_env("POWERSHELL_UPDATECHECK").is_none_or(|v| v.is_empty())
{
cmd.env("POWERSHELL_UPDATECHECK", "Off");
}
}
/// Git Bash's MSYSTEM profile on Windows, when nobody chose one. A bare
/// `bash.exe` would run with the `MSYS` default, whose PATH leaves `git` and
/// the mingw64 tools out unless `<Git>\cmd` happens to be inherited — the Git
@@ -951,56 +938,6 @@ mod tests {
mod shell_start_on_every_platform {
use super::*;
#[test]
fn powershell_update_notifications_default_to_off_on_windows() {
for shell in ["pwsh", "pwsh.exe", "PWSH.EXE", "C:\\Program Files\\PowerShell\\7\\PwSh.ExE", "C:/pwsh/pwsh.exe"]
{
for value in [None, Some("")] {
let mut cmd = CommandBuilder::new(shell);
cmd.env_clear();
if let Some(value) = value {
cmd.env("POWERSHELL_UPDATECHECK", value);
}
apply_powershell_env(shell, &mut cmd);
let want = if cfg!(windows) { Some("Off") } else { value };
assert_eq!(cmd.get_env("POWERSHELL_UPDATECHECK"), want.map(std::ffi::OsStr::new), "{shell}");
}
}
}
#[test]
fn powershell_update_notification_preferences_are_preserved() {
for value in ["Default", "LTS", "Off"] {
let mut cmd = CommandBuilder::new("pwsh.exe");
cmd.env_clear();
cmd.env("POWERSHELL_UPDATECHECK", value);
apply_powershell_env("pwsh.exe", &mut cmd);
assert_eq!(cmd.get_env("POWERSHELL_UPDATECHECK"), Some(std::ffi::OsStr::new(value)));
}
}
#[cfg(windows)]
#[test]
fn powershell_update_notification_preferences_ignore_key_case() {
let mut cmd = CommandBuilder::new("pwsh.exe");
cmd.env_clear();
cmd.env("POWERSHELL_UPDATECHECK", "Off");
cmd.env("powershell_updatecheck", "Default");
apply_powershell_env("pwsh.exe", &mut cmd);
assert_eq!(cmd.get_env("POWERSHELL_UPDATECHECK"), Some(std::ffi::OsStr::new("Default")));
assert_eq!(cmd.iter_full_env_as_str().count(), 1);
}
#[test]
fn other_shells_keep_their_update_notification_environment() {
for shell in ["powershell.exe", "cmd.exe", "wsl.exe", "bash.exe", "C:\\pwsh.exe\\other.exe", "other-pwsh.exe"] {
let mut cmd = CommandBuilder::new(shell);
cmd.env_clear();
apply_powershell_env(shell, &mut cmd);
assert_eq!(cmd.get_env("POWERSHELL_UPDATECHECK"), None, "{shell}");
}
}
#[test]
fn posix_shells_start_as_login_shells_everywhere() {
let (shell, args) = resolve_shell(Some("C:\\Program Files\\Git\\bin\\bash.exe"), &[]);
+4 -21
Переглянути файл
@@ -868,18 +868,17 @@ impl Documents {
.then(|| st.path.clone())
})
.collect();
self.reload_from_disk(&paths, force_clean, true);
self.reload_from_disk(&paths, force_clean);
}
/// Re-reads from disk after an external change. Clean documents reload
/// silently; dirty ones are left alone and reported via `IdeEvent::Notify`.
/// Changes matching our own last save are ignored.
pub fn on_disk_changed(&self, paths: &[PathBuf]) {
self.reload_from_disk(paths, false, false);
self.reload_from_disk(paths, false);
}
/// `dedup`: blind scans skip files whose `(mtime, length)` stamp still matches.
fn reload_from_disk(&self, paths: &[PathBuf], force_clean: bool, dedup: bool) {
fn reload_from_disk(&self, paths: &[PathBuf], force_clean: bool) {
for path in paths {
let Some(id) = self.by_path(path) else { continue };
let result = self.with_doc(id, |st| {
@@ -888,23 +887,7 @@ impl Documents {
}
let Ok(meta) = std::fs::metadata(&st.path) else { return Ok(()) };
let mtime = ide_vfs::mtime_ms(&meta);
let unchanged = mtime == st.disk_mtime && meta.len() == st.disk_len;
// Blind scans trust the stamp. OS events are authoritative, but they also
// echo our own saves: a clean document whose stamp matches is re-checked by
// bytes — an external write that preserved both length and mtime differs
// from what saving this buffer would write, our own save's echo does not.
// Native-to-ascii properties documents and dirty documents keep the stamp
// dedup: the former's disk bytes legitimately differ from the buffer text,
// the latter warn once per disk state.
if unchanged
&& (!force_clean || st.dirty)
&& (dedup
|| st.dirty
|| st.native_to_ascii
|| ide_vfs::encode(&st.doc.text_for_save(), &st.encoding, st.has_bom)
.map(|bytes| bytes == std::fs::read(&st.path).unwrap_or_default())
.unwrap_or(true))
{
if mtime == st.disk_mtime && meta.len() == st.disk_len && (!force_clean || st.dirty) {
return Ok(());
}
if st.dirty {
-40
Переглянути файл
@@ -403,46 +403,6 @@ fn external_changes() {
f.docs.on_disk_changed(&[f.root.join("other.txt")]);
}
/// An IDE operation that rewrites a file with the same length and mtime still refreshes
/// the clean buffer.
#[test]
fn own_disk_change_preserving_length_and_mtime_reloads_a_clean_document() {
let f = fixture();
let path = f.root.join("stamp.txt");
fs::write(&path, "first").unwrap();
let id = f.docs.open(&path).unwrap().id;
let mtime = fs::metadata(&path).unwrap().modified().unwrap();
fs::write(&path, "other").unwrap();
fs::File::options().write(true).open(&path).unwrap().set_modified(mtime).unwrap();
f.docs.sync_after_disk_change();
assert_eq!(f.docs.snapshot(id).unwrap().text, "other");
}
/// An external write that keeps the byte length and the mtime (timestamp-preserving
/// tools, coarse-granularity filesystems) leaves the `(mtime, length)` stamp equal:
/// the OS event is still authoritative, so a clean document reloads.
#[test]
fn external_change_preserving_length_and_mtime_reloads_a_clean_document() {
let f = fixture();
let path = f.root.join("stamp.txt");
fs::write(&path, "first").unwrap(); // 5 bytes
let id = f.docs.open(&path).unwrap().id;
let mtime = fs::metadata(&path).unwrap().modified().unwrap();
fs::write(&path, "other").unwrap(); // 5 bytes, different content
fs::File::options().write(true).open(&path).unwrap().set_modified(mtime).unwrap();
f.docs.on_disk_changed(std::slice::from_ref(&path));
let snap = f.docs.snapshot(id).unwrap();
assert_eq!(snap.text, "other");
assert!(!snap.dirty);
// The reload recorded the new stamp: repeating the same event changes nothing.
let before = f.events.lock().len();
f.docs.on_disk_changed(std::slice::from_ref(&path));
assert_eq!(f.events.lock().len(), before);
assert_eq!(f.docs.snapshot(id).unwrap().text, "other");
}
#[test]
fn encodings_and_read_only() {
let f = fixture();
+1 -3
Переглянути файл
@@ -324,7 +324,7 @@ a token.
<!-- BEGIN GENERATED TOKEN REFERENCE: pnpm gen:theme-docs -->
242 themeable tokens: 121 in the UI theme file, 121 in the editor colour scheme file.
240 themeable tokens: 121 in the UI theme file, 119 in the editor colour scheme file.
### Surfaces (UI theme)
@@ -446,8 +446,6 @@ a token.
| `--syn-python-predefined-usage` | `var(--syn-predefined)` | `var(--syn-predefined)` |
| `--syn-python-fstring` | `#a5c261` | `var(--syn-string)` |
| `--syn-python-bytes` | `#a5c261` | `var(--syn-string)` |
| `--syn-php-variable` | `var(--syn-property)` | `var(--syn-property)` |
| `--syn-php-function-call` | `var(--syn-function)` | `var(--syn-function)` |
| `--syn-builtin` | `#8888c6` | `#000080` |
| `--syn-self` | `#94558d` | `#94558d` |
| `--syn-keyword-arg` | `#aa4926` | `#660099` |
-2
Переглянути файл
@@ -34,8 +34,6 @@
"--syn-python-predefined-usage": "#c4a0f2",
"--syn-python-fstring": "#9ccc7a",
"--syn-python-bytes": "#9ccc7a",
"--syn-php-variable": "#b9a3f0",
"--syn-php-function-call": "#f2d07a",
"--syn-builtin": "#6fc3df",
"--syn-self": "#d6849c",
"--syn-keyword-arg": "#c4a0f2",
-18
Переглянути файл
@@ -262,24 +262,6 @@ describe("EditorController", () => {
useProject.setState({ lightEdit: false });
});
it("opens a file requested while the LightEdit session is being restored", async () => {
ctrl = new EditorController(createMemoryBackend({ "/x/a.txt": "a", "/y/b.md": "b", "/z/launch.lua": "l" }));
ctrl.start();
useProject.setState({ lightEdit: true });
await ctrl.openFile("/x/a.txt", { focus: false });
await ctrl.openFile("/y/b.md", { focus: false });
useProject.setState({ lightEdit: false });
// A launch with a file path: LightEdit starts and the file opens before the old tabs are back.
useProject.setState({ lightEdit: true });
await ctrl.openFile("/z/launch.lua", { focus: false });
expect(openFilePaths(useTabs.getState())).toEqual(["/x/a.txt", "/y/b.md", "/z/launch.lua"]);
const s = useTabs.getState();
const active = s.panes[s.activePane]!;
expect(active.tabs.find((t) => t.id === active.active)?.input.path).toBe("/z/launch.lua");
await ctrl.closeEverything();
useProject.setState({ lightEdit: false });
});
it("closes a tab by its input key", async () => {
ctrl = new EditorController(createMemoryBackend());
ctrl.start();
+1 -9
Переглянути файл
@@ -237,8 +237,6 @@ export class EditorController implements SlotHost {
private selectionRequests = new Map<string, number>();
private activationGeneration = 0;
private admitting = false;
/** Tabs restored from a saved session: not a user's activation, so a pending open still activates its tab. */
private restoring = false;
private closeRequests = 0;
private projectTransition: Promise<void> = Promise.resolve();
@@ -271,7 +269,6 @@ export class EditorController implements SlotHost {
prevTabs = s;
if (
!this.admitting &&
!this.restoring &&
(s.activePane !== prev.activePane || s.panes[s.activePane]?.active !== prev.panes[prev.activePane]?.active)
)
++this.activationGeneration;
@@ -489,12 +486,7 @@ export class EditorController implements SlotHost {
pane.tabs = pane.tabs.map((tab) => (documentLifecycle(tab.input, kinds) ? { ...tab, preview: false } : tab));
this.restoredViews = new Map(Object.entries(session.files));
this.restoredTabs = new Set(Object.values(state.panes).flatMap((p) => p.tabs.map((t) => t.id)));
this.restoring = true;
try {
useTabs.setState(state, true);
} finally {
this.restoring = false;
}
useTabs.setState(state, true);
for (const pane of Object.values(state.panes)) if (pane.active) void this.ensureSlot(pane.active);
}
-16
Переглянути файл
@@ -1,16 +0,0 @@
import { describe, expect, it } from "vitest";
import { filterColumns } from "./ColumnsPopup";
const columns = ["id", "user_id", "name", "created_at", "username"].map((name) => ({ name, type: "TEXT" }));
describe("filterColumns", () => {
it("lists every column for an empty query", () => {
expect(filterColumns(columns, " ")).toEqual([0, 1, 2, 3, 4]);
});
it("puts prefix matches first, then other matches, ignoring case", () => {
expect(filterColumns(columns, "US")).toEqual([1, 4]);
expect(filterColumns(columns, "name")).toEqual([2, 4]);
expect(filterColumns(columns, "_id")).toEqual([1]);
});
});
-92
Переглянути файл
@@ -1,92 +0,0 @@
/**
* Go to Column in a table editor (⌘F12 / Ctrl+F12): the grid's columns, filtered as you type;
* Enter selects that column's cell in the current row.
*/
import { useState } from "react";
import { Icon, Input, List, Popup, listNavigate } from "@/ui";
import { tx } from "@/platform/i18n";
import type { GridColumn } from "./Grid";
import styles from "./Database.module.css";
export function filterColumns(columns: readonly GridColumn[], query: string): number[] {
const q = query.trim().toLowerCase();
const all = columns.map((_, i) => i);
if (!q) return all;
const starts = all.filter((i) => columns[i]!.name.toLowerCase().startsWith(q));
const contains = all.filter((i) => !starts.includes(i) && columns[i]!.name.toLowerCase().includes(q));
return [...starts, ...contains];
}
export function ColumnsPopup(props: {
anchor: { x: number; y: number };
table: string;
columns: readonly GridColumn[];
onPick: (col: number) => void;
onClose: () => void;
}) {
const [query, setQuery] = useState("");
const [active, setActive] = useState(0);
const shown = filterColumns(props.columns, query);
const current = Math.min(active, shown.length - 1);
const pick = (i: number) => {
const col = shown[i];
if (col !== undefined) props.onPick(col);
};
return (
<Popup
open
anchor={props.anchor}
placement="bottom"
onClose={props.onClose}
aria-label={tx`Columns of ${props.table}`}
className={styles.columnsPopup}
trapFocus
>
<Input
autoFocus
aria-label={tx("Search columns")}
placeholder={tx`Columns of ${props.table}`}
value={query}
onChange={(e) => {
setQuery(e.target.value);
setActive(0);
}}
onKeyDown={(e) => {
if (e.key === "Enter") {
e.preventDefault();
pick(current);
return;
}
const next = listNavigate(e.key, { items: shown, active: current });
if (next !== null) {
e.preventDefault();
setActive(next);
}
}}
/>
<List
items={shown}
getKey={(col) => String(col)}
activeIndex={current}
onActiveChange={setActive}
onActivate={(_, i) => pick(i)}
focusable={false}
hoverSelects
rowHeight={22}
aria-label={tx("Columns")}
className={styles.columnsList}
empty={<span>{tx("No matching columns")}</span>}
renderItem={(col) => {
const c = props.columns[col]!;
return (
<span className={styles.columnsRow}>
<Icon name={c.primaryKey ? "db-column-key" : c.foreignKey ? "db-column-fk" : "db-column"} size={16} />
{c.name}
{c.type && c.type !== "NULL" && <span className={styles.treeType}>{c.type}</span>}
</span>
);
}}
/>
</Popup>
);
}
-2
Переглянути файл
@@ -90,7 +90,6 @@ export interface DataViewProps extends Pick<
/** The search bar is shown (the toolbar's search button, ⌘F in the grid). */
searchOpen?: boolean;
onSearchOpenChange?: (open: boolean) => void;
revealColumn?: GridProps["revealColumn"];
"aria-label"?: string;
}
@@ -201,7 +200,6 @@ export function DataView(props: DataViewProps) {
isMatch={test ? (r, c) => matchSet.has(`${r}:${c}`) : undefined}
currentMatch={currentMatch}
onFind={onSearchOpenChange && openSearch}
revealColumn={props.revealColumn}
aria-label={props["aria-label"]}
columns={columns}
rowCount={shown}
-19
Переглянути файл
@@ -823,25 +823,6 @@
font: inherit;
cursor: pointer;
}
/* Go to Column (ColumnsPopup.tsx). */
.columnsPopup {
display: flex;
flex-direction: column;
gap: 6px;
width: 320px;
padding: 8px;
}
.columnsList {
height: min(320px, 50vh);
}
.columnsRow {
display: flex;
flex: 1;
align-items: center;
gap: 6px;
min-width: 0;
white-space: nowrap;
}
.filterPopup {
display: flex;
flex-direction: column;
-25
Переглянути файл
@@ -57,8 +57,6 @@ export interface GridProps {
currentMatch?: { row: number; col: number } | null;
/** ⌘F / Ctrl+F in the grid (opens the search bar). */
onFind?: () => void;
/** Go to Column: a new object selects that column's cell in the current row, scrolls to it and focuses the grid. */
revealColumn?: { col: number } | null;
"aria-label"?: string;
}
@@ -162,37 +160,15 @@ export function Grid(props: GridProps) {
estimateSize: () => ROW_H,
overscan: 12,
});
/** Scrolls sideways so column `c` is visible (the first one with the row numbers). */
const scrollColumnIntoView = (c: number) => {
const el = scrollRef.current;
if (!el || c < 0 || c >= widths.length) return;
const left = c ? NUM_W + widths.slice(0, c).reduce((a, b) => a + b, 0) : 0;
const right = NUM_W + widths.slice(0, c + 1).reduce((a, b) => a + b, 0);
if (left < el.scrollLeft) el.scrollLeft = left;
else if (right > el.scrollLeft + el.clientWidth) el.scrollLeft = Math.min(left, right - el.clientWidth);
};
const { currentMatch } = props;
useEffect(() => {
if (!currentMatch) return;
const { row, col } = currentMatch;
setSel({ r0: row, c0: col, r1: row, c1: col });
virtualizer.scrollToIndex(row, { align: "auto" });
scrollColumnIntoView(col);
// Follows the match only, not the virtualizer's identity.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [currentMatch?.row, currentMatch?.col]);
const { revealColumn } = props;
useEffect(() => {
if (!revealColumn || !rowCount) return;
const { col } = revealColumn;
const row = sel ? Math.min(sel.r1, rowCount - 1) : 0;
setSel({ r0: row, c0: col, r1: row, c1: col });
virtualizer.scrollToIndex(row, { align: "auto" });
scrollColumnIntoView(col);
scrollRef.current?.focus({ preventScroll: true });
// Runs once per request.
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [revealColumn]);
const totalWidth = useMemo(() => NUM_W + widths.reduce((a, b) => a + b, 0), [widths]);
const template = `${NUM_W}px ${widths.map((w) => `${w}px`).join(" ")}`;
@@ -279,7 +255,6 @@ export function Grid(props: GridProps) {
const c = Math.max(0, Math.min(columns.length - 1, sel.c1 + m[1]));
setSel(e.shiftKey ? { ...sel, r1: r, c1: c } : { r0: r, c0: c, r1: r, c1: c });
virtualizer.scrollToIndex(r, { align: "auto" });
scrollColumnIntoView(c);
};
const onCellMouseDown = (e: MouseEvent, r: number, c: number) => {
+1 -26
Переглянути файл
@@ -16,7 +16,6 @@ import {
import { Button, EmptyState, Icon, IconButton, Select, Spinner, T, showContextMenu } from "@/ui";
import { notifications, type EditorInput } from "@/workbench/contributions";
import { SqlFilterInput } from "./SqlFilterInput";
import { ColumnsPopup } from "./ColumnsPopup";
import { DataView, ExtractorSelect, PanelToggle, exportMenu, type DataPanel } from "./DataView";
import type { ExportFormat } from "./export";
import {
@@ -183,23 +182,12 @@ export function TableEditor({ input }: { input: EditorInput }) {
const dirty = hasEdits(edits);
// Submit / Revert actions (⌘↩ / ⌥⌘Z) reach the latest state through the handle.
const viewRef = useRef<HTMLDivElement>(null);
const handle = useRef<TableEditorHandle>({
dirty: false,
submit: () => {},
revert: () => {},
showColumns: () => {},
}).current;
const handle = useRef<TableEditorHandle>({ dirty: false, submit: () => {}, revert: () => {} }).current;
handle.dirty = editable && dirty;
handle.submit = () => {
if (editable && dirty) void submit();
};
handle.revert = () => setEdits(emptyEdits());
const [columnsAt, setColumnsAt] = useState<{ x: number; y: number } | null>(null);
const [revealColumn, setRevealColumn] = useState<{ col: number } | null>(null);
handle.showColumns = () => {
const r = viewRef.current?.getBoundingClientRect();
if (page && r) setColumnsAt({ x: r.left + r.width / 2, y: r.top + 48 });
};
useEffect(() => registerTableEditor(viewRef.current!, handle), [handle]);
useEffect(() => tableEditorChanged(handle), [handle, dirty, editable]);
const orderInvalid = orderDraft !== null && !parseOrderBy(orderDraft, names);
@@ -351,7 +339,6 @@ export function TableEditor({ input }: { input: EditorInput }) {
columns={gridColumns}
rowCount={rowCount}
fixedRows={loaded}
revealColumn={revealColumn}
value={value}
panel={panel}
onPanelChange={setPanel}
@@ -379,18 +366,6 @@ export function TableEditor({ input }: { input: EditorInput }) {
/>
</div>
)}
{columnsAt && (
<ColumnsPopup
anchor={columnsAt}
table={ref.table}
columns={gridColumns}
onPick={(col) => {
setColumnsAt(null);
setRevealColumn({ col });
}}
onClose={() => setColumnsAt(null)}
/>
)}
</div>
);
}
-8
Переглянути файл
@@ -154,14 +154,6 @@ export function activate(): () => void {
await executeInView(e.view, e.ctx.path);
},
},
{
id: "db.goToColumn",
title: "Go to Column",
category: "Tools",
keywords: ["table editor", "file structure", "columns"],
when: "dbTableEditorFocus",
run: () => activeTableEditor()?.showColumns(),
},
{
id: "db.submitChanges",
title: "Submit",
+2 -3
Переглянути файл
@@ -1,6 +1,6 @@
/**
* The table editor that has focus, for Submit / Revert (⌘↩ / ⌥⌘Z) and Go to Column (⌘F12). Not
* while a text field has it: ⌘↩ there applies the field's own edit (the Value panel, the cell editor).
* The table editor that has focus, for Submit / Revert (⌘↩ / ⌥⌘Z). Not while a text field has
* it: ⌘↩ there applies the field's own edit (the Value panel, the cell editor).
*/
import { setContext } from "@/platform/context";
@@ -8,7 +8,6 @@ export interface TableEditorHandle {
dirty: boolean;
submit(): void;
revert(): void;
showColumns(): void;
}
const handles = new WeakMap<Element, TableEditorHandle>();
+4 -18
Переглянути файл
@@ -664,24 +664,10 @@ describe("Show Members", () => {
});
});
it("sorts workspace member roots by the folder names shown in the tree", async () => {
fs = new MemoryFs({
"/a/service10/ten.txt": "",
"/z/Service2/two.txt": "",
"/m/alpha/first.txt": "",
"/workspace/.openidea/workspace.json": "{}",
});
it("renders workspace member roots with their own paths, without the settings directory", async () => {
fs = new MemoryFs({ "/z/first.txt": "", "/a/second.txt": "", "/workspace/.openidea/workspace.json": "{}" });
setProjectFsForTests(fs, "/workspace");
initProjectTree("/workspace", "Workspace", ["/a/service10", "/z/Service2", "/m/alpha"]);
initProjectTree("/workspace", "Workspace", ["/z", "/a"]);
const { rows } = setup();
await waitFor(() =>
expect(rows()).toEqual([
"alpha/m/alpha",
"first.txt",
"Service2/z/Service2",
"two.txt",
"service10/a/service10",
"ten.txt",
]),
);
await waitFor(() => expect(rows()).toEqual(["z/z", "first.txt", "a/a", "second.txt"]));
});
+1 -5
Переглянути файл
@@ -100,10 +100,6 @@ export function isVisible(entry: FileEntry, opts: TreeOptions): boolean {
const collator = new Intl.Collator(undefined, { numeric: true, sensitivity: "base" });
export function compareNames(a: string, b: string): number {
return collator.compare(a, b) || (a < b ? -1 : a > b ? 1 : 0);
}
/** Symlinks report the target's metadata; folders have size 0 (the entry has no target kind). */
export const isDirEntry = (e: FileEntry) => e.kind === "dir" || (e.kind === "symlink" && e.size === 0);
@@ -129,7 +125,7 @@ export function sortEntries(
const m = (b.mtimeMs ?? 0) - (a.mtimeMs ?? 0);
if (m) return m;
}
return compareNames(a.name, b.name);
return collator.compare(a.name, b.name) || (a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
});
}
+2 -3
Переглянути файл
@@ -104,13 +104,12 @@ describe("creating packages", () => {
});
});
it("shows manifest members in name order in workspace Project and Project Files views", () => {
it("uses only manifest members in order in workspace Project and Project Files views", () => {
for (const mode of ["project", "projectFiles"] as const) {
initProjectTree("/workspace", "Workspace", ["/z", "/a"]);
useProjectTree.setState({ mode });
const model = selectModel(useProjectTree.getState());
expect(model.roots.map((r) => r.path)).toEqual(["/a", "/z"]);
expect(useProjectTree.getState().members).toEqual(["/z", "/a"]);
expect(model.roots.map((r) => r.path)).toEqual(["/z", "/a"]);
expect(model.byKey.has("/workspace")).toBe(false);
initProjectTree("/workspace", "Workspace", ["/a"]);
expect(selectModel(useProjectTree.getState()).roots.map((r) => r.path)).toEqual(["/a"]);
+7 -5
Переглянути файл
@@ -14,7 +14,6 @@ import {
GROUP_PREFIX,
buildModel,
buildPathsModel,
compareNames,
extraFolders,
isGroupKey,
isLibKey,
@@ -35,7 +34,7 @@ import {
} from "./model";
import { projectFs } from "./fs";
import { projectViewRoots, useProjectViewRoots, type ProjectViewRootContribution } from "@/workbench/contributions";
import { ancestorsWithin, isSameOrInside, nameOf, type PackageKind } from "./paths";
import { ancestorsWithin, isSameOrInside, type PackageKind } from "./paths";
export interface ViewOptions extends TreeOptions {
/** Select the active editor's file in the tree. */
@@ -219,9 +218,12 @@ export function selectModel(s: ProjectTreeState): TreeModel {
const extras = useProjectViewRoots.getState().roots;
const options = treeOptions(s);
const contributed = projectViewRoots(extras);
const memberRoots = s.members
?.map((path) => ({ path, label: nameOf(path), icon: "", detail: path }))
.sort((a, b) => compareNames(a.label, b.label));
const memberRoots = s.members?.map((path) => ({
path,
label: path.slice(path.lastIndexOf("/") + 1),
icon: "",
detail: path,
}));
const project = () =>
memberRoots
? withExtraRoots(EMPTY_MODEL, memberRoots, s.listings, options, placeholder)
+2 -19
Переглянути файл
@@ -129,32 +129,15 @@
flex-direction: column;
padding: 0 14px 14px;
}
/* Push dialog: commits above their changed files, split by a draggable divider; the pair fills the body. */
.pushSplit {
flex: 1;
min-height: min(540px, 60vh);
}
/* The panel's own `height: 100%` doesn't resolve against a flex-basis height in WebKit: stretch instead. */
.pushSplit .pushSplitPanel {
height: auto;
align-self: stretch;
}
.pushSplitPanel > .pushListWrap {
min-height: 0;
padding-bottom: 8px;
}
/* Push dialogs: the outgoing commits' changed files below the commits, the diff beside them. */
.pushChanges {
flex: 1;
flex: none;
display: flex;
flex-direction: column;
min-height: 0;
padding-top: 8px;
}
.pushChanges .comparison {
flex: 1;
height: auto;
min-height: 0;
height: min(360px, 45vh);
padding: 0 14px 14px;
}
.pushChangesTitle {
+35 -82
Переглянути файл
@@ -5,7 +5,7 @@ import { call, commands } from "@/platform/ipc";
import { tx } from "@/platform/i18n";
import { workflowSettings } from "@/platform/workflowSettings";
import { notifications } from "@/workbench/contributions";
import { Checkbox, Dialog, Input, List, Select, Spinner, SplitGroup, SplitHandle, SplitPanel, T, Tree } from "@/ui";
import { Checkbox, Dialog, Input, List, Select, Spinner, T, Tree } from "@/ui";
import { ask } from "@/workbench/messages";
import { openDialog } from "./dialogs";
import { formatTime } from "./model";
@@ -340,11 +340,6 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
const [commits, setCommits] = useState<Commit[] | null>(null);
// The commit whose changes are shown; -1: all outgoing commits.
const [shownCommit, setShownCommit] = useState(-1);
const [pushSplit, setPushSplit] = useState(loadPushSplit);
const keepPushSplit = (layout: Record<string, number>) => {
setPushSplit(layout);
savePushSplit(layout);
};
const shownCommits = useMemo(
() => (commits && shownCommit >= 0 && commits[shownCommit] ? [commits[shownCommit]] : (commits ?? [])),
[commits, shownCommit],
@@ -445,36 +440,6 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
);
};
const commitList = (
<div className={styles.pushListWrap}>
{error ? (
<div className={styles.error}>{error}</div>
) : !commits ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : (
<List
items={commits}
getKey={(c) => c.id}
activeIndex={shownCommit}
onActiveChange={setShownCommit}
rowHeight={22}
aria-label="Outgoing commits"
className={styles.boxList}
empty={<span>{upstream ? tx("Everything is up to date") : tx("No commits")}</span>}
renderItem={(c) => (
<span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
<span className={styles.commitHash}>{c.shortId}</span>
<span className={styles.commitSubject}>{c.summary}</span>
<span className={styles.commitMeta}>{c.author}</span>
<span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
</span>
)}
/>
)}
</div>
);
return (
<Dialog
open
@@ -555,56 +520,44 @@ function PushDialog({ target: pushTarget, onClose }: { target: PushTarget; onClo
)}
{retarget && <span className={styles.hint}> {tx("New")}</span>}
</div>
{commits?.length && !error ? (
<SplitGroup
orientation="vertical"
id="vcs-push-split"
className={styles.pushSplit}
defaultLayout={pushSplit}
onLayoutChanged={keepPushSplit}
>
<SplitPanel id="commits" minSize="72px" defaultSize="35%" className={styles.pushSplitPanel}>
{commitList}
</SplitPanel>
<SplitHandle />
<SplitPanel id="changes" minSize="160px" className={styles.pushSplitPanel}>
<PushChanges
key={pushChangesKey(repo, shownCommits)}
repo={repo}
commits={shownCommits}
onShowAll={shownCommit >= 0 && commits.length > 1 ? () => setShownCommit(-1) : undefined}
/>
</SplitPanel>
</SplitGroup>
) : (
commitList
)}
<div className={styles.pushListWrap}>
{error ? (
<div className={styles.error}>{error}</div>
) : !commits ? (
<div className={styles.empty}>
<Spinner size={14} />
</div>
) : (
<List
items={commits}
getKey={(c) => c.id}
activeIndex={shownCommit}
onActiveChange={setShownCommit}
rowHeight={22}
aria-label="Outgoing commits"
className={styles.boxList}
empty={<span>{upstream ? tx("Everything is up to date") : tx("No commits")}</span>}
renderItem={(c) => (
<span className={styles.commitRow} style={{ flex: 1, padding: 0 }}>
<span className={styles.commitHash}>{c.shortId}</span>
<span className={styles.commitSubject}>{c.summary}</span>
<span className={styles.commitMeta}>{c.author}</span>
<span className={styles.commitMeta}>{formatTime(c.timeMs)}</span>
</span>
)}
/>
)}
</div>
<PushChanges
key={pushChangesKey(repo, shownCommits)}
repo={repo}
commits={shownCommits}
onShowAll={shownCommit >= 0 && (commits?.length ?? 0) > 1 ? () => setShownCommit(-1) : undefined}
/>
</Dialog>
);
}
const PUSH_SPLIT_KEY = "openidea.vcs.pushSplit";
/** Heights of the Push dialog's commits and changed files, as the splitter left them. */
function loadPushSplit(): Record<string, number> | undefined {
try {
const v: unknown = JSON.parse(localStorage.getItem(PUSH_SPLIT_KEY) ?? "null");
return v && typeof v === "object" && Object.values(v).every((n) => typeof n === "number")
? (v as Record<string, number>)
: undefined;
} catch {
return undefined;
}
}
function savePushSplit(layout: Record<string, number>) {
try {
localStorage.setItem(PUSH_SPLIT_KEY, JSON.stringify(layout));
} catch {
/* kept for this dialog only */
}
}
const SILENT_FORCE_PUSH_KEY = "openidea.vcs.silentForcePushTargets";
function silentForcePushTargets(): string[] {
-1
Переглянути файл
@@ -50,7 +50,6 @@ export const eclipseMacos: Record<string, string[]> = {
"code.expandToLevel5": [],
"refactor.extractMethod": ["Meta+Alt+M"],
"navigate.fileStructure": ["Meta+O"],
"db.goToColumn": ["Meta+O"],
"find.inFile": [],
"find.inPath": ["Ctrl+H"],
"find.next": ["Meta+K"],
-1
Переглянути файл
@@ -52,7 +52,6 @@ export const eclipseWindows: Record<string, string[]> = {
"code.expandToLevel5": [],
"refactor.extractMethod": ["Shift+Alt+M"],
"navigate.fileStructure": ["Ctrl+F3", "Ctrl+O"],
"db.goToColumn": ["Ctrl+F3", "Ctrl+O"],
"find.inFile": [],
"find.inPath": ["Ctrl+H"],
"find.next": ["Ctrl+K"],
-1
Переглянути файл
@@ -41,7 +41,6 @@ const shared = [
"find.popup.openResult",
],
["navigate.typeHierarchy", "db.editData"],
["navigate.fileStructure", "db.goToColumn"],
["find.replaceInFile", "agents.findInConversation", "vcs.log.goToRef"],
["find.next", "find.popup.nextResult"],
["find.previous", "find.popup.previousResult"],
-1
Переглянути файл
@@ -353,7 +353,6 @@ export const intellijMacos: Record<string, string[]> = {
"http.runAll": [],
"db.execute": ["Meta+Enter"],
// Table editor with pending changes (after `vcs.rollback`, so ⌥⌘Z reverts the table's edits there).
"db.goToColumn": ["Meta+F12"],
"db.submitChanges": ["Meta+Enter"],
"db.revertChanges": ["Meta+Alt+Z"],
"db.showToolWindow": [],
-1
Переглянути файл
@@ -351,7 +351,6 @@ export const intellijWindows: Record<string, string[]> = {
"http.runAll": [],
"db.execute": ["Ctrl+Enter"],
// Table editor with pending changes (after `vcs.rollback`, so Ctrl+Alt+Z reverts the table's edits there).
"db.goToColumn": ["Ctrl+F12"],
"db.submitChanges": ["Ctrl+Enter"],
"db.revertChanges": ["Ctrl+Alt+Z"],
"db.showToolWindow": [],
-1
Переглянути файл
@@ -22,7 +22,6 @@ export const vscodeMacos: Record<string, string[]> = {
"navigate.implementation": ["Meta+F12"],
"navigate.typeDeclaration": [],
"navigate.fileStructure": ["Meta+Shift+O"],
"db.goToColumn": ["Meta+Shift+O"],
"navigate.relatedSymbol": [],
"navigate.nextError": ["F8"],
"navigate.prevError": ["Shift+F8"],
-4
Переглянути файл
@@ -3744,10 +3744,6 @@
"Clear local filter": "清除本地筛选",
"Search values": "搜索值",
"No matching values": "没有匹配的值",
"Go to Column": "转到列",
"Columns of {table}": "{table} 的列",
"Search columns": "搜索列",
"No matching columns": "没有匹配的列",
"Clear Filter": "清除筛选",
"Clear Local Filter For All Columns": "清除所有列的本地筛选",
"Value panel": "值面板",