Skip to content

Add support for cover image repositioning #3404

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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/rude-games-beg.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"gitbook": patch
---

Add support for cover repositioning
99 changes: 56 additions & 43 deletions packages/gitbook/src/components/PageBody/PageCover.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ import type { GitBookSiteContext } from '@/lib/context';
import type { RevisionPageDocument, RevisionPageDocumentCover } from '@gitbook/api';
import type { StaticImageData } from 'next/image';

import { Image, type ImageSize } from '@/components/utils';
import { resolveContentRef } from '@/lib/references';
import { getImageAttributes } from '@/components/utils';
import { type ResolvedContentRef, resolveContentRef } from '@/lib/references';
import { tcls } from '@/lib/tailwind';

import { PageCoverImage } from './PageCoverImage';
import defaultPageCoverSVG from './default-page-cover.svg';

const defaultPageCover = defaultPageCoverSVG as StaticImageData;
const PAGE_COVER_SIZE: ImageSize = { width: 1990, height: 480 };

/**
* Cover for the page.
Expand All @@ -26,6 +26,53 @@ export async function PageCover(props: {
cover.refDark ? resolveContentRef(cover.refDark, context) : null,
]);

const sizes = [
// Cover takes the full width on mobile/table
{
media: '(max-width: 768px)',
width: 768,
},
{
media: '(max-width: 1024px)',
width: 1024,
},
// Maximum size of the cover
{ width: 1248 },
];

const getImage = async (resolved: ResolvedContentRef | null, returnNull = false) => {
if (!resolved && returnNull) return;
const attrs = await getImageAttributes({
sizes,
source: resolved
? {
src: resolved.href,
size: resolved.file?.dimensions ?? null,
}
: {
src: defaultPageCover.src,
size: {
width: defaultPageCover.width,
height: defaultPageCover.height,
},
},
quality: 100,
resize: context.imageResizer ?? false,
});
const size =
(await context.imageResizer?.getImageSize(
resolved?.href || defaultPageCover.src,
{}
)) ?? undefined;
return {
...attrs,
size,
};
};

const images = await Promise.all([getImage(resolved), getImage(resolvedDark, true)]);
const [light, dark] = images;

return (
<div
className={tcls(
Expand All @@ -52,47 +99,13 @@ export async function PageCover(props: {
]
)}
>
<Image
alt="Page cover image"
sources={{
light: resolved
? {
src: resolved.href,
size: resolved.file?.dimensions,
}
: {
src: defaultPageCover.src,
size: {
width: defaultPageCover.width,
height: defaultPageCover.height,
},
},
dark: resolvedDark
? {
src: resolvedDark.href,
size: resolvedDark.file?.dimensions,
}
: null,
<PageCoverImage
imgs={{
// biome-ignore lint/style/noNonNullAssertion: light image is always defined
light: light!,
dark,
}}
resize={
// When using the default cover, we don't want to resize as it's a SVG
resolved ? context.imageResizer : false
}
sizes={[
// Cover takes the full width on mobile/table
{
media: '(max-width: 768px)',
width: 768,
},
{
media: '(max-width: 1024px)',
width: 1024,
},
// Maximum size of the cover
{ width: 1248 },
]}
className={tcls('w-full', 'object-cover', 'object-center')}
inlineStyle={{ aspectRatio: `${PAGE_COVER_SIZE.width}/${PAGE_COVER_SIZE.height}` }}
y={cover.yPos}
/>
</div>
);
Expand Down
83 changes: 83 additions & 0 deletions packages/gitbook/src/components/PageBody/PageCoverImage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
'use client';
import { tcls } from '@/lib/tailwind';
import { useMemo, useRef } from 'react';
import { useResizeObserver } from 'usehooks-ts';
import type { ImageSize } from '../utils';

interface ImageAttributes {
src: string;
srcSet?: string;
sizes?: string;
width?: number;
height?: number;
size?: ImageSize;
}

interface Images {
light: ImageAttributes;
dark?: ImageAttributes;
}

const PAGE_COVER_SIZE: ImageSize = { width: 1990, height: 480 };

function useGetTop(
container: { height?: number; width?: number },
y: number,
img?: ImageAttributes
) {
const top = useMemo(() => {
// When the size of the image hasn't been determined, we fallback to the center position
if (!img || !img.size || y === 0) return '50%';
const ratio =
img?.size && container.height && container.width
? Math.max(container.width / img.size.width, container.height / img.size.height)
: 1;
const scaledHeight = img.size ? img.size.height * ratio : PAGE_COVER_SIZE.height;
const top =
container.height && img.size ? (container.height - scaledHeight) / 2 + y * ratio : y;
return `${top}px`;
}, [container.width, container.height, img, y]);

return top;
}

export function PageCoverImage({ imgs, y }: { imgs: Images; y: number }) {
const containerRef = useRef<HTMLDivElement>(null);
const imageRef = useRef<HTMLImageElement>(null);

const container = useResizeObserver({
ref: containerRef,
});

const topLight = useGetTop(container, y, imgs.light);
const topDark = useGetTop(container, y, imgs.dark);

return (
<div className="h-full w-full overflow-hidden" ref={containerRef}>
<img
ref={imageRef}
src={imgs.light.src}
fetchPriority="high"
alt="Page cover"
className={tcls('w-full', 'object-cover', imgs.dark ? 'dark:hidden' : '')}
style={{
aspectRatio: `${PAGE_COVER_SIZE.width}/${PAGE_COVER_SIZE.height}`,
objectPosition: `50% ${topLight}`,
}}
/>
{imgs.dark && (
<img
ref={imageRef}
src={imgs.dark.src}
fetchPriority="low"
alt="Page cover"
className={tcls('w-full', 'object-cover', 'dark:inline', 'hidden')}
style={{
aspectRatio: `${PAGE_COVER_SIZE.width}/${PAGE_COVER_SIZE.height}`,
objectPosition: `50% ${topDark}`,
}}
/>
)}
</div>
);
}
4 changes: 2 additions & 2 deletions packages/gitbook/src/components/utils/Image.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ type ImageSource = {
aspectRatio?: string;
};

type ImageSourceSized = {
export type ImageSourceSized = {
src: string;
size: ImageSize | null;
aspectRatio?: string;
Expand Down Expand Up @@ -244,7 +244,7 @@ async function ImagePictureSized(
* Get the attributes for an image.
* src, srcSet, sizes, width, height, etc.
*/
async function getImageAttributes(params: {
export async function getImageAttributes(params: {
sizes: ImageResponsiveSize[];
source: ImageSourceSized;
quality: number;
Expand Down