feat(nav): concept sidebar with folds, collapse rail, and user menu (UI migration PR 2) (#1133)
* feat(nav): concept sidebar with folds, collapse rail, and user menu (UI migration PR 2) The concept's navigation, exactly, with all current functionality kept: - Groups restructured per concept: top (Hem, Assistenten), ARBETA (Bokforing, Underlag, Transaktioner, Granskning, Kundfakturor, Leverantorsfakturor, Loner), ANALYS, DATA (Register fold + Importera/exportera), SKATT & BOKSLUT (Moms, Skattekonto, Viktiga datum, Bokslut fold). Entity/capability/dimension gating unchanged. - Register and Bokslut are animated folds (grid-rows 0fr/1fr), children text-indented behind a hairline; closed by default, forced open by an active child route; state persists per user. - Sidebar collapses to a 64px icon rail (toggle top of rail); width is one inline --nav-w CSS variable on #dash-shell that aside and <main> both read, so the panel follows in lockstep. Server-rendered from ui_state so first paint is right. - Sticky bottom user block (avatar, name, active company) opening an upward user menu: identity, company-switcher flyout (search + building glyphs + roles + check, real switch mechanism via shared lib/company/switch-client), Installningar, Medlemmar och roller, Abonnemang, Hjalp, support, terracotta logout. Trial touchpoint kept. - CompanySwitcher removed from desktop top (lives in the user menu now); mobile bottom nav + sheet unchanged. - New migration 20260723120000: user_preferences.ui_state jsonb bag (founder-approved) + POST /api/user/ui-state (requireAuth, strict zod, merge semantics) with route tests. - i18n: fold/collapse/menu keys added sv+en; deadlines -> "Viktiga datum", year_end -> "Arsbokslut" per concept. Discord-community row deferred: no invite URL exists in the repo. Badges stay the current two (Transaktioner, Granskning); an Underlag count is a follow-up with lib/worklist. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(nav): brand-mark sidebar header + auto-hiding scrollbars Concept alignment feedback: the sidebar gets a header row (brand mark left, collapse toggle right) hanging from the same top line as the panel, instead of a lone right-aligned toggle. Scrollbars go overlay-style app-wide: transparent at rest, revealed only while their container scrolls (ScrollbarReveal stamps .is-scrolling via one capture-phase document listener), fading out after 700ms idle. The gutter stays reserved so revealing never shifts layout. Co-Authored-By: Claude Fable 5 <[email protected]> * fix(nav): company flyout opens downward + Discord community row The flyout was bottom-anchored to its row and grew upward over the menu; founder feedback: top-align with the row and grow downward. Adds the Discord community row to the user menu (external invite link). Co-Authored-By: Claude Fable 5 <[email protected]> --------- Co-authored-by: Claude Fable 5 <[email protected]>
This commit is contained in:
co-authored by
Claude Fable 5
parent
6b506a9ca8
commit
d59e4708cf
File diff suppressed because one or more lines are too long
@@ -38,8 +38,9 @@ const NO_COMPANY_ALLOWED_PATHS = ['/settings/account']
|
||||
*/
|
||||
const MAIN_PANEL_CLASS =
|
||||
'safe-area-main-padding md:!pb-0 relative bg-background min-h-screen ' +
|
||||
'md:min-h-0 md:ml-64 md:mt-[10px] md:mr-[10px] md:h-[calc(100vh-20px)] ' +
|
||||
'md:overflow-y-auto md:rounded-xl md:border md:border-border'
|
||||
'md:min-h-0 md:ml-[var(--nav-w)] md:mt-[10px] md:mr-[10px] md:h-[calc(100vh-20px)] ' +
|
||||
'md:overflow-y-auto md:rounded-xl md:border md:border-border ' +
|
||||
'md:transition-[margin-left] md:duration-200'
|
||||
|
||||
export default async function DashboardLayout({
|
||||
children,
|
||||
@@ -146,6 +147,7 @@ export default async function DashboardLayout({
|
||||
{ data: userProfile },
|
||||
entitlements,
|
||||
{ data: allSettingsNames },
|
||||
{ data: userPrefs },
|
||||
] = await Promise.all([
|
||||
supabase.from('companies').select('*').eq('id', companyId).single(),
|
||||
supabase.from('company_members').select('role').eq('company_id', companyId).eq('user_id', user.id).single(),
|
||||
@@ -168,6 +170,9 @@ export default async function DashboardLayout({
|
||||
// select returns exactly the caller's companies, letting non-active rows
|
||||
// show company_settings.company_name instead of the frozen companies.name.
|
||||
supabase.from('company_settings').select('company_id, company_name'),
|
||||
// Per-user UI state (nav collapse/fold state): server-rendered so the
|
||||
// sidebar width is right on first paint, no post-hydration jump.
|
||||
supabase.from('user_preferences').select('ui_state').eq('user_id', user.id).maybeSingle(),
|
||||
])
|
||||
|
||||
// company_id -> current display name for every company the user belongs to.
|
||||
@@ -248,6 +253,12 @@ export default async function DashboardLayout({
|
||||
|
||||
const isSandbox = settings?.is_sandbox === true
|
||||
|
||||
// Client-driven UI preferences (sidebar collapse + fold state). Read here
|
||||
// so the shell renders at the right width on first paint; the nav toggles
|
||||
// flip the data attribute client-side and persist via /api/user/ui-state.
|
||||
const uiState = (userPrefs?.ui_state ?? {}) as import('@/types').UserUiState
|
||||
const navCollapsed = uiState.nav_collapsed === true
|
||||
|
||||
const companyContextValue = {
|
||||
company: companyWithName,
|
||||
role: memberRow.role as CompanyRole,
|
||||
@@ -278,7 +289,11 @@ export default async function DashboardLayout({
|
||||
}}
|
||||
>
|
||||
<CompanyTabSync />
|
||||
<div className="min-h-screen bg-frame md:flex md:flex-col">
|
||||
<div
|
||||
id="dash-shell"
|
||||
className="min-h-screen bg-frame md:flex md:flex-col"
|
||||
style={{ '--nav-w': navCollapsed ? '64px' : '248px' } as React.CSSProperties}
|
||||
>
|
||||
{/* Skip to content link for keyboard/screen reader users */}
|
||||
<a
|
||||
href="#main-content"
|
||||
@@ -296,6 +311,7 @@ export default async function DashboardLayout({
|
||||
extensionNavItems={getExtensionNavItems()}
|
||||
userName={userProfile?.full_name ?? null}
|
||||
userEmail={user.email ?? null}
|
||||
initialUiState={uiState}
|
||||
/>
|
||||
<main id="main-content" className={MAIN_PANEL_CLASS} role="main">
|
||||
<MainContainer companyId={companyId}>{children}</MainContainer>
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Tests for POST /api/user/ui-state: the per-user UI preference bag
|
||||
* (nav collapse/fold state, split-button create modes).
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { createQueuedMockSupabase, createMockRequest, parseJsonResponse } from '@/tests/helpers'
|
||||
|
||||
const { supabase, enqueue, reset } = createQueuedMockSupabase()
|
||||
|
||||
const requireAuthMock = vi.fn()
|
||||
vi.mock('@/lib/auth/require-auth', () => ({
|
||||
requireAuth: (...args: unknown[]) => requireAuthMock(...args),
|
||||
}))
|
||||
|
||||
import { POST } from '../route'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
reset()
|
||||
requireAuthMock.mockResolvedValue({ user: { id: 'user-1' }, supabase, error: null })
|
||||
})
|
||||
|
||||
function request(body: unknown) {
|
||||
return createMockRequest('/api/user/ui-state', { method: 'POST', body })
|
||||
}
|
||||
|
||||
describe('POST /api/user/ui-state', () => {
|
||||
it('returns 401 when not authenticated', async () => {
|
||||
requireAuthMock.mockResolvedValue({
|
||||
user: null,
|
||||
supabase,
|
||||
error: NextResponse.json({ error: 'Unauthorized' }, { status: 401 }),
|
||||
})
|
||||
|
||||
const res = await POST(request({ nav_collapsed: true }))
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
it('returns 400 on unknown keys (strict schema)', async () => {
|
||||
const res = await POST(request({ nav_collapsed: true, evil: 'x' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('returns 400 on wrong value types', async () => {
|
||||
const res = await POST(request({ nav_collapsed: 'yes' }))
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
it('merges the patch into the existing ui_state', async () => {
|
||||
// select existing row
|
||||
enqueue({
|
||||
data: { ui_state: { nav_collapsed: false, nav_folds: { register: true } } },
|
||||
})
|
||||
// upsert result
|
||||
enqueue({ data: null })
|
||||
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { ui_state: { nav_collapsed: boolean; nav_folds: Record<string, boolean> } }
|
||||
}>(await POST(request({ nav_folds: { bokslut: true } })))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.ui_state).toEqual({
|
||||
nav_collapsed: false,
|
||||
nav_folds: { register: true, bokslut: true },
|
||||
})
|
||||
})
|
||||
|
||||
it('handles a missing preferences row (first write)', async () => {
|
||||
enqueue({ data: null }) // no existing row
|
||||
enqueue({ data: null }) // upsert
|
||||
|
||||
const { status, body } = await parseJsonResponse<{
|
||||
data: { ui_state: { nav_collapsed: boolean } }
|
||||
}>(await POST(request({ nav_collapsed: true })))
|
||||
|
||||
expect(status).toBe(200)
|
||||
expect(body.data.ui_state).toEqual({ nav_collapsed: true })
|
||||
})
|
||||
|
||||
it('returns 500 when the upsert fails', async () => {
|
||||
enqueue({ data: null })
|
||||
enqueue({ data: null, error: { message: 'boom' } })
|
||||
|
||||
const res = await POST(request({ nav_collapsed: true }))
|
||||
expect(res.status).toBe(500)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,71 @@
|
||||
import { NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { requireAuth } from '@/lib/auth/require-auth'
|
||||
import type { UserUiState } from '@/types'
|
||||
|
||||
// Partial update: the client sends only the keys it changed. Strict schemas
|
||||
// so typos fail loudly instead of accumulating junk in the jsonb bag.
|
||||
const BodySchema = z
|
||||
.object({
|
||||
nav_collapsed: z.boolean().optional(),
|
||||
nav_folds: z
|
||||
.object({
|
||||
register: z.boolean().optional(),
|
||||
bokslut: z.boolean().optional(),
|
||||
})
|
||||
.strict()
|
||||
.optional(),
|
||||
create_mode: z.record(z.string(), z.string().max(64)).optional(),
|
||||
})
|
||||
.strict()
|
||||
|
||||
// User-scoped preference endpoint: no company context exists or is needed,
|
||||
// so requireAuth() directly (same opt-out as /api/user/locale). RLS scopes
|
||||
// user_preferences to the caller's own row.
|
||||
export async function POST(request: Request) {
|
||||
const { user, supabase, error } = await requireAuth()
|
||||
if (error) return error
|
||||
|
||||
let body: unknown
|
||||
try {
|
||||
body = await request.json()
|
||||
} catch {
|
||||
return NextResponse.json({ error: 'Invalid JSON body' }, { status: 400 })
|
||||
}
|
||||
|
||||
const parsed = BodySchema.safeParse(body)
|
||||
if (!parsed.success) {
|
||||
return NextResponse.json({ error: 'Invalid ui_state payload' }, { status: 400 })
|
||||
}
|
||||
|
||||
// Read-merge-write: last write wins per key. Fine for cosmetic UI state;
|
||||
// concurrent tabs converge on the next read.
|
||||
const { data: existing } = await supabase
|
||||
.from('user_preferences')
|
||||
.select('ui_state')
|
||||
.eq('user_id', user.id)
|
||||
.maybeSingle()
|
||||
|
||||
const current: UserUiState = (existing?.ui_state as UserUiState) ?? {}
|
||||
const patch = parsed.data
|
||||
const next: UserUiState = {
|
||||
...current,
|
||||
...patch,
|
||||
...(patch.nav_folds
|
||||
? { nav_folds: { ...current.nav_folds, ...patch.nav_folds } }
|
||||
: {}),
|
||||
...(patch.create_mode
|
||||
? { create_mode: { ...current.create_mode, ...patch.create_mode } }
|
||||
: {}),
|
||||
}
|
||||
|
||||
const { error: upsertError } = await supabase
|
||||
.from('user_preferences')
|
||||
.upsert({ user_id: user.id, ui_state: next }, { onConflict: 'user_id' })
|
||||
|
||||
if (upsertError) {
|
||||
return NextResponse.json({ error: 'Could not save UI preferences' }, { status: 500 })
|
||||
}
|
||||
|
||||
return NextResponse.json({ data: { ui_state: next } })
|
||||
}
|
||||
+28
-4
@@ -11,6 +11,14 @@
|
||||
|
||||
:root {
|
||||
color-scheme: light;
|
||||
|
||||
/* Sidebar column width (frame layout). Default for shells that don't
|
||||
override it; the dashboard shell (#dash-shell) sets it inline from
|
||||
user_preferences.ui_state (248px expanded / 64px collapsed rail) and
|
||||
the nav toggle updates it client-side. aside and <main> both read the
|
||||
variable so they stay in lockstep. */
|
||||
--nav-w: 248px;
|
||||
|
||||
/* Grayscale Chrome Palette: paper white + warm beige */
|
||||
|
||||
--background: 0 0% 100%;
|
||||
@@ -169,6 +177,7 @@
|
||||
border-color: hsl(var(--border));
|
||||
}
|
||||
|
||||
|
||||
body {
|
||||
background-color: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
@@ -322,7 +331,11 @@ h1, h2, h3 {
|
||||
0 0 0 4px hsl(var(--primary) / 0.35);
|
||||
}
|
||||
|
||||
/* Custom scrollbar - minimal */
|
||||
/* Overlay-style scrollbars: invisible at rest, revealed only while the
|
||||
container is actually scrolling. ScrollbarReveal (mounted in the root
|
||||
layout) toggles .is-scrolling on the scrolled element; the thumb fades
|
||||
back out when scrolling stops. The gutter is reserved either way, so
|
||||
revealing never shifts layout. */
|
||||
::-webkit-scrollbar {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
@@ -333,12 +346,23 @@ h1, h2, h3 {
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
background: hsl(var(--muted-foreground) / 0.2);
|
||||
background: transparent;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
background: hsl(var(--muted-foreground) / 0.3);
|
||||
.is-scrolling::-webkit-scrollbar-thumb {
|
||||
background: hsl(var(--muted-foreground) / 0.25);
|
||||
}
|
||||
|
||||
@supports (scrollbar-color: auto) {
|
||||
* {
|
||||
scrollbar-width: thin;
|
||||
scrollbar-color: transparent transparent;
|
||||
transition: scrollbar-color 300ms ease-out;
|
||||
}
|
||||
.is-scrolling {
|
||||
scrollbar-color: hsl(var(--muted-foreground) / 0.3) transparent;
|
||||
}
|
||||
}
|
||||
|
||||
/* Hide scrollbar utility */
|
||||
|
||||
@@ -11,6 +11,7 @@ import { ThemeProvider } from "@/components/theme-provider";
|
||||
import { SWRProvider } from "@/components/providers/SWRProvider";
|
||||
import { RecaptLoader } from "@/components/RecaptLoader";
|
||||
import { RecaptHideWidget } from "@/components/RecaptHideWidget";
|
||||
import { ScrollbarReveal } from "@/components/ScrollbarReveal";
|
||||
import { ensureInitialized } from "@/lib/init";
|
||||
import { getBranding } from "@/lib/branding/service";
|
||||
import "./globals.css";
|
||||
@@ -92,6 +93,7 @@ export default async function RootLayout({
|
||||
<Toaster />
|
||||
<DeployReloadPrompt />
|
||||
<RecaptHideWidget />
|
||||
<ScrollbarReveal />
|
||||
</SWRProvider>
|
||||
</ThemeProvider>
|
||||
</NextIntlClientProvider>
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect } from 'react'
|
||||
|
||||
// How long after the last scroll event the scrollbar stays visible.
|
||||
const IDLE_MS = 700
|
||||
|
||||
/**
|
||||
* Reveals scrollbars only while their container is actually scrolling.
|
||||
* One capture-phase listener on the document catches scroll events from
|
||||
* every scroll container (panel, sidebar, dialogs, dropdown lists) and
|
||||
* stamps .is-scrolling on the scrolled element; globals.css makes the
|
||||
* thumb visible for that class and transparent otherwise. Renders nothing.
|
||||
*/
|
||||
export function ScrollbarReveal() {
|
||||
useEffect(() => {
|
||||
const timers = new WeakMap<Element, number>()
|
||||
|
||||
const onScroll = (e: Event) => {
|
||||
const target = e.target
|
||||
const el =
|
||||
target === document ? document.documentElement : (target as Element)
|
||||
if (!(el instanceof Element)) return
|
||||
el.classList.add('is-scrolling')
|
||||
const prev = timers.get(el)
|
||||
if (prev) window.clearTimeout(prev)
|
||||
timers.set(
|
||||
el,
|
||||
window.setTimeout(() => el.classList.remove('is-scrolling'), IDLE_MS),
|
||||
)
|
||||
}
|
||||
|
||||
document.addEventListener('scroll', onScroll, {
|
||||
capture: true,
|
||||
passive: true,
|
||||
})
|
||||
return () =>
|
||||
document.removeEventListener('scroll', onScroll, { capture: true })
|
||||
}, [])
|
||||
|
||||
return null
|
||||
}
|
||||
@@ -6,7 +6,7 @@ import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { switchCompany } from '@/lib/company/actions'
|
||||
import { performCompanySwitch } from '@/lib/company/switch-client'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { Check, ChevronsUpDown, Plus, Loader2 } from 'lucide-react'
|
||||
|
||||
@@ -81,33 +81,16 @@ export default function CompanySwitcher() {
|
||||
return
|
||||
}
|
||||
setIsPending(true)
|
||||
const result = await switchCompany(companyId)
|
||||
if (result.error) {
|
||||
// Shared switch-and-reload mechanism (lib/company/switch-client), same
|
||||
// path as the sidebar user-menu flyout.
|
||||
const result = await performCompanySwitch(companyId)
|
||||
if (result?.error) {
|
||||
setIsPending(false)
|
||||
toast({
|
||||
title: t(result.error === 'not_member' ? 'error_no_access' : 'error_switch_failed'),
|
||||
variant: 'destructive',
|
||||
})
|
||||
return
|
||||
}
|
||||
// Notify every other open tab of the same user so they hard-reload
|
||||
// onto the new company. BroadcastChannel is best-effort: if the
|
||||
// browser doesn't support it (very old) we still hard-reload
|
||||
// ourselves, and other tabs will self-correct via the visibilitychange
|
||||
// / pageshow listeners in CompanyTabSync on their next focus event.
|
||||
if (typeof BroadcastChannel !== 'undefined') {
|
||||
try {
|
||||
const channel = new BroadcastChannel('gnubok-company-switch')
|
||||
channel.postMessage({ companyId })
|
||||
channel.close()
|
||||
} catch {
|
||||
// Ignore: hard reload still happens below
|
||||
}
|
||||
}
|
||||
// Hard navigation: tears down React state, router cache, in-flight
|
||||
// fetches, blob URLs, etc. This is the whole point: nothing from the
|
||||
// previous company can survive the switch.
|
||||
window.location.assign('/')
|
||||
}
|
||||
|
||||
// Always allow opening the dropdown (to show "Lägg till företag")
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,358 @@
|
||||
'use client'
|
||||
|
||||
import { useState, useRef, useEffect, useCallback } from 'react'
|
||||
import { createPortal } from 'react-dom'
|
||||
import Link from 'next/link'
|
||||
import { useTranslations } from 'next-intl'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { useCompany } from '@/contexts/CompanyContext'
|
||||
import { performCompanySwitch } from '@/lib/company/switch-client'
|
||||
import { useToast } from '@/components/ui/use-toast'
|
||||
import { SupportLink } from '@/components/ui/support-link'
|
||||
import {
|
||||
Building2,
|
||||
Check,
|
||||
ChevronsUpDown,
|
||||
ChevronRight,
|
||||
CreditCard,
|
||||
HelpCircle,
|
||||
Loader2,
|
||||
LogOut,
|
||||
MessagesSquare,
|
||||
Plus,
|
||||
Search,
|
||||
Settings,
|
||||
Users,
|
||||
} from 'lucide-react'
|
||||
|
||||
// Community invite (Accounted's Discord). Deliberately a constant, not
|
||||
// branding config: self-hosted rebrands can hide or swap it when someone
|
||||
// actually asks for that.
|
||||
const DISCORD_INVITE_URL = 'https://discord.gg/D9SxtTgvx'
|
||||
|
||||
interface UserMenuProps {
|
||||
userName: string | null
|
||||
userEmail: string | null
|
||||
isSandbox: boolean
|
||||
collapsed: boolean
|
||||
onLogout: () => void
|
||||
}
|
||||
|
||||
// Best single-character initial for the avatar. Prefers the first letter of
|
||||
// the full name; falls back to the email; falls back to "?" so the circle
|
||||
// never renders empty.
|
||||
function accountInitial(name: string | null, email: string | null): string {
|
||||
const trimmedName = name?.trim()
|
||||
if (trimmedName && trimmedName.length > 0) return trimmedName[0]!.toUpperCase()
|
||||
const trimmedEmail = email?.trim()
|
||||
if (trimmedEmail && trimmedEmail.length > 0) return trimmedEmail[0]!.toUpperCase()
|
||||
return '?'
|
||||
}
|
||||
|
||||
/**
|
||||
* Sticky bottom-of-sidebar user block: avatar initials, name, active company,
|
||||
* chevron. Opens an upward popover aligned with the nav column holding
|
||||
* identity, the company-switcher flyout, account links and logout.
|
||||
* Concept reference: ui_migration_plan.md PR 2.
|
||||
*/
|
||||
export default function UserMenu({
|
||||
userName,
|
||||
userEmail,
|
||||
isSandbox,
|
||||
collapsed,
|
||||
onLogout,
|
||||
}: UserMenuProps) {
|
||||
const { company, companies, isSandbox: companyCtxSandbox } = useCompany()
|
||||
const tNav = useTranslations('nav')
|
||||
const tCommon = useTranslations('common')
|
||||
const tSwitcher = useTranslations('company_switcher')
|
||||
const { toast } = useToast()
|
||||
|
||||
const [open, setOpen] = useState(false)
|
||||
const [companiesOpen, setCompaniesOpen] = useState(false)
|
||||
const [query, setQuery] = useState('')
|
||||
const [isPending, setIsPending] = useState(false)
|
||||
const triggerRef = useRef<HTMLButtonElement>(null)
|
||||
const menuRef = useRef<HTMLDivElement>(null)
|
||||
const searchRef = useRef<HTMLInputElement>(null)
|
||||
const [menuPos, setMenuPos] = useState({ top: 0, left: 0 })
|
||||
|
||||
const sandbox = isSandbox || companyCtxSandbox
|
||||
|
||||
const updatePosition = useCallback(() => {
|
||||
if (!triggerRef.current || !menuRef.current) return
|
||||
const triggerRect = triggerRef.current.getBoundingClientRect()
|
||||
const menuRect = menuRef.current.getBoundingClientRect()
|
||||
const margin = 8
|
||||
// Upward popover: bottom edge sits just above the trigger, left-aligned
|
||||
// with the nav column.
|
||||
const top = Math.max(margin, triggerRect.top - menuRect.height - 6)
|
||||
const left = Math.max(margin, triggerRect.left)
|
||||
setMenuPos({ top, left })
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
const raf = requestAnimationFrame(() => updatePosition())
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [open, companiesOpen, updatePosition])
|
||||
|
||||
// Focus the search field when the company flyout opens.
|
||||
useEffect(() => {
|
||||
if (!companiesOpen) return
|
||||
const raf = requestAnimationFrame(() => searchRef.current?.focus())
|
||||
return () => cancelAnimationFrame(raf)
|
||||
}, [companiesOpen])
|
||||
|
||||
const close = useCallback(() => {
|
||||
setOpen(false)
|
||||
setCompaniesOpen(false)
|
||||
setQuery('')
|
||||
}, [])
|
||||
|
||||
// Outside click. Two carve-outs: elements already removed from the DOM
|
||||
// (isConnected: clicking a row that re-renders must not read as outside,
|
||||
// known concept bug pattern), and portaled dialogs (the support dialog
|
||||
// opens above the menu; interacting with it must not unmount it).
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
function handleClick(e: MouseEvent) {
|
||||
const target = e.target as HTMLElement
|
||||
if (!target.isConnected) return
|
||||
if (target.closest('[role="dialog"]')) return
|
||||
if (
|
||||
(!triggerRef.current || !triggerRef.current.contains(target)) &&
|
||||
(!menuRef.current || !menuRef.current.contains(target))
|
||||
) {
|
||||
close()
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClick)
|
||||
return () => document.removeEventListener('mousedown', handleClick)
|
||||
}, [open, close])
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return
|
||||
function handleKey(e: KeyboardEvent) {
|
||||
if (e.key !== 'Escape') return
|
||||
// Esc closes the flyout first, then the menu; but never while the
|
||||
// support dialog is open (it handles its own Esc).
|
||||
if (document.querySelector('[role="dialog"]')) return
|
||||
if (companiesOpen) {
|
||||
setCompaniesOpen(false)
|
||||
setQuery('')
|
||||
} else {
|
||||
close()
|
||||
}
|
||||
}
|
||||
document.addEventListener('keydown', handleKey)
|
||||
return () => document.removeEventListener('keydown', handleKey)
|
||||
}, [open, companiesOpen, close])
|
||||
|
||||
const handleSwitch = async (companyId: string) => {
|
||||
if (company && companyId === company.id) {
|
||||
close()
|
||||
return
|
||||
}
|
||||
setIsPending(true)
|
||||
const result = await performCompanySwitch(companyId)
|
||||
if (result?.error) {
|
||||
setIsPending(false)
|
||||
toast({
|
||||
title: tSwitcher(
|
||||
result.error === 'not_member' ? 'error_no_access' : 'error_switch_failed',
|
||||
),
|
||||
variant: 'destructive',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
const filteredCompanies = companies.filter(({ company: c }) =>
|
||||
c.name.toLowerCase().includes(query.trim().toLowerCase()),
|
||||
)
|
||||
|
||||
const menuRow =
|
||||
'flex w-full items-center gap-2.5 rounded-md px-2.5 py-2 text-left text-[13px] ' +
|
||||
'text-muted-foreground hover:text-foreground hover:bg-secondary/60 ' +
|
||||
'transition-colors duration-150 cursor-pointer'
|
||||
|
||||
return (
|
||||
<>
|
||||
<button
|
||||
ref={triggerRef}
|
||||
type="button"
|
||||
onClick={() => (open ? close() : setOpen(true))}
|
||||
aria-expanded={open}
|
||||
aria-haspopup="menu"
|
||||
className={cn(
|
||||
'group flex w-full items-center rounded-lg text-left transition-colors duration-150 hover:bg-secondary/60',
|
||||
collapsed ? 'justify-center p-2' : 'gap-2.5 px-3 py-2',
|
||||
)}
|
||||
>
|
||||
<span className="flex h-7 w-7 flex-shrink-0 items-center justify-center rounded-full bg-secondary text-[11px] font-semibold uppercase text-foreground">
|
||||
{accountInitial(userName, userEmail)}
|
||||
</span>
|
||||
{!collapsed && (
|
||||
<>
|
||||
<span className="flex-1 min-w-0">
|
||||
<span className="block truncate text-[13px] font-medium text-foreground leading-tight">
|
||||
{userName?.trim() || userEmail || tNav('mitt_konto')}
|
||||
</span>
|
||||
{company && (
|
||||
<span className="block truncate text-[11px] text-muted-foreground leading-tight">
|
||||
{company.name}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<ChevronsUpDown className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground opacity-50 group-hover:opacity-100" />
|
||||
</>
|
||||
)}
|
||||
</button>
|
||||
|
||||
{open &&
|
||||
createPortal(
|
||||
<div
|
||||
ref={menuRef}
|
||||
role="menu"
|
||||
className="fixed z-[60] w-[232px] rounded-lg border border-border bg-popover py-1 shadow-lg animate-in fade-in slide-in-from-bottom-1 duration-150"
|
||||
style={{ top: menuPos.top, left: menuPos.left }}
|
||||
>
|
||||
{/* Identity */}
|
||||
{(userName || userEmail) && (
|
||||
<div className="border-b border-border/60 px-3 py-2.5">
|
||||
{userName && (
|
||||
<p className="truncate text-[13px] font-medium text-foreground">{userName}</p>
|
||||
)}
|
||||
{userEmail && (
|
||||
<p className="truncate text-[11px] text-muted-foreground">{userEmail}</p>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Company switcher flyout */}
|
||||
<div className="relative px-1 pt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setCompaniesOpen((v) => !v)}
|
||||
aria-expanded={companiesOpen}
|
||||
className={cn(menuRow, companiesOpen && 'bg-secondary/60 text-foreground')}
|
||||
>
|
||||
<Building2 className="h-4 w-4 flex-shrink-0" />
|
||||
<span className="flex-1 truncate">
|
||||
{company?.name || tSwitcher('default_company_name')}
|
||||
</span>
|
||||
<ChevronRight className="h-3.5 w-3.5 flex-shrink-0 opacity-50" />
|
||||
</button>
|
||||
|
||||
{companiesOpen && (
|
||||
// Top-aligned with the company row, growing DOWNWARD
|
||||
// (founder feedback 2026-07-23: never upward over the menu).
|
||||
<div className="absolute top-0 left-full z-[61] ml-1.5 w-60 rounded-lg border border-border bg-popover py-1 shadow-lg animate-in fade-in slide-in-from-left-1 duration-150">
|
||||
<div className="flex items-center gap-2 border-b border-border/60 px-3 pb-2 pt-1.5">
|
||||
<Search className="h-3.5 w-3.5 flex-shrink-0 text-muted-foreground" />
|
||||
<input
|
||||
ref={searchRef}
|
||||
value={query}
|
||||
onChange={(e) => setQuery(e.target.value)}
|
||||
placeholder={tSwitcher('search_placeholder')}
|
||||
className="w-full bg-transparent text-[13px] text-foreground placeholder:text-muted-foreground/60 focus:outline-none"
|
||||
/>
|
||||
</div>
|
||||
<div className="max-h-56 overflow-y-auto px-1 py-1" role="listbox">
|
||||
{filteredCompanies.length === 0 && (
|
||||
<p className="px-2.5 py-2 text-[12px] text-muted-foreground">
|
||||
{tSwitcher('no_results')}
|
||||
</p>
|
||||
)}
|
||||
{filteredCompanies.map(({ company: c, role }) => (
|
||||
<button
|
||||
key={c.id}
|
||||
onClick={() => handleSwitch(c.id)}
|
||||
disabled={isPending}
|
||||
role="option"
|
||||
aria-selected={c.id === company?.id}
|
||||
className={cn(
|
||||
'flex w-full items-center gap-2 rounded-md px-2.5 py-2 text-left text-[13px] leading-snug transition-colors',
|
||||
c.id === company?.id
|
||||
? 'bg-secondary/60 text-foreground'
|
||||
: 'text-muted-foreground hover:bg-secondary/60 hover:text-foreground',
|
||||
isPending && 'opacity-50',
|
||||
)}
|
||||
>
|
||||
<Building2 className="h-4 w-4 flex-shrink-0 text-muted-foreground" />
|
||||
<span className="min-w-0 flex-1 truncate">{c.name}</span>
|
||||
{role !== 'owner' && (
|
||||
<span className="flex-shrink-0 text-[10px] text-muted-foreground/60">
|
||||
{role}
|
||||
</span>
|
||||
)}
|
||||
{c.id === company?.id && (
|
||||
<Check className="h-3.5 w-3.5 flex-shrink-0 text-primary" />
|
||||
)}
|
||||
{isPending && c.id !== company?.id && (
|
||||
<Loader2 className="h-3 w-3 flex-shrink-0 animate-spin text-muted-foreground" />
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
{!sandbox && (
|
||||
<div className="border-t border-border/60 px-1 pt-1">
|
||||
<Link href="/select-company" onClick={close} className={menuRow}>
|
||||
<Plus className="h-4 w-4 flex-shrink-0" />
|
||||
{tSwitcher('add_company')}
|
||||
</Link>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Account links */}
|
||||
<div className="px-1 pb-1">
|
||||
<Link href="/settings" onClick={close} className={menuRow}>
|
||||
<Settings className="h-4 w-4 flex-shrink-0" />
|
||||
{tNav('settings')}
|
||||
</Link>
|
||||
<Link href="/settings/team" onClick={close} className={menuRow}>
|
||||
<Users className="h-4 w-4 flex-shrink-0" />
|
||||
{tNav('members_roles')}
|
||||
</Link>
|
||||
<Link href="/settings/billing" onClick={close} className={menuRow}>
|
||||
<CreditCard className="h-4 w-4 flex-shrink-0" />
|
||||
{tNav('subscription')}
|
||||
</Link>
|
||||
<div className="my-1 border-t border-border/60" />
|
||||
<Link href="/help" onClick={close} className={menuRow}>
|
||||
<HelpCircle className="h-4 w-4 flex-shrink-0" />
|
||||
{tNav('help')}
|
||||
</Link>
|
||||
<a
|
||||
href={DISCORD_INVITE_URL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
onClick={close}
|
||||
className={menuRow}
|
||||
>
|
||||
<MessagesSquare className="h-4 w-4 flex-shrink-0" />
|
||||
{tNav('discord_community')}
|
||||
</a>
|
||||
<SupportLink variant="muted" className={menuRow} />
|
||||
<div className="my-1 border-t border-border/60" />
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
close()
|
||||
onLogout()
|
||||
}}
|
||||
className={cn(menuRow, 'text-destructive hover:text-destructive')}
|
||||
>
|
||||
<LogOut className="h-4 w-4 flex-shrink-0" />
|
||||
{sandbox ? tNav('logout_sandbox') : tCommon('logout')}
|
||||
</button>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
'use client'
|
||||
|
||||
import { switchCompany } from '@/lib/company/actions'
|
||||
|
||||
/**
|
||||
* Client-side company switch: persists the new active company via the
|
||||
* server action, notifies sibling tabs, then hard-reloads onto the new
|
||||
* company. Shared by CompanySwitcher (mobile sheet) and the sidebar
|
||||
* user-menu flyout so both use the exact same mechanism.
|
||||
*
|
||||
* Returns an error code instead of navigating when the switch fails.
|
||||
*/
|
||||
export async function performCompanySwitch(
|
||||
companyId: string,
|
||||
): Promise<{ error: string } | void> {
|
||||
const result = await switchCompany(companyId)
|
||||
if (result.error) {
|
||||
return { error: result.error }
|
||||
}
|
||||
// Notify every other open tab of the same user so they hard-reload
|
||||
// onto the new company. BroadcastChannel is best-effort: if the
|
||||
// browser doesn't support it (very old) we still hard-reload
|
||||
// ourselves, and other tabs will self-correct via the visibilitychange
|
||||
// / pageshow listeners in CompanyTabSync on their next focus event.
|
||||
if (typeof BroadcastChannel !== 'undefined') {
|
||||
try {
|
||||
const channel = new BroadcastChannel('gnubok-company-switch')
|
||||
channel.postMessage({ companyId })
|
||||
channel.close()
|
||||
} catch {
|
||||
// Ignore: hard reload still happens below
|
||||
}
|
||||
}
|
||||
// Hard navigation: tears down React state, router cache, in-flight
|
||||
// fetches, blob URLs, etc. This is the whole point: nothing from the
|
||||
// previous company can survive the switch.
|
||||
window.location.assign('/')
|
||||
}
|
||||
+13
-4
@@ -97,11 +97,11 @@
|
||||
"time_tracking": "Time tracking",
|
||||
"expenses": "Expenses",
|
||||
"receipts": "Receipts",
|
||||
"deadlines": "Deadlines",
|
||||
"deadlines": "Important dates",
|
||||
"vat_declaration": "VAT",
|
||||
"skattekonto": "Tax account",
|
||||
"periodiseringar": "Accruals",
|
||||
"year_end": "Year-end",
|
||||
"year_end": "Annual accounts",
|
||||
"annual_report": "Annual report",
|
||||
"income_declaration": "Income tax return",
|
||||
"pending": "Pending",
|
||||
@@ -129,7 +129,14 @@
|
||||
"logout_sandbox": "Exit sandbox",
|
||||
"trial_days_left": "Trial: {days, plural, =1 {1 day} other {# days}} left",
|
||||
"ext_tic": "Company profile",
|
||||
"ext_invoice_inbox": "Document inbox"
|
||||
"ext_invoice_inbox": "Document inbox",
|
||||
"fold_register": "Registers",
|
||||
"fold_bokslut": "Year-end",
|
||||
"collapse_nav": "Collapse menu",
|
||||
"expand_nav": "Expand menu",
|
||||
"members_roles": "Members and roles",
|
||||
"subscription": "Subscription",
|
||||
"discord_community": "Discord community"
|
||||
},
|
||||
"agentKnowledge": {
|
||||
"load_error_title": "Couldn't load the knowledge profile",
|
||||
@@ -4447,7 +4454,9 @@
|
||||
"default_company_name": "My business",
|
||||
"add_company": "Add company",
|
||||
"error_no_access": "You don't have access to this company.",
|
||||
"error_switch_failed": "The company switch could not be saved. Please try again."
|
||||
"error_switch_failed": "The company switch could not be saved. Please try again.",
|
||||
"search_placeholder": "Search companies...",
|
||||
"no_results": "No matching companies"
|
||||
},
|
||||
"transactions": {
|
||||
"page_title": "Transactions",
|
||||
|
||||
+13
-4
@@ -97,11 +97,11 @@
|
||||
"time_tracking": "Tidrapportering",
|
||||
"expenses": "Utlägg",
|
||||
"receipts": "Kvitton",
|
||||
"deadlines": "Deadlines",
|
||||
"deadlines": "Viktiga datum",
|
||||
"vat_declaration": "Moms",
|
||||
"skattekonto": "Skattekonto",
|
||||
"periodiseringar": "Periodiseringar",
|
||||
"year_end": "Bokslut",
|
||||
"year_end": "Årsbokslut",
|
||||
"annual_report": "Årsredovisning",
|
||||
"income_declaration": "Inkomstdeklaration",
|
||||
"pending": "Väntande",
|
||||
@@ -129,7 +129,14 @@
|
||||
"logout_sandbox": "Avsluta sandbox",
|
||||
"trial_days_left": "Provperiod: {days, plural, =1 {1 dag} other {# dagar}} kvar",
|
||||
"ext_tic": "Företagsprofil",
|
||||
"ext_invoice_inbox": "Dokumentinkorg"
|
||||
"ext_invoice_inbox": "Dokumentinkorg",
|
||||
"fold_register": "Register",
|
||||
"fold_bokslut": "Bokslut",
|
||||
"collapse_nav": "Minimera menyn",
|
||||
"expand_nav": "Expandera menyn",
|
||||
"members_roles": "Medlemmar och roller",
|
||||
"subscription": "Abonnemang",
|
||||
"discord_community": "Discord-community"
|
||||
},
|
||||
"agentKnowledge": {
|
||||
"load_error_title": "Kunde inte läsa in kunskapsprofilen",
|
||||
@@ -4447,7 +4454,9 @@
|
||||
"default_company_name": "Min verksamhet",
|
||||
"add_company": "Lägg till företag",
|
||||
"error_no_access": "Du har inte tillgång till detta företag.",
|
||||
"error_switch_failed": "Företagsbytet kunde inte sparas. Försök igen."
|
||||
"error_switch_failed": "Företagsbytet kunde inte sparas. Försök igen.",
|
||||
"search_placeholder": "Sök företag...",
|
||||
"no_results": "Inga företag matchar"
|
||||
},
|
||||
"transactions": {
|
||||
"page_title": "Transaktioner",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
-- Per-user UI state bag (UI migration PR 2, dev_docs/ui_migration_plan.md).
|
||||
-- Holds client-driven interface preferences that should follow the user
|
||||
-- across devices: sidebar collapse (nav_collapsed), nav fold state
|
||||
-- (nav_folds.register / nav_folds.bokslut), and later the split-button
|
||||
-- last-used create modes (create_mode.*, plan PR 3/4).
|
||||
--
|
||||
-- Deliberately one jsonb column instead of per-preference columns: these
|
||||
-- values are cosmetic, never load-bearing, and never queried server-side
|
||||
-- except to echo back to the client. Existing RLS on user_preferences
|
||||
-- (select/insert/update own row) covers it; no policy changes.
|
||||
|
||||
ALTER TABLE public.user_preferences
|
||||
ADD COLUMN IF NOT EXISTS ui_state jsonb NOT NULL DEFAULT '{}'::jsonb;
|
||||
|
||||
COMMENT ON COLUMN public.user_preferences.ui_state IS
|
||||
'Client-driven UI preferences (nav collapse/fold state, last-used create modes). Cosmetic only, never authoritative for business logic.';
|
||||
@@ -59,10 +59,26 @@ export interface UserPreferences {
|
||||
id: string
|
||||
user_id: string
|
||||
active_company_id: string | null
|
||||
// Client-driven UI preferences (nav collapse/fold state, last-used create
|
||||
// modes). jsonb DEFAULT '{}'. Cosmetic only, never load-bearing.
|
||||
ui_state?: UserUiState
|
||||
created_at: string
|
||||
updated_at: string
|
||||
}
|
||||
|
||||
// Shape of user_preferences.ui_state. All fields optional: the bag grows
|
||||
// as UI surfaces add preferences (UI migration plan PR 2/3).
|
||||
export interface UserUiState {
|
||||
nav_collapsed?: boolean
|
||||
nav_folds?: {
|
||||
register?: boolean
|
||||
bokslut?: boolean
|
||||
}
|
||||
// Split-button last-used create modes, keyed per surface (plan PR 3/4),
|
||||
// e.g. create_mode.bookkeeping = 'mall'.
|
||||
create_mode?: Record<string, string>
|
||||
}
|
||||
|
||||
// Transaction categories
|
||||
export type TransactionCategory =
|
||||
| 'income_services'
|
||||
|
||||
Reference in New Issue
Block a user