/** * Settings › Project Structure (File › Project Structure…, ⌘; / Ctrl+Alt+Shift+S): * IntelliJ IDEA-style Project Structure configuration across Project, Modules * (Sources, Paths, Dependencies), Libraries, Facets, Artifacts, and SDKs. */ import { useCallback, useEffect, useId, useMemo, useState } from "react"; import clsx from "clsx"; import { Channel } from "@tauri-apps/api/core"; import { Button, Checkbox, Dialog, Icon, IconButton, Input, Select, Tree, folderIconName, type DialogButton, type FolderKind, type IconName, type SelectOption, T, } from "@/ui"; import { SettingsFormContext } from "@/workbench/contributions"; import { call, commands, isTauri, nextRequestId, type FileEntry } from "@/platform/ipc"; import { mergeLibraryGroups } from "@/platform/libraries"; import type { BuildModel, LibraryGroup, WebArtifact } from "@/bindings"; import { relativePath, useProject } from "@/platform/project"; import { PageContext, useSettingsFormFor } from "../components/context"; import { applySettings, closeProjectStructure, pendingChanges, resetPage, selectProjectStructureSection, useSettingsDialog, } from "../model/staging"; import { ARTIFACT_KINDS, DEPENDENCY_SCOPES, JAVA_LANGUAGE_LEVELS, PROJECT_STRUCTURE_KEYS, effectiveRoots, markFolder, normalizeFolder, restoreDetected, rootRole, unmarkedRoots, validateProjectStructure, type ArtifactConfigValid, type ArtifactKindValid, type DependencyScopeValid, type FacetConfigValid, type FolderListKey, type FolderRole, type ModuleStructureValid, type ProjectLibraryValid, type ProjectStructureValid, } from "@/platform/languageSettings"; import { initProjectRoots, useDetectedRoots } from "@/platform/projectRoots"; import { Row, Section } from "../components/Form"; import { choosePath, detectSdks, useSdks, type SdkKind } from "./api"; import { DownloadJdkDialog } from "./DownloadJdkDialog"; import { SdkField, tildify, useDetected, useProjectSetting } from "./components"; import styles from "./Sdk.module.css"; import { tx } from "@/platform/i18n"; export type ProjectStructureSectionId = | "project" | "modules" | "dependencies" | "libraries" | "facets" | "artifacts" | "sdks"; interface DirNode { path: string; name: string; /** Project-relative; null outside the project (another content root). */ rel: string | null; /** A content root besides the project folder. */ contentRoot?: boolean; } const inside = (root: string, path: string) => path === root || path.startsWith(root + "/"); const ROLES: Array<{ role: FolderRole; label: string; title: string; kind: FolderKind; cls: string }> = [ { role: "source", label: "Sources", title: "Source Folders", kind: "source", cls: styles.sourceTitle! }, { role: "test", label: "Tests", title: "Test Source Folders", kind: "test", cls: styles.testTitle! }, { role: "resources", label: "Resources", title: "Resource Folders", kind: "resources", cls: styles.resourcesTitle! }, { role: "testResources", label: "Test Resources", title: "Test Resource Folders", kind: "testResources", cls: styles.testResourcesTitle!, }, { role: "excluded", label: "Excluded", title: "Excluded Folders", kind: "excluded", cls: styles.excludedTitle! }, ]; const SECTION_TABS: Array<{ id: ProjectStructureSectionId; label: string; icon: IconName }> = [ { id: "project", label: "Project", icon: "folder" }, { id: "modules", label: "Modules", icon: "module" }, { id: "dependencies", label: "Dependencies", icon: "build-dependencies" }, { id: "libraries", label: "Libraries", icon: "folder-library" }, { id: "facets", label: "Facets", icon: "file-config" }, { id: "artifacts", label: "Artifacts", icon: "file-archive" }, { id: "sdks", label: "SDKs", icon: "settings" }, ]; const PROJECT_JAVA_LEVEL_OPTIONS: SelectOption[] = JAVA_LANGUAGE_LEVELS.map((level) => level ? { value: level, label: level } : { value: "", label: "SDK default", detail: "from build / JDK" }, ); const MODULE_JAVA_LEVEL_OPTIONS: SelectOption[] = JAVA_LANGUAGE_LEVELS.map((level) => level ? { value: level, label: level } : { value: "", label: "Project default", detail: "inherit project" }, ); const SCOPE_OPTIONS: SelectOption[] = DEPENDENCY_SCOPES.map((s) => ({ value: s, label: s === "compile" ? "Compile" : s === "test" ? "Test" : s === "runtime" ? "Runtime" : "Provided", })); const ARTIFACT_KIND_OPTIONS: SelectOption[] = ARTIFACT_KINDS.map((k) => ({ value: k, label: k === "jar" ? "JAR" : k === "war" ? "WAR Archive" : "WAR (exploded)", })); const FACET_KIND_OPTIONS: SelectOption[] = [ { value: "web", label: "Web" }, { value: "spring", label: "Spring" }, { value: "jpa", label: "JPA" }, ]; const SDK_KINDS: Array<{ kind: SdkKind; label: string }> = [ { kind: "jdk", label: "JDK" }, { kind: "python", label: "Python" }, { kind: "node", label: "Node.js" }, { kind: "go", label: "Go" }, { kind: "rust", label: "Rust" }, { kind: "php", label: "PHP" }, { kind: "ruby", label: "Ruby" }, { kind: "maven", label: "Maven" }, ]; async function readDirs(root: string, path: string): Promise { if (!isTauri()) return []; const entries: FileEntry[] = await call(commands.fsReadDir(path)); return entries .filter((e) => e.kind === "dir" || (e.kind === "symlink" && e.targetKind === "dir")) .filter((e) => e.name !== ".git") .map((e) => ({ path: e.path, name: e.name, rel: inside(root, e.path) ? relativePath(root, e.path) : null })); } function useStructure(): [ProjectStructureValid, (next: ProjectStructureValid) => void] { const [sourceRoots, setSource] = useProjectSetting("projectStructure.sourceRoots"); const [testRoots, setTest] = useProjectSetting("projectStructure.testRoots"); const [resourceRoots, setResources] = useProjectSetting("projectStructure.resourceRoots"); const [testResourceRoots, setTestResources] = useProjectSetting( "projectStructure.testResourceRoots", ); const [excluded, setExcluded] = useProjectSetting("projectStructure.excluded"); const [unmarked, setUnmarked] = useProjectSetting("projectStructure.unmarked"); const [contentRoots] = useProjectSetting("projectStructure.contentRoots"); const [dependencies] = useProjectSetting("projectStructure.dependencies"); const [memberDependencies] = useProjectSetting | undefined>( "projectStructure.memberDependencies", ); const [excludeFiles] = useProjectSetting("projectStructure.excludeFiles"); const [compilerOutput] = useProjectSetting("projectStructure.compilerOutput"); const [modules] = useProjectSetting | undefined>("projectStructure.modules"); const [libraries] = useProjectSetting("projectStructure.libraries"); const [facets] = useProjectSetting("projectStructure.facets"); const [artifacts] = useProjectSetting("projectStructure.artifacts"); const ps = useMemo( () => validateProjectStructure({ sourceRoots: sourceRoots ?? [], testRoots: testRoots ?? [], resourceRoots: resourceRoots ?? [], testResourceRoots: testResourceRoots ?? [], excluded: excluded ?? [], unmarked: unmarked ?? [], contentRoots: contentRoots ?? [], dependencies: dependencies ?? [], memberDependencies: memberDependencies ?? {}, excludeFiles: excludeFiles ?? "", compilerOutput: compilerOutput ?? "", modules: modules ?? {}, libraries: libraries ?? [], facets: facets ?? [], artifacts: artifacts ?? [], }), [ sourceRoots, testRoots, resourceRoots, testResourceRoots, excluded, unmarked, contentRoots, dependencies, memberDependencies, excludeFiles, compilerOutput, modules, libraries, facets, artifacts, ], ); const set = useCallback( (next: ProjectStructureValid) => { const setters: Record void> = { sourceRoots: setSource, testRoots: setTest, resourceRoots: setResources, testResourceRoots: setTestResources, excluded: setExcluded, unmarked: setUnmarked, }; for (const k of PROJECT_STRUCTURE_KEYS) if (JSON.stringify(next[k]) !== JSON.stringify(ps[k])) setters[k](next[k]); }, [ps, setSource, setTest, setResources, setTestResources, setExcluded, setUnmarked], ); return [ps, set]; } function useBuildModelData(root: string | null): BuildModel | null { const [model, setModel] = useState(null); useEffect(() => { if (!root || !isTauri()) return; let live = true; call(commands.buildModel()) .then((m) => live && setModel(m)) .catch(() => {}); return () => { live = false; }; }, [root]); return root && isTauri() ? model : null; } /** "+ Add Content Root" and the content roots, the project folder first (IDEA's module Sources tab). */ function ContentRoots({ root }: { root: string }) { const [roots, setRoots] = useProjectSetting("projectStructure.contentRoots"); const list = roots ?? []; const add = async () => { const picked = await choosePath({ directory: true, title: "Add Content Root", defaultPath: root }); if (!picked || inside(root, picked) || list.includes(picked)) return; setRoots([...list, picked]); }; return (
{root}
{list.map((r) => (
{r} setRoots(list.filter((x) => x !== r))} />
))}
); } function ExcludeFiles() { const [value, setValue] = useProjectSetting("projectStructure.excludeFiles"); const id = useId(); return (
setValue(e.target.value)} />
Use ; to separate name patterns, * for any number of symbols, ? for one.
); } // --------------------------------------------------------------------------- // 1. Project Section function ProjectSection() { const root = useProject((s) => s.project?.root ?? null); const name = useProject((s) => s.project?.name ?? ""); const [jdk, setJdk] = useProjectSetting("languages.java.jdk"); const [languageLevel, setLanguageLevel] = useProjectSetting("languages.java.languageLevel"); const [compilerOutput, setCompilerOutput] = useProjectSetting("projectStructure.compilerOutput"); const [jdtlsJdk, setJdtlsJdk] = useProjectSetting("languages.java.jdtlsJdk"); const outId = useId(); return (
{name || "Default Project"} setCompilerOutput(e.target.value)} /> { const picked = await choosePath({ directory: true, title: "Select Compiler Output Directory", defaultPath: compilerOutput || root || undefined, }); if (picked) setCompilerOutput(root && inside(root, picked) ? relativePath(root, picked) : picked); }} />
); } // --------------------------------------------------------------------------- // 2. Modules Section (Sources, Paths, Dependencies) function ModuleSourcesTab({ moduleKey }: { moduleKey: string }) { const root = useProject((s) => s.project?.root ?? null); const name = useProject((s) => s.project?.name ?? ""); const [ps, setPs] = useStructure(); const detected = useDetectedRoots(); const roots = useMemo(() => effectiveRoots(detected, ps), [detected, ps]); useEffect(() => initProjectRoots(), []); const [children, setChildren] = useState>(new Map()); const moduleRoot = root ? (moduleKey === "." ? root : `${root}/${moduleKey}`) : null; const [expanded, setExpanded] = useState>(() => new Set(moduleRoot ? [moduleRoot] : [])); const [selected, setSelected] = useState(null); const load = useCallback( async (node: DirNode) => { if (!root) return; const dirs = await readDirs(root, node.path); setChildren((m) => new Map(m).set(node.path, dirs)); }, [root], ); const rootNode = useMemo( () => moduleRoot ? { path: moduleRoot, name: moduleKey === "." ? name : moduleKey.split("/").pop()!, rel: moduleKey === "." ? "" : moduleKey, } : null, [moduleRoot, moduleKey, name], ); const treeRoots = useMemo( () => rootNode ? [ rootNode, ...(moduleKey === "." ? ps.contentRoots : []).map((p) => ({ path: p, name: p.slice(p.lastIndexOf("/") + 1) || p, rel: null, contentRoot: true, })), ] : [], [rootNode, ps.contentRoots, moduleKey], ); useEffect(() => { if (!root) return; let live = true; for (const dir of [moduleRoot!, ...(moduleKey === "." ? ps.contentRoots : [])]) void readDirs(root, dir) .then((dirs) => live && setChildren((m) => new Map(m).set(dir, dirs))) .catch(() => {}); return () => { live = false; }; }, [root, ps.contentRoots, moduleRoot, moduleKey]); if (!rootNode) return (
Open a project to configure its folders.
); const markable = selected?.rel ?? null; const role = markable !== null ? rootRole(roots, markable) : null; const mark = (r: FolderRole) => { if (markable === null) return; setPs(markFolder(ps, markable, role === r ? null : r, detected)); }; const moduleDetected = moduleKey === "." ? detected : detected.filter((folder) => folder.path === moduleKey || folder.path.startsWith(moduleKey + "/")); const unmarkedDetected = unmarkedRoots(moduleDetected, ps); const restore = () => setPs(restoreDetected(ps, moduleDetected)); return (
Mark as: {ROLES.map((r) => ( ))}
aria-label="Content root" roots={treeRoots} getKey={(n) => n.path} getLabel={(n) => n.name} getChildren={(n) => children.get(n.path)} isExpandable={() => true} loadChildren={load} expanded={expanded} onExpandedChange={(set) => setExpanded(set)} multiSelect={false} selected={selected ? new Set([selected.path]) : new Set()} onSelectionChange={(_s, lead) => setSelected(lead)} getIcon={(n) => { if (n.rel === null) return n.contentRoot ? "module" : folderIconName("plain"); const r = rootRole(roots, n.rel); if (!n.rel && !r) return "module"; return folderIconName(r ? ROLES.find((x) => x.role === r)!.kind : "plain"); }} getDetail={(n) => (n.rel === "" ? (root ?? undefined) : n.contentRoot ? n.path : undefined)} />
{moduleKey === "." && }
{moduleKey === "." && } {ROLES.map((r) => { const list = roots.filter( (x) => x.kind === r.role && (moduleKey === "." || x.path === moduleKey || x.path.startsWith(moduleKey + "/")), ); return (
{r.title}
{list.length === 0 && (
None
)} {list.map((x) => { const shown = x.path || name || "."; return (
{shown} {x.detectedFrom && ( {tx`detected from ${x.detectedFrom}`} )} setPs(markFolder(ps, x.path, null, detected))} />
); })}
); })} {unmarkedDetected.length > 0 && (
{unmarkedDetected.length === 1 ? tx("1 detected folder is unmarked.") : tx`${unmarkedDetected.length} detected folders are unmarked.`}{" "}
)}
{ "Folders are detected from build files (pom.xml, build.gradle, Cargo.toml, go.mod, pyproject.toml, package.json, composer.json); marking or unmarking a folder overrides detection. Excluded folders are skipped by the Project view, Find in Files and the index (reopen the project to re-index)." }
); } interface DiscoveredModule { key: string; name: string; buildTool: "maven" | "gradle" | "custom"; } /** One row of the Project Structure › Dependencies checklist. */ export interface DependencyCandidate { path: string; name: string; checked: boolean; disabled: boolean; } /** * Rows of the "project dependencies" checklist of a single root (the project folder, or a * workspace member): the configured dependencies. A workspace additionally lists the other * roots attached to the window, in MemberDependencies. */ export function dependencyCandidates(root: string | null, dependencies: readonly string[]): DependencyCandidate[] { const out: DependencyCandidate[] = []; const listed = new Set(); const nameOf = (p: string) => p.slice(p.lastIndexOf("/") + 1).replace(/[\\/]+$/, "") || p; const attachable = (p: string) => !!root && p !== root && !p.startsWith(`${root}/`); for (const p of dependencies) { if (listed.has(p) || !attachable(p)) continue; listed.add(p); out.push({ path: p, name: nameOf(p), checked: true, disabled: false }); } return out; } /** Settings › Project Structure › Modules › Dependencies. */ function ModuleDependenciesTab() { const workspaceProjects = useProject((s) => s.project?.workspace?.projects ?? null); // A workspace: every member is an equal root that picks the roots it depends on. return workspaceProjects ? : ; } /** The dependency checklist of a standalone project (no workspace). */ function ProjectDependencies() { const root = useProject((s) => s.project?.root ?? null); const [deps, setDeps] = useProjectSetting("projectStructure.dependencies"); const list = deps ?? []; // Only the configured projects: candidates come from Add Project…, not every recent project. const candidates = useMemo(() => dependencyCandidates(root, deps ?? []), [root, deps]); const toggle = (path: string, checked: boolean) => setDeps(checked ? [...list, path] : list.filter((x) => x !== path)); const add = async () => { const picked = await choosePath({ directory: true, title: "Add Project Dependency", defaultPath: root ?? undefined, }); if (!picked || !root || picked === root || inside(root, picked) || list.includes(picked)) return; setDeps([...list, picked]); }; return (
Dependency projects are indexed and navigable together with this project: Go to Declaration, Find Usages and the Project view include them.
{candidates.length === 0 && (
No candidate projects yet. Use Add Project… to pick one.
)} {candidates.map((c) => (
toggle(c.path, checked)} aria-label={tx`The project depends on ${c.name}`} /> {tildify(c.path)}
))}
); } /** The per-root dependency checklist of a workspace: all members are equal roots. */ function MemberDependencies({ members }: { members: readonly string[] }) { const [memberDeps, setMemberDeps] = useProjectSetting | undefined>( "projectStructure.memberDependencies", ); const [selected, setSelected] = useState(0); const active = members[Math.min(selected, members.length - 1)] ?? ""; const activeName = active.slice(active.lastIndexOf("/") + 1); const deps = useMemo(() => memberDeps?.[active] ?? [], [memberDeps, active]); const others = useMemo(() => { const nameOf = (p: string) => p.slice(p.lastIndexOf("/") + 1); const extra = deps.filter((d) => !members.includes(d)).map((path) => ({ path, name: nameOf(path) })); return members .filter((m) => m !== active) .map((path) => ({ path, name: nameOf(path) })) .concat(extra); }, [members, active, deps]); const roots = useMemo( () => members.map((path) => ({ path, name: path.slice(path.lastIndexOf("/") + 1) })), [members], ); const setDeps = (next: string[]) => setMemberDeps({ ...(memberDeps ?? {}), [active]: next }); const toggle = (path: string, checked: boolean) => setDeps(checked ? [...deps, path] : deps.filter((x) => x !== path)); const add = async () => { const picked = await choosePath({ directory: true, title: "Add Project Dependency", defaultPath: active, }); if (!picked || picked === active || inside(active, picked) || deps.includes(picked)) return; setDeps([...deps, picked]); }; return (
Every root is equal: pick a root on the left, then check the roots it depends on. Go to Declaration in it resolves only into its own code and its dependencies.
{roots.map((m, i) => ( ))}
{others.length === 0 && (
No other roots.
)} {others.map((c) => (
toggle(c.path, checked)} aria-label={tx`The root depends on ${c.name}`} /> {tildify(c.path)}
))}
); } function ModulesSection() { const root = useProject((s) => s.project?.root ?? null); const projectName = useProject((s) => s.project?.name ?? ""); const model = useBuildModelData(root); const [modulesMap, setModulesMap] = useProjectSetting | undefined>( "projectStructure.modules", ); const [selectedModule, setSelectedModule] = useState("."); const [subTab, setSubTab] = useState<"sources" | "paths">("sources"); const [moduleError, setModuleError] = useState(false); const outId = useId(); const testOutId = useId(); const modules = useMemo(() => { const seen = new Set(); const list: DiscoveredModule[] = []; const add = (key: string, name: string, buildTool: "maven" | "gradle" | "custom") => { const norm = normalizeFolder(key) || "."; if (seen.has(norm)) return; seen.add(norm); list.push({ key: norm, name, buildTool }); }; add(".", projectName || "Root Module", model?.maven ? "maven" : model?.gradle?.length ? "gradle" : "custom"); for (const p of model?.maven?.projects ?? []) { add(p.dir, p.displayName || p.artifactId || p.dir, "maven"); } for (const gm of model?.gradle ?? []) { for (const p of gm.projects) { add(p.dir, p.name || p.path || p.dir, "gradle"); } } for (const k of Object.keys(modulesMap ?? {})) { add(k, k === "." ? projectName || "Root Module" : k.split("/").pop() || k, "custom"); } return list; }, [projectName, model, modulesMap]); const activeKey = modules.some((m) => m.key === selectedModule) ? selectedModule : "."; const currentModuleCfg: ModuleStructureValid = modulesMap?.[activeKey] ?? { jdk: "", languageLevel: "", compilerOutput: "", testCompilerOutput: "", dependencies: [], }; const updateModuleCfg = (patch: Partial) => { const next: ModuleStructureValid = { ...currentModuleCfg, ...patch }; setModulesMap({ ...(modulesMap ?? {}), [activeKey]: next }); }; const addModule = async () => { const picked = await choosePath({ directory: true, title: "Select Module Directory", defaultPath: root ?? undefined, }); if (!picked) return; if (!root || !inside(root, picked)) { setModuleError(true); return; } setModuleError(false); const rel = normalizeFolder(relativePath(root, picked)) || "."; if (!(modulesMap && modulesMap[rel])) { setModulesMap({ ...(modulesMap ?? {}), [rel]: { jdk: "", languageLevel: "", compilerOutput: "", testCompilerOutput: "", dependencies: [] }, }); } setSelectedModule(rel); }; const removeModule = () => { if (activeKey === "." || !modulesMap?.[activeKey]) return; const next = { ...modulesMap }; delete next[activeKey]; setModulesMap(next); setSelectedModule("."); }; const activeMod = modules.find((m) => m.key === activeKey) ?? modules[0]; return (
{moduleError && (
Select a module directory inside the project.
)}
{modules.map((m) => ( ))}
{activeMod?.name ?? activeKey} {activeKey !== "." && {activeKey}}
{subTab === "sources" && } {subTab === "paths" && (
{activeKey !== "." && (
Per-module language levels and compiler output overrides are not supported yet. Configure them in Maven or Gradle.
)} updateModuleCfg({ jdk })} emptyLabel="Project SDK" emptyDetail="inherit from Project" directory browseTitle="Select JDK Home Directory" aria-label="Module SDK" /> updateModuleCfg({ compilerOutput: e.target.value })} /> { const picked = await choosePath({ directory: true, title: "Select Compiler Output Directory", defaultPath: currentModuleCfg.compilerOutput || root || undefined, }); if (picked) updateModuleCfg({ compilerOutput: root && inside(root, picked) ? relativePath(root, picked) : picked, }); }} /> updateModuleCfg({ testCompilerOutput: e.target.value })} /> { const picked = await choosePath({ directory: true, title: "Select Test Output Directory", defaultPath: currentModuleCfg.testCompilerOutput || root || undefined, }); if (picked) updateModuleCfg({ testCompilerOutput: root && inside(root, picked) ? relativePath(root, picked) : picked, }); }} />
)}
); } // --------------------------------------------------------------------------- // 3. Libraries Section function LibrariesSection() { const root = useProject((s) => s.project?.root ?? null); const [rawLibs, setRawLibs] = useProjectSetting("projectStructure.libraries"); const libs = rawLibs ?? []; const [selectedIdx, setSelectedIdx] = useState(0); const [detectedGroups, setDetectedGroups] = useState([]); const nameId = useId(); useEffect(() => { if (!root || !isTauri()) return; let live = true; const request = nextRequestId(); const channel = new Channel(); let collected: LibraryGroup[] = []; channel.onmessage = (groups) => { collected = mergeLibraryGroups([...collected, ...groups]); if (live) setDetectedGroups(collected); }; call(commands.sdkProjectLibraries(request, channel)) .then((groups) => { collected = groups; if (live) setDetectedGroups(groups); }) .catch(() => {}); return () => { live = false; void commands.cancelRequest(request).catch(() => {}); }; }, [root, libs.length]); const activeIdx = selectedIdx >= 0 && selectedIdx < libs.length ? selectedIdx : libs.length > 0 ? 0 : -1; const current = activeIdx >= 0 ? libs[activeIdx]! : null; const updateCurrent = (patch: Partial) => { if (!current || activeIdx < 0) return; const next = [...libs]; next[activeIdx] = { ...current, ...patch }; setRawLibs(next); }; const addLibraryFromJar = async (directory: boolean) => { const picked = await choosePath({ directory, title: directory ? "Select Classes Directory" : "Select Library JAR", defaultPath: root ?? undefined, }); if (!picked) return; const rel = root && inside(root, picked) ? relativePath(root, picked) : picked; const baseName = picked .split(/[\\/]/) .pop() ?.replace(/\.jar$/i, "") || "Library"; const created: ProjectLibraryValid = { name: baseName, classes: [rel], sources: [], javadocs: [], scope: "compile", }; const next = [...libs, created]; setRawLibs(next); setSelectedIdx(next.length - 1); }; const removeSelectedLibrary = () => { if (activeIdx < 0) return; const next = libs.filter((_, idx) => idx !== activeIdx); setRawLibs(next); setSelectedIdx(Math.max(0, activeIdx - 1)); }; const appendPath = async (field: "classes" | "sources" | "javadocs", directory: boolean, title: string) => { if (!current) return; const picked = await choosePath({ directory, title, defaultPath: root ?? undefined }); if (!picked) return; const rel = root && inside(root, picked) ? relativePath(root, picked) : picked; if (!current[field].includes(rel)) { updateCurrent({ [field]: [...current[field], rel] }); } }; return (
void addLibraryFromJar(false)} /> void addLibraryFromJar(true)} />
{libs.length === 0 && (
No project libraries added.
)} {libs.map((lib, idx) => ( ))}
{current ? (
updateCurrent({ name: e.target.value })} /> updateCurrent({ kind: v as "web" | "spring" | "jpa" })} aria-label="Facet framework" /> updateCurrent({ module: e.target.value })} /> updateCurrent({ descriptor: e.target.value })} /> { const picked = await choosePath({ directory: false, title: "Select Deployment Descriptor", defaultPath: root ?? undefined, }); if (picked) updateCurrent({ descriptor: root && inside(root, picked) ? relativePath(root, picked) : picked, }); }} /> {current.kind === "web" && ( updateCurrent({ webRoot: e.target.value })} /> { const picked = await choosePath({ directory: true, title: "Select Web Resource Directory", defaultPath: root ?? undefined, }); if (picked) updateCurrent({ webRoot: root && inside(root, picked) ? relativePath(root, picked) : picked, }); }} /> )}
) : (
Facets describe the frameworks (Web, Spring, JPA) used by a module. Adding a Web facet also registers its WEB-INF/lib/*.jar archives with the Java language server.
)} {detectedSummary.length > 0 && (
{detectedSummary.map((d, i) => (
{d.kind} ({d.module}) {d.detail}
))}
)}
); } // --------------------------------------------------------------------------- // 5. Artifacts Section (JAR, WAR, Exploded WAR) function ArtifactsSection() { const root = useProject((s) => s.project?.root ?? null); const projectName = useProject((s) => s.project?.name ?? "app"); const [rawArtifacts, setRawArtifacts] = useProjectSetting( "projectStructure.artifacts", ); const [libraries] = useProjectSetting("projectStructure.libraries"); const artifacts = rawArtifacts ?? []; const [selectedIdx, setSelectedIdx] = useState(0); const [webArtifacts, setWebArtifacts] = useState([]); const nameId = useId(); const outId = useId(); const mainClassId = useId(); useEffect(() => { if (!root || !isTauri()) return; let live = true; call(commands.runTomcatArtifacts()) .then((list) => live && setWebArtifacts(list)) .catch(() => {}); return () => { live = false; }; }, [root]); const activeIdx = selectedIdx >= 0 && selectedIdx < artifacts.length ? selectedIdx : artifacts.length > 0 ? 0 : -1; const current = activeIdx >= 0 ? artifacts[activeIdx]! : null; const updateCurrent = (patch: Partial) => { if (!current || activeIdx < 0) return; const next = [...artifacts]; next[activeIdx] = { ...current, ...patch }; setRawArtifacts(next); }; const addArtifact = (kind: ArtifactKindValid) => { const base = projectName || "app"; const suffix = kind === "jar" ? "jar" : kind === "war" ? "war" : "war exploded"; const created: ArtifactConfigValid = { name: `${base}:${suffix}`, kind, module: ".", outputDirectory: `out/artifacts/${base}_${suffix.replace(/\s+/g, "_")}`, mainClass: "", includeLibraries: (libraries ?? []).map((l) => l.name), }; const next = [...artifacts, created]; setRawArtifacts(next); setSelectedIdx(next.length - 1); }; const removeArtifact = () => { if (activeIdx < 0) return; const next = artifacts.filter((_, idx) => idx !== activeIdx); setRawArtifacts(next); setSelectedIdx(Math.max(0, activeIdx - 1)); }; return (
Custom artifact packaging is not supported yet. Build and deploy artifacts defined by Maven or Gradle.
{artifacts.length === 0 && (
No custom artifacts configured.
)} {artifacts.map((a, idx) => ( ))}
{current ? (
updateCurrent({ name: e.target.value })} /> updateCurrent({ module: e.target.value })} /> updateCurrent({ outputDirectory: e.target.value })} /> { const picked = await choosePath({ directory: true, title: "Select Artifact Output Directory", defaultPath: root ?? undefined, }); if (picked) updateCurrent({ outputDirectory: root && inside(root, picked) ? relativePath(root, picked) : picked, }); }} /> {current.kind === "jar" && ( updateCurrent({ mainClass: e.target.value })} /> )} {(libraries ?? []).length > 0 && (
{(libraries ?? []).map((lib) => { const included = current.includeLibraries.includes(lib.name); return ( { const next = checked ? [...current.includeLibraries, lib.name] : current.includeLibraries.filter((n) => n !== lib.name); updateCurrent({ includeLibraries: next }); }} /> ); })}
)}
) : (
Configure JAR, WAR, or exploded WAR artifacts for packaging and application server deployment.
)} {webArtifacts.length > 0 && (
{webArtifacts.map((w) => (
{w.name} ({w.module || "."}) {w.tool}
))}
)}
); } // --------------------------------------------------------------------------- // 6. SDKs Section (IDEA 3-Column Master-Detail: SDK List | Selected SDK Details) function SdksSection() { const byKind = useSdks((s) => s.byKind); const [downloading, setDownloading] = useState(false); const [selectedKey, setSelectedKey] = useState(""); const [projectJdk, setProjectJdk] = useProjectSetting("languages.java.jdk"); useDetected("jdk"); useEffect(() => { for (const { kind } of SDK_KINDS) { void detectSdks(kind); } }, []); const refreshAll = () => { for (const { kind } of SDK_KINDS) { void detectSdks(kind, true); } }; const rows = useMemo(() => { const out: Array<{ key: string; kind: SdkKind; kindLabel: string; name: string; version: string; path: string }> = []; for (const { kind, label } of SDK_KINDS) { for (const sdk of byKind[kind] ?? []) { out.push({ key: `${kind}:${sdk.path}`, kind, kindLabel: label, name: sdk.name, version: sdk.version ?? "", path: sdk.path, }); } } return out; }, [byKind]); const activeSdk = rows.find((r) => r.key === selectedKey) ?? rows[0]; return (
{rows.length === 0 && (
No SDK installations detected yet.
)} {rows.map((r) => ( ))}
{activeSdk ? (
{activeSdk.kindLabel} {activeSdk.name} {activeSdk.version && {activeSdk.version}} {activeSdk.kind === "jdk" && ( )}
) : null}
{rows.length === 0 && ( )} {rows.map((r) => ( setSelectedKey(r.key)}> ))}
Type Name Version Home Path
No SDK installations detected yet.
{r.kindLabel} {r.name} {r.version || "—"} {tildify(r.path)}
{downloading && ( setDownloading(false)} onDownloaded={(sdk) => { setDownloading(false); setProjectJdk(sdk.path); }} /> )}
); } // --------------------------------------------------------------------------- // Exported Pages const NAV_GROUPS: Array<{ title: string; items: Array<{ id: ProjectStructureSectionId; label: string; icon: IconName }>; }> = [ { title: "Project Settings", items: [ { id: "project", label: "Project", icon: "folder" }, { id: "modules", label: "Modules", icon: "module" }, { id: "dependencies", label: "Dependencies", icon: "build-dependencies" }, { id: "libraries", label: "Libraries", icon: "folder-library" }, { id: "facets", label: "Facets", icon: "file-config" }, { id: "artifacts", label: "Artifacts", icon: "file-archive" }, ], }, { title: "Platform Settings", items: [{ id: "sdks", label: "SDKs", icon: "settings" }], }, ]; export function ProjectStructureDialog() { const open = useSettingsDialog((s) => s.projectStructureOpen); if (!open) return null; return ; } function ProjectStructureStatus() { const error = useSettingsDialog((s) => s.error); return ( {error && ( {tx`Could not save: ${error}`} )} ); } function ProjectStructureDialogInner() { const section = useSettingsDialog((s) => s.projectStructureSection); const { staged, base, globalBase, saving } = useSettingsDialog(); const hasProject = useProject((s) => !!s.project); const scope = hasProject ? "project" : "global"; const pageId = "projectStructure"; const ctx = useMemo(() => ({ pageId, scope }) as const, [scope]); const form = useSettingsFormFor(pageId, scope); const pending = useMemo(() => pendingChanges({ base, globalBase, staged }).length > 0, [base, globalBase, staged]); const activeGroup = NAV_GROUPS.find((g) => g.items.some((i) => i.id === section)) ?? NAV_GROUPS[0]!; const activeItem = activeGroup.items.find((i) => i.id === section) ?? activeGroup.items[0]!; const ok = async () => { if (await applySettings()) closeProjectStructure(); }; const buttons: DialogButton[] = [ { label: "OK", role: "default", disabled: saving, onClick: () => void ok() }, { label: "Cancel", role: "cancel", onClick: closeProjectStructure }, { label: "Apply", disabled: !pending || saving, onClick: () => void applySettings() }, ]; const onNavKeyDown = (e: React.KeyboardEvent) => { if ((e.key !== "ArrowDown" && e.key !== "ArrowUp") || e.altKey || e.metaKey || e.ctrlKey) return; e.preventDefault(); const idx = SECTION_TABS.findIndex((t) => t.id === section); const nextIdx = e.key === "ArrowDown" ? Math.min(SECTION_TABS.length - 1, idx + 1) : Math.max(0, idx - 1); const next = SECTION_TABS[nextIdx]; if (next) selectProjectStructureSection(next.id); }; return ( } buttons={buttons} >
{activeGroup.title} {activeItem.label}
{pending && !saving && ( )}
{section === "project" && } {section === "modules" && } {section === "dependencies" && } {section === "libraries" && } {section === "facets" && } {section === "artifacts" && } {section === "sdks" && }
); } export function ProjectStructurePage({ initialSection = "modules" }: { initialSection?: ProjectStructureSectionId }) { const [section, setSection] = useState(initialSection); return (
{SECTION_TABS.map((tab) => ( ))}
{section === "project" && } {section === "modules" && } {section === "dependencies" && } {section === "libraries" && } {section === "facets" && } {section === "artifacts" && } {section === "sdks" && }
); }