Skip to content

Open-source agentic AI Search Execution Platform. Track AI visibility, find opportunities, and let agents turn signals into prioritized actions and drafted fixes across ChatGPT, Claude, Gemini, Google AI Overviews, Google AI Mode, Perplexity, Grok, and Microsoft Copilot.

feat(settings): choose which left-menu sections each role sees (menu access, part 3) (#1704)

Cihan8fb01425d51c
diff --git a/web/messages/en.json b/web/messages/en.json
index 69acad08a..8cef04d8c 100644
--- a/web/messages/en.json
+++ b/web/messages/en.json
@@ -7998,6 +7998,62 @@
"general": "General",
"apiKeys": "API Keys",
"team": "Team",
+ "menuAccess": {
+ "title": "Menu access",
+ "new": "New",
+ "notAllowed": "Only admins, and managers an admin lets, choose what each role sees on the menu.",
+ "note": "Hiding a section only takes it off the menu. Its pages still open from a link, and what each role can do there doesn't change. Nobody can take a section off an admin's menu (only their own work areas narrow it), and Action Center is on everyone's menu.",
+ "rolesTitle": "Sections each role sees",
+ "rolesDescription": "Pick what's on the left menu for everyone with a role. Start from a ready-made set, then adjust.",
+ "section": "Section",
+ "everything": "Everything",
+ "useSet": "Use a set…",
+ "useSetLabel": "Fill {role} from a ready-made set",
+ "sees": "{role} sees {section}",
+ "alwaysOn": "Everyone sees {section}",
+ "adminSees": "Admins see {section}",
+ "otherGroup": "Other",
+ "saveFailed": "Couldn't save the menu. Try again.",
+ "loadFailed": "Couldn't load menu access.",
+ "areas": {
+ "leaders": {
+ "title": "Founders & leaders",
+ "text": "Founders, C-level and team leads: whether AI recommends you, what it brings, and what the team ships."
+ },
+ "aeo": {
+ "title": "AEO/GEO & Audit",
+ "text": "Pages AI can read and cite, fixes, and the traffic they bring."
+ },
+ "content": {
+ "title": "Content",
+ "text": "Pages to write and improve, and the prompts they answer."
+ },
+ "brand": {
+ "title": "Brand & PR",
+ "text": "How AI talks about the brand, what it cites, and how that changes."
+ },
+ "growth": {
+ "title": "Growth",
+ "text": "AI visits, key events and signups, and the prompts and pages that bring them."
+ },
+ "product": {
+ "title": "Product Development",
+ "text": "What buyers ask AI about your category, how it compares you, and needs nobody meets."
+ },
+ "bizdev": {
+ "title": "Business Development",
+ "text": "Markets and segments where AI picks you or a rival, and the sources it trusts."
+ },
+ "developers": {
+ "title": "Developers",
+ "text": "Answer data through the API and MCP (keys in Settings), the site's AI checks and the tracking snippet."
+ },
+ "analytics": {
+ "title": "Analytics",
+ "text": "Where the brand stands in AI search, by prompt, engine and market."
+ }
+ }
+ },
"content": {
"title": "Content",
"description": "How the Content Editor works for each brand.",
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts b/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts
index 7c6804c51..96e08c8e1 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_sections.ts
@@ -9,6 +9,7 @@ export const SETTINGS_SECTIONS = [
'account',
'organization',
'team',
+ 'menu-access',
'authors',
'content',
'notifications',
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx
new file mode 100644
index 000000000..f0f9a82d5
--- /dev/null
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.test.tsx
@@ -0,0 +1,83 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../../../../messages/en.json';
+
+/**
+ * Settings' list of sections: Menu access is listed for admins and the
+ * managers they let change menus, and nobody else.
+ */
+
+vi.mock('@/i18n/navigation', () => ({ useRouter: () => ({ push: vi.fn(), refresh: vi.fn() }) }));
+vi.mock('@/lib/supabase/client', () => ({
+ createClient: () => ({ auth: { getUser: async () => ({ data: { user: null } }) } }),
+}));
+vi.mock('@/components/providers/plan-provider', () => ({
+ usePlanContext: () => ({ isCloud: false }),
+}));
+let canManageMenus = false;
+vi.mock('@/components/providers/menu-access-provider', () => ({
+ useCanManageMenus: () => canManageMenus,
+}));
+vi.mock('@/lib/actions/organization', () => ({ updateAccountName: vi.fn() }));
+vi.mock('@/components/ai-usage/ai-usage-meter', () => ({
+ HeaderWithAiUsage: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,
+}));
+for (const [path, name] of [
+ ['@/components/settings/billing-section', 'BillingSection'],
+ ['@/components/settings/team-section', 'TeamSection'],
+ ['@/components/settings/authors-section', 'AuthorsSection'],
+ ['@/components/settings/content-section', 'ContentSection'],
+ ['@/components/settings/api-keys-section', 'ApiKeysSection'],
+ ['@/components/settings/ai-providers-section', 'AiProvidersSection'],
+ ['@/components/settings/notifications-section', 'NotificationsSection'],
+ ['@/components/settings/integrations-section', 'IntegrationsSection'],
+ ['@/components/settings/organization-section', 'OrganizationSection'],
+ ['@/components/settings/menu-access-section', 'MenuAccessSection'],
+]) {
+ vi.doMock(path, () => ({ [name]: () => null }));
+}
+
+const { SettingsView } = await import('./_settings-view');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function sections() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <SettingsView section="account" />
+ </NextIntlClientProvider>,
+ );
+ });
+ return [...container.querySelectorAll('nav button')].map((b) => b.textContent);
+}
+
+describe('SettingsView', () => {
+ it('lists Menu access, marked new, for someone who can change menus', async () => {
+ canManageMenus = true;
+ expect(await sections()).toContain('Menu accessNew');
+ });
+
+ it('leaves it off for everyone else', async () => {
+ canManageMenus = false;
+ const list = await sections();
+ expect(list).toContain('Team');
+ expect(list.some((s) => s?.startsWith('Menu access'))).toBe(false);
+ });
+});
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx
index 4fa5d9a9d..88ba366a7 100644
--- a/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx
+++ b/web/src/app/[locale]/(dashboard)/dashboard/settings/_settings-view.tsx
@@ -20,6 +20,9 @@ import { AiProvidersSection } from '@/components/settings/ai-providers-section';
import { NotificationsSection } from '@/components/settings/notifications-section';
import { IntegrationsSection } from '@/components/settings/integrations-section';
import { OrganizationSection } from '@/components/settings/organization-section';
+import { MenuAccessSection } from '@/components/settings/menu-access-section';
+import { useCanManageMenus } from '@/components/providers/menu-access-provider';
+import { Badge } from '@/components/ui/badge';
import { updateAccountName } from '@/lib/actions/organization';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';
@@ -41,6 +44,7 @@ export function SettingsView({ section }: { section: SettingsSection }) {
const tAuth = useTranslations('auth');
const router = useRouter();
const { isCloud } = usePlanContext();
+ const canManageMenus = useCanManageMenus();
const [active, setActive] = useState<SettingsSection>(section);
const show = (next: SettingsSection) => {
@@ -82,6 +86,7 @@ export function SettingsView({ section }: { section: SettingsSection }) {
account: t('account'),
organization: t('organization'),
team: t('team'),
+ 'menu-access': t('menuAccess.title'),
authors: t('authors.title'),
content: t('content.title'),
notifications: t('notifications'),
@@ -92,9 +97,10 @@ export function SettingsView({ section }: { section: SettingsSection }) {
};
// AI Providers (bring your own key) and Billing are cloud-only: self-host
// operators set ANTHROPIC_API_KEY in their own env.
- const navItems = SETTINGS_SECTIONS.filter((id) => hasSettingsSection(id, { isCloud })).map(
- (id) => ({ id, label: labels[id] }),
- );
+ // Menu access is listed for admins and the managers they let change menus.
+ const navItems = SETTINGS_SECTIONS.filter(
+ (id) => hasSettingsSection(id, { isCloud }) && (id !== 'menu-access' || canManageMenus),
+ ).map((id) => ({ id, label: labels[id] }));
return (
<div className="space-y-6">
@@ -122,6 +128,11 @@ export function SettingsView({ section }: { section: SettingsSection }) {
)}
>
{item.label}
+ {item.id === 'menu-access' && (
+ <Badge variant="secondary" className="ml-2 px-1.5 py-0 text-[10px]">
+ {t('menuAccess.new')}
+ </Badge>
+ )}
</button>
))}
</nav>
@@ -178,6 +189,8 @@ export function SettingsView({ section }: { section: SettingsSection }) {
{/* Team */}
{active === 'team' && <TeamSection />}
+ {active === 'menu-access' && <MenuAccessSection />}
+
{active === 'authors' && hasSettingsSection('authors', { isCloud }) && <AuthorsSection />}
{active === 'content' && hasSettingsSection('content', { isCloud }) && <ContentSection />}
diff --git a/web/src/app/[locale]/(dashboard)/layout.tsx b/web/src/app/[locale]/(dashboard)/layout.tsx
index 1e327b4f9..cbf8dc396 100644
--- a/web/src/app/[locale]/(dashboard)/layout.tsx
+++ b/web/src/app/[locale]/(dashboard)/layout.tsx
@@ -96,7 +96,7 @@ export default async function DashboardLayout({ children }: { children: React.Re
<GettingStartedPageOpened />
<PlanProvider planId={planId} allowedModelIds={allowedModelIds}>
<RoleProvider role={role}>
- <MenuAccessProvider hidden={menu.hidden}>
+ <MenuAccessProvider hidden={menu.hidden} canManageMenus={menu.canManageMenus}>
<AiUsageProvider>
<div className="flex h-screen overflow-hidden">
{/* Desktop sidebar */}
diff --git a/web/src/components/layout/mobile-nav.test.tsx b/web/src/components/layout/mobile-nav.test.tsx
index bf7c97de2..c1c5f2408 100644
--- a/web/src/components/layout/mobile-nav.test.tsx
+++ b/web/src/components/layout/mobile-nav.test.tsx
@@ -78,7 +78,7 @@ async function open(hidden: string[]) {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <MenuAccessProvider hidden={hidden}>
+ <MenuAccessProvider hidden={hidden} canManageMenus={false}>
<MobileNav />
</MenuAccessProvider>
</NextIntlClientProvider>,
diff --git a/web/src/components/layout/sidebar.test.tsx b/web/src/components/layout/sidebar.test.tsx
index 69ca40eed..aa239dd53 100644
--- a/web/src/components/layout/sidebar.test.tsx
+++ b/web/src/components/layout/sidebar.test.tsx
@@ -122,7 +122,7 @@ describe('Sidebar', () => {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <MenuAccessProvider hidden={['content']}>
+ <MenuAccessProvider hidden={['content']} canManageMenus={false}>
<Sidebar />
</MenuAccessProvider>
</NextIntlClientProvider>,
@@ -136,7 +136,7 @@ describe('Sidebar', () => {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <MenuAccessProvider hidden={['prompts', 'mentions']}>
+ <MenuAccessProvider hidden={['prompts', 'mentions']} canManageMenus={false}>
<Sidebar />
</MenuAccessProvider>
</NextIntlClientProvider>,
@@ -164,7 +164,7 @@ describe('Sidebar', () => {
await act(async () => {
root.render(
<NextIntlClientProvider locale="en" messages={messages} timeZone="UTC">
- <MenuAccessProvider hidden={['prompts']}>
+ <MenuAccessProvider hidden={['prompts']} canManageMenus={false}>
<Sidebar />
</MenuAccessProvider>
</NextIntlClientProvider>,
diff --git a/web/src/components/providers/menu-access-provider.tsx b/web/src/components/providers/menu-access-provider.tsx
index fdf732031..d21d724ea 100644
--- a/web/src/components/providers/menu-access-provider.tsx
+++ b/web/src/components/providers/menu-access-provider.tsx
@@ -2,24 +2,42 @@
import { createContext, useContext, useMemo, type ReactNode } from 'react';
+interface MenuAccessValue {
+ /** The left-menu sections the viewer's menu leaves out. */
+ hidden: ReadonlySet<string>;
+ /** Admin, or a manager an admin let change menus: Settings › Menu access. */
+ canManageMenus: boolean;
+}
+
/**
- * The left-menu sections the viewer's menu leaves out (menu access, 00374),
- * read once by the dashboard layout. Empty by default, so a tree without the
- * provider shows the whole menu.
+ * The viewer's menu access (00374), read once by the dashboard layout. The
+ * whole menu by default, so a tree without the provider shows every section.
*/
-const MenuAccessContext = createContext<ReadonlySet<string>>(new Set());
+const MenuAccessContext = createContext<MenuAccessValue>({
+ hidden: new Set(),
+ canManageMenus: false,
+});
export function MenuAccessProvider({
hidden,
+ canManageMenus,
children,
}: {
hidden: string[];
+ canManageMenus: boolean;
children: ReactNode;
}) {
- const value = useMemo(() => new Set(hidden), [hidden]);
+ const value = useMemo(
+ () => ({ hidden: new Set(hidden), canManageMenus }),
+ [hidden, canManageMenus],
+ );
return <MenuAccessContext.Provider value={value}>{children}</MenuAccessContext.Provider>;
}
export function useHiddenMenuSections(): ReadonlySet<string> {
- return useContext(MenuAccessContext);
+ return useContext(MenuAccessContext).hidden;
+}
+
+export function useCanManageMenus(): boolean {
+ return useContext(MenuAccessContext).canManageMenus;
}
diff --git a/web/src/components/settings/menu-access-section.test.tsx b/web/src/components/settings/menu-access-section.test.tsx
new file mode 100644
index 000000000..9903154ab
--- /dev/null
+++ b/web/src/components/settings/menu-access-section.test.tsx
@@ -0,0 +1,165 @@
+import { act } from 'react';
+import { createRoot, type Root } from 'react-dom/client';
+import { NextIntlClientProvider } from 'next-intl';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import messages from '../../../messages/en.json';
+
+/**
+ * Settings › Menu access: the sections each role sees, saved as they change;
+ * Action Center and the admins' column can't be changed, and the page is for
+ * admins and the managers they let change menus.
+ */
+
+const toast = vi.hoisted(() => ({ error: vi.fn(), success: vi.fn() }));
+vi.mock('sonner', () => ({ toast }));
+
+let canManageMenus = true;
+vi.mock('@/components/providers/menu-access-provider', () => ({
+ useCanManageMenus: () => canManageMenus,
+}));
+
+const actions = vi.hoisted(() => ({
+ getMenuAccessSettings: vi.fn(),
+ setRoleMenu: vi.fn(),
+}));
+vi.mock('@/lib/actions/menu-access', () => actions);
+
+const { MenuAccessSection, hiddenForSet } = await import('./menu-access-section');
+
+(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =
+ true;
+
+let container: HTMLDivElement;
+let root: Root;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ canManageMenus = true;
+ actions.getMenuAccessSettings.mockResolvedValue({
+ roles: { manager: [], analyst: ['content', 'audit'], agency_partner: [] },
+ members: [],
+ viewerIsAdmin: true,
+ });
+ actions.setRoleMenu.mockResolvedValue(undefined);
+ container = document.createElement('div');
+ document.body.appendChild(container);
+ root = createRoot(container);
+});
+
+afterEach(() => {
+ act(() => root.unmount());
+ container.remove();
+});
+
+async function render() {
+ await act(async () => {
+ root.render(
+ <NextIntlClientProvider locale="en" messages={messages}>
+ <MenuAccessSection />
+ </NextIntlClientProvider>,
+ );
+ });
+}
+
+const box = (label: string) =>
+ container.querySelector(`[aria-label="${label}"]`) as HTMLButtonElement | null;
+
+describe('MenuAccessSection', () => {
+ it('ticks what each role sees, by the menu’s labels', async () => {
+ await render();
+ expect(box('Analyst sees Content')?.getAttribute('aria-checked')).toBe('false');
+ expect(box('Analyst sees Audit')?.getAttribute('aria-checked')).toBe('false');
+ expect(box('Analyst sees Brand Visibility')?.getAttribute('aria-checked')).toBe('true');
+ expect(box('Manager sees Content')?.getAttribute('aria-checked')).toBe('true');
+ expect(container.textContent).toContain('Product Visibility');
+ expect(container.textContent).toContain('Execution');
+ expect(container.textContent).toContain('Analytics');
+ });
+
+ it('keeps Action Center and the admins’ column on', async () => {
+ await render();
+ expect(box('Everyone sees Action Center')?.disabled).toBe(true);
+ expect(box('Admins see Content')?.disabled).toBe(true);
+ expect(box('Admins see Content')?.getAttribute('aria-checked')).toBe('true');
+ });
+
+ it('saves a role’s menu as a box changes', async () => {
+ await render();
+ await act(async () => box('Analyst sees Content')!.click());
+ expect(actions.setRoleMenu).toHaveBeenCalledWith('analyst', ['audit']);
+ expect(box('Analyst sees Content')?.getAttribute('aria-checked')).toBe('true');
+
+ await act(async () => box('Manager sees Reports')!.click());
+ expect(actions.setRoleMenu).toHaveBeenLastCalledWith('manager', ['reports']);
+ });
+
+ it('reads the menus again when a save fails, keeping a save that went through', async () => {
+ await render();
+ // The first click's save fails after the second's went through.
+ actions.setRoleMenu.mockRejectedValueOnce(new Error('nope')).mockResolvedValueOnce(undefined);
+ actions.getMenuAccessSettings.mockResolvedValueOnce({
+ roles: { manager: ['reports'], analyst: ['content', 'audit'], agency_partner: [] },
+ members: [],
+ viewerIsAdmin: true,
+ });
+ await act(async () => {
+ box('Manager sees Mentions')!.click();
+ box('Manager sees Reports')!.click();
+ });
+ expect(toast.error).toHaveBeenCalledWith("Couldn't save the menu. Try again.");
+ expect(box('Manager sees Mentions')?.getAttribute('aria-checked')).toBe('true');
+ expect(box('Manager sees Reports')?.getAttribute('aria-checked')).toBe('false');
+ });
+
+ it('fills a role from a ready-made set', async () => {
+ await render();
+ const trigger = container.querySelector(
+ '[aria-label="Fill Manager from a ready-made set"]',
+ ) as HTMLElement;
+ await act(async () => {
+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ trigger.click();
+ });
+ const option = [...document.querySelectorAll('[role="option"]')].find(
+ (o) => o.textContent === 'Brand & PR',
+ ) as HTMLElement;
+ // Base UI picks the highlighted option: the pointer moves onto it first.
+ await act(async () => {
+ option.dispatchEvent(new MouseEvent('mousemove', { bubbles: true }));
+ });
+ await act(async () => {
+ option.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));
+ option.click();
+ });
+ expect(actions.setRoleMenu).toHaveBeenCalledWith('manager', [
+ 'content',
+ 'audit',
+ 'prompts',
+ 'shopping',
+ 'traffic',
+ ]);
+ expect(box('Manager sees Content')?.getAttribute('aria-checked')).toBe('false');
+ });
+
+ it('tells people who can’t change menus, without reading them', async () => {
+ canManageMenus = false;
+ await render();
+ expect(container.textContent).toContain(
+ 'Only admins, and managers an admin lets, choose what each role sees on the menu.',
+ );
+ expect(actions.getMenuAccessSettings).not.toHaveBeenCalled();
+ });
+
+ it('says so when the settings can’t be read', async () => {
+ actions.getMenuAccessSettings.mockRejectedValueOnce(new Error('down'));
+ await render();
+ expect(container.textContent).toContain("Couldn't load menu access.");
+ });
+});
+
+describe('hiddenForSet', () => {
+ it('hides what a ready-made set leaves out, never Action Center', () => {
+ expect(hiddenForSet('brand')).toEqual(['content', 'audit', 'prompts', 'shopping', 'traffic']);
+ expect(hiddenForSet('all')).toEqual([]);
+ });
+});
diff --git a/web/src/components/settings/menu-access-section.tsx b/web/src/components/settings/menu-access-section.tsx
new file mode 100644
index 000000000..f6a71e1c3
--- /dev/null
+++ b/web/src/components/settings/menu-access-section.tsx
@@ -0,0 +1,266 @@
+'use client';
+
+import { useEffect, useState } from 'react';
+import { useTranslations } from 'next-intl';
+import { toast } from 'sonner';
+import { Info } from 'lucide-react';
+import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
+import { Checkbox } from '@/components/ui/checkbox';
+import { Skeleton } from '@/components/ui/skeleton';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import {
+ Table,
+ TableBody,
+ TableCell,
+ TableHead,
+ TableHeader,
+ TableRow,
+} from '@/components/ui/table';
+import { dashboardNav } from '@/config/dashboard';
+import { getDashboardNavGroupLabel, getDashboardNavLabel } from '@/lib/dashboard-navigation';
+import {
+ ALWAYS_ON_SECTION,
+ MENU_SECTIONS,
+ WORK_AREAS,
+ menuSectionOf,
+ workAreaSections,
+} from '@/lib/menu-access';
+import {
+ getMenuAccessSettings,
+ setRoleMenu,
+ type MenuAccessSettings,
+ type MenuRole,
+} from '@/lib/actions/menu-access';
+import { useCanManageMenus } from '@/components/providers/menu-access-provider';
+
+const MENU_ROLES: MenuRole[] = ['manager', 'analyst', 'agency_partner'];
+
+/** The menu's sections, by its groups, as the role table lists them. */
+const GROUPS = dashboardNav.map((group) => ({
+ title: group.title,
+ items: group.items.flatMap((item) => {
+ const section = menuSectionOf(item.href);
+ return section ? [{ section, title: item.title, icon: item.icon }] : [];
+ }),
+}));
+
+/** What a ready-made set hides: every section it doesn't name; none for Everything. */
+export function hiddenForSet(set: string): string[] {
+ const sections = set === 'all' ? null : workAreaSections([set]);
+ if (!sections) return [];
+ return MENU_SECTIONS.filter((section) => section !== ALWAYS_ON_SECTION && !sections.has(section));
+}
+
+/**
+ * Settings › Menu access (00374): which left-menu sections each role sees.
+ * Admins, and managers an admin lets, change it; each change saves at once.
+ * Hide only: the pages still open from a link.
+ */
+export function MenuAccessSection() {
+ const t = useTranslations('settings.menuAccess');
+ if (!useCanManageMenus()) {
+ return (
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('title')}</CardTitle>
+ <CardDescription>{t('notAllowed')}</CardDescription>
+ </CardHeader>
+ </Card>
+ );
+ }
+ return <MenuAccessSettingsView />;
+}
+
+function MenuAccessSettingsView() {
+ const t = useTranslations('settings.menuAccess');
+ const tSettings = useTranslations('settings');
+ const tNav = useTranslations('nav');
+ const [settings, setSettings] = useState<MenuAccessSettings | null>(null);
+ const [failed, setFailed] = useState(false);
+
+ useEffect(() => {
+ let current = true;
+ getMenuAccessSettings().then(
+ (next) => {
+ if (current) setSettings(next);
+ },
+ () => {
+ if (current) setFailed(true);
+ },
+ );
+ return () => {
+ current = false;
+ };
+ }, []);
+
+ // After a failed save, the settings as the server has them: a change saved
+ // meanwhile stays, which putting back the state before it wouldn't.
+ const reload = () => getMenuAccessSettings().then(setSettings, () => setFailed(true));
+
+ // The save's own revalidation brings the menu up to date (setRoleMenu).
+ const saveRole = async (role: MenuRole, hidden: string[]) => {
+ if (!settings) return;
+ setSettings((current) =>
+ current ? { ...current, roles: { ...current.roles, [role]: hidden } } : current,
+ );
+ try {
+ await setRoleMenu(role, hidden);
+ } catch {
+ toast.error(t('saveFailed'));
+ void reload();
+ }
+ };
+
+ const toggle = (role: MenuRole, section: string, sees: boolean) => {
+ const hidden = settings?.roles[role] ?? [];
+ void saveRole(
+ role,
+ sees
+ ? hidden.filter((s) => s !== section)
+ : MENU_SECTIONS.filter((s) => s === section || hidden.includes(s)),
+ );
+ };
+
+ const roleName = (role: MenuRole) => tSettings(`team_role_${role}`);
+ const setItems = [
+ { value: 'all', label: t('everything') },
+ ...WORK_AREAS.map((area) => ({ value: area.id, label: t(`areas.${area.id}.title`) })),
+ ];
+
+ return (
+ <div className="space-y-4">
+ <div className="flex gap-2 rounded-md border border-blue-200 bg-blue-50 p-3 text-sm text-blue-900 dark:border-blue-900/60 dark:bg-blue-950/40 dark:text-blue-200">
+ <Info className="mt-0.5 h-4 w-4 shrink-0" />
+ <p>{t('note')}</p>
+ </div>
+
+ <Card>
+ <CardHeader>
+ <CardTitle>{t('rolesTitle')}</CardTitle>
+ <CardDescription>{t('rolesDescription')}</CardDescription>
+ </CardHeader>
+ <CardContent>
+ {failed ? (
+ <p className="text-sm text-muted-foreground">{t('loadFailed')}</p>
+ ) : !settings ? (
+ <div className="space-y-2">
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ <Skeleton className="h-8 w-full" />
+ </div>
+ ) : (
+ <Table className="table-fixed">
+ {/* Fixed shares, so the table fits Settings' column at 1024 px wide. */}
+ <colgroup>
+ <col className="w-[20%]" />
+ <col className="w-[15%]" />
+ {MENU_ROLES.map((role) => (
+ <col key={role} />
+ ))}
+ </colgroup>
+ <TableHeader>
+ <TableRow>
+ <TableHead>{t('section')}</TableHead>
+ <TableHead className="px-1 text-center">{tSettings('team_role_admin')}</TableHead>
+ {MENU_ROLES.map((role) => (
+ <TableHead
+ key={role}
+ className="px-1 text-center leading-tight whitespace-normal"
+ >
+ {roleName(role)}
+ </TableHead>
+ ))}
+ </TableRow>
+ <TableRow>
+ <TableHead />
+ <TableHead className="px-1 text-center text-[11px] font-normal text-muted-foreground">
+ {t('everything')}
+ </TableHead>
+ {MENU_ROLES.map((role) => (
+ <TableHead key={role} className="px-0.5">
+ <Select
+ value=""
+ onValueChange={(set) => {
+ if (set) void saveRole(role, hiddenForSet(set));
+ }}
+ items={setItems}
+ >
+ <SelectTrigger
+ size="sm"
+ className="h-7 w-full min-w-0 gap-0.5 px-1 text-xs [&_svg]:size-3"
+ aria-label={t('useSetLabel', { role: roleName(role) })}
+ >
+ <SelectValue placeholder={t('useSet')} className="min-w-0 truncate" />
+ </SelectTrigger>
+ <SelectContent className="w-auto min-w-48">
+ {setItems.map((item) => (
+ <SelectItem key={item.value} value={item.value}>
+ {item.label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </TableHead>
+ ))}
+ </TableRow>
+ </TableHeader>
+ <TableBody>
+ {GROUPS.map((group, i) => [
+ <TableRow key={`group-${i}`} className="hover:bg-transparent">
+ <TableCell
+ colSpan={2 + MENU_ROLES.length}
+ className="pt-4 pb-1 text-xs font-medium uppercase tracking-wider text-muted-foreground"
+ >
+ {group.title ? getDashboardNavGroupLabel(group.title, tNav) : t('otherGroup')}
+ </TableCell>
+ </TableRow>,
+ ...group.items.map(({ section, title, icon: Icon }) => {
+ const label = getDashboardNavLabel(title, tNav);
+ const always = section === ALWAYS_ON_SECTION;
+ return (
+ <TableRow key={section}>
+ <TableCell className="whitespace-normal">
+ <span className="flex items-center gap-2">
+ <Icon className="h-4 w-4 shrink-0 text-muted-foreground" />
+ {label}
+ </span>
+ </TableCell>
+ <TableCell className="px-1 text-center">
+ <Checkbox
+ checked
+ disabled
+ aria-label={t('adminSees', { section: label })}
+ />
+ </TableCell>
+ {MENU_ROLES.map((role) => (
+ <TableCell key={role} className="px-1 text-center">
+ <Checkbox
+ checked={always || !settings.roles[role].includes(section)}
+ disabled={always}
+ onCheckedChange={(checked) => toggle(role, section, checked === true)}
+ aria-label={
+ always
+ ? t('alwaysOn', { section: label })
+ : t('sees', { role: roleName(role), section: label })
+ }
+ />
+ </TableCell>
+ ))}
+ </TableRow>
+ );
+ }),
+ ])}
+ </TableBody>
+ </Table>
+ )}
+ </CardContent>
+ </Card>
+ </div>
+ );
+}