UI: Support linking to a specific tab

This commit is contained in:
fuma-nama
2024-10-11 10:56:14 +08:00
parent d445cf38e8
commit 3d054a81b8
15 changed files with 180 additions and 77 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'fumadocs-ui': minor
---
Support linking to a specific tab
+7 -2
View File
@@ -80,10 +80,15 @@ export const baseOptions: BaseLayoutProps = {
},
links: [
{
type: 'menu',
icon: <BookIcon />,
text: 'Documentation',
url: '/docs/ui',
active: 'none',
items: [
{
text: 'Getting Started',
url: '/docs/ui',
},
],
},
...linkItems,
],
@@ -56,6 +56,28 @@ Set a default value by passing `defaultIndex`.
</Tabs>
```
### Link to Tab
You can use HTML `id` attribute to link to a specific tab.
```mdx
<Tabs items={['Javascript', 'Rust', 'C++']}>
<Tab value="Javascript">Javascript is weird</Tab>
<Tab value="Rust">Rust is fast</Tab>
<Tab id="tab-cpp" value="C++">
`Hello World`
</Tab>
</Tabs>
```
<Tabs items={['Javascript', 'Rust', 'C++']}>
<Tab value="Javascript">Javascript is weird</Tab>
<Tab value="Rust">Rust is fast</Tab>
<Tab id="tab-cpp" value="C++">
`Hello World`
</Tab>
</Tabs>
### Advanced
You can use the styled Radix UI primitive directly from exported `Primitive`.
+1 -5
View File
@@ -14,6 +14,7 @@ const config = {
// Replaced by root workspace command
ignoreDuringBuilds: true,
},
serverExternalPackages: ['ts-morph', 'typescript'],
images: {
unoptimized: true,
remotePatterns: [
@@ -24,11 +25,6 @@ const config = {
},
],
},
webpack: (config) => {
config.module.noParse = [/typescript\/lib\/typescript.js/];
return config;
},
};
const withMDX = createMDX();
+1
View File
@@ -67,6 +67,7 @@
"@radix-ui/react-collapsible": "^1.1.1",
"@radix-ui/react-dialog": "^1.1.2",
"@radix-ui/react-direction": "^1.1.0",
"@radix-ui/react-navigation-menu": "^1.2.1",
"@radix-ui/react-popover": "^1.1.2",
"@radix-ui/react-scroll-area": "^1.2.0",
"@radix-ui/react-tabs": "^1.1.1",
@@ -76,10 +76,15 @@ export function DynamicSidebar(props: SidebarProps): React.ReactElement {
onPointerEnter: onEnter,
onPointerLeave: onLeave,
'aria-hidden': Boolean(collapsed && !hover),
style: {
// the offset given to docs content when the sidebar is collapsed
'--fd-content-offset':
'max(calc(var(--fd-c-sidebar) - 2 * var(--fd-sidebar-width)), var(--fd-sidebar-width) * -1)',
} as object,
className: cn(
'md:transition-[transform,padding,width,margin]',
collapsed && [
'md:me-fd-sidebar-offset md:w-[var(--fd-sidebar-width)] md:rounded-xl md:border md:ps-0 md:shadow-md',
'md:me-[var(--fd-content-offset)] md:w-[var(--fd-sidebar-width)] md:rounded-xl md:border md:ps-0 md:shadow-md',
hover
? 'md:translate-x-1 rtl:md:-translate-x-1'
: 'md:translate-x-[calc(var(--fd-sidebar-width)*-1)] rtl:md:translate-x-[var(--fd-sidebar-width)]',
+28 -20
View File
@@ -2,7 +2,7 @@ import Link from 'fumadocs-core/link';
import { ChevronDown } from 'lucide-react';
import { usePathname } from 'next/navigation';
import { cva } from 'class-variance-authority';
import { HTMLAttributes, type ReactNode, useState } from 'react';
import { type HTMLAttributes, type ReactNode, useState } from 'react';
import { useOnChange } from 'fumadocs-core/utils/use-on-change';
import { cn } from '@/utils/cn';
import { isActive } from '@/utils/shared';
@@ -101,20 +101,25 @@ export type LinkItemType =
| CustomItem;
interface LinkItemProps extends React.HTMLAttributes<HTMLElement> {
key?: string | number;
item: LinkItemType;
}
export function MenuItem({ item, ...props }: LinkItemProps): React.ReactNode {
export function renderMenuItem({
key,
item,
...props
}: LinkItemProps): ReactNode {
if (item.type === 'custom')
return (
<div {...props} className={cn('grid', props.className)}>
<div key={key} {...props} className={cn('grid', props.className)}>
{item.children}
</div>
);
if (item.type === 'menu') {
return (
<Collapsible className="flex flex-col">
<Collapsible key={key} className="flex flex-col">
<CollapsibleTrigger
{...props}
className={cn(itemVariants(), props.className, 'group/link')}
@@ -125,9 +130,9 @@ export function MenuItem({ item, ...props }: LinkItemProps): React.ReactNode {
</CollapsibleTrigger>
<CollapsibleContent>
<div className="ms-2 flex flex-col border-s py-2 ps-2">
{item.items.map((child, i) => (
<MenuItem key={i} item={child} />
))}
{item.items.map((child, i) =>
renderMenuItem({ key: i, item: child }),
)}
</div>
</CollapsibleContent>
</Collapsible>
@@ -135,11 +140,12 @@ export function MenuItem({ item, ...props }: LinkItemProps): React.ReactNode {
}
if (item.type === 'button') {
return <ButtonItem item={item} {...props} />;
return <ButtonItem key={key} item={item} {...props} />;
}
return (
<BaseLinkItem
key={key}
item={item}
{...props}
className={cn(itemVariants(), props.className)}
@@ -150,10 +156,14 @@ export function MenuItem({ item, ...props }: LinkItemProps): React.ReactNode {
);
}
export function NavItem({ item, ...props }: LinkItemProps): React.ReactNode {
export function renderNavItem({
key,
item,
...props
}: LinkItemProps): ReactNode {
if (item.type === 'custom')
return (
<div {...props} className={cn('grid', props.className)}>
<div key={key} {...props} className={cn('grid', props.className)}>
{item.children}
</div>
);
@@ -161,13 +171,13 @@ export function NavItem({ item, ...props }: LinkItemProps): React.ReactNode {
if (item.type === 'menu') {
return (
<LinksMenu
items={item.items.map((child, i) => (
<MenuItem key={i} item={child} />
))}
key={key}
items={item.items.map((child, i) =>
renderMenuItem({ key: i, item: child }),
)}
{...props}
className={cn(navItemVariants(), props.className)}
>
{item.icon}
{item.text}
<ChevronDown className="ms-auto !size-3.5" />
</LinksMenu>
@@ -175,15 +185,16 @@ export function NavItem({ item, ...props }: LinkItemProps): React.ReactNode {
}
if (item.type === 'button') {
return <ButtonItem item={item} {...props} />;
return <ButtonItem key={key} item={item} {...props} />;
}
if (item.type === 'icon') {
return <IconItem item={item} {...props} />;
return <IconItem key={key} item={item} {...props} />;
}
return (
<BaseLinkItem
key={key}
item={item}
{...props}
className={cn(navItemVariants(), props.className)}
@@ -263,10 +274,7 @@ interface LinksMenuProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
items?: ReactNode;
}
export function LinksMenu({
items,
...props
}: LinksMenuProps): React.ReactElement {
export function LinksMenu({ items, ...props }: LinksMenuProps): ReactNode {
const [open, setOpen] = useState(false);
const pathname = usePathname();
@@ -16,7 +16,10 @@ import { cn } from '@/utils/cn';
import { useTreeContext } from '@/contexts/tree';
import { ScrollArea, ScrollViewport } from '@/components/ui/scroll-area';
import { hasActive, isActive } from '@/utils/shared';
import { type LinkItemType, MenuItem } from '@/components/layout/link-item';
import {
type LinkItemType,
renderMenuItem,
} from '@/components/layout/link-item';
import { LargeSearchToggle } from '@/components/layout/search-toggle';
import { useSearchContext } from '@/contexts/search';
import { itemVariants } from '@/components/layout/variants';
@@ -145,9 +148,7 @@ export function Sidebar({
<ViewportContent>
{items.length > 0 ? (
<div className="flex flex-col px-4 pt-6 md:hidden">
{items.map((item, i) => (
<MenuItem key={i} item={item} />
))}
{items.map((item, i) => renderMenuItem({ key: i, item }))}
</div>
) : null}
</ViewportContent>
+3 -1
View File
@@ -40,9 +40,11 @@ export function Toc({ header, footer, children }: TOCProps): ReactElement {
return (
<div
data-toc=""
className="sticky top-fd-layout-top flex h-fd-toc-height w-[var(--fd-c-toc)] min-w-[var(--fd-toc-width)] flex-col gap-3 pb-2 pe-[var(--fd-toc-offset)] pt-12 max-lg:hidden"
className="sticky top-fd-layout-top flex h-[var(--fd-toc-height)] w-[var(--fd-c-toc)] min-w-[var(--fd-toc-width)] flex-col gap-3 pb-2 pe-[var(--fd-toc-offset)] pt-12 max-lg:hidden"
style={
{
'--fd-toc-height':
'calc(100dvh - var(--fd-banner-height) - var(--fd-nav-height))',
'--fd-toc-offset':
'max(calc(var(--fd-c-toc) - var(--fd-toc-width)), 0.75rem)',
} as object
+36 -15
View File
@@ -4,7 +4,15 @@ import type {
TabsContentProps,
TabsProps as BaseProps,
} from '@radix-ui/react-tabs';
import { useMemo, useState, useCallback, useLayoutEffect } from 'react';
import {
useMemo,
useState,
useCallback,
createContext,
useContext,
useRef,
useLayoutEffect,
} from 'react';
import { cn } from '@/utils/cn';
import * as Primitive from './ui/tabs';
@@ -27,15 +35,6 @@ function removeChangeListener(id: string, listener: ChangeListener): void {
);
}
function update(id: string, v: string, persist: boolean): void {
listeners.get(id)?.forEach((item) => {
item(v);
});
if (persist) localStorage.setItem(id, v);
else sessionStorage.setItem(id, v);
}
export interface TabsProps extends BaseProps {
/**
* Identifier for Sharing value of tabs
@@ -54,6 +53,8 @@ export interface TabsProps extends BaseProps {
items?: string[];
}
const ValueChangeContext = createContext<(v: string) => void>(() => undefined);
export function Tabs({
groupId,
items = [],
@@ -63,12 +64,14 @@ export function Tabs({
}: TabsProps): React.ReactElement {
const values = useMemo(() => items.map((item) => toValue(item)), [items]);
const [value, setValue] = useState(values[defaultIndex]);
const valuesRef = useRef(values);
valuesRef.current = values;
useLayoutEffect(() => {
if (!groupId) return;
const onUpdate: ChangeListener = (v) => {
if (values.includes(v)) setValue(v);
if (valuesRef.current.includes(v)) setValue(v);
};
const previous = persist
@@ -80,12 +83,17 @@ export function Tabs({
return () => {
removeChangeListener(groupId, onUpdate);
};
}, [groupId, persist, values]);
}, [groupId, persist]);
const onValueChange = useCallback(
(v: string) => {
if (groupId) {
update(groupId, v, persist);
listeners.get(groupId)?.forEach((item) => {
item(v);
});
if (persist) localStorage.setItem(groupId, v);
else sessionStorage.setItem(groupId, v);
} else {
setValue(v);
}
@@ -107,7 +115,9 @@ export function Tabs({
</Primitive.TabsTrigger>
))}
</Primitive.TabsList>
{props.children}
<ValueChangeContext.Provider value={onValueChange}>
{props.children}
</ValueChangeContext.Provider>
</Primitive.Tabs>
);
}
@@ -121,9 +131,20 @@ export function Tab({
className,
...props
}: TabsContentProps): React.ReactElement {
const v = toValue(value);
const onValueChange = useContext(ValueChangeContext);
useLayoutEffect(() => {
const hash = window.location.hash.slice(1);
if (hash === props.id) {
onValueChange(v);
}
}, [onValueChange, props.id, v]);
return (
<Primitive.TabsContent
value={toValue(value)}
value={v}
className={cn(
'prose-no-margin [&>figure:only-child]:-m-4 [&>figure:only-child]:rounded-none [&>figure:only-child]:border-none',
className,
+2 -2
View File
@@ -82,9 +82,9 @@ export function SidebarCollapseTrigger(
export {
LinksMenu,
NavItem,
renderNavItem,
IconItem,
MenuItem,
renderMenuItem,
} from '@/components/layout/link-item';
export { NavProvider } from '@/components/layout/nav';
export { RootToggle } from '@/components/layout/root-toggle';
+3 -2
View File
@@ -24,7 +24,7 @@ declare const {
DynamicSidebar,
Sidebar,
IconItem,
MenuItem,
renderMenuItem,
NavProvider,
}: typeof import('./docs.client');
@@ -61,6 +61,7 @@ export function DocsLayout({
i18n = false,
...props
}: DocsLayoutProps): React.ReactNode {
const MenuItem = renderMenuItem;
const links = getLinks(props.links ?? [], props.githubUrl);
const Aside = collapsible ? DynamicSidebar : Sidebar;
@@ -79,7 +80,7 @@ export function DocsLayout({
>
{nav.title}
</Link>,
nav.children,
<Fragment key="children">{nav.children}</Fragment>,
);
if (links.length > 0)
+23 -15
View File
@@ -4,10 +4,10 @@ import { ChevronDown, Languages, MoreVertical } from 'lucide-react';
import { useContext, useMemo } from 'react';
import { useSearchContext } from '@/contexts/search';
import {
NavItem,
renderNavItem,
type LinkItemType,
LinksMenu,
MenuItem,
renderMenuItem,
} from '@/components/layout/link-item';
import {
LargeSearchToggle,
@@ -57,9 +57,13 @@ export function Nav({
{props.children}
{navItems
.filter((item) => !isSecondary(item))
.map((item, i) => (
<NavItem key={i} item={item} className="text-sm max-sm:hidden" />
))}
.map((item, i) =>
renderNavItem({
key: i,
item,
className: 'text-sm max-sm:hidden',
}),
)}
<div className="flex flex-1 flex-row items-center justify-end">
{enableSearch && search.enabled ? (
<>
@@ -76,20 +80,24 @@ export function Nav({
</LanguageToggle>
) : null}
{navItems.filter(isSecondary).map((item, i) => (
<NavItem key={i} item={item} className="max-lg:hidden" />
))}
{navItems.filter(isSecondary).map((item, i) =>
renderNavItem({
key: i,
item,
className: 'max-lg:hidden',
}),
)}
<LinksMenu
items={
<>
{menuItems.map((item, i) => (
<MenuItem
key={i}
item={item}
className={cn(!isSecondary(item) && 'sm:hidden')}
/>
))}
{menuItems.map((item, i) =>
renderMenuItem({
key: i,
item,
className: cn(!isSecondary(item) && 'sm:hidden'),
}),
)}
<div className="flex flex-row items-center gap-1.5 px-2 pt-1.5 empty:hidden">
{props.i18n ? (
<LanguageToggle className="-ms-1.5">
-10
View File
@@ -271,22 +271,12 @@ export const docsUi = plugin.withOptions<DocsUIOptions>(
}
: undefined,
maxWidth: {
container: '1400px',
'fd-container': '1400px',
},
height: {
'fd-toc-height':
'calc(100dvh - var(--fd-banner-height) - var(--fd-nav-height))',
},
spacing: {
'fd-layout-top':
'calc(var(--fd-banner-height) + var(--fd-nav-height))',
},
margin: {
// the offset given to docs content when the sidebar is collapsed
'fd-sidebar-offset':
'max(calc(var(--fd-c-sidebar) - 2 * var(--fd-sidebar-width)), var(--fd-sidebar-width) * -1)',
},
colors: createTailwindColors(cssPrefix, addGlobalColors),
...animations,
},
+38
View File
@@ -1078,6 +1078,9 @@ importers:
'@radix-ui/react-direction':
specifier: ^1.1.0
version: 1.1.0(@types/[email protected])([email protected])
'@radix-ui/react-navigation-menu':
specifier: ^1.2.1
version: 1.2.1(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-popover':
specifier: ^1.1.2
version: 1.1.2(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
@@ -2519,6 +2522,19 @@ packages:
'@types/react':
optional: true
'@radix-ui/[email protected]':
resolution: {integrity: sha512-egDo0yJD2IK8L17gC82vptkvW1jLeni1VuqCyzY727dSJdk5cDjINomouLoNk8RVF7g2aNIfENKWL4UzeU9c8Q==}
peerDependencies:
'@types/react': '*'
'@types/react-dom': '*'
react: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
react-dom: ^16.8 || ^17.0 || ^18.0 || ^19.0 || ^19.0.0-rc
peerDependenciesMeta:
'@types/react':
optional: true
'@types/react-dom':
optional: true
'@radix-ui/[email protected]':
resolution: {integrity: sha512-u2HRUyWW+lOiA2g0Le0tMmT55FGOEWHwPFt1EPfbLly7uXQExFo5duNKqG2DzmFXIdqOeNd+TpE8baHWJCyP9w==}
peerDependencies:
@@ -8749,6 +8765,28 @@ snapshots:
optionalDependencies:
'@types/react': 18.3.11
'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':
dependencies:
'@radix-ui/primitive': 1.1.0
'@radix-ui/react-collection': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-compose-refs': 1.1.0(@types/[email protected])([email protected])
'@radix-ui/react-context': 1.1.1(@types/[email protected])([email protected])
'@radix-ui/react-direction': 1.1.0(@types/[email protected])([email protected])
'@radix-ui/react-dismissable-layer': 1.1.1(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-id': 1.1.0(@types/[email protected])([email protected])
'@radix-ui/react-presence': 1.1.1(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-primitive': 2.0.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
'@radix-ui/react-use-callback-ref': 1.1.0(@types/[email protected])([email protected])
'@radix-ui/react-use-controllable-state': 1.1.0(@types/[email protected])([email protected])
'@radix-ui/react-use-layout-effect': 1.1.0(@types/[email protected])([email protected])
'@radix-ui/react-use-previous': 1.1.0(@types/[email protected])([email protected])
'@radix-ui/react-visually-hidden': 1.1.0(@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])
react: 18.3.1
react-dom: 18.3.1([email protected])
optionalDependencies:
'@types/react': 18.3.11
'@types/react-dom': 18.3.0
'@radix-ui/[email protected](@types/[email protected])(@types/[email protected])([email protected]([email protected]))([email protected])':
dependencies:
'@radix-ui/primitive': 1.1.0