Sidebar: make it possible to set the sidebar as collapsed (#72)

* Sidebar: make it possible to set the sidebar as collapsed
This commit is contained in:
Giancarlo Buomprisco
2024-10-14 11:31:18 +02:00
committed by GitHub
parent d137df2675
commit b2c27eb25b
19 changed files with 221 additions and 100 deletions

View File

@@ -52,6 +52,7 @@ function SuspendedPersonalAccountDropdown(props: { user: User | null }) {
if (userData) {
return (
<PersonalAccountDropdown
showProfileName={false}
paths={paths}
features={features}
user={userData}

View File

@@ -20,7 +20,7 @@ export function AdminSidebar(props: { user: User }) {
</SidebarContent>
<SidebarContent className={'mt-5'}>
<SidebarGroup label={'Admin'} collapsible={false}>
<SidebarGroup label={'Admin'}>
<SidebarItem end path={'/admin'} Icon={<Home className={'h-4'} />}>
Home
</SidebarItem>
@@ -35,7 +35,7 @@ export function AdminSidebar(props: { user: User }) {
</SidebarContent>
<SidebarContent className={'absolute bottom-4'}>
<ProfileAccountDropdownContainer user={props.user} collapsed={false} />
<ProfileAccountDropdownContainer user={props.user} />
</SidebarContent>
</Sidebar>
);

View File

@@ -1,8 +1,11 @@
'use client';
import { useContext } from 'react';
import { useRouter } from 'next/navigation';
import { AccountSelector } from '@kit/accounts/account-selector';
import { SidebarContext } from '@kit/ui/sidebar';
import featureFlagsConfig from '~/config/feature-flags.config';
import pathsConfig from '~/config/paths.config';
@@ -19,13 +22,13 @@ export function HomeAccountSelector(props: {
}>;
userId: string;
collapsed: boolean;
}) {
const router = useRouter();
const { collapsed } = useContext(SidebarContext);
return (
<AccountSelector
collapsed={props.collapsed}
collapsed={collapsed}
accounts={props.accounts}
features={features}
userId={props.userId}

View File

@@ -53,14 +53,12 @@ export function HomeMenuNavigation(props: { workspace: UserWorkspace }) {
<HomeAccountSelector
userId={user.id}
accounts={accounts}
collapsed={false}
/>
</If>
<UserNotifications userId={user.id} />
<ProfileAccountDropdownContainer
collapsed={true}
user={user}
account={workspace}
/>

View File

@@ -71,7 +71,6 @@ export function HomeMobileNavigation(props: { workspace: UserWorkspace }) {
<HomeAccountSelector
userId={props.workspace.user.id}
accounts={props.workspace.accounts}
collapsed={false}
/>
</DropdownMenuGroup>

View File

@@ -11,25 +11,28 @@ import { UserNotifications } from '~/home/(user)/_components/user-notifications'
import type { UserWorkspace } from '../_lib/server/load-user-workspace';
import { HomeAccountSelector } from './home-account-selector';
export function HomeSidebar(props: { workspace: UserWorkspace }) {
interface HomeSidebarProps {
workspace: UserWorkspace;
}
export function HomeSidebar(props: HomeSidebarProps) {
const { workspace, user, accounts } = props.workspace;
const collapsed = personalAccountNavigationConfig.sidebarCollapsed;
return (
<Sidebar>
<Sidebar collapsed={collapsed}>
<SidebarContent className={'h-16 justify-center'}>
<div className={'flex items-center justify-between space-x-2'}>
<If
condition={featuresFlagConfig.enableTeamAccounts}
fallback={<AppLogo className={'py-2'} />}
>
<HomeAccountSelector
userId={user.id}
collapsed={false}
accounts={accounts}
/>
<HomeAccountSelector userId={user.id} accounts={accounts} />
</If>
<UserNotifications userId={user.id} />
<div className={'hidden group-aria-[expanded=true]/sidebar:block'}>
<UserNotifications userId={user.id} />
</div>
</div>
</SidebarContent>
@@ -40,7 +43,6 @@ export function HomeSidebar(props: { workspace: UserWorkspace }) {
<div className={'absolute bottom-4 left-0 w-full'}>
<SidebarContent>
<ProfileAccountDropdownContainer
collapsed={false}
user={user}
account={workspace}
/>

View File

@@ -39,6 +39,7 @@ function UserHomeLayout({ children }: React.PropsWithChildren) {
<PageMobileNavigation className={'flex items-center justify-between'}>
<AppLogo />
<HomeMobileNavigation workspace={workspace} />
</PageMobileNavigation>
@@ -56,4 +57,4 @@ function getLayoutStyle() {
(cookies().get('layout-style')?.value as PageLayoutStyle) ??
personalAccountNavigationConfig.style
);
}
}

View File

@@ -20,6 +20,8 @@ export function TeamAccountAccountsSelector(params: {
value: string | null;
image: string | null;
}>;
collapsed?: boolean;
}) {
const router = useRouter();
@@ -28,7 +30,7 @@ export function TeamAccountAccountsSelector(params: {
selectedAccount={params.selectedAccount}
accounts={params.accounts}
userId={params.userId}
collapsed={false}
collapsed={params.collapsed}
features={features}
onAccountChange={(value) => {
const path = value

View File

@@ -1,8 +1,14 @@
import { User } from '@supabase/supabase-js';
'use client';
import { Sidebar, SidebarContent } from '@kit/ui/sidebar';
import { useContext } from 'react';
import type { User } from '@supabase/supabase-js';
import { Sidebar, SidebarContent, SidebarContext } from '@kit/ui/sidebar';
import { cn } from '@kit/ui/utils';
import { ProfileAccountDropdownContainer } from '~/components//personal-account-dropdown-container';
import { getTeamAccountSidebarConfig } from '~/config/team-account-navigation.config';
import { TeamAccountNotifications } from '~/home/[account]/_components/team-account-notifications';
import { TeamAccountAccountsSelector } from '../_components/team-account-accounts-selector';
@@ -18,11 +24,12 @@ export function TeamAccountLayoutSidebar(props: {
account: string;
accountId: string;
accounts: AccountModel[];
collapsed: boolean;
user: User;
}) {
const collapsed = getTeamAccountSidebarConfig(props.account).sidebarCollapsed;
return (
<Sidebar>
<Sidebar collapsed={collapsed}>
<SidebarContainer
account={props.account}
accountId={props.accountId}
@@ -37,28 +44,40 @@ function SidebarContainer(props: {
account: string;
accountId: string;
accounts: AccountModel[];
collapsible?: boolean;
user: User;
}) {
const { account, accounts, user } = props;
const userId = user.id;
const { collapsed } = useContext(SidebarContext);
const className = cn(
'flex max-w-full items-center justify-between space-x-4',
{
'w-full justify-start space-x-0': collapsed,
},
);
return (
<>
<SidebarContent className={'h-16 justify-center'}>
<div
className={'flex max-w-full items-center justify-between space-x-4'}
>
<div className={className}>
<TeamAccountAccountsSelector
userId={userId}
selectedAccount={account}
accounts={accounts}
collapsed={collapsed}
/>
<TeamAccountNotifications
userId={userId}
accountId={props.accountId}
/>
<div
className={cn({
hidden: collapsed,
})}
>
<TeamAccountNotifications
userId={userId}
accountId={props.accountId}
/>
</div>
</div>
</SidebarContent>
@@ -70,7 +89,6 @@ function SidebarContainer(props: {
<SidebarContent>
<ProfileAccountDropdownContainer
user={props.user}
collapsed={false}
/>
</SidebarContent>
</div>

View File

@@ -62,7 +62,6 @@ export function TeamAccountNavigationMenu(props: {
<TeamAccountNotifications accountId={account.id} userId={user.id} />
<ProfileAccountDropdownContainer
collapsed={true}
user={user}
account={account}
/>

View File

@@ -21,7 +21,7 @@ import { TeamAccountLayoutSidebar } from './_components/team-account-layout-side
import { TeamAccountNavigationMenu } from './_components/team-account-navigation-menu';
import { loadTeamWorkspace } from './_lib/server/team-account-workspace.loader';
interface Params {
interface TeamWorkspaceLayoutParams {
account: string;
}
@@ -29,7 +29,7 @@ function TeamWorkspaceLayout({
children,
params,
}: React.PropsWithChildren<{
params: Params;
params: TeamWorkspaceLayoutParams;
}>) {
const data = use(loadTeamWorkspace(params.account));
const style = getLayoutStyle(params.account);
@@ -45,7 +45,6 @@ function TeamWorkspaceLayout({
<PageNavigation>
<If condition={style === 'sidebar'}>
<TeamAccountLayoutSidebar
collapsed={false}
account={params.account}
accountId={data.account.id}
accounts={accounts}

View File

@@ -18,7 +18,6 @@ const features = {
};
export function ProfileAccountDropdownContainer(props: {
collapsed: boolean;
user: User;
account?: {
@@ -32,16 +31,13 @@ export function ProfileAccountDropdownContainer(props: {
const userData = user.data as User;
return (
<div className={props.collapsed ? '' : 'w-full'}>
<PersonalAccountDropdown
className={'w-full'}
paths={paths}
features={features}
showProfileName={!props.collapsed}
user={userData}
account={props.account}
signOutRequested={() => signOut.mutateAsync()}
/>
</div>
<PersonalAccountDropdown
className={'w-full'}
paths={paths}
features={features}
user={userData}
account={props.account}
signOutRequested={() => signOut.mutateAsync()}
/>
);
}

View File

@@ -32,4 +32,5 @@ if (featureFlagsConfig.enablePersonalAccountBilling) {
export const personalAccountNavigationConfig = NavigationConfigSchema.parse({
routes,
style: process.env.NEXT_PUBLIC_USER_NAVIGATION_STYLE,
sidebarCollapsed: process.env.NEXT_PUBLIC_HOME_SIDEBAR_COLLAPSED,
});

View File

@@ -43,6 +43,7 @@ export function getTeamAccountSidebarConfig(account: string) {
return NavigationConfigSchema.parse({
routes: getRoutes(account),
style: process.env.NEXT_PUBLIC_TEAM_NAVIGATION_STYLE,
sidebarCollapsed: process.env.NEXT_PUBLIC_TEAM_SIDEBAR_COLLAPSED,
});
}

View File

@@ -101,7 +101,7 @@ export function AccountSelector({
'dark:shadow-primary/10 group w-full min-w-0 px-2 lg:w-auto lg:max-w-fit',
{
'justify-start': !collapsed,
'justify-center': collapsed,
'm-auto justify-center px-4 lg:w-full': collapsed,
},
className,
)}
@@ -143,7 +143,11 @@ export function AccountSelector({
)}
</If>
<CaretSortIcon className="ml-2 h-4 w-4 shrink-0 opacity-50" />
<CaretSortIcon
className={cn('ml-2 h-4 w-4 shrink-0 opacity-50', {
hidden: collapsed,
})}
/>
</Button>
</PopoverTrigger>

View File

@@ -33,7 +33,7 @@ export function PersonalAccountDropdown({
className,
user,
signOutRequested,
showProfileName,
showProfileName = true,
paths,
features,
account,
@@ -56,8 +56,9 @@ export function PersonalAccountDropdown({
enableThemeToggle: boolean;
};
className?: string;
showProfileName?: boolean;
className?: string;
}) {
const { data: personalAccountData } = usePersonalAccountData(
user.id,

View File

@@ -7,6 +7,11 @@ const RouteMatchingEnd = z
export const NavigationConfigSchema = z.object({
style: z.enum(['custom', 'sidebar', 'header']).default('sidebar'),
sidebarCollapsed: z
.enum(['false', 'true'])
.default('false')
.optional()
.transform((value) => value === `true`),
routes: z.array(
z.union([
z.object({

View File

@@ -30,14 +30,14 @@ function PageWithSidebar(props: PageProps) {
return (
<div
className={cn('flex bg-gray-50/50 dark:bg-background', props.className)}
className={cn('flex bg-gray-50/95 dark:bg-background/85', props.className)}
>
{Navigation}
<div
className={
props.contentContainerClassName ??
'mx-auto flex h-screen w-full flex-col overflow-y-auto px-4 lg:px-0'
'mx-auto flex h-screen w-full flex-col overflow-y-auto px-4 lg:px-0 bg-inherit'
}
>
{MobileNavigation}
@@ -115,7 +115,7 @@ export function PageBody(
}
export function PageNavigation(props: React.PropsWithChildren) {
return <div className={'hidden flex-1 lg:flex'}>{props.children}</div>;
return <div className={'hidden flex-1 lg:flex bg-inherit'}>{props.children}</div>;
}
export function PageDescription(props: React.PropsWithChildren) {

View File

@@ -1,6 +1,6 @@
'use client';
import { useContext, useId, useState } from 'react';
import { useContext, useId, useRef, useState } from 'react';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
@@ -24,8 +24,11 @@ import { Trans } from './trans';
export type SidebarConfig = z.infer<typeof NavigationConfigSchema>;
export { SidebarContext };
export function Sidebar(props: {
collapsed?: boolean;
expandOnHover?: boolean;
className?: string;
children:
| React.ReactNode
@@ -35,19 +38,62 @@ export function Sidebar(props: {
}) => React.ReactNode);
}) {
const [collapsed, setCollapsed] = useState(props.collapsed ?? false);
const isExpandedRef = useRef<boolean>(false);
const className = getClassNameBuilder(props.className ?? '')({
const expandOnHover =
props.expandOnHover ??
process.env.NEXT_PUBLIC_EXPAND_SIDEBAR_ON_HOVER === 'true';
const sidebarSizeClassName = getSidebarSizeClassName(
collapsed,
isExpandedRef.current,
);
const className = getClassNameBuilder(
cn(props.className ?? '', sidebarSizeClassName, {}),
)();
const containerClassName = cn(sidebarSizeClassName, 'bg-inherit', {
'max-w-[4rem]': expandOnHover && isExpandedRef.current,
});
const ctx = { collapsed, setCollapsed };
const onMouseEnter =
props.collapsed && expandOnHover
? () => {
setCollapsed(false);
isExpandedRef.current = true;
}
: undefined;
const onMouseLeave =
props.collapsed && expandOnHover
? () => {
if (!isRadixPopupOpen()) {
setCollapsed(true);
isExpandedRef.current = false;
} else {
onRadixPopupClose(() => {
setCollapsed(true);
isExpandedRef.current = false;
});
}
}
: undefined;
return (
<SidebarContext.Provider value={ctx}>
<div className={className}>
{typeof props.children === 'function'
? props.children(ctx)
: props.children}
<div
className={containerClassName}
onMouseEnter={onMouseEnter}
onMouseLeave={onMouseLeave}
>
<div aria-expanded={!collapsed} className={className}>
{typeof props.children === 'function'
? props.children(ctx)
: props.children}
</div>
</div>
</SidebarContext.Provider>
);
@@ -55,17 +101,22 @@ export function Sidebar(props: {
export function SidebarContent({
children,
className,
className: customClassName,
}: React.PropsWithChildren<{
className?: string;
}>) {
return (
<div
className={cn('flex w-full flex-col space-y-1.5 px-4 py-1', className)}
>
{children}
</div>
const { collapsed } = useContext(SidebarContext);
const className = cn(
'flex w-full flex-col space-y-1.5 py-1',
customClassName,
{
'px-4': !collapsed,
'px-2': collapsed,
},
);
return <div className={className}>{children}</div>;
}
export function SidebarGroup({
@@ -96,7 +147,7 @@ export function SidebarGroup({
const Wrapper = () => {
const className = cn(
'group flex items-center justify-between px-container space-x-2.5',
'px-container group flex items-center justify-between space-x-2.5',
{
'py-2.5': !sidebarCollapsed,
},
@@ -131,7 +182,11 @@ export function SidebarGroup({
};
return (
<div className={'flex flex-col space-y-1 py-1'}>
<div
className={cn('flex flex-col', {
'space-y-1 py-1': !collapsed,
})}
>
<Wrapper />
<If condition={collapsible ? !isGroupCollapsed : true}>
@@ -164,48 +219,84 @@ export function SidebarItem({
const active = isRouteActive(path, currentPath, end ?? false);
const variant = active ? 'secondary' : 'ghost';
const size = collapsed ? 'icon' : 'sm';
return (
<Button
asChild
className={cn('flex w-full text-sm shadow-none active:bg-secondary/60', {
'justify-start space-x-2.5': !collapsed,
'hover:bg-initial': active,
})}
size={size}
variant={variant}
>
<Link key={path} href={path}>
<If condition={collapsed} fallback={Icon}>
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>{Icon}</TooltipTrigger>
<TooltipProvider delayDuration={0}>
<Tooltip disableHoverableContent>
<TooltipTrigger asChild>
<Button
asChild
className={cn(
'flex w-full text-sm shadow-none active:bg-secondary/60',
{
'justify-start space-x-2.5': !collapsed,
'hover:bg-initial': active,
},
)}
size={'sm'}
variant={variant}
>
<Link key={path} href={path}>
{Icon}
<span className={cn({ hidden: collapsed })}>{children}</span>
</Link>
</Button>
</TooltipTrigger>
<TooltipContent side={'right'} sideOffset={20}>
{children}
</TooltipContent>
</Tooltip>
</TooltipProvider>
<If condition={collapsed}>
<TooltipContent side={'right'} sideOffset={10}>
{children}
</TooltipContent>
</If>
<span className={cn({ hidden: collapsed })}>{children}</span>
</Link>
</Button>
</Tooltip>
</TooltipProvider>
);
}
function getClassNameBuilder(className: string) {
return cva([cn('flex box-content h-screen flex-col relative', className)], {
variants: {
collapsed: {
true: `w-[6rem]`,
false: `w-2/12 lg:w-[17rem]`,
},
},
return cva([
cn(
'group/sidebar transition-width fixed box-content flex h-screen w-2/12 flex-col bg-inherit backdrop-blur-sm duration-100',
className,
),
]);
}
function getSidebarSizeClassName(collapsed: boolean, isExpanded: boolean) {
return cn(['z-10 flex w-full flex-col'], {
'dark:shadow-primary/20 lg:w-[17rem]': !collapsed,
'lg:w-[4rem]': collapsed,
shadow: isExpanded,
});
}
function getRadixPopup() {
return document.querySelector('[data-radix-popper-content-wrapper]');
}
function isRadixPopupOpen() {
return getRadixPopup() !== null;
}
function onRadixPopupClose(callback: () => void) {
const element = getRadixPopup();
if (element) {
const observer = new MutationObserver(() => {
if (!getRadixPopup()) {
callback();
observer.disconnect();
}
});
observer.observe(element.parentElement!, {
childList: true,
subtree: true,
});
}
}
export function SidebarNavigation({
config,
}: React.PropsWithChildren<{