Compare commits

...

2 Commits

Author SHA1 Message Date
Viktor Renkema bddd458446 Add buttons to hide toolbar 2025-10-03 11:53:39 +02:00
Viktor Renkema 174e7f43a2 wip 2025-10-02 10:50:23 +02:00
9 changed files with 1941 additions and 2494 deletions
+1312 -2258
View File
File diff suppressed because it is too large Load Diff
@@ -1,10 +1,12 @@
'use client';
import { Icon } from '@gitbook/icons';
import { MotionConfig } from 'motion/react';
import React from 'react';
import { useCheckForContentUpdate } from '../AutoRefreshContent';
import { useVisitorSession } from '../Insights';
import { useCurrentPagePath } from '../hooks';
import { DateRelative } from '../primitives';
import { DateRelative, Tooltip } from '../primitives';
import { HideToolbarButton } from './HideToolbarButton';
import { IframeWrapper } from './IframeWrapper';
import { RefreshContentButton } from './RefreshContentButton';
import {
@@ -17,48 +19,123 @@ import {
ToolbarSubtitle,
ToolbarTitle,
} from './Toolbar';
import type { AdminToolbarClientProps } from './types';
import { ToolbarControlsProvider } from './ToolbarControlsContext';
import type { AdminToolbarClientProps, AdminToolbarContext } from './types';
export function AdminToolbarClient(props: AdminToolbarClientProps) {
const { context } = props;
const { context, onPersistentClose, onSessionClose, onToggleMinify } = props;
const [minified, setMinified] = React.useState(true);
const visitorSession = useVisitorSession();
const [sessionClosed, setSessionClosed] = React.useState(false);
const [shouldHide, setShouldHide] = React.useState(false);
React.useEffect(() => {
const STORAGE_KEY = 'gitbook_toolbar_closed';
try {
const hidden = !!localStorage.getItem(STORAGE_KEY);
setShouldHide(hidden);
} catch {
setShouldHide(false);
}
}, []);
const handleSessionClose = React.useCallback(() => {
setSessionClosed(true);
onSessionClose?.();
}, [onSessionClose]);
const handlePersistentClose = React.useCallback(() => {
try {
localStorage.setItem('gitbook_toolbar_closed', '1');
} catch {
console.error('Failed to close toolbar using local storage');
}
setSessionClosed(true);
onPersistentClose?.();
}, [onPersistentClose]);
const handleMinifiedChange = React.useCallback(
(value: boolean) => {
setMinified(value);
onToggleMinify?.();
},
[onToggleMinify]
);
const toolbarControls = React.useMemo(
() => ({
minimize: () => handleMinifiedChange(true),
closeSession: handleSessionClose,
closePersistent: handlePersistentClose,
}),
[handleMinifiedChange, handleSessionClose, handlePersistentClose]
);
if (shouldHide || sessionClosed) {
return null;
}
// If there is a change request, show the change request toolbar
if (context.changeRequest) {
return (
<IframeWrapper>
<MotionConfig reducedMotion="user">
<ChangeRequestToolbar context={context} />
</MotionConfig>
</IframeWrapper>
<ToolbarControlsProvider value={toolbarControls}>
<IframeWrapper>
<MotionConfig reducedMotion="user">
<ChangeRequestToolbar
context={context}
minified={minified}
onMinifiedChange={handleMinifiedChange}
/>
</MotionConfig>
</IframeWrapper>
</ToolbarControlsProvider>
);
}
// If the revision is not the current revision, the user is looking at a previous version of the site, so show the revision toolbar
if (context.revisionId !== context.space.revision) {
return (
<IframeWrapper>
<MotionConfig reducedMotion="user">
<RevisionToolbar context={context} />
</MotionConfig>
</IframeWrapper>
<ToolbarControlsProvider value={toolbarControls}>
<IframeWrapper>
<MotionConfig reducedMotion="user">
<RevisionToolbar
context={context}
minified={minified}
onMinifiedChange={handleMinifiedChange}
/>
</MotionConfig>
</IframeWrapper>
</ToolbarControlsProvider>
);
}
// If the user is authenticated and part of the organization owning this site, show the authenticated user toolbar
if (visitorSession?.organizationId === context.organizationId) {
return (
<IframeWrapper>
<MotionConfig reducedMotion="user">
<AuthenticatedUserToolbar context={context} />
</MotionConfig>
</IframeWrapper>
<ToolbarControlsProvider value={toolbarControls}>
<IframeWrapper>
<MotionConfig reducedMotion="user">
<AuthenticatedUserToolbar
context={context}
minified={minified}
onMinifiedChange={handleMinifiedChange}
/>
</MotionConfig>
</IframeWrapper>
</ToolbarControlsProvider>
);
}
}
function ChangeRequestToolbar(props: AdminToolbarClientProps) {
const { context } = props;
interface ToolbarViewProps {
context: AdminToolbarContext;
minified: boolean;
onMinifiedChange: (value: boolean) => void;
}
function ChangeRequestToolbar(props: ToolbarViewProps) {
const { context, minified, onMinifiedChange } = props;
const { changeRequest, site } = context;
if (!changeRequest) {
throw new Error('Change request is not set');
@@ -71,11 +148,11 @@ function ChangeRequestToolbar(props: AdminToolbarClientProps) {
});
return (
<Toolbar label="Site preview">
<Toolbar minified={minified} onMinifiedChange={onMinifiedChange}>
<ToolbarBody>
<ToolbarTitle
prefix="Change request"
suffix={`#${changeRequest.number} ${changeRequest.subject || 'Untitled'}`}
prefix={`Change #${changeRequest.number}:`}
suffix={`${changeRequest.subject || 'Untitled'}`}
/>
<ToolbarSubtitle
subtitle={
@@ -88,9 +165,13 @@ function ChangeRequestToolbar(props: AdminToolbarClientProps) {
<ToolbarSeparator />
<ToolbarButtonGroup>
<ToolbarActions>
{/* Refresh to retrieve latest changes */}
{updated ? <RefreshContentButton refreshForUpdates={refreshForUpdates} /> : null}
{/* Edit in GitBook */}
<EditPageButton href={changeRequest.urls.app} siteId={site.id} />
{/* Comment in app */}
<ToolbarButton
title="Comment in a GitBook"
@@ -125,16 +206,13 @@ function ChangeRequestToolbar(props: AdminToolbarClientProps) {
})}
icon="code-pull-request"
/>
{/* Edit in GitBook */}
<EditPageButton href={changeRequest.urls.app} siteId={site.id} />
</ToolbarButtonGroup>
</ToolbarActions>
</Toolbar>
);
}
function RevisionToolbar(props: AdminToolbarClientProps) {
const { context } = props;
function RevisionToolbar(props: ToolbarViewProps) {
const { context, minified, onMinifiedChange } = props;
const { revision, site } = context;
if (!revision) {
throw new Error('Revision is not set');
@@ -145,19 +223,21 @@ function RevisionToolbar(props: AdminToolbarClientProps) {
const gitProvider = isGitHub ? 'GitHub' : 'GitLab';
return (
<Toolbar label="Site preview">
<ToolbarBody>
<ToolbarTitle prefix="Site version" suffix={context.site.title} />
<ToolbarSubtitle
subtitle={
<>
Created <DateRelative value={revision.createdAt} />
</>
}
/>
</ToolbarBody>
<Toolbar minified={minified} onMinifiedChange={onMinifiedChange}>
<Tooltip label="Site preview">
<ToolbarBody>
<ToolbarTitle prefix="Site version" suffix={context.site.title} />
<ToolbarSubtitle
subtitle={
<>
Created <DateRelative value={revision.createdAt} />
</>
}
/>
</ToolbarBody>
</Tooltip>
<ToolbarSeparator />
<ToolbarButtonGroup>
<ToolbarActions>
{/* Open commit in Git client */}
<ToolbarButton
title={
@@ -205,34 +285,41 @@ function RevisionToolbar(props: AdminToolbarClientProps) {
})}
icon="code-commit"
/>
</ToolbarButtonGroup>
</ToolbarActions>
</Toolbar>
);
}
function AuthenticatedUserToolbar(props: AdminToolbarClientProps) {
const { context } = props;
function AuthenticatedUserToolbar(props: ToolbarViewProps) {
const { context, minified, onMinifiedChange } = props;
const { revision, space, site } = context;
const { refreshForUpdates, updated } = useCheckForContentUpdate({
revisionId: space.revision,
});
return (
<Toolbar label="Only visible to your GitBook organization">
<ToolbarBody>
<ToolbarTitle prefix="Site" suffix={context.site.title} />
<ToolbarSubtitle
subtitle={
<>
Updated <DateRelative value={revision.createdAt} />
</>
}
/>
</ToolbarBody>
<Toolbar minified={minified} onMinifiedChange={onMinifiedChange}>
<Tooltip label="Site preview">
<ToolbarBody>
<ToolbarTitle suffix={context.site.title} />
<ToolbarSubtitle
subtitle={
<>
Updated <DateRelative value={revision.createdAt} />
</>
}
/>
</ToolbarBody>
</Tooltip>
<ToolbarSeparator />
<ToolbarButtonGroup>
<ToolbarActions>
{/* Refresh to retrieve latest changes */}
{updated ? <RefreshContentButton refreshForUpdates={refreshForUpdates} /> : null}
{/* Edit in GitBook */}
<EditPageButton href={space.urls.app} siteId={site.id} />
{/* Open site in GitBook */}
<ToolbarButton
title="Open site in GitBook"
href={getToolbarHref({
@@ -240,8 +327,10 @@ function AuthenticatedUserToolbar(props: AdminToolbarClientProps) {
siteId: site.id,
buttonId: 'site',
})}
icon="gear"
icon="gears"
/>
{/* Customize in GitBook */}
<ToolbarButton
title="Customize in GitBook"
href={getToolbarHref({
@@ -251,6 +340,8 @@ function AuthenticatedUserToolbar(props: AdminToolbarClientProps) {
})}
icon="palette"
/>
{/* Open insights in GitBook */}
<ToolbarButton
title="Open insights in GitBook"
href={getToolbarHref({
@@ -260,12 +351,22 @@ function AuthenticatedUserToolbar(props: AdminToolbarClientProps) {
})}
icon="chart-simple"
/>
<EditPageButton href={space.urls.app} siteId={site.id} />
</ToolbarButtonGroup>
</ToolbarActions>
</Toolbar>
);
}
function ToolbarActions(props: { children: React.ReactNode }) {
const { children } = props;
return (
<ToolbarButtonGroup>
{children}
<HideToolbarButton />
</ToolbarButtonGroup>
);
}
function EditPageButton(props: {
href: string;
siteId: string;
@@ -1,9 +1,9 @@
.svgLogo {
--logo-fill: var(--color-neutral-100);
--logo-fill: var(--color-neutral-900);
--seg-A-color: #2782c4;
--seg-B-color: #43b7f2;
--seg-C-color: #8be2ff;
--trace-color: #46474c;
--trace-color: #dedfe3;
--T: 2s;
@@ -12,8 +12,8 @@
}
:global(html.dark) .svgLogo {
--logo-fill: var(--color-neutral-800);
--trace-color: #dedfe3;
--logo-fill: var(--color-neutral-100);
--trace-color: #46474c;
}
/* Base segment animation */
@@ -0,0 +1,238 @@
'use client';
import { tcls } from '@/lib/tailwind';
import { Icon, type IconName, IconStyle } from '@gitbook/icons';
import { motion } from 'motion/react';
import React, { useRef } from 'react';
import { useOnClickOutside } from 'usehooks-ts';
import { ToolbarButton, type ToolbarButtonProps } from './Toolbar';
import styles from './Toolbar.module.css';
import { useToolbarControls } from './ToolbarControlsContext';
const ARC_DURATION_SECONDS = 0.4;
const ARC_STAGGER_MS = 80;
const BASE_ROTATION_DEG = 95;
const ROTATION_STEP_DEG = 18;
interface HideToolbarButtonProps {
motionValues?: ToolbarButtonProps['motionValues'];
}
/**
* Hide menu trigger. Expands a macOS Dock-like submenu with 3 labeled actions.
*/
export function HideToolbarButton(props: HideToolbarButtonProps) {
const { motionValues } = props;
const [open, setOpen] = React.useState(false);
const controls = useToolbarControls();
const ref = useRef<HTMLDivElement>(null);
const buttonRef = useRef<HTMLDivElement>(null);
const handleClickOutsideArcMenu = (event: Event) => {
// Don't close the arc if we are clicking clicking on the button itself
if (buttonRef.current?.contains(event.target as Node)) {
return;
}
setOpen(false);
};
useOnClickOutside(ref, handleClickOutsideArcMenu);
// Close arc menu on scroll
React.useEffect(() => {
if (!open) return;
const handleScroll = () => setOpen(false);
window.addEventListener('scroll', handleScroll, { passive: true });
return () => window.removeEventListener('scroll', handleScroll);
}, [open]);
const items = React.useMemo(
() =>
[
controls?.minimize
? {
id: 'minimize',
icon: 'minus',
label: 'Minimize',
onClick: controls.minimize,
}
: null,
controls?.closeSession
? {
id: 'session-close',
icon: 'xmark',
label: 'Close for one session',
onClick: controls.closeSession,
}
: null,
controls?.closePersistent
? {
id: 'persistent-close',
icon: 'ban',
label: "Don't show again",
onClick: controls.closePersistent,
}
: null,
].filter(Boolean) as Array<ArcMenuItem>,
[controls]
);
const sharedMotionStyle = motionValues
? {
x: motionValues.x,
}
: undefined;
return (
<ToolbarButton
ref={buttonRef}
title={open ? 'Hide options' : 'Hide toolbar'}
onClick={() => {
setOpen((v) => !v);
}}
motionValues={motionValues}
icon="eye-slash"
>
{/* Expanding arc menu */}
{open && (
<motion.div
className={tcls('pointer-events-none absolute inset-0', styles.arcMenu)}
style={sharedMotionStyle as React.CSSProperties | undefined}
>
<div
className={tcls(
'pointer-events-none absolute left-0 overflow-visible',
styles.arcMenuPath
)}
ref={ref}
>
{items.map((item, index) => (
<ArcToolbarButton
index={index}
staggerIndex={items.length - 1 - index}
key={item.icon}
{...item}
onClick={() => {
setOpen(false);
item.onClick?.();
}}
/>
))}
</div>
</motion.div>
)}
</ToolbarButton>
);
}
type ArcMenuItem = {
id: string;
icon: IconName;
label: string;
description: string;
onClick?: () => void;
};
type ArcToolbarButtonProps = Pick<ArcMenuItem, 'label' | 'icon' | 'onClick'> & {
index: number;
staggerIndex?: number;
disabled?: boolean;
className?: string;
iconClassName?: string;
};
export function ArcToolbarButton(props: ArcToolbarButtonProps) {
const {
index,
staggerIndex = index,
label,
disabled,
className,
onClick = () => {},
icon,
iconClassName,
} = props;
const targetOffset = `calc(var(--start-distance) + ${index} * var(--spread-distance))`;
// Calculate rotation based on position along the arc
const calculateRotation = () => {
return BASE_ROTATION_DEG - index * ROTATION_STEP_DEG;
};
const itemRotation = calculateRotation();
return (
<div className="pointer-events-none">
<button
type="button"
onClick={() => {
onClick();
}}
style={
{
'--target-offset-distance': targetOffset,
'--arc-duration': `${ARC_DURATION_SECONDS}s`,
'--arc-delay': `${(staggerIndex ?? 0) * ARC_STAGGER_MS}ms`,
'--rotation-offset': `${itemRotation}deg`,
offsetPath: 'border-box',
offsetDistance: targetOffset,
offsetAnchor: '0% 40%',
offsetRotate: `auto ${itemRotation}deg`,
} as React.CSSProperties
}
className={tcls(
'group',
'absolute',
'top-0',
'left-0',
'w-40',
'opacity-0',
'pointer-events-auto',
'flex',
'items-center',
'gap-2',
styles.arcMenuItem,
className
)}
>
<div
className={tcls(
'flex shrink-0 items-center justify-center gap-1',
'h-8 w-8 rounded-full border',
'truncate text-sm',
'cursor-pointer transition-colors',
'group-hover:-rotate-5 group-hover:scale-105',
disabled ? 'cursor-not-allowed opacity-50' : '',
'text-tint-1 dark:text-tint-12',
'bg-[linear-gradient(110deg,rgba(51,53,57,1)_0%,rgba(50,52,56,1)_100%)]',
'dark:[background:linear-gradient(110deg,rgba(255,255,255,1)_0%,rgba(240,246,248,1)_100%)]',
'border border-solid dark:border-[rgb(255_255_255_/_40%)]'
)}
style={{
background: 'linear-gradient(rgb(51, 53, 57), rgb(50, 52, 56))',
border: '1px solid rgba(0, 0, 0, 0.06)',
boxShadow: 'rgba(255, 255, 255, 0.15) 0px 1px 1px 0px inset',
}}
>
<Icon
icon={icon as IconName}
iconStyle={IconStyle.Solid}
className={tcls('size-4 shrink-0 group-hover:scale-110', iconClassName)}
/>
</div>
<span
className={tcls(
'whitespace-nowrap rounded-lg px-3 py-1 font-normal text-sm transition-transform',
'group-hover:rotate-2 group-hover:scale-105',
'text-neutral-1 dark:text-neutral-12',
'bg-[linear-gradient(110deg,rgba(51,53,57,1)_0%,rgba(50,52,56,1)_100%)]'
)}
>
{label}
</span>
</button>
</div>
);
}
@@ -0,0 +1,40 @@
.arcMenu {
--arc-width: 505px;
--arc-height: 400px;
--arc-radius: 34%;
--start-distance: -240px;
--spread-distance: 45px;
}
.arcMenuPath {
bottom: calc(var(--arc-height) / -2);
width: var(--arc-width);
height: var(--arc-height);
border-radius: var(--arc-radius);
transform: translate(0%, 0%);
}
.arcMenuItem {
animation-name: hide-toolbar-arc-enter;
animation-timing-function: cubic-bezier(0.22, 1, 0.36, 1);
animation-fill-mode: forwards;
animation-duration: var(--arc-duration, 0.4s);
animation-delay: var(--arc-delay, 0s);
transform-origin: center left;
offset-path: border-box;
offset-anchor: 0% 0%;
offset-rotate: auto var(--rotation-offset, 0deg);
}
@keyframes hide-toolbar-arc-enter {
from {
offset-distance: var(--start-distance);
transform: scale(0.5);
opacity: 0;
}
to {
offset-distance: var(--target-offset-distance);
transform: scale(1);
opacity: 1;
}
}
@@ -1,12 +1,18 @@
'use client';
import { AnimatePresence, type MotionValue, motion, useReducedMotion } from 'motion/react';
import {
AnimatePresence,
type MotionValue,
motion,
useReducedMotion,
useSpring,
} from 'motion/react';
import React from 'react';
import { AnimatedLogo } from './AnimatedLogo';
import { tcls } from '@/lib/tailwind';
import { Icon, type IconName } from '@gitbook/icons';
import { Icon, type IconName, IconStyle } from '@gitbook/icons';
import { Tooltip } from '../primitives';
import { getCopyVariants, minifyButtonAnimation, toolbarEasings } from './transitions';
import { getCopyVariants, toolbarEasings } from './transitions';
import { useMagnificationEffect } from './useMagnificationEffect';
const DURATION_LOGO_APPEARANCE = 2000;
@@ -14,13 +20,12 @@ const DELAY_BETWEEN_LOGO_AND_CONTENT = 100;
interface ToolbarProps {
children: React.ReactNode;
label: React.ReactNode;
minified: boolean;
onMinifiedChange: (value: boolean) => void;
}
export function Toolbar(props: ToolbarProps) {
const { children, label } = props;
const [minified, setMinified] = React.useState(true);
const [showToolbarControls, setShowToolbarControls] = React.useState(false);
const { children, minified, onMinifiedChange } = props;
const [isReady, setIsReady] = React.useState(false);
// Wait for page to be ready, then show the toolbar
@@ -39,14 +44,16 @@ export function Toolbar(props: ToolbarProps) {
// After toolbar appears, wait then show the full content
React.useEffect(() => {
if (isReady) {
const expandAfterTimeout = setTimeout(() => {
setMinified(false);
}, DURATION_LOGO_APPEARANCE + DELAY_BETWEEN_LOGO_AND_CONTENT);
return () => clearTimeout(expandAfterTimeout);
if (!isReady) {
return;
}
}, [isReady]);
const expandAfterTimeout = setTimeout(() => {
onMinifiedChange(false);
}, DURATION_LOGO_APPEARANCE + DELAY_BETWEEN_LOGO_AND_CONTENT);
return () => clearTimeout(expandAfterTimeout);
}, [isReady, onMinifiedChange]);
// Don't render anything until page is ready
if (!isReady) {
@@ -54,65 +61,51 @@ export function Toolbar(props: ToolbarProps) {
}
return (
<Tooltip label={label}>
<motion.div
onMouseEnter={() => setShowToolbarControls(true)}
onMouseLeave={() => setShowToolbarControls(false)}
className="-translate-x-1/2 fixed bottom-5 left-1/2 z-40 w-auto max-w-xl transform px-4"
>
<AnimatePresence mode="wait">
<motion.div
onClick={() => {
if (minified) {
setMinified((prev) => !prev);
}
}}
layout
transition={toolbarEasings.spring}
className={tcls(
minified ? 'cursor-pointer px-2' : 'pr-2 pl-3.5',
'flex',
'items-center',
'justify-center',
'min-h-11',
'min-w-12',
'h-12',
'py-2',
'border-tint-1/3',
'backdrop-blur-sm',
'origin-center',
'bg-[linear-gradient(110deg,rgba(20,23,28,0.90)_0%,rgba(20,23,28,0.80)_100%)]',
'dark:bg-[linear-gradient(110deg,rgba(256,256,256,0.90)_0%,rgba(256,256,256,0.80)_100%)]'
)}
initial={{
scale: 1,
opacity: 1,
}}
animate={{
scale: 1,
opacity: 1,
boxShadow: minified
? '0 4px 40px 8px rgba(0, 0, 0, .2), 0 0 0 .5px rgba(0, 0, 0, .4), inset 0 .5px 0 0 hsla(0, 0%, 100%, .15)'
: '0 4px 40px 8px rgba(0, 0, 0, .4), 0 0 0 .5px rgba(0, 0, 0, .8), inset 0 .5px 0 0 hsla(0, 0%, 100%, .3)',
}}
style={{
borderRadius: '100px', // This is set on `style` so Framer Motion can correct for distortions
}}
>
{/* Logo with stroke segments animation in blue-tints */}
<motion.div layout>
<AnimatedLogo />
</motion.div>
{!minified ? children : null}
{!minified && showToolbarControls && (
<MinifyButton setMinified={setMinified} />
)}
<motion.div className="-translate-x-1/2 fixed bottom-5 left-1/2 z-40 w-auto max-w-xl transform px-4">
<AnimatePresence mode="wait">
<motion.div
onClick={() => {
if (minified) {
onMinifiedChange(false);
}
}}
layout
transition={toolbarEasings.spring}
className={tcls(
minified ? 'cursor-pointer px-2' : 'pr-2 pl-3.5',
'flex',
'items-center',
'justify-center',
'min-h-11',
'min-w-12',
'h-12',
'py-2',
'backdrop-blur-sm',
'origin-center',
'border-[0.5px] border-neutral-5 border-solid dark:border-neutral-8',
'bg-[linear-gradient(45deg,rgba(255,255,255,0)_0%,rgba(255,255,255,0.2)_100%)]'
)}
initial={{
scale: 1,
opacity: 1,
}}
animate={{
scale: 1,
opacity: 1,
}}
style={{
borderRadius: '100px', // This is set on `style` so Framer Motion can correct for distortions
}}
>
{/* Logo with stroke segments animation in blue-tints */}
<motion.div layout>
<AnimatedLogo />
</motion.div>
</AnimatePresence>
</motion.div>
</Tooltip>
{!minified ? children : null}
</motion.div>
</AnimatePresence>
</motion.div>
);
}
@@ -139,12 +132,15 @@ export function ToolbarButtonGroup(props: { children: React.ReactNode }) {
className="flex items-center gap-1 overflow-visible pr-2 pl-4"
>
{buttonChildren.map((child, index) => {
const motionValues = buttonMotionValues[index];
const childEl = child as React.ReactElement;
return React.cloneElement(childEl, {
key: index,
motionValues,
});
const childKey = childEl.key ?? `toolbar-button-${index}`;
return (
<ToolbarButtonWrapper
key={childKey}
child={childEl}
rawMotionValues={buttonMotionValues[index]}
/>
);
})}
</motion.div>
);
@@ -158,15 +154,27 @@ export interface ToolbarButtonProps extends Omit<React.HTMLProps<HTMLAnchorEleme
icon: IconName;
iconClassName?: string;
title?: React.ReactNode;
children?: React.ReactNode;
}
export function ToolbarButton(props: ToolbarButtonProps) {
const { title, disabled, motionValues, className, style, href, onClick, icon, iconClassName } =
props;
export const ToolbarButton = React.forwardRef<HTMLDivElement, ToolbarButtonProps>((props, ref) => {
const {
title,
disabled,
motionValues,
className,
style,
href,
onClick,
icon,
iconClassName,
children,
} = props;
const reduceMotion = useReducedMotion();
return (
<motion.div variants={toolbarEasings.staggeringChild}>
<motion.div variants={toolbarEasings.staggeringChild} className="relative" ref={ref}>
{children ? children : null}
<Tooltip label={title}>
<motion.a
href={href}
@@ -182,6 +190,9 @@ export function ToolbarButton(props: ToolbarButtonProps) {
transformOrigin: 'bottom center',
zIndex: motionValues?.scale ? 10 : 'auto',
...style,
background: 'linear-gradient(rgb(51, 53, 57), rgb(50, 52, 56))',
boxShadow: 'rgba(255, 255, 255, 0.15) 0px 1px 1px 0px inset',
border: '1px solid rgba(0, 0, 0, 0.06)',
}
}
transition={{
@@ -199,39 +210,75 @@ export function ToolbarButton(props: ToolbarButtonProps) {
'gap-1',
'text-sm',
'rounded-full',
'border-neutral-500',
'outline-neutral-800',
'outline-1',
'border',
'truncate',
'text-tint-1',
'dark:text-tint-12',
'cursor-pointer',
'transition-colors',
'size-8',
'bg-tint-1/3',
'hover:bg-tint-1/4',
'dark:bg-tint-3',
'dark:hover:bg-tint-1',
disabled ? 'cursor-not-allowed opacity-50' : '',
'shadow-1xs'
disabled ? 'cursor-not-allowed opacity-50' : ''
)}
>
<Icon icon={icon} className={tcls('size-4', iconClassName)} />
<Icon
icon={icon}
iconStyle={IconStyle.Solid}
className={tcls(
'size-4 shrink-0 group-hover:scale-110 group-hover:text-tint-3',
iconClassName
)}
/>
</motion.a>
</Tooltip>
</motion.div>
);
});
ToolbarButton.displayName = 'ToolbarButton';
function ToolbarButtonWrapper(props: {
child: React.ReactElement;
rawMotionValues?: { scale: MotionValue<number>; x: MotionValue<number> };
}) {
const { child, rawMotionValues } = props;
// Convert the raw motion values to smooth spring easings
const springScale = useSpring(rawMotionValues?.scale.get() ?? 1, {
stiffness: 400,
damping: 30,
});
const springX = useSpring(rawMotionValues?.x.get() ?? 0, { stiffness: 400, damping: 30 });
// Sync springs with raw motion values
React.useEffect(() => {
if (!rawMotionValues) return;
const unsubScale = rawMotionValues.scale.on('change', (v) => springScale.set(v));
const unsubX = rawMotionValues.x.on('change', (v) => springX.set(v));
return () => {
unsubScale();
unsubX();
};
}, [rawMotionValues, springScale, springX]);
const motionValues = {
scale: springScale,
x: springX,
};
return React.cloneElement(child, {
motionValues,
});
}
export function ToolbarSeparator() {
return <div className="h-5 w-px bg-tint-1/3" />;
}
export function ToolbarTitle(props: { prefix: string; suffix: string }) {
export function ToolbarTitle(props: { prefix?: string; suffix: string }) {
return (
<div className="flex items-center gap-1 text-xs ">
<ToolbarTitlePrefix title={props.prefix} />
{props.prefix ? <ToolbarTitlePrefix title={props.prefix} /> : null}
<ToolbarTitleSuffix title={props.suffix} />
</div>
);
@@ -239,10 +286,7 @@ export function ToolbarTitle(props: { prefix: string; suffix: string }) {
function ToolbarTitlePrefix(props: { title: string }) {
return (
<motion.span
{...getCopyVariants(0)}
className="font-light text-neutral-7 dark:text-neutral-3"
>
<motion.span {...getCopyVariants(0)} className="truncate font-medium text-neutral-12">
{props.title}
</motion.span>
);
@@ -250,10 +294,7 @@ function ToolbarTitlePrefix(props: { title: string }) {
function ToolbarTitleSuffix(props: { title: string }) {
return (
<motion.span
{...getCopyVariants(1)}
className="max-w-[24ch] truncate font-semibold text-neutral-3 dark:text-neutral-2"
>
<motion.span {...getCopyVariants(1)} className="max-w-[20ch] truncate text-neutral-12">
{props.title}
</motion.span>
);
@@ -261,38 +302,8 @@ function ToolbarTitleSuffix(props: { title: string }) {
export function ToolbarSubtitle(props: { subtitle: React.ReactNode }) {
return (
<motion.span
{...getCopyVariants(1)}
className="text-neutral-7 text-xxs dark:text-neutral-2"
>
<motion.span {...getCopyVariants(1)} className="text-neutral-12/90 text-xxs">
{props.subtitle}
</motion.span>
);
}
function MinifyButton(props: { setMinified: (minified: boolean) => void }) {
return (
<Tooltip label="Minify">
<motion.div
{...minifyButtonAnimation}
transition={{
duration: 0.2,
}}
whileHover={{
scale: 1.05,
}}
onClick={(e) => {
e.stopPropagation();
props.setMinified(true);
}}
className={tcls(
'-top-2 -right-4 absolute flex size-4 cursor-pointer items-center justify-center rounded-full border',
'border-neutral-500 bg-neutral-700 hover:border-neutral-400 hover:bg-neutral-600',
'dark:border-neutral-400 dark:bg-neutral-200 dark:hover:border-neutral-200 dark:hover:bg-neutral-100'
)}
>
<Icon icon="minus" className="size-2 text-neutral-1 dark:text-neutral-9" />
</motion.div>
</Tooltip>
);
}
@@ -0,0 +1,21 @@
'use client';
import React from 'react';
export interface ToolbarControlsContextValue {
minimize: () => void;
closeSession?: () => void;
closePersistent?: () => void;
}
const ToolbarControlsContext = React.createContext<ToolbarControlsContextValue | null>(null);
export function ToolbarControlsProvider(
props: React.PropsWithChildren<{ value: ToolbarControlsContextValue | null }>
) {
const { children, value } = props;
return <ToolbarControlsContext.Provider value={value}>{children}</ToolbarControlsContext.Provider>;
}
export function useToolbarControls() {
return React.useContext(ToolbarControlsContext);
}
@@ -54,4 +54,7 @@ export type AdminToolbarContext = {
export interface AdminToolbarClientProps {
context: AdminToolbarContext;
onSessionClose?: () => void;
onPersistentClose?: () => void;
onToggleMinify?: () => void;
}
@@ -1,11 +1,6 @@
import { type MotionValue, motionValue } from 'framer-motion';
import { type MotionValue, motionValue } from 'motion/react';
import React from 'react';
interface ButtonMotionValues {
scale: MotionValue<number>;
x: MotionValue<number>;
}
interface MagnificationConfig {
/** Size of each button in pixels - used for spacing calculations */
buttonSize?: number;
@@ -30,14 +25,9 @@ const defaultConfig: Required<MagnificationConfig> = {
padding: 10, // Small buffer zone around container edges
};
// Helper functions for cleaner code
const createMotionValues = (count: number): ButtonMotionValues[] =>
Array.from({ length: count }, () => ({
scale: motionValue(1),
x: motionValue(0),
}));
const resetMotionValues = (motionValues: ButtonMotionValues[]) => {
const resetMotionValues = (
motionValues: Array<{ scale: MotionValue<number>; x: MotionValue<number> }>
) => {
motionValues.forEach(({ scale, x }) => {
scale.set(1);
x.set(0);
@@ -62,23 +52,18 @@ const captureButtonPositions = (buttons: HTMLElement[]) => {
const calculateScale = (
mouseX: number,
mouseY: number,
buttonCenterX: number,
buttonCenterY: number,
containerRect: DOMRect,
config: Required<MagnificationConfig>
) => {
// Calculate 2D distance from mouse to button center
const deltaX = mouseX - buttonCenterX;
const deltaY = mouseY - buttonCenterY;
const distance = Math.sqrt(deltaX * deltaX + deltaY * deltaY);
// Calculate only X-axis distance from mouse to button center
const distance = Math.abs(mouseX - buttonCenterX);
if (distance > config.influenceRadius) return 1;
// Calculate distance from container edge
// Calculate distance from container edge (X-axis only)
const distanceFromEdgeX = Math.min(mouseX - containerRect.left, containerRect.right - mouseX);
const distanceFromEdgeY = Math.min(mouseY - containerRect.top, containerRect.bottom - mouseY);
const distanceFromEdge = Math.min(distanceFromEdgeX, distanceFromEdgeY);
const distanceFromEdge = distanceFromEdgeX;
// Define the "heart" zone - 8px from center (16x16px total area)
const heartZoneRadius = 8;
@@ -155,13 +140,20 @@ export function useMagnificationEffect(props: {
config?: MagnificationConfig;
}) {
const { childrenCount, containerRef, config } = props;
const [buttonMotionValues, setButtonMotionValues] = React.useState<ButtonMotionValues[]>([]);
const originalPositionsRef = React.useRef<
Array<{ left: number; width: number; top: number; height: number }>
>([]);
const finalConfig = React.useMemo(() => ({ ...defaultConfig, ...config }), [config]);
// Create basic motion values that will be consumed by springs in the components
const buttonMotionValues = React.useMemo(() => {
return Array.from({ length: childrenCount }, () => ({
scale: motionValue(1),
x: motionValue(0),
}));
}, [childrenCount]);
React.useEffect(() => {
const container = containerRef.current;
if (!container) return;
@@ -175,11 +167,6 @@ export function useMagnificationEffect(props: {
return;
}
// Initialize motion values if button count changed
if (buttonMotionValues.length !== buttons.length) {
setButtonMotionValues(createMotionValues(buttons.length));
}
const handleMouseMove = (event: MouseEvent) => {
const buttons = Array.from(
container.querySelectorAll('.toolbar-button')
@@ -211,15 +198,7 @@ export function useMagnificationEffect(props: {
if (!pos) return { scale: 1, translateX: 0 };
const buttonCenterX = pos.left + pos.width / 2;
const buttonCenterY = pos.top + pos.height / 2;
const scale = calculateScale(
mouseX,
mouseY,
buttonCenterX,
buttonCenterY,
containerRect,
finalConfig
);
const scale = calculateScale(mouseX, buttonCenterX, containerRect, finalConfig);
return { scale, translateX: 0 };
});
@@ -233,7 +212,7 @@ export function useMagnificationEffect(props: {
);
});
// Update motion values
// Update motion values - springs in components will animate to these values
buttonEffects.forEach((effect, index) => {
const motionValue = buttonMotionValues[index];
if (motionValue) {