Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/toc-link-active-highlight.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"gitbook": patch
---

Highlight a table-of-contents link entry as active when it points to the page you are currently viewing.
11 changes: 10 additions & 1 deletion packages/gitbook/src/components/TableOfContents/PageLinkItem.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,27 @@ import { Link } from '@/components/primitives';
import { tcls } from '@/lib/tailwind';

import { SiteInsightsLinkPosition } from '@gitbook/api';
import { useCurrentPagePath } from '../hooks';
import { TOCPageIcon } from './TOCPageIcon';

export function PageLinkItem(props: { page: ClientTOCPageLink }) {
const { page } = props;

const isExternal = page.target.kind === 'url';

const currentPagePath = useCurrentPagePath();
const isActive = page.pathnames?.some((pathname) => pathname === currentPagePath) ?? false;

return (
<li className="page-link-item flex flex-col [.page-group-item+&]:mt-4">
<Link
href={page.href ?? '#'}
classNames={['ToCLinkItemStyles']}
data-active={isActive}
aria-current={isActive ? 'page' : undefined}
classNames={[
'ToCLinkItemStyles',
...(isActive ? ['ToCLinkItemActiveStyles' as const] : []),
]}
insights={{
type: 'link_click',
link: {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ export type ClientTOCPageLink = {
emoji?: string;
icon?: string;
target: ContentRef;
/** Paths of the page this link points to, when it resolves to a page in the current space. */
pathnames?: string[];
};

export type ClientTOCPageDocument = {
Expand Down Expand Up @@ -93,6 +95,15 @@ export async function encodeClientTableOfContents(
}
case 'link': {
const resolved = await resolveContentRef(page.target, context);
// Highlight the link when it points to a page in the current space, matching how
// page entries compute their active state. Restricted to page targets (no anchors,
// no cross-space refs) to avoid over-highlighting.
const pathnames =
page.target.kind === 'page' &&
resolved?.page &&
resolved.space?.id === context.space.id
? getPagePaths(rootPages, resolved.page)
: undefined;
result.push(
removeUndefined({
id: page.id,
Expand All @@ -101,6 +112,7 @@ export async function encodeClientTableOfContents(
emoji: page.emoji,
icon: page.icon,
target: page.target,
pathnames,
type: 'link',
})
);
Expand Down
Loading