Compare commits

..

2 Commits

Author SHA1 Message Date
Samy Pessé 19789f15a9 Script to deploy 2024-11-14 14:03:03 +01:00
Samy Pessé 1d71fdaa6a Start 2024-11-14 13:10:11 +01:00
83 changed files with 934 additions and 1019 deletions
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Fix an issue with the cookie banner buttons being non responsive
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Update styling of search+ask modal
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Fix a regression in variant drop-down caused by missing z-index.
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Add scroll margin to the top when there are sections
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': minor
---
Fix an issue where the active site section indicator appeared above any dropdowns.
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Optimize performances by using new API endpoint for fetching site data.
-5
View File
@@ -1,5 +0,0 @@
---
'@gitbook/react-openapi': patch
---
Support Integers in Response example
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Restyle hint blocks
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Fix security issue with image resizing that could be used for phishing
-5
View File
@@ -1,5 +0,0 @@
---
'@gitbook/react-openapi': patch
---
bumped the scalar api client dependency
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Fix - whitespace added to site section tabs with icons.
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Add icons to sections
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
style: adds missing scalar css variables
+25
View File
@@ -0,0 +1,25 @@
# Use the official Node.js image as the base image
FROM imbios/bun-node:latest
# Set the working directory inside the container
WORKDIR /app
# Copy the package.json and bun.lockb files to the working directory
COPY . .
# Install the app dependencies
RUN bun install --frozen-lockfile
# Next.js collects completely anonymous telemetry data about general usage.
# Learn more here: https://nextjs.org/telemetry
# Disable telemetry during the build
ENV NEXT_TELEMETRY_DISABLED 1
RUN bun run build
# Expose the port on which the app will run
EXPOSE 3000
# Start the app
ENV PORT 3000
ENV HOSTNAME "0.0.0.0"
CMD ["bun", "run", "start"]
BIN
View File
Binary file not shown.
Executable
+6
View File
@@ -0,0 +1,6 @@
#!/bin/bash
set -o errexit
set -o pipefail
gcloud run deploy gitbook-open-test --source=. --project=getsquad-dev-samy --region=us-central1 --allow-unauthenticated
+2 -1
View File
@@ -27,7 +27,8 @@
"release": "turbo run release && changeset publish",
"release:preview": "turbo run release:preview",
"download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local",
"clean": "turbo run clean"
"clean": "turbo run clean",
"start": "cd packages/gitbook && bun run start"
},
"workspaces": [
"packages/*"
-49
View File
@@ -491,55 +491,6 @@ const testCases: TestsCase[] = [
},
],
},
{
name: 'Shared space navigation (first site)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-uno/',
tests: [
{
name: 'Navigation to shared space',
url: '',
run: async (page) => {
const sharedSpaceLink = page.locator('a.underline');
await sharedSpaceLink.click();
expect(page.locator('h1')).toHaveText('shared');
const url = page.url();
expect(url.includes('shared-space-uno')).toBeTruthy(); // same uno site
expect(url.endsWith('/shared')).toBeTruthy(); // correct page
},
},
],
},
{
name: 'Shared space navigation (second site)',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/shared-space-dos/',
tests: [
{
name: 'Navigation to shared space',
url: '',
run: async (page) => {
const sharedSpaceLink = page.locator('a.underline');
await sharedSpaceLink.click();
expect(page.locator('h1')).toHaveText('shared');
const url = page.url();
expect(url.includes('shared-space-dos')).toBeTruthy(); // same dos site
expect(url.endsWith('/shared')).toBeTruthy(); // correct page
},
},
],
},
{
name: 'Site Redirects',
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
tests: [
{
name: 'Redirect to SSO page',
url: 'a/redirect/to/sso',
run: async (page) => {
await expect(page.locator('h1')).toHaveText('SSO');
},
},
],
},
{
name: 'Share links',
baseUrl: 'https://gitbook.gitbook.io/gbo-tests-share-links/',
+2
View File
@@ -2,6 +2,8 @@ const { withSentryConfig } = require('@sentry/nextjs');
module.exports = withSentryConfig(
{
output: 'standalone',
env: {
BUILD_VERSION: (process.env.GITHUB_SHA ?? '').slice(0, 7),
SENTRY_DSN: process.env.SENTRY_DSN ?? '',
+2 -2
View File
@@ -16,7 +16,7 @@
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
},
"dependencies": {
"@gitbook/api": "^0.80.0",
"@gitbook/api": "^0.73.0",
"@gitbook/cache-do": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*",
"@gitbook/icons": "workspace:*",
@@ -60,7 +60,7 @@
"remark-rehype": "^11.1.0",
"rison": "^0.1.1",
"server-only": "^0.0.1",
"shiki": "^1.23.1",
"shiki": "^1.22.0",
"tailwind-merge": "^2.2.0",
"tailwind-shades": "^1.1.2",
"unified": "^11.0.4",
@@ -4,7 +4,6 @@ import {
verifyImageSignature,
resizeImage,
CloudflareImageOptions,
imagesResizingSignVersion,
checkIsSizableImageURL,
} from '@/lib/images';
import { parseImageAPIURL } from '@/lib/urls';
@@ -19,29 +18,28 @@ export const runtime = 'edge';
export async function GET(request: NextRequest) {
let urlParam = request.nextUrl.searchParams.get('url');
const signature = request.nextUrl.searchParams.get('sign');
// The current signature algorithm sets version as 2, but we need to support the older version as well
const signatureVersion = request.nextUrl.searchParams.get('sv') as string | undefined;
// The current signature algorithm sets version as 1, but we need to support the older version as well
// for previously generated content. In this case, we default to version 0.
const signatureVersion = (request.nextUrl.searchParams.get('sv') as '1') || '0';
if (!urlParam || !signature) {
return new Response('Missing url/sign parameters', { status: 400 });
}
const url = parseImageAPIURL(urlParam);
// Prevent infinite loops
if (url.includes('/~gitbook/image')) {
return new Response('Invalid url parameter', { status: 400 });
}
// Check again if the image can be sized, even though we checked when rendering the Image component
// Otherwise, it's possible to pass just any link to this endpoint and trigger HTML injection on the domain
// Also prevent infinite redirects.
if (!checkIsSizableImageURL(url)) {
return new Response('Invalid url parameter', { status: 400 });
}
// For older signatures, we redirect to the url.
if (signatureVersion !== imagesResizingSignVersion) {
return Response.redirect(url, 302);
}
// Verify the signature
const verified = await verifyImageSignature(url, { signature });
const verified = await verifyImageSignature(url, { signature, version: signatureVersion });
if (!verified) {
return new Response(`Invalid signature "${signature ?? ''}" for "${url}"`, { status: 400 });
}
@@ -8,10 +8,10 @@ import { useScrollPage } from '@/components/hooks';
/**
* Client component to initialize interactivity for a page.
*/
export function PageClientLayout(props: { withSections?: boolean }) {
export function PageClientLayout(props: {}) {
// We use this hook in the page layout to ensure the elements for the blocks
// are rendered before we scroll to a hash or to the top of the page
useScrollPage({ scrollMarginTop: props.withSections ? 50 : undefined });
useScrollPage();
useStripFallbackQueryParam();
return null;
@@ -1,11 +1,11 @@
import { getSpaceLanguage, t } from '@/intl/server';
import { getSiteData } from '@/lib/api';
import { getSiteLayoutData } from '@/lib/api';
import { getSiteContentPointer } from '@/lib/pointer';
import { tcls } from '@/lib/tailwind';
export default async function NotFound() {
const pointer = getSiteContentPointer();
const { customization } = await getSiteData(pointer);
const { customization } = await getSiteLayoutData(pointer);
const language = getSpaceLanguage(customization);
@@ -73,7 +73,7 @@ export default async function Page(props: {
page,
};
const withSections = Boolean(sections && sections.list.length > 0);
const withSections = Boolean(sections && sections.length > 0);
const headerOffset = { sectionsHeader: withSections, topHeader: withTopHeader };
return (
@@ -111,7 +111,7 @@ export default async function Page(props: {
/>
</div>
<React.Suspense fallback={null}>
<PageClientLayout withSections={withSections} />
<PageClientLayout />
</React.Suspense>
</>
);
@@ -1,6 +1,7 @@
import { ContentVisibility } from '@gitbook/api';
import { NextRequest } from 'next/server';
import { getSpace, getSite } from '@/lib/api';
import { getCollection, getSite, getSpace } from '@/lib/api';
import { absoluteHref } from '@/lib/links';
import { getSiteContentPointer } from '@/lib/pointer';
import { isSpaceIndexable } from '@/lib/seo';
@@ -3,7 +3,7 @@ import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
import React from 'react';
import { getSite, getSiteData, getSpace } from '@/lib/api';
import { getCurrentSiteCustomization, getSite, getSpace } from '@/lib/api';
import { getEmojiForCode } from '@/lib/emojis';
import { getSiteContentPointer } from '@/lib/pointer';
import { tcls } from '@/lib/tailwind';
@@ -38,9 +38,9 @@ export async function GET(req: NextRequest) {
const pointer = getSiteContentPointer();
const spaceId = pointer.spaceId;
const [space, { customization }] = await Promise.all([
const [space, customization] = await Promise.all([
getSpace(spaceId, pointer.siteShareKey),
getSiteData(pointer),
getCurrentSiteCustomization(pointer),
]);
const site = await getSite(pointer.organizationId, pointer.siteId);
const contentTitle = getContentTitle(space, customization, site);
+122 -48
View File
@@ -1,12 +1,14 @@
import { RevisionPage } from '@gitbook/api';
import { redirect } from 'next/navigation';
import { RevisionPage, SiteSection, SiteSpace, Space } from '@gitbook/api';
import { assert } from 'ts-essentials';
import {
getRevisionPageByPath,
getDocument,
getSpaceContentData,
ContentTarget,
getSiteData,
getSiteRedirectBySource,
getSite,
getCurrentSiteCustomization,
getSiteStructure,
} from '@/lib/api';
import { resolvePagePath, resolvePageId } from '@/lib/pages';
import { getSiteContentPointer } from '@/lib/pointer';
@@ -19,18 +21,35 @@ export interface PageIdParams {
pageId: string;
}
export type SectionsList = { list: SiteSection[]; section: SiteSection; index: number };
/**
* Fetch all the data needed to render the content layout.
*/
export async function fetchContentData() {
const content = getSiteContentPointer();
const [{ space, contentTarget, pages }, { customization, site, sections, spaces, scripts }] =
const [{ space, contentTarget, pages, customization, scripts }, siteStructure] =
await Promise.all([
getSpaceContentData(content, content.siteShareKey),
getSiteData(content),
fetchSiteStructure({
organizationId: content.organizationId,
siteId: content.siteId,
siteShareKey: content.siteShareKey,
}),
]);
const site = siteStructure.site;
const siteSections =
content.siteSectionId && siteStructure.sections
? parseSiteSectionsList(content.siteSectionId, siteStructure.sections)
: null;
const spaces =
siteStructure.spaces ??
(siteSections ? parseSpacesFromSiteSpaces(siteSections.section.siteSpaces) : []);
// we grab the space attached to the parent as it contains overriden customizations
const spaceRelativeToParent = spaces?.find((space) => space.id === content.spaceId);
@@ -39,39 +58,53 @@ export async function fetchContentData() {
contentTarget,
space: spaceRelativeToParent ?? space,
pages,
sections: siteSections,
site,
sections,
spaces,
shareKey: content.siteShareKey,
customization,
scripts,
ancestors: [],
};
}
function parseSiteSectionsList(siteSectionId: string, sections: SiteSection[]) {
const section = sections.find((section) => section.id === siteSectionId);
assert(sectionIsDefined(section), 'A section must be defined when there are multiple sections');
return { list: sections, section, index: sections.indexOf(section) } satisfies SectionsList;
}
function sectionIsDefined(section?: SiteSection): section is NonNullable<SiteSection> {
return typeof section !== 'undefined' && section !== null;
}
/**
* Fetch all the data needed to render the content.
* Optimized to fetch in parallel as much as possible.
*/
export async function fetchPageData(params: PagePathParams | PageIdParams) {
const contentData = await fetchContentData();
const content = getSiteContentPointer();
const page = await resolvePage({
organizationId: contentData.space.organization,
siteId: contentData.site.id,
spaceId: contentData.contentTarget.spaceId,
revisionId: contentData.contentTarget.revisionId,
pages: contentData.pages,
shareKey: contentData.shareKey,
params,
});
const document = page?.page.documentId
? await getDocument(contentData.space.id, page.page.documentId)
: null;
const { space, contentTarget, pages, customization, scripts } = await getSiteData(content);
const page = await resolvePage(contentTarget, pages, params);
const [siteStructure, document] = await Promise.all([
fetchSiteStructure({
organizationId: content.organizationId,
siteId: content.siteId,
siteShareKey: content.siteShareKey,
}),
page?.page.documentId ? getDocument(space.id, page.page.documentId) : null,
]);
return {
...contentData,
content,
contentTarget,
space,
pages,
customization,
scripts,
ancestors: [],
...page,
...siteStructure,
document,
};
}
@@ -80,17 +113,11 @@ export async function fetchPageData(params: PagePathParams | PageIdParams) {
* Resolve a page from the params.
* If the path can't be found, we try to resolve it from the API to handle redirects.
*/
async function resolvePage(input: {
organizationId: string;
siteId: string;
spaceId: string;
revisionId: string;
shareKey: string | undefined;
pages: RevisionPage[];
params: PagePathParams | PageIdParams;
}) {
const { organizationId, siteId, spaceId, revisionId, pages, shareKey, params } = input;
async function resolvePage(
contentTarget: ContentTarget,
pages: RevisionPage[],
params: PagePathParams | PageIdParams,
) {
if ('pageId' in params) {
return resolvePageId(pages, params.pageId);
}
@@ -104,31 +131,78 @@ async function resolvePage(input: {
return page;
}
// If page can't be found, we try with the API, in case we have a redirect
// We use the raw pathname to handle special/malformed redirects setup by users in the GitSync.
// The page rendering will take care of redirecting to a normalized pathname.
//
// We don't test path that are too long as GitBook doesn't support them and will return a 404 anyway.
if (rawPathname.length <= 512) {
// If page can't be found, we try with the API, in case we have a redirect at space level.
// We use the raw pathname to handle special/malformed redirects setup by users in the GitSync.
// The page rendering will take care of redirecting to a normalized pathname.
const resolved = await getRevisionPageByPath(spaceId, revisionId, rawPathname);
const resolved = await getRevisionPageByPath(
contentTarget.spaceId,
contentTarget.revisionId,
rawPathname,
);
if (resolved) {
return resolvePageId(pages, resolved.id);
}
// If a page still can't be found, we try with the API, in case we have a redirect at site level.
const resolvedSiteRedirect = await getSiteRedirectBySource({
organizationId,
siteId,
source: rawPathname.startsWith('/') ? rawPathname : `/${rawPathname}`,
siteShareKey: input.shareKey,
});
if (resolvedSiteRedirect) {
return redirect(resolvedSiteRedirect.target);
}
}
return undefined;
}
/**
* Fetch the structure of an organization site.
* This includes the site and its sections or spaces.
*/
async function fetchSiteStructure(args: {
organizationId: string;
siteId: string;
siteShareKey: string | undefined;
}) {
const { organizationId, siteId, siteShareKey } = args;
const [orgSite, siteStructure, siteParentCustomizations] = await Promise.all([
getSite(organizationId, siteId),
getSiteStructure({ organizationId, siteId, siteShareKey }),
getCurrentSiteCustomization({ organizationId, siteId, siteSpaceId: undefined }),
]);
const siteSections =
siteStructure.type === 'sections' && siteStructure.structure
? siteStructure.structure
: null;
const siteSpaces =
siteStructure.type === 'siteSpaces' && siteStructure.structure
? parseSpacesFromSiteSpaces(siteStructure.structure)
: null;
// override the title with the customization title
const site = {
...orgSite,
...(siteParentCustomizations?.title ? { title: siteParentCustomizations.title } : {}),
};
return {
site,
spaces: siteSpaces,
sections: siteSections,
};
}
function parseSpacesFromSiteSpaces(siteSpaces: SiteSpace[]) {
const spaces: Record<string, Space> = {};
siteSpaces.forEach((siteSpace) => {
spaces[siteSpace.space.id] = {
...siteSpace.space,
title: siteSpace.title ?? siteSpace.space.title,
urls: {
...siteSpace.space.urls,
published: siteSpace.urls.published,
},
};
});
return Object.values(spaces);
}
/**
* Get the page path from the params.
*/
+2 -2
View File
@@ -1,5 +1,5 @@
import { CustomizationRootLayout } from '@/components/RootLayout';
import { getSiteData } from '@/lib/api';
import { getSiteLayoutData } from '@/lib/api';
import { getSiteContentPointer } from '@/lib/pointer';
/**
@@ -10,7 +10,7 @@ export default async function SiteRootLayout(props: { children: React.ReactNode
const { children } = props;
const pointer = getSiteContentPointer();
const { customization } = await getSiteData(pointer);
const { customization } = await getSiteLayoutData(pointer);
return (
<CustomizationRootLayout customization={customization}>{children}</CustomizationRootLayout>
@@ -1,7 +1,7 @@
import { SpaceIntegrationScript } from '@gitbook/api';
import { CustomizationRootLayout } from '@/components/RootLayout';
import { getSiteData, getSpaceCustomization } from '@/lib/api';
import { getSiteLayoutData, getSpaceCustomization } from '@/lib/api';
import { getSiteOrSpacePointerForPDF } from './pointer';
@@ -14,7 +14,7 @@ export default async function PDFRootLayout(props: { children: React.ReactNode }
const pointer = getSiteOrSpacePointerForPDF();
const { customization } = await ('siteId' in pointer
? getSiteData(pointer)
? getSiteLayoutData(pointer)
: getSpaceLayoutData(pointer.spaceId));
return (
@@ -26,7 +26,7 @@ export default async function PDFRootLayout(props: { children: React.ReactNode }
* Fetch all the layout data about a space at once.
*/
async function getSpaceLayoutData(spaceId: string) {
const [{ customization }, scripts] = await Promise.all([
const [customization, scripts] = await Promise.all([
getSpaceCustomization(spaceId),
[] as SpaceIntegrationScript[],
]);
@@ -11,7 +11,7 @@ import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import * as React from 'react';
import { DocumentView } from '@/components/DocumentView';
import { DocumentView, createHighlightingContext } from '@/components/DocumentView';
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
import { PolymorphicComponentProp } from '@/components/utils/types';
import { getSpaceLanguage } from '@/intl/server';
@@ -21,7 +21,7 @@ import {
getSpace,
getSpaceCustomization,
getSpaceContentData,
getSiteData,
getCurrentSiteCustomization,
} from '@/lib/api';
import { pagePDFContainerId, PageHrefContext, absoluteHref } from '@/lib/links';
import { resolvePageId } from '@/lib/pages';
@@ -40,9 +40,11 @@ export const runtime = 'edge';
export async function generateMetadata(): Promise<Metadata> {
const pointer = getSiteOrSpacePointerForPDF();
const [space, { customization }] = await Promise.all([
const [space, customization] = await Promise.all([
getSpace(pointer.spaceId, 'siteId' in pointer ? pointer.siteShareKey : undefined),
'siteId' in pointer ? getSiteData(pointer) : getSpaceCustomization(pointer.spaceId),
'siteId' in pointer
? getCurrentSiteCustomization(pointer)
: getSpaceCustomization(pointer.spaceId),
]);
return {
@@ -65,8 +67,10 @@ export default async function PDFHTMLOutput(props: { searchParams: { [key: strin
currentPDFUrl += '?' + searchParams.toString();
// Load the content,
const [{ customization }, { space, contentTarget, pages: rootPages }] = await Promise.all([
'siteId' in pointer ? getSiteData(pointer) : getSpaceCustomization(pointer.spaceId),
const [customization, { space, contentTarget, pages: rootPages }] = await Promise.all([
'siteId' in pointer
? getCurrentSiteCustomization(pointer)
: getSpaceCustomization(pointer.spaceId),
getSpaceContentData(pointer, 'siteId' in pointer ? pointer.siteShareKey : undefined),
]);
const language = getSpaceLanguage(customization);
@@ -227,6 +231,7 @@ async function PDFPageDocument(props: {
const { space, page, refContext } = props;
const document = page.documentId ? await getDocument(space.id, page.documentId) : null;
const shouldHighlightCode = createHighlightingContext();
return (
<PrintPage id={pagePDFContainerId(page)}>
@@ -249,6 +254,7 @@ async function PDFPageDocument(props: {
contentRefContext: refContext,
resolveContentRef: (ref) => resolveContentRef(ref, refContext),
getId: (id) => pagePDFContainerId(page, id),
shouldHighlightCode,
}}
/>
) : null}
@@ -48,7 +48,7 @@ async function SpaceRefCard(
return null;
}
const { customization: spaceCustomization } = getSpaceCustomization(spaceId);
const spaceCustomization = await ignoreAPIError(getSpaceCustomization(spaceId));
const customFavicon = spaceCustomization?.favicon;
const customEmoji = customFavicon && 'emoji' in customFavicon ? customFavicon.emoji : undefined;
const customIcon = customFavicon && 'icon' in customFavicon ? customFavicon.icon : undefined;
@@ -71,7 +71,7 @@ export function Caption(
'text-center',
'mt-2',
'text-dark/7',
'dark:text-light/7',
'dark:text-light/6',
)}
>
<Inlines
@@ -15,7 +15,8 @@ import './theme.css';
*/
export async function CodeBlock(props: BlockProps<DocumentBlockCode>) {
const { block, document, style, context } = props;
const lines = await highlight(block);
const withHighlighting = context.shouldHighlightCode(context.content?.spaceId);
const lines = withHighlighting ? await highlight(block) : plainHighlighting(block);
const id = block.key!;
@@ -98,8 +99,6 @@ export async function CodeBlock(props: BlockProps<DocumentBlockCode>) {
'overflow-auto',
'bg-light-2',
'dark:bg-dark-2',
'border-light-4',
'dark:border-dark-4',
'hide-scroll',
titleRoundingStyle,
)}
@@ -50,6 +50,7 @@ export function PlainCodeBlock(props: { code: string; syntax: string }) {
mode: 'default',
contentRefContext: null,
resolveContentRef: async () => null,
shouldHighlightCode: () => true,
}}
block={block}
ancestorBlocks={[]}
@@ -0,0 +1,30 @@
const CODE_HIGHLIGHT_BLOCK_LIMIT = 50;
/**
* Spaces where we'll always use plain highlighting.
*/
const PLAIN_HIGHLIGHTING_SPACES: string[] = [
'V9geAO9ITPi8WOYK5o0r',
'puRmcwVxGFtHph8IjXaf',
'e3jwbMOrr4RhKtZ9C0XL',
'ryjzVNizLfd6pYogN3dm',
];
/**
* Protect against memory issues when highlighting a large number of code blocks.
* This context only allows 50 code blocks per render to be highlighted.
* Once highlighting can scale up to a large number of code blocks, it can be removed.
*
* https://linear.app/gitbook-x/issue/RND-3588/gitbook-open-code-syntax-highlighting-runs-out-of-memory-after-a
*/
export function createHighlightingContext() {
let count = 0;
return (spaceId?: string | undefined) => {
if (!spaceId || PLAIN_HIGHLIGHTING_SPACES.includes(spaceId)) {
return false;
}
count += 1;
return count < CODE_HIGHLIGHT_BLOCK_LIMIT;
};
}
@@ -1,2 +1,3 @@
export * from './CodeBlock';
export * from './PlainCodeBlock';
export * from './createHighlightingContext';
@@ -38,6 +38,16 @@ export interface DocumentContext {
*/
getId?: (id: string) => string;
/**
* Returns true if the given code block should be highlighted.
* This function was added to protect against memory issues when highlighting
* a large number of code blocks.
* Once highlighting can scale up to a large number of code blocks, it can be removed.
*
* https://linear.app/gitbook-x/issue/RND-3588/gitbook-open-code-syntax-highlighting-runs-out-of-memory-after-a
*/
shouldHighlightCode: (spaceId: string | undefined) => boolean;
/**
* True if the blocks should be wrapped in suspense boundary for isolated loading skeletons.
* @default true
@@ -16,8 +16,8 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
return (
<div
className={tcls(
'hint',
'p-4',
'px-4',
'py-4',
'transition-colors',
'rounded-md',
'straight-corners:rounded-none',
@@ -26,16 +26,19 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
)}
>
<div className={tcls('flex', 'flex-row')}>
<Icon
icon={hintStyle.icon}
<div
className={tcls(
'size-5',
'mr-4',
'flex',
'items-start',
'justify-center',
'pr-3',
'mt-0.5',
firstLine.lineHeight,
hintStyle.iconColor,
)}
/>
>
<Icon icon={hintStyle.icon} className={tcls('size-4')} />
</div>
<Blocks
{...contextProps}
ancestorBlocks={[...ancestorBlocks, block]}
@@ -45,7 +48,7 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
// render hash icon on the other side of the heading
'flip-heading-hash',
)}
style={['flex-1', 'space-y-4', '[&_.hint]:border', '[&_pre]:border']}
style={['flex-1', 'space-y-4', '[&>p]:text-sm', '[&>p]:leading-relaxed']}
/>
</div>
</div>
@@ -62,69 +65,130 @@ const HINT_STYLES: {
} = {
info: {
icon: 'circle-info',
iconColor: ['text-primary-500', 'dark:text-primary-400'],
iconColor: ['text-periwinkle-700', 'dark:text-periwinkle-400'],
bodyColor: [
'[&_a]:text-primary-500',
'[&_a:hover]:text-primary-600',
'dark:[&_a]:text-primary-400',
'dark:[&_a:hover]:text-primary-300',
'[&>a]:text-periwinkle-700',
'[&>a:hover]:text-periwinkle-800',
'[&>code]:bg-periwinkle-700/4',
'[&>code]:text-inherit',
'[&>code]:shadow-none',
'text-periwinkle-900',
'dark:text-periwinkle-200',
'dark:[&>a]:text-periwinkle',
'dark:[&>a:hover]:text-periwinkle-600',
'dark:[&>code]:bg-periwinkle-200/2',
'dark:[&>code]:text-inherit',
'decoration-periwinkle-700/6',
'dark:decoration-periwinkle/6',
],
style: [
'bg-dark-1/1',
'border-dark/3',
'dark:bg-light/1',
'dark:border-light/3',
'[&_.can-override-bg]:bg-dark-1/2',
'[&_.can-override-text]:text-dark',
'dark:[&_.can-override-bg]:bg-light/2',
'dark:[&_.can-override-text]:text-light',
'bg-gradient-to-b',
'from-periwinkle/6',
'to-periwinkle/5',
'ring-1',
'ring-inset',
'ring-dark/1',
'dark:ring-periwinkle/1',
'dark:from-periwinkle/2',
'dark:to-periwinkle/[0.1]',
],
},
warning: {
icon: 'circle-exclamation',
iconColor: ['text-amber-500', 'dark:text-orange-400'], // Darker shades of orange-* mismatch with lighter shades, so in light mode we use amber text on top of orange bg.
iconColor: ['text-yellow-800', 'dark:text-yellow'],
bodyColor: [
'[&_a]:text-orange-800',
'[&_a:hover]:text-orange-900',
'dark:[&_a]:text-orange-400',
'dark:[&_a:hover]:text-orange-300',
'[&_.can-override-bg]:bg-orange-500/3',
'[&_.can-override-text]:text-orange-800',
'dark:[&_.can-override-text]:text-orange-400',
'decoration-orange-800/6',
'dark:decoration-orange-400/6',
'[&>a]:text-yellow-700',
'[&>a:hover]:text-yellow-800',
'[&>code]:bg-yellow-600/5',
'[&>code]:text-inherit',
'[&>code]:shadow-none',
'text-yellow-900',
'dark:text-yellow-200',
'dark:[&>a]:text-yellow',
'dark:[&>a:hover]:text-yellow-600',
'dark:[&>code]:bg-yellow-200/2',
'dark:[&>code]:text-inherit',
'decoration-yellow-700/6',
'dark:decoration-yellow/6',
],
style: [
'bg-gradient-to-b',
'from-yellow/6',
'to-yellow/5',
'ring-1',
'ring-inset',
'ring-dark/1',
'dark:ring-yellow/[0.02]',
'dark:from-yellow/[0.06]',
'dark:to-yellow/2',
],
style: ['bg-orange-500/2', 'border-orange-500/4'],
},
danger: {
icon: 'triangle-exclamation',
iconColor: ['text-red-500', 'dark:text-red-400'],
iconColor: ['text-pomegranate-700', 'dark:text-pomegranate-400'],
bodyColor: [
'[&_a]:text-red-800',
'[&_a:hover]:text-red-900',
'dark:[&_a]:text-red-400',
'dark:[&_a:hover]:text-red-300',
'[&_.can-override-bg]:bg-red-500/3',
'[&_.can-override-text]:text-red-400',
'decoration-red-800/6',
'dark:decoration-red-400/6',
'[&>a]:text-pomegranate-600/9',
'[&>a:hover]:text-pomegranate-800',
'[&>code]:bg-pomegranate-600/4',
'[&>code]:text-inherit',
'[&>code]:shadow-none',
'text-pomegranate-900',
'dark:text-pomegranate-100',
'dark:[&>a]:text-pomegranate',
'dark:[&>a:hover]:text-pomegranate-600',
'dark:[&>code]:bg-pomegranate-200/2',
'dark:[&>code]:text-inherit',
'decoration-pomegranate-600/6',
'dark:decoration-pomegranate/6',
],
style: [
'bg-gradient-to-b',
'from-pomegranate/4',
'to-pomegranate/3',
'ring-1',
'ring-inset',
'ring-dark/1',
'dark:ring-pomegranate/1',
'dark:from-pomegranate/2',
'dark:to-pomegranate/3',
],
style: ['bg-red-500/2', 'border-red-500/4'],
},
success: {
icon: 'circle-check',
iconColor: ['text-green-500', 'dark:text-green-400'],
iconColor: ['text-teal-700', 'dark:text-teal-400'],
bodyColor: [
'[&_a]:text-green-800',
'[&_a:hover]:text-green-900',
'dark:[&_a]:text-green-400',
'dark:[&_a:hover]:text-green-300',
'[&_.can-override-bg]:bg-green-500/3',
'[&_.can-override-text]:text-green-800',
'dark:[&_.can-override-text]:text-green-400',
'decoration-green-800/6',
'dark:decoration-green-400/6',
'[&>a]:text-teal-600',
'[&>a:hover]:text-teal-800',
'[&>code]:bg-teal-600/4',
'[&>code]:text-inherit',
'[&>code]:shadow-none',
'text-teal-800',
'dark:text-teal-100',
'dark:[&>a]:text-teal-400',
'dark:[&>a:hover]:text-teal-500',
'dark:[&>code]:bg-teal-200/2',
'dark:[&>code]:text-inherit',
'decoration-teal/6',
'dark:decoration-teal/6',
],
style: [
'bg-gradient-to-b',
'from-teal/4',
'to-teal/3',
'ring-1',
'ring-inset',
'ring-dark/1',
'dark:ring-teal/1',
'dark:from-teal/2',
'dark:to-teal/3',
],
style: ['bg-green-500/2', 'border-green-500/4'],
},
};
@@ -57,9 +57,6 @@
--scalar-shadow-1: 0 1px 3px 0 rgba(0, 0, 0, 0.11);
--scalar-shadow-2: rgba(0, 0, 0, 0.08) 0px 13px 20px 0px, rgba(0, 0, 0, 0.08) 0px 3px 8px 0px,
#eeeeed 0px 0 0 1px;
--scalar-selection-background: rgba(96, 175, 255, 0.4);
--scalar-selection-color: rgb(var(--dark-base, 22 22 22));
}
.dark .scalar-modal-layout,
.dark .scalar-app,
@@ -117,9 +114,6 @@
--scalar-shadow-1: 0 1px 3px 0 rgb(0, 0, 0, 0.1);
--scalar-shadow-2: rgba(15, 15, 15, 0.2) 0px 3px 6px, rgba(15, 15, 15, 0.4) 0px 9px 24px,
0 0 0 1px rgba(255, 255, 255, 0.1);
--scalar-selection-background: rgba(96, 175, 255, 0.4);
--scalar-selection-color: rgb(var(--light-base, 255 255 255));
}
.scalar-modal-layout,
.scalar-app,
@@ -7,11 +7,6 @@ export function Stepper(props: BlockProps<DocumentBlockStepper>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
return (
<Blocks
blockStyle={style}
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
/>
<Blocks {...contextProps} nodes={block.nodes} ancestorBlocks={[...ancestorBlocks, block]} />
);
}
@@ -30,17 +30,17 @@ export function StepperStep(props: BlockProps<DocumentBlockStepperStep>) {
})();
return (
<div className={tcls('flex flex-row gap-4 md:gap-8 max-w-3xl w-full mx-auto', style)}>
<div className="flex flex-row gap-4 md:gap-8 max-w-3xl w-full mx-auto">
<div className="relative select-none">
<div
className={tcls(
'can-override-bg can-override-text flex size-[calc(1.75rem+1px)] items-center justify-center rounded-full bg-primary-50 dark:bg-primary-900 tabular-nums',
'flex size-[calc(1.75rem+1px)] items-center justify-center rounded-full bg-primary-50 dark:bg-primary-900 tabular-nums',
'font-medium text-primary-800 dark:text-primary-200',
)}
>
{index + 1}
</div>
<div className="absolute bottom-2 left-[0.875rem] top-9 w-px bg-primary-50 dark:bg-primary-900 can-override-bg" />
<div className="absolute bottom-2 left-[0.875rem] top-9 w-px bg-primary-50 dark:bg-primary-900" />
</div>
<Blocks
{...contextProps}
@@ -1 +1,2 @@
export * from './DocumentView';
export { createHighlightingContext } from './CodeBlock';
@@ -13,7 +13,7 @@ export function FooterLinksGroup(props: {
return (
<div className={tcls('flex', 'flex-col', 'gap-3')}>
<p className={tcls('text-base', 'font-semibold')}>{group.title}</p>
<p className={tcls('text-base', 'font-medium')}>{group.title}</p>
{group.links.map((link, index) => {
return <FooterLink key={index} link={link} context={context} />;
})}
@@ -32,14 +32,7 @@ async function FooterLink(props: { link: CustomizationContentLink; context: Cont
return (
<Link
href={resolved.href}
className={tcls(
'text-sm',
'font-normal',
'text-dark/8',
'hover:text-dark/9',
'dark:text-light/8',
'dark:hover:text-light/9',
)}
className={tcls('text-sm', 'text-primary-400', 'hover:text-primary-500')}
>
{link.title}
</Link>
@@ -82,12 +82,11 @@ export function Dropdown<E extends HTMLElement>(props: {
/**
* Animated chevron to display in the dropdown button.
*/
export function DropdownChevron() {
export function DropdownChevron(props: {}) {
return (
<Icon
icon="chevron-down"
className={tcls(
'shrink-0',
'opacity-6',
'size-3',
'ms-1',
@@ -2,9 +2,9 @@ import { CustomizationSettings, Site, SiteCustomizationSettings, Space } from '@
import { CustomizationHeaderPreset } from '@gitbook/api';
import { Suspense } from 'react';
import type { SectionsList } from '@/app/(site)/fetch';
import { CONTAINER_STYLE, HEADER_HEIGHT_DESKTOP } from '@/components/layout';
import { t, getSpaceLanguage } from '@/intl/server';
import type { SectionsList } from '@/lib/api';
import { ContentRefContext } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
@@ -72,11 +72,11 @@ export function Header(props: {
)}
>
<HeaderLogo site={site} space={space} customization={customization} />
<div className="z-20">
<span>
{!hasSiteSections && isMultiVariants ? (
<SpacesDropdown space={space} spaces={spaces} />
) : null}
</div>
</span>
<HeaderLinks>
{customization.header.links.map((link, index) => {
return (
@@ -1,9 +1,9 @@
import {
CustomizationContentLink,
CustomizationHeaderLink,
CustomizationSettings,
CustomizationHeaderPreset,
SiteCustomizationSettings,
CustomizationHeaderItem,
} from '@gitbook/api';
import assertNever from 'assert-never';
@@ -21,40 +21,93 @@ import { Button, Link } from '../primitives';
export async function HeaderLink(props: {
context: ContentRefContext;
link: CustomizationHeaderItem;
link: CustomizationHeaderLink;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { context, link, customization } = props;
const target = link.to ? await resolveContentRef(link.to, context) : null;
const target = await resolveContentRef(link.to, context);
if (!target) {
return null;
}
const headerPreset = customization.header.preset;
const linkStyle = link.style ?? 'link';
const renderLink = (linkProps: DropdownButtonProps<HTMLAnchorElement>) => {
const linkStyle = link.style ?? 'link';
switch (linkStyle) {
case 'button-secondary':
case 'button-primary': {
const variant = (() => {
switch (linkStyle) {
case 'button-secondary':
return 'secondary';
case 'button-primary':
return 'primary';
default:
assertNever(linkStyle);
}
})();
return (
<Button
href={target.href}
variant={variant}
size="medium"
className={tcls(
{
'button-primary':
headerPreset === CustomizationHeaderPreset.Custom ||
headerPreset === CustomizationHeaderPreset.Bold
? tcls(
'bg-header-link-500 hover:bg-text-header-link-300 text-header-button-text',
'dark:bg-header-link-500 dark:hover:bg-text-header-link-300 dark:text-header-button-text',
)
: null,
'button-secondary': tcls(
'bg:transparent hover:bg-transparent',
'dark:bg-transparent dark:hover:bg-transparent',
'ring-header-link-500 hover:ring-header-link-300 text-header-link-500',
'dark:ring-header-link-500 dark:hover:ring-header-link-300 dark:text-header-link-500',
),
}[linkStyle],
)}
>
{link.title}
</Button>
);
}
case 'link': {
return (
<Link
{...linkProps}
href={target.href}
className={tcls(
'overflow-hidden',
'text-sm lg:text-base',
'flex flex-row items-center',
'whitespace-nowrap',
'hover:text-header-link-400 dark:hover:text-light',
headerPreset === CustomizationHeaderPreset.Default
? ['text-dark/8', 'dark:text-light/8']
: ['text-header-link-500 hover:text-header-link-400'],
)}
>
<span className={tcls('truncate')}>{link.title}</span>
{link.links && link.links.length > 0 ? <DropdownChevron /> : null}
</Link>
);
}
default:
assertNever(linkStyle);
}
};
if (link.links && link.links.length > 0) {
return (
<Dropdown
button={(buttonProps) => {
if (!target) {
return (
<HeaderItemDropdown
{...buttonProps}
headerPreset={headerPreset}
title={link.title}
/>
);
}
return (
<HeaderLinkNavItem
{...buttonProps}
linkStyle={linkStyle}
headerPreset={headerPreset}
title={link.title}
isDropdown
href={target?.href}
/>
);
}}
>
<Dropdown button={renderLink}>
<DropdownMenu>
{link.links.map((subLink, index) => (
<SubHeaderLink key={index} {...props} link={subLink} />
@@ -64,128 +117,7 @@ export async function HeaderLink(props: {
);
}
if (!target) {
return null;
}
return (
<HeaderLinkNavItem
linkStyle={linkStyle}
headerPreset={headerPreset}
title={link.title}
isDropdown={false}
href={target.href}
/>
);
}
export type HeaderLinkNavItemProps = {
linkStyle: NonNullable<CustomizationHeaderItem['style']>;
headerPreset: CustomizationHeaderPreset;
title: string;
href: string;
isDropdown: boolean;
} & DropdownButtonProps<HTMLElement>;
function HeaderLinkNavItem(props: HeaderLinkNavItemProps) {
switch (props.linkStyle) {
case 'button-secondary':
case 'button-primary':
return <HeaderItemButton {...props} linkStyle={props.linkStyle} />;
case 'link':
return <HeaderItemLink {...props} />;
default:
assertNever(props.linkStyle);
}
}
function HeaderItemButton(
props: Omit<HeaderLinkNavItemProps, 'linkStyle'> & {
linkStyle: 'button-secondary' | 'button-primary';
},
) {
const { linkStyle, headerPreset, title, href, ...rest } = props;
const variant = (() => {
switch (linkStyle) {
case 'button-secondary':
return 'secondary';
case 'button-primary':
return 'primary';
default:
assertNever(linkStyle);
}
})();
return (
<Button
href={href}
variant={variant}
size="medium"
className={tcls(
{
'button-primary':
headerPreset === CustomizationHeaderPreset.Custom ||
headerPreset === CustomizationHeaderPreset.Bold
? tcls(
'bg-header-link-500 hover:bg-text-header-link-300 text-header-button-text',
'dark:bg-header-link-500 dark:hover:bg-text-header-link-300 dark:text-header-button-text',
)
: null,
'button-secondary': tcls(
'bg:transparent hover:bg-transparent',
'dark:bg-transparent dark:hover:bg-transparent',
'ring-header-link-500 hover:ring-header-link-300 text-header-link-500',
'dark:ring-header-link-500 dark:hover:ring-header-link-300 dark:text-header-link-500',
),
}[linkStyle],
)}
{...rest}
>
{title}
</Button>
);
}
function getHeaderLinkClassName(props: { headerPreset: CustomizationHeaderPreset }) {
return tcls(
'overflow-hidden',
'text-sm lg:text-base',
'flex flex-row items-center',
'whitespace-nowrap',
'hover:text-header-link-400 dark:hover:text-light',
'truncate',
props.headerPreset === CustomizationHeaderPreset.Default
? ['text-dark/8', 'dark:text-light/8']
: ['text-header-link-500 hover:text-header-link-400'],
);
}
function HeaderItemLink(props: HeaderLinkNavItemProps) {
const { headerPreset, title, isDropdown, href, ...rest } = props;
return (
<Link href={href} className={getHeaderLinkClassName({ headerPreset })} {...rest}>
{title}
{isDropdown ? <DropdownChevron /> : null}
</Link>
);
}
function HeaderItemDropdown(
props: {
headerPreset: CustomizationHeaderPreset;
title: string;
} & DropdownButtonProps<HTMLElement>,
) {
const { headerPreset, title, ...rest } = props;
return (
<span
className={tcls(getHeaderLinkClassName({ headerPreset }), 'cursor-default')}
{...rest}
>
{title}
<DropdownChevron />
</span>
);
return renderLink({});
}
async function SubHeaderLink(props: {
@@ -1,5 +1,5 @@
import {
CustomizationHeaderItem,
CustomizationHeaderLink,
CustomizationHeaderPreset,
CustomizationSettings,
SiteCustomizationSettings,
@@ -13,13 +13,12 @@ import { tcls } from '@/lib/tailwind';
import { Dropdown, DropdownMenu, DropdownMenuItem } from './Dropdown';
import styles from './headerLinks.module.css';
/**
* Dropdown menu for header links hidden at small screen size.
*/
export function HeaderLinkMore(props: {
label: React.ReactNode;
links: CustomizationHeaderItem[];
links: CustomizationHeaderLink[];
context: ContentRefContext;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
@@ -44,7 +43,7 @@ export function HeaderLinkMore(props: {
);
return (
<div className={`${styles.linkEllipsis} items-center z-20`}>
<div className={`${styles.linkEllipsis} items-center`}>
<Dropdown button={renderButton} className="-translate-x-48 md:translate-x-0">
<DropdownMenu>
{links.map((link, index) => (
@@ -56,10 +55,10 @@ export function HeaderLinkMore(props: {
);
}
async function MoreMenuLink(props: { context: ContentRefContext; link: CustomizationHeaderItem }) {
async function MoreMenuLink(props: { context: ContentRefContext; link: CustomizationHeaderLink }) {
const { context, link } = props;
const target = link.to ? await resolveContentRef(link.to, context) : null;
const target = await resolveContentRef(link.to, context);
if (!target) {
return null;
@@ -13,7 +13,7 @@ export async function HeaderLinks({ children }: HeaderLinksProps) {
<div
className={tcls(
styles.containerHeaderlinks,
'flex justify-end items-center gap-x-2.5 mr-2.5 lg:gap-x-5 lg:mr-2.5 *:max-w-56 z-20',
'flex justify-end items-center gap-x-2.5 mr-2.5 lg:gap-x-5 lg:mr-2.5 *:max-w-56',
)}
>
{children}
@@ -1,27 +0,0 @@
'use client';
import { Transition, motion, useReducedMotion } from 'framer-motion';
import React from 'react';
import { tcls } from '@/lib/tailwind';
export function AnimatedLine({ transition }: { transition?: Transition }) {
const prefersReducedMotion = useReducedMotion();
return (
<motion.div
layout
layoutId="sections-line"
className={tcls([
'border-primary',
'border-l',
'dark:border-primary-400',
'h-full',
'absolute',
'z-20',
'-left-[5px]',
])}
transition={prefersReducedMotion ? { duration: 0 } : transition}
/>
);
}
@@ -1,12 +1,11 @@
'use client';
import { motion } from 'framer-motion';
import React from 'react';
import { useScrollActiveId } from '@/components/hooks';
import { DocumentSection } from '@/lib/document';
import { tcls } from '@/lib/tailwind';
import { AnimatedLine } from './AnimatedLine';
import { HEADER_HEIGHT_DESKTOP } from '../layout';
/**
@@ -14,13 +13,6 @@ import { HEADER_HEIGHT_DESKTOP } from '../layout';
*/
const SECTION_INTERSECTING_THRESHOLD = 0.9;
const springCurve = {
type: 'spring',
stiffness: 700,
damping: 50,
mass: 0.8,
};
export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
const { sections } = props;
@@ -36,44 +28,37 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
});
return (
<ul className={tcls('border-l', 'border-dark/2', 'dark:border-light/1', 'pl-1')}>
<ul className={tcls('border-l', 'border-dark/2', 'dark:border-light/1', 'space-y-1')}>
{sections.map((section) => (
<motion.li
key={section.id}
className={tcls('flex', 'flex-row', 'relative', 'h-fit')}
>
{activeId === section.id ? <AnimatedLine transition={springCurve} /> : null}
<li key={section.id} className={tcls('flex', 'flex-row')}>
<a
href={`#${section.id}`}
className={tcls(
'flex',
'flex-row',
'z-10',
'w-full',
'items-baseline',
'left-[-1px]',
'relative',
'text-sm',
'py-1',
'ps-3',
'pe-2',
'hover:text-primary',
'transition-all',
'duration-200',
'border-l',
'border-transparent',
section.depth > 1 ? ['ps-6', 'opacity-8'] : null,
activeId === section.id
? [
'text-primary',
'border-primary',
'dark:text-primary-400',
'dark:border-primary-400',
'opacity-[1]',
'[&>span]:bg-primary-400',
'dark:[&>span]:bg-primary-600',
'dark:[&>span]:text-dark',
]
: [
'text-neutral-500',
'dark:text-neutral-400',
'hover:text-neutral-900',
'dark:hover:text-neutral-100',
],
: '',
)}
>
{section.tag ? (
@@ -86,7 +71,7 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
{section.title}
</a>
</motion.li>
</li>
))}
</ul>
);
@@ -21,7 +21,7 @@ import { PageFooterNavigation } from './PageFooterNavigation';
import { PageHeader } from './PageHeader';
import { PreservePageLayout } from './PreservePageLayout';
import { TrackPageView } from './TrackPageView';
import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
import { DocumentView, DocumentViewSkeleton, createHighlightingContext } from '../DocumentView';
import { PageFeedbackForm } from '../PageFeedback';
import { DateRelative } from '../primitives';
@@ -49,6 +49,7 @@ export function PageBody(props: {
const asFullWidth = document ? hasFullWidthBlock(document) : false;
const language = getSpaceLanguage(customization);
const updatedAt = page.updatedAt ?? page.createdAt;
const shouldHighlightCode = createHighlightingContext();
return (
<>
@@ -99,6 +100,7 @@ export function PageBody(props: {
contentRefContext: context,
resolveContentRef: (ref, options) =>
resolveContentRef(ref, context, options),
shouldHighlightCode,
}}
/>
</React.Suspense>
@@ -11,32 +11,17 @@ export function HighlightQuery(props: {
/** Style to apply on matching parts (default to primary) */
highlight?: ClassValue;
}): React.ReactElement {
const {
query,
text,
highlight = [
'text-bold',
'bg-primary-100',
'text-contrast-primary-100',
'dark:bg-primary-700',
'dark:text-contrast-primary-700',
'px-0.5',
'-mx-0.5',
'py-0.5',
'rounded',
'straight-corners:rounded-sm',
],
} = props;
const { query, text, highlight = ['text-bold', 'text-primary'] } = props;
const matches = matchString(text, query);
return (
<div className={tcls('whitespace-break-spaces')}>
<span className={tcls('whitespace-break-spaces')}>
{matches.map((entry, index) => (
<span key={index} className={tcls(entry.match ? highlight : null)}>
{entry.text}
</span>
))}
</div>
</span>
);
}
@@ -101,12 +101,20 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
const loading = (
<div className={tcls('w-full', 'flex', 'items-center', 'justify-center')}>
<Loading className={tcls('w-6', 'py-8', 'text-primary')} />
<Loading className={tcls('w-5', 'py-4', 'text-primary')} />
</div>
);
return (
<div className={tcls('max-h-[60vh]', 'overflow-y-auto')}>
<div
className={tcls(
'max-h-[60vh]',
'overflow-y-auto',
'border-t',
'border-dark/2',
'dark:border-light/1',
)}
>
{state?.type === 'answer' ? (
<>
{state.answer ? (
@@ -158,20 +166,13 @@ function AnswerBody(props: { answer: AskAnswerResult }) {
<>
<div
data-test="search-ask-answer"
className={tcls(
'mt-4',
'sm:mt-6',
'px-4',
'sm:px-12',
'text-dark/9',
'dark:text-light/8',
)}
className={tcls('mt-4', 'px-4', 'text-dark/9', 'dark:text-light/8')}
>
{answer.hasAnswer ? answer.body : t(language, 'search_ask_no_answer')}
{answer.followupQuestions.length > 0 ? (
<AnswerFollowupQuestions followupQuestions={answer.followupQuestions} />
) : null}
</div>
{answer.followupQuestions.length > 0 ? (
<AnswerFollowupQuestions followupQuestions={answer.followupQuestions} />
) : null}
{answer.sources.length > 0 ? (
<AnswerSources
hasAnswer={answer.hasAnswer}
@@ -188,25 +189,23 @@ function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
const getSearchLinkProps = useSearchLink();
return (
<div className={tcls('flex', 'flex-col', 'flex-wrap', 'mt-4', 'sm:mt-6')}>
<div className={tcls('mt-7 mb-4', 'flex', 'flex-col', 'flex-wrap', 'gap-1')}>
{followupQuestions.map((question) => (
<Link
key={question}
className={tcls(
'flex',
'items-center',
'text-sm',
'font-medium',
'inline-flex',
'items-start',
'gap-2',
'px-4',
'-mx-4',
'py-2',
'rounded',
'straight-corners:rounded-none',
'text-dark/7',
'dark:text-light/8',
'hover:bg-dark-4/2',
'dark:hover:bg-light-4/2',
'focus-within:bg-dark-4/2',
'dark:focus-within:bg-light-4/2',
'py-1',
'text-primary-500',
'focus-within:text-primary-700',
'hover:bg-primary/2',
'dark:text-primary-400',
'dark:hover:bg-primary-500/3',
)}
{...getSearchLinkProps({
query: question,
@@ -215,13 +214,7 @@ function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
>
<Icon
icon="magnifying-glass"
className={tcls(
'size-4',
'shrink-0',
'mr-2',
'text-dark/5',
'dark:text-light/5',
)}
className={tcls('size-[15px]', 'shrink-0', 'mt-0.5', '[opacity:0.64]')}
/>
<span>{question}</span>
</Link>
@@ -243,8 +236,7 @@ function AnswerSources(props: {
'flex',
'flex-wrap',
'gap-2',
'mt-4',
'sm:mt-6',
'mt-7',
'py-4',
'px-4',
'border-t',
@@ -252,7 +244,7 @@ function AnswerSources(props: {
'dark:border-light/1',
)}
>
<span>
<span className={tcls('text-sm')}>
{t(language, hasAnswer ? 'search_ask_sources' : 'search_ask_sources_no_answer')}
</span>
@@ -261,9 +253,7 @@ function AnswerSources(props: {
<Link
className={tcls(
'flex',
'flex-wrap',
'gap-1',
'items-center',
'text-sm',
'text-dark/7',
'hover:underline',
'focus-within:text-primary-700',
@@ -276,8 +266,11 @@ function AnswerSources(props: {
icon="arrow-up-right"
className={tcls(
'text-dark/6',
'size-4',
'w-[15px]',
'h-[15px]',
'shrink-0',
'mt-0.5',
'mr-0.5',
'dark:text-light/6',
)}
/>
@@ -182,7 +182,7 @@ function SearchModalBody(
};
return (
<motion.div
<div
role="dialog"
aria-label={tString(language, 'search')}
className={tcls(
@@ -193,55 +193,29 @@ function SearchModalBody(
'max-w-[768px]',
'mt-[-1px]',
'w-full',
'max-h',
'rounded-lg',
'straight-corners:rounded-sm',
'ring-1',
'ring-dark/1',
'shadow-2xl',
'backdrop-blur-lg',
'overflow-hidden',
'dark:ring-inset',
'dark:bg-dark-3',
'dark:ring-light/2',
)}
initial={{
scale: 0.95,
opacity: 0,
}}
animate={{
scale: 1,
opacity: 1,
}}
onClick={(event) => {
event.stopPropagation();
}}
>
<div
className={tcls(
'flex',
'flex-row',
'items-start',
state.query !== null ? 'border-b' : null,
'border-dark/2',
'dark:border-light/2',
)}
>
<div className={tcls('p-2', 'pl-4', 'pt-4')}>
<div className={tcls('flex', 'flex-row', 'items-center')}>
<div className={tcls('p-2', 'pl-4')}>
<Icon
icon="magnifying-glass"
className={tcls('size-4', 'text-dark/4', 'dark:text-light/5')}
/>
</div>
<div
className={tcls(
'w-full',
'flex',
'flex-row',
'flex-wrap',
'gap-y-0',
'gap-x-4',
'items-end',
)}
>
<div className={tcls('flex-1')}>
<input
ref={inputRef}
value={state.query}
@@ -252,7 +226,7 @@ function SearchModalBody(
'placeholder:text-dark/7',
'flex',
'resize-none',
'flex-1',
'w-full',
'h-12',
'p-2',
'focus:outline-none',
@@ -269,7 +243,6 @@ function SearchModalBody(
autoComplete="off"
autoCorrect="off"
/>
{isMultiVariants ? <SearchScopeToggle spaceTitle={spaceTitle} /> : null}
</div>
</div>
{!state.ask || !withAsk ? (
@@ -288,11 +261,15 @@ function SearchModalBody(
global: state.global,
});
}}
></SearchResults>
>
{isMultiVariants && state.query ? (
<SearchScopeToggle spaceTitle={spaceTitle} />
) : null}
</SearchResults>
) : null}
{state.query && state.ask && withAsk ? (
<SearchAskAnswer spaceId={spaceId} query={state.query} />
) : null}
</motion.div>
</div>
);
}
@@ -1,4 +1,3 @@
import { Icon } from '@gitbook/icons';
import React from 'react';
import { tcls } from '@/lib/tailwind';
@@ -24,46 +23,25 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
className={tcls(
'flex',
'flex-row',
'items-center',
'px-4',
'sm:px-12',
'py-4',
'sm:py-6',
'border-t',
'first:border-t-0',
'border-dark/2',
'dark:border-light/2',
'px-6',
'py-3',
'hover:bg-dark-4/2',
'text-base',
'text-dark',
'font-medium',
'font-semibold',
'first:mt-0',
'[&:has(+.search-section-result-item):not(:first-child)]:mt-6',
'dark:text-light',
'dark:hover:bg-light-4/2',
active ? ['bg-dark/1', 'dark:bg-light/1'] : null,
)}
>
<div className={tcls('flex', 'flex-col', 'w-full')}>
{item.spaceTitle ? (
<div
className={tcls(
'text-xs',
'opacity-6',
'font-normal',
'uppercase',
'tracking-wider',
'mb-1',
)}
>
{item.spaceTitle}
</div>
) : null}
<HighlightQuery query={query} text={item.title} />
</div>
<Icon
icon="chevron-right"
className={tcls('size-4', 'text-dark', 'dark:text-light', 'opacity-6')}
/>
{item.spaceTitle ? (
<span className={tcls('opacity-6', 'font-normal', 'mr-2')}>
{item.spaceTitle + ' '}
</span>
) : null}
<HighlightQuery query={query} text={item.title} />
</Link>
);
});
@@ -31,6 +31,8 @@ export const SearchQuestionResultItem = React.forwardRef(function SearchQuestion
'py-2',
'hover:bg-dark-4/2',
'text-dark/7',
'text-sm',
'font-medium',
'first:mt-0',
'last:pb-3',
'dark:text-light/8',
@@ -45,11 +47,11 @@ export const SearchQuestionResultItem = React.forwardRef(function SearchQuestion
<Icon
icon="magnifying-glass"
className={tcls(
'size-4',
'w-[15px]',
'h-[15px]',
'shrink-0',
'mt-0.5',
'mr-4',
'mt-1',
'text-dark/5',
'dark:text-light/5',
)}
@@ -174,15 +174,24 @@ export const SearchResults = React.forwardRef(function SearchResults(
}
return (
<div className={tcls('max-h-[70vh]', 'overflow-auto', 'relative')}>
<div
className={tcls(
'max-h-[60vh]',
'overflow-auto',
'relative',
'shadow-[0_1px_0_0_inset]',
'shadow-dark/2',
'dark:shadow-light/2',
)}
>
{children}
{results.length === 0 ? (
<div
data-test="search-noresults"
className={tcls(
'text',
'text-dark/8',
'p-8',
'text-sm',
'text-dark',
'p-6',
'text-center',
'dark:text-light/8',
)}
@@ -20,7 +20,31 @@ export function SearchScopeToggle(props: { spaceTitle: string }) {
<div
role="toolbar"
aria-orientation="horizontal"
className={tcls('flex', 'flex-row', 'mr-4')}
className={tcls(
'overflow-x-auto',
'hide-scroll',
'flex',
'flex-row',
'py-3',
'gap-0',
'px-0',
'pt-0',
'sticky',
'z-[0]',
'w-[calc(100%-1px)]',
'left-[1px]',
'top-[0px]',
'bg-gradient-to-b',
'from-white',
'to-transparent',
'from-60%',
'dark:from-dark-3',
'shadow-[0_1px_0_0_inset]',
'shadow-dark/2',
'dark:shadow-light/2',
'md:px-6',
'md:gap-3',
)}
>
<ToggleButton
active={!state.global}
@@ -57,14 +81,30 @@ function ToggleButton(props: { onClick: () => void; children: React.ReactNode; a
aria-selected={active}
onClick={onClick}
className={tcls(
'text-sm',
'text-xs',
'transition-colors',
'px-3',
'py-2',
'border-b-2',
'duration-75',
'px-2.5',
'py-1.5',
'border-t',
'relative',
'top-[0px]',
'z-[1]',
'border-dark/2',
'whitespace-pre',
'-mb-[1px]',
active ? ['text-primary-500', 'border-primary-500'] : ['border-transparent'],
'hover:border-dark/6',
'dark:hover:border-light/6',
'md:px-1',
active
? [
'text-primary-400',
'border-primary-400',
'hover:border-primary-400',
'dark:hover:text-primary-400',
'dark:border-primary-400',
'dark:hover:border-primary-400',
]
: null,
)}
>
{children}
@@ -25,29 +25,15 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
'[&:has(+:not(&))]:mb-6',
'flex',
'flex-col',
'mb-2',
'px-4',
'sm:px-12',
'pl-6',
'hover:bg-dark-4/2',
'dark:hover:bg-light-4/2',
'text-dark/8',
'dark:text-light/8',
'font-normal',
'transition-colors',
active ? ['bg-dark/1', 'dark:bg-light/1'] : null,
)}
>
<div
className={tcls(
'border-l-2',
'px-4',
'py-2',
'border-dark/2',
'dark:border-light/2',
)}
>
<div className={tcls('border-l', 'p-3', 'border-dark/2', 'dark:border-light/2')}>
{item.title ? (
<p className={tcls('text-base', 'mb-2')}>
<p className={tcls('text-base', 'text-dark/7', 'dark:text-light/8')}>
<HighlightQuery query={query} text={item.title} />
</p>
) : null}
@@ -55,9 +41,12 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
<p
className={tcls(
'text-sm',
'line-clamp-3',
'text-dark',
'line-clamp-6',
'linear-mask-gradient',
'z-[-1]', //to force stacking order
'relative',
'dark:text-light/8',
)}
>
<HighlightQuery query={query} text={item.body} />
@@ -68,11 +68,16 @@ async function searchSiteContent(args: {
scope.mode === 'current' ||
(scope.mode === 'specific' && scope.siteSpaceIds.length > 1);
const [searchResults, siteData] = await Promise.all([
const [searchResults, siteStructure] = await Promise.all([
api.searchSiteContent(pointer.organizationId, pointer.siteId, query, scope, cacheBust),
needsStructure ? api.getSiteData(pointer) : null,
needsStructure
? api.getSiteStructure({
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
})
: null,
]);
const siteStructure = siteData?.structure;
const siteSpaces = siteStructure
? siteStructure.type === 'siteSpaces'
@@ -82,7 +87,7 @@ async function searchSiteContent(args: {
...siteSpace,
space: {
...siteSpace.space,
title: section.title || siteSpace.space.title,
title: section.title + ' ' + siteSpace.space.title,
},
}));
@@ -210,6 +215,7 @@ function transformAnswer(
mode: 'default',
contentRefContext: null,
resolveContentRef: async () => null,
shouldHighlightCode: () => true,
wrapBlocksInSuspense: false,
}}
style={['space-y-5']}
@@ -1,21 +0,0 @@
import type { SiteSection } from '@gitbook/api';
import { Icon, type IconName } from '@gitbook/icons';
import { type ClassValue, tcls } from '@/lib/tailwind';
/**
* Icon shown beside a section in the site section tabs.
*/
export function SectionIcon(props: { icon: IconName; isActive: boolean }) {
const { icon, isActive } = props;
return (
<Icon
icon={icon}
className={tcls(
'size-[1em] text-inherit opacity-8',
isActive && 'text-inherit opacity-10',
)}
/>
);
}
@@ -1,13 +1,10 @@
'use client';
import type { SiteSection } from '@gitbook/api';
import type { IconName } from '@gitbook/icons';
import { SiteSection } from '@gitbook/api';
import React from 'react';
import { tcls } from '@/lib/tailwind';
import { Link } from '../primitives';
import { SectionIcon } from './SectionIcon';
/**
* A set of navigational tabs representing site sections for multi-section sites
@@ -17,7 +14,13 @@ export function SiteSectionTabs(props: {
section: SiteSection;
index: number;
}) {
const { list: sections, index: currentIndex } = props;
const { list: sections, section: currentSection, index: currentIndex } = props;
const tabs = sections.map((section) => ({
id: section.id,
label: section.title,
path: section.urls.published ?? '',
}));
const currentTabRef = React.useRef<HTMLAnchorElement>(null);
const navRef = React.useRef<HTMLDivElement>(null);
@@ -40,9 +43,7 @@ export function SiteSectionTabs(props: {
}, []);
React.useEffect(() => {
if (currentIndex >= 0) {
updateTabDimensions();
}
updateTabDimensions();
}, [currentIndex, updateTabDimensions]);
React.useLayoutEffect(() => {
@@ -54,11 +55,11 @@ export function SiteSectionTabs(props: {
};
}, [updateTabDimensions]);
const opacity = tabDimensions ? 1 : 0.0;
const opacity = Boolean(tabDimensions) ? 1 : 0.0;
const scale = (tabDimensions?.width ?? 0) * 0.01;
const startPos = `${tabDimensions?.left ?? 0}px`;
return sections.length > 0 ? (
return tabs.length > 0 ? (
<nav
aria-label="Sections"
ref={navRef}
@@ -83,24 +84,15 @@ export function SiteSectionTabs(props: {
'md:px-5',
)}
>
{sections.map((section, index) => {
const { id, urls, title, icon } = section;
const isActive = index === currentIndex;
return (
<Tab
active={isActive}
key={id}
label={title}
href={urls.published ?? ''}
ref={isActive ? currentTabRef : null}
icon={
icon ? (
<SectionIcon isActive={isActive} icon={icon as IconName} />
) : null
}
/>
);
})}
{tabs.map((tab, index) => (
<Tab
active={currentIndex === index}
key={index + tab.path}
label={tab.label}
href={tab.path}
ref={currentIndex === index ? currentTabRef : null}
/>
))}
</div>
{/* A container for a pseudo element for active tab indicator. A container is needed so we can set
a relative position without breaking the z-index of other parts of the header. */}
@@ -125,7 +117,7 @@ export function SiteSectionTabs(props: {
'after:bg-primary',
'dark:after:bg-primary-400',
)}
/>
></div>
</div>
</nav>
) : null;
@@ -134,26 +126,24 @@ export function SiteSectionTabs(props: {
/**
* The tab item - a link to a site section
*/
const Tab = React.forwardRef<
HTMLSpanElement,
{ active: boolean; href: string; icon?: React.ReactNode; label: string }
>(function Tab(props, ref) {
const { active, href, icon, label } = props;
return (
<Link
className={tcls(
'group/tab px-3 py-1 my-2 rounded straight-corners:rounded-none transition-colors',
active && 'text-primary dark:text-primary-400',
!active &&
'text-dark/8 hover:bg-dark/1 hover:text-dark/9 dark:text-light/8 dark:hover:bg-light/2 dark:hover:text-light/9',
)}
role="tab"
href={href}
>
<span ref={ref} className={tcls('flex gap-2 items-center w-full truncate')}>
{icon}
{label}
</span>
</Link>
);
});
const Tab = React.forwardRef<HTMLSpanElement, { active: boolean; href: string; label: string }>(
function Tab(props, ref) {
const { active, href, label } = props;
return (
<Link
className={tcls(
'px-3 py-1 my-2 rounded straight-corners:rounded-none transition-colors',
active && 'text-primary dark:text-primary-400',
!active &&
'text-dark/8 hover:bg-dark/1 hover:text-dark/9 dark:text-light/8 dark:hover:bg-light/2 dark:hover:text-light/9',
)}
role="tab"
href={href}
>
<span ref={ref} className={tcls('inline-flex w-full truncate')}>
{label}
</span>
</Link>
);
},
);
@@ -10,13 +10,14 @@ import {
} from '@gitbook/api';
import React from 'react';
import { SectionsList } from '@/app/(site)/fetch';
import { Footer } from '@/components/Footer';
import { CompactHeader, Header } from '@/components/Header';
import { CONTAINER_STYLE } from '@/components/layout';
import { ColorDebugger } from '@/components/primitives/ColorDebugger';
import { SearchModal } from '@/components/Search';
import { TableOfContents } from '@/components/TableOfContents';
import { ContentTarget, type SectionsList, SiteContentPointer } from '@/lib/api';
import { ContentTarget, SiteContentPointer } from '@/lib/api';
import { ContentRefContext } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
@@ -8,16 +8,13 @@ import { useHash } from './useHash';
* to the top of the page when navigating between pages (pathname)
* or sections of a page (hash).
*/
export function useScrollPage(props: { scrollMarginTop?: number }) {
export function useScrollPage() {
const hash = useHash();
const pathname = usePathname();
React.useLayoutEffect(() => {
if (hash) {
const element = document.getElementById(hash);
if (element) {
if (props.scrollMarginTop) {
element.style.scrollMarginTop = `${props.scrollMarginTop}px`;
}
element.scrollIntoView({
block: 'start',
behavior: 'smooth',
@@ -26,13 +23,5 @@ export function useScrollPage(props: { scrollMarginTop?: number }) {
} else {
window.scrollTo(0, 0);
}
return () => {
if (hash) {
const element = document.getElementById(hash);
if (element) {
element.style.scrollMarginTop = '';
}
}
};
}, [hash, pathname, props.scrollMarginTop]);
}, [hash, pathname]);
}
@@ -1,25 +1,25 @@
'use client';
import type { ComponentPropsWithoutRef, HTMLAttributes } from 'react';
import { tcls, ClassValue } from '@/lib/tailwind';
import { Link } from './Link';
type ButtonProps = {
href?: string;
onClick?: () => void;
children: React.ReactNode;
variant?: 'primary' | 'secondary';
size?: 'default' | 'medium' | 'small';
className?: ClassValue;
} & HTMLAttributes<HTMLElement>;
};
export function Button({
href,
onClick,
children,
variant = 'primary',
size = 'default',
className,
...rest
}: ButtonProps) {
const variantClasses =
variant === 'primary'
@@ -69,14 +69,14 @@ export function Button({
if (href) {
return (
<Link href={href} className={domClassName} {...rest}>
<Link href={href} className={domClassName}>
{children}
</Link>
);
}
return (
<button type="button" className={domClassName} {...rest}>
<button type="button" onClick={onClick} className={domClassName}>
{children}
</button>
);
+1 -1
View File
@@ -10,7 +10,7 @@ export const de = {
search_input_placeholder: 'Inhalt durchsuchen',
search_ask_input_placeholder: 'Inhalt durchsuchen oder eine Frage stellen',
search_no_results: 'Keine Ergebnisse für "${1}".',
search_scope_space: '${1}',
search_scope_space: 'Nur in ${1}',
search_scope_all: 'Alle Inhalte',
search_ask: 'Fragen "${1}"',
search_ask_sources: 'Quellen',
+2 -2
View File
@@ -10,8 +10,8 @@ export const en = {
search_input_placeholder: 'Search content',
search_ask_input_placeholder: 'Search content or ask a question',
search_no_results: 'No results for "${1}".',
search_scope_space: '${1}',
search_scope_all: 'All content',
search_scope_space: 'Only in ${1}',
search_scope_all: 'All the content',
search_ask: 'Ask "${1}"',
search_ask_sources: 'Sources',
search_ask_sources_no_answer: 'Related pages',
+1 -1
View File
@@ -12,7 +12,7 @@ export const es: TranslationLanguage = {
search_input_placeholder: 'Buscar contenido',
search_ask_input_placeholder: 'Buscar contenido o hacer una pregunta',
search_no_results: 'No hay resultados para "${1}".',
search_scope_space: '${1}',
search_scope_space: 'Solo en ${1}',
search_scope_all: 'Todo el contenido',
search_ask: 'Preguntar "${1}"',
search_ask_sources: 'Fuentes',
+1 -1
View File
@@ -12,7 +12,7 @@ export const fr: TranslationLanguage = {
search_input_placeholder: 'Rechercher le contenu',
search_ask_input_placeholder: 'Rechercher du contenu ou poser une question',
search_no_results: 'Aucun résultat pour "${1}".',
search_scope_space: '${1}',
search_scope_space: 'Uniquement dans ${1}',
search_scope_all: 'Tout le contenu',
search_ask: 'Demander "${1}"',
search_ask_sources: 'Sources',
+1 -1
View File
@@ -12,7 +12,7 @@ export const ja: TranslationLanguage = {
search_input_placeholder: 'コンテンツを検索',
search_ask_input_placeholder: 'コンテンツを検索するか質問をする',
search_no_results: '"${1}" の結果はありません。',
search_scope_space: '${1}',
search_scope_space: '${1}内のみ',
search_scope_all: '全てのコンテンツ',
search_ask: '"${1}" を質問する',
search_ask_sources: '情報源',
+1 -1
View File
@@ -12,7 +12,7 @@ export const nl: TranslationLanguage = {
search_input_placeholder: 'Zoek inhoud',
search_ask_input_placeholder: 'Zoek inhoud of stel een vraag',
search_no_results: 'Geen resultaten voor "${1}".',
search_scope_space: '${1}',
search_scope_space: 'Alleen in ${1}',
search_scope_all: 'Alle inhoud',
search_ask: 'Vraag "${1}"',
search_ask_sources: 'Bronnen',
+1 -1
View File
@@ -12,7 +12,7 @@ export const no: TranslationLanguage = {
search_input_placeholder: 'Søk i innhold',
search_ask_input_placeholder: 'Søk i innhold eller still et spørsmål',
search_no_results: 'Ingen resultater for "${1}".',
search_scope_space: '${1}',
search_scope_space: 'Kun i ${1}',
search_scope_all: 'Alt innhold',
search_ask: 'Spør "${1}"',
search_ask_sources: 'Kilder',
@@ -10,7 +10,7 @@ export const pt_br = {
search_input_placeholder: 'Buscar conteúdo',
search_ask_input_placeholder: 'Buscar conteúdo ou fazer uma pergunta',
search_no_results: 'Sem resultados para "${1}".',
search_scope_space: '${1}',
search_scope_space: 'Somente em ${1}',
search_scope_all: 'Todo o conteúdo',
search_ask: 'Perguntar "${1}"',
search_ask_sources: 'Fontes',
+1 -1
View File
@@ -12,7 +12,7 @@ export const zh: TranslationLanguage = {
search_input_placeholder: '搜索内容',
search_ask_input_placeholder: '搜索内容或提问',
search_no_results: '没有找到"${1}"的结果。',
search_scope_space: '${1}',
search_scope_space: '仅在${1}',
search_scope_all: '所有内容',
search_ask: '询问"${1}"',
search_ask_sources: '来源',
+199 -128
View File
@@ -13,15 +13,11 @@ import {
RevisionFile,
SiteCustomizationSettings,
RevisionReusableContent,
SiteSpace,
Space,
SiteSection,
PublishedSiteContent,
} from '@gitbook/api';
import assertNever from 'assert-never';
import { headers } from 'next/headers';
import rison from 'rison';
import { assert, DeepPartial } from 'ts-essentials';
import { DeepPartial } from 'ts-essentials';
import { batch } from './async';
import { buildVersion } from './build';
@@ -135,10 +131,22 @@ export function withAPI<T>(client: GitBookAPI, fn: () => Promise<T>): Promise<T>
return apiSyncStorage.run(client, fn);
}
type SpaceContentLookup = Pick<
PublishedSiteContent,
'space' | 'changeRequest' | 'revision' | 'pathname' | 'basePath' | 'apiToken'
> & { kind: 'space' };
// FIXME: Fix @gitbook/api types for PublishedSiteContentLookup
type SpaceContentLookup = {
kind: 'space';
/** ID of the space matching. */
space: string;
/** Identifier of the change request being previewed in this URL. */
changeRequest?: string;
/** Identifier of the revision being previewed in this URL. */
revision?: string;
/** Path of the content relative to the space */
pathname: string;
/** Prefix of the path in the URL dedicated to the space */
basePath: string;
/** Short-lived API token to fetch content related to the space in the context of the URL. */
apiToken: string;
};
export type PublishedContentWithCache =
| ((SpaceContentLookup | PublishedSiteContentLookup) & {
@@ -621,48 +629,83 @@ export const getDocument = cache({
});
/**
* Resolve a site redirect by its source path.
* Get the customization settings for a site-space from the API.
*/
export const getSiteRedirectBySource = cache({
name: 'api.getSiteRedirectBySource',
tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }),
const getSiteSpaceCustomizationFromAPI = cache({
name: 'api.getSiteSpaceCustomizationById',
tag: (organizationId, siteId, siteSpaceId) => getAPICacheTag({ tag: 'site', site: siteId }),
get: async (
args: {
organizationId: string;
siteId: string;
/** Site share key that can be used as context to resolve site space published urls */
siteShareKey: string | undefined;
source: string;
},
organizationId: string,
siteId: string,
siteSpaceId: string,
options: CacheFunctionOptions,
) => {
try {
const response = await api().orgs.getSiteRedirectBySource(
args.organizationId,
args.siteId,
{
shareKey: args.siteShareKey,
source: args.source,
},
{
...noCacheFetchOptions,
signal: options.signal,
},
);
return cacheResponse(response, cacheTtl_1day);
} catch (error) {
if ((error as GitBookAPIError).code === 404) {
return {
data: null,
...cacheTtl_1day,
};
}
throw error;
}
const response = await api().orgs.getSiteSpaceCustomizationById(
organizationId,
siteId,
siteSpaceId,
{},
{
signal: options.signal,
...noCacheFetchOptions,
},
);
return cacheResponse(response, {
revalidateBefore: 60 * 60,
});
},
});
/**
* Get the customization settings for a site from the API.
*/
const getSiteCustomizationFromAPI = cache({
name: 'api.getSiteCustomizationById',
tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }),
get: async (organizationId: string, siteId: string, options: CacheFunctionOptions) => {
const response = await api().orgs.getSiteCustomizationById(
organizationId,
siteId,
{},
{
signal: options.signal,
...noCacheFetchOptions,
},
);
return cacheResponse(response, {
revalidateBefore: 60 * 60,
});
},
});
/**
* Get the customization settings for a site space from the API.
*/
async function getSiteSpaceCustomization(args: {
organizationId: string;
siteId: string;
siteSpaceId: string;
}): Promise<SiteCustomizationSettings> {
const raw = await getSiteSpaceCustomizationFromAPI(
args.organizationId,
args.siteId,
args.siteSpaceId,
);
return mergeCustomizationWithExtend(raw);
}
/**
* Get the customization settings for a site space from the API.
*/
async function getSiteCustomization(args: {
organizationId: string;
siteId: string;
}): Promise<SiteCustomizationSettings> {
const raw = await getSiteCustomizationFromAPI(args.organizationId, args.siteId);
return mergeCustomizationWithExtend(raw);
}
/**
* Get the infos about a site by its ID.
*/
@@ -681,24 +724,59 @@ export const getSite = cache({
});
/**
* Get the published content site data for a site's published experience
* List all the site-spaces variants published in a site.
*/
export const getPublishedContentSite = cache({
name: 'api.getPublishedContentSite',
export const getSiteSpaces = cache({
name: 'api.getSiteSpaces',
tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }),
get: async (
args: {
organizationId: string;
siteId: string /** Site share key that can be used as context to resolve site space published urls */;
siteId: string;
/** Site share key that can be used as context to resolve site space published urls */
siteShareKey: string | undefined;
},
options: CacheFunctionOptions,
) => {
const response = await api().orgs.getPublishedContentSite(
const response = await getAll((params) =>
api().orgs.listSiteSpaces(
args.organizationId,
args.siteId,
{
...params,
...(args.siteShareKey ? { shareKey: args.siteShareKey } : {}),
},
{
...noCacheFetchOptions,
signal: options.signal,
},
),
);
return cacheResponse(response, {
revalidateBefore: 60 * 60,
data: response.data.items.map((siteSpace) => siteSpace),
});
},
});
export const getSiteStructure = cache({
name: 'api.getSiteStructure',
tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }),
get: async (
args: {
organizationId: string;
siteId: string;
/** Site share key that can be used as context to resolve site space published urls */
siteShareKey: string | undefined;
},
options: CacheFunctionOptions,
) => {
const response = await api().orgs.getSiteStructure(
args.organizationId,
args.siteId,
{
shareKey: args.siteShareKey,
...(args.siteShareKey ? { shareKey: args.siteShareKey } : {}),
},
{
...noCacheFetchOptions,
@@ -707,96 +785,89 @@ export const getPublishedContentSite = cache({
);
return cacheResponse(response, {
revalidateBefore: 60 * 60,
data: response.data,
});
},
});
export type SectionsList = { list: SiteSection[]; section: SiteSection; index: number };
/**
* List the scripts to load for the site.
*/
export const getSiteIntegrationScripts = cache({
name: 'api.getSiteIntegrationScripts',
tag: (organizationId, siteId) => getAPICacheTag({ tag: 'site', site: siteId }),
get: async (organizationId: string, siteId: string, options: CacheFunctionOptions) => {
const response = await api().orgs.listSiteIntegrationScripts(organizationId, siteId, {
...noCacheFetchOptions,
signal: options.signal,
});
return cacheResponse(response, {
revalidateBefore: 60 * 60,
});
},
});
/**
* Parse the site spaces into a list of spaces with their title and urls.
* Fetch all the data to render the current site at once.
*/
export function parseSpacesFromSiteSpaces(siteSpaces: SiteSpace[]) {
const spaces: Record<string, Space> = {};
siteSpaces.forEach((siteSpace) => {
spaces[siteSpace.space.id] = {
...siteSpace.space,
title: siteSpace.title ?? siteSpace.space.title,
urls: {
...siteSpace.space.urls,
published: siteSpace.urls.published,
},
};
});
return Object.values(spaces);
}
export async function getSiteData(pointer: SiteContentPointer) {
const [{ space, pages, contentTarget }, { customization, scripts }] = await Promise.all([
getSpaceContentData(pointer, pointer.siteShareKey),
getSiteLayoutData(pointer),
]);
function parseSiteSectionsList(siteSectionId: string, sections: SiteSection[]) {
const section = sections.find((section) => section.id === siteSectionId);
assert(section, 'A section must be defined when there are multiple sections');
return { list: sections, section, index: sections.indexOf(section) } satisfies SectionsList;
}
/**
* This function fetches the published content site data to render the published
* experience for the site (structure, customizations, scripts etc)
*/
export async function getSiteData(
pointer: Pick<
SiteContentPointer,
'organizationId' | 'siteId' | 'siteSectionId' | 'siteSpaceId' | 'siteShareKey'
>,
) {
const {
site: orgSite,
structure: siteStructure,
customizations,
return {
space,
pages,
contentTarget,
customization,
scripts,
} = await getPublishedContentSite({
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
});
const siteSections =
siteStructure.type === 'sections' && siteStructure.structure
? siteStructure.structure
: null;
const siteSpaces =
siteStructure.type === 'siteSpaces' && siteStructure.structure
? parseSpacesFromSiteSpaces(siteStructure.structure)
: null;
// override the title with the customization title
const site = {
...orgSite,
...(customizations.site?.title ? { title: customizations.site.title } : {}),
};
}
const sections =
pointer.siteSectionId && siteSections
? parseSiteSectionsList(pointer.siteSectionId, siteSections)
: null;
const spaces =
siteSpaces ?? (sections ? parseSpacesFromSiteSpaces(sections.section.siteSpaces) : []);
const customization = mergeCustomizationWithExtend(
pointer.siteSpaceId ? customizations.siteSpaces[pointer.siteSpaceId] : customizations.site,
);
/**
* Fetch all the layout data about the current site at once.
*/
export async function getSiteLayoutData(args: {
organizationId: string;
siteId: string;
siteSpaceId: string | undefined;
}) {
const [customization, scripts] = await Promise.all([
getCurrentSiteCustomization(args),
getSiteIntegrationScripts(args.organizationId, args.siteId),
]);
return {
customization,
site,
structure: siteStructure,
sections,
spaces,
scripts,
};
}
/**
* Get the customization settings for the current site from the API.
*/
export async function getCurrentSiteCustomization(args: {
organizationId: string;
siteId: string;
siteSpaceId: string | undefined;
}): Promise<SiteCustomizationSettings> {
return args.siteSpaceId
? getSiteSpaceCustomization({
organizationId: args.organizationId,
siteId: args.siteId,
siteSpaceId: args.siteSpaceId,
})
: getSiteCustomization({
organizationId: args.organizationId,
siteId: args.siteId,
});
}
/**
* Get the customization settings for a space from the API.
*/
export function getSpaceCustomization(spaceId: string): { customization: CustomizationSettings } {
export async function getSpaceCustomization(spaceId: string): Promise<CustomizationSettings> {
const headersList = headers();
const raw = defaultCustomizationForSpace();
@@ -804,7 +875,7 @@ export function getSpaceCustomization(spaceId: string): { customization: Customi
if (extend) {
try {
const parsed = rison.decode_object<Partial<CustomizationSettings>>(extend);
return { customization: { ...raw, ...parsed } };
return { ...raw, ...parsed };
} catch (error) {
console.error(
`Failed to parse x-gitbook-customization header (ignored): ${
@@ -814,9 +885,7 @@ export function getSpaceCustomization(spaceId: string): { customization: Customi
}
}
return {
customization: raw,
};
return raw;
}
/**
@@ -877,11 +946,13 @@ export async function getSpaceContentData(
spaceId: pointer.spaceId,
revisionId: changeRequest?.revision ?? pointer.revisionId ?? space.revision,
};
const pages = await getRevisionPages(space.id, contentTarget.revisionId, {
// We only care about the Git metadata when the Git sync is enabled
// otherwise we can optimize performance by not fetching it
metadata: !!space.gitSync,
});
const [pages] = await Promise.all([
getRevisionPages(space.id, contentTarget.revisionId, {
// We only care about the Git metadata when the Git sync is enabled
// otherwise we can optimize performance by not fetching it
metadata: !!space.gitSync,
}),
]);
return {
space,
+1 -1
View File
@@ -54,7 +54,7 @@ export function getContentSecurityPolicy(scripts: SpaceIntegrationScript[], nonc
object-src 'none';
base-uri 'self' ${assetsDomain};
form-action 'self' ${assetsDomain};
frame-ancestors https: ${process.env.NODE_ENV !== 'production' ? 'http:' : ''};
frame-ancestors https:;
`;
const result = scripts
+28 -28
View File
@@ -4,7 +4,7 @@ import fnv1a from '@sindresorhus/fnv1a';
import { noCacheFetchOptions } from '@/lib/cache/http';
import { host, rootUrl } from './links';
import { rootUrl } from './links';
import { getImageAPIUrl } from './urls';
export interface CloudflareImageJsonFormat {
@@ -31,8 +31,6 @@ export interface CloudflareImageOptions {
quality?: number;
}
export const imagesResizingSignVersion = '2';
/**
* Return true if images resizing is enabled.
*/
@@ -55,26 +53,17 @@ export function checkIsHttpURL(input: string | URL): boolean {
* Check if an image URL is resizable.
* Skip it for non-http(s) URLs (data, etc).
* Skip it for SVGs.
* Skip it for GitBook images (to avoid recursion).
*/
export function checkIsSizableImageURL(input: string): boolean {
if (!URL.canParse(input)) {
return false;
}
if (input.includes('/~gitbook/image')) {
return false;
}
const parsed = new URL(input);
if (parsed.pathname.endsWith('.svg')) {
return false;
}
if (!checkIsHttpURL(parsed)) {
return false;
}
return true;
return checkIsHttpURL(parsed);
}
interface ResizeImageOptions {
@@ -94,7 +83,7 @@ export function getResizedImageURLFactory(
return null;
}
const signature = generateSignature(input);
const signature = generateSignatureV1(input);
return (options) => {
const url = new URL('/~gitbook/image', rootUrl());
@@ -114,7 +103,7 @@ export function getResizedImageURLFactory(
}
url.searchParams.set('sign', signature);
url.searchParams.set('sv', imagesResizingSignVersion);
url.searchParams.set('sv', '1');
return url.toString();
};
@@ -134,9 +123,11 @@ export function getResizedImageURL(input: string, options: ResizeImageOptions):
*/
export async function verifyImageSignature(
input: string,
{ signature }: { signature: string },
{ signature, version }: { signature: string; version: '1' | '0' },
): Promise<boolean> {
return generateSignature(input) === signature;
const expectedSignature =
version === '1' ? generateSignatureV1(input) : await generateSignatureV0(input);
return expectedSignature === signature;
}
/**
@@ -238,17 +229,26 @@ function stringifyOptions(options: CloudflareImageOptions): string {
const fnv1aUtf8Buffer = new Uint8Array(512);
/**
* Generate a signature for an image.
* The signature is relative to the current site being rendered to avoid serving images from other sites on the same domain.
* New and faster algorithm to generate a signature for an image.
* When setting it in a URL, we use version '1' for the 'sv' querystring parameneter
* to know that it was the algorithm that was used.
*/
function generateSignature(input: string) {
const hostName = host();
const all = [
input,
hostName, // The hostname is used to avoid serving images from other sites on the same domain
process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY,
]
.filter(Boolean)
.join(':');
function generateSignatureV1(input: string): string {
const all = [input, process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
return fnv1a(all, { utf8Buffer: fnv1aUtf8Buffer }).toString(16);
}
/**
* Initial algorithm used to generate a signature for an image. It didn't use any versioning in the URL.
* We still need it to validate older signatures that were generated without versioning
* but still exist in previously generated and cached content.
*/
async function generateSignatureV0(input: string): Promise<string> {
const all = [input, process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(all));
// Convert ArrayBuffer to hex string
const hashArray = Array.from(new Uint8Array(hash));
const hashHex = hashArray.map((b) => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
+8 -55
View File
@@ -1,11 +1,9 @@
import {
ContentRef,
ContentRefSpace,
Revision,
RevisionFile,
RevisionPageDocument,
RevisionReusableContent,
SiteSpace,
Space,
} from '@gitbook/api';
import assertNever from 'assert-never';
@@ -18,14 +16,12 @@ import {
SpaceContentPointer,
getCollection,
getDocument,
getPublishedContentSite,
getReusableContent,
getRevisionFile,
getSpace,
getSpaceContentData,
getUserById,
ignoreAPIError,
parseSpacesFromSiteSpaces,
} from './api';
import { getBlockById, getBlockTitle } from './document';
import { gitbookAppHref, pageHref, PageHrefContext } from './links';
@@ -209,7 +205,12 @@ export async function resolveContentRef(
const targetSpace =
contentRef.space === space.id
? space
: await getBestTargetSpace(contentRef.space, siteContext);
: await ignoreAPIError(
getSpace(
contentRef.space,
siteContext?.siteShareKey ? siteContext.siteShareKey : undefined,
),
);
if (!targetSpace) {
return {
@@ -286,50 +287,6 @@ export async function resolveContentRef(
}
}
/**
* This function is used to get the best possible target space while resolving a content ref.
* It will try to return the space in the site context if it exists to avoid cross-site links.
*/
async function getBestTargetSpace(
spaceId: string,
siteContext: SiteContentPointer | null,
): Promise<Space | undefined> {
const [fetchedSpace, publishedContentSite] = await Promise.all([
ignoreAPIError(
getSpace(spaceId, siteContext?.siteShareKey ? siteContext.siteShareKey : undefined),
),
siteContext
? ignoreAPIError(
getPublishedContentSite({
organizationId: siteContext.organizationId,
siteId: siteContext.siteId,
siteShareKey: siteContext.siteShareKey,
}),
)
: null,
]);
// In the context of sites, we try to find our target space in the site structure.
// because the url of this space will be in the same site.
if (publishedContentSite) {
const siteSpaces =
publishedContentSite.structure.type === 'siteSpaces'
? publishedContentSite.structure.structure
: publishedContentSite.structure.structure.reduce<SiteSpace[]>((acc, section) => {
acc.push(...section.siteSpaces);
return acc;
}, []);
const spaces = parseSpacesFromSiteSpaces(siteSpaces);
const foundSpace = spaces.find((space) => space.id === spaceId);
if (foundSpace) {
return foundSpace;
}
}
// Else we try return the fetched space from the API.
return fetchedSpace ?? undefined;
}
async function resolveContentRefInSpace(
spaceId: string,
siteContext: SiteContentPointer | null,
@@ -339,16 +296,12 @@ async function resolveContentRefInSpace(
spaceId,
};
const [result, bestTargetSpace] = await Promise.all([
ignoreAPIError(getSpaceContentData(pointer, siteContext?.siteShareKey)),
getBestTargetSpace(spaceId, siteContext),
]);
const result = await ignoreAPIError(getSpaceContentData(pointer, siteContext?.siteShareKey));
if (!result) {
return null;
}
const { pages } = result;
const space = bestTargetSpace ?? result.space;
const { space, pages } = result;
// Base URL to use to prepend to relative URLs.
let baseUrl = space.urls.published ?? space.urls.app;
+22 -33
View File
@@ -14,8 +14,8 @@ import {
userAgent,
withAPI,
DEFAULT_API_ENDPOINT,
getPublishedContentSite,
getSiteData,
getSiteLayoutData,
getSite,
} from '@/lib/api';
import { race } from '@/lib/async';
import { buildVersion } from '@/lib/build';
@@ -161,31 +161,26 @@ export async function middleware(request: NextRequest) {
userAgent: userAgent(),
}),
async () => {
const [siteData] = await Promise.all([
'site' in resolved
? getSiteData({
organizationId: resolved.organization,
siteId: resolved.site,
siteSectionId: resolved.siteSection,
siteSpaceId: resolved.siteSpace,
siteShareKey: resolved.shareKey,
})
: null,
// Start fetching everything as soon as possible, but do not block the middleware on it
// the cache will handle concurrent calls
waitUntil(
getSpaceContentData(
{
spaceId: resolved.space,
changeRequestId: resolved.changeRequest,
revisionId: resolved.revision,
},
'site' in resolved ? resolved.shareKey : undefined,
),
// Start fetching everything as soon as possible, but do not block the middleware on it
// the cache will handle concurrent calls
await waitUntil(
getSpaceContentData(
{
spaceId: resolved.space,
changeRequestId: resolved.changeRequest,
revisionId: resolved.revision,
},
'site' in resolved ? resolved.shareKey : undefined,
),
]);
);
const scripts = siteData?.scripts ?? [];
const { scripts } = await ('site' in resolved
? getSiteLayoutData({
organizationId: resolved.organization,
siteId: resolved.site,
siteSpaceId: resolved.siteSpace,
})
: { scripts: [] });
return getContentSecurityPolicy(scripts, nonce);
},
);
@@ -485,13 +480,7 @@ async function lookupSiteOrSpaceInMultiIdMode(
// Verify access to the site to avoid leaking cached data in this mode
// (the cache is not dependend on the auth token, so it could leak data)
if (source.kind === 'site') {
await withAPI(gitbookAPI, () =>
getPublishedContentSite.revalidate({
organizationId: decoded.organization,
siteId: source.id,
siteShareKey: undefined,
}),
);
await withAPI(gitbookAPI, () => getSite.revalidate(decoded.organization, source.id));
}
const cookies: LookupCookies = {
@@ -501,7 +490,7 @@ async function lookupSiteOrSpaceInMultiIdMode(
httpOnly: true,
maxAge: 60 * 30,
secure: process.env.NODE_ENV === 'production',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined,
sameSite: 'none',
},
},
};
-13
View File
@@ -99,9 +99,6 @@ const config: Config = {
pomegranate: generateShades('#f25b3a'),
periwinkle: generateShades('#acc6ee'),
},
animation: {
present: 'present .5s ease-out both',
},
keyframes: {
pulseAlt: {
'0%': {
@@ -124,16 +121,6 @@ const config: Config = {
opacity: '1',
},
},
present: {
from: {
opacity: '0',
transform: 'translateY(2rem) scale(0.9)',
},
to: {
opacity: '1',
transform: 'translateY(0) scale(1)',
},
},
rotateLoop: {
'0%': {
transform: 'rotate(0deg) scaleY(2.5) scaleX(2.5)',
+1 -1
View File
@@ -10,7 +10,7 @@
},
"dependencies": {
"classnames": "^2.5.1",
"@gitbook/api": "^0.77.0",
"@gitbook/api": "^0.72.0",
"assert-never": "^1.2.1"
},
"peerDependencies": {
+1 -1
View File
@@ -10,7 +10,7 @@
},
"version": "0.7.0",
"dependencies": {
"@scalar/api-client-react": "1.0.87",
"@scalar/api-client-react": "1.0.76",
"classnames": "^2.5.1",
"flatted": "^3.2.9",
"openapi-types": "^12.1.3",
@@ -79,7 +79,7 @@ export function generateSchemaExample(
return 'text';
}
if (schema.type === 'number' || schema.type === 'integer') {
if (schema.type === 'number') {
return schema.default || 0;
}