Compare commits

...

3 Commits

Author SHA1 Message Date
taranvohra 3b1d083554 changeset 2026-11-01 21:17:45 +05:30
taranvohra fd6a22a0b3 Pack expandable styles into CSS classes
An expandable carried around 750 characters of classes across its
details, summary, chevron and anchor, repeated for every one on a page.
They now live in `Expandable.css`. `group/expandable` stays a literal
class, since the children's hover and open styles match it by name.
2026-11-01 21:17:28 +05:30
taranvohra 5fb928a149 Define a page's repeated icons once in an SVG sprite
Every icon inlined its full SVG path, so a page repeated the same markup
at each heading anchor, expandable chevron and embed placeholder: on a
page with 700 headings the anchor icon alone came to almost half a
megabyte. The page's icon provider now draws its sources once in a hidden
sprite, and icons reference them with `<use>`. Those sources are the
document's own icons plus the ones its blocks repeat once per instance.

The embed placeholder's spinner was not an inline source, so it rendered
as a six-element mask over a remote image; it now references the sprite
too.
2026-11-01 21:17:28 +05:30
11 changed files with 248 additions and 86 deletions
@@ -0,0 +1,6 @@
---
"@gitbook/icons": minor
"gitbook": patch
---
Define a page's repeated icons once in an SVG sprite that each icon references, instead of repeating the full SVG at every heading anchor, expandable and embed placeholder, and pack the class lists every expandable repeats into shared CSS classes.
@@ -50,27 +50,8 @@ export function Details(props: {
id={id}
data-block-key={props.commentKey}
open={props.open || openFromHash}
className={tcls(
className,
'group/expandable',
'bg-tint-base',
'border',
'border-b-0',
'border-tint-subtle',
//all
'mt-0!',
'mb-0',
//select first child
'first:mt-5!',
'first:rounded-t-lg',
//select first in group
'[:not(&)_+_&]:mt-5!',
'[:not(&)_+_&]:rounded-t-lg',
//select last in group
'[&:not(:has(+_&))]:mb-5',
'[&:not(:has(+_&))]:rounded-b-lg',
'[&:not(:has(+_&))]:border-b'
)}
// Styles live on `.expandable` in `Expandable.css`; the group name is matched literally.
className={tcls(className, 'expandable', 'group/expandable')}
>
{children}
</details>
@@ -0,0 +1,43 @@
@reference "../../RootLayout/globals.css";
/* This file can be the first stylesheet a route loads, and layer order follows first
appearance. Without this, `components` would be created here and Tailwind's `base`
only later, letting preflight's `padding: 0` and `border: 0` win over the rules below. */
@layer theme, base, components, utilities;
/* A page can stack a hundred expandables, so their styles live here rather than in each one's
class attributes. They sit in `components` so the utilities passed as props still override. */
@layer components {
/* Consecutive expandables join into one bordered group: only the first of a run gets the top
margin and corners, and only the last the bottom border, margin and corners. */
.expandable {
@apply scroll-mt-(--content-scroll-margin) border border-b-0 border-tint-subtle bg-tint-base;
@apply mt-0! mb-0 first:mt-5! first:rounded-t-lg;
@apply [:not(&)_+_&]:mt-5! [:not(&)_+_&]:rounded-t-lg;
@apply [&:not(:has(+_&))]:mb-5 [&:not(:has(+_&))]:rounded-b-lg [&:not(:has(+_&))]:border-b;
}
.expandable-summary {
@apply relative cursor-pointer list-none select-none p-4 text-tint transition-colors;
@apply group-hover/expandable:text-tint-strong group-open/expandable:text-tint-strong;
@apply [&::-webkit-details-marker]:hidden;
}
/* Room for the anchor icon pinned to the right edge. */
.expandable-summary-anchored {
@apply pr-10;
}
.expandable-chevron {
@apply mr-3 mb-1 inline-block group-open/expandable:rotate-90;
}
.expandable-anchor {
@apply absolute top-2 right-4 bottom-2 flex items-center dark:shadow-none dark:ring-0;
}
.expandable-anchor-icon {
@apply inline-block size-3 text-transparent transition-colors;
@apply group-hover/expandable:text-tint-subtle contrast-more:group-hover/expandable:text-tint-strong;
}
}
@@ -7,6 +7,7 @@ import { shouldShowHashLinks } from '../HashLinkButton';
import { Inlines } from '../Inlines';
import { getCommentAnchorProps, getCommentKeyProp } from '../utils';
import { Details } from './Details';
import './Expandable.css';
import { ToggleChevron } from '@/components/primitives';
import { getSpaceLanguage, tString } from '@/intl/server';
import { defaultLanguage } from '@/intl/translations';
@@ -40,37 +41,19 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
id={id}
{...getCommentKeyProp(context, block.key)}
open={context.mode === 'print' || isDefaultExpanded}
className={tcls('scroll-mt-(--content-scroll-margin)', style)}
className={style}
>
<summary
{...getCommentAnchorProps(context, titleParagraph.key)}
className={tcls(
'cursor-pointer',
'px-4',
// Reserve room for the anchor icon pinned to the right edge
showHashLink && 'pr-10',
'py-4',
'relative',
'list-none',
'select-none',
'transition-colors',
'text-tint',
'group-hover/expandable:text-tint-strong',
'group-open/expandable:text-tint-strong',
'[&::-webkit-details-marker]:hidden'
'expandable-summary',
showHashLink && 'expandable-summary-anchored'
)}
>
<ToggleChevron
orientation="right-to-down"
open={context.mode === 'print'}
className={tcls(
'inline-block',
'size-3',
'mr-3',
'mb-1',
'shrink-0',
'group-open/expandable:rotate-90'
)}
className="expandable-chevron"
/>
<Inlines
nodes={titleParagraph.nodes}
@@ -82,28 +65,9 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
<a
href={`#${id}`}
aria-label={tString(language, 'direct_link_to_heading')}
className={tcls(
'absolute',
'top-2',
'bottom-2',
'right-4',
'flex',
'items-center',
'dark:shadow-none',
'dark:ring-0'
)}
className="expandable-anchor"
>
<Icon
icon="hashtag"
className={tcls(
'inline-block',
'size-3',
'transition-colors',
'text-transparent',
'group-hover/expandable:text-tint-subtle',
'contrast-more:group-hover/expandable:text-tint-strong'
)}
/>
<Icon icon="hashtag" className="expandable-anchor-icon" />
</a>
) : null}
</summary>
@@ -140,7 +140,7 @@ export async function SitePage(props: SitePageProps & { staticRoute: boolean })
);
return (
<IconsProvider iconSources={iconSources}>
<IconsProvider iconSources={iconSources} sprite>
<PageContextProvider pageId={page.id} spaceId={context.space.id} title={page.title}>
{filterableTagSlugs.length > 0 ? (
<UpdatesFilterProvider tagSlugs={filterableTagSlugs}>
@@ -132,6 +132,27 @@ describe('getContentInlineIconSourceRequests', () => {
]);
});
it('collects the icons that blocks repeat once per instance', () => {
const document = {
object: 'document',
nodes: [
{ object: 'block', type: 'heading-2', nodes: [] },
{ object: 'block', type: 'expandable', nodes: [] },
{ object: 'block', type: 'integration', nodes: [] },
{ object: 'block', type: 'paragraph', nodes: [] },
],
} as unknown as JSONDocument;
expect(
getContentInlineIconSourceRequests({ iconStyle: IconStyle.Regular, document })
).toEqual([
{ icon: 'hashtag', iconStyle: IconStyle.Regular },
{ icon: 'hashtag', iconStyle: IconStyle.Regular },
{ icon: 'chevron-right', iconStyle: IconStyle.Regular },
{ icon: 'spinner', iconStyle: IconStyle.Regular },
]);
});
it('ignores invalid, missing, and non-string icon values', () => {
const pages = [
{ icon: 'not-a-real-icon' },
+17
View File
@@ -138,6 +138,17 @@ const customIconSourceRequests = [
'vscode',
] satisfies IconName[];
/**
* Icons a block renders once per instance, so a document with many such blocks repeats them.
*/
const blockIconSourceRequests: Partial<Record<string, IconName[]>> = {
'heading-1': ['hashtag'],
'heading-2': ['hashtag'],
'heading-3': ['hashtag'],
expandable: ['hashtag', 'chevron-right'],
integration: ['spinner'],
};
const explicitStyleIconSourceRequests = [
{ icon: 'check', iconStyle: IconStyle.Solid },
{ icon: 'chevron-right', iconStyle: IconStyle.Solid },
@@ -380,6 +391,12 @@ function collectDocumentIconSourceRequests(
}
}
if (record.object === 'block' && typeof record.type === 'string') {
for (const icon of blockIconSourceRequests[record.type] ?? []) {
addIconSourceRequest(requests, icon, iconStyle);
}
}
for (const value of Object.values(record)) {
if (Array.isArray(value)) {
for (const item of value) {
@@ -0,0 +1,57 @@
import { describe, expect, it } from 'bun:test';
import { renderToStaticMarkup } from 'react-dom/server';
import { Icon, IconStyle, IconsProvider } from '@gitbook/icons';
const hashtag = { viewBox: '0 0 448 512', markup: '<path d="M1 1h2"></path>' };
const star = { viewBox: '0 0 576 512', markup: '<path d="M3 3h4"></path>' };
describe('icon sprite', () => {
it('defines each source once and references it from every icon', () => {
const html = renderToStaticMarkup(
<IconsProvider
iconStyle={IconStyle.Regular}
iconSources={{ 'regular/hashtag': hashtag }}
sprite
>
<Icon icon="hashtag" />
<Icon icon="hashtag" className="size-4" />
</IconsProvider>
);
expect(html.split(hashtag.markup)).toHaveLength(2);
expect(html).toContain('<g id="gb-icon-regular-hashtag">');
expect(html.match(/<use href="#gb-icon-regular-hashtag"><\/use>/g)).toHaveLength(2);
expect(html).toContain('viewBox="0 0 448 512"');
});
it('inlines the markup without a sprite', () => {
const html = renderToStaticMarkup(
<IconsProvider
iconStyle={IconStyle.Regular}
iconSources={{ 'regular/hashtag': hashtag }}
>
<Icon icon="hashtag" />
</IconsProvider>
);
expect(html).not.toContain('<use');
expect(html).not.toContain('data-gb-icon-sprite');
expect(html).toContain(hashtag.markup);
});
it('inlines sources that only an outer provider defines', () => {
const html = renderToStaticMarkup(
<IconsProvider iconStyle={IconStyle.Regular} iconSources={{ 'regular/star': star }}>
<IconsProvider iconSources={{ 'regular/hashtag': hashtag }} sprite>
<Icon icon="star" />
<Icon icon="hashtag" />
</IconsProvider>
</IconsProvider>
);
expect(html).toContain(`>${star.markup}</svg>`);
expect(html).not.toContain('gb-icon-regular-star');
expect(html).toContain('<use href="#gb-icon-regular-hashtag"></use>');
});
});
+26 -17
View File
@@ -3,7 +3,7 @@
import * as React from 'react';
import { getIconStyle } from './getIconStyle';
import { getInlineIconSourceKey } from './IconSources';
import { getIconSpriteId, getInlineIconSourceKey } from './IconSources';
import { getIconAssetURL, useIcons } from './IconsProvider';
import type { IconName, IconStyle } from './types';
@@ -51,25 +51,34 @@ export const Icon = React.forwardRef(function Icon(
} = props;
const [iconStyle, icon] = getIconStyle(propIconStyle, propIcon);
const source = context.iconSources?.[getInlineIconSourceKey(iconStyle, icon)];
const sourceKey = getInlineIconSourceKey(iconStyle, icon);
const source = context.iconSources?.[sourceKey];
const maskId = React.useId();
if (source) {
return (
<svg
ref={ref}
{...rest}
viewBox={source.viewBox}
fill="currentColor"
style={{
overflow: 'visible',
...(size ? { width: size, height: size } : {}),
...rest.style,
}}
className={`gb-icon ${className}`}
dangerouslySetInnerHTML={{ __html: source.markup }}
/>
);
const svgProps = {
ref,
...rest,
viewBox: source.viewBox,
fill: 'currentColor',
style: {
overflow: 'visible',
...(size ? { width: size, height: size } : {}),
...rest.style,
},
className: `gb-icon ${className}`,
};
// A page can repeat one icon hundreds of times (heading anchors), so reference the sprite.
if (context.spriteKeys?.has(sourceKey)) {
return (
<svg {...svgProps}>
<use href={`#${getIconSpriteId(sourceKey)}`} />
</svg>
);
}
return <svg {...svgProps} dangerouslySetInnerHTML={{ __html: source.markup }} />;
}
const url = getIconAssetURL(context, iconStyle, icon);
+7
View File
@@ -11,3 +11,10 @@ export interface InlineIconSource {
export function getInlineIconSourceKey(style: string, icon: string): string {
return `${style}/${icon}`;
}
/**
* Get the element id an icon's sprite entry is defined under, from its source key.
*/
export function getIconSpriteId(key: string): string {
return `gb-icon-${key.replace(/[^a-z0-9-]/gi, '-')}`;
}
+61 -4
View File
@@ -2,7 +2,7 @@
import * as React from 'react';
import type { InlineIconSource } from './IconSources';
import { type InlineIconSource, getIconSpriteId } from './IconSources';
import { IconStyle } from './types';
import { GITBOOK_ICONS_ASSET_VERSION } from './version';
@@ -18,6 +18,8 @@ export type IconsContextType = Partial<IconsAssetsLocation> & {
assetsByStyles?: Record<string, IconsAssetsLocation>;
/** Server-resolved SVG sources keyed by style and icon. */
iconSources?: Record<string, InlineIconSource>;
/** Source keys defined in an on-page sprite, which icons reference instead of repeating the markup. */
spriteKeys?: ReadonlySet<string>;
/** Current default style for icons */
iconStyle: IconStyle;
};
@@ -29,7 +31,17 @@ const IconsContext = React.createContext<IconsContextType>({
/**
* Provider to control the loading of icons.
*/
export function IconsProvider(props: React.PropsWithChildren<Partial<IconsContextType>>) {
export function IconsProvider(
props: React.PropsWithChildren<
Partial<Omit<IconsContextType, 'spriteKeys'>> & {
/**
* Define this provider's own `iconSources` once in a hidden sprite, so icons below
* reference them rather than each repeating the SVG markup.
*/
sprite?: boolean;
}
>
) {
const parent = React.useContext(IconsContext);
const {
children,
@@ -38,7 +50,9 @@ export function IconsProvider(props: React.PropsWithChildren<Partial<IconsContex
iconStyle = parent.iconStyle,
assetsByStyles = parent.assetsByStyles,
iconSources = parent.iconSources,
sprite = false,
} = props;
const spriteSources = sprite ? props.iconSources : undefined;
const value = React.useMemo(() => {
return {
assetsURL,
@@ -49,10 +63,53 @@ export function IconsProvider(props: React.PropsWithChildren<Partial<IconsContex
parent.iconSources && iconSources
? { ...parent.iconSources, ...iconSources }
: (iconSources ?? parent.iconSources),
spriteKeys: spriteSources
? new Set([...(parent.spriteKeys ?? []), ...Object.keys(spriteSources)])
: parent.spriteKeys,
};
}, [assetsURL, assetsURLToken, iconStyle, assetsByStyles, iconSources, parent.iconSources]);
}, [
assetsURL,
assetsURLToken,
iconStyle,
assetsByStyles,
iconSources,
spriteSources,
parent.iconSources,
parent.spriteKeys,
]);
return <IconsContext.Provider value={value}>{children}</IconsContext.Provider>;
return (
<IconsContext.Provider value={value}>
{spriteSources ? <IconSprite sources={spriteSources} /> : null}
{children}
</IconsContext.Provider>
);
}
/**
* Hidden SVG holding one copy of each source, for `<use>` references from icons.
* Entries are groups rather than symbols so they draw in the referencing icon's own viewBox.
*/
function IconSprite(props: { sources: Record<string, InlineIconSource> }) {
return (
<svg
aria-hidden="true"
data-gb-icon-sprite=""
width="0"
height="0"
style={{ position: 'absolute' }}
>
<defs>
{Object.entries(props.sources).map(([key, source]) => (
<g
key={key}
id={getIconSpriteId(key)}
dangerouslySetInnerHTML={{ __html: source.markup }}
/>
))}
</defs>
</svg>
);
}
/**