mirror of
https://github.com/l0ng-ai/openidea.git
synced 2026-11-19 00:10:00 +00:00
feat(appearance): scopes and file colors for the project view and editor tabs (#3624)
Settings › Appearance & Behavior gets Scopes (named file sets as file:pattern expressions with ||, && and !, optionally limited to a module) and File Colors (a background colour per scope, first match wins, in the project view and on editor tabs; on by default with Tests green and Non-Project Files yellow). The project view's context menu gets File Color for a file or folder, kept as a scope of that path first in the project's File Colors, with Clear File Color. Closes #3183
This commit is contained in:
@@ -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<NamedScope>,
|
||||
/// Appearance & Behavior › File Colors.
|
||||
pub file_colors: FileColorSettings,
|
||||
/// Plugin settings (`[contributes.settings]`): plugin id → its values by key.
|
||||
#[specta(type = BTreeMap<String, BTreeMap<String, specta_typescript::Unknown>>)]
|
||||
pub plugins: BTreeMap<String, serde_json::Map<String, serde_json::Value>>,
|
||||
@@ -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<FileColor>,
|
||||
}
|
||||
|
||||
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 {
|
||||
|
||||
@@ -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 } },
|
||||
};
|
||||
|
||||
@@ -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<DropZone | null>(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,
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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"]);
|
||||
});
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
|
||||
@@ -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<void> {
|
||||
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") },
|
||||
],
|
||||
};
|
||||
}
|
||||
@@ -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"];
|
||||
|
||||
@@ -225,7 +225,8 @@ export function Select<V extends string>({
|
||||
|
||||
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)}
|
||||
>
|
||||
<span className={styles.swatchColor} style={{ background: p.value }} />
|
||||
<span className={styles.swatchColor} style={{ background: p.css ?? p.value }} />
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
|
||||
@@ -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<string, Record<string, unknown>>;
|
||||
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),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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 (
|
||||
<div className={styles.toolbar} role="toolbar" aria-label={tx(label)}>
|
||||
<IconButton icon="plus" title="Add" size="small" onClick={onAdd} />
|
||||
<IconButton icon="minus" title="Remove" size="small" disabled={index < 0} onClick={onRemove} />
|
||||
<IconButton icon="arrow-up" title="Move Up" size="small" disabled={index <= 0} onClick={() => onMove(-1)} />
|
||||
<IconButton
|
||||
icon="arrow-down"
|
||||
title="Move Down"
|
||||
size="small"
|
||||
disabled={index < 0 || index >= count - 1}
|
||||
onClick={() => onMove(1)}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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];
|
||||
[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<unknown>("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<NamedScope>) => 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 (
|
||||
<div className={styles.toolsLayout}>
|
||||
<div className={styles.tableBox}>
|
||||
<ListToolbar
|
||||
label="Scopes actions"
|
||||
index={index}
|
||||
count={scopes.length}
|
||||
onAdd={() => {
|
||||
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);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className={styles.toolList} role="listbox" aria-label={tx("Scopes")}>
|
||||
{scopes.length === 0 && (
|
||||
<div className={clsx(styles.toolRow, styles.empty)}>
|
||||
<T>No scopes. Click + to add one.</T>
|
||||
</div>
|
||||
)}
|
||||
{scopes.map((s, i) => (
|
||||
<div
|
||||
key={i}
|
||||
role="option"
|
||||
aria-selected={i === index}
|
||||
className={clsx(styles.toolRow, i === index && styles.toolRowSelected)}
|
||||
onMouseDown={() => setSelected(i)}
|
||||
>
|
||||
<span className={styles.toolName}>{s.name}</span>
|
||||
<span className={styles.toolGroup} title={s.pattern}>
|
||||
{s.pattern}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{current && (
|
||||
<Section title="Scope">
|
||||
<Row label="Name" htmlFor={nameId} className={styles.alignedRow}>
|
||||
<Input
|
||||
id={nameId}
|
||||
className={styles.wide}
|
||||
value={current.name}
|
||||
invalid={nameClash || !current.name.trim()}
|
||||
onChange={(e) => update({ name: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
<Row
|
||||
label="Pattern"
|
||||
htmlFor={patternId}
|
||||
className={styles.alignedRow}
|
||||
hint={
|
||||
error ? (
|
||||
<span className={own.error} role="alert">
|
||||
{errorText(error)}
|
||||
</span>
|
||||
) : (
|
||||
"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."
|
||||
)
|
||||
}
|
||||
>
|
||||
<Input
|
||||
id={patternId}
|
||||
mono
|
||||
className={styles.wide}
|
||||
value={current.pattern}
|
||||
invalid={!!error}
|
||||
placeholder={PATTERN_EXAMPLE}
|
||||
onChange={(e) => update({ pattern: e.target.value })}
|
||||
/>
|
||||
</Row>
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
const COLOR_LABELS: Record<string, string> = {
|
||||
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<unknown>("fileColors");
|
||||
const [rawScopes] = useSetting<unknown>("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<FileColorEntry>) => 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 (
|
||||
<div className={styles.toolsLayout}>
|
||||
<div className={styles.tableBox}>
|
||||
<ListToolbar
|
||||
label="File colors actions"
|
||||
index={index}
|
||||
count={colors.length}
|
||||
onAdd={() => {
|
||||
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);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<div className={styles.toolList} role="listbox" aria-label={tx("File colors")}>
|
||||
{colors.length === 0 && (
|
||||
<div className={clsx(styles.toolRow, styles.empty)}>
|
||||
<T>No file colors. Click + to add one.</T>
|
||||
</div>
|
||||
)}
|
||||
{colors.map((c, i) => (
|
||||
<div
|
||||
key={i}
|
||||
role="option"
|
||||
aria-selected={i === index}
|
||||
className={clsx(styles.toolRow, i === index && styles.toolRowSelected)}
|
||||
onMouseDown={() => setSelected(i)}
|
||||
>
|
||||
<span className={styles.toolName}>{tx(c.scope)}</span>
|
||||
<span className={own.color}>
|
||||
<span className={own.swatch} style={{ background: fileColorCss(c.color) }} aria-hidden />
|
||||
{tx(colorLabel(c.color))}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{current && (
|
||||
<Section title="File Color">
|
||||
<Row label="Scope" className={styles.alignedRow}>
|
||||
<Select
|
||||
value={current.scope}
|
||||
options={scopeOptions}
|
||||
onChange={(scope) => update({ scope })}
|
||||
aria-label="Scope"
|
||||
/>
|
||||
</Row>
|
||||
<Row label="Color" className={styles.alignedRow}>
|
||||
<ColorSwatches
|
||||
value={current.color}
|
||||
presets={presets}
|
||||
onChange={(color) => update({ color })}
|
||||
aria-label="Color"
|
||||
/>
|
||||
</Row>
|
||||
</Section>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export const SCOPE_PAGES: PageSpec[] = [
|
||||
{
|
||||
id: "fileColors",
|
||||
title: "File Colors",
|
||||
group: APPEARANCE_GROUP,
|
||||
order: 1.5,
|
||||
projectScope: true,
|
||||
defaultScope: "project",
|
||||
keywords: ["colour", "color", "tab", "background", "tests", "non-project"],
|
||||
sections: [
|
||||
{
|
||||
options: [
|
||||
{ kind: "toggle", key: "fileColors.enabled", label: "Enable file colors" },
|
||||
{ kind: "toggle", key: "fileColors.editorTabs", label: "Use in editor tabs" },
|
||||
{ kind: "toggle", key: "fileColors.projectView", label: "Use in project view" },
|
||||
],
|
||||
},
|
||||
{
|
||||
options: [
|
||||
{
|
||||
kind: "custom",
|
||||
label: "File Colors",
|
||||
keywords: ["Scope", "Color", "Custom", "Hex value"],
|
||||
component: FileColorsEditor,
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "scopes",
|
||||
title: "Scopes",
|
||||
group: APPEARANCE_GROUP,
|
||||
order: 1.6,
|
||||
projectScope: true,
|
||||
defaultScope: "project",
|
||||
keywords: ["scope", "file set", "pattern"],
|
||||
sections: [
|
||||
{
|
||||
options: [{ kind: "custom", label: "Scopes", keywords: ["Name", "Pattern"], component: ScopesEditor }],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
@@ -0,0 +1,129 @@
|
||||
/**
|
||||
* File Colors (Settings › Appearance & Behavior › File Colors): files of a scope get a
|
||||
* background colour in the project view and on their editor tabs. The first scope in the
|
||||
* list that holds a file decides its colour.
|
||||
*/
|
||||
import { inScope, validateScopes, type NamedScope, type ScopeContext } from "./scopes";
|
||||
|
||||
export const FILE_COLOR_NAMES = ["blue", "green", "orange", "rose", "violet", "yellow", "gray"] as const;
|
||||
|
||||
export interface FileColorEntry {
|
||||
scope: string;
|
||||
/** A palette name or `#rrggbb`. */
|
||||
color: string;
|
||||
}
|
||||
|
||||
export interface FileColorSettings {
|
||||
enabled: boolean;
|
||||
editorTabs: boolean;
|
||||
projectView: boolean;
|
||||
colors: FileColorEntry[];
|
||||
}
|
||||
|
||||
export const DEFAULT_FILE_COLORS: FileColorSettings = {
|
||||
enabled: true,
|
||||
editorTabs: true,
|
||||
projectView: true,
|
||||
colors: [
|
||||
{ scope: "Non-Project Files", color: "yellow" },
|
||||
{ scope: "Tests", color: "green" },
|
||||
],
|
||||
};
|
||||
|
||||
const HEX = /^#[0-9a-f]{6}$/i;
|
||||
|
||||
export function validateFileColors(raw: unknown): FileColorSettings {
|
||||
const v = raw && typeof raw === "object" && !Array.isArray(raw) ? (raw as Record<string, unknown>) : {};
|
||||
const d = DEFAULT_FILE_COLORS;
|
||||
const bool = (x: unknown, def: boolean) => (typeof x === "boolean" ? x : def);
|
||||
const colors = Array.isArray(v.colors)
|
||||
? v.colors.flatMap((c: unknown) => {
|
||||
const e = c && typeof c === "object" ? (c as Record<string, unknown>) : {};
|
||||
return typeof e.scope === "string" && e.scope && typeof e.color === "string"
|
||||
? [{ scope: e.scope, color: e.color }]
|
||||
: [];
|
||||
})
|
||||
: d.colors;
|
||||
return {
|
||||
enabled: bool(v.enabled, d.enabled),
|
||||
editorTabs: bool(v.editorTabs, d.editorTabs),
|
||||
projectView: bool(v.projectView, d.projectView),
|
||||
colors,
|
||||
};
|
||||
}
|
||||
|
||||
/** The CSS colour of a stored colour value. */
|
||||
export function fileColorCss(color: string): string | undefined {
|
||||
const name = color.toLowerCase();
|
||||
if ((FILE_COLOR_NAMES as readonly string[]).includes(name)) return `var(--file-color-${name})`;
|
||||
return HEX.test(color) ? color : undefined;
|
||||
}
|
||||
|
||||
/** Where a file colour shows. */
|
||||
export type FileColorPlace = "editorTabs" | "projectView";
|
||||
|
||||
/** The colour of the absolute `path` from these settings, or undefined. */
|
||||
export function fileColorOf(
|
||||
path: string,
|
||||
settings: FileColorSettings,
|
||||
ctx: ScopeContext,
|
||||
dir = false,
|
||||
): string | undefined {
|
||||
if (!settings.enabled) return undefined;
|
||||
for (const entry of settings.colors) {
|
||||
if (inScope(entry.scope, path, ctx, dir)) return fileColorCss(entry.color);
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
let cachedRaw: unknown = Symbol("unset");
|
||||
let cached = DEFAULT_FILE_COLORS;
|
||||
/** The File Colors settings in the raw settings `fileColors` (cached per object). */
|
||||
export function fileColorSettings(raw: unknown): FileColorSettings {
|
||||
if (raw !== cachedRaw) {
|
||||
cachedRaw = raw;
|
||||
cached = validateFileColors(raw);
|
||||
}
|
||||
return cached;
|
||||
}
|
||||
|
||||
/**
|
||||
* A pattern for exactly `rel` (a folder: everything in it), or null when the path has
|
||||
* characters a pattern can't hold.
|
||||
*/
|
||||
export function pathPattern(rel: string, dir: boolean): string | null {
|
||||
if (!rel || /[\s()|&!*[\]]/.test(rel)) return null;
|
||||
return dir ? `file:${rel}//*` : `file:${rel}`;
|
||||
}
|
||||
|
||||
/** The colour given to `rel` itself through its own scope (Set File Color), if any. */
|
||||
export function ownFileColor(rel: string, dir: boolean, settings: unknown): string | null {
|
||||
const pattern = pathPattern(rel, dir);
|
||||
const s = settings as { scopes?: unknown; fileColors?: unknown } | null;
|
||||
const scope = validateScopes(s?.scopes).find((x) => x.name === rel && x.pattern === pattern);
|
||||
return (scope && validateFileColors(s?.fileColors).colors.find((c) => c.scope === scope.name)?.color) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The project's scopes and File Colors with `rel` given `color` (first in the list, so it
|
||||
* wins over broader scopes), or with that colour and its scope removed (`null`).
|
||||
*/
|
||||
export function withOwnFileColor(
|
||||
settings: unknown,
|
||||
rel: string,
|
||||
dir: boolean,
|
||||
color: string | null,
|
||||
): { scopes: NamedScope[]; fileColors: FileColorSettings } | null {
|
||||
const pattern = pathPattern(rel, dir);
|
||||
if (!pattern) return null;
|
||||
const s = settings as { scopes?: unknown; fileColors?: unknown } | null;
|
||||
const scopes = validateScopes(s?.scopes).filter((x) => x.name !== rel);
|
||||
const fileColors = validateFileColors(s?.fileColors);
|
||||
const colors = fileColors.colors.filter((c) => c.scope !== rel);
|
||||
return color
|
||||
? {
|
||||
scopes: [...scopes, { name: rel, pattern }],
|
||||
fileColors: { ...fileColors, colors: [{ scope: rel, color }, ...colors] },
|
||||
}
|
||||
: { scopes, fileColors: { ...fileColors, colors } };
|
||||
}
|
||||
@@ -1927,5 +1927,37 @@
|
||||
"Collapse All Files": "Collapse All Files",
|
||||
"Show Files in Separate Diff Tabs": "Show Files in Separate Diff Tabs",
|
||||
"Show All Files in One Diff View": "Show All Files in One Diff View",
|
||||
"No changes": "No changes"
|
||||
"No changes": "No changes",
|
||||
"Scopes actions": "Scopes actions",
|
||||
"Scopes": "Scopes",
|
||||
"No scopes. Click + to add one.": "No scopes. Click + to add one.",
|
||||
"Scope": "Scope",
|
||||
"Pattern": "Pattern",
|
||||
"{message} at column {column}": "{message} at column {column}",
|
||||
"')' expected": "')' expected",
|
||||
"'file:' expected": "'file:' expected",
|
||||
"':' expected": "':' expected",
|
||||
"']' expected": "']' expected",
|
||||
"Pattern expected": "Pattern expected",
|
||||
"Unexpected text": "Unexpected text",
|
||||
"File colors actions": "File colors actions",
|
||||
"File colors": "File colors",
|
||||
"No file colors. Click + to add one.": "No file colors. Click + to add one.",
|
||||
"File Color": "File Color",
|
||||
"Color": "Color",
|
||||
"File Colors": "File Colors",
|
||||
"Enable file colors": "Enable file colors",
|
||||
"Use in editor tabs": "Use in editor tabs",
|
||||
"Use in project view": "Use in project view",
|
||||
"Orange": "Orange",
|
||||
"Rose": "Rose",
|
||||
"Violet": "Violet",
|
||||
"Gray": "Gray",
|
||||
"Project Files": "Project Files",
|
||||
"Production": "Production",
|
||||
"Tests": "Tests",
|
||||
"Non-Project Files": "Non-Project Files",
|
||||
"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.": "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.",
|
||||
"Clear File Color": "Clear File Color",
|
||||
"Edit File Colors…": "Edit File Colors…"
|
||||
}
|
||||
|
||||
@@ -8328,5 +8328,29 @@
|
||||
"Expand All Files": "展开所有文件",
|
||||
"Collapse All Files": "折叠所有文件",
|
||||
"Show Files in Separate Diff Tabs": "在单独的差异标签页中显示文件",
|
||||
"Show All Files in One Diff View": "在一个差异视图中显示所有文件"
|
||||
"Show All Files in One Diff View": "在一个差异视图中显示所有文件",
|
||||
"Scopes actions": "作用域操作",
|
||||
"No scopes. Click + to add one.": "没有作用域。点击 + 添加。",
|
||||
"{message} at column {column}": "{message}(第 {column} 列)",
|
||||
"')' expected": "缺少 ')'",
|
||||
"'file:' expected": "缺少 'file:'",
|
||||
"':' expected": "缺少 ':'",
|
||||
"']' expected": "缺少 ']'",
|
||||
"Pattern expected": "缺少模式",
|
||||
"Unexpected text": "意外的文本",
|
||||
"File colors actions": "文件颜色操作",
|
||||
"File colors": "文件颜色",
|
||||
"No file colors. Click + to add one.": "没有文件颜色。点击 + 添加。",
|
||||
"File Color": "文件颜色",
|
||||
"File Colors": "文件颜色",
|
||||
"Enable file colors": "启用文件颜色",
|
||||
"Use in editor tabs": "在编辑器标签页中使用",
|
||||
"Use in project view": "在项目视图中使用",
|
||||
"Rose": "玫瑰色",
|
||||
"Gray": "灰色",
|
||||
"Production": "生产",
|
||||
"Non-Project Files": "非项目文件",
|
||||
"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.": "file:src//*.ts && !file:*.test.ts —— 路径相对于项目;// 表示任意层文件夹,* 表示任意字符。file[module]:pattern 将模式限定在某个模块内。",
|
||||
"Clear File Color": "清除文件颜色",
|
||||
"Edit File Colors…": "编辑文件颜色…"
|
||||
}
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
import { beforeEach, describe, expect, it } from "vitest";
|
||||
import {
|
||||
DEFAULT_FILE_COLORS,
|
||||
fileColorCss,
|
||||
fileColorOf,
|
||||
ownFileColor,
|
||||
validateFileColors,
|
||||
withOwnFileColor,
|
||||
} from "./fileColors";
|
||||
import { useProject } from "./project";
|
||||
import { filePatternRegExp, inScope, parseScope, scopeError, type ScopeContext } from "./scopes";
|
||||
|
||||
const ctx = (scopes: ScopeContext["scopes"] = [], extra: Partial<ScopeContext> = {}): ScopeContext => ({
|
||||
roots: [
|
||||
{ path: "src/test", kind: "test" },
|
||||
{ path: "build", kind: "excluded" },
|
||||
] as never,
|
||||
modules: [
|
||||
{ name: "p", path: "" },
|
||||
{ name: "web", path: "web" },
|
||||
],
|
||||
scopes,
|
||||
...extra,
|
||||
});
|
||||
|
||||
beforeEach(() => {
|
||||
useProject.setState({ project: { name: "p", root: "/p", trusted: true, settings: {} } as never });
|
||||
});
|
||||
|
||||
describe("file patterns", () => {
|
||||
const m = (pattern: string, path: string) => filePatternRegExp(pattern).test(path);
|
||||
|
||||
it("reads * within a name, ** and a trailing * as one name, // as any folders", () => {
|
||||
expect(m("src/*", "src/a.ts")).toBe(true);
|
||||
expect(m("src/*", "src/a/b.ts")).toBe(false);
|
||||
// A `*` followed by more of the name matches across folders.
|
||||
expect(m("src/*.ts", "src/a/b.ts")).toBe(true);
|
||||
expect(m("src/**.ts", "src/a/b.ts")).toBe(false);
|
||||
expect(m("src//*", "src/a/b/c.ts")).toBe(true);
|
||||
expect(m("src//*", "lib/a.ts")).toBe(false);
|
||||
expect(m("*.md", "README.md")).toBe(true);
|
||||
expect(m("*.md", "README.mdx")).toBe(false);
|
||||
// Folders end in `/`.
|
||||
expect(m("src//*", "src/a/")).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
describe("scope expressions", () => {
|
||||
it("combines file patterns with !, && and || in precedence order", () => {
|
||||
const scope = { name: "TS", pattern: "file:src//*.ts && !file:*.test.ts || file:README.md" };
|
||||
const c = ctx([scope]);
|
||||
expect(inScope("TS", "/p/src/a/b.ts", c)).toBe(true);
|
||||
expect(inScope("TS", "/p/src/a/b.test.ts", c)).toBe(false);
|
||||
expect(inScope("TS", "/p/README.md", c)).toBe(true);
|
||||
expect(inScope("TS", "/elsewhere/src/a.ts", c)).toBe(false);
|
||||
});
|
||||
|
||||
it("limits a pattern to a module", () => {
|
||||
const c = ctx([{ name: "Web", pattern: "file[web]:*.ts" }]);
|
||||
expect(inScope("Web", "/p/web/app.ts", c)).toBe(true);
|
||||
expect(inScope("Web", "/p/src/app.ts", c)).toBe(false);
|
||||
});
|
||||
|
||||
it("reports where a pattern goes wrong", () => {
|
||||
expect(scopeError("file:a && (file:b")).toEqual({ message: "')' expected", at: 17 });
|
||||
expect(scopeError("src/*")).toEqual({ message: "'file:' expected", at: 0 });
|
||||
expect(scopeError("file:")).toEqual({ message: "Pattern expected", at: 5 });
|
||||
expect(scopeError("file:a)")).toEqual({ message: "Unexpected text", at: 6 });
|
||||
expect(() => parseScope("(file:a || file:b) && !file:c")).not.toThrow();
|
||||
});
|
||||
|
||||
it("knows the built-in scopes", () => {
|
||||
const c = ctx([], { ownFolders: ["/scratches"] });
|
||||
expect(inScope("Tests", "/p/src/test/A.java", c)).toBe(true);
|
||||
expect(inScope("Production", "/p/src/main/A.java", c)).toBe(true);
|
||||
expect(inScope("Project Files", "/p/build/out.class", c)).toBe(false);
|
||||
expect(inScope("Non-Project Files", "/lib/rt.jar", c)).toBe(true);
|
||||
expect(inScope("Non-Project Files", "/scratches/a.sql", c)).toBe(false);
|
||||
expect(inScope("Non-Project Files", "/p/a.ts", c)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("file colors", () => {
|
||||
it("colours tests green and non-project files yellow by default; the first matching scope wins", () => {
|
||||
const c = ctx([{ name: "Docs", pattern: "file:*.md" }]);
|
||||
expect(fileColorOf("/p/src/test/A.java", DEFAULT_FILE_COLORS, c)).toBe("var(--file-color-green)");
|
||||
expect(fileColorOf("/lib/A.java", DEFAULT_FILE_COLORS, c)).toBe("var(--file-color-yellow)");
|
||||
expect(fileColorOf("/p/src/A.java", DEFAULT_FILE_COLORS, c)).toBeUndefined();
|
||||
const s = validateFileColors({
|
||||
colors: [
|
||||
{ scope: "Docs", color: "#112233" },
|
||||
{ scope: "Project Files", color: "Blue" },
|
||||
],
|
||||
});
|
||||
expect(fileColorOf("/p/a.md", s, c)).toBe("#112233");
|
||||
expect(fileColorOf("/p/a.ts", s, c)).toBe("var(--file-color-blue)");
|
||||
expect(fileColorOf("/p/a.ts", { ...s, enabled: false }, c)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("ignores colours it can't draw", () => {
|
||||
expect(fileColorCss("red; background: url(x)")).toBeUndefined();
|
||||
expect(fileColorCss("Gray")).toBe("var(--file-color-gray)");
|
||||
});
|
||||
});
|
||||
|
||||
describe("a file or folder's own colour", () => {
|
||||
it("adds a scope of the path ahead of the other colours, and removes both again", () => {
|
||||
const set = withOwnFileColor({}, "src/api", true, "rose")!;
|
||||
expect(set.scopes).toEqual([{ name: "src/api", pattern: "file:src/api//*" }]);
|
||||
expect(set.fileColors.colors[0]).toEqual({ scope: "src/api", color: "rose" });
|
||||
expect(set.fileColors.colors.slice(1)).toEqual(DEFAULT_FILE_COLORS.colors);
|
||||
expect(ownFileColor("src/api", true, set)).toBe("rose");
|
||||
const c = ctx(set.scopes);
|
||||
// Everything in the folder, including its tests, takes the folder's colour.
|
||||
expect(fileColorOf("/p/src/api/x_test.go", set.fileColors, c)).toBe("var(--file-color-rose)");
|
||||
expect(fileColorOf("/p/src/api", set.fileColors, c, true)).toBe("var(--file-color-rose)");
|
||||
expect(fileColorOf("/p/src/apix/a.go", set.fileColors, c)).toBeUndefined();
|
||||
|
||||
const recolored = withOwnFileColor(set, "src/api", true, "blue")!;
|
||||
expect(recolored.fileColors.colors.filter((x) => x.scope === "src/api")).toHaveLength(1);
|
||||
const cleared = withOwnFileColor(set, "src/api", true, null)!;
|
||||
expect(cleared.scopes).toEqual([]);
|
||||
expect(cleared.fileColors.colors).toEqual(DEFAULT_FILE_COLORS.colors);
|
||||
});
|
||||
|
||||
it("is not offered for paths a pattern can't name", () => {
|
||||
expect(withOwnFileColor({}, "my docs", true, "blue")).toBeNull();
|
||||
expect(withOwnFileColor({}, "", true, "blue")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,255 @@
|
||||
/**
|
||||
* Scopes (Settings › Appearance & Behavior › Scopes): named sets of files that other
|
||||
* settings refer to, e.g. File Colors. A scope's pattern is an expression over file
|
||||
* patterns: `file:src//*.ts && !file:*.test.ts`, `file[web]:*.ts` or `(a || b) && !c`.
|
||||
*
|
||||
* A file pattern matches the project-relative path (folders end in `/`): `*` stands for
|
||||
* any characters, `**` and a trailing `*` for characters within one name, and `//` for
|
||||
* any folders in between. `file[module]:` also requires the file to be in a module of that name.
|
||||
*/
|
||||
import { useMemo } from "react";
|
||||
import type { RootFolder } from "./languageSettings";
|
||||
import { useProject } from "./project";
|
||||
import {
|
||||
inFileSet,
|
||||
projectModules,
|
||||
projectRelative,
|
||||
useDetectedRoots,
|
||||
useEffectiveRoots,
|
||||
type ProjectModule,
|
||||
} from "./projectRoots";
|
||||
|
||||
export interface NamedScope {
|
||||
name: string;
|
||||
pattern: string;
|
||||
}
|
||||
|
||||
/** Scopes every project has, by name. */
|
||||
export const BUILTIN_SCOPES = ["Project Files", "Production", "Tests", "Non-Project Files"] as const;
|
||||
|
||||
type Node =
|
||||
| { kind: "file"; module: RegExp | null; path: RegExp }
|
||||
| { kind: "not"; of: Node }
|
||||
| { kind: "and" | "or"; left: Node; right: Node };
|
||||
|
||||
export class ScopeSyntaxError extends Error {
|
||||
constructor(
|
||||
message: string,
|
||||
readonly at: number,
|
||||
) {
|
||||
super(message);
|
||||
}
|
||||
}
|
||||
|
||||
/** The regular expression of a file pattern, read the way the pattern syntax defines it. */
|
||||
export function filePatternRegExp(pattern: string): RegExp {
|
||||
let out = "";
|
||||
let afterSlash = false;
|
||||
let afterStar = false;
|
||||
for (const c of pattern) {
|
||||
if (c !== "/" && afterSlash) {
|
||||
out += "\\/";
|
||||
afterSlash = false;
|
||||
}
|
||||
if (c !== "*" && afterStar) {
|
||||
out += ".*";
|
||||
afterStar = false;
|
||||
}
|
||||
if (c === "*") {
|
||||
if (afterStar) out += "[^/]*";
|
||||
afterStar = !afterStar;
|
||||
} else if (c === "/") {
|
||||
if (afterSlash) out += "\\/(.*\\/)?";
|
||||
afterSlash = !afterSlash;
|
||||
} else {
|
||||
out += c.replace(/[.+?^${}()|[\]\\]/g, "\\$&");
|
||||
}
|
||||
}
|
||||
if (afterStar) out += "[^/]*";
|
||||
return new RegExp(`^${out}$`);
|
||||
}
|
||||
|
||||
/** A module name pattern: `*` stands for any characters. */
|
||||
const moduleRegExp = (pattern: string) =>
|
||||
new RegExp(`^${pattern.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*")}$`);
|
||||
|
||||
/** Parses a scope pattern; throws `ScopeSyntaxError` with the offset of the problem. */
|
||||
export function parseScope(text: string): Node {
|
||||
let i = 0;
|
||||
const ws = () => {
|
||||
while (i < text.length && /\s/.test(text[i]!)) i++;
|
||||
};
|
||||
const eat = (token: string) => {
|
||||
ws();
|
||||
if (!text.startsWith(token, i)) return false;
|
||||
i += token.length;
|
||||
return true;
|
||||
};
|
||||
const or = (): Node => {
|
||||
let left = and();
|
||||
while (eat("||")) left = { kind: "or", left, right: and() };
|
||||
return left;
|
||||
};
|
||||
const and = (): Node => {
|
||||
let left = unary();
|
||||
while (eat("&&")) left = { kind: "and", left, right: unary() };
|
||||
return left;
|
||||
};
|
||||
const unary = (): Node => {
|
||||
if (eat("!")) return { kind: "not", of: unary() };
|
||||
if (eat("(")) {
|
||||
const inner = or();
|
||||
if (!eat(")")) throw new ScopeSyntaxError("')' expected", i);
|
||||
return inner;
|
||||
}
|
||||
return atom();
|
||||
};
|
||||
const atom = (): Node => {
|
||||
ws();
|
||||
const start = i;
|
||||
if (!text.startsWith("file", i)) throw new ScopeSyntaxError("'file:' expected", start);
|
||||
i += 4;
|
||||
let module: RegExp | null = null;
|
||||
if (text[i] === "[") {
|
||||
const close = text.indexOf("]", i);
|
||||
if (close < 0) throw new ScopeSyntaxError("']' expected", i);
|
||||
module = moduleRegExp(text.slice(i + 1, close).trim());
|
||||
i = close + 1;
|
||||
}
|
||||
if (text[i] !== ":") throw new ScopeSyntaxError("':' expected", i);
|
||||
i++;
|
||||
const from = i;
|
||||
// A pattern runs to whitespace or an operator.
|
||||
while (i < text.length && !/[\s()|&!]/.test(text[i]!)) i++;
|
||||
if (i === from) throw new ScopeSyntaxError("Pattern expected", i);
|
||||
return { kind: "file", module, path: filePatternRegExp(text.slice(from, i)) };
|
||||
};
|
||||
const node = or();
|
||||
ws();
|
||||
if (i < text.length) throw new ScopeSyntaxError("Unexpected text", i);
|
||||
return node;
|
||||
}
|
||||
|
||||
/** The problem with a scope pattern and its offset, or null when it parses. */
|
||||
export function scopeError(pattern: string): { message: string; at: number } | null {
|
||||
try {
|
||||
parseScope(pattern);
|
||||
return null;
|
||||
} catch (e) {
|
||||
return e instanceof ScopeSyntaxError ? { message: e.message, at: e.at } : { message: String(e), at: 0 };
|
||||
}
|
||||
}
|
||||
|
||||
/** What a scope is matched against. */
|
||||
export interface ScopeContext {
|
||||
roots: readonly RootFolder[];
|
||||
modules: readonly ProjectModule[];
|
||||
scopes: readonly NamedScope[];
|
||||
/** Folders outside the project that are not Non-Project Files either (scratches). */
|
||||
ownFolders?: readonly string[];
|
||||
}
|
||||
|
||||
/** The innermost module holding the file (`rel` in the project, `path` absolute). */
|
||||
function moduleOf(rel: string, path: string, modules: readonly ProjectModule[]): ProjectModule | undefined {
|
||||
let best: ProjectModule | undefined;
|
||||
for (const m of modules) {
|
||||
// Workspace members have absolute paths.
|
||||
const at = m.path.startsWith("/") ? path : rel;
|
||||
const holds = m.path === "" || at === m.path || at.startsWith(`${m.path}/`);
|
||||
if (holds && (!best || m.path.length > best.path.length)) best = m;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function matches(node: Node, rel: string, path: string, dir: boolean, ctx: ScopeContext): boolean {
|
||||
switch (node.kind) {
|
||||
case "not":
|
||||
return !matches(node.of, rel, path, dir, ctx);
|
||||
case "and":
|
||||
return matches(node.left, rel, path, dir, ctx) && matches(node.right, rel, path, dir, ctx);
|
||||
case "or":
|
||||
return matches(node.left, rel, path, dir, ctx) || matches(node.right, rel, path, dir, ctx);
|
||||
case "file": {
|
||||
if (node.module) {
|
||||
const m = moduleOf(rel, path, ctx.modules);
|
||||
if (!m || !node.module.test(m.name)) return false;
|
||||
}
|
||||
return node.path.test(dir ? `${rel}/` : rel);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const parsed = new Map<string, Node | null>();
|
||||
function compiled(pattern: string): Node | null {
|
||||
let node = parsed.get(pattern);
|
||||
if (node === undefined) {
|
||||
try {
|
||||
node = parseScope(pattern);
|
||||
} catch {
|
||||
node = null;
|
||||
}
|
||||
if (parsed.size > 200) parsed.clear();
|
||||
parsed.set(pattern, node);
|
||||
}
|
||||
return node;
|
||||
}
|
||||
|
||||
/** Whether the absolute `path` is in the scope called `name` (built-in or user-defined). */
|
||||
export function inScope(name: string, path: string, ctx: ScopeContext, dir = false): boolean {
|
||||
switch (name) {
|
||||
case "Project Files":
|
||||
return inFileSet("all", path, ctx.roots);
|
||||
case "Production":
|
||||
return inFileSet("production", path, ctx.roots);
|
||||
case "Tests":
|
||||
return inFileSet("test", path, ctx.roots);
|
||||
case "Non-Project Files":
|
||||
return projectRelative(path) === null && !ctx.ownFolders?.some((d) => path === d || path.startsWith(`${d}/`));
|
||||
}
|
||||
const scope = ctx.scopes.find((s) => s.name === name);
|
||||
const node = scope ? compiled(scope.pattern) : null;
|
||||
const rel = projectRelative(path);
|
||||
return !!node && rel !== null && rel !== "" && matches(node, rel, path, dir, ctx);
|
||||
}
|
||||
|
||||
/** User scopes from settings. */
|
||||
export function validateScopes(raw: unknown): NamedScope[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.flatMap((s) =>
|
||||
s && typeof s === "object" && typeof s.name === "string" && s.name.trim()
|
||||
? [{ name: s.name, pattern: typeof s.pattern === "string" ? s.pattern : "" }]
|
||||
: [],
|
||||
);
|
||||
}
|
||||
|
||||
let cachedRaw: unknown = Symbol("unset");
|
||||
let cachedScopes: NamedScope[] = [];
|
||||
/** The project's user scopes (cached per settings object). */
|
||||
export function userScopes(raw: unknown = (useProject.getState().settings as { scopes?: unknown } | null)?.scopes) {
|
||||
if (raw !== cachedRaw) {
|
||||
cachedRaw = raw;
|
||||
cachedScopes = validateScopes(raw);
|
||||
}
|
||||
return cachedScopes;
|
||||
}
|
||||
|
||||
function modulesOf(detected: readonly RootFolder[]): ProjectModule[] {
|
||||
const project = useProject.getState().project;
|
||||
return project?.workspace
|
||||
? project.workspace.projects.map((path) => ({ path, name: path.slice(path.lastIndexOf("/") + 1) }))
|
||||
: projectModules(detected, project?.name ?? "");
|
||||
}
|
||||
|
||||
/** The scope context, following roots and settings. */
|
||||
export function useScopeContext(): ScopeContext {
|
||||
const roots = useEffectiveRoots();
|
||||
const detected = useDetectedRoots();
|
||||
const raw = useProject((s) => (s.settings as { scopes?: unknown } | null)?.scopes);
|
||||
const project = useProject((s) => s.project);
|
||||
return useMemo(
|
||||
() => ({ roots, modules: modulesOf(detected), scopes: userScopes(raw) }),
|
||||
// `project` changes the module names.
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
[roots, detected, raw, project],
|
||||
);
|
||||
}
|
||||
@@ -477,6 +477,15 @@ html {
|
||||
--db-color-blue: #3b92b8;
|
||||
--db-color-violet: #955ae0;
|
||||
--tint-strength: 22%;
|
||||
/* File Colors palette (Appearance › File Colors); drawn as tints like the data source colours. */
|
||||
--file-color-blue: #3b92b8;
|
||||
--file-color-green: #5fad65;
|
||||
--file-color-orange: #e08855;
|
||||
--file-color-rose: #e06c88;
|
||||
--file-color-violet: #955ae0;
|
||||
--file-color-yellow: #d4b106;
|
||||
--file-color-gray: #8c8c8c;
|
||||
--file-tint-strength: 14%;
|
||||
}
|
||||
|
||||
/* Windows caption buttons (frameless title bar): the system close red in every theme. */
|
||||
|
||||
@@ -68,6 +68,17 @@
|
||||
.row:hover {
|
||||
background: var(--bg-tree-hover, color-mix(in srgb, var(--fg-strong) 4%, transparent));
|
||||
}
|
||||
/* File Colors: the row's background takes its scope's colour. */
|
||||
.tinted {
|
||||
background: color-mix(in srgb, var(--row-tint) var(--file-tint-strength, 14%), transparent);
|
||||
}
|
||||
.tinted:hover {
|
||||
background: color-mix(
|
||||
in srgb,
|
||||
var(--row-tint) var(--file-tint-strength, 14%),
|
||||
var(--bg-tree-hover, color-mix(in srgb, var(--fg-strong) 4%, transparent))
|
||||
);
|
||||
}
|
||||
/* Tree.selectionInactiveBackground when unfocused, selectionBackground when focused. */
|
||||
.selected,
|
||||
.selected:hover {
|
||||
|
||||
+7
-1
@@ -15,6 +15,7 @@ import {
|
||||
useMemo,
|
||||
useRef,
|
||||
useState,
|
||||
type CSSProperties,
|
||||
type KeyboardEvent,
|
||||
type MouseEvent,
|
||||
type ReactNode,
|
||||
@@ -128,6 +129,8 @@ export interface TreeProps<T> {
|
||||
indent?: number;
|
||||
className?: string;
|
||||
rowClassName?: (node: T) => string | undefined;
|
||||
/** CSS colour the row background is tinted with (File Colors). */
|
||||
rowTint?: (node: T) => string | undefined;
|
||||
"aria-label"?: string;
|
||||
handleRef?: Ref<TreeHandle>;
|
||||
/** Context key set while the tree itself has keyboard focus. */
|
||||
@@ -273,6 +276,7 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
indent = 20,
|
||||
className,
|
||||
rowClassName,
|
||||
rowTint,
|
||||
handleRef,
|
||||
empty,
|
||||
} = props;
|
||||
@@ -748,6 +752,7 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
const icon = getIcon?.(row.node, row.expanded);
|
||||
const detail = getDetail?.(row.node);
|
||||
const color = getColor?.(row.node);
|
||||
const tint = rowTint?.(row.node);
|
||||
return (
|
||||
<div
|
||||
key={v.key}
|
||||
@@ -763,13 +768,14 @@ export function Tree<T>(props: TreeProps<T>) {
|
||||
styles.row,
|
||||
props.horizontalScroll && styles.wideRow,
|
||||
rowClassName?.(row.node),
|
||||
tint && styles.tinted,
|
||||
isSelected && styles.selected,
|
||||
joinPrev && styles.joinPrev,
|
||||
joinNext && styles.joinNext,
|
||||
isLead && styles.lead,
|
||||
reordering.drop?.key === row.key && styles[reordering.drop.position],
|
||||
)}
|
||||
style={style}
|
||||
style={tint ? ({ ...style, "--row-tint": tint } as CSSProperties) : style}
|
||||
onPointerDown={
|
||||
props.reorder
|
||||
? (e) => reordering.start(e, row)
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
/** File Colors for the views that show them (project view, editor tabs). */
|
||||
import { useMemo } from "react";
|
||||
import { fileColorOf, fileColorSettings, type FileColorPlace } from "@/platform/fileColors";
|
||||
import { useProject } from "@/platform/project";
|
||||
import { useScopeContext } from "@/platform/scopes";
|
||||
import { useProjectViewRoots } from "./contributions";
|
||||
|
||||
const rawFileColors = (s: { settings: unknown }) => (s.settings as { fileColors?: unknown } | null)?.fileColors;
|
||||
|
||||
/**
|
||||
* The colour lookup of `place`, or null while file colours are off there. It changes
|
||||
* with the settings and the project's roots; lookups are memoised per path.
|
||||
*/
|
||||
export function useFileColors(place: FileColorPlace): ((path: string, dir?: boolean) => string | undefined) | null {
|
||||
const raw = useProject(rawFileColors);
|
||||
const ctx = useScopeContext();
|
||||
const extra = useProjectViewRoots((s) => s.roots);
|
||||
return useMemo(() => {
|
||||
const s = fileColorSettings(raw);
|
||||
if (!s.enabled || !s[place] || !s.colors.length) return null;
|
||||
// Scratches are neither project nor non-project files.
|
||||
const ownFolders = [...extra.values()].flatMap((r) => (r.scope === "scratches" && r.path ? [r.path] : []));
|
||||
const scope = { ...ctx, ownFolders };
|
||||
const memo = new Map<string, string | undefined>();
|
||||
return (path, dir = false) => {
|
||||
const key = dir ? `${path}/` : path;
|
||||
if (!memo.has(key)) memo.set(key, fileColorOf(path, s, scope, dir));
|
||||
return memo.get(key);
|
||||
};
|
||||
}, [raw, ctx, extra, place]);
|
||||
}
|
||||
Reference in New Issue
Block a user