feat(settings): derive project-sections toggles from sidebar nav registry
- sidebarNavigation.ts: static SIDEBAR_SECTIONS registry (i18n labelKey) + getTogglableFeatureNodes() with per-flag dedup - projectSections.json: shared feature-id manifest; vitest guard pins nav ids to it, pytest guard pins it to FeaturesConfig fields - FeaturesSettings: toggles derived and grouped by sidebar section/category, extra block for non-nav flags - features.svelte.ts: reactive flags store; sidebar rebuilds live after settings save, untracked health polling
This commit is contained in:
52
backend/tests/core/test_project_features_manifest.py
Normal file
52
backend/tests/core/test_project_features_manifest.py
Normal file
@@ -0,0 +1,52 @@
|
||||
# #region Test.Core.ProjectFeaturesManifest [C:2] [TYPE Module] [SEMANTICS test,features,manifest,guard]
|
||||
# @BRIEF Guard — every nav feature-id from the frontend projectSections.json manifest must exist
|
||||
# as a field on FeaturesConfig, otherwise the settings "Разделы проекта" toggle would
|
||||
# silently fail to persist (FeaturesConfig(**patch) drops unknown keys).
|
||||
# @RELATION BINDS_TO -> [Core.ConfigModels.FeaturesConfig]
|
||||
# @RELATION BINDS_TO -> [EXT:frontend:SidebarNavigation]
|
||||
# @RATIONALE The settings features tab derives its toggles from the sidebar nav registry
|
||||
# (frontend/src/lib/components/layout/sidebarNavigation.ts). The shared JSON manifest
|
||||
# is the cross-language contract: the frontend guard test pins nav ids to it, this
|
||||
# test pins backend model fields to it.
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
from src.core.config_models import FeaturesConfig
|
||||
|
||||
MANIFEST_PATH = (
|
||||
Path(__file__).resolve().parents[3]
|
||||
/ "frontend"
|
||||
/ "src"
|
||||
/ "lib"
|
||||
/ "components"
|
||||
/ "layout"
|
||||
/ "projectSections.json"
|
||||
)
|
||||
|
||||
|
||||
# #region Test.Core.ProjectFeaturesManifest.Helpers [TYPE Function]
|
||||
def _nav_feature_ids() -> list[str]:
|
||||
with MANIFEST_PATH.open(encoding="utf-8") as fh:
|
||||
manifest = json.load(fh)
|
||||
return list(manifest["navFeatures"])
|
||||
# #endregion Test.Core.ProjectFeaturesManifest.Helpers
|
||||
|
||||
|
||||
# #region Test.Core.ProjectFeaturesManifest.TestProjectFeaturesManifest [C:1] [TYPE Class]
|
||||
# @ingroup Test
|
||||
class TestProjectFeaturesManifest:
|
||||
def test_manifest_exists_and_lists_features(self) -> None:
|
||||
assert MANIFEST_PATH.is_file(), f"Manifest missing: {MANIFEST_PATH}"
|
||||
ids = _nav_feature_ids()
|
||||
assert ids, "projectSections.json must list nav feature ids"
|
||||
|
||||
def test_every_nav_feature_exists_on_features_config(self) -> None:
|
||||
model_fields = set(FeaturesConfig.model_fields)
|
||||
missing = [fid for fid in _nav_feature_ids() if fid not in model_fields]
|
||||
assert not missing, (
|
||||
"Feature ids present in projectSections.json but missing from FeaturesConfig "
|
||||
f"(a settings toggle would not persist): {missing}"
|
||||
)
|
||||
# #endregion Test.Core.ProjectFeaturesManifest.TestProjectFeaturesManifest
|
||||
|
||||
# #endregion Test.Core.ProjectFeaturesManifest
|
||||
@@ -4,6 +4,7 @@
|
||||
<!-- @LAYER UI -->
|
||||
<!-- @RELATION BINDS_TO -> [EXT:frontend:sidebarStore] -->
|
||||
<!-- @RELATION BINDS_TO -> [EXT:frontend:healthStore] -->
|
||||
<!-- @RELATION BINDS_TO -> [EXT:frontend:featuresStore] -->
|
||||
<!-- @RELATION BINDS_TO -> [Stores.ScenarioRuns.WaitingStore] -->
|
||||
<!-- @RELATION BINDS_TO -> [EXT:frontend:authStore] -->
|
||||
<!-- @RELATION DEPENDS_ON -> [Ui.Icon] -->
|
||||
@@ -32,11 +33,16 @@ import { SvelteSet } from "svelte/reactivity";
|
||||
import { onMount, untrack } from "svelte";
|
||||
import { t } from "$lib/i18n/index.svelte.js";
|
||||
import { auth } from "$lib/auth/store.svelte.js";
|
||||
import { buildSidebarSections } from "$lib/components/layout/sidebarNavigation.js";
|
||||
import { fetchApi } from "$lib/api.js";
|
||||
import { browser } from "$app/environment";
|
||||
import { ROUTES } from "$lib/routes";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
import { buildSidebarSections } from "$lib/components/layout/sidebarNavigation.js";
|
||||
import {
|
||||
getFeatures,
|
||||
isFeatureEnabled,
|
||||
isLoaded as featuresLoaded,
|
||||
loadFeatures,
|
||||
} from "$lib/stores/features.svelte.js";
|
||||
import { browser } from "$app/environment";
|
||||
import { ROUTES } from "$lib/routes";
|
||||
import Icon from "$lib/ui/Icon.svelte";
|
||||
|
||||
let _authState = $state({ user: null, token: null, isAuthenticated: false, loading: true });
|
||||
onMount(() => {
|
||||
@@ -44,14 +50,11 @@ import { SvelteSet } from "svelte/reactivity";
|
||||
return unsub;
|
||||
});
|
||||
|
||||
let features = $state({});
|
||||
let cleanupInterval = null;
|
||||
|
||||
let sections = $derived(
|
||||
buildSidebarSections(
|
||||
t,
|
||||
_authState.user || null,
|
||||
features,
|
||||
getFeatures(),
|
||||
),
|
||||
);
|
||||
|
||||
@@ -81,6 +84,17 @@ import { SvelteSet } from "svelte/reactivity";
|
||||
return () => clearInterval(id);
|
||||
});
|
||||
|
||||
// Poll dashboard health only while the health_monitor flag is enabled. The flags come from the
|
||||
// reactive features store, so toggling the flag in Settings restarts/stops polling live —
|
||||
// without the reload the old onMount fetch required. The refresh call itself is untracked:
|
||||
// the effect must depend only on the flag, not on anything refresh() reads or writes.
|
||||
$effect(() => {
|
||||
if (!featuresLoaded() || !isFeatureEnabled("health_monitor")) return;
|
||||
untrack(() => healthStore.refresh());
|
||||
const interval = setInterval(() => untrack(() => healthStore.refresh()), 5 * 60 * 1000);
|
||||
return () => clearInterval(interval);
|
||||
});
|
||||
|
||||
function withExpandedCategory(categoryId) {
|
||||
expandedCategories.add(categoryId);
|
||||
}
|
||||
@@ -209,26 +223,7 @@ import { SvelteSet } from "svelte/reactivity";
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
fetchApi("/settings/features")
|
||||
.then((res) => {
|
||||
features = res;
|
||||
if (res.health_monitor) {
|
||||
healthStore.refresh();
|
||||
const interval = setInterval(() => healthStore.refresh(), 5 * 60 * 1000);
|
||||
cleanupInterval = interval;
|
||||
}
|
||||
})
|
||||
.catch(() => {
|
||||
features = {};
|
||||
healthStore.refresh().then(() => {
|
||||
const interval = setInterval(() => healthStore.refresh(), 5 * 60 * 1000);
|
||||
cleanupInterval = interval;
|
||||
}).catch(() => {});
|
||||
});
|
||||
|
||||
return () => {
|
||||
if (cleanupInterval) clearInterval(cleanupInterval);
|
||||
};
|
||||
void loadFeatures();
|
||||
});
|
||||
</script>
|
||||
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
// #region Tests.ProjectSections.Guard [C:2] [TYPE Module] [SEMANTICS test, sidebar, features, manifest, guard]
|
||||
// @SEMANTICS: tests, sidebar, features, manifest
|
||||
// @BRIEF: Guard — nav feature-ids, the projectSections.json manifest, and what buildSidebarSections
|
||||
// surfaces must stay in sync. Catches a raw requiredFeature string that bypassed the manifest
|
||||
// and a manifest id that no nav node uses anymore.
|
||||
// @LAYER Tests
|
||||
// @RELATION DEPENDS_ON -> [EXT:frontend:SidebarNavigation]
|
||||
// @RELATION BINDS_TO -> [Core.ConfigModels.FeaturesConfig]
|
||||
// @TEST_INVARIANT: NavFeatureManifestSync -> VERIFIED_BY: nav_ids_match_manifest, admin_view_surfaces_manifest, every_node_has_context.
|
||||
|
||||
import { describe, it, expect } from "vitest";
|
||||
import { buildSidebarSections, getTogglableFeatureNodes } from "../sidebarNavigation";
|
||||
import manifest from "../projectSections.json";
|
||||
|
||||
const adminUser = { roles: [{ name: "Admin", permissions: [] }] };
|
||||
|
||||
// #region Tests.ProjectSections.Guard.NavFeatureIdsFromBuiltSections [TYPE Function]
|
||||
// @BRIEF: Collect feature ids surfaced by buildSidebarSections for an admin with all flags enabled.
|
||||
function navFeatureIdsFromBuiltSections(): string[] {
|
||||
const seen = new Set<string>();
|
||||
for (const section of buildSidebarSections({ nav: {} }, adminUser, {})) {
|
||||
for (const category of section.categories) {
|
||||
if (category.requiredFeature) seen.add(category.requiredFeature);
|
||||
for (const sub of category.subItems || []) {
|
||||
if (sub.requiredFeature) seen.add(sub.requiredFeature);
|
||||
}
|
||||
}
|
||||
}
|
||||
return [...seen].sort();
|
||||
}
|
||||
// #endregion Tests.ProjectSections.Guard.NavFeatureIdsFromBuiltSections
|
||||
|
||||
describe("projectSections manifest guard", () => {
|
||||
it("nav_ids_match_manifest: getTogglableFeatureNodes covers exactly the manifest ids", () => {
|
||||
const fromRegistry = getTogglableFeatureNodes().map((node) => node.featureId).sort();
|
||||
expect(fromRegistry).toEqual([...manifest.navFeatures].sort());
|
||||
});
|
||||
|
||||
it("admin_view_surfaces_manifest: buildSidebarSections exposes every manifest flag", () => {
|
||||
expect(navFeatureIdsFromBuiltSections()).toEqual([...manifest.navFeatures].sort());
|
||||
});
|
||||
|
||||
it("every_node_has_context: each togglable node carries section and category context", () => {
|
||||
const nodes = getTogglableFeatureNodes();
|
||||
expect(nodes.length).toBeGreaterThan(0);
|
||||
for (const node of nodes) {
|
||||
expect(node.featureId, "featureId must be set").toBeTruthy();
|
||||
expect(node.labelKey, `labelKey missing for ${node.featureId}`).toBeTruthy();
|
||||
expect(node.sectionId, `sectionId missing for ${node.featureId}`).toBeTruthy();
|
||||
expect(node.sectionLabelKey, `sectionLabelKey missing for ${node.featureId}`).toBeTruthy();
|
||||
expect(node.categoryId, `categoryId missing for ${node.featureId}`).toBeTruthy();
|
||||
expect(node.categoryLabelKey, `categoryLabelKey missing for ${node.featureId}`).toBeTruthy();
|
||||
}
|
||||
});
|
||||
|
||||
it("groups follow nav order: resources → operations → system", () => {
|
||||
const nodes = getTogglableFeatureNodes();
|
||||
const sectionOrder = [...new Set(nodes.map((node) => node.sectionId))];
|
||||
expect(sectionOrder).toEqual(["resources", "operations", "system"]);
|
||||
});
|
||||
});
|
||||
// #endregion Tests.ProjectSections.Guard
|
||||
16
frontend/src/lib/components/layout/projectSections.json
Normal file
16
frontend/src/lib/components/layout/projectSections.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"version": 1,
|
||||
"navFeatures": [
|
||||
"health_monitor",
|
||||
"translate",
|
||||
"translate_dictionaries",
|
||||
"migration",
|
||||
"git_integration",
|
||||
"backup",
|
||||
"dataset_mapper",
|
||||
"debug",
|
||||
"storage_manager",
|
||||
"maintenance_banner",
|
||||
"llm_dashboard_validation"
|
||||
]
|
||||
}
|
||||
@@ -12,9 +12,49 @@
|
||||
// @LAYER UI
|
||||
// @RELATION DEPENDS_ON -> [Auth.Permissions.PermissionsModuleModule]
|
||||
// @RELATION BINDS_TO -> [Layout.Sidebar]
|
||||
// @RELATION BINDS_TO -> [Settings.FeaturesSettings]
|
||||
// @INVARIANT: Admin role can access all categories and subitems through permission utility.
|
||||
// @INVARIANT: Every requiredFeature in SIDEBAR_SECTIONS is listed in projectSections.json and has a
|
||||
// matching FeaturesConfig field on the backend (enforced by Tests.ProjectSections.Guard
|
||||
// and the backend manifest guard test). The settings "Разделы проекта" tab derives its
|
||||
// toggles from the same registry, so a new gated route appears there automatically.
|
||||
|
||||
import { hasPermission } from "$lib/auth/permissions.js";
|
||||
import projectSections from "./projectSections.json";
|
||||
|
||||
/**
|
||||
* Feature ids that gate sidebar routes. The id list lives in projectSections.json and is the
|
||||
* single source shared with the backend manifest guard (FeaturesConfig field check).
|
||||
*/
|
||||
export type NavFeatureId = (typeof projectSections.navFeatures)[number];
|
||||
|
||||
interface NavItemDef {
|
||||
labelKey: string;
|
||||
labelFallback?: string;
|
||||
path: string;
|
||||
requiredPermission?: string;
|
||||
requiredAction?: string;
|
||||
requiredFeature?: NavFeatureId;
|
||||
}
|
||||
|
||||
interface CategoryDef {
|
||||
id: string;
|
||||
labelKey: string;
|
||||
labelFallback?: string;
|
||||
icon: string;
|
||||
tone: string;
|
||||
path: string;
|
||||
requiredPermission?: string;
|
||||
requiredAction?: string;
|
||||
requiredFeature?: NavFeatureId;
|
||||
subItems: NavItemDef[];
|
||||
}
|
||||
|
||||
interface SectionDef {
|
||||
id: string;
|
||||
labelKey: string;
|
||||
categories: CategoryDef[];
|
||||
}
|
||||
|
||||
interface NavItem {
|
||||
label: string;
|
||||
@@ -56,6 +96,186 @@ interface User {
|
||||
roles?: UserRole[];
|
||||
}
|
||||
|
||||
// #region Layout.SidebarNavigation.SidebarSectionsRegistry [TYPE Data]
|
||||
// @BRIEF Static navigation registry — single source for the sidebar structure and the settings
|
||||
// feature toggles (getTogglableFeatureNodes). Labels are stored as i18n keys and resolved
|
||||
// at build time so the registry itself stays locale-independent.
|
||||
const SIDEBAR_SECTIONS: SectionDef[] = [
|
||||
// ── Section 1: Resources ─────────────────────────────────
|
||||
{
|
||||
id: "resources",
|
||||
labelKey: "section_resources",
|
||||
categories: [
|
||||
{
|
||||
id: "dashboards",
|
||||
labelKey: "dashboards",
|
||||
icon: "dashboard",
|
||||
tone: "from-category-dashboards-from to-category-dashboards-to text-category-dashboards-text ring-category-dashboards-ring",
|
||||
path: "/dashboards",
|
||||
requiredPermission: "plugin:migration",
|
||||
requiredAction: "READ",
|
||||
subItems: [
|
||||
{ labelKey: "overview", path: "/dashboards", requiredPermission: "plugin:migration", requiredAction: "READ" },
|
||||
{ labelKey: "health_center", path: "/dashboards/health", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "health_monitor" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "datasets",
|
||||
labelKey: "datasets",
|
||||
icon: "database",
|
||||
tone: "from-category-datasets-from to-category-datasets-to text-category-datasets-text ring-category-datasets-ring",
|
||||
path: "/datasets",
|
||||
requiredPermission: "plugin:migration",
|
||||
requiredAction: "READ",
|
||||
subItems: [
|
||||
{ labelKey: "all_datasets", path: "/datasets", requiredPermission: "plugin:migration", requiredAction: "READ" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "migration",
|
||||
labelKey: "migration",
|
||||
icon: "layers",
|
||||
tone: "from-category-migration-from to-category-migration-to text-category-migration-text ring-category-migration-ring",
|
||||
path: "/migration",
|
||||
requiredPermission: "plugin:migration",
|
||||
requiredAction: "READ",
|
||||
requiredFeature: "migration",
|
||||
subItems: [
|
||||
{ labelKey: "migration_overview", labelFallback: "Overview", path: "/migration", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "migration" },
|
||||
{ labelKey: "migration_mappings", labelFallback: "Mappings", path: "/migration/mappings", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "migration" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
// ── Section 2: Operations ──────────────────────────────────
|
||||
{
|
||||
id: "operations",
|
||||
labelKey: "section_operations",
|
||||
categories: [
|
||||
{
|
||||
id: "git",
|
||||
labelKey: "git",
|
||||
icon: "activity",
|
||||
tone: "from-category-git-from to-category-git-to text-category-git-text ring-category-git-ring",
|
||||
path: "/git",
|
||||
requiredFeature: "git_integration",
|
||||
subItems: [
|
||||
{ labelKey: "git_repo_status", labelFallback: "Repository Status", path: "/git", requiredFeature: "git_integration" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "translation",
|
||||
labelKey: "translation",
|
||||
icon: "translate",
|
||||
tone: "from-category-translation-from to-category-translation-to text-category-translation-text ring-category-translation-ring",
|
||||
path: "/translate",
|
||||
requiredPermission: "translate.job",
|
||||
requiredAction: "VIEW",
|
||||
requiredFeature: "translate",
|
||||
subItems: [
|
||||
{ labelKey: "translation_jobs", path: "/translate", requiredPermission: "translate.job", requiredAction: "VIEW", requiredFeature: "translate" },
|
||||
{ labelKey: "translation_dictionaries", path: "/translate/dictionaries", requiredPermission: "translate.dictionary", requiredAction: "VIEW", requiredFeature: "translate_dictionaries" },
|
||||
{ labelKey: "translation_history", path: "/translate/history", requiredPermission: "translate.job", requiredAction: "VIEW", requiredFeature: "translate" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "validation",
|
||||
labelKey: "validation",
|
||||
icon: "activity",
|
||||
tone: "from-category-validation-from to-category-validation-to text-category-validation-text ring-category-validation-ring",
|
||||
path: "/validation-tasks",
|
||||
requiredPermission: "validation.task",
|
||||
requiredAction: "VIEW",
|
||||
requiredFeature: "llm_dashboard_validation",
|
||||
subItems: [
|
||||
{ labelKey: "validation_tasks", path: "/validation-tasks", requiredPermission: "validation.task", requiredAction: "VIEW", requiredFeature: "llm_dashboard_validation" },
|
||||
{ labelKey: "validation_history", path: "/validation-tasks/history", requiredPermission: "validation.run", requiredAction: "VIEW", requiredFeature: "llm_dashboard_validation" },
|
||||
],
|
||||
},
|
||||
{
|
||||
// 042/044/045/046/047 dashboard-testing workspace. No category-level permission:
|
||||
// visibility is derived from the RBAC-gated subitems (registry read / run / result /
|
||||
// automation). Each subitem mirrors its exact backend has_permission gate so the nav
|
||||
// never advertises a route the user cannot open. The runs hub is the human approval loop.
|
||||
id: "dashboard_testing",
|
||||
labelKey: "dashboard_testing",
|
||||
icon: "clipboard",
|
||||
tone: "from-category-testing-from to-category-testing-to text-category-testing-text ring-category-testing-ring",
|
||||
path: "/dashboard-testing",
|
||||
subItems: [
|
||||
{ labelKey: "dt_scenarios", path: "/dashboard-testing/scenarios", requiredPermission: "dashboard:testing", requiredAction: "READ" },
|
||||
{ labelKey: "dt_runs", path: "/dashboard-testing/runs", requiredPermission: "scenario", requiredAction: "RUN" },
|
||||
{ labelKey: "dt_analytics", path: "/dashboard-testing/analytics", requiredPermission: "scenario:result", requiredAction: "VIEW" },
|
||||
{ labelKey: "dt_automation", path: "/dashboard-testing/automation", requiredPermission: "scenario:automation", requiredAction: "TRIGGER" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "reports",
|
||||
labelKey: "reports",
|
||||
icon: "reports",
|
||||
tone: "from-category-reports-from to-category-reports-to text-category-reports-text ring-category-reports-ring",
|
||||
path: "/reports",
|
||||
requiredPermission: "tasks",
|
||||
requiredAction: "READ",
|
||||
subItems: [
|
||||
{ labelKey: "all_reports", labelFallback: "All Reports", path: "/reports", requiredPermission: "tasks", requiredAction: "READ" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
// ── Section 3: System ────────────────────────────────────
|
||||
{
|
||||
id: "system",
|
||||
labelKey: "section_system",
|
||||
categories: [
|
||||
{
|
||||
id: "tools",
|
||||
labelKey: "tools",
|
||||
icon: "list",
|
||||
tone: "from-category-tools-from to-category-tools-to text-category-tools-text ring-category-tools-ring",
|
||||
path: "/tools/mapper",
|
||||
subItems: [
|
||||
{ labelKey: "tools_mapper", path: "/tools/mapper", requiredFeature: "dataset_mapper" },
|
||||
{ labelKey: "tools_debug", path: "/tools/debug", requiredFeature: "debug" },
|
||||
{ labelKey: "tools_storage", path: "/tools/storage", requiredFeature: "storage_manager" },
|
||||
{ labelKey: "tools_backups", path: "/tools/backups", requiredFeature: "backup" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "admin",
|
||||
labelKey: "admin",
|
||||
icon: "admin",
|
||||
tone: "from-category-admin-from to-category-admin-to text-category-admin-text ring-category-admin-ring",
|
||||
path: "/admin/users",
|
||||
subItems: [
|
||||
{ labelKey: "admin_users", path: "/admin/users", requiredPermission: "admin:users", requiredAction: "READ" },
|
||||
{ labelKey: "admin_roles", path: "/admin/roles", requiredPermission: "admin:roles", requiredAction: "READ" },
|
||||
{ labelKey: "admin_settings", path: "/admin/settings", requiredPermission: "admin:settings", requiredAction: "READ" },
|
||||
{ labelKey: "admin_llm", path: "/admin/settings/llm", requiredPermission: "admin:settings", requiredAction: "READ" },
|
||||
{ labelKey: "admin_mcp", path: "/admin/mcp", requiredPermission: "admin:roles", requiredAction: "READ" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "maintenance",
|
||||
labelKey: "maintenance",
|
||||
labelFallback: "Maintenance",
|
||||
icon: "activity",
|
||||
tone: "from-category-maintenance-from to-category-maintenance-to text-category-maintenance-text ring-category-maintenance-ring",
|
||||
path: "/maintenance",
|
||||
requiredPermission: "maintenance",
|
||||
requiredAction: "READ",
|
||||
requiredFeature: "maintenance_banner",
|
||||
subItems: [
|
||||
{ labelKey: "maintenance", labelFallback: "Maintenance", path: "/maintenance", requiredPermission: "maintenance", requiredAction: "READ", requiredFeature: "maintenance_banner" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
// #endregion Layout.SidebarNavigation.SidebarSectionsRegistry
|
||||
|
||||
// #region Layout.SidebarNavigation.IsItemAllowedFunction [TYPE Function]
|
||||
// @BRIEF: Check whether a single menu node can be shown for a given user.
|
||||
// @PRE: item can contain optional requiredPermission/requiredAction.
|
||||
@@ -77,186 +297,42 @@ function isFeatureEnabled(item: { requiredFeature?: string }, features: Record<s
|
||||
}
|
||||
// #endregion Layout.SidebarNavigation.IsFeatureEnabledFunction
|
||||
|
||||
// #region Layout.SidebarNavigation.ResolveLabelFunction [TYPE Function]
|
||||
// @BRIEF: Resolve a nav label from the i18n nav dictionary with optional static fallback.
|
||||
function resolveLabel(i18nState: I18nNavState, item: { labelKey: string; labelFallback?: string }): string {
|
||||
const nav = i18nState?.nav || {};
|
||||
const value = nav[item.labelKey];
|
||||
if (typeof value === "string" && value) return value;
|
||||
return item.labelFallback || item.labelKey;
|
||||
}
|
||||
// #endregion Layout.SidebarNavigation.ResolveLabelFunction
|
||||
|
||||
// #region Layout.SidebarNavigation.BuildSidebarSectionsFunction [TYPE Function]
|
||||
// @BRIEF: Build translated sidebar sections with categories, filtered by RBAC permissions and feature flags.
|
||||
// @PRE: i18nState provides nav labels; user can be null; features default to {} (all enabled).
|
||||
// @POST: Returns only sections/categories/subitems available for provided user and enabled features.
|
||||
export function buildSidebarSections(i18nState: I18nNavState, user: User | null | undefined, features: Record<string, boolean | undefined> = {}): Section[] {
|
||||
const nav = i18nState?.nav || {};
|
||||
|
||||
// ── Section 1: Resources ─────────────────────────────────
|
||||
const resources: Section = {
|
||||
id: "resources",
|
||||
label: nav.section_resources,
|
||||
categories: [
|
||||
{
|
||||
id: "dashboards",
|
||||
label: nav.dashboards,
|
||||
icon: "dashboard",
|
||||
tone: "from-category-dashboards-from to-category-dashboards-to text-category-dashboards-text ring-category-dashboards-ring",
|
||||
path: "/dashboards",
|
||||
requiredPermission: "plugin:migration",
|
||||
requiredAction: "READ",
|
||||
subItems: [
|
||||
{ label: nav.overview, path: "/dashboards", requiredPermission: "plugin:migration", requiredAction: "READ" },
|
||||
{ label: nav.health_center, path: "/dashboards/health", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "health_monitor" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "datasets",
|
||||
label: nav.datasets,
|
||||
icon: "database",
|
||||
tone: "from-category-datasets-from to-category-datasets-to text-category-datasets-text ring-category-datasets-ring",
|
||||
path: "/datasets",
|
||||
requiredPermission: "plugin:migration",
|
||||
requiredAction: "READ",
|
||||
subItems: [
|
||||
{ label: nav.all_datasets, path: "/datasets", requiredPermission: "plugin:migration", requiredAction: "READ" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "migration",
|
||||
label: nav.migration,
|
||||
icon: "layers",
|
||||
tone: "from-category-migration-from to-category-migration-to text-category-migration-text ring-category-migration-ring",
|
||||
path: "/migration",
|
||||
requiredPermission: "plugin:migration",
|
||||
requiredAction: "READ",
|
||||
requiredFeature: "migration",
|
||||
subItems: [
|
||||
{ label: nav.migration_overview || "Overview", path: "/migration", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "migration" },
|
||||
{ label: nav.migration_mappings || "Mappings", path: "/migration/mappings", requiredPermission: "plugin:migration", requiredAction: "READ", requiredFeature: "migration" },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// ── Section 2: Operations ──────────────────────────────────
|
||||
const operations: Section = {
|
||||
id: "operations",
|
||||
label: nav.section_operations,
|
||||
categories: [
|
||||
{
|
||||
id: "git",
|
||||
label: nav.git,
|
||||
icon: "activity",
|
||||
tone: "from-category-git-from to-category-git-to text-category-git-text ring-category-git-ring",
|
||||
path: "/git",
|
||||
requiredFeature: "git_integration",
|
||||
subItems: [
|
||||
{ label: nav.git_repo_status || "Repository Status", path: "/git", requiredFeature: "git_integration" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "translation",
|
||||
label: nav.translation,
|
||||
icon: "translate",
|
||||
tone: "from-category-translation-from to-category-translation-to text-category-translation-text ring-category-translation-ring",
|
||||
path: "/translate",
|
||||
requiredPermission: "translate.job",
|
||||
requiredAction: "VIEW",
|
||||
requiredFeature: "translate",
|
||||
subItems: [
|
||||
{ label: nav.translation_jobs, path: "/translate", requiredPermission: "translate.job", requiredAction: "VIEW", requiredFeature: "translate" },
|
||||
{ label: nav.translation_dictionaries, path: "/translate/dictionaries", requiredPermission: "translate.dictionary", requiredAction: "VIEW", requiredFeature: "translate_dictionaries" },
|
||||
{ label: nav.translation_history, path: "/translate/history", requiredPermission: "translate.job", requiredAction: "VIEW", requiredFeature: "translate" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "validation",
|
||||
label: nav.validation,
|
||||
icon: "activity",
|
||||
tone: "from-category-validation-from to-category-validation-to text-category-validation-text ring-category-validation-ring",
|
||||
path: "/validation-tasks",
|
||||
requiredPermission: "validation.task",
|
||||
requiredAction: "VIEW",
|
||||
requiredFeature: "llm_dashboard_validation",
|
||||
subItems: [
|
||||
{ label: nav.validation_tasks, path: "/validation-tasks", requiredPermission: "validation.task", requiredAction: "VIEW", requiredFeature: "llm_dashboard_validation" },
|
||||
{ label: nav.validation_history, path: "/validation-tasks/history", requiredPermission: "validation.run", requiredAction: "VIEW", requiredFeature: "llm_dashboard_validation" },
|
||||
],
|
||||
},
|
||||
{
|
||||
// 042/044/045/046/047 dashboard-testing workspace. No category-level permission:
|
||||
// visibility is derived from the RBAC-gated subitems (registry read / run / result /
|
||||
// automation). Each subitem mirrors its exact backend has_permission gate so the nav
|
||||
// never advertises a route the user cannot open. The runs hub is the human approval loop.
|
||||
id: "dashboard_testing",
|
||||
label: nav.dashboard_testing,
|
||||
icon: "clipboard",
|
||||
tone: "from-category-testing-from to-category-testing-to text-category-testing-text ring-category-testing-ring",
|
||||
path: "/dashboard-testing",
|
||||
subItems: [
|
||||
{ label: nav.dt_scenarios, path: "/dashboard-testing/scenarios", requiredPermission: "dashboard:testing", requiredAction: "READ" },
|
||||
{ label: nav.dt_runs, path: "/dashboard-testing/runs", requiredPermission: "scenario", requiredAction: "RUN" },
|
||||
{ label: nav.dt_analytics, path: "/dashboard-testing/analytics", requiredPermission: "scenario:result", requiredAction: "VIEW" },
|
||||
{ label: nav.dt_automation, path: "/dashboard-testing/automation", requiredPermission: "scenario:automation", requiredAction: "TRIGGER" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "reports",
|
||||
label: nav.reports,
|
||||
icon: "reports",
|
||||
tone: "from-category-reports-from to-category-reports-to text-category-reports-text ring-category-reports-ring",
|
||||
path: "/reports",
|
||||
requiredPermission: "tasks",
|
||||
requiredAction: "READ",
|
||||
subItems: [
|
||||
{ label: nav.all_reports || "All Reports", path: "/reports", requiredPermission: "tasks", requiredAction: "READ" },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
// ── Section 3: System ────────────────────────────────────
|
||||
const system: Section = {
|
||||
id: "system",
|
||||
label: nav.section_system,
|
||||
categories: [
|
||||
{
|
||||
id: "tools",
|
||||
label: nav.tools,
|
||||
icon: "list",
|
||||
tone: "from-category-tools-from to-category-tools-to text-category-tools-text ring-category-tools-ring",
|
||||
path: "/tools/mapper",
|
||||
subItems: [
|
||||
{ label: nav.tools_mapper, path: "/tools/mapper", requiredFeature: "dataset_mapper" },
|
||||
{ label: nav.tools_debug, path: "/tools/debug", requiredFeature: "debug" },
|
||||
{ label: nav.tools_storage, path: "/tools/storage", requiredFeature: "storage_manager" },
|
||||
{ label: nav.tools_backups, path: "/tools/backups", requiredFeature: "backup" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "admin",
|
||||
label: nav.admin,
|
||||
icon: "admin",
|
||||
tone: "from-category-admin-from to-category-admin-to text-category-admin-text ring-category-admin-ring",
|
||||
path: "/admin/users",
|
||||
subItems: [
|
||||
{ label: nav.admin_users, path: "/admin/users", requiredPermission: "admin:users", requiredAction: "READ" },
|
||||
{ label: nav.admin_roles, path: "/admin/roles", requiredPermission: "admin:roles", requiredAction: "READ" },
|
||||
{ label: nav.admin_settings, path: "/admin/settings", requiredPermission: "admin:settings", requiredAction: "READ" },
|
||||
{ label: nav.admin_llm, path: "/admin/settings/llm", requiredPermission: "admin:settings", requiredAction: "READ" },
|
||||
{ label: nav.admin_mcp, path: "/admin/mcp", requiredPermission: "admin:roles", requiredAction: "READ" },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "maintenance",
|
||||
label: nav.maintenance || "Maintenance",
|
||||
icon: "activity",
|
||||
tone: "from-category-maintenance-from to-category-maintenance-to text-category-maintenance-text ring-category-maintenance-ring",
|
||||
path: "/maintenance",
|
||||
requiredPermission: "maintenance",
|
||||
requiredAction: "READ",
|
||||
requiredFeature: "maintenance_banner",
|
||||
subItems: [
|
||||
{ label: nav.maintenance || "Maintenance", path: "/maintenance", requiredPermission: "maintenance", requiredAction: "READ", requiredFeature: "maintenance_banner" },
|
||||
],
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
const allSections = [resources, operations, system];
|
||||
const allSections: Section[] = SIDEBAR_SECTIONS.map((section) => ({
|
||||
id: section.id,
|
||||
label: resolveLabel(i18nState, section),
|
||||
categories: section.categories.map((category) => ({
|
||||
id: category.id,
|
||||
label: resolveLabel(i18nState, category),
|
||||
icon: category.icon,
|
||||
tone: category.tone,
|
||||
path: category.path,
|
||||
requiredPermission: category.requiredPermission,
|
||||
requiredAction: category.requiredAction,
|
||||
requiredFeature: category.requiredFeature,
|
||||
subItems: category.subItems.map((sub) => ({
|
||||
label: resolveLabel(i18nState, sub),
|
||||
path: sub.path,
|
||||
requiredPermission: sub.requiredPermission,
|
||||
requiredAction: sub.requiredAction,
|
||||
requiredFeature: sub.requiredFeature,
|
||||
})),
|
||||
})),
|
||||
}));
|
||||
|
||||
// Filter by permissions and features
|
||||
return allSections
|
||||
@@ -279,4 +355,64 @@ export function buildSidebarSections(i18nState: I18nNavState, user: User | null
|
||||
}
|
||||
// #endregion Layout.SidebarNavigation.BuildSidebarSectionsFunction
|
||||
|
||||
// #region Layout.SidebarNavigation.GetTogglableFeatureNodesFunction [TYPE Function]
|
||||
// @BRIEF: Collect every sidebar feature flag, for the settings "Разделы проекта" tab.
|
||||
// @PRE: SIDEBAR_SECTIONS is the static registry; no user/RBAC filtering is applied (settings are admin-only).
|
||||
// @POST: Returns one node per distinct requiredFeature in nav order (duplicates — a category and its
|
||||
// subitems sharing one flag — collapse to the first occurrence), with section/category context.
|
||||
// @RATIONALE: The settings tab derives its toggle list from this registry instead of a hardcoded
|
||||
// copy, so adding a gated route to the sidebar makes it appear in settings automatically.
|
||||
export interface TogglableFeatureNode {
|
||||
featureId: NavFeatureId;
|
||||
labelKey: string;
|
||||
labelFallback?: string;
|
||||
sectionId: string;
|
||||
sectionLabelKey: string;
|
||||
categoryId: string;
|
||||
categoryLabelKey: string;
|
||||
categoryLabelFallback?: string;
|
||||
}
|
||||
|
||||
export function getTogglableFeatureNodes(): TogglableFeatureNode[] {
|
||||
const nodes: TogglableFeatureNode[] = [];
|
||||
const seenFeatureIds = new Set<NavFeatureId>();
|
||||
const pushNode = (node: TogglableFeatureNode): void => {
|
||||
if (seenFeatureIds.has(node.featureId)) return;
|
||||
seenFeatureIds.add(node.featureId);
|
||||
nodes.push(node);
|
||||
};
|
||||
for (const section of SIDEBAR_SECTIONS) {
|
||||
for (const category of section.categories) {
|
||||
if (category.requiredFeature) {
|
||||
pushNode({
|
||||
featureId: category.requiredFeature,
|
||||
labelKey: category.labelKey,
|
||||
labelFallback: category.labelFallback,
|
||||
sectionId: section.id,
|
||||
sectionLabelKey: section.labelKey,
|
||||
categoryId: category.id,
|
||||
categoryLabelKey: category.labelKey,
|
||||
categoryLabelFallback: category.labelFallback,
|
||||
});
|
||||
}
|
||||
for (const sub of category.subItems) {
|
||||
if (sub.requiredFeature) {
|
||||
pushNode({
|
||||
featureId: sub.requiredFeature,
|
||||
labelKey: sub.labelKey,
|
||||
labelFallback: sub.labelFallback,
|
||||
sectionId: section.id,
|
||||
sectionLabelKey: section.labelKey,
|
||||
categoryId: category.id,
|
||||
categoryLabelKey: category.labelKey,
|
||||
categoryLabelFallback: category.labelFallback,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return nodes;
|
||||
}
|
||||
// #endregion Layout.SidebarNavigation.GetTogglableFeatureNodesFunction
|
||||
|
||||
// #endregion Layout.SidebarNavigation.SidebarNavigationModule
|
||||
|
||||
@@ -112,6 +112,7 @@
|
||||
"env_update": "Update Environment",
|
||||
"features": "Features",
|
||||
"features_description": "Enable or disable top-level application features.",
|
||||
"features_extra": "Additional features",
|
||||
"feature_health_monitor": "Health Monitor",
|
||||
"feature_health_monitor_hint": "Dashboard health monitoring and validation report aggregation.",
|
||||
"save_features": "Save feature settings",
|
||||
|
||||
@@ -112,6 +112,7 @@
|
||||
"env_update": "Обновить окружение",
|
||||
"features": "Разделы проекта",
|
||||
"features_description": "Включение и отключение разделов приложения.",
|
||||
"features_extra": "Дополнительные функции",
|
||||
"feature_health_monitor": "Health Monitor",
|
||||
"feature_health_monitor_hint": "Мониторинг здоровья дашбордов и агрегация отчётов валидации.",
|
||||
"save_features": "Сохранить настройки разделов",
|
||||
|
||||
96
frontend/src/lib/stores/__tests__/test_features.ts
Normal file
96
frontend/src/lib/stores/__tests__/test_features.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
// #region Test.Features [C:2] [TYPE Module] [SEMANTICS test, features, store, flags]
|
||||
// @BRIEF Unit tests for the reactive feature-flag store — defaults, setFeatures, load dedup, error recovery.
|
||||
// @RELATION DEPENDS_ON -> [Stores.Features.FeaturesStore]
|
||||
// @TEST_EDGE: unknown_flag -> isFeatureEnabled returns true for ids absent from the flags dict (default-on posture)
|
||||
// @TEST_EDGE: external_fail -> fetchApi rejection degrades to empty flags without throwing
|
||||
// @TEST_SCENARIO: concurrent_load -> two loadFeatures() calls share one in-flight request
|
||||
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
|
||||
vi.mock('$lib/api.js', () => ({
|
||||
fetchApi: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('$lib/cot-logger', () => ({
|
||||
log: vi.fn(),
|
||||
}));
|
||||
|
||||
import { fetchApi } from '$lib/api.js';
|
||||
|
||||
describe('features store', () => {
|
||||
beforeEach(() => {
|
||||
vi.resetModules();
|
||||
vi.mocked(fetchApi).mockReset();
|
||||
});
|
||||
|
||||
it('starts unloaded with all flags treated as enabled', async () => {
|
||||
const store = await import('../features.svelte.js');
|
||||
|
||||
expect(store.isLoaded()).toBe(false);
|
||||
expect(store.getFeatures()).toEqual({});
|
||||
expect(store.isFeatureEnabled('health_monitor')).toBe(true);
|
||||
expect(store.isFeatureEnabled('anything_unknown')).toBe(true);
|
||||
});
|
||||
|
||||
it('setFeatures stores a copy and marks the store loaded', async () => {
|
||||
const store = await import('../features.svelte.js');
|
||||
|
||||
const next = { health_monitor: true, migration: false };
|
||||
store.setFeatures(next);
|
||||
|
||||
// Mutating the source object must not leak into the store state.
|
||||
next.migration = true;
|
||||
|
||||
expect(store.isLoaded()).toBe(true);
|
||||
expect(store.getFeatures()).toEqual({ health_monitor: true, migration: false });
|
||||
expect(store.isFeatureEnabled('migration')).toBe(false);
|
||||
});
|
||||
|
||||
it('setFeatures tolerates null/undefined payloads', async () => {
|
||||
const store = await import('../features.svelte.js');
|
||||
|
||||
store.setFeatures(null);
|
||||
expect(store.isLoaded()).toBe(true);
|
||||
expect(store.getFeatures()).toEqual({});
|
||||
});
|
||||
|
||||
it('loadFeatures fetches /settings/features and stores the result', async () => {
|
||||
vi.mocked(fetchApi).mockResolvedValueOnce({ health_monitor: false, migration: true });
|
||||
const store = await import('../features.svelte.js');
|
||||
|
||||
const flags = await store.loadFeatures();
|
||||
|
||||
expect(fetchApi).toHaveBeenCalledWith('/settings/features');
|
||||
expect(store.isLoaded()).toBe(true);
|
||||
expect(flags).toEqual({ health_monitor: false, migration: true });
|
||||
expect(store.isFeatureEnabled('health_monitor')).toBe(false);
|
||||
});
|
||||
|
||||
it('concurrent loadFeatures calls share one request', async () => {
|
||||
let resolveFetch: (value: unknown) => void = () => {};
|
||||
vi.mocked(fetchApi).mockImplementationOnce(
|
||||
() => new Promise((resolve) => { resolveFetch = resolve; }),
|
||||
);
|
||||
const store = await import('../features.svelte.js');
|
||||
|
||||
const first = store.loadFeatures();
|
||||
const second = store.loadFeatures();
|
||||
|
||||
resolveFetch({ migration: false });
|
||||
await Promise.all([first, second]);
|
||||
|
||||
expect(fetchApi).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('loadFeatures degrades to empty flags on fetch failure', async () => {
|
||||
vi.mocked(fetchApi).mockRejectedValueOnce(new Error('network down'));
|
||||
const store = await import('../features.svelte.js');
|
||||
|
||||
const flags = await store.loadFeatures();
|
||||
|
||||
expect(flags).toEqual({});
|
||||
expect(store.isLoaded()).toBe(true);
|
||||
expect(store.isFeatureEnabled('migration')).toBe(true);
|
||||
});
|
||||
});
|
||||
// #endregion Test.Features
|
||||
59
frontend/src/lib/stores/features.svelte.ts
Normal file
59
frontend/src/lib/stores/features.svelte.ts
Normal file
@@ -0,0 +1,59 @@
|
||||
// #region Stores.Features.FeaturesStore [C:2] [TYPE Store] [SEMANTICS features, flags, store, settings]
|
||||
// @ingroup Stores
|
||||
// @BRIEF Reactive feature-flag store shared by the sidebar and the settings "Разделы проекта" tab —
|
||||
// saving toggles in settings rebuilds the left panel without a page reload.
|
||||
// @LAYER UI
|
||||
// @RELATION DEPENDS_ON -> [Api.ApiModule.FetchApi]
|
||||
// @RELATION BINDS_TO -> [Layout.Sidebar]
|
||||
// @RELATION BINDS_TO -> [Settings.Page.SettingsPage]
|
||||
// @UX_STATE Loading -> flags empty, nav renders with defaults (all enabled).
|
||||
// @UX_STATE Ready -> flags reflect the persisted FeaturesConfig.
|
||||
// @PRE GET /settings/features is reachable (unauthenticated endpoint).
|
||||
// @POST setFeatures(next) re-renders every consumer reading getFeatures()/isFeatureEnabled().
|
||||
// @RATIONALE Module-level $state store following the health.svelte.ts pattern: the sidebar and the
|
||||
// settings features tab must read the same flags, so a save can push new flags into the
|
||||
// nav without remounting. Concurrent loadFeatures() calls share one request.
|
||||
|
||||
import { fetchApi } from "$lib/api.js";
|
||||
import { log } from "$lib/cot-logger";
|
||||
|
||||
let _flags = $state<Record<string, boolean>>({});
|
||||
let _loaded = $state(false);
|
||||
let _inflight: Promise<Record<string, boolean>> | null = null;
|
||||
|
||||
export function getFeatures(): Record<string, boolean> {
|
||||
return _flags;
|
||||
}
|
||||
|
||||
export function isLoaded(): boolean {
|
||||
return _loaded;
|
||||
}
|
||||
|
||||
/** Unknown/missing ids are treated as enabled (matches the backend default-true posture). */
|
||||
export function isFeatureEnabled(id: string): boolean {
|
||||
return _flags[id] !== false;
|
||||
}
|
||||
|
||||
export function setFeatures(next: Record<string, boolean> | undefined | null): void {
|
||||
_flags = { ...(next || {}) };
|
||||
_loaded = true;
|
||||
}
|
||||
|
||||
export async function loadFeatures(): Promise<Record<string, boolean>> {
|
||||
if (_inflight) return _inflight;
|
||||
_inflight = fetchApi("/settings/features")
|
||||
.then((res) => {
|
||||
setFeatures(res as Record<string, boolean>);
|
||||
return _flags;
|
||||
})
|
||||
.catch((err) => {
|
||||
log("FeaturesStore", "EXPLORE", "Failed to load feature flags", {}, String(err));
|
||||
setFeatures({});
|
||||
return _flags;
|
||||
})
|
||||
.finally(() => {
|
||||
_inflight = null;
|
||||
});
|
||||
return _inflight;
|
||||
}
|
||||
// #endregion Stores.Features.FeaturesStore
|
||||
@@ -28,6 +28,7 @@
|
||||
import { Button, Skeleton, Tabs } from "$lib/ui";
|
||||
|
||||
import { log } from "$lib/cot-logger";
|
||||
import { setFeatures } from "$lib/stores/features.svelte.js";
|
||||
import {
|
||||
normalizeTab,
|
||||
readTabFromUrl,
|
||||
@@ -80,6 +81,8 @@
|
||||
response.mcp_oauth_refresh_default_days ??= 30;
|
||||
response.mcp_oauth_refresh_max_days ??= 90;
|
||||
settings = response;
|
||||
// Push the fresh flags into the reactive store so the sidebar stays in sync.
|
||||
setFeatures(response.features);
|
||||
} catch (err) {
|
||||
error = err.message || $t.settings?.load_failed;
|
||||
log("SettingsPage", "EXPLORE", "Failed to load settings", {}, String(err));
|
||||
@@ -100,6 +103,8 @@
|
||||
try {
|
||||
settings.llm = normalizeLlmSettings(settings.llm);
|
||||
await api.updateConsolidatedSettings(settings);
|
||||
// Update the shared features store so the sidebar rebuilds without a page reload.
|
||||
setFeatures(settings.features);
|
||||
notifications.success($t.settings?.save_success);
|
||||
} catch (err) {
|
||||
log("SettingsPage", "EXPLORE", "Failed to save settings", {}, String(err));
|
||||
|
||||
@@ -1,62 +1,93 @@
|
||||
<!-- #region Settings.FeaturesSettings [C:3] [TYPE Component] [SEMANTICS settings, features, toggle, enable] -->
|
||||
<!-- @ingroup Routes -->
|
||||
<!-- @BRIEF Dynamic feature flags configuration tab: enable/disable all application features. -->
|
||||
<!-- @BRIEF "Разделы проекта" tab: toggles derived from the sidebar nav registry + a block for non-navigation flags. -->
|
||||
<!-- @LAYER UI -->
|
||||
<!-- @PRE: settings object with features config is provided. -->
|
||||
<!-- @POST: User can toggle all feature flags dynamically rendered from FeaturesConfig. -->
|
||||
<!-- @RATIONALE Dynamic rendering: features are derived from backend FeaturesConfig model.
|
||||
Each feature gets a toggle with i18n label if available. -->
|
||||
<!-- @POST: Every sidebar node with a requiredFeature gets a toggle; non-nav flags render in the extra block. -->
|
||||
<!-- @RELATION DEPENDS_ON -> [Layout.SidebarNavigation.SidebarNavigationModule] -->
|
||||
<!-- @RATIONALE The toggle list is derived from getTogglableFeatureNodes() (sidebarNavigation.ts), not from a
|
||||
hardcoded copy: adding a gated route to the sidebar makes it appear here automatically. The manifest
|
||||
projectSections.json + guard tests keep the nav ids and backend FeaturesConfig fields in sync.
|
||||
Feature flags without a sidebar route (translate_scheduling, search_datasets, llm_documentation) are
|
||||
not derivable from nav and stay in an explicit extra block. -->
|
||||
<script lang="ts">
|
||||
import { t } from "$lib/i18n/index.svelte.js";
|
||||
import HelpTooltip from "$lib/ui/HelpTooltip.svelte";
|
||||
import { getTogglableFeatureNodes } from "$lib/components/layout/sidebarNavigation.js";
|
||||
|
||||
let { settings = $bindable(), onSave } = $props();
|
||||
|
||||
// Feature descriptors: ordered list for UI display.
|
||||
// Each entry maps to settings.features.<id> with optional i18n keys.
|
||||
// i18n keys follow pattern: feature_<id>, feature_<id>_hint, help_feature_<id>
|
||||
const FEATURES = [
|
||||
// Core features
|
||||
{ id: "health_monitor", category: "core" },
|
||||
|
||||
// Translation subsystem
|
||||
{ id: "translate", category: "translate" },
|
||||
{ id: "translate_scheduling", category: "translate" },
|
||||
{ id: "translate_dictionaries", category: "translate" },
|
||||
|
||||
// Dashboard migration & version control
|
||||
{ id: "migration", category: "migration" },
|
||||
{ id: "git_integration", category: "migration" },
|
||||
|
||||
// System tools
|
||||
{ id: "backup", category: "tools" },
|
||||
{ id: "dataset_mapper", category: "tools" },
|
||||
{ id: "debug", category: "tools" },
|
||||
{ id: "storage_manager", category: "tools" },
|
||||
{ id: "search_datasets", category: "tools" },
|
||||
{ id: "maintenance_banner", category: "tools" },
|
||||
|
||||
// LLM analysis tools
|
||||
{ id: "llm_dashboard_validation", category: "llm" },
|
||||
{ id: "llm_documentation", category: "llm" },
|
||||
// Non-navigation feature flags: no sidebar route exists for them, so they cannot be derived
|
||||
// from the nav registry and are listed explicitly. Keep in sync with backend FeaturesConfig.
|
||||
const EXTRA_FEATURES: ToggleEntry[] = [
|
||||
{ id: "translate_scheduling" },
|
||||
{ id: "search_datasets" },
|
||||
{ id: "llm_documentation" },
|
||||
];
|
||||
|
||||
// Category labels
|
||||
const CATEGORIES: Record<string, string> = {
|
||||
core: "Core",
|
||||
translate: "Translation",
|
||||
migration: "Migration & Version Control",
|
||||
tools: "System Tools",
|
||||
llm: "LLM Analysis",
|
||||
};
|
||||
interface ToggleEntry {
|
||||
id: string;
|
||||
labelKey?: string;
|
||||
labelFallback?: string;
|
||||
}
|
||||
|
||||
function featureLabel(id: string): string {
|
||||
// Try i18n first
|
||||
interface ToggleCategory {
|
||||
id: string;
|
||||
labelKey: string;
|
||||
labelFallback?: string;
|
||||
features: ToggleEntry[];
|
||||
}
|
||||
|
||||
interface ToggleSection {
|
||||
id: string;
|
||||
labelKey: string;
|
||||
categories: ToggleCategory[];
|
||||
}
|
||||
|
||||
// Group nav-derived toggles by sidebar section → category, preserving nav order.
|
||||
const navGroups: ToggleSection[] = (() => {
|
||||
const sections: ToggleSection[] = [];
|
||||
for (const node of getTogglableFeatureNodes()) {
|
||||
let section = sections.find((s) => s.id === node.sectionId);
|
||||
if (!section) {
|
||||
section = { id: node.sectionId, labelKey: node.sectionLabelKey, categories: [] };
|
||||
sections.push(section);
|
||||
}
|
||||
let category = section.categories.find((c) => c.id === node.categoryId);
|
||||
if (!category) {
|
||||
category = {
|
||||
id: node.categoryId,
|
||||
labelKey: node.categoryLabelKey,
|
||||
labelFallback: node.categoryLabelFallback,
|
||||
features: [],
|
||||
};
|
||||
section.categories.push(category);
|
||||
}
|
||||
category.features.push({ id: node.featureId, labelKey: node.labelKey, labelFallback: node.labelFallback });
|
||||
}
|
||||
return sections;
|
||||
})();
|
||||
|
||||
function navLabel(key: string, fallback?: string): string {
|
||||
const nav = $t.nav as Record<string, string | undefined> | undefined;
|
||||
const value = nav?.[key];
|
||||
if (typeof value === "string" && value) return value;
|
||||
return fallback || key;
|
||||
}
|
||||
|
||||
function featureLabel(id: string, labelKey?: string, labelFallback?: string): string {
|
||||
// Explicit feature_<id> override first, then the sidebar label, then humanized id.
|
||||
const key = `feature_${id}` as keyof typeof $t.settings;
|
||||
const i18nVal = $t.settings?.[key];
|
||||
if (i18nVal && typeof i18nVal === "string") return i18nVal;
|
||||
|
||||
// Fallback: human-readable from snake_case
|
||||
if (labelKey) {
|
||||
const nav = $t.nav as Record<string, string | undefined> | undefined;
|
||||
const navVal = nav?.[labelKey];
|
||||
if (typeof navVal === "string" && navVal) return navVal;
|
||||
if (labelFallback) return labelFallback;
|
||||
}
|
||||
|
||||
return id
|
||||
.replace(/_/g, " ")
|
||||
.replace(/\b\w/g, (c) => c.toUpperCase());
|
||||
@@ -83,16 +114,6 @@
|
||||
settings.features = { ...settings.features };
|
||||
}
|
||||
}
|
||||
|
||||
// Group features by category
|
||||
const groupedFeatures = $derived.by(() => {
|
||||
const grouped: Record<string, typeof FEATURES> = {};
|
||||
for (const f of FEATURES) {
|
||||
if (!grouped[f.category]) grouped[f.category] = [];
|
||||
grouped[f.category].push(f);
|
||||
}
|
||||
return grouped;
|
||||
});
|
||||
</script>
|
||||
|
||||
<div class="text-lg font-medium mb-4">
|
||||
@@ -103,45 +124,65 @@
|
||||
{$t.settings?.features_description || "Enable or disable application features. Disabled features are hidden from the UI and blocked at the API level."}
|
||||
</p>
|
||||
|
||||
{#each Object.entries(groupedFeatures) as [category, features]}
|
||||
{#snippet toggleRow(feature: ToggleEntry, bordered: boolean)}
|
||||
<div class="flex items-center justify-between p-4" class:border-t={bordered} class:border-border={bordered}>
|
||||
<div class="flex-1 mr-4">
|
||||
<span class="flex items-center gap-1.5">
|
||||
<label for="feature-{feature.id}" class="text-sm font-medium text-text">
|
||||
{featureLabel(feature.id, feature.labelKey, feature.labelFallback)}
|
||||
</label>
|
||||
{#if featureHelp(feature.id)}
|
||||
<HelpTooltip text={featureHelp(feature.id)} />
|
||||
{/if}
|
||||
</span>
|
||||
{#if featureHint(feature.id)}
|
||||
<p class="text-xs text-text-muted mt-1">
|
||||
{featureHint(feature.id)}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
<label class="relative inline-flex items-center cursor-pointer flex-shrink-0">
|
||||
<input
|
||||
id="feature-{feature.id}"
|
||||
type="checkbox"
|
||||
class="sr-only peer"
|
||||
checked={settings?.features?.[feature.id] ?? true}
|
||||
onchange={() => toggleFeature(feature.id)}
|
||||
>
|
||||
<div class="w-11 h-6 bg-surface-muted peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-ring rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-surface-card after:border-border-strong after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
|
||||
</label>
|
||||
</div>
|
||||
{/snippet}
|
||||
|
||||
{#each navGroups as section (section.id)}
|
||||
<div class="mb-6">
|
||||
<h3 class="text-lg font-semibold mb-3 text-text">
|
||||
{CATEGORIES[category] || category}
|
||||
{navLabel(section.labelKey)}
|
||||
</h3>
|
||||
<div class="app-section-muted">
|
||||
{#each features as feature, i}
|
||||
<div class="flex items-center justify-between p-4" class:border-t={i > 0} class:border-border={i > 0}>
|
||||
<div class="flex-1 mr-4">
|
||||
<span class="flex items-center gap-1.5">
|
||||
<label for="feature-{feature.id}" class="text-sm font-medium text-text">
|
||||
{featureLabel(feature.id)}
|
||||
</label>
|
||||
{#if featureHelp(feature.id)}
|
||||
<HelpTooltip text={featureHelp(feature.id)} />
|
||||
{/if}
|
||||
</span>
|
||||
{#if featureHint(feature.id)}
|
||||
<p class="text-xs text-text-muted mt-1">
|
||||
{featureHint(feature.id)}
|
||||
</p>
|
||||
{/if}
|
||||
</div>
|
||||
<label class="relative inline-flex items-center cursor-pointer flex-shrink-0">
|
||||
<input
|
||||
id="feature-{feature.id}"
|
||||
type="checkbox"
|
||||
class="sr-only peer"
|
||||
checked={settings?.features?.[feature.id] ?? true}
|
||||
onchange={() => toggleFeature(feature.id)}
|
||||
>
|
||||
<div class="w-11 h-6 bg-surface-muted peer-focus:outline-none peer-focus:ring-4 peer-focus:ring-primary-ring rounded-full peer peer-checked:after:translate-x-full rtl:peer-checked:after:-translate-x-full peer-checked:after:border-white after:content-[''] after:absolute after:top-[2px] after:start-[2px] after:bg-surface-card after:border-border-strong after:border after:rounded-full after:h-5 after:w-5 after:transition-all peer-checked:bg-primary"></div>
|
||||
</label>
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{#each section.categories as category (category.id)}
|
||||
<h4 class="text-sm font-semibold mb-2 text-text-muted">
|
||||
{navLabel(category.labelKey, category.labelFallback)}
|
||||
</h4>
|
||||
<div class="app-section-muted">
|
||||
{#each category.features as feature, i (feature.id)}
|
||||
{@render toggleRow(feature, i > 0)}
|
||||
{/each}
|
||||
</div>
|
||||
{/each}
|
||||
</div>
|
||||
{/each}
|
||||
|
||||
<div class="mb-6">
|
||||
<h3 class="text-lg font-semibold mb-3 text-text">
|
||||
{$t.settings?.features_extra || "Additional features"}
|
||||
</h3>
|
||||
<div class="app-section-muted">
|
||||
{#each EXTRA_FEATURES as feature, i (feature.id)}
|
||||
{@render toggleRow(feature, i > 0)}
|
||||
{/each}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex justify-end">
|
||||
<button
|
||||
onclick={onSave}
|
||||
|
||||
Reference in New Issue
Block a user