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.
TypeScript aeoai-agentai-searchanswer-engine-optimizationbrand-monitoringchatgptclaudecopilotdockergeminigeogoogle-ai-overviewsgrokmcpnextjsopen-sourceperplexityseosupabasetypescript
feat(brands): switch brands from the brand page's header (#1340)
Cihan855482bf85f0
diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.test.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.test.tsxnew file mode 100644index 000000000..d185c5e6f--- /dev/null+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.test.tsx@@ -0,0 +1,107 @@+import { act, Suspense } 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';+import BrandDetailLayout from './layout';++const push = vi.fn();+const nav = vi.hoisted(() => ({ pathname: '/dashboard/brands/b1/settings' }));+vi.mock('@/i18n/navigation', () => ({+ useRouter: () => ({ push }),+ usePathname: () => nav.pathname,+ Link: ({ href, children }: { href: string; children?: React.ReactNode }) => (+ <a href={href}>{children}</a>+ ),+}));+const brand = (id: string, name: string) => ({+ id,+ name,+ logoUrl: undefined,+ isActive: true,+ domains: [+ { id: `${id}-d`, brandId: id, domain: `${name.toLowerCase()}.example`, isPrimary: true },+ ],+});+const store = vi.hoisted(() => ({+ brands: [] as ReturnType<typeof brand>[],+ activeBrandId: 'b1' as string | null,+ setActiveBrand: vi.fn(),+}));+vi.mock('@/stores/use-brand-store', () => ({ useBrandStore: () => store }));++(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT: boolean }).IS_REACT_ACT_ENVIRONMENT =+ true;++let container: HTMLDivElement;+let root: Root;++/** A params promise React reads at once: already fulfilled. */+const params = (id: string) =>+ Object.assign(Promise.resolve({ id }), { status: 'fulfilled', value: { id } });++async function render(id = 'b1') {+ await act(async () =>+ root.render(+ <NextIntlClientProvider locale="en" messages={messages}>+ <Suspense>+ <BrandDetailLayout params={params(id)}>+ <p>page</p>+ </BrandDetailLayout>+ </Suspense>+ </NextIntlClientProvider>,+ ),+ );+}+async function openSwitch() {+ const trigger = container.querySelector<HTMLButtonElement>('[aria-label="Switch brand"]')!;+ await act(async () => {+ trigger.dispatchEvent(new MouseEvent('pointerdown', { bubbles: true }));+ trigger.click();+ });+ return [...document.querySelectorAll<HTMLElement>('[role="menuitem"]')];+}++beforeEach(() => {+ container = document.createElement('div');+ document.body.appendChild(container);+ root = createRoot(container);+ store.brands = [brand('b1', 'Acme'), brand('b2', 'Globex')];+ store.setActiveBrand.mockReset();+ push.mockReset();+ nav.pathname = '/dashboard/brands/b1/settings';+});++afterEach(() => {+ act(() => root.unmount());+ container.remove();+ document.body.replaceChildren();+});++describe('the brand header', () => {+ it("opens another brand's settings from the arrows beside the name", async () => {+ await render();+ expect(container.querySelector('h1')!.textContent).toBe('Acme');+ const items = await openSwitch();+ expect(items).toHaveLength(2);+ await act(async () => items[1].click());+ expect(store.setActiveBrand).toHaveBeenCalledWith('b2');+ expect(push).toHaveBeenCalledWith('/dashboard/brands/b2/settings');+ });++ it("keeps the brand's page: prompts open the other brand's prompts", async () => {+ nav.pathname = '/dashboard/brands/b1/prompts';+ await render();+ const items = await openSwitch();+ await act(async () => items[1].click());+ expect(push).toHaveBeenCalledWith('/dashboard/brands/b2/prompts');+ });++ it('stays put when the same brand is picked', async () => {+ await render();+ const items = await openSwitch();+ await act(async () => items[0].click());+ expect(push).not.toHaveBeenCalled();+ expect(store.setActiveBrand).not.toHaveBeenCalled();+ });+});diff --git a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsxindex 49ba6edee..a24c5c393 100644--- a/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx+++ b/web/src/app/[locale]/(dashboard)/dashboard/brands/[id]/layout.tsx@@ -1,12 +1,23 @@'use client';import { use } from 'react';-import { usePathname, Link } from '@/i18n/navigation';+import { useTranslations } from 'next-intl';+import { usePathname, useRouter, Link } from '@/i18n/navigation';import { useBrandStore } from '@/stores/use-brand-store';import { Button } from '@/components/ui/button';import { BrandAvatar } from '@/components/brand-avatar';+import { BrandSwitchItems } from '@/components/layout/brand-switcher';+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuGroup,+ DropdownMenuLabel,+ DropdownMenuSeparator,+ DropdownMenuTrigger,+} from '@/components/ui/dropdown-menu';+import { brandPagePath } from '@/lib/brand-path';import { cn } from '@/lib/utils';-import { ArrowLeft, MessageSquareText, Settings, Tag } from 'lucide-react';+import { ArrowLeft, ChevronsUpDown, MessageSquareText, Settings, Tag } from 'lucide-react';const SUB_NAV = [{ href: 'topics', label: 'Topics', icon: Tag },@@ -24,8 +35,17 @@ export default function BrandDetailLayout({}) {const { id } = use(params) as { id: string };const pathname = usePathname();- const { brands } = useBrandStore();+ const router = useRouter();+ const t = useTranslations('brands');+ const { brands, setActiveBrand } = useBrandStore();const brand = brands.find((b) => b.id === id);+ // Another brand from the header opens the same page of that brand (its+ // settings, from the settings), and becomes the brand the app shows.+ const switchTo = (brandId: string) => {+ if (brandId === id) return;+ setActiveBrand(brandId);+ router.push(brandPagePath(pathname, brandId) ?? `/dashboard/brands/${brandId}/settings`);+ };return (<div className="space-y-6">@@ -47,7 +67,26 @@ export default function BrandDetailLayout({imageClassName="object-contain p-1"/><div>- <h1 className="text-xl font-bold tracking-tight">{brand.name}</h1>+ <div className="flex items-center gap-1">+ <h1 className="text-xl font-bold tracking-tight">{brand.name}</h1>+ <DropdownMenu>+ <DropdownMenuTrigger+ aria-label={t('switchBrand')}+ className="inline-flex h-7 w-7 items-center justify-center rounded-md text-muted-foreground transition-colors hover:bg-muted hover:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring/50"+ >+ <ChevronsUpDown className="h-4 w-4" />+ </DropdownMenuTrigger>+ <DropdownMenuContent className="w-56" align="start">+ <DropdownMenuGroup>+ <DropdownMenuLabel className="text-xs text-muted-foreground">+ {t('switchBrand')}+ </DropdownMenuLabel>+ </DropdownMenuGroup>+ <DropdownMenuSeparator />+ <BrandSwitchItems brands={brands} currentId={id} onSelect={switchTo} />+ </DropdownMenuContent>+ </DropdownMenu>+ </div><p className="text-xs text-muted-foreground">{brand.domains.find((d) => d.isPrimary)?.domain ?? ''}</p>diff --git a/web/src/components/layout/brand-switcher.test.tsx b/web/src/components/layout/brand-switcher.test.tsxindex 2b2a0901a..a5bbf3f8b 100644--- a/web/src/components/layout/brand-switcher.test.tsx+++ b/web/src/components/layout/brand-switcher.test.tsx@@ -6,8 +6,10 @@ import messages from '../../../messages/en.json';import { BrandSwitcher } from './brand-switcher';const push = vi.fn();+const nav = vi.hoisted(() => ({ pathname: '/dashboard/content' }));vi.mock('@/i18n/navigation', () => ({useRouter: () => ({ push }),+ usePathname: () => nav.pathname,Link: ({ href, children, ...rest }: { href: string; children?: React.ReactNode }) => (<a href={href} {...rest}>{children}@@ -67,6 +69,8 @@ beforeEach(() => {store.activeBrandId = 'b1';push.mockReset();onNavigate.mockReset();+ store.setActiveBrand.mockReset();+ nav.pathname = '/dashboard/content';role.canManage = true;});@@ -104,6 +108,23 @@ describe('BrandSwitcher', () => {expect(onNavigate).toHaveBeenCalled();});+ it("switches brands in place, or to the same page of a brand's own pages", async () => {+ await render();+ let items = await openMenu();+ await act(async () => items[1].click());+ expect(store.setActiveBrand).toHaveBeenCalledWith('b2');+ expect(push).not.toHaveBeenCalled();++ act(() => root.unmount());+ document.body.replaceChildren(container);+ root = createRoot(container);+ nav.pathname = '/dashboard/brands/b1/settings';+ await render();+ items = await openMenu();+ await act(async () => items[1].click());+ expect(push).toHaveBeenCalledWith('/dashboard/brands/b2/settings');+ });+it('adds a brand on its own page', async () => {await render();const items = await openMenu();diff --git a/web/src/components/layout/brand-switcher.tsx b/web/src/components/layout/brand-switcher.tsxindex 4c50b6e44..d26c8c03c 100644--- a/web/src/components/layout/brand-switcher.tsx+++ b/web/src/components/layout/brand-switcher.tsx@@ -1,7 +1,9 @@'use client';import { useTranslations } from 'next-intl';-import { Link, useRouter } from '@/i18n/navigation';+import { Link, usePathname, useRouter } from '@/i18n/navigation';+import { brandPagePath } from '@/lib/brand-path';+import type { Brand } from '@/types';import { useBrandStore } from '@/stores/use-brand-store';import { useUserRole } from '@/hooks/use-user-role';import {@@ -34,6 +36,7 @@ interface BrandSwitcherProps {export function BrandSwitcher({ collapsed = false, onOpenChange, onNavigate }: BrandSwitcherProps) {const t = useTranslations('brands');const router = useRouter();+ const pathname = usePathname();const { brands, activeBrandId, setActiveBrand } = useBrandStore();// Only admins and managers add a brand (brands: admin/manager insert).const { canManage } = useUserRole();@@ -44,6 +47,13 @@ export function BrandSwitcher({ collapsed = false, onOpenChange, onNavigate }: BonNavigate?.();router.push(href);};+ // On a brand's own page (its settings, prompts or topics), the same page+ // of the brand picked; elsewhere the page stays.+ const select = (brandId: string) => {+ setActiveBrand(brandId);+ const next = brandPagePath(pathname, brandId);+ if (next) go(next);+ };if (brands.length === 0) {if (!canManage) return null;@@ -103,40 +113,7 @@ export function BrandSwitcher({ collapsed = false, onOpenChange, onNavigate }: B</DropdownMenuGroup><DropdownMenuSeparator />- {brands.map((brand) => {- const isActive = brand.id === activeBrandId;- const primaryDomain = brand.domains.find((d) => d.isPrimary);-- return (- <DropdownMenuItem- key={brand.id}- onClick={() => setActiveBrand(brand.id)}- className="flex items-center gap-2"- >- <BrandAvatar- logoUrl={brand.logoUrl}- name={brand.name}- domains={brand.domains}- className="h-5 w-5 shrink-0 rounded-md bg-zinc-50 dark:bg-zinc-100"- fallbackClassName="rounded-md bg-primary/10 text-primary text-xs font-semibold"- />- <div className="flex-1 overflow-hidden">- <p className="flex items-center gap-1.5 truncate text-sm font-medium">- <span className="truncate">{brand.name}</span>- {!brand.isActive && (- <span className="shrink-0 rounded bg-amber-500/15 px-1 py-px text-[9px] font-medium uppercase tracking-wide text-amber-700 dark:text-amber-400">- Paused- </span>- )}- </p>- {primaryDomain && (- <p className="truncate text-xs text-muted-foreground">{primaryDomain.domain}</p>- )}- </div>- {isActive && <Check className="h-3.5 w-3.5 shrink-0 text-primary" />}- </DropdownMenuItem>- );- })}+ <BrandSwitchItems brands={brands} currentId={activeBrandId} onSelect={select} /><DropdownMenuSeparator />@@ -183,3 +160,49 @@ export function BrandSwitcher({ collapsed = false, onOpenChange, onNavigate }: B</div>);}++/** The brands to switch to, the current one checked. */+export function BrandSwitchItems({+ brands,+ currentId,+ onSelect,+}: {+ brands: Brand[];+ currentId: string | null;+ onSelect: (brandId: string) => void;+}) {+ return brands.map((brand) => {+ const isActive = brand.id === currentId;+ const primaryDomain = brand.domains.find((d) => d.isPrimary);++ return (+ <DropdownMenuItem+ key={brand.id}+ onClick={() => onSelect(brand.id)}+ className="flex items-center gap-2"+ >+ <BrandAvatar+ logoUrl={brand.logoUrl}+ name={brand.name}+ domains={brand.domains}+ className="h-5 w-5 shrink-0 rounded-md bg-zinc-50 dark:bg-zinc-100"+ fallbackClassName="rounded-md bg-primary/10 text-primary text-xs font-semibold"+ />+ <div className="flex-1 overflow-hidden">+ <p className="flex items-center gap-1.5 truncate text-sm font-medium">+ <span className="truncate">{brand.name}</span>+ {!brand.isActive && (+ <span className="shrink-0 rounded bg-amber-500/15 px-1 py-px text-[9px] font-medium uppercase tracking-wide text-amber-700 dark:text-amber-400">+ Paused+ </span>+ )}+ </p>+ {primaryDomain && (+ <p className="truncate text-xs text-muted-foreground">{primaryDomain.domain}</p>+ )}+ </div>+ {isActive && <Check className="h-3.5 w-3.5 shrink-0 text-primary" />}+ </DropdownMenuItem>+ );+ });+}diff --git a/web/src/lib/brand-path.test.ts b/web/src/lib/brand-path.test.tsnew file mode 100644index 000000000..b072dc0fb--- /dev/null+++ b/web/src/lib/brand-path.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';+import { brandPagePath } from './brand-path';++describe('brandPagePath', () => {+ it('keeps the brand page, for the other brand', () => {+ expect(brandPagePath('/dashboard/brands/a1/settings', 'b2')).toBe(+ '/dashboard/brands/b2/settings',+ );+ expect(brandPagePath('/dashboard/brands/a1/prompts', 'b2')).toBe(+ '/dashboard/brands/b2/prompts',+ );+ expect(brandPagePath('/dashboard/brands/a1', 'b2')).toBe('/dashboard/brands/b2');+ });++ it('is null off a brand page, the brands list and the new-brand page', () => {+ expect(brandPagePath('/dashboard/brands', 'b2')).toBeNull();+ expect(brandPagePath('/dashboard/brands/new', 'b2')).toBeNull();+ expect(brandPagePath('/dashboard/content/plan', 'b2')).toBeNull();+ });+});diff --git a/web/src/lib/brand-path.ts b/web/src/lib/brand-path.tsnew file mode 100644index 000000000..f6318344c--- /dev/null+++ b/web/src/lib/brand-path.ts@@ -0,0 +1,12 @@+/** /dashboard/brands/<id> and anything under it; "new" is the new-brand page. */+const BRAND_PAGE = /^\/dashboard\/brands\/(?!new(?:\/|$))[^/]+(\/.*)?$/;++/**+ * The same brand page for another brand: switching brands on+ * /dashboard/brands/A/settings opens /dashboard/brands/B/settings. Null off a+ * brand's pages, where switching brands stays on the page.+ */+export function brandPagePath(pathname: string, brandId: string): string | null {+ const match = BRAND_PAGE.exec(pathname);+ return match ? `/dashboard/brands/${brandId}${match[1] ?? ''}` : null;+}