дзеркало
https://github.com/l0ng-ai/openidea.git
синхронізовано 2026-12-05 09:41:34 +02:00
feat(json): settings page for custom JSON Schema mappings (#6707)
Adds Settings > Languages & Frameworks > JSON Schema Mappings: each mapping has a name, a schema (URL or project file) and the files it applies to (paths or globs, !pattern excludes). Mappings are saved to the project's .openidea/settings.toml by default, or globally, and are sent to vscode-json-language-server and yaml-language-server through workspace/didChangeConfiguration without a restart. Patterns are sent as absolute paths because both servers prefix patterns with **/, built-in SchemaStore entries exclude the files a custom mapping takes so the custom schema replaces rather than adds to them, a project schema file is not validated against itself, and the page warns about patterns that take every JSON or YAML file. Closes #6679 Co-authored-by: wildcatDownstairs <[email protected]>
Цей коміт міститься в:
1 джерело
6b61b15f00
коміт
c3de09be78
14 files changed
+520
-6
No files matched your search
@@ -52,6 +52,8 @@ pub struct Settings {
|
||||
/// Per language server, by name (`rust-analyzer`): launch and protocol
|
||||
/// options on top of the language definition, or a server defined here.
|
||||
pub language_servers: BTreeMap<String, LanguageServerSettings>,
|
||||
/// Languages & Frameworks › JSON Schema Mappings: schemas for JSON and YAML files.
|
||||
pub json_schemas: Vec<JsonSchemaMapping>,
|
||||
/// Tools › Download sources: a mirror prefix for the release archives the installer fetches.
|
||||
pub tool_downloads: ToolDownloadSettings,
|
||||
/// Editor › Inspections profiles.
|
||||
@@ -613,6 +615,7 @@ impl Default for Settings {
|
||||
mcp_server: McpServerSettings::default(),
|
||||
agent_security: AgentSecuritySettings::default(),
|
||||
scopes: Vec::new(),
|
||||
json_schemas: Vec::new(),
|
||||
file_colors: FileColorSettings::default(),
|
||||
database: DatabaseSettings::default(),
|
||||
plugins: BTreeMap::new(),
|
||||
@@ -634,6 +637,17 @@ pub struct NamedScope {
|
||||
pub pattern: String,
|
||||
}
|
||||
|
||||
/// A schema for the JSON and YAML files matching `files`; wins over a built-in SchemaStore mapping.
|
||||
#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct JsonSchemaMapping {
|
||||
pub name: String,
|
||||
/// A URL, or a file path relative to the project.
|
||||
pub schema: String,
|
||||
/// Project-relative paths or glob patterns (`config/*.json`, `**/*.app.yaml`).
|
||||
pub files: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct FileColorSettings {
|
||||
|
||||
@@ -492,7 +492,10 @@ pub fn set_settings(
|
||||
|| key.starts_with("inspections.")
|
||||
|| key == "files"
|
||||
|| key == "files.composeFileOverrides"
|
||||
|| key.starts_with("files.composeFileOverrides.");
|
||||
|| key.starts_with("files.composeFileOverrides.")
|
||||
// JSON Schema Mappings reach the JSON and YAML servers as settings.
|
||||
|| key == "jsonSchemas"
|
||||
|| key.starts_with("jsonSchemas.");
|
||||
let toolchain = ["languages", "tools", "languageServers", "projectStructure"]
|
||||
.iter()
|
||||
.any(|k| key == *k || key.starts_with(&format!("{k}.")));
|
||||
|
||||
@@ -212,6 +212,7 @@ impl Host {
|
||||
let root = member.as_ref().unwrap_or(window_root);
|
||||
ide_sdk::apply::server_launch_overrides(cfg, &effective);
|
||||
ide_sdk::apply::configure_server(cfg, root, server_root, &effective);
|
||||
ide_sdk::json_schemas::configure(cfg, root, &effective.json_schemas);
|
||||
crate::ts_code_style::configure(cfg, server_root, &effective);
|
||||
ide_sdk::apply::configure_vue_module_resolution(cfg, &data_dir);
|
||||
ide_sdk::apply::configure_path_aliases(cfg, server_root, &data_dir);
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
//! Settings › JSON Schema Mappings, sent as vscode-json-language-server's `json.schemas` and
|
||||
//! yaml-language-server's `yaml.schemas`.
|
||||
//!
|
||||
//! Both servers prefix every pattern with `**/`, so a pattern is anchored to the project by making
|
||||
//! it absolute. Both validate a file against every schema whose patterns match it, so the built-in
|
||||
//! SchemaStore mappings exclude (`!pattern`) the files a custom mapping takes.
|
||||
|
||||
use ide_core::settings::JsonSchemaMapping;
|
||||
use ide_language::LanguageServerConfig;
|
||||
use serde_json::{Value, json};
|
||||
use std::path::Path;
|
||||
|
||||
pub const JSON_SERVER: &str = "vscode-json-language-server";
|
||||
pub const YAML_SERVER: &str = "yaml-language-server";
|
||||
|
||||
struct Mapping {
|
||||
url: String,
|
||||
/// Anchored patterns; exclusions (the user's `!pattern`, the schema file itself) come last.
|
||||
patterns: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn configure(cfg: &mut LanguageServerConfig, root: &Path, mappings: &[JsonSchemaMapping]) {
|
||||
if cfg.name != JSON_SERVER && cfg.name != YAML_SERVER {
|
||||
return;
|
||||
}
|
||||
let base = root_glob(root);
|
||||
let anchor = |pattern: &str| {
|
||||
let pattern = pattern.trim_start_matches("./").trim_start_matches('/');
|
||||
match &base {
|
||||
Some(base) => format!("{base}/{pattern}"),
|
||||
None => pattern.to_owned(),
|
||||
}
|
||||
};
|
||||
let mut taken: Vec<String> = Vec::new();
|
||||
let mappings: Vec<Mapping> = mappings
|
||||
.iter()
|
||||
.filter_map(|m| {
|
||||
let schema = m.schema.trim();
|
||||
let mut include = Vec::new();
|
||||
let mut exclude = Vec::new();
|
||||
for file in &m.files {
|
||||
let file = file.trim().replace('\\', "/");
|
||||
match file.strip_prefix('!') {
|
||||
Some(negated) if !negated.trim().is_empty() => exclude.push(anchor(negated.trim())),
|
||||
Some(_) => {}
|
||||
None if !file.is_empty() => include.push(anchor(&file)),
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
if schema.is_empty() || include.is_empty() {
|
||||
return None;
|
||||
}
|
||||
// A schema in the project is not validated against itself.
|
||||
if !schema.contains("://")
|
||||
&& let Ok(own) = root.join(schema).strip_prefix(root)
|
||||
{
|
||||
exclude.push(anchor(&own.to_string_lossy().replace('\\', "/")));
|
||||
}
|
||||
taken.extend(include.iter().cloned());
|
||||
let patterns = include.into_iter().chain(exclude.into_iter().map(|p| format!("!{p}"))).collect();
|
||||
Some(Mapping { url: schema_uri(root, schema), patterns })
|
||||
})
|
||||
.collect();
|
||||
if mappings.is_empty() {
|
||||
return;
|
||||
}
|
||||
let excluded: Vec<Value> = taken.iter().map(|p| json!(format!("!{p}"))).collect();
|
||||
let mut settings = cfg.settings.take().filter(Value::is_object).unwrap_or_else(|| json!({}));
|
||||
if cfg.name == JSON_SERVER {
|
||||
let schemas = &mut settings["json"]["schemas"];
|
||||
let builtin = match schemas.take() {
|
||||
Value::Array(list) => list,
|
||||
_ => Vec::new(),
|
||||
};
|
||||
let mut list: Vec<Value> =
|
||||
mappings.into_iter().map(|m| json!({ "url": m.url, "fileMatch": m.patterns })).collect();
|
||||
list.extend(builtin.into_iter().map(|mut entry| {
|
||||
if let Some(patterns) = entry.get_mut("fileMatch").and_then(Value::as_array_mut) {
|
||||
patterns.extend(excluded.iter().cloned());
|
||||
}
|
||||
entry
|
||||
}));
|
||||
*schemas = Value::Array(list);
|
||||
} else {
|
||||
let schemas = &mut settings["yaml"]["schemas"];
|
||||
if !schemas.is_object() {
|
||||
*schemas = json!({});
|
||||
}
|
||||
let map = schemas.as_object_mut().expect("object");
|
||||
for patterns in map.values_mut() {
|
||||
if let Value::String(single) = patterns {
|
||||
*patterns = json!([single.clone()]);
|
||||
}
|
||||
if let Some(list) = patterns.as_array_mut() {
|
||||
list.extend(excluded.iter().cloned());
|
||||
}
|
||||
}
|
||||
for m in mappings {
|
||||
let entry = map.entry(m.url).or_insert_with(|| json!([]));
|
||||
match entry.as_array_mut() {
|
||||
// A built-in schema mapped again: it no longer excludes the files mapped to it.
|
||||
Some(list) => {
|
||||
list.retain(|p| {
|
||||
!p.as_str().is_some_and(|p| m.patterns.iter().any(|f| p.strip_prefix('!') == Some(f.as_str())))
|
||||
});
|
||||
list.extend(m.patterns.into_iter().map(Value::String));
|
||||
}
|
||||
None => *entry = json!(m.patterns),
|
||||
}
|
||||
}
|
||||
}
|
||||
cfg.settings = Some(settings);
|
||||
}
|
||||
|
||||
/// The project folder as the servers see it in a file URI's path (`/work/app`, `c:/work/app`), or
|
||||
/// `None` when it holds glob characters, which neither server can escape: patterns then stay relative.
|
||||
fn root_glob(root: &Path) -> Option<String> {
|
||||
let mut path = root.to_string_lossy().replace('\\', "/").trim_end_matches('/').to_owned();
|
||||
if path.contains(['*', '?', '[', ']', '{', '}']) {
|
||||
return None;
|
||||
}
|
||||
// vscode-uri lower-cases the drive letter of the file URIs both servers match against.
|
||||
if path.as_bytes().get(1) == Some(&b':') {
|
||||
path[..1].make_ascii_lowercase();
|
||||
}
|
||||
Some(path)
|
||||
}
|
||||
|
||||
/// A URL as it is; a path, relative to the project, as a `file:` URI.
|
||||
fn schema_uri(root: &Path, schema: &str) -> String {
|
||||
if schema.contains("://") {
|
||||
return schema.to_owned();
|
||||
}
|
||||
let path = root.join(schema);
|
||||
url::Url::from_file_path(&path).map_or_else(|()| path.to_string_lossy().into_owned(), String::from)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use ide_language::LanguageRegistry;
|
||||
|
||||
fn server(language: &str, name: &str) -> LanguageServerConfig {
|
||||
let registry = LanguageRegistry::load(None).unwrap();
|
||||
let lang = registry.get(&ide_core::LanguageId::new(language)).expect("language");
|
||||
lang.language_servers.iter().find(|s| s.name == name).expect("server").clone()
|
||||
}
|
||||
|
||||
fn mapping(schema: &str, files: &[&str]) -> JsonSchemaMapping {
|
||||
JsonSchemaMapping {
|
||||
name: "Custom".into(),
|
||||
schema: schema.into(),
|
||||
files: files.iter().map(|f| (*f).to_owned()).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// An absolute folder on every platform, and the pattern prefix the servers match it with.
|
||||
fn root() -> (std::path::PathBuf, String) {
|
||||
let root = std::env::temp_dir().join("app");
|
||||
let base = root_glob(&root).expect("no glob characters");
|
||||
(root, base)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_json_mappings_come_first_and_built_in_ones_skip_their_files() {
|
||||
let mut cfg = server("json", JSON_SERVER);
|
||||
let (root, base) = root();
|
||||
configure(
|
||||
&mut cfg,
|
||||
&root,
|
||||
&[mapping("schemas/app.json", &["./config/*.json", " package.json ", "!config/x.json"])],
|
||||
);
|
||||
let schemas = cfg.settings.as_ref().unwrap()["json"]["schemas"].as_array().unwrap().clone();
|
||||
let url = String::from(url::Url::from_file_path(root.join("schemas/app.json")).unwrap());
|
||||
assert_eq!(
|
||||
schemas[0],
|
||||
json!({ "url": url, "fileMatch": [
|
||||
format!("{base}/config/*.json"),
|
||||
format!("{base}/package.json"),
|
||||
format!("!{base}/config/x.json"),
|
||||
format!("!{base}/schemas/app.json"),
|
||||
] })
|
||||
);
|
||||
let package = schemas.iter().find(|s| s["url"] == "https://json.schemastore.org/package.json").unwrap();
|
||||
assert_eq!(
|
||||
package["fileMatch"],
|
||||
json!(["package.json", format!("!{base}/config/*.json"), format!("!{base}/package.json")])
|
||||
);
|
||||
assert_eq!(cfg.settings.as_ref().unwrap()["json"]["validate"]["enable"], json!(true));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn custom_yaml_mappings_add_to_yaml_schemas() {
|
||||
let mut cfg = server("yaml", YAML_SERVER);
|
||||
let (root, base) = root();
|
||||
configure(&mut cfg, &root, &[mapping("https://example.com/s.json", &["deploy\\*.yaml"])]);
|
||||
let schemas = cfg.settings.as_ref().unwrap()["yaml"]["schemas"].as_object().unwrap().clone();
|
||||
assert_eq!(schemas["https://example.com/s.json"], json!([format!("{base}/deploy/*.yaml")]));
|
||||
let compose = schemas.get(ide_language::COMPOSE_SCHEMA_URL).unwrap().as_array().unwrap();
|
||||
assert_eq!(compose.last(), Some(&json!(format!("!{base}/deploy/*.yaml"))));
|
||||
assert!(compose.contains(&json!("compose.yaml")));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn project_folders_become_pattern_prefixes() {
|
||||
assert_eq!(root_glob(Path::new("/work/my app/")).as_deref(), Some("/work/my app"));
|
||||
assert_eq!(root_glob(Path::new("C:\\work\\app")).as_deref(), Some("c:/work/app"));
|
||||
assert_eq!(root_glob(Path::new("/work/[draft]")), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incomplete_mappings_and_other_servers_are_left_alone() {
|
||||
let mut cfg = server("json", JSON_SERVER);
|
||||
let before = cfg.settings.clone();
|
||||
let (root, _) = root();
|
||||
configure(&mut cfg, &root, &[mapping("", &["a.json"]), mapping("s.json", &[" ", "!a.json"])]);
|
||||
assert_eq!(cfg.settings, before);
|
||||
let mut other = LanguageServerConfig { name: "taplo".into(), ..cfg.clone() };
|
||||
configure(&mut other, &root, &[mapping("s.json", &["a.toml"])]);
|
||||
assert_eq!(other.settings, before);
|
||||
}
|
||||
}
|
||||
@@ -19,6 +19,7 @@ pub mod godot;
|
||||
pub mod java;
|
||||
pub mod jdtls;
|
||||
pub mod jdtls_workspaces;
|
||||
pub mod json_schemas;
|
||||
pub mod libraries;
|
||||
pub mod locate;
|
||||
pub mod lombok;
|
||||
|
||||
@@ -9420,6 +9420,15 @@ export type JsResponseRule = {
|
||||
body: string,
|
||||
};
|
||||
|
||||
/** A schema for the JSON and YAML files matching `files`; wins over a built-in SchemaStore mapping. */
|
||||
export type JsonSchemaMapping = {
|
||||
name?: string,
|
||||
/** A URL, or a file path relative to the project. */
|
||||
schema?: string,
|
||||
/** Project-relative paths or glob patterns (`config/*.json`, `**\/*.app.yaml`). */
|
||||
files?: string[],
|
||||
};
|
||||
|
||||
/** The test JVM of OpenIDEA's JUnit runner. */
|
||||
export type JunitLaunch = {
|
||||
classPaths: string[],
|
||||
@@ -13754,6 +13763,8 @@ export type Settings_Deserialize = {
|
||||
* options on top of the language definition, or a server defined here.
|
||||
*/
|
||||
languageServers?: { [key in string]: LanguageServerSettings_Deserialize },
|
||||
/** Languages & Frameworks › JSON Schema Mappings: schemas for JSON and YAML files. */
|
||||
jsonSchemas?: JsonSchemaMapping[],
|
||||
/** Tools › Download sources: a mirror prefix for the release archives the installer fetches. */
|
||||
toolDownloads?: ToolDownloadSettings,
|
||||
/** Editor › Inspections profiles. */
|
||||
@@ -13831,6 +13842,8 @@ export type Settings_Serialize = {
|
||||
* options on top of the language definition, or a server defined here.
|
||||
*/
|
||||
languageServers: { [key in string]: LanguageServerSettings_Serialize },
|
||||
/** Languages & Frameworks › JSON Schema Mappings: schemas for JSON and YAML files. */
|
||||
jsonSchemas: JsonSchemaMapping[],
|
||||
/** Tools › Download sources: a mirror prefix for the release archives the installer fetches. */
|
||||
toolDownloads: ToolDownloadSettings,
|
||||
/** Editor › Inspections profiles. */
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { matchesEveryFile, validateJsonSchemas } from "../model/schema";
|
||||
|
||||
describe("JSON Schema Mappings", () => {
|
||||
it("keeps named mappings and their string fields", () => {
|
||||
expect(
|
||||
validateJsonSchemas([
|
||||
{ name: "App", schema: "schemas/app.json", files: ["config/*.json", 3, " "] },
|
||||
{ schema: "nameless.json" },
|
||||
"junk",
|
||||
]),
|
||||
).toEqual([{ name: "App", schema: "schemas/app.json", files: ["config/*.json"] }]);
|
||||
expect(validateJsonSchemas(undefined)).toEqual([]);
|
||||
});
|
||||
|
||||
it("flags patterns that take every JSON or YAML file", () => {
|
||||
for (const p of ["*", "**/*", "*.json", "./**/*.yaml", "/*.yml", "**\\*.json"])
|
||||
expect(matchesEveryFile(p), p).toBe(true);
|
||||
for (const p of ["config/*.json", "package.json", "**/*.app.yaml", "!*.json"])
|
||||
expect(matchesEveryFile(p), p).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -395,6 +395,7 @@ describe("language pages", () => {
|
||||
"Java",
|
||||
"JavaScript Runtime",
|
||||
"Markdown",
|
||||
"JSON Schema Mappings",
|
||||
"Python",
|
||||
"PHP",
|
||||
"Prettier",
|
||||
|
||||
@@ -10,7 +10,7 @@ import { validateCMake } from "@/platform/cmakeSettings";
|
||||
import { SUPPORTED_LOCALES, type Locale } from "@/platform/i18n";
|
||||
import { DEFAULT_IGNORED_NAMES } from "@/platform/ignoredNames";
|
||||
import { validateFileTypeOverrides, validateFileTypes, type FileTypeAssociations } from "@/platform/fileTypes";
|
||||
import type { AgentSettings, LanguageServerSettings, Settings } from "@/platform/ipc";
|
||||
import type { AgentSettings, JsonSchemaMapping, LanguageServerSettings, Settings } from "@/platform/ipc";
|
||||
import {
|
||||
DEFAULT_LANGUAGES,
|
||||
DEFAULT_PROJECT_STRUCTURE,
|
||||
@@ -63,9 +63,32 @@ export interface CustomKeymapSettings {
|
||||
overrides: Record<string, string[]>;
|
||||
}
|
||||
|
||||
export type JsonSchemaMappingValid = Required<JsonSchemaMapping>;
|
||||
|
||||
export function validateJsonSchemas(raw: unknown): JsonSchemaMappingValid[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.flatMap((m) => {
|
||||
const o = obj(m);
|
||||
return typeof o.name === "string"
|
||||
? [{ name: o.name, schema: typeof o.schema === "string" ? o.schema : "", files: stringList(o.files) }]
|
||||
: [];
|
||||
});
|
||||
}
|
||||
|
||||
/** A mapping pattern that takes every JSON or YAML file in the project, such as `*.json`. */
|
||||
export function matchesEveryFile(pattern: string): boolean {
|
||||
const p = pattern
|
||||
.trim()
|
||||
.replaceAll("\\", "/")
|
||||
.replace(/^(?:\.\/|\/|\*\*\/)+/, "");
|
||||
return ["*", "**", "*.*", "*.json", "*.jsonc", "*.yaml", "*.yml"].includes(p);
|
||||
}
|
||||
|
||||
export interface ValidSettings extends WorkflowSettings {
|
||||
plugins: Record<string, Record<string, unknown>>;
|
||||
scopes: NamedScope[];
|
||||
/** Languages & Frameworks › JSON Schema Mappings. */
|
||||
jsonSchemas: JsonSchemaMappingValid[];
|
||||
fileColors: FileColorSettings;
|
||||
/** Database › Query Execution. */
|
||||
database: {
|
||||
@@ -188,6 +211,7 @@ export { ACCENT_PRESETS } from "@/workbench/theme";
|
||||
export const DEFAULT_SETTINGS: ValidSettings = {
|
||||
plugins: {},
|
||||
scopes: [],
|
||||
jsonSchemas: [],
|
||||
fileColors: DEFAULT_FILE_COLORS,
|
||||
database: { inEditorResults: false, outputDestination: "databaseOutput", resolutionScopes: [] },
|
||||
general: {
|
||||
@@ -375,6 +399,7 @@ export function validateSettings(raw: Settings | unknown): ValidSettings {
|
||||
return {
|
||||
plugins: Object.fromEntries(Object.entries(obj(root.plugins)).map(([id, values]) => [id, obj(values)])),
|
||||
scopes: validateScopes(root.scopes),
|
||||
jsonSchemas: validateJsonSchemas(root.jsonSchemas),
|
||||
fileColors: validateFileColors(root.fileColors),
|
||||
database: {
|
||||
inEditorResults: bool(obj(root.database).inEditorResults, d.database.inEditorResults),
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* Languages & Frameworks › JSON Schema Mappings: schemas (a URL or a project file) for the JSON and
|
||||
* YAML files matching paths or patterns. The backend sends them to the JSON and YAML language servers.
|
||||
*/
|
||||
import { useId, useLayoutEffect, useRef, useState } from "react";
|
||||
import clsx from "clsx";
|
||||
import { choosePath } from "@/platform/choosePath";
|
||||
import { tx } from "@/platform/i18n";
|
||||
import { relativePath, useProject } from "@/platform/project";
|
||||
import { IconButton, Input, List, T } from "@/ui";
|
||||
import { GlobListEditor, Row, Section } from "../components/Form";
|
||||
import { useSetting } from "../components/context";
|
||||
import {
|
||||
matchesEveryFile,
|
||||
validateJsonSchemas,
|
||||
type JsonSchemaMappingValid as JsonSchemaMapping,
|
||||
} from "../model/schema";
|
||||
import { ListToolbar, moved } from "./ScopesBody";
|
||||
import styles from "./Workflow.module.css";
|
||||
import own from "./Scopes.module.css";
|
||||
import sdk from "../languages/Sdk.module.css";
|
||||
|
||||
/** Examples, the same in every language. */
|
||||
const SCHEMA_EXAMPLE = "schemas/app.schema.json";
|
||||
const FILES_EXAMPLE = "config/*.json";
|
||||
|
||||
/** A name not taken yet: `Mapping`, `Mapping 2`, … */
|
||||
function freshSchemaName(taken: readonly string[]): string {
|
||||
const base = tx("Mapping");
|
||||
for (let n = 1; ; n++) {
|
||||
const name = n === 1 ? base : `${base} ${n}`;
|
||||
if (!taken.includes(name)) return name;
|
||||
}
|
||||
}
|
||||
|
||||
export function JsonSchemasEditor() {
|
||||
const [raw, setRaw] = useSetting<unknown>("jsonSchemas");
|
||||
const root = useProject((s) => s.project?.root);
|
||||
const mappings = validateJsonSchemas(raw);
|
||||
const [selected, setSelected] = useState(0);
|
||||
const index = mappings.length ? Math.min(selected, mappings.length - 1) : -1;
|
||||
const current = mappings[index];
|
||||
const nameId = useId();
|
||||
const schemaId = useId();
|
||||
const nameInput = useRef<HTMLInputElement>(null);
|
||||
const focusNew = useRef(false);
|
||||
useLayoutEffect(() => {
|
||||
if (!focusNew.current) return;
|
||||
focusNew.current = false;
|
||||
nameInput.current?.focus();
|
||||
nameInput.current?.select();
|
||||
}, [mappings.length]);
|
||||
const set = (next: JsonSchemaMapping[]) => setRaw(next);
|
||||
const update = (patch: Partial<JsonSchemaMapping>) =>
|
||||
set(mappings.map((m, i) => (i === index ? { ...m, ...patch } : m)));
|
||||
const names = mappings.map((m) => m.name);
|
||||
const nameClash = !!current && names.filter((n) => n === current.name).length > 1;
|
||||
const catchAll = current?.files.find(matchesEveryFile);
|
||||
|
||||
return (
|
||||
<div className={own.scopeLayout}>
|
||||
<div className={clsx(styles.tableBox, own.scopePane)}>
|
||||
<ListToolbar
|
||||
label="JSON schema mappings actions"
|
||||
index={index}
|
||||
count={mappings.length}
|
||||
onAdd={() => {
|
||||
focusNew.current = true;
|
||||
set([...mappings, { name: freshSchemaName(names), schema: "", files: [] }]);
|
||||
setSelected(mappings.length);
|
||||
}}
|
||||
onRemove={() => set(mappings.filter((_, i) => i !== index))}
|
||||
onMove={(d) => {
|
||||
const next = moved(mappings, index, d);
|
||||
if (next) {
|
||||
set(next);
|
||||
setSelected(index + d);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<List
|
||||
aria-label={tx("JSON schema mappings")}
|
||||
className={own.scopeList}
|
||||
items={mappings}
|
||||
activeIndex={index}
|
||||
onActiveChange={setSelected}
|
||||
getKey={(_, i) => String(i)}
|
||||
renderItem={({ name, schema }) => (
|
||||
<span className={own.scopeName} title={schema ? `${name}\n${schema}` : name}>
|
||||
{name}
|
||||
</span>
|
||||
)}
|
||||
empty={
|
||||
<div className={own.scopeEmpty}>
|
||||
<T>No schema mappings. Click + to add one.</T>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
{current && (
|
||||
<Section title="Mapping">
|
||||
<Row label="Name" htmlFor={nameId}>
|
||||
<Input
|
||||
id={nameId}
|
||||
ref={nameInput}
|
||||
className={own.scopeInput}
|
||||
value={current.name}
|
||||
invalid={nameClash || !current.name.trim()}
|
||||
onChange={(e) => update({ name: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
<Row
|
||||
label="Schema file or URL"
|
||||
htmlFor={schemaId}
|
||||
hint="A URL, or a path relative to the project. The schema's own $schema picks the JSON Schema version."
|
||||
>
|
||||
<span className={sdk.pathRow}>
|
||||
<Input
|
||||
id={schemaId}
|
||||
mono
|
||||
className={sdk.pathInput}
|
||||
value={current.schema}
|
||||
invalid={!current.schema.trim()}
|
||||
placeholder={SCHEMA_EXAMPLE}
|
||||
onChange={(e) => update({ schema: e.target.value })}
|
||||
/>
|
||||
<IconButton
|
||||
icon="folder-open"
|
||||
size="small"
|
||||
title="Browse…"
|
||||
onClick={async () => {
|
||||
const p = await choosePath({ directory: false, title: tx("Select Schema File"), defaultPath: root });
|
||||
// Windows choosers return `\` separators; project paths use `/`.
|
||||
const picked = p?.replaceAll("\\", "/");
|
||||
if (picked) update({ schema: root ? relativePath(root.replaceAll("\\", "/"), picked) : picked });
|
||||
}}
|
||||
/>
|
||||
</span>
|
||||
</Row>
|
||||
<Row
|
||||
label="Files"
|
||||
stacked
|
||||
hint={
|
||||
catchAll ? (
|
||||
<span className={own.error} role="alert">
|
||||
{tx`${catchAll} matches every file of its type: the built-in mappings no longer apply to them.`}
|
||||
</span>
|
||||
) : (
|
||||
"Paths or glob patterns, relative to the project: config/*.json, **/*.app.yaml; !pattern leaves files out. Wins over the built-in mapping for the same files."
|
||||
)
|
||||
}
|
||||
>
|
||||
<GlobListEditor
|
||||
value={current.files}
|
||||
onChange={(files) => update({ files })}
|
||||
placeholder={FILES_EXAMPLE}
|
||||
emptyText="No files"
|
||||
itemLabel="File or pattern"
|
||||
aria-label="Files"
|
||||
fullWidth
|
||||
/>
|
||||
</Row>
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -14,7 +14,7 @@ import styles from "./Workflow.module.css";
|
||||
import own from "./Scopes.module.css";
|
||||
|
||||
/** Toolbar of an ordered list: add, remove, move up / down. */
|
||||
function ListToolbar({
|
||||
export function ListToolbar({
|
||||
label,
|
||||
index,
|
||||
count,
|
||||
@@ -45,7 +45,7 @@ function ListToolbar({
|
||||
);
|
||||
}
|
||||
|
||||
function moved<T>(list: readonly T[], index: number, d: -1 | 1): T[] | null {
|
||||
export function moved<T>(list: readonly T[], index: number, d: -1 | 1): T[] | null {
|
||||
const j = index + d;
|
||||
if (index < 0 || j < 0 || j >= list.length) return null;
|
||||
const next = [...list];
|
||||
|
||||
@@ -46,6 +46,9 @@ const TypeScriptPage = lazyPage("languages.typescript", () =>
|
||||
const FlutterPage = lazyPage("languages.flutter", () =>
|
||||
import("../languages/LanguagePages").then((m) => m.FlutterPage),
|
||||
);
|
||||
const JsonSchemasEditor = lazyPage("languages.jsonSchemas", () =>
|
||||
import("./JsonSchemasBody").then((m) => m.JsonSchemasEditor),
|
||||
);
|
||||
const ZigPage = lazyPage("languages.zig", () => import("../languages/LanguagePages").then((m) => m.ZigPage));
|
||||
|
||||
export const LANGUAGES_GROUP = "Languages & Frameworks";
|
||||
@@ -206,6 +209,28 @@ export const LANGUAGE_PAGES: PageSpec[] = [
|
||||
],
|
||||
component: MarkdownPage,
|
||||
},
|
||||
{
|
||||
// IDEA's Schemas and DTDs › JSON Schema Mappings; project settings, so they can be shared.
|
||||
id: "languages.jsonSchemas",
|
||||
projectScope: true,
|
||||
defaultScope: "project",
|
||||
title: "JSON Schema Mappings",
|
||||
group: LANGUAGES_GROUP,
|
||||
order: 400.5,
|
||||
keywords: ["json", "yaml", "schema", "schemastore", "validation", "completion", "file match", "dtd"],
|
||||
sections: [
|
||||
{
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "JSON Schema Mappings",
|
||||
keywords: ["Name", "Schema file or URL", "Files"],
|
||||
component: JsonSchemasEditor,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "languages.prettier",
|
||||
projectScope: true,
|
||||
|
||||
@@ -4515,5 +4515,15 @@
|
||||
"Task kwargs": "Task kwargs",
|
||||
"e.g. --loglevel INFO": "e.g. --loglevel INFO",
|
||||
"Enter a JSON list of arguments": "Enter a JSON list of arguments",
|
||||
"Enter a JSON object of keyword arguments": "Enter a JSON object of keyword arguments"
|
||||
"Enter a JSON object of keyword arguments": "Enter a JSON object of keyword arguments",
|
||||
"JSON Schema Mappings": "JSON Schema Mappings",
|
||||
"JSON schema mappings actions": "JSON schema mappings actions",
|
||||
"JSON schema mappings": "JSON schema mappings",
|
||||
"No schema mappings. Click + to add one.": "No schema mappings. Click + to add one.",
|
||||
"Schema file or URL": "Schema file or URL",
|
||||
"A URL, or a path relative to the project. The schema's own $schema picks the JSON Schema version.": "A URL, or a path relative to the project. The schema's own $schema picks the JSON Schema version.",
|
||||
"Select Schema File": "Select Schema File",
|
||||
"Mapping": "Mapping",
|
||||
"{catchAll} matches every file of its type: the built-in mappings no longer apply to them.": "{catchAll} matches every file of its type: the built-in mappings no longer apply to them.",
|
||||
"Paths or glob patterns, relative to the project: config/*.json, **/*.app.yaml; !pattern leaves files out. Wins over the built-in mapping for the same files.": "Paths or glob patterns, relative to the project: config/*.json, **/*.app.yaml; !pattern leaves files out. Wins over the built-in mapping for the same files."
|
||||
}
|
||||
@@ -11046,5 +11046,15 @@
|
||||
"Task kwargs": "任务 kwargs",
|
||||
"e.g. --loglevel INFO": "例如 --loglevel INFO",
|
||||
"Enter a JSON list of arguments": "请输入参数的 JSON 列表",
|
||||
"Enter a JSON object of keyword arguments": "请输入关键字参数的 JSON 对象"
|
||||
"Enter a JSON object of keyword arguments": "请输入关键字参数的 JSON 对象",
|
||||
"JSON Schema Mappings": "JSON Schema 映射",
|
||||
"JSON schema mappings actions": "JSON Schema 映射操作",
|
||||
"JSON schema mappings": "JSON Schema 映射",
|
||||
"No schema mappings. Click + to add one.": "没有 Schema 映射。点击 + 添加。",
|
||||
"Schema file or URL": "Schema 文件或 URL",
|
||||
"A URL, or a path relative to the project. The schema's own $schema picks the JSON Schema version.": "URL,或相对于项目的路径。JSON Schema 版本由 Schema 自身的 $schema 决定。",
|
||||
"Select Schema File": "选择 Schema 文件",
|
||||
"Mapping": "映射",
|
||||
"{catchAll} matches every file of its type: the built-in mappings no longer apply to them.": "{catchAll} 匹配该类型的所有文件:内置映射不再作用于它们。",
|
||||
"Paths or glob patterns, relative to the project: config/*.json, **/*.app.yaml; !pattern leaves files out. Wins over the built-in mapping for the same files.": "相对于项目的路径或 glob 模式:config/*.json、**/*.app.yaml;!pattern 排除文件。对相同的文件优先于内置映射。"
|
||||
}
|
||||
Reference in new issue
Заблокувати користувача