mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-23 08:49:33 -10:00
Compare commits
6
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f0b25501f5 | ||
|
|
85347088e6 | ||
|
|
2dd72d4c36 | ||
|
|
4ce05ff14e | ||
|
|
9c12cacbdb | ||
|
|
d773621276 |
No files matched your search
Generated
+1
@@ -4511,6 +4511,7 @@ dependencies = [
|
||||
name = "ide-http"
|
||||
version = "0.1.49"
|
||||
dependencies = [
|
||||
"hyper-util",
|
||||
"ide-core",
|
||||
"ide-vfs",
|
||||
"parking_lot",
|
||||
|
||||
@@ -602,7 +602,13 @@ impl DbManager {
|
||||
pub(crate) async fn jdbc_completion(&self, id: &str, pool: &JdbcPool) -> IdeResult<crate::CompletionModel> {
|
||||
let mut tables = vec![];
|
||||
let mut column_count = 0;
|
||||
let schemas = self.schemas(id).await?;
|
||||
// Read the schemas the source's Schemas tab picks, like the database tree does. It also
|
||||
// keeps large instances usable: an Oracle server exposes dozens of system schemas, and
|
||||
// dumping the columns of all of them takes minutes, during which the bridge (a single
|
||||
// Java process that runs one command at a time) executes none of the user's statements.
|
||||
let introspection = self.source(id)?.introspection;
|
||||
let schemas: Vec<String> =
|
||||
self.schemas(id).await?.into_iter().filter(|s| introspection.shows_schema(s)).collect();
|
||||
for schema in &schemas {
|
||||
// Columns of the whole namespace in one call; a driver that refuses it still completes tables.
|
||||
let mut columns = if column_count < crate::MAX_META_ROWS {
|
||||
|
||||
@@ -124,6 +124,45 @@ impl Default for DbIntrospection {
|
||||
}
|
||||
}
|
||||
|
||||
impl DbIntrospection {
|
||||
/// Whether the tree shows this schema: every one with `all_schemas`, otherwise it has to
|
||||
/// match one of the `schemas` patterns. The completion model uses the same test, so it
|
||||
/// offers exactly the tables the tree lists (and does not read the ones it never shows).
|
||||
pub fn shows_schema(&self, name: &str) -> bool {
|
||||
self.all_schemas
|
||||
|| self.schemas.iter().map(|p| p.trim()).filter(|p| !p.is_empty()).any(|p| schema_matches(p, name))
|
||||
}
|
||||
}
|
||||
|
||||
/// `*` matches any run of characters, `?` a single one; a pattern without wildcards matches the
|
||||
/// name as typed (the dialog fills names from the list the server returned, so case is settled).
|
||||
fn schema_matches(pattern: &str, name: &str) -> bool {
|
||||
if !pattern.contains('*') && !pattern.contains('?') {
|
||||
return pattern == name;
|
||||
}
|
||||
let p: Vec<char> = pattern.chars().collect();
|
||||
let n: Vec<char> = name.chars().collect();
|
||||
let (mut pi, mut ni) = (0, 0);
|
||||
// Position of the last `*` and how much of the name it has already swallowed.
|
||||
let mut star: Option<(usize, usize)> = None;
|
||||
while ni < n.len() {
|
||||
if pi < p.len() && (p[pi] == '?' || p[pi] == n[ni]) {
|
||||
pi += 1;
|
||||
ni += 1;
|
||||
} else if pi < p.len() && p[pi] == '*' {
|
||||
star = Some((pi, ni));
|
||||
pi += 1;
|
||||
} else if let Some((at, taken)) = star {
|
||||
pi = at + 1;
|
||||
ni = taken + 1;
|
||||
star = Some((at, taken + 1));
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
p[pi..].iter().all(|&c| c == '*')
|
||||
}
|
||||
|
||||
/// Advanced tab: a driver property. PostgreSQL: run-time parameters (and
|
||||
/// `application_name`); MySQL: session variables (and `charset`, `collation`);
|
||||
/// SQLite: pragmas. See [`crate::conn`].
|
||||
@@ -765,4 +804,24 @@ mod tests {
|
||||
assert_eq!(r.snowflake().auth, DbSnowflakeAuth::Browser);
|
||||
assert_eq!(scheme_driver("snowflake"), Some(DbDriver::Snowflake));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn introspection_shows_only_the_picked_schemas() {
|
||||
let mut i = DbIntrospection::default();
|
||||
assert!(i.shows_schema("SYS"), "the default reads every schema");
|
||||
|
||||
i.all_schemas = false;
|
||||
assert!(!i.shows_schema("SYS"), "nothing picked: the tree lists nothing either");
|
||||
|
||||
i.schemas = vec!["XMCB".into(), " APP_* ".into()];
|
||||
assert!(i.shows_schema("XMCB"));
|
||||
assert!(i.shows_schema("APP_INFO"));
|
||||
assert!(!i.shows_schema("APP"), "`*` needs the text that follows it");
|
||||
assert!(!i.shows_schema("SYS"));
|
||||
assert!(!i.shows_schema("xmcb"), "patterns match the names the server returned");
|
||||
|
||||
i.schemas = vec!["?".into()];
|
||||
assert!(i.shows_schema("A"));
|
||||
assert!(!i.shows_schema("AB"));
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,8 @@ tokio.workspace = true
|
||||
tracing.workspace = true
|
||||
parking_lot.workspace = true
|
||||
reqwest.workspace = true
|
||||
# The system proxy reqwest reads, to notice when it changes (see `client::shared`).
|
||||
hyper-util = { version = "0.1", default-features = false, features = ["client-proxy", "client-proxy-system"] }
|
||||
rustls.workspace = true
|
||||
rustls-platform-verifier.workspace = true
|
||||
uuid.workspace = true
|
||||
|
||||
@@ -5,7 +5,7 @@ use ide_core::proxy_settings::{ProxyMode, ProxyRoute, ProxySettings};
|
||||
use ide_core::{CancellationToken, IdeError, IdeResult};
|
||||
use parking_lot::Mutex;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// `builder` routed as `proxy` says: direct, the environment's proxy (reqwest's
|
||||
/// default), or the manual proxy except for the "No proxy for" hosts.
|
||||
@@ -62,33 +62,61 @@ pub fn build_with_redirect(proxy: &ProxySettings, redirect: reqwest::redirect::P
|
||||
with_proxy(builder, proxy).build().map_err(|e| fail(e.to_string()))
|
||||
}
|
||||
|
||||
/// A client built for these proxy settings and, in Auto mode, this system proxy.
|
||||
struct Cached {
|
||||
settings: Arc<ProxySettings>,
|
||||
system: Option<String>,
|
||||
client: reqwest::Client,
|
||||
}
|
||||
|
||||
/// The client for the current proxy settings, rebuilt when they change.
|
||||
pub fn shared() -> IdeResult<reqwest::Client> {
|
||||
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
|
||||
cached_client(&CLIENT, build)
|
||||
static CLIENT: Mutex<Option<Cached>> = Mutex::new(None);
|
||||
cached_client(&CLIENT, build, system_proxy)
|
||||
}
|
||||
|
||||
/// The client the HTTP Client executes requests with: redirects off, `exec`
|
||||
/// follows them by hand — that is what lets a `POST` stay a `POST` on a
|
||||
/// 301/302 and puts the redirect chain into the response.
|
||||
pub fn shared_without_redirects() -> IdeResult<reqwest::Client> {
|
||||
static CLIENT: Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>> = Mutex::new(None);
|
||||
cached_client(&CLIENT, |proxy| build_with_redirect(proxy, reqwest::redirect::Policy::none()))
|
||||
static CLIENT: Mutex<Option<Cached>> = Mutex::new(None);
|
||||
cached_client(&CLIENT, |proxy| build_with_redirect(proxy, reqwest::redirect::Policy::none()), system_proxy)
|
||||
}
|
||||
|
||||
/// The system proxy (the environment's, then macOS / Windows settings) as reqwest reads
|
||||
/// it when a client is built, re-read at most every few seconds. A client in Auto mode
|
||||
/// keeps the proxy it was built with, so a proxy app that switches the system proxy on
|
||||
/// after launch would otherwise leave downloads going direct until a restart.
|
||||
fn system_proxy() -> String {
|
||||
static LAST: Mutex<Option<(Instant, String)>> = Mutex::new(None);
|
||||
let mut last = LAST.lock();
|
||||
if let Some((at, seen)) = last.as_ref()
|
||||
&& at.elapsed() < Duration::from_secs(3)
|
||||
{
|
||||
return seen.clone();
|
||||
}
|
||||
// Credentials are left out of the matcher's `Debug`.
|
||||
let seen = format!("{:?}", hyper_util::client::proxy::matcher::Matcher::from_system());
|
||||
*last = Some((Instant::now(), seen.clone()));
|
||||
seen
|
||||
}
|
||||
|
||||
fn cached_client(
|
||||
slot: &Mutex<Option<(Arc<ProxySettings>, reqwest::Client)>>,
|
||||
build: fn(&ProxySettings) -> IdeResult<reqwest::Client>,
|
||||
slot: &Mutex<Option<Cached>>,
|
||||
build: impl Fn(&ProxySettings) -> IdeResult<reqwest::Client>,
|
||||
system: fn() -> String,
|
||||
) -> IdeResult<reqwest::Client> {
|
||||
let proxy = ide_core::proxy_settings::proxy();
|
||||
let system = (proxy.mode == ProxyMode::Auto).then(system);
|
||||
let mut cached = slot.lock();
|
||||
if let Some((settings, client)) = cached.as_ref()
|
||||
&& **settings == *proxy
|
||||
if let Some(c) = cached.as_ref()
|
||||
&& *c.settings == *proxy
|
||||
&& c.system == system
|
||||
{
|
||||
return Ok(client.clone());
|
||||
return Ok(c.client.clone());
|
||||
}
|
||||
let client = build(&proxy)?;
|
||||
*cached = Some((proxy, client.clone()));
|
||||
*cached = Some(Cached { settings: proxy, system, client: client.clone() });
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
@@ -142,6 +170,36 @@ pub fn describe(e: &reqwest::Error) -> String {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn auto_mode_rebuilds_the_shared_client_when_the_system_proxy_changes() {
|
||||
static SYSTEM: Mutex<String> = Mutex::new(String::new());
|
||||
static BUILDS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
|
||||
fn system() -> String {
|
||||
SYSTEM.lock().clone()
|
||||
}
|
||||
let slot = Mutex::new(None);
|
||||
let get = || {
|
||||
cached_client(
|
||||
&slot,
|
||||
|proxy| {
|
||||
BUILDS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
|
||||
build(proxy)
|
||||
},
|
||||
system,
|
||||
)
|
||||
.unwrap()
|
||||
};
|
||||
assert_eq!(ide_core::proxy_settings::proxy().mode, ProxyMode::Auto);
|
||||
get();
|
||||
get();
|
||||
assert_eq!(BUILDS.load(std::sync::atomic::Ordering::SeqCst), 1);
|
||||
// A proxy app switches the system proxy on after launch.
|
||||
*SYSTEM.lock() = "Matcher { https: 127.0.0.1:7890 }".into();
|
||||
get();
|
||||
get();
|
||||
assert_eq!(BUILDS.load(std::sync::atomic::Ordering::SeqCst), 2);
|
||||
}
|
||||
use ide_core::proxy_settings::ProxyKind;
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::net::TcpListener;
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import { expect, stubDesktop, test } from "./fixtures";
|
||||
|
||||
test("the floating navigation list stays beside the visible segment and scrolls to keyboard selection", async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
await page.setViewportSize({ width: 600, height: 560 });
|
||||
const folder = "billing";
|
||||
const parent =
|
||||
"/dev/acme-api/quarterly-settlement-and-reconciliation/merchant-accounts-with-exchange-rate-adjustments";
|
||||
const directory = `${parent}/${folder}`;
|
||||
const filename = "SettlementSummary.ts";
|
||||
const path = `${directory}/${filename}`;
|
||||
const long = "QuarterlyReconciliationForPendingSettlementAndCrossBorderMerchantAdjustments.ts";
|
||||
const last = "YearEndTotals.ts";
|
||||
await page.evaluate(async (path) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend)).docBackend().files.set(path, "export const pending = 1;\n");
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
}, path);
|
||||
await expect(page.locator(".cm-content")).toContainText("pending");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ directory, filename, long, last }) => {
|
||||
window.__ipc.handlers.fs_read_dir = ({ path }) =>
|
||||
path === directory
|
||||
? ["archive", long, ...Array.from({ length: 24 }, (_, i) => `Report-${i + 1}.ts`), filename, last].map(
|
||||
(name) => ({
|
||||
name,
|
||||
path: `${directory}/${name}`,
|
||||
kind: name === "archive" ? "dir" : "file",
|
||||
size: name === "archive" ? 0 : 1,
|
||||
}),
|
||||
)
|
||||
: [];
|
||||
const actions = "/src/platform/actions.ts";
|
||||
await (await import(/* @vite-ignore */ actions)).executeAction("navigate.navigationBar");
|
||||
},
|
||||
{ directory, filename, long, last },
|
||||
);
|
||||
const bar = page.getByRole("toolbar", { name: "Navigation bar" });
|
||||
await expect(bar).toBeVisible();
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
const segment = bar.getByRole("button", { name: folder, exact: true });
|
||||
await expect(segment).toHaveAttribute("aria-current", "location");
|
||||
const barBounds = (await bar.boundingBox())!;
|
||||
await page.keyboard.press("ArrowDown");
|
||||
const list = page.getByRole("listbox", { name: "Children" });
|
||||
await expect(list).toBeVisible();
|
||||
await expect(list.getByRole("option", { name: filename, exact: true })).toHaveAttribute("aria-selected", "true");
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const bounds = (await list.boundingBox())!;
|
||||
return bounds.x >= 5 && bounds.x + bounds.width <= 595;
|
||||
})
|
||||
.toBe(true);
|
||||
expect((await list.boundingBox())!.y).toBeGreaterThanOrEqual(barBounds.y + barBounds.height - 4);
|
||||
expect((await bar.boundingBox())!.height).toBeCloseTo(barBounds.height);
|
||||
|
||||
await page.keyboard.press("Home");
|
||||
const folderRow = list.getByRole("option", { name: "archive" });
|
||||
await expect(folderRow).toHaveAttribute("aria-selected", "true");
|
||||
await expect(folderRow).toBeInViewport({ ratio: 1 });
|
||||
await expect(list.getByRole("option", { name: long, exact: true }).getByTitle(long)).toBeVisible();
|
||||
expect(await list.evaluate((el) => el.scrollWidth - el.clientWidth)).toBeLessThanOrEqual(1);
|
||||
await page.keyboard.press("End");
|
||||
const lastRow = list.getByRole("option", { name: last, exact: true });
|
||||
await expect(lastRow).toHaveAttribute("aria-selected", "true");
|
||||
await expect(lastRow).toBeInViewport({ ratio: 1 });
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(list).toBeHidden();
|
||||
await expect(bar).toBeFocused();
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(bar).toBeHidden();
|
||||
});
|
||||
|
||||
for (const position of ["top", "statusBar"] as const) {
|
||||
test(`the ${position} navigation list opens toward the editor and keeps folder navigation`, async ({
|
||||
workbench: page,
|
||||
}) => {
|
||||
const directory = "/dev/acme-api/src";
|
||||
const path = `${directory}/Overview.ts`;
|
||||
await page.evaluate(async (path) => {
|
||||
const backend = "/src/editor/core/backend.ts";
|
||||
(await import(/* @vite-ignore */ backend)).docBackend().files.set(path, "export const overview = 1;\n");
|
||||
const service = "/src/workbench/contributions.ts";
|
||||
await (await import(/* @vite-ignore */ service)).editorService().openFile(path);
|
||||
}, path);
|
||||
await expect(page.locator(".cm-content")).toContainText("overview");
|
||||
await stubDesktop(page);
|
||||
await page.evaluate(
|
||||
async ({ directory, position }) => {
|
||||
const archive = `${directory}/archive`;
|
||||
window.__ipc.handlers.fs_read_dir = ({ path }) =>
|
||||
path === directory
|
||||
? [
|
||||
{ path: archive, name: "archive", kind: "dir", size: 0 },
|
||||
{ path: `${directory}/Overview.ts`, name: "Overview.ts", kind: "file", size: 1 },
|
||||
]
|
||||
: path === archive
|
||||
? [{ path: `${archive}/Previous.ts`, name: "Previous.ts", kind: "file", size: 1 }]
|
||||
: [];
|
||||
const source = await (await fetch("/src/workbench/Workbench.tsx")).text();
|
||||
const project = source.match(/["'](\/src\/platform\/project\.ts(?:\?[^"']+)?)["']/)?.[1];
|
||||
if (!project) throw new Error("Missing project store");
|
||||
const { useProject } = await import(/* @vite-ignore */ project);
|
||||
const settings = useProject.getState().settings;
|
||||
useProject.setState({
|
||||
settings: { ...settings, appearance: { ...settings?.appearance, navigationBar: position } },
|
||||
});
|
||||
},
|
||||
{ directory, position },
|
||||
);
|
||||
const anchor = page
|
||||
.getByRole("navigation", { name: "Breadcrumbs" })
|
||||
.getByRole("button", { name: "src", exact: true });
|
||||
await anchor.click();
|
||||
const list = page.getByRole("listbox", { name: "src", exact: true });
|
||||
const archive = list.getByRole("option", { name: "archive" });
|
||||
await expect(archive).toHaveAttribute("aria-selected", "true");
|
||||
await expect(list).toBeFocused();
|
||||
await expect
|
||||
.poll(async () => {
|
||||
const bounds = (await anchor.boundingBox())!;
|
||||
const popup = (await list.boundingBox())!;
|
||||
return position === "top" ? popup.y >= bounds.y + bounds.height : popup.y + popup.height <= bounds.y;
|
||||
})
|
||||
.toBe(true);
|
||||
await page.keyboard.press("ArrowRight");
|
||||
const nested = page.getByRole("listbox", { name: "archive" });
|
||||
await expect(nested.getByRole("option", { name: "Previous.ts" })).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("ArrowLeft");
|
||||
await expect(archive).toHaveAttribute("aria-selected", "true");
|
||||
await page.keyboard.press("Escape");
|
||||
await expect(list).toBeHidden();
|
||||
await expect(anchor).toBeFocused();
|
||||
});
|
||||
}
|
||||
@@ -1,18 +1,22 @@
|
||||
.popup {
|
||||
max-width: min(90vw, 900px);
|
||||
padding: 0;
|
||||
.barPopup,
|
||||
.childPopup {
|
||||
width: max-content;
|
||||
overflow: hidden;
|
||||
font-size: var(--fs-chrome);
|
||||
}
|
||||
.root {
|
||||
outline: none;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
max-width: 900px;
|
||||
}
|
||||
.bar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0;
|
||||
padding: 3px 4px;
|
||||
min-width: 0;
|
||||
padding: var(--space-1);
|
||||
overflow-x: auto;
|
||||
scrollbar-width: thin;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.segmentWrap {
|
||||
@@ -22,20 +26,20 @@
|
||||
}
|
||||
.sep {
|
||||
color: var(--fg-faint);
|
||||
margin: 0 1px;
|
||||
margin: 0 var(--space-0-5);
|
||||
}
|
||||
.segment {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
gap: var(--space-1);
|
||||
max-width: min(288px, 55vw);
|
||||
height: var(--h-control-small);
|
||||
padding: 0 5px;
|
||||
padding: 0 var(--space-1-5);
|
||||
border: none;
|
||||
border-radius: var(--radius-small);
|
||||
background: transparent;
|
||||
color: var(--fg);
|
||||
font: inherit;
|
||||
font-size: var(--fs-ui);
|
||||
cursor: default;
|
||||
}
|
||||
.segment:hover {
|
||||
@@ -46,22 +50,28 @@
|
||||
background: var(--bg-list-selected);
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.childPopup {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
min-width: min(200px, calc(100vw - 12px));
|
||||
}
|
||||
.list {
|
||||
align-self: flex-start;
|
||||
min-width: 200px;
|
||||
max-height: 360px;
|
||||
overflow-y: auto;
|
||||
margin: 0 4px 4px;
|
||||
padding: 4px;
|
||||
border-top: 1px solid var(--border-popup);
|
||||
min-height: 0;
|
||||
min-width: 0;
|
||||
max-width: min(480px, calc(100vw - 14px));
|
||||
max-height: min(360px, 62vh);
|
||||
padding: var(--space-1);
|
||||
overflow: auto;
|
||||
overflow-x: hidden;
|
||||
outline: none;
|
||||
}
|
||||
.row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
gap: var(--space-1);
|
||||
height: var(--h-list-row);
|
||||
padding: 0 6px;
|
||||
border-radius: var(--radius-row);
|
||||
padding: 0 var(--space-2);
|
||||
border-radius: var(--radius-selection);
|
||||
color: var(--fg);
|
||||
white-space: nowrap;
|
||||
}
|
||||
@@ -70,31 +80,31 @@
|
||||
color: var(--fg-strong);
|
||||
}
|
||||
.rowLabel {
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
.rowIcon {
|
||||
flex: none;
|
||||
}
|
||||
.empty {
|
||||
padding: 4px 6px;
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.childList {
|
||||
min-width: 200px;
|
||||
max-height: 360px;
|
||||
overflow-y: auto;
|
||||
padding: 4px;
|
||||
outline: none;
|
||||
}
|
||||
.childHeader {
|
||||
display: flex;
|
||||
flex: none;
|
||||
align-items: center;
|
||||
gap: var(--space-1-5);
|
||||
height: var(--h-list-row);
|
||||
padding: 0 6px;
|
||||
margin-bottom: 2px;
|
||||
gap: var(--space-1);
|
||||
max-width: min(480px, calc(100vw - 14px));
|
||||
height: calc(var(--h-list-row) + var(--space-2));
|
||||
padding: 0 var(--space-3);
|
||||
border-bottom: 1px solid var(--border-popup);
|
||||
color: var(--fg-muted);
|
||||
}
|
||||
.rowChevron {
|
||||
flex: none;
|
||||
margin-left: auto;
|
||||
color: var(--fg-faint);
|
||||
}
|
||||
@@ -4,13 +4,13 @@
|
||||
* (folder contents, file / symbol members); Enter on a child opens it (a
|
||||
* folder becomes the next segment), Escape closes the list, then the bar.
|
||||
*/
|
||||
import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import { useEffect, useId, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent } from "react";
|
||||
import clsx from "clsx";
|
||||
import { create } from "zustand";
|
||||
import { call, commands, isTauri, type OutlineItem } from "@/platform/ipc";
|
||||
import { projectFolder, useProject } from "@/platform/project";
|
||||
import { useProjectViewLead } from "@/workbench/contributions";
|
||||
import { Icon, Popup, T } from "@/ui";
|
||||
import { Icon, listNavigate, Popup, revealHorizontally, revealVertically, T } from "@/ui";
|
||||
import { editorController, useEditorStatus } from "../controller";
|
||||
import { useOutline } from "../model/document";
|
||||
import { symbolChain } from "./outline";
|
||||
@@ -64,6 +64,74 @@ function anchorPoint(): { x: number; y: number } {
|
||||
return r ? { x: r.left + 8, y: r.top + 4 } : { x: 80, y: 80 };
|
||||
}
|
||||
|
||||
function NavChildList({
|
||||
label,
|
||||
id,
|
||||
items,
|
||||
active,
|
||||
onSelect,
|
||||
onChoose,
|
||||
onKeyDown,
|
||||
}: {
|
||||
label: string;
|
||||
id: string;
|
||||
items: readonly NavChild[] | null;
|
||||
active: number;
|
||||
onSelect: (index: number) => void;
|
||||
onChoose: (child: NavChild) => void;
|
||||
onKeyDown?: (e: KeyboardEvent) => void;
|
||||
}) {
|
||||
const ref = useRef<HTMLDivElement>(null);
|
||||
useLayoutEffect(() => {
|
||||
const scroller = ref.current;
|
||||
const row = scroller?.querySelector<HTMLElement>('[aria-selected="true"]');
|
||||
if (!scroller || !row) return;
|
||||
const reveal = () => revealVertically(scroller, row);
|
||||
reveal();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const resize = new ResizeObserver(reveal);
|
||||
resize.observe(scroller);
|
||||
return () => resize.disconnect();
|
||||
}, [active, items]);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
id={id}
|
||||
className={styles.list}
|
||||
role="listbox"
|
||||
aria-label={label}
|
||||
aria-activedescendant={items?.[active] ? `${id}-${active}` : undefined}
|
||||
tabIndex={0}
|
||||
data-autofocus
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{items?.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>Nothing here</T>
|
||||
</div>
|
||||
)}
|
||||
{items?.map((child, i) => (
|
||||
<div
|
||||
key={`${child.path}:${child.label}:${i}`}
|
||||
id={`${id}-${i}`}
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
className={clsx(styles.row, i === active && styles.rowActive)}
|
||||
onMouseEnter={() => onSelect(i)}
|
||||
onClick={() => onChoose(child)}
|
||||
>
|
||||
<Icon name={iconOf(child)} size={16} className={styles.rowIcon} />
|
||||
<span className={styles.rowLabel} title={child.label}>
|
||||
{child.label}
|
||||
</span>
|
||||
{child.kind === "dir" && <Icon name="chevron-right" size={12} className={styles.rowChevron} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function NavBar({ path, line, col, directory }: { path: string; line: number; col: number; directory: boolean }) {
|
||||
const project = useProject((s) => s.project);
|
||||
const outline = useOutline((s) => s[path]);
|
||||
@@ -77,11 +145,19 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
const [active, setActive] = useState(() =>
|
||||
Math.max(0, directory ? initial.length - 1 : initial.findIndex((s) => s.kind === "file")),
|
||||
);
|
||||
const [list, setList] = useState<{ seg: number; items: NavChild[]; active: number; left: number } | null>(null);
|
||||
const [list, setList] = useState<{ seg: number; items: NavChild[]; active: number } | null>(null);
|
||||
const [childAnchor, setChildAnchor] = useState<HTMLButtonElement | null>(null);
|
||||
const listId = useId();
|
||||
const [anchor] = useState(anchorPoint);
|
||||
const strip = useRef<HTMLDivElement>(null);
|
||||
const buttons = useRef<Array<HTMLButtonElement | null>>([]);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const request = useRef(0);
|
||||
const listSegment = list?.seg;
|
||||
|
||||
const closeList = () => {
|
||||
request.current++;
|
||||
setList(null);
|
||||
};
|
||||
|
||||
const openList = async (index: number, segs = segments) => {
|
||||
const seg = segs[index];
|
||||
@@ -92,7 +168,7 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
// Start on the child that leads to the next segment, like IDEA.
|
||||
const next = segs[index + 1];
|
||||
const at = next ? items.findIndex((c) => c.path === next.path && c.label === next.label) : -1;
|
||||
setList({ seg: index, items, active: Math.max(0, at), left: buttons.current[index]?.offsetLeft ?? 0 });
|
||||
setList({ seg: index, items, active: Math.max(0, at) });
|
||||
};
|
||||
|
||||
const choose = (child: NavChild) => {
|
||||
@@ -125,15 +201,14 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
let handled = true;
|
||||
if (e.key === "ArrowLeft") move(-1);
|
||||
else if (e.key === "ArrowRight") move(1);
|
||||
else if (e.key === "ArrowDown" && !list) void openList(active);
|
||||
else if (e.key === "ArrowDown" && list)
|
||||
setList({ ...list, active: Math.min(list.items.length - 1, list.active + 1) });
|
||||
else if (e.key === "ArrowUp" && list) setList({ ...list, active: Math.max(0, list.active - 1) });
|
||||
else if (e.key === "Enter" && list) {
|
||||
const child = list.items[list.active];
|
||||
if (child) choose(child);
|
||||
} else if (e.key === "Enter") void openList(active);
|
||||
else if (e.key === "Escape" && list) setList(null);
|
||||
else if (list) {
|
||||
const next = listNavigate(e.key, list);
|
||||
if (next !== null) setList({ ...list, active: next });
|
||||
else if (e.key === "Enter") {
|
||||
const child = list.items[list.active];
|
||||
if (child) choose(child);
|
||||
} else handled = false;
|
||||
} else if (e.key === "ArrowDown" || e.key === "Enter") void openList(active);
|
||||
else handled = false;
|
||||
if (handled) {
|
||||
e.preventDefault();
|
||||
@@ -142,11 +217,19 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
};
|
||||
|
||||
useLayoutEffect(() => {
|
||||
buttons.current[active]?.scrollIntoView?.({ block: "nearest", inline: "nearest" });
|
||||
}, [active]);
|
||||
useEffect(() => {
|
||||
listRef.current?.querySelector<HTMLElement>('[aria-selected="true"]')?.scrollIntoView?.({ block: "nearest" });
|
||||
}, [list]);
|
||||
const row = strip.current;
|
||||
const current = buttons.current[active];
|
||||
if (!row || !current) return;
|
||||
const reveal = () => revealHorizontally(row, current);
|
||||
reveal();
|
||||
if (typeof ResizeObserver === "undefined") return;
|
||||
const resize = new ResizeObserver(reveal);
|
||||
resize.observe(row);
|
||||
return () => resize.disconnect();
|
||||
}, [active, segments]);
|
||||
useLayoutEffect(() => {
|
||||
setChildAnchor(listSegment === undefined ? null : (buttons.current[listSegment] ?? null));
|
||||
}, [listSegment, segments]);
|
||||
|
||||
return (
|
||||
<Popup
|
||||
@@ -156,7 +239,7 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
offset={0}
|
||||
onClose={close}
|
||||
aria-label="Navigation bar"
|
||||
className={styles.popup}
|
||||
className={styles.barPopup}
|
||||
>
|
||||
<div
|
||||
className={styles.root}
|
||||
@@ -166,7 +249,7 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
role="toolbar"
|
||||
aria-label={tx("Navigation bar")}
|
||||
>
|
||||
<div className={styles.bar}>
|
||||
<div className={styles.bar} ref={strip}>
|
||||
{segments.map((s, i) => (
|
||||
<span key={`${i}:${s.path}:${s.label}`} className={styles.segmentWrap}>
|
||||
{i > 0 && <Icon name="chevron-right" size={12} className={styles.sep} />}
|
||||
@@ -176,44 +259,39 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
tabIndex={-1}
|
||||
className={clsx(styles.segment, i === active && styles.active)}
|
||||
aria-current={i === active ? "location" : undefined}
|
||||
aria-haspopup="listbox"
|
||||
aria-expanded={i === listSegment}
|
||||
aria-controls={i === listSegment ? listId : undefined}
|
||||
title={s.label}
|
||||
onClick={() => {
|
||||
setActive(i);
|
||||
void openList(i);
|
||||
}}
|
||||
>
|
||||
<Icon name={iconOf(s)} size={14} />
|
||||
<span>{s.label}</span>
|
||||
<Icon name={iconOf(s)} size={14} className={styles.rowIcon} />
|
||||
<span className={styles.rowLabel}>{s.label}</span>
|
||||
</button>
|
||||
</span>
|
||||
))}
|
||||
</div>
|
||||
{list && (
|
||||
<div
|
||||
ref={listRef}
|
||||
className={styles.list}
|
||||
style={{ marginLeft: list.left }}
|
||||
role="listbox"
|
||||
{list && childAnchor && (
|
||||
<Popup
|
||||
open
|
||||
anchor={childAnchor}
|
||||
placement="bottom-start"
|
||||
onClose={closeList}
|
||||
aria-label={tx("Children")}
|
||||
className={styles.childPopup}
|
||||
>
|
||||
{list.items.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>Nothing here</T>
|
||||
</div>
|
||||
)}
|
||||
{list.items.map((c, i) => (
|
||||
<div
|
||||
key={`${c.path}:${c.label}:${i}`}
|
||||
role="option"
|
||||
aria-selected={i === list.active}
|
||||
className={clsx(styles.row, i === list.active && styles.rowActive)}
|
||||
onMouseEnter={() => setList({ ...list, active: i })}
|
||||
onClick={() => choose(c)}
|
||||
>
|
||||
<Icon name={iconOf(c)} size={14} />
|
||||
<span className={styles.rowLabel}>{c.label}</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<NavChildList
|
||||
id={listId}
|
||||
label={tx("Children")}
|
||||
items={list.items}
|
||||
active={list.active}
|
||||
onSelect={(i) => setList({ ...list, active: i })}
|
||||
onChoose={choose}
|
||||
/>
|
||||
</Popup>
|
||||
)}
|
||||
</div>
|
||||
</Popup>
|
||||
@@ -228,10 +306,12 @@ function NavBar({ path, line, col, directory }: { path: string; line: number; co
|
||||
export function NavChildrenPopup({
|
||||
segment,
|
||||
anchor,
|
||||
openAbove = true,
|
||||
onClose,
|
||||
}: {
|
||||
segment: NavSegment;
|
||||
anchor: HTMLElement;
|
||||
openAbove?: boolean;
|
||||
onClose: () => void;
|
||||
}) {
|
||||
const [stack, setStack] = useState<NavSegment[]>([segment]);
|
||||
@@ -239,7 +319,7 @@ export function NavChildrenPopup({
|
||||
const outline = useOutline((s) => s[top.path]);
|
||||
const [loaded, setLoaded] = useState<{ top: NavSegment; items: NavChild[] } | null>(null);
|
||||
const [active, setActive] = useState(0);
|
||||
const listRef = useRef<HTMLDivElement>(null);
|
||||
const listId = useId();
|
||||
const items = loaded?.top === top ? loaded.items : null;
|
||||
|
||||
useEffect(() => {
|
||||
@@ -255,10 +335,6 @@ export function NavChildrenPopup({
|
||||
alive = false;
|
||||
};
|
||||
}, [top, outline]);
|
||||
useEffect(() => {
|
||||
listRef.current?.querySelector<HTMLElement>('[aria-selected="true"]')?.scrollIntoView?.({ block: "nearest" });
|
||||
}, [active, items]);
|
||||
|
||||
const choose = (child: NavChild) => {
|
||||
if (child.kind === "dir") return setStack((s) => [...s, { kind: "dir", path: child.path, label: child.label }]);
|
||||
onClose();
|
||||
@@ -270,10 +346,9 @@ export function NavChildrenPopup({
|
||||
};
|
||||
|
||||
const onKeyDown = (e: KeyboardEvent) => {
|
||||
const n = items?.length ?? 0;
|
||||
const next = items ? listNavigate(e.key, { items, active, wrap: true }) : null;
|
||||
let handled = true;
|
||||
if (e.key === "ArrowDown" && n) setActive((a) => (a + 1) % n);
|
||||
else if (e.key === "ArrowUp" && n) setActive((a) => (a - 1 + n) % n);
|
||||
if (next !== null) setActive(next);
|
||||
else if (e.key === "Enter" || (e.key === "ArrowRight" && items?.[active]?.kind === "dir")) {
|
||||
const child = items?.[active];
|
||||
if (child) choose(child);
|
||||
@@ -286,44 +361,31 @@ export function NavChildrenPopup({
|
||||
};
|
||||
|
||||
return (
|
||||
<Popup open anchor={anchor} placement="top-start" onClose={onClose} aria-label={top.label} className={styles.popup}>
|
||||
<div
|
||||
ref={listRef}
|
||||
className={styles.childList}
|
||||
role="listbox"
|
||||
aria-label={top.label}
|
||||
tabIndex={0}
|
||||
data-autofocus
|
||||
aria-activedescendant={items?.length ? `navbar-child-${active}` : undefined}
|
||||
<Popup
|
||||
open
|
||||
anchor={anchor}
|
||||
placement={openAbove ? "top-start" : "bottom-start"}
|
||||
onClose={onClose}
|
||||
aria-label={top.label}
|
||||
className={styles.childPopup}
|
||||
>
|
||||
{stack.length > 1 && (
|
||||
<div className={styles.childHeader}>
|
||||
<Icon name={iconOf(top)} size={16} className={styles.rowIcon} />
|
||||
<span className={styles.rowLabel} title={top.label}>
|
||||
{top.label}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
<NavChildList
|
||||
id={listId}
|
||||
label={top.label}
|
||||
items={items}
|
||||
active={active}
|
||||
onSelect={setActive}
|
||||
onChoose={choose}
|
||||
onKeyDown={onKeyDown}
|
||||
>
|
||||
{stack.length > 1 && (
|
||||
<div className={styles.childHeader}>
|
||||
<Icon name={iconOf(top)} size={14} />
|
||||
<span className={styles.rowLabel}>{top.label}</span>
|
||||
</div>
|
||||
)}
|
||||
{items?.length === 0 && (
|
||||
<div className={styles.empty}>
|
||||
<T>Nothing here</T>
|
||||
</div>
|
||||
)}
|
||||
{items?.map((c, i) => (
|
||||
<div
|
||||
key={`${c.path}:${c.label}:${i}`}
|
||||
id={`navbar-child-${i}`}
|
||||
role="option"
|
||||
aria-selected={i === active}
|
||||
className={clsx(styles.row, i === active && styles.rowActive)}
|
||||
onMouseEnter={() => setActive(i)}
|
||||
onClick={() => choose(c)}
|
||||
>
|
||||
<Icon name={iconOf(c)} size={14} />
|
||||
<span className={styles.rowLabel}>{c.label}</span>
|
||||
{c.kind === "dir" && <Icon name="chevron-right" size={12} className={styles.rowChevron} />}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
/>
|
||||
</Popup>
|
||||
);
|
||||
}
|
||||
@@ -226,7 +226,15 @@ function BreadcrumbStrip({
|
||||
}
|
||||
|
||||
/** A row of crumbs; a segment with `nav` opens a popup of its children. */
|
||||
function CrumbNav({ segments, className }: { segments: Crumb[]; className?: string }) {
|
||||
function CrumbNav({
|
||||
segments,
|
||||
className,
|
||||
inStatusBar,
|
||||
}: {
|
||||
segments: Crumb[];
|
||||
className?: string;
|
||||
inStatusBar: boolean;
|
||||
}) {
|
||||
const [popup, setPopup] = useState<{ nav: NavSegment; anchor: HTMLElement } | null>(null);
|
||||
return (
|
||||
<BreadcrumbStrip
|
||||
@@ -261,7 +269,15 @@ function CrumbNav({ segments, className }: { segments: Crumb[]; className?: stri
|
||||
</Fragment>
|
||||
);
|
||||
})}
|
||||
{popup && <NavChildrenPopup segment={popup.nav} anchor={popup.anchor} onClose={() => setPopup(null)} />}
|
||||
{popup && (
|
||||
<NavChildrenPopup
|
||||
key={`${popup.nav.kind}:${popup.nav.path}:${popup.nav.label}`}
|
||||
segment={popup.nav}
|
||||
anchor={popup.anchor}
|
||||
openAbove={inStatusBar}
|
||||
onClose={() => setPopup(null)}
|
||||
/>
|
||||
)}
|
||||
</BreadcrumbStrip>
|
||||
);
|
||||
}
|
||||
@@ -311,7 +327,7 @@ export function Breadcrumbs({ className, inStatusBar = false }: { className?: st
|
||||
segments.push(projectCrumb(project ?? currentProject));
|
||||
}
|
||||
if (!segments.length) return null;
|
||||
return <CrumbNav segments={segments} className={className ?? styles.status} />;
|
||||
return <CrumbNav segments={segments} className={className ?? styles.status} inStatusBar={inStatusBar} />;
|
||||
}
|
||||
|
||||
/** The status bar instance of the navigation bar; renders only for `statusBar`. */
|
||||
|
||||
@@ -112,6 +112,7 @@ const TEMPLATE_CONTEXT_KEY = "openideaTemplateContexts";
|
||||
|
||||
import { formatElapsed } from "./resultView";
|
||||
import { SQL_LANGUAGE } from "./sqlLanguage";
|
||||
import { jdbcDialect } from "./vendors";
|
||||
export { SQL_LANGUAGE };
|
||||
const ROW_LIMITS = ["100", "500", "1000", "5000", "50000"];
|
||||
|
||||
@@ -1069,6 +1070,9 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl
|
||||
const current = id ? databaseRequest(id) : projectRequest();
|
||||
const source = sourceById(id);
|
||||
const driver: DbDriver = source?.driver ?? "sqlite";
|
||||
// A custom JDBC source (`driver: "jdbc"`) says nothing about how its server folds
|
||||
// identifiers; its URL does (`jdbc:oracle:thin:@…`). Quoting follows that dialect.
|
||||
const dialect = driver === "jdbc" ? jdbcDialect(source?.url) : null;
|
||||
const model = id ? (useDatabase.getState().completion[id] ?? null) : null;
|
||||
if (id && !model) void loadCompletion(id);
|
||||
// Unqualified names resolve in the console's active schema (IDEA's schema dropdown).
|
||||
@@ -1091,6 +1095,7 @@ export function completionSource(path: string, sql: SqlText = WHOLE_FILE): Compl
|
||||
model: scoped,
|
||||
analysis,
|
||||
driver,
|
||||
dialect,
|
||||
sourceName: source?.name ?? undefined,
|
||||
catalog: cataloged ? catalogOf(id) : undefined,
|
||||
});
|
||||
|
||||
@@ -63,20 +63,26 @@ export function shouldAutoCompleteSql(analysis: Analysis): boolean {
|
||||
|
||||
const MAX_ALL_COLUMNS = 3000;
|
||||
|
||||
/** `name`, quoted when the dialect needs it (case, characters, reserved words). */
|
||||
export function quoteIdent(name: string, driver: DbDriver): string {
|
||||
/**
|
||||
* `name`, quoted when the dialect needs it (case, characters, reserved words).
|
||||
* A `jdbc` source quotes by the dialect its URL speaks (`dialect`); without one, only
|
||||
* what is not a plain word is quoted, which is right for the dialects that fold case
|
||||
* neither way.
|
||||
*/
|
||||
export function quoteIdent(name: string, driver: DbDriver, dialect?: DbDriver | null): string {
|
||||
const d = driver === "jdbc" && dialect ? dialect : driver;
|
||||
const plain =
|
||||
driver === "postgres"
|
||||
d === "postgres"
|
||||
? /^[a-z_][a-z0-9_$]*$/
|
||||
: // Oracle and Snowflake fold unquoted names to upper case; a lower-case name must stay quoted.
|
||||
driver === "oracle" || driver === "snowflake"
|
||||
d === "oracle" || d === "snowflake"
|
||||
? /^[A-Z_][A-Z0-9_$]*$/
|
||||
: driver === "clickhouse"
|
||||
: d === "clickhouse"
|
||||
? /^[A-Za-z_][A-Za-z0-9_]*$/
|
||||
: /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
||||
if (plain.test(name) && !isReserved(name, driver)) return name;
|
||||
if (driver === "clickhouse") return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
||||
const q = driver === "mysql" ? "`" : '"';
|
||||
if (plain.test(name) && !isReserved(name, d)) return name;
|
||||
if (d === "clickhouse") return `"${name.replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
|
||||
const q = d === "mysql" ? "`" : '"';
|
||||
return q + name.split(q).join(q + q) + q;
|
||||
}
|
||||
|
||||
@@ -121,11 +127,20 @@ export interface CompletionInput {
|
||||
model: DbCompletion | null;
|
||||
analysis: Analysis;
|
||||
driver: DbDriver;
|
||||
/** The dialect a `jdbc` source speaks, from its URL (`jdbcDialect`); quoting follows it. */
|
||||
dialect?: DbDriver | null;
|
||||
/** Data source name, shown next to tables like IDEA does. */
|
||||
sourceName?: string;
|
||||
}
|
||||
|
||||
export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog }: CompletionInput): SqlCandidate[] {
|
||||
export function sqlCandidates({
|
||||
model,
|
||||
analysis: a,
|
||||
driver,
|
||||
dialect,
|
||||
sourceName,
|
||||
catalog,
|
||||
}: CompletionInput): SqlCandidate[] {
|
||||
const eq = nameMatcher(driver);
|
||||
const ctx = a.context;
|
||||
if (ctx.kind === "none") return [];
|
||||
@@ -135,7 +150,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog
|
||||
const kw = (k: string) => (lower ? k.toLowerCase() : k);
|
||||
const tables = model?.tables ?? [];
|
||||
const defaultSchema = model?.defaultSchema ?? "";
|
||||
const exact = (n: string) => quoteIdent(n, driver);
|
||||
const exact = (n: string) => quoteIdent(n, driver, dialect);
|
||||
// Snowflake folds unquoted names to upper case, so a name typed in lower case may stay lower case.
|
||||
const lowerQualifier = !!a.qualifier?.length && a.qualifier.every((p) => /[a-z]/.test(p) && p === p.toLowerCase());
|
||||
// What is typed decides: the name's own prefix, else the qualifier before it, else the statement's keywords.
|
||||
@@ -270,7 +285,7 @@ export function sqlCandidates({ model, analysis: a, driver, sourceName, catalog
|
||||
|
||||
case "table": {
|
||||
const taken = new Set(a.refs.flatMap((r) => [refName(r).toLowerCase(), r.name.toLowerCase()]));
|
||||
if (ctx.join) out.push(...joinCandidates(a, model, driver, taken, kw));
|
||||
if (ctx.join) out.push(...joinCandidates(a, model, driver, dialect, taken, kw));
|
||||
for (const c of a.ctes) out.push({ label: c.name, kind: "table", tail: "(CTE)", boost: 40 });
|
||||
const schemas = new Set<string>();
|
||||
for (const t of tables) {
|
||||
@@ -472,13 +487,14 @@ function joinCandidates(
|
||||
a: Analysis,
|
||||
model: DbCompletion | null,
|
||||
driver: DbDriver,
|
||||
dialect: DbDriver | null | undefined,
|
||||
taken: Set<string>,
|
||||
kw: Kw,
|
||||
): SqlCandidate[] {
|
||||
if (!model) return [];
|
||||
const eq = nameMatcher(driver);
|
||||
const out: SqlCandidate[] = [];
|
||||
const q = (n: string) => quoteIdent(n, driver);
|
||||
const q = (n: string) => quoteIdent(n, driver, dialect);
|
||||
const seen = new Set<string>();
|
||||
const local = (s: string) => eq(s, model.defaultSchema) || driver === "sqlite";
|
||||
const tableText = (schema: string, name: string) => (local(schema) ? q(name) : `${q(schema)}.${q(name)}`);
|
||||
|
||||
@@ -8,6 +8,7 @@ import { identName, inLiteral, lex } from "./lexer";
|
||||
import { DATA_TYPES, statementStarters } from "./dialect";
|
||||
import { bindParams, findParams } from "./params";
|
||||
import { SqlResolver } from "./resolve";
|
||||
import { jdbcDialect } from "../vendors";
|
||||
|
||||
const col = (name: string, dataType = "INTEGER", primaryKey = false, hasDefault = false) => ({
|
||||
name,
|
||||
@@ -280,6 +281,51 @@ describe("completion candidates", () => {
|
||||
expect(quoteIdent('a"b', "oracle")).toBe('"a""b"');
|
||||
});
|
||||
|
||||
it("quotes a custom JDBC source's names by the dialect its URL speaks", () => {
|
||||
expect(jdbcDialect("jdbc:oracle:thin:@//db.local:1521/ORCL")).toBe("oracle");
|
||||
expect(jdbcDialect("JDBC:Oracle:thin:@db:1521:ORCL")).toBe("oracle");
|
||||
expect(jdbcDialect("jdbc:postgresql://db.local/shop")).toBe("postgres");
|
||||
expect(jdbcDialect("jdbc:MariaDB://db/shop")).toBe("mysql");
|
||||
expect(jdbcDialect("jdbc:sqlserver://db;databaseName=shop")).toBe("sqlServer");
|
||||
expect(jdbcDialect("jdbc:unknown://db/shop")).toBeNull();
|
||||
expect(jdbcDialect("")).toBeNull();
|
||||
expect(jdbcDialect(null)).toBeNull();
|
||||
// Oracle folds unquoted names to upper case, so only an upper-case name stays bare.
|
||||
expect(quoteIdent("MyTable", "jdbc", "oracle")).toBe('"MyTable"');
|
||||
expect(quoteIdent("MYTABLE", "jdbc", "oracle")).toBe("MYTABLE");
|
||||
expect(quoteIdent("mytable", "jdbc", "oracle")).toBe('"mytable"');
|
||||
// Without a dialect, a plain word still stays bare: the source never said which server it is.
|
||||
expect(quoteIdent("MyTable", "jdbc")).toBe("MyTable");
|
||||
expect(quoteIdent("MyTable", "jdbc", null)).toBe("MyTable");
|
||||
const hr: DbCompletion = {
|
||||
defaultSchema: "HR",
|
||||
tables: [
|
||||
{
|
||||
schema: "HR",
|
||||
name: "MyTable",
|
||||
kind: "table",
|
||||
columns: [col("ID", "NUMBER", true), col("fullName", "VARCHAR2")],
|
||||
},
|
||||
],
|
||||
foreignKeys: [],
|
||||
};
|
||||
const tables = sqlCandidates({
|
||||
model: hr,
|
||||
analysis: at("SELECT * FROM |", "jdbc"),
|
||||
driver: "jdbc",
|
||||
dialect: jdbcDialect("jdbc:oracle:thin:@//db.local:1521/ORCL"),
|
||||
});
|
||||
expect(tables.find((c) => c.label === "MyTable")?.insert).toBe('"MyTable"');
|
||||
const columns = sqlCandidates({
|
||||
model: hr,
|
||||
analysis: at("SELECT | FROM MyTable", "jdbc"),
|
||||
driver: "jdbc",
|
||||
dialect: "oracle",
|
||||
});
|
||||
expect(columns.find((c) => c.label === "ID")?.insert).toBe("ID");
|
||||
expect(columns.find((c) => c.label === "fullName")?.insert).toBe('"fullName"');
|
||||
});
|
||||
|
||||
it("offers Snowflake vocabulary and quotes names the server folds to upper case", () => {
|
||||
expect(statementStarters("snowflake")).toEqual(
|
||||
expect.arrayContaining([
|
||||
|
||||
@@ -176,6 +176,15 @@ const SCHEMES: Record<string, string> = {
|
||||
|
||||
export const vendorOfScheme = (scheme: string): DbVendor | undefined => BY_ID.get(SCHEMES[scheme.toLowerCase()] ?? "");
|
||||
|
||||
/**
|
||||
* The dialect a custom JDBC source's URL speaks (`jdbc:oracle:thin:@//db:1521/ORCL` → `oracle`):
|
||||
* its `driver: "jdbc"` says nothing about how the server folds identifiers.
|
||||
*/
|
||||
export function jdbcDialect(url: string | null | undefined): DbDriver | null {
|
||||
const scheme = /^(?:jdbc:)?([a-z][a-z0-9]*):/i.exec((url ?? "").trim())?.[1] ?? "";
|
||||
return vendorOfScheme(scheme)?.driver ?? null;
|
||||
}
|
||||
|
||||
const bracketed = (host: string) => (host.includes(":") && !host.startsWith("[") ? `[${host}]` : host);
|
||||
|
||||
/** The JDBC URL of a data source's fields (the General tab's URL preview). */
|
||||
|
||||
@@ -10,7 +10,15 @@ import {
|
||||
updateBreakpoint,
|
||||
useBreakpoints,
|
||||
} from "../breakpoints/store";
|
||||
import { adoptSession, useExecutionPoint, useDebug, handleDebugEvent, type DebugSession } from "../state";
|
||||
import {
|
||||
adoptSession,
|
||||
selectSession,
|
||||
stopTarget,
|
||||
useExecutionPoint,
|
||||
useDebug,
|
||||
handleDebugEvent,
|
||||
type DebugSession,
|
||||
} from "../state";
|
||||
import { getContext } from "@/platform/context";
|
||||
import styles from "../editor/editor.module.css";
|
||||
|
||||
@@ -314,6 +322,23 @@ describe("session events", () => {
|
||||
expect(getContext().debugSessionActive).toBe(false);
|
||||
});
|
||||
|
||||
it("enables Stop for the selected session tab only (#4738)", () => {
|
||||
adoptSession(80, { name: "server" });
|
||||
adoptSession(81, { name: "client" });
|
||||
selectSession(80);
|
||||
expect(getContext().debugCanStop).toBe(true);
|
||||
expect(stopTarget()?.id).toBe(80);
|
||||
handleDebugEvent(81, { kind: "terminated" });
|
||||
selectSession(81);
|
||||
// The finished session's tab: Stop is off although the server still runs.
|
||||
expect(getContext().debugSessionActive).toBe(true);
|
||||
expect(getContext().debugCanStop).toBe(false);
|
||||
expect(stopTarget()).toBeNull();
|
||||
selectSession(80);
|
||||
expect(getContext().debugCanStop).toBe(true);
|
||||
handleDebugEvent(80, { kind: "terminated" });
|
||||
});
|
||||
|
||||
it("ignores sessions this window did not start, but adopts children of its own", async () => {
|
||||
vi.spyOn(console, "warn").mockImplementation(() => {});
|
||||
adoptSession(90, { name: "app", adapter: "js-debug" });
|
||||
|
||||
@@ -79,6 +79,7 @@ import {
|
||||
startPreparedSession,
|
||||
stopSession,
|
||||
stopAssociatedProcess,
|
||||
stopTarget,
|
||||
useDebug,
|
||||
type DebugSession,
|
||||
} from "./state";
|
||||
@@ -560,9 +561,9 @@ export function registerDebugActions(): () => void {
|
||||
title: "Stop",
|
||||
category: "Debug",
|
||||
icon: "stop",
|
||||
when: "debugSessionActive",
|
||||
when: "debugCanStop",
|
||||
run: () => {
|
||||
const s = activeSession() ?? Object.values(useDebug.getState().sessions).find(isLive);
|
||||
const s = stopTarget();
|
||||
if (s) void stopSession(s.id);
|
||||
},
|
||||
},
|
||||
|
||||
@@ -197,6 +197,13 @@ export function isLive(s: DebugSession | null | undefined): boolean {
|
||||
return !!s && s.status !== "terminated";
|
||||
}
|
||||
|
||||
/** The session the Debug tool window's Stop acts on: the selected one while it runs (any live one when none is selected). */
|
||||
export function stopTarget(): DebugSession | null {
|
||||
const s = activeSession();
|
||||
if (s) return isLive(s) ? s : null;
|
||||
return Object.values(useDebug.getState().sessions).find(isLive) ?? null;
|
||||
}
|
||||
|
||||
/** Whether the session with this id is still there and running, as of now. */
|
||||
export const isLiveSession = (id: DebugSessionId) => isLive(useDebug.getState().sessions[id]);
|
||||
|
||||
@@ -405,6 +412,8 @@ export function publishContext() {
|
||||
});
|
||||
const anyLive = Object.values(useDebug.getState().sessions).some(isLive);
|
||||
setContext("debugSessionActive", anyLive);
|
||||
// Stop acts on the selected session tab, so a finished one doesn't stop another session.
|
||||
setContext("debugCanStop", !!stopTarget());
|
||||
setContext("debugSessionRunning", s?.status === "running");
|
||||
setContext("debugSessionPaused", s?.status === "paused");
|
||||
// Dart and Flutter sessions: Hot Reload / Hot Restart.
|
||||
|
||||
@@ -14,6 +14,7 @@ import { GlobListEditor, Row, Section, Select, Toggle } from "../components/Form
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { usePageContext, useSetting } from "../components/context";
|
||||
import { SdkField, tildify, useDetected, useJdtlsJdk } from "./components";
|
||||
import { isMavenThreadCount } from "./mavenThreads";
|
||||
import styles from "./Sdk.module.css";
|
||||
|
||||
function PathInput({
|
||||
@@ -566,6 +567,7 @@ export function MavenPage() {
|
||||
const [downloadSources, setDownloadSources] = useSetting<boolean>("languages.java.maven.downloadSources");
|
||||
const [updateSnapshots, setUpdateSnapshots] = useSetting<boolean>("languages.java.maven.updateSnapshots");
|
||||
const [threads, setThreads] = useSetting<string>("languages.java.maven.threads");
|
||||
const threadsInvalid = !!threads?.trim() && !isMavenThreadCount(threads);
|
||||
const [activeProfiles, setActiveProfiles] = useSetting<string>("languages.java.maven.activeProfiles");
|
||||
const id = useId();
|
||||
return (
|
||||
@@ -651,12 +653,24 @@ export function MavenPage() {
|
||||
<Row
|
||||
label="Thread count"
|
||||
htmlFor={id}
|
||||
hint="Passed as -T to Maven builds and run configurations: a thread count (4) or a core multiplier (2C, 2.5C) for parallel builds of multi-module projects. Empty runs Maven serially."
|
||||
hint={
|
||||
threadsInvalid ? (
|
||||
<span className={styles.error} role="alert">
|
||||
<T>
|
||||
Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C,
|
||||
2.5C).
|
||||
</T>
|
||||
</span>
|
||||
) : (
|
||||
"Passed as -T to Maven builds and run configurations: a thread count (4) or a core multiplier (2C, 2.5C) for parallel builds of multi-module projects. Empty runs Maven serially."
|
||||
)
|
||||
}
|
||||
>
|
||||
<span className={styles.pathRow}>
|
||||
<Input
|
||||
id={id}
|
||||
mono
|
||||
invalid={threadsInvalid}
|
||||
className={styles.pathInput}
|
||||
value={threads}
|
||||
placeholder="4, 2C"
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
import { expect, it } from "vitest";
|
||||
import { isMavenThreadCount } from "./mavenThreads";
|
||||
|
||||
it("accepts the -T values Maven takes and nothing else (#4743)", () => {
|
||||
for (const ok of ["4", "1C", "2.5C", "0.5C", " 8 "]) expect(isMavenThreadCount(ok), ok).toBe(true);
|
||||
for (const bad of ["0", "0C", "-2", "2c", "2.C", ".5C", "2.5.1C", "four", "4 threads", "C"])
|
||||
expect(isMavenThreadCount(bad), bad).toBe(false);
|
||||
});
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* Whether Maven accepts `value` as `-T`: a thread count (`4`) or a core multiplier with an
|
||||
* optional decimal fraction (`1C`, `2.5C`). Mirrors `MavenSettings::thread_count`, which
|
||||
* leaves any other value out of the command line.
|
||||
*/
|
||||
export function isMavenThreadCount(value: string): boolean {
|
||||
return /^(?:\d+(?:\.\d+)?)C?$/.test(value.trim()) && parseFloat(value) > 0;
|
||||
}
|
||||
@@ -2789,5 +2789,6 @@
|
||||
"Download to {folder} finished with errors": "Download to {folder} finished with errors",
|
||||
"Cannot download to {folder}": "Cannot download to {folder}",
|
||||
"Copy the selected files and folders of a remote project to a folder on this computer": "Copy the selected files and folders of a remote project to a folder on this computer",
|
||||
"{modifier}+Click to only see \"{name}\"": "{modifier}+Click to only see \"{name}\""
|
||||
"{modifier}+Click to only see \"{name}\"": "{modifier}+Click to only see \"{name}\"",
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C)."
|
||||
}
|
||||
@@ -9152,5 +9152,6 @@
|
||||
"Download to {folder} finished with errors": "下载到 {folder} 完成,但有错误",
|
||||
"Cannot download to {folder}": "无法下载到 {folder}",
|
||||
"Copy the selected files and folders of a remote project to a folder on this computer": "把远程项目中选中的文件和文件夹复制到本机的文件夹",
|
||||
"{modifier}+Click to only see \"{name}\"": "{modifier}+点击仅显示“{name}”"
|
||||
"{modifier}+Click to only see \"{name}\"": "{modifier}+点击仅显示“{name}”",
|
||||
"Not a thread count Maven accepts, so builds run serially. Use a number (4) or a core multiplier (2C, 2.5C).": "Maven 不接受这个线程数,构建将串行执行。请填写数字(4)或核数倍数(2C、2.5C)。"
|
||||
}
|
||||
Reference in new issue
Block a user