diff --git a/crates/ide-core/src/settings.rs b/crates/ide-core/src/settings.rs index a48e6924d..1392d93e4 100644 --- a/crates/ide-core/src/settings.rs +++ b/crates/ide-core/src/settings.rs @@ -67,6 +67,10 @@ pub struct Settings { pub mcp_server: McpServerSettings, /// Tools › Agents: Command Execution Policy. pub agent_security: AgentSecuritySettings, + /// Appearance & Behavior › Scopes: named file sets other settings refer to. + pub scopes: Vec, + /// Appearance & Behavior › File Colors. + pub file_colors: FileColorSettings, /// Plugin settings (`[contributes.settings]`): plugin id → its values by key. #[specta(type = BTreeMap>)] pub plugins: BTreeMap>, @@ -502,6 +506,8 @@ impl Default for Settings { agents: AgentSettings::default(), mcp_server: McpServerSettings::default(), agent_security: AgentSecuritySettings::default(), + scopes: Vec::new(), + file_colors: FileColorSettings::default(), plugins: BTreeMap::new(), } } @@ -512,6 +518,47 @@ fn default_keymap() -> &'static str { if cfg!(target_os = "macos") { "intellij-macos" } else { "intellij-windows" } } +/// A named set of files: `file:src//*.ts && !file:*.test.ts` (project-relative path patterns +/// joined with `||`, `&&`, `!` and parentheses). +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(default, rename_all = "camelCase")] +pub struct NamedScope { + pub name: String, + pub pattern: String, +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize, Type)] +#[serde(default, rename_all = "camelCase")] +pub struct FileColorSettings { + pub enabled: bool, + pub editor_tabs: bool, + pub project_view: bool, + /// Scope → colour; the first scope that holds a file gives its colour. + pub colors: Vec, +} + +impl Default for FileColorSettings { + fn default() -> Self { + let color = |scope: &str, color: &str| FileColor { scope: scope.into(), color: color.into() }; + Self { + enabled: true, + editor_tabs: true, + project_view: true, + colors: vec![color("Non-Project Files", "yellow"), color("Tests", "green")], + } + } +} + +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] +#[serde(default, rename_all = "camelCase")] +pub struct FileColor { + /// A built-in scope (`Tests`, `Production`, `Project Files`, `Non-Project Files`) or a + /// `scopes` entry, by name. + pub scope: String, + /// A palette name (`blue`, `green`, `orange`, `rose`, `violet`, `yellow`, `gray`) or `#rrggbb`. + pub color: String, +} + #[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize, Type)] #[serde(default, rename_all = "camelCase")] pub struct CustomKeymap { diff --git a/src/bindings.ts b/src/bindings.ts index 690ded5d0..f62f6e2e9 100644 --- a/src/bindings.ts +++ b/src/bindings.ts @@ -5259,6 +5259,24 @@ export type FieldValue = { kind: "label"; value: string } | { kind: "readonlyTex selected: string, } }; +export type FileColor = { + /** + * A built-in scope (`Tests`, `Production`, `Project Files`, `Non-Project Files`) or a + * `scopes` entry, by name. + */ + scope?: string, + /** A palette name (`blue`, `green`, `orange`, `rose`, `violet`, `yellow`, `gray`) or `#rrggbb`. */ + color?: string, +}; + +export type FileColorSettings = { + enabled?: boolean, + editorTabs?: boolean, + projectView?: boolean, + /** Scope → colour; the first scope that holds a file gives its colour. */ + colors?: FileColor[], +}; + export type FileCoverage = { path: IpcPath, /** Sorted by line. */ @@ -7782,6 +7800,15 @@ export type ModuleStructureSettings = { dependencies?: ModuleDependency[], }; +/** + * A named set of files: `file:src//*.ts && !file:*.test.ts` (project-relative path patterns + * joined with `||`, `&&`, `!` and parentheses). + */ +export type NamedScope = { + name?: string, + pattern?: string, +}; + /** * Where the Navigation Bar (the file path breadcrumbs) is shown. Mirrors * IDEA's `View | Appearance | Navigation Bar` (Top / Status Bar / Don't show). @@ -9895,6 +9922,10 @@ export type Settings_Deserialize = { mcpServer?: McpServerSettings, /** Tools › Agents: Command Execution Policy. */ agentSecurity?: AgentSecuritySettings, + /** Appearance & Behavior › Scopes: named file sets other settings refer to. */ + scopes?: NamedScope[], + /** Appearance & Behavior › File Colors. */ + fileColors?: FileColorSettings, /** Plugin settings (`[contributes.settings]`): plugin id → its values by key. */ plugins?: { [key in string]: { [key in string]: unknown } }, }; @@ -9961,6 +9992,10 @@ export type Settings_Serialize = { mcpServer: McpServerSettings, /** Tools › Agents: Command Execution Policy. */ agentSecurity: AgentSecuritySettings, + /** Appearance & Behavior › Scopes: named file sets other settings refer to. */ + scopes: NamedScope[], + /** Appearance & Behavior › File Colors. */ + fileColors: FileColorSettings, /** Plugin settings (`[contributes.settings]`): plugin id → its values by key. */ plugins: { [key in string]: { [key in string]: unknown } }, }; diff --git a/src/editor/core/view/EditorArea.tsx b/src/editor/core/view/EditorArea.tsx index 8e91ca69e..961907164 100644 --- a/src/editor/core/view/EditorArea.tsx +++ b/src/editor/core/view/EditorArea.tsx @@ -31,6 +31,7 @@ import { type EditorKindContribution, } from "@/workbench/contributions"; import { useDistractionFree } from "@/workbench/distractionFree"; +import { useFileColors } from "@/workbench/fileColors"; import { EmptyEditor } from "@/workbench/EditorArea"; import { EmptyState, @@ -177,6 +178,7 @@ function PaneView({ paneId }: { paneId: string }) { const dirty = tabs.map((tab, i) => inputDirty(tab.input, kinds) ?? textDirty[i] ?? false); const colors = useFileDecorations(useShallow(() => paths.map((p) => (p ? (getFileDecoration(p)?.color ?? "") : "")))); const tints = useFileDecorations(useShallow(() => paths.map((p) => (p ? (getFileDecoration(p)?.tint ?? "") : "")))); + const fileColors = useFileColors("editorTabs"); const hints = useTitleHints(); const [dropZone, setDropZone] = useState(null); @@ -225,7 +227,8 @@ function PaneView({ paneId }: { paneId: string }) { // (middle click, Shift+click, Delete) alive when its position is None. showCloseButton, color: colors[i] || undefined, - tint: tints[i] || undefined, + tint: + tints[i] || (fileColors && t.input.kind === "file" && t.input.path ? fileColors(t.input.path) : undefined), tooltip: virtualTooltip(t.input) ?? (showFullPathOnHover ? (t.input.path ?? name) : undefined), trailing: kindMark || pin ? ( @@ -244,6 +247,7 @@ function PaneView({ paneId }: { paneId: string }) { dirty, colors, tints, + fileColors, hints, showExtension, markModified, diff --git a/src/features/project-tree/ProjectView.tsx b/src/features/project-tree/ProjectView.tsx index cf208041b..072251fd1 100644 --- a/src/features/project-tree/ProjectView.tsx +++ b/src/features/project-tree/ProjectView.tsx @@ -33,6 +33,7 @@ import { useFileDecoration, type DecorationSegment, } from "@/workbench/contributions"; +import { useFileColors } from "@/workbench/fileColors"; import { FILES_DRAG, REMOTE_FILES_DRAG, @@ -461,6 +462,7 @@ export function ProjectView() { useFileIconRevision(); const root = useProjectTree((s) => s.root); const model = useProjectTree(selectModel); + const fileColors = useFileColors("projectView"); const expanded = useProjectTree((s) => s.expanded); const selected = useProjectTree((s) => s.selected); const editing = useProjectTree((s) => s.editing); @@ -872,6 +874,11 @@ export function ProjectView() { loadChildren={loadChildren} renderNode={renderNode} rowClassName={(n) => (n.excluded ? styles.excludedRow : undefined)} + rowTint={ + fileColors + ? (n) => (n.excluded || n.group || n.placeholder ? undefined : fileColors(n.path, n.dir)) + : undefined + } expanded={expanded} onExpandedChange={onExpandedChange} selected={selected} diff --git a/src/features/project-tree/contextMenu.test.ts b/src/features/project-tree/contextMenu.test.ts index 143cbbbb0..04a550759 100644 --- a/src/features/project-tree/contextMenu.test.ts +++ b/src/features/project-tree/contextMenu.test.ts @@ -151,8 +151,20 @@ describe("project view context menu", () => { "Git", "-", "Compare With…", + "File Color", ]); expect(sub(items, "Refactor")).toEqual(["Rename…", "Move File…", "Copy File…", "-", "Safe Delete…"]); + expect(sub(items, "File Color")).toEqual([ + "Blue", + "Green", + "Orange", + "Rose", + "Violet", + "Yellow", + "Gray", + "-", + "Edit File Colors…", + ]); expect(sub(items, "Open In")).toEqual([revealLabel(), "Terminal"]); expect(sub(items, "Git")?.slice(0, 4)).toEqual(["Commit File…", "Add", "-", "Annotate with Git Blame"]); }); diff --git a/src/features/project-tree/contextMenu.ts b/src/features/project-tree/contextMenu.ts index 82f6162ef..a2f67d940 100644 --- a/src/features/project-tree/contextMenu.ts +++ b/src/features/project-tree/contextMenu.ts @@ -9,6 +9,7 @@ import type { MenuItem } from "@/ui"; import { menuGroupItems, toolWindowService, type MenuGroupContext } from "@/workbench/contributions"; import type { FolderRole } from "@/platform/languageSettings"; import { directoryRole, markDirectory } from "./markDirectory"; +import { fileColorMenu } from "./fileColor"; import type { ProjectNode } from "./model"; import { packageKindAt } from "./packages"; import { @@ -456,6 +457,10 @@ export function contextMenuItems(nodes: ProjectNode[]): MenuItem[] { ], }); } + if (inProject && single && !single.root && !single.placeholder && !single.group) { + const color = fileColorMenu(single.path, single.dir); + if (color) push(color); + } return items; } diff --git a/src/features/project-tree/fileColor.ts b/src/features/project-tree/fileColor.ts new file mode 100644 index 000000000..df262f6c3 --- /dev/null +++ b/src/features/project-tree/fileColor.ts @@ -0,0 +1,55 @@ +/** + * Project view › File Color: gives a file or folder its own background colour, kept as a + * scope of that path and a File Colors entry in the project's settings. + */ +import { executeAction } from "@/platform/actions"; +import { FILE_COLOR_NAMES, ownFileColor, pathPattern, withOwnFileColor } from "@/platform/fileColors"; +import { call, commands, isTauri } from "@/platform/ipc"; +import { loadSettings, relativePath, useProject } from "@/platform/project"; +import type { MenuItem } from "@/ui"; + +const LABELS: Record<(typeof FILE_COLOR_NAMES)[number], string> = { + blue: "Blue", + green: "Green", + orange: "Orange", + rose: "Rose", + violet: "Violet", + yellow: "Yellow", + gray: "Gray", +}; + +export async function setFileColor(path: string, dir: boolean, color: string | null): Promise { + const { project, settings } = useProject.getState(); + if (!project || !isTauri()) return; + const next = withOwnFileColor(settings, relativePath(project.root, path), dir, color); + if (!next) return; + await call(commands.settingsSet("project", "scopes", JSON.stringify(next.scopes))); + await call(commands.settingsSet("project", "fileColors", JSON.stringify(next.fileColors))); + await loadSettings(); +} + +/** The File Color submenu of a file or folder inside the project, or null when it can't have one. */ +export function fileColorMenu(path: string, dir: boolean): MenuItem | null { + const { project, settings } = useProject.getState(); + if (!project) return null; + const rel = relativePath(project.root, path); + if (rel === path || !pathPattern(rel, dir)) return null; + const current = ownFileColor(rel, dir, settings)?.toLowerCase(); + return { + id: "fileColor", + label: "File Color", + submenu: [ + ...FILE_COLOR_NAMES.map((name): MenuItem => ({ + id: name, + label: LABELS[name], + checked: current === name, + run: () => void setFileColor(path, dir, name), + })), + { kind: "separator" }, + ...(current + ? [{ id: "clear", label: "Clear File Color", run: () => void setFileColor(path, dir, null) } as MenuItem] + : []), + { id: "edit", label: "Edit File Colors…", run: () => void executeAction("file.settings", "fileColors") }, + ], + }; +} diff --git a/src/features/settings/__tests__/contrast.test.ts b/src/features/settings/__tests__/contrast.test.ts index 75762306c..1e465aaf7 100644 --- a/src/features/settings/__tests__/contrast.test.ts +++ b/src/features/settings/__tests__/contrast.test.ts @@ -125,7 +125,7 @@ describe("theme tokens", () => { * the selection foreground, whose base default preserves syntax colours. */ const INHERITED_FROM_BASE = - /^--(project-color-|db-color-|caption-close-|fg-caption-close-|tint-strength$|fg-editor-selection$)/; + /^--(project-color-|db-color-|file-color-|caption-close-|fg-caption-close-|tint-strength$|file-tint-strength$|fg-editor-selection$)/; describe("palette themes", () => { const ISLANDS = ["light", "dark", "dark-hc"]; diff --git a/src/features/settings/components/Form.tsx b/src/features/settings/components/Form.tsx index caa74a478..b5ff24629 100644 --- a/src/features/settings/components/Form.tsx +++ b/src/features/settings/components/Form.tsx @@ -225,7 +225,8 @@ export function Select({ export interface ColorSwatchesProps { value: string; - presets: readonly { value: string; label: string }[]; + /** `css`: how the swatch is drawn when `value` is a name rather than a colour. */ + presets: readonly { value: string; label: string; css?: string }[]; onChange: (value: string) => void; /** Offer a custom colour picker + hex field. */ allowCustom?: boolean; @@ -253,7 +254,7 @@ export function ColorSwatches({ value, presets, onChange, allowCustom = true, .. className={clsx(styles.swatch, on && styles.swatchOn)} onClick={() => onChange(p.value)} > - + ); })} diff --git a/src/features/settings/model/schema.ts b/src/features/settings/model/schema.ts index 8c2619e65..3f162fe3c 100644 --- a/src/features/settings/model/schema.ts +++ b/src/features/settings/model/schema.ts @@ -4,6 +4,8 @@ * so `validateSettings` never throws — anything unknown or malformed falls * back to the default (mirrors `ide-core::settings` defaults). */ +import { DEFAULT_FILE_COLORS, validateFileColors, type FileColorSettings } from "@/platform/fileColors"; +import { validateScopes, type NamedScope } from "@/platform/scopes"; import { validateCMake } from "@/platform/cmakeSettings"; import { SUPPORTED_LOCALES, type Locale } from "@/platform/i18n"; import { DEFAULT_IGNORED_NAMES } from "@/platform/ignoredNames"; @@ -59,6 +61,8 @@ export interface CustomKeymapSettings { export interface ValidSettings extends WorkflowSettings { plugins: Record>; + scopes: NamedScope[]; + fileColors: FileColorSettings; general: { reopenLastProject: boolean; confirmExit: boolean; @@ -159,6 +163,8 @@ export { ACCENT_PRESETS } from "@/workbench/theme"; export const DEFAULT_SETTINGS: ValidSettings = { plugins: {}, + scopes: [], + fileColors: DEFAULT_FILE_COLORS, general: { reopenLastProject: true, confirmExit: true, @@ -332,6 +338,8 @@ 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), + fileColors: validateFileColors(root.fileColors), general: { ...validateGeneralExtras(g), reopenLastProject: bool(g.reopenLastProject, d.general.reopenLastProject), diff --git a/src/features/settings/pages/Scopes.module.css b/src/features/settings/pages/Scopes.module.css new file mode 100644 index 000000000..8e474c111 --- /dev/null +++ b/src/features/settings/pages/Scopes.module.css @@ -0,0 +1,28 @@ +.error { + color: var(--danger); +} +.color { + display: inline-flex; + align-items: center; + gap: var(--space-1-5); +} +.swatch { + flex: none; + width: 12px; + height: 12px; + border-radius: 3px; + border: 1px solid var(--border-strong); +} +.custom { + display: inline-flex; + align-items: center; + gap: var(--space-2); +} +.picker { + width: 32px; + height: 22px; + padding: 0; + border: 1px solid var(--border-strong); + border-radius: var(--radius-sm, 4px); + background: none; +} diff --git a/src/features/settings/pages/registry.tsx b/src/features/settings/pages/registry.tsx index 6b41d4b95..622a55371 100644 --- a/src/features/settings/pages/registry.tsx +++ b/src/features/settings/pages/registry.tsx @@ -11,6 +11,7 @@ import { EXECUTION_PAGES } from "./execution"; import { LANGUAGE_PAGES } from "./languages"; import { OptionsPage } from "./OptionsPage"; import { RUN_TARGET_PAGES } from "./runTargets"; +import { SCOPE_PAGES } from "./scopes"; import { specLabels, type PageSpec } from "./spec"; import { SSH_PAGES } from "./ssh"; import { TOOLS_PAGES } from "./tools"; @@ -18,6 +19,7 @@ import { VCS_PAGES } from "./vcs"; const BUILTIN_PAGES = [ ...BEHAVIOR_PAGES, + ...SCOPE_PAGES, UPDATES_PAGE, ...CORE_PAGES, ...EDITOR_PAGES, diff --git a/src/features/settings/pages/scopes.tsx b/src/features/settings/pages/scopes.tsx new file mode 100644 index 000000000..ecaedfb94 --- /dev/null +++ b/src/features/settings/pages/scopes.tsx @@ -0,0 +1,313 @@ +/** + * Appearance & Behavior › Scopes (named file sets) and › File Colors (a background + * colour per scope in the project view and on editor tabs). Both are project settings. + */ +import { useId, useState } from "react"; +import clsx from "clsx"; +import { FILE_COLOR_NAMES, fileColorCss, validateFileColors, type FileColorEntry } from "@/platform/fileColors"; +import { tx } from "@/platform/i18n"; +import { BUILTIN_SCOPES, scopeError, validateScopes, type NamedScope } from "@/platform/scopes"; +import { IconButton, Input, T, type SelectOption } from "@/ui"; +import { ColorSwatches, Row, Section, Select } from "../components/Form"; +import { useSetting } from "../components/context"; +import { APPEARANCE_GROUP } from "./behavior"; +import type { PageSpec } from "./spec"; +import styles from "./Workflow.module.css"; +import own from "./Scopes.module.css"; + +/** Toolbar of an ordered list: add, remove, move up / down. */ +function ListToolbar({ + label, + index, + count, + onAdd, + onRemove, + onMove, +}: { + label: string; + index: number; + count: number; + onAdd: () => void; + onRemove: () => void; + onMove: (d: -1 | 1) => void; +}) { + return ( +
+ + + onMove(-1)} /> + = count - 1} + onClick={() => onMove(1)} + /> +
+ ); +} + +function moved(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]; + [next[index], next[j]] = [next[j]!, next[index]!]; + return next; +} + +/** A name not taken yet: `Scope`, `Scope 2`, … */ +function freshName(taken: readonly string[]): string { + const base = tx("Scope"); + for (let n = 1; ; n++) { + const name = n === 1 ? base : `${base} ${n}`; + if (!taken.includes(name)) return name; + } +} + +/** A pattern, the same in every language. */ +const PATTERN_EXAMPLE = "file:src//*"; + +function errorText(error: { message: string; at: number }): string { + const message = tx(error.message); + const column = error.at + 1; + return tx`${message} at column ${column}`; +} + +function ScopesEditor() { + const [raw, setRaw] = useSetting("scopes"); + const scopes = validateScopes(raw); + const [selected, setSelected] = useState(0); + const index = scopes.length ? Math.min(selected, scopes.length - 1) : -1; + const current = scopes[index]; + const nameId = useId(); + const patternId = useId(); + const set = (next: NamedScope[]) => setRaw(next); + const update = (patch: Partial) => set(scopes.map((s, i) => (i === index ? { ...s, ...patch } : s))); + const error = current?.pattern.trim() ? scopeError(current.pattern) : null; + const taken = [...BUILTIN_SCOPES, ...scopes.map((s) => s.name)]; + const nameClash = !!current && taken.filter((n) => n === current.name).length > 1; + + return ( +
+
+ { + set([...scopes, { name: freshName(taken), pattern: "" }]); + setSelected(scopes.length); + }} + onRemove={() => set(scopes.filter((_, i) => i !== index))} + onMove={(d) => { + const next = moved(scopes, index, d); + if (next) { + set(next); + setSelected(index + d); + } + }} + /> +
+ {scopes.length === 0 && ( +
+ No scopes. Click + to add one. +
+ )} + {scopes.map((s, i) => ( +
setSelected(i)} + > + {s.name} + + {s.pattern} + +
+ ))} +
+
+ {current && ( +
+ + update({ name: e.target.value })} + /> + + + {errorText(error)} + + ) : ( + "file:src//*.ts && !file:*.test.ts — paths are relative to the project; // is any folders, * any characters. file[module]:pattern limits a pattern to a module." + ) + } + > + update({ pattern: e.target.value })} + /> + +
+ )} +
+ ); +} + +const COLOR_LABELS: Record = { + blue: "Blue", + green: "Green", + orange: "Orange", + rose: "Rose", + violet: "Violet", + yellow: "Yellow", + gray: "Gray", +}; + +const colorLabel = (color: string) => COLOR_LABELS[color.toLowerCase()] ?? color; + +function FileColorsEditor() { + const [raw, setRaw] = useSetting("fileColors"); + const [rawScopes] = useSetting("scopes"); + const settings = validateFileColors(raw); + const colors = settings.colors; + const [selected, setSelected] = useState(0); + const index = colors.length ? Math.min(selected, colors.length - 1) : -1; + const current = colors[index]; + const set = (next: FileColorEntry[]) => setRaw({ ...settings, colors: next }); + const update = (patch: Partial) => set(colors.map((c, i) => (i === index ? { ...c, ...patch } : c))); + + const scopeNames = [...BUILTIN_SCOPES, ...validateScopes(rawScopes).map((s) => s.name)]; + const scopeOptions: SelectOption[] = scopeNames.map((n) => ({ value: n, label: n })); + if (current && !scopeNames.includes(current.scope)) + scopeOptions.push({ value: current.scope, label: tx`${current.scope} (missing)` }); + const presets = FILE_COLOR_NAMES.map((n) => ({ value: n, label: colorLabel(n), css: fileColorCss(n) })); + + return ( +
+
+ { + const scope = scopeNames.find((n) => !colors.some((c) => c.scope === n)) ?? scopeNames[0]!; + set([...colors, { scope, color: "blue" }]); + setSelected(colors.length); + }} + onRemove={() => set(colors.filter((_, i) => i !== index))} + onMove={(d) => { + const next = moved(colors, index, d); + if (next) { + set(next); + setSelected(index + d); + } + }} + /> +
+ {colors.length === 0 && ( +
+ No file colors. Click + to add one. +
+ )} + {colors.map((c, i) => ( +
setSelected(i)} + > + {tx(c.scope)} + + + {tx(colorLabel(c.color))} + +
+ ))} +
+
+ {current && ( +
+ +