Compare commits

..

40 Commits

Author SHA1 Message Date
Valentino Hudhra 81af6bb077 Replace header link API type 2024-12-06 10:51:39 +01:00
Samy Pessé 1005ee5d52 Prevent resizing the url of an image already resized (#2600) 2024-12-05 16:34:31 +01:00
Valentino Hudhra d9bb9f9a07 Fix cookie banner button being non responsive (#2599) 2024-12-05 14:04:03 +01:00
Greg Bergé 75a6fabe61 Support dropdown without link (#2596) 2024-12-04 12:05:17 +01:00
Greg Bergé 75e29b69cc Allow to work locally (#2597) 2024-12-03 14:49:13 +01:00
Samy Pessé ffd3937538 Fix security issue with images resizing (#2595) 2024-12-03 08:51:46 +01:00
Valentino Hudhra 575587e4c5 Improve footer link styling (#2591) 2024-12-01 07:54:45 +01:00
Brett Jephson 2ce59d7c92 Fix whitespace added with image (#2594) 2024-11-29 17:10:29 +00:00
Brett Jephson 3b3d6e2a73 Add an icon to site sections (#2593) 2024-11-29 16:09:06 +00:00
Zeno Kapitein f2a467fdbf Fix hint block decoration color (#2590) 2024-11-29 16:40:10 +01:00
vibhanshub 867481c66d Support Integers in Response sample (#2592) 2024-11-28 14:19:37 +00:00
spastorelli fc8065b7a8 Revert "Fix canonical URL ending with "/" (#2586)" (#2588) 2024-11-27 13:05:34 +01:00
Greg Bergé 28f1ed9205 Fix canonical URL ending with "/" (#2586) 2024-11-26 21:57:15 +01:00
Viktor Renkema 568266bc9a Add transitions to Sections bg and line (#2491) 2024-11-26 19:59:07 +01:00
Samy Pessé 7739f341b8 Revert "Serve the correct status code for not found and redirects 👌" (#2587) 2024-11-26 18:36:00 +01:00
Greg Bergé 2b501f191c Serve the correct status code for not found and redirects 👌 (#2582) 2024-11-26 18:05:47 +01:00
Zeno Kapitein aa2ed0fda1 Restyle hint block (#2579) 2024-11-26 12:41:47 +01:00
Greg Bergé 51cba074d7 Update shiki (#2583) 2024-11-26 11:50:08 +01:00
Taran Vohra 2c945c663c Get the best possible target space for content refs (#2580) 2024-11-26 10:53:37 +05:30
Viktor Renkema d9a18ecabb Improve contrast ratio for text color on image captions (#2584) 2024-11-25 14:01:09 +01:00
Greg Bergé eab7931afb Parallelize and remove useless Promise.all (#2581) 2024-11-22 15:54:56 +01:00
Taran Vohra 99b6c92377 Resolve site level redirects (#2577) 2024-11-22 12:04:15 +05:30
Zeno Kapitein 4d56f1163b Improve styling of search & ask AI box (#2576) 2024-11-20 16:59:15 +01:00
Brett Jephson 07cf835551 Add a scroll margin to the top when layout has sections (#2574) 2024-11-19 16:34:27 +00:00
Steven H 061c0c1a90 Fix a regression in variant drop-down caused by missing z-index. (#2575) 2024-11-19 17:23:44 +01:00
Anthony Lio 1ed18c05ef Adds missing css variables (#2558)
Co-authored-by: Steven H <steven@gitbook.io>
2024-11-19 16:08:07 +01:00
Steven H ca134c8a60 Fix an issue where the active site section indicator appeared above any dropdowns. (#2568) 2024-11-19 15:16:47 +01:00
Amrit Kahlon 7ba67fd852 chore: scalar bump (#2571)
Co-authored-by: Steven Hall <steven@gitbook.io>
2024-11-19 13:54:35 +01:00
Taran Vohra 7675c2c411 use getPublishedContentSite API (#2570)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-11-15 09:21:08 +01:00
Brett Jephson 7c71363af8 Set adjustFallbackFont to false for mono font (#2569) 2024-11-12 13:03:25 +00:00
Steven H d48926eb2a Fix an issue where the space dropdown was shown under the site sections in Safari. (#2567) 2024-11-05 11:49:33 +00:00
Steven H d843e5e06f Fix an issue where the space dropdown could appear behind the header. (#2566) 2024-11-05 09:47:32 +00:00
Steven H a2e564738e Fix the styling of site section tabs on smaller screens. (#2565) 2024-11-04 17:36:10 +00:00
Greg Bergé 54a797a0b1 Nested list support (#2562) 2024-10-31 14:02:42 +01:00
Amrit Kahlon a78c1ecb4d Bump scalar api client package (#2563) 2024-10-30 11:45:56 -07:00
Amrit Kahlon 4771c78001 Fix Scalar ApiClient routing (#2561) 2024-10-28 12:38:18 -07:00
Samy Pessé b7a5106f36 Disable logs for cache-do (#2560) 2024-10-27 08:16:56 -04:00
Samy Pessé 4bcbdc50ff Output caching headers on RSC/prefetch responses (#2559) 2024-10-26 10:57:52 +02:00
Brett Jephson 5d72b35c7f Improve animation of section tabs (#2553) 2024-10-25 14:00:27 +01:00
Amrit Kahlon ff50ac215c Bump @scalar/api-client-react version (#2555)
Co-authored-by: taranvohra <taranvohra@outlook.com>
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-10-25 12:06:49 +05:30
107 changed files with 1506 additions and 1271 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix an issue with the cookie banner buttons being non responsive
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/cache-do': patch
---
Disable cloudflare observability in production
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Update styling of search+ask modal
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix a regression in variant drop-down caused by missing z-index.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Add scroll margin to the top when there are sections
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Smoother tab transition for sections
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix an issue where the active site section indicator appeared above any dropdowns.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Don't adjust fallback font for mono font.
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Fixed scalar api client routing
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Optimize performances by using new API endpoint for fetching site data.
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Bump @scalar/api-client-react version
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Support Integers in Response example
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Restyle hint blocks
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix security issue with image resizing that could be used for phishing
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
bumped the scalar api client dependency
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Bumped scalar api client pacakge
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix an issue where the space dropdown was shown under the site sections in Safari.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix - whitespace added to site section tabs with icons.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Add icons to sections
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
style: adds missing scalar css variables
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix an issue where the space dropdown could appear behind the header.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix the styling of site section tabs on smaller screens.
+7 -7
View File
@@ -18,7 +18,7 @@ jobs:
checks: write
statuses: write
outputs:
deployment_url: ${{ steps.deploy.outputs.url }}
deployment_url: ${{ steps.deploy.outputs.deployment-url }}
steps:
- name: Checkout
uses: actions/checkout@v4
@@ -58,7 +58,7 @@ jobs:
SENTRY_DSN: ${{ vars.SENTRY_DSN }}
- id: deploy
name: Deploy to Cloudflare
uses: cloudflare/wrangler-action@v3
uses: cloudflare/wrangler-action@v3.11.0
with:
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
@@ -67,7 +67,7 @@ jobs:
command: pages deploy ./packages/gitbook/.vercel/output/static --project-name=${{ vars.CLOUDFLARE_PROJECT_NAME }} --branch=${{ github.ref == 'refs/heads/main' && 'main' || format('pr{0}', github.event.pull_request.number) }}
- name: Outputs
run: |
echo "URL: ${{ steps.deploy.outputs.url }}"
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
echo "Alias URL: ${{ steps.deploy.outputs.deployment-alias-url }}"
- name: Archive build output
uses: actions/upload-artifact@v4
@@ -77,12 +77,12 @@ jobs:
# Until https://github.com/cloudflare/wrangler-action/issues/301 is done
- name: Update Deployment Status to Success
env:
DEPLOYMENT_URL: ${{ steps.deploy.outputs.url }}
DEPLOYMENT_URL: ${{ steps.deploy.outputs.deployment-url }}
run: |
curl -X POST \
-H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
-H "Accept: application/vnd.github.v3+json" \
-d '{"state": "success", "target_url": "${{ steps.deploy.outputs.url }}", "description": "Deployed Preview URL for commit", "context": "cloudflare/preview"}' \
-d '{"state": "success", "target_url": "${{ steps.deploy.outputs.deployment-url }}", "description": "Deployed Preview URL for commit", "context": "cloudflare/preview"}' \
https://api.github.com/repos/${{ github.repository }}/statuses/${{ github.sha }}
- name: Find GitHub Comment
@@ -102,8 +102,8 @@ jobs:
issue-number: ${{ github.event.pull_request.number }}
body: |
**GitBook Preview**
Latest commit: [${{ steps.deploy.outputs.url }}](${{ steps.deploy.outputs.url }})
PR: [${{ steps.deploy.outputs.alias }}](${{ steps.deploy.outputs.alias }})
Latest commit: [${{ steps.deploy.outputs.deployment-url }}](${{ steps.deploy.outputs.deployment-url }})
PR: [${{ steps.deploy.outputs.deployment-alias-url }}](${{ steps.deploy.outputs.deployment-alias-url }})
edit-mode: replace
visual-testing:
runs-on: ubuntu-latest
BIN
View File
Binary file not shown.
+2 -1
View File
@@ -8,7 +8,8 @@
},
"packageManager": "bun@1.1.18",
"patchedDependencies": {
"@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.patch"
"@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.patch",
"@cloudflare/next-on-pages@1.13.5": "patches/@cloudflare%2Fnext-on-pages@1.13.5.patch"
},
"private": true,
"scripts": {
+2 -3
View File
@@ -11,8 +11,7 @@ migrations = [
]
[observability]
enabled = true
head_sampling_rate = 0.01
enabled = false
[env.preview]
name = "gitbook-open-cache-preview"
@@ -25,4 +24,4 @@ migrations = [
[env.preview.observability]
enabled = true
head_sampling_rate = 1
head_sampling_rate = 0.1
+49
View File
@@ -491,6 +491,55 @@ 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/',
+3 -3
View File
@@ -5,7 +5,7 @@
"scripts": {
"dev": "env-cmd --silent -f ../../.env.local next dev",
"build": "next build",
"build:cloudflare": "next-on-pages",
"build:cloudflare": "next-on-pages --custom-entrypoint=./src/cloudflare-entrypoint.ts",
"start": "next start",
"lint": "next lint",
"typecheck": "tsc --noEmit",
@@ -16,7 +16,7 @@
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
},
"dependencies": {
"@gitbook/api": "^0.73.0",
"@gitbook/api": "^0.80.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.22.0",
"shiki": "^1.23.1",
"tailwind-merge": "^2.2.0",
"tailwind-shades": "^1.1.2",
"unified": "^11.0.4",
@@ -4,6 +4,7 @@ import {
verifyImageSignature,
resizeImage,
CloudflareImageOptions,
imagesResizingSignVersion,
checkIsSizableImageURL,
} from '@/lib/images';
import { parseImageAPIURL } from '@/lib/urls';
@@ -18,28 +19,29 @@ 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 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';
// 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;
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, version: signatureVersion });
const verified = await verifyImageSignature(url, { signature });
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: {}) {
export function PageClientLayout(props: { withSections?: boolean }) {
// 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();
useScrollPage({ scrollMarginTop: props.withSections ? 50 : undefined });
useStripFallbackQueryParam();
return null;
@@ -1,11 +1,11 @@
import { getSpaceLanguage, t } from '@/intl/server';
import { getSiteLayoutData } from '@/lib/api';
import { getSiteData } from '@/lib/api';
import { getSiteContentPointer } from '@/lib/pointer';
import { tcls } from '@/lib/tailwind';
export default async function NotFound() {
const pointer = getSiteContentPointer();
const { customization } = await getSiteLayoutData(pointer);
const { customization } = await getSiteData(pointer);
const language = getSpaceLanguage(customization);
@@ -73,7 +73,7 @@ export default async function Page(props: {
page,
};
const withSections = Boolean(sections && sections.length > 0);
const withSections = Boolean(sections && sections.list.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 />
<PageClientLayout withSections={withSections} />
</React.Suspense>
</>
);
@@ -1,7 +1,6 @@
import { ContentVisibility } from '@gitbook/api';
import { NextRequest } from 'next/server';
import { getCollection, getSite, getSpace } from '@/lib/api';
import { getSpace, getSite } 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 { getCurrentSiteCustomization, getSite, getSpace } from '@/lib/api';
import { getSite, getSiteData, 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),
getCurrentSiteCustomization(pointer),
getSiteData(pointer),
]);
const site = await getSite(pointer.organizationId, pointer.siteId);
const contentTitle = getContentTitle(space, customization, site);
+48 -122
View File
@@ -1,14 +1,12 @@
import { RevisionPage, SiteSection, SiteSpace, Space } from '@gitbook/api';
import { assert } from 'ts-essentials';
import { RevisionPage } from '@gitbook/api';
import { redirect } from 'next/navigation';
import {
getRevisionPageByPath,
getDocument,
ContentTarget,
getSpaceContentData,
getSiteData,
getSite,
getCurrentSiteCustomization,
getSiteStructure,
getSiteRedirectBySource,
} from '@/lib/api';
import { resolvePagePath, resolvePageId } from '@/lib/pages';
import { getSiteContentPointer } from '@/lib/pointer';
@@ -21,35 +19,18 @@ export interface PageIdParams {
pageId: string;
}
type SectionsList = { list: SiteSection[]; section: SiteSection };
/**
* Fetch all the data needed to render the content layout.
*/
export async function fetchContentData() {
const content = getSiteContentPointer();
const [{ space, contentTarget, pages, customization, scripts }, siteStructure] =
const [{ space, contentTarget, pages }, { customization, site, sections, spaces, scripts }] =
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);
@@ -58,53 +39,39 @@ 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 } 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 content = getSiteContentPointer();
const contentData = await fetchContentData();
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,
]);
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;
return {
content,
contentTarget,
space,
pages,
customization,
scripts,
ancestors: [],
...contentData,
...page,
...siteStructure,
document,
};
}
@@ -113,11 +80,17 @@ 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(
contentTarget: ContentTarget,
pages: RevisionPage[],
params: PagePathParams | PageIdParams,
) {
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;
if ('pageId' in params) {
return resolvePageId(pages, params.pageId);
}
@@ -131,78 +104,31 @@ async function resolvePage(
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) {
const resolved = await getRevisionPageByPath(
contentTarget.spaceId,
contentTarget.revisionId,
rawPathname,
);
// 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);
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 { getSiteLayoutData } from '@/lib/api';
import { getSiteData } 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 getSiteLayoutData(pointer);
const { customization } = await getSiteData(pointer);
return (
<CustomizationRootLayout customization={customization}>{children}</CustomizationRootLayout>
@@ -1,7 +1,7 @@
import { SpaceIntegrationScript } from '@gitbook/api';
import { CustomizationRootLayout } from '@/components/RootLayout';
import { getSiteLayoutData, getSpaceCustomization } from '@/lib/api';
import { getSiteData, 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
? getSiteLayoutData(pointer)
? getSiteData(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, createHighlightingContext } from '@/components/DocumentView';
import { DocumentView } 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,
getCurrentSiteCustomization,
getSiteData,
} from '@/lib/api';
import { pagePDFContainerId, PageHrefContext, absoluteHref } from '@/lib/links';
import { resolvePageId } from '@/lib/pages';
@@ -40,11 +40,9 @@ 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
? getCurrentSiteCustomization(pointer)
: getSpaceCustomization(pointer.spaceId),
'siteId' in pointer ? getSiteData(pointer) : getSpaceCustomization(pointer.spaceId),
]);
return {
@@ -67,10 +65,8 @@ 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
? getCurrentSiteCustomization(pointer)
: getSpaceCustomization(pointer.spaceId),
const [{ customization }, { space, contentTarget, pages: rootPages }] = await Promise.all([
'siteId' in pointer ? getSiteData(pointer) : getSpaceCustomization(pointer.spaceId),
getSpaceContentData(pointer, 'siteId' in pointer ? pointer.siteShareKey : undefined),
]);
const language = getSpaceLanguage(customization);
@@ -231,7 +227,6 @@ 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)}>
@@ -254,7 +249,6 @@ async function PDFPageDocument(props: {
contentRefContext: refContext,
resolveContentRef: (ref) => resolveContentRef(ref, refContext),
getId: (id) => pagePDFContainerId(page, id),
shouldHighlightCode,
}}
/>
) : null}
@@ -0,0 +1,18 @@
// @ts-ignore
import nextOnPagesHandler from '@cloudflare/next-on-pages/fetch-handler';
import { withMiddlewareHeadersStorage } from './lib/middleware';
/**
* We use a custom entrypoint until we can move to opennext (https://github.com/opennextjs/opennextjs-cloudflare/issues/92).
* There is a bug in next-on-pages where headers can't be set on the response in the middleware for RSC requests (https://github.com/cloudflare/next-on-pages/issues/897).
*/
export default {
async fetch(request, env, ctx) {
const response = await withMiddlewareHeadersStorage(() =>
nextOnPagesHandler.fetch(request, env, ctx),
);
return response;
},
} as ExportedHandler<{ ASSETS: Fetcher }>;
@@ -22,10 +22,8 @@ import { Heading } from './Heading';
import { Hint } from './Hint';
import { Images } from './Images';
import { IntegrationBlock } from './Integration';
import { List } from './List';
import { ListItem } from './ListItem';
import { ListOrdered } from './ListOrdered';
import { ListTasks } from './ListTasks';
import { ListUnordered } from './ListUnordered';
import { BlockMath } from './Math';
import { OpenAPI } from './OpenAPI';
import { Paragraph } from './Paragraph';
@@ -65,11 +63,9 @@ export function Block<T extends DocumentBlock>(props: BlockProps<T>) {
case 'heading-3':
return <Heading {...props} block={block} />;
case 'list-ordered':
return <ListOrdered {...props} block={block} />;
case 'list-unordered':
return <ListUnordered {...props} block={block} />;
case 'list-tasks':
return <ListTasks {...props} block={block} />;
return <List {...props} block={block} />;
case 'list-item':
return <ListItem {...props} block={block} />;
case 'code':
@@ -48,7 +48,7 @@ async function SpaceRefCard(
return null;
}
const spaceCustomization = await ignoreAPIError(getSpaceCustomization(spaceId));
const { customization: spaceCustomization } = 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/6',
'dark:text-light/7',
)}
>
<Inlines
@@ -15,8 +15,7 @@ import './theme.css';
*/
export async function CodeBlock(props: BlockProps<DocumentBlockCode>) {
const { block, document, style, context } = props;
const withHighlighting = context.shouldHighlightCode(context.content?.spaceId);
const lines = withHighlighting ? await highlight(block) : plainHighlighting(block);
const lines = await highlight(block);
const id = block.key!;
@@ -99,6 +98,8 @@ 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,7 +50,6 @@ export function PlainCodeBlock(props: { code: string; syntax: string }) {
mode: 'default',
contentRefContext: null,
resolveContentRef: async () => null,
shouldHighlightCode: () => true,
}}
block={block}
ancestorBlocks={[]}
@@ -1,30 +0,0 @@
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,3 +1,2 @@
export * from './CodeBlock';
export * from './PlainCodeBlock';
export * from './createHighlightingContext';
@@ -38,16 +38,6 @@ 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(
'px-4',
'py-4',
'hint',
'p-4',
'transition-colors',
'rounded-md',
'straight-corners:rounded-none',
@@ -26,19 +26,16 @@ export function Hint(props: BlockProps<DocumentBlockHint>) {
)}
>
<div className={tcls('flex', 'flex-row')}>
<div
<Icon
icon={hintStyle.icon}
className={tcls(
'flex',
'items-start',
'justify-center',
'pr-3',
'size-5',
'mr-4',
'mt-0.5',
firstLine.lineHeight,
hintStyle.iconColor,
)}
>
<Icon icon={hintStyle.icon} className={tcls('size-4')} />
</div>
/>
<Blocks
{...contextProps}
ancestorBlocks={[...ancestorBlocks, block]}
@@ -48,7 +45,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', '[&>p]:text-sm', '[&>p]:leading-relaxed']}
style={['flex-1', 'space-y-4', '[&_.hint]:border', '[&_pre]:border']}
/>
</div>
</div>
@@ -65,130 +62,69 @@ const HINT_STYLES: {
} = {
info: {
icon: 'circle-info',
iconColor: ['text-periwinkle-700', 'dark:text-periwinkle-400'],
iconColor: ['text-primary-500', 'dark:text-primary-400'],
bodyColor: [
'[&>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',
'[&_a]:text-primary-500',
'[&_a:hover]:text-primary-600',
'dark:[&_a]:text-primary-400',
'dark:[&_a:hover]:text-primary-300',
],
style: [
'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]',
'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',
],
},
warning: {
icon: 'circle-exclamation',
iconColor: ['text-yellow-800', 'dark:text-yellow'],
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.
bodyColor: [
'[&>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',
'[&_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',
],
style: ['bg-orange-500/2', 'border-orange-500/4'],
},
danger: {
icon: 'triangle-exclamation',
iconColor: ['text-pomegranate-700', 'dark:text-pomegranate-400'],
iconColor: ['text-red-500', 'dark:text-red-400'],
bodyColor: [
'[&>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',
'[&_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',
],
style: ['bg-red-500/2', 'border-red-500/4'],
},
success: {
icon: 'circle-check',
iconColor: ['text-teal-700', 'dark:text-teal-400'],
iconColor: ['text-green-500', 'dark:text-green-400'],
bodyColor: [
'[&>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',
'[&_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',
],
style: ['bg-green-500/2', 'border-green-500/4'],
},
};
@@ -0,0 +1,44 @@
import {
DocumentBlockListOrdered,
DocumentBlockListTasks,
DocumentBlockListUnordered,
} from '@gitbook/api';
import assertNever from 'assert-never';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
export function List(
props: BlockProps<
DocumentBlockListUnordered | DocumentBlockListOrdered | DocumentBlockListTasks
>,
) {
const { block, style, ancestorBlocks, ...contextProps } = props;
return (
<Blocks
{...contextProps}
tag={getListTag(block.type)}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={['space-y-2', style]}
/>
);
}
function getListTag(
type:
| DocumentBlockListUnordered['type']
| DocumentBlockListOrdered['type']
| DocumentBlockListTasks['type'],
) {
switch (type) {
case 'list-ordered':
return 'ol';
case 'list-unordered':
case 'list-tasks':
return 'ul';
default:
assertNever(type);
}
}
@@ -1,13 +0,0 @@
.olListItemBullet {
/* Align the bullet container with the first line of text */
line-height: inherit;
height: 1lh;
/* Align the bullet content with the middle of the text */
display: flex;
align-items: center;
}
.olListItemBullet::before {
@apply text-base;
--tw-content: attr(data-value) '. ';
content: var(--tw-content);
}
@@ -1,114 +1,231 @@
import {
DocumentBlock,
DocumentBlockListItem,
DocumentBlockListOrdered,
DocumentBlockListTasks,
DocumentBlockListUnordered,
} from '@gitbook/api';
import classNames from 'classnames';
import assertNever from 'assert-never';
import { assert } from 'ts-essentials';
import { Checkbox } from '@/components/primitives';
import { tcls } from '@/lib/tailwind';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
import styles from './ListItem.module.css';
import { getBlockTextStyle } from './spacing';
export function ListItem(props: BlockProps<DocumentBlockListItem>) {
const { block, ancestorBlocks, ...contextProps } = props;
const textStyle = getBlockTextStyle(block);
const parent = ancestorBlocks[ancestorBlocks.length - 1];
assert(
(parent && parent.type === 'list-ordered') ||
parent.type === 'list-unordered' ||
parent.type === 'list-tasks',
'Invalid parent list type',
);
const parent = ancestorBlocks[ancestorBlocks.length - 1] as
| DocumentBlockListOrdered
| DocumentBlockListUnordered
| DocumentBlockListTasks
| undefined;
const blocksElement = (
<Blocks
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
blockStyle={tcls(
'min-h-[1lh]',
// flip heading hash icon if list item is a heading
'flip-heading-hash',
// remove margin-top for the first heading in a list
'[&:is(h2)>div]:mt-0',
'[&:is(h3)>div]:mt-0',
'[&:is(h4)>div]:mt-0',
)}
style="space-y-2 flex flex-col flex-1"
/>
);
const ListItemType = () => {
switch (parent?.type) {
case 'list-tasks':
return (
<li>
<div className={tcls('flex', 'flex-row')}>
<div
className={tcls(
textStyle.textSize,
'flex',
'flex-col',
'justify-center',
'h-[1lh]',
)}
>
<Checkbox
id={block.key!}
disabled
checked={block.data?.checked}
className={tcls('relative')}
/>
</div>
<label htmlFor={block.key} className={tcls('flex-1')}>
<Blocks
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
blockStyle={tcls('flip-heading-hash')}
style={tcls('ml-2', 'space-y-2')}
/>
</label>
</div>
</li>
);
case 'list-ordered':
const start = parent.data.start ?? 1;
const indexInParent = parent.nodes.findIndex((node) => node.key === block.key) ?? 0;
const index = indexInParent + start;
return (
<li value={index} className={tcls(textStyle.lineHeight)}>
<div
data-value={index}
className={classNames(
'bullet',
styles.olListItemBullet,
tcls(textStyle.textSize),
)}
></div>
{/* zero width space to force layouts with empty lists */}
<Blocks
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={tcls('space-y-2', 'flex-1', 'flex', 'flex-col')}
blockStyle={tcls(
textStyle.lineHeight,
'min-h-[1lh]',
//flip heading hash icon if list item is a heading
'flip-heading-hash',
)}
switch (parent.type) {
case 'list-tasks':
return (
<ListItemLI block={block}>
<ListItemPrefix block={block}>
<Checkbox
id={block.key!}
disabled
checked={block.data?.checked}
className="relative"
size="small"
/>
</li>
);
default:
return (
<li className={tcls(textStyle.lineHeight)}>
<div className={tcls('bullet', textStyle.textSize)}></div>
<Blocks
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={tcls('space-y-2', 'flex', 'flex-col')}
blockStyle={tcls(
'min-h-[1lh]',
//flip heading hash icon if list item is a heading
'flip-heading-hash',
)}
/>
</li>
);
}
};
</ListItemPrefix>
return <ListItemType />;
<label htmlFor={block.key} className={tcls('flex-1')}>
{blocksElement}
</label>
</ListItemLI>
);
case 'list-ordered':
return (
<ListItemLI block={block}>
<ListItemPrefix block={block}>
<PseudoBefore
content={getOrderedListItemPrefixContent({
depth: getListItemDepth({ ancestorBlocks, type: parent.type }),
block,
parent,
})}
style={{
fontSize: 'min(1em, 24px)',
}}
/>
</ListItemPrefix>
{blocksElement}
</ListItemLI>
);
case 'list-unordered':
return (
<ListItemLI block={block}>
<ListItemPrefix block={block}>
<PseudoBefore
content={getUnorderedListItemsPrefixContent({
depth: getListItemDepth({ ancestorBlocks, type: parent.type }),
})}
fontFamily="Arial"
style={{ fontSize: 'min(1.5em, 24px)', lineHeight: 1 }}
/>
</ListItemPrefix>
{blocksElement}
</ListItemLI>
);
default:
assertNever(parent);
}
}
function getListItemDepth(input: {
ancestorBlocks: DocumentBlock[];
type: DocumentBlockListOrdered['type'] | DocumentBlockListUnordered['type'];
}): number {
const { ancestorBlocks, type } = input;
let depth = -1;
for (let i = ancestorBlocks.length - 1; i >= 0; i--) {
const block = ancestorBlocks[i];
if (block.type === type) {
depth = depth + 1;
continue;
}
if (block.type === 'list-item') {
continue;
}
break;
}
return depth;
}
function ListItemLI(props: { block: DocumentBlockListItem; children: React.ReactNode }) {
const textStyle = getBlockTextStyle(props.block);
return <li className={tcls(textStyle.lineHeight, 'flex items-start')}>{props.children}</li>;
}
function ListItemPrefix(props: { block: DocumentBlockListItem; children: React.ReactNode }) {
const textStyle = getBlockTextStyle(props.block);
return (
<div
className={tcls(
textStyle.textSize,
textStyle.lineHeight,
'flex items-center justify-center mr-1 min-h-[1lh] min-w-6 text-dark/6 dark:text-light/5',
)}
>
{props.children}
</div>
);
}
function getUnorderedListItemsPrefixContent(input: { depth: number }): string {
switch (input.depth % 3) {
case 0:
return '•';
case 1:
return '◦';
case 2:
return '▪';
default:
return '•';
}
}
function PseudoBefore(props: {
style?: React.CSSProperties;
content: string;
fontFamily?: string;
}) {
return (
<div
className="before:font-var before:content-[--pseudoBefore--content]"
style={
{
'--pseudoBefore--content': `'${props.content}'`,
'--font-family': props.fontFamily ?? 'inherit',
...props.style,
} as React.CSSProperties
}
/>
);
}
function getOrderedListItemPrefixContent(input: {
depth: number;
parent: DocumentBlockListOrdered;
block: DocumentBlockListItem;
}): string {
const { parent, block } = input;
const start = parent.data.start ?? 1;
const index = parent.nodes.findIndex((node) => node.key === block.key) ?? 0;
const value = index + start;
switch (input.depth % 3) {
// Use numbers
case 0: {
return `${value}.`;
}
// Use letters
case 1: {
const letters = 'abcdefghijklmnopqrstuvwxyz';
return `${letters[(value - 1) % letters.length]}.`;
}
// Use roman numbers
case 2: {
return `${toRoman(value).toLowerCase()}.`;
}
default:
return '•';
}
}
function toRoman(input: number): string {
const lookup = {
M: 1000,
CM: 900,
D: 500,
CD: 400,
C: 100,
XC: 90,
L: 50,
XL: 40,
X: 10,
IX: 9,
V: 5,
IV: 4,
I: 1,
};
let roman = '';
let number = input;
for (const i in lookup) {
while (number >= lookup[i as keyof typeof lookup]) {
roman += i;
number -= lookup[i as keyof typeof lookup];
}
}
return roman;
}
@@ -1,45 +0,0 @@
import { DocumentBlockListOrdered } from '@gitbook/api';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
export function ListOrdered(props: BlockProps<DocumentBlockListOrdered>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
return (
<Blocks
{...contextProps}
tag="ol"
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={[
'space-y-2',
'flex',
'flex-col',
'[&>li]:gap-[1ch]',
'[counter-reset:list-decimal]',
'[&>li]:flex',
'[&>li]:flex-row',
/* '[&>li>.bullet]:w-[1ch]', */
'[&>li>.bullet]:tabular-nums',
'[&>li>.bullet]:whitespace-nowrap',
'[&>li>.bullet]:list-decimal',
'[&>li>.bullet]:before:h-[1lh]',
'[&>li>.bullet]:before:leading-[inherit]',
'[&>li>.bullet]:before:flex',
/* '[&>li>.bullet]:before:pr-[1ch]', */
'[&>li>.bullet]:text-dark/6',
//remove any spacing when using heading as list item
'[&>li>div_div]:mt-0',
'dark:[&>li>.bullet]:text-light/6',
style,
]}
/>
);
}
@@ -1,25 +0,0 @@
import { DocumentBlockListTasks, DocumentBlockListUnordered } from '@gitbook/api';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
export function ListTasks(props: BlockProps<DocumentBlockListTasks>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
return (
<Blocks
{...contextProps}
tag="ul"
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={[
'list-none',
'[&>li]:pl-[.25ch]',
//remove any spacing when using heading as list item
'[&>li>div_div]:mt-0',
'space-y-2',
style,
]}
/>
);
}
@@ -1,51 +0,0 @@
import { DocumentBlockListUnordered } from '@gitbook/api';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
export function ListUnordered(props: BlockProps<DocumentBlockListUnordered>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
const nestedBulletStyle = [
// Level 1
'[&>li>.bullet:before]:bullet-circleFilled',
// Level 2
`[&_&>li>.bullet:before]:bullet-circle`,
// Level 3
`[&_&_&>li>.bullet:before]:bullet-dash`,
// Level 4
`[&_&_&_&>li>.bullet:before]:bullet-squareFilled`,
// Level 5
`[&_&_&_&_&>li>.bullet:before]:bullet-square`,
// Level 6 // reset back to reg bullets here
`[&_&_&_&_&_&>li>.bullet:before]:bullet-circleFilled`,
];
return (
<Blocks
{...contextProps}
tag="ul"
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={[
'list-none',
'space-y-2',
'[&>li]:relative',
'[&>li]:ps-[2.25ch]',
//remove any spacing when using heading as list item
'[&>li>div_div]:mt-0',
//custom content setup for lists
'[&>li>.bullet]:before:bg-dark/6',
'[&>li>.bullet]:before:absolute',
'[&>li>.bullet]:before:left-0',
'[&>li>.bullet]:before:w-[1ch]',
'[&>li>.bullet]:before:h-[1lh]',
'[&>li>.bullet]:before:[mask-repeat:no-repeat]',
'[&>li>.bullet]:before:[mask-position:left]',
'dark:[&>li>.bullet]:before:bg-light/6',
nestedBulletStyle,
style,
]}
/>
);
}
@@ -57,6 +57,9 @@
--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,
@@ -114,6 +117,9 @@
--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,6 +7,11 @@ export function Stepper(props: BlockProps<DocumentBlockStepper>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
return (
<Blocks {...contextProps} nodes={block.nodes} ancestorBlocks={[...ancestorBlocks, block]} />
<Blocks
blockStyle={style}
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
/>
);
}
@@ -30,17 +30,17 @@ export function StepperStep(props: BlockProps<DocumentBlockStepperStep>) {
})();
return (
<div className="flex flex-row gap-4 md:gap-8 max-w-3xl w-full mx-auto">
<div className={tcls('flex flex-row gap-4 md:gap-8 max-w-3xl w-full mx-auto', style)}>
<div className="relative select-none">
<div
className={tcls(
'flex size-[calc(1.75rem+1px)] items-center justify-center rounded-full bg-primary-50 dark:bg-primary-900 tabular-nums',
'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',
'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" />
<div className="absolute bottom-2 left-[0.875rem] top-9 w-px bg-primary-50 dark:bg-primary-900 can-override-bg" />
</div>
<Blocks
{...contextProps}
@@ -1,2 +1 @@
export * from './DocumentView';
export { createHighlightingContext } from './CodeBlock';
@@ -6,46 +6,44 @@ import {
} from '@gitbook/api';
import { assertNever } from 'assert-never';
import { ClassValue } from '@/lib/tailwind';
/**
* Get the line height of a block
*/
export function getBlockTextStyle(block: DocumentBlock): {
/** Tailwind class for the text size */
textSize: ClassValue;
textSize: string;
/** Tailwind class for the height (h-*) */
lineHeight: ClassValue;
lineHeight: string;
/** Tailwind class for the margin top (mt-*) */
marginTop?: ClassValue;
marginTop?: string;
} {
switch (block.type) {
case 'paragraph':
return {
textSize: ['text-base'],
textSize: 'text-base',
lineHeight: 'leading-normal',
};
case 'heading-1':
return {
textSize: ['text-3xl', 'font-semibold'],
textSize: 'text-3xl font-semibold',
lineHeight: 'leading-tight',
marginTop: '[margin-top:_1em]',
marginTop: 'mt-[1em]',
};
case 'heading-2':
return {
textSize: ['text-2xl', 'font-semibold'],
textSize: 'text-2xl font-semibold',
lineHeight: 'leading-snug',
marginTop: '[margin-top:_0.75em]',
marginTop: 'mt-[0.75em]',
};
case 'heading-3':
return {
textSize: ['text-base', 'font-semibold'],
textSize: 'text-base font-semibold',
lineHeight: 'leading-snug',
marginTop: '[margin-top:_0.5em]',
marginTop: 'mt-[0.5em]',
};
case 'divider':
return {
textSize: [],
textSize: '',
lineHeight: 'leading-none',
};
case 'list-ordered':
@@ -56,7 +54,7 @@ export function getBlockTextStyle(block: DocumentBlock): {
return getBlockTextStyle(block.nodes[0]);
default:
return {
textSize: ['text-base'],
textSize: 'text-base',
lineHeight: 'leading-normal',
};
}
@@ -13,7 +13,7 @@ export function FooterLinksGroup(props: {
return (
<div className={tcls('flex', 'flex-col', 'gap-3')}>
<p className={tcls('text-base', 'font-medium')}>{group.title}</p>
<p className={tcls('text-base', 'font-semibold')}>{group.title}</p>
{group.links.map((link, index) => {
return <FooterLink key={index} link={link} context={context} />;
})}
@@ -32,7 +32,14 @@ async function FooterLink(props: { link: CustomizationContentLink; context: Cont
return (
<Link
href={resolved.href}
className={tcls('text-sm', 'text-primary-400', 'hover:text-primary-500')}
className={tcls(
'text-sm',
'font-normal',
'text-dark/8',
'hover:text-dark/9',
'dark:text-light/8',
'dark:hover:text-light/9',
)}
>
{link.title}
</Link>
@@ -44,7 +44,7 @@ export function Dropdown<E extends HTMLElement>(props: {
'absolute',
'top-full',
'left-0',
'z-10',
'z-20',
'origin-top-left',
'invisible',
'transition-opacity',
@@ -82,11 +82,12 @@ export function Dropdown<E extends HTMLElement>(props: {
/**
* Animated chevron to display in the dropdown button.
*/
export function DropdownChevron(props: {}) {
export function DropdownChevron() {
return (
<Icon
icon="chevron-down"
className={tcls(
'shrink-0',
'opacity-6',
'size-3',
'ms-1',
@@ -1,15 +1,10 @@
import {
CustomizationSettings,
Site,
SiteCustomizationSettings,
SiteSection,
Space,
} from '@gitbook/api';
import { CustomizationSettings, Site, SiteCustomizationSettings, Space } from '@gitbook/api';
import { CustomizationHeaderPreset } from '@gitbook/api';
import { Suspense } from 'react';
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';
@@ -27,14 +22,12 @@ export function Header(props: {
space: Space;
site: Site | null;
spaces: Space[];
sections: { list: SiteSection[]; section: SiteSection } | null;
sections: SectionsList | null;
context: ContentRefContext;
customization: CustomizationSettings | SiteCustomizationSettings;
withTopHeader?: boolean;
children?: React.ReactNode;
}) {
const { children, context, space, site, spaces, sections, customization, withTopHeader } =
props;
const { context, space, site, spaces, sections, customization, withTopHeader } = props;
const isCustomizationDefault =
customization.header.preset === CustomizationHeaderPreset.Default;
const hasSiteSections = sections && sections.list.length > 1;
@@ -79,11 +72,11 @@ export function Header(props: {
)}
>
<HeaderLogo site={site} space={space} customization={customization} />
<span>
<div className="z-20">
{!hasSiteSections && isMultiVariants ? (
<SpacesDropdown space={space} spaces={spaces} />
) : null}
</span>
</div>
<HeaderLinks>
{customization.header.links.map((link, index) => {
return (
@@ -149,12 +142,12 @@ export function Header(props: {
{sections ? (
<div
className={tcls(
'w-full shadow-thintop dark:shadow-light/1 bg-light dark:bg-dark z-[9] mt-0.5',
'w-full shadow-thintop dark:shadow-light/1 bg-light dark:bg-dark mt-0.5',
// Handle long section tabs, particularly on smaller screens.
'overflow-x-auto hide-scroll',
)}
>
<div className={tcls(CONTAINER_STYLE)}>
<SiteSectionTabs sections={sections.list} section={sections.section} />
</div>
<SiteSectionTabs {...sections} />
</div>
) : null}
</header>
@@ -1,9 +1,9 @@
import {
CustomizationContentLink,
CustomizationHeaderLink,
CustomizationSettings,
CustomizationHeaderPreset,
SiteCustomizationSettings,
CustomizationHeaderItem,
} from '@gitbook/api';
import assertNever from 'assert-never';
@@ -21,93 +21,40 @@ import { Button, Link } from '../primitives';
export async function HeaderLink(props: {
context: ContentRefContext;
link: CustomizationHeaderLink;
link: CustomizationHeaderItem;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { context, link, customization } = props;
const target = await resolveContentRef(link.to, context);
if (!target) {
return null;
}
const target = link.to ? await resolveContentRef(link.to, context) : null;
const headerPreset = customization.header.preset;
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);
}
};
const linkStyle = link.style ?? 'link';
if (link.links && link.links.length > 0) {
return (
<Dropdown button={renderLink}>
<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}
/>
);
}}
>
<DropdownMenu>
{link.links.map((subLink, index) => (
<SubHeaderLink key={index} {...props} link={subLink} />
@@ -117,7 +64,128 @@ export async function HeaderLink(props: {
);
}
return renderLink({});
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>
);
}
async function SubHeaderLink(props: {
@@ -1,5 +1,5 @@
import {
CustomizationHeaderLink,
CustomizationHeaderItem,
CustomizationHeaderPreset,
CustomizationSettings,
SiteCustomizationSettings,
@@ -13,12 +13,13 @@ 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: CustomizationHeaderLink[];
links: CustomizationHeaderItem[];
context: ContentRefContext;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
@@ -43,7 +44,7 @@ export function HeaderLinkMore(props: {
);
return (
<div className={`${styles.linkEllipsis} items-center`}>
<div className={`${styles.linkEllipsis} items-center z-20`}>
<Dropdown button={renderButton} className="-translate-x-48 md:translate-x-0">
<DropdownMenu>
{links.map((link, index) => (
@@ -55,10 +56,10 @@ export function HeaderLinkMore(props: {
);
}
async function MoreMenuLink(props: { context: ContentRefContext; link: CustomizationHeaderLink }) {
async function MoreMenuLink(props: { context: ContentRefContext; link: CustomizationHeaderItem }) {
const { context, link } = props;
const target = await resolveContentRef(link.to, context);
const target = link.to ? await resolveContentRef(link.to, context) : null;
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',
'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',
)}
>
{children}
@@ -0,0 +1,27 @@
'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,11 +1,12 @@
'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';
/**
@@ -13,6 +14,13 @@ 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;
@@ -28,37 +36,44 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
});
return (
<ul className={tcls('border-l', 'border-dark/2', 'dark:border-light/1', 'space-y-1')}>
<ul className={tcls('border-l', 'border-dark/2', 'dark:border-light/1', 'pl-1')}>
{sections.map((section) => (
<li key={section.id} className={tcls('flex', 'flex-row')}>
<motion.li
key={section.id}
className={tcls('flex', 'flex-row', 'relative', 'h-fit')}
>
{activeId === section.id ? <AnimatedLine transition={springCurve} /> : null}
<a
href={`#${section.id}`}
className={tcls(
'flex',
'flex-row',
'z-10',
'w-full',
'items-baseline',
'left-[-1px]',
'relative',
'text-sm',
'py-1',
'ps-3',
'hover:text-primary',
'pe-2',
'transition-all',
'border-l',
'border-transparent',
'duration-200',
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 ? (
@@ -71,7 +86,7 @@ export function ScrollSectionsList(props: { sections: DocumentSection[] }) {
{section.title}
</a>
</li>
</motion.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, createHighlightingContext } from '../DocumentView';
import { DocumentView, DocumentViewSkeleton } from '../DocumentView';
import { PageFeedbackForm } from '../PageFeedback';
import { DateRelative } from '../primitives';
@@ -49,7 +49,6 @@ export function PageBody(props: {
const asFullWidth = document ? hasFullWidthBlock(document) : false;
const language = getSpaceLanguage(customization);
const updatedAt = page.updatedAt ?? page.createdAt;
const shouldHighlightCode = createHighlightingContext();
return (
<>
@@ -100,7 +99,6 @@ export function PageBody(props: {
contentRefContext: context,
resolveContentRef: (ref, options) =>
resolveContentRef(ref, context, options),
shouldHighlightCode,
}}
/>
</React.Suspense>
@@ -126,23 +126,6 @@
@apply [&:is(h1,h2,h3,h4)>div:first-child]:[grid-area:1/2];
@apply [&:is(h1,h2,h3,h4)>div:first-child]:ml-1;
}
/* bullet icons */
.bullet-dash {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjEiIHk9IjIuNSIgd2lkdGg9IjgiIGhlaWdodD0iMS41IiByeD0iMC42NiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==")];
}
.bullet-circleFilled {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjIiIHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHJ4PSIzIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K")];
}
.bullet-circle {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjIuNzUiIHk9IjAuNzUiIHdpZHRoPSI1LjUiIGhlaWdodD0iNS41IiByeD0iMi43NSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiLz4KPC9zdmc+Cg==")];
}
.bullet-squareFilled {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjIiIHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHJ4PSIxIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K")];
}
.bullet-square {
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxtYXNrIGlkPSJwYXRoLTEtaW5zaWRlLTFfOV80OCIgZmlsbD0id2hpdGUiPgo8cmVjdCB4PSIyIiB3aWR0aD0iNyIgaGVpZ2h0PSI3IiByeD0iMSIvPgo8L21hc2s+CjxyZWN0IHg9IjIiIHdpZHRoPSI3IiBoZWlnaHQ9IjciIHJ4PSIxIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjMiIG1hc2s9InVybCgjcGF0aC0xLWluc2lkZS0xXzlfNDgpIi8+Cjwvc3ZnPgo=")];
}
}
@layer utilities {
@@ -11,17 +11,32 @@ export function HighlightQuery(props: {
/** Style to apply on matching parts (default to primary) */
highlight?: ClassValue;
}): React.ReactElement {
const { query, text, highlight = ['text-bold', 'text-primary'] } = props;
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 matches = matchString(text, query);
return (
<span className={tcls('whitespace-break-spaces')}>
<div className={tcls('whitespace-break-spaces')}>
{matches.map((entry, index) => (
<span key={index} className={tcls(entry.match ? highlight : null)}>
{entry.text}
</span>
))}
</span>
</div>
);
}
@@ -101,20 +101,12 @@ export function SearchAskAnswer(props: { spaceId: string; query: string }) {
const loading = (
<div className={tcls('w-full', 'flex', 'items-center', 'justify-center')}>
<Loading className={tcls('w-5', 'py-4', 'text-primary')} />
<Loading className={tcls('w-6', 'py-8', 'text-primary')} />
</div>
);
return (
<div
className={tcls(
'max-h-[60vh]',
'overflow-y-auto',
'border-t',
'border-dark/2',
'dark:border-light/1',
)}
>
<div className={tcls('max-h-[60vh]', 'overflow-y-auto')}>
{state?.type === 'answer' ? (
<>
{state.answer ? (
@@ -166,13 +158,20 @@ function AnswerBody(props: { answer: AskAnswerResult }) {
<>
<div
data-test="search-ask-answer"
className={tcls('mt-4', 'px-4', 'text-dark/9', 'dark:text-light/8')}
className={tcls(
'mt-4',
'sm:mt-6',
'px-4',
'sm:px-12',
'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}
@@ -189,23 +188,25 @@ function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
const getSearchLinkProps = useSearchLink();
return (
<div className={tcls('mt-7 mb-4', 'flex', 'flex-col', 'flex-wrap', 'gap-1')}>
<div className={tcls('flex', 'flex-col', 'flex-wrap', 'mt-4', 'sm:mt-6')}>
{followupQuestions.map((question) => (
<Link
key={question}
className={tcls(
'text-sm',
'font-medium',
'inline-flex',
'items-start',
'flex',
'items-center',
'gap-2',
'px-4',
'py-1',
'text-primary-500',
'focus-within:text-primary-700',
'hover:bg-primary/2',
'dark:text-primary-400',
'dark:hover:bg-primary-500/3',
'-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',
)}
{...getSearchLinkProps({
query: question,
@@ -214,7 +215,13 @@ function AnswerFollowupQuestions(props: { followupQuestions: string[] }) {
>
<Icon
icon="magnifying-glass"
className={tcls('size-[15px]', 'shrink-0', 'mt-0.5', '[opacity:0.64]')}
className={tcls(
'size-4',
'shrink-0',
'mr-2',
'text-dark/5',
'dark:text-light/5',
)}
/>
<span>{question}</span>
</Link>
@@ -236,7 +243,8 @@ function AnswerSources(props: {
'flex',
'flex-wrap',
'gap-2',
'mt-7',
'mt-4',
'sm:mt-6',
'py-4',
'px-4',
'border-t',
@@ -244,7 +252,7 @@ function AnswerSources(props: {
'dark:border-light/1',
)}
>
<span className={tcls('text-sm')}>
<span>
{t(language, hasAnswer ? 'search_ask_sources' : 'search_ask_sources_no_answer')}
</span>
@@ -253,7 +261,9 @@ function AnswerSources(props: {
<Link
className={tcls(
'flex',
'text-sm',
'flex-wrap',
'gap-1',
'items-center',
'text-dark/7',
'hover:underline',
'focus-within:text-primary-700',
@@ -266,11 +276,8 @@ function AnswerSources(props: {
icon="arrow-up-right"
className={tcls(
'text-dark/6',
'w-[15px]',
'h-[15px]',
'size-4',
'shrink-0',
'mt-0.5',
'mr-0.5',
'dark:text-light/6',
)}
/>
@@ -182,7 +182,7 @@ function SearchModalBody(
};
return (
<div
<motion.div
role="dialog"
aria-label={tString(language, 'search')}
className={tcls(
@@ -193,29 +193,55 @@ 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-center')}>
<div className={tcls('p-2', 'pl-4')}>
<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')}>
<Icon
icon="magnifying-glass"
className={tcls('size-4', 'text-dark/4', 'dark:text-light/5')}
/>
</div>
<div className={tcls('flex-1')}>
<div
className={tcls(
'w-full',
'flex',
'flex-row',
'flex-wrap',
'gap-y-0',
'gap-x-4',
'items-end',
)}
>
<input
ref={inputRef}
value={state.query}
@@ -226,7 +252,7 @@ function SearchModalBody(
'placeholder:text-dark/7',
'flex',
'resize-none',
'w-full',
'flex-1',
'h-12',
'p-2',
'focus:outline-none',
@@ -243,6 +269,7 @@ function SearchModalBody(
autoComplete="off"
autoCorrect="off"
/>
{isMultiVariants ? <SearchScopeToggle spaceTitle={spaceTitle} /> : null}
</div>
</div>
{!state.ask || !withAsk ? (
@@ -261,15 +288,11 @@ function SearchModalBody(
global: state.global,
});
}}
>
{isMultiVariants && state.query ? (
<SearchScopeToggle spaceTitle={spaceTitle} />
) : null}
</SearchResults>
></SearchResults>
) : null}
{state.query && state.ask && withAsk ? (
<SearchAskAnswer spaceId={spaceId} query={state.query} />
) : null}
</div>
</motion.div>
);
}
@@ -1,3 +1,4 @@
import { Icon } from '@gitbook/icons';
import React from 'react';
import { tcls } from '@/lib/tailwind';
@@ -23,25 +24,46 @@ export const SearchPageResultItem = React.forwardRef(function SearchPageResultIt
className={tcls(
'flex',
'flex-row',
'px-6',
'py-3',
'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',
'hover:bg-dark-4/2',
'text-base',
'text-dark',
'font-semibold',
'font-medium',
'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,
)}
>
{item.spaceTitle ? (
<span className={tcls('opacity-6', 'font-normal', 'mr-2')}>
{item.spaceTitle + ' '}
</span>
) : null}
<HighlightQuery query={query} text={item.title} />
<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')}
/>
</Link>
);
});
@@ -31,8 +31,6 @@ 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',
@@ -47,11 +45,11 @@ export const SearchQuestionResultItem = React.forwardRef(function SearchQuestion
<Icon
icon="magnifying-glass"
className={tcls(
'w-[15px]',
'h-[15px]',
'size-4',
'shrink-0',
'mt-0.5',
'mr-4',
'mt-1',
'text-dark/5',
'dark:text-light/5',
)}
@@ -174,24 +174,15 @@ export const SearchResults = React.forwardRef(function SearchResults(
}
return (
<div
className={tcls(
'max-h-[60vh]',
'overflow-auto',
'relative',
'shadow-[0_1px_0_0_inset]',
'shadow-dark/2',
'dark:shadow-light/2',
)}
>
<div className={tcls('max-h-[70vh]', 'overflow-auto', 'relative')}>
{children}
{results.length === 0 ? (
<div
data-test="search-noresults"
className={tcls(
'text-sm',
'text-dark',
'p-6',
'text',
'text-dark/8',
'p-8',
'text-center',
'dark:text-light/8',
)}
@@ -20,31 +20,7 @@ export function SearchScopeToggle(props: { spaceTitle: string }) {
<div
role="toolbar"
aria-orientation="horizontal"
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',
)}
className={tcls('flex', 'flex-row', 'mr-4')}
>
<ToggleButton
active={!state.global}
@@ -81,30 +57,14 @@ function ToggleButton(props: { onClick: () => void; children: React.ReactNode; a
aria-selected={active}
onClick={onClick}
className={tcls(
'text-xs',
'text-sm',
'transition-colors',
'duration-75',
'px-2.5',
'py-1.5',
'border-t',
'relative',
'top-[0px]',
'z-[1]',
'border-dark/2',
'px-3',
'py-2',
'border-b-2',
'whitespace-pre',
'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,
'-mb-[1px]',
active ? ['text-primary-500', 'border-primary-500'] : ['border-transparent'],
)}
>
{children}
@@ -25,15 +25,29 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
'[&:has(+:not(&))]:mb-6',
'flex',
'flex-col',
'pl-6',
'mb-2',
'px-4',
'sm:px-12',
'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', 'p-3', 'border-dark/2', 'dark:border-light/2')}>
<div
className={tcls(
'border-l-2',
'px-4',
'py-2',
'border-dark/2',
'dark:border-light/2',
)}
>
{item.title ? (
<p className={tcls('text-base', 'text-dark/7', 'dark:text-light/8')}>
<p className={tcls('text-base', 'mb-2')}>
<HighlightQuery query={query} text={item.title} />
</p>
) : null}
@@ -41,12 +55,9 @@ export const SearchSectionResultItem = React.forwardRef(function SearchSectionRe
<p
className={tcls(
'text-sm',
'text-dark',
'line-clamp-6',
'linear-mask-gradient',
'line-clamp-3',
'z-[-1]', //to force stacking order
'relative',
'dark:text-light/8',
)}
>
<HighlightQuery query={query} text={item.body} />
@@ -68,16 +68,11 @@ async function searchSiteContent(args: {
scope.mode === 'current' ||
(scope.mode === 'specific' && scope.siteSpaceIds.length > 1);
const [searchResults, siteStructure] = await Promise.all([
const [searchResults, siteData] = await Promise.all([
api.searchSiteContent(pointer.organizationId, pointer.siteId, query, scope, cacheBust),
needsStructure
? api.getSiteStructure({
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
})
: null,
needsStructure ? api.getSiteData(pointer) : null,
]);
const siteStructure = siteData?.structure;
const siteSpaces = siteStructure
? siteStructure.type === 'siteSpaces'
@@ -87,7 +82,7 @@ async function searchSiteContent(args: {
...siteSpace,
space: {
...siteSpace.space,
title: section.title + ' ' + siteSpace.space.title,
title: section.title || siteSpace.space.title,
},
}));
@@ -215,7 +210,6 @@ function transformAnswer(
mode: 'default',
contentRefContext: null,
resolveContentRef: async () => null,
shouldHighlightCode: () => true,
wrapBlocksInSuspense: false,
}}
style={['space-y-5']}
@@ -0,0 +1,21 @@
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,107 +1,132 @@
'use client';
import { SiteSection } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import type { SiteSection } from '@gitbook/api';
import type { IconName } from '@gitbook/icons';
import React from 'react';
import { tcls } from '@/lib/tailwind';
import { Button, Link } from '../primitives';
import { Link } from '../primitives';
import { SectionIcon } from './SectionIcon';
/**
* A set of tabs representing site sections for multi-section sites
* A set of navigational tabs representing site sections for multi-section sites
*/
export function SiteSectionTabs(props: { sections: SiteSection[]; section: SiteSection }) {
const { sections, section: currentSection } = props;
const tabs = sections.map((section) => ({
id: section.id,
label: section.title,
path: section.urls.published ?? '',
}));
export function SiteSectionTabs(props: {
list: SiteSection[];
section: SiteSection;
index: number;
}) {
const { list: sections, index: currentIndex } = props;
const currentTabRef = React.useRef<HTMLAnchorElement>(null);
const navRef = React.useRef<HTMLDivElement>(null);
const [currentIndex, setCurrentIndex] = React.useState(
sections.findIndex((section) => section.id === currentSection?.id),
);
const [tabDimensions, setTabDimensions] = React.useState<{
left: number;
width: number;
} | null>(null);
React.useEffect(() => {
const updateTabDimensions = React.useCallback(() => {
if (currentTabRef.current && navRef.current) {
const rect = currentTabRef.current.getBoundingClientRect();
const navRect = navRef.current.getBoundingClientRect();
setTabDimensions({ left: rect.left - navRect.left, width: rect.width });
}
}, [currentIndex]);
React.useLayoutEffect(() => {
function onResize() {
if (currentTabRef.current && navRef.current) {
const rect = currentTabRef.current.getBoundingClientRect();
const navRect = navRef.current.getBoundingClientRect();
setTabDimensions({ left: rect.left - navRect.left, width: rect.width });
}
setTabDimensions({
left: rect.left - navRect.left,
width: rect.width,
});
}
window.addEventListener('resize', onResize);
() => window.removeEventListener('resize', onResize);
}, []);
React.useEffect(() => {
if (currentIndex >= 0) {
updateTabDimensions();
}
}, [currentIndex, updateTabDimensions]);
React.useLayoutEffect(() => {
window.addEventListener('load', updateTabDimensions);
window.addEventListener('resize', updateTabDimensions);
() => {
window.removeEventListener('resize', updateTabDimensions);
window.removeEventListener('load', updateTabDimensions);
};
}, [updateTabDimensions]);
const opacity = tabDimensions ? 1 : 0.0;
const scale = (tabDimensions?.width ?? 0) * 0.01;
const startPos = `${tabDimensions?.left ?? 0}px`;
const hasMoreSections = false; /** TODO: determine whether we need to show the more button */
return tabs.length > 0 ? (
return sections.length > 0 ? (
<nav
aria-label="Sections"
ref={navRef}
className="flex flex-nowrap items-center max-w-screen mb-px"
className="flex flex-nowrap items-center mb-px max-w-screen-2xl mx-auto page-full-width:max-w-full"
style={
{
'--tab-opacity': `${opacity}`,
'--tab-scale': `${scale}`,
'--tab-start': `${startPos}`,
} as React.CSSProperties
}
>
<div
className={tcls(
'relative',
'flex',
'gap-2',
'bg-transparent',
/* add a pseudo element for active tab indicator */
'after:block',
"after:content-['']",
'after:origin-left',
'after:absolute',
'after:-bottom-px',
'after:left-0',
'after:scale-x-[--tab-scale]',
'after:transition-transform',
'after:translate-x-[var(--tab-start)]',
'after:h-0.5',
'after:w-[100px]',
'after:bg-primary',
'dark:after:bg-primary-400',
)}
role="tablist"
>
{tabs.map((tab, index) => (
<Tab
active={currentIndex === index}
key={index + tab.path}
label={tab.label}
href={tab.path}
ref={currentIndex === index ? currentTabRef : null}
onClick={() => setCurrentIndex(index)}
/>
))}
<div className="flex flex-col bg-transparent">
{/* An element for the tabs which includes the page padding */}
<div
role="tablist"
className={tcls(
'flex flex-row gap-2',
// Horizontal padding, which is the layout padding minus the padding of the tabs themselves.
'px-1',
'sm:px-3',
'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
}
/>
);
})}
</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. */}
<div
className={tcls(
'flex',
'relative',
'after:block',
"after:content-['']",
'after:origin-left',
'after:absolute',
'after:-bottom-px',
'after:left-0',
'after:opacity-[--tab-opacity]',
'after:scale-x-[--tab-scale]',
'after:[transition:_opacity_150ms_25ms,transform_150ms]',
'after:motion-reduce:transition-none',
'after:translate-x-[var(--tab-start)]',
'after:will-change-transform',
'after:h-0.5',
'after:w-[100px]',
'after:bg-primary',
'dark:after:bg-primary-400',
)}
/>
</div>
{hasMoreSections ? <MoreSectionsButton /> : null}
</nav>
) : null;
}
@@ -111,37 +136,24 @@ export function SiteSectionTabs(props: { sections: SiteSection[]; section: SiteS
*/
const Tab = React.forwardRef<
HTMLSpanElement,
{ active: boolean; href: string; label: string; onClick?: () => void }
{ active: boolean; href: string; icon?: React.ReactNode; label: string }
>(function Tab(props, ref) {
const { active, href, label, onClick } = props;
const { active, href, icon, label } = props;
return (
<Link
className={tcls(
'px-3 py-1 my-2 rounded straight-corners:rounded-none transition-colors',
'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}
onClick={onClick}
>
<span ref={ref} className={tcls('inline-flex w-full truncate')}>
<span ref={ref} className={tcls('flex gap-2 items-center w-full truncate')}>
{icon}
{label}
</span>
</Link>
);
});
/**
* Dropdown trigger for when there are too many sections to show them all
*/
function MoreSectionsButton() {
return (
<div>
<Button variant="secondary" size="small">
<Icon icon="ellipsis-h" size={12} />
</Button>
</div>
);
}
@@ -6,7 +6,6 @@ import {
RevisionPageGroup,
Site,
SiteCustomizationSettings,
SiteSection,
Space,
} from '@gitbook/api';
import React from 'react';
@@ -17,7 +16,7 @@ import { CONTAINER_STYLE } from '@/components/layout';
import { ColorDebugger } from '@/components/primitives/ColorDebugger';
import { SearchModal } from '@/components/Search';
import { TableOfContents } from '@/components/TableOfContents';
import { ContentTarget, SiteContentPointer } from '@/lib/api';
import { ContentTarget, type SectionsList, SiteContentPointer } from '@/lib/api';
import { ContentRefContext } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
@@ -31,7 +30,7 @@ export function SpaceLayout(props: {
contentTarget: ContentTarget;
space: Space;
site: Site | null;
sections: { list: SiteSection[]; section: SiteSection } | null;
sections: SectionsList | null;
spaces: Space[];
customization: CustomizationSettings | SiteCustomizationSettings;
pages: Revision['pages'];
@@ -8,13 +8,16 @@ import { useHash } from './useHash';
* to the top of the page when navigating between pages (pathname)
* or sections of a page (hash).
*/
export function useScrollPage() {
export function useScrollPage(props: { scrollMarginTop?: number }) {
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',
@@ -23,5 +26,13 @@ export function useScrollPage() {
} else {
window.scrollTo(0, 0);
}
}, [hash, pathname]);
return () => {
if (hash) {
const element = document.getElementById(hash);
if (element) {
element.style.scrollMarginTop = '';
}
}
};
}, [hash, pathname, props.scrollMarginTop]);
}
@@ -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}>
<Link href={href} className={domClassName} {...rest}>
{children}
</Link>
);
}
return (
<button type="button" onClick={onClick} className={domClassName}>
<button type="button" className={domClassName} {...rest}>
{children}
</button>
);
@@ -6,16 +6,22 @@ import React from 'react';
import { tcls } from '@/lib/tailwind';
export type CheckboxProps = React.ComponentProps<typeof CheckboxPrimitive.Root> & {
/**
* The size of the checkbox.
* @default medium
*/
size?: 'small' | 'medium';
};
export const Checkbox = React.forwardRef<
React.ElementRef<typeof CheckboxPrimitive.Root>,
React.ComponentPropsWithoutRef<typeof CheckboxPrimitive.Root>
>(({ className, ...props }, ref) => (
CheckboxProps
>(({ className, size = 'medium', ...props }, ref) => (
<CheckboxPrimitive.Root
ref={ref}
className={tcls(
'peer',
'h-5',
'w-5',
'shrink-0',
'rounded-sm',
'straight-corners:rounded-none',
@@ -32,11 +38,12 @@ export const Checkbox = React.forwardRef<
'dark:ring-light/3',
'dark:contrast-more:ring-light/6',
'dark:data-[state=checked]:bg-primary-500',
{ small: 'size-4', medium: 'size-5' }[size],
className,
)}
{...props}
>
<CheckboxPrimitive.Indicator className={tcls('relative', 'text-current')}>
<CheckboxPrimitive.Indicator className="relative text-current">
{props.checked ? (
<Icon icon="check" iconStyle={IconStyle.Solid} className={'size-3'} />
) : null}
+1
View File
@@ -39,6 +39,7 @@ export const ibmPlexMono = IBM_Plex_Mono({
display: 'swap',
preload: false,
fallback: ['monospace'],
adjustFontFallback: false,
});
const firaSans = Fira_Sans_Extra_Condensed({
+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: 'Nur in ${1}',
search_scope_space: '${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: 'Only in ${1}',
search_scope_all: 'All the content',
search_scope_space: '${1}',
search_scope_all: 'All 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: 'Solo en ${1}',
search_scope_space: '${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: 'Uniquement dans ${1}',
search_scope_space: '${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: 'Alleen in ${1}',
search_scope_space: '${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: 'Kun i ${1}',
search_scope_space: '${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: 'Somente em ${1}',
search_scope_space: '${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: '来源',
+127 -198
View File
@@ -13,11 +13,15 @@ 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 { DeepPartial } from 'ts-essentials';
import { assert, DeepPartial } from 'ts-essentials';
import { batch } from './async';
import { buildVersion } from './build';
@@ -131,22 +135,10 @@ export function withAPI<T>(client: GitBookAPI, fn: () => Promise<T>): Promise<T>
return apiSyncStorage.run(client, fn);
}
// 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;
};
type SpaceContentLookup = Pick<
PublishedSiteContent,
'space' | 'changeRequest' | 'revision' | 'pathname' | 'basePath' | 'apiToken'
> & { kind: 'space' };
export type PublishedContentWithCache =
| ((SpaceContentLookup | PublishedSiteContentLookup) & {
@@ -629,83 +621,48 @@ export const getDocument = cache({
});
/**
* Get the customization settings for a site-space from the API.
* Resolve a site redirect by its source path.
*/
const getSiteSpaceCustomizationFromAPI = cache({
name: 'api.getSiteSpaceCustomizationById',
tag: (organizationId, siteId, siteSpaceId) => getAPICacheTag({ tag: 'site', site: siteId }),
export const getSiteRedirectBySource = cache({
name: 'api.getSiteRedirectBySource',
tag: ({ siteId }) => getAPICacheTag({ tag: 'site', site: siteId }),
get: async (
organizationId: string,
siteId: string,
siteSpaceId: string,
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;
},
options: CacheFunctionOptions,
) => {
const response = await api().orgs.getSiteSpaceCustomizationById(
organizationId,
siteId,
siteSpaceId,
{},
{
signal: options.signal,
...noCacheFetchOptions,
},
);
return cacheResponse(response, {
revalidateBefore: 60 * 60,
});
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;
}
},
});
/**
* 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.
*/
@@ -724,59 +681,24 @@ export const getSite = cache({
});
/**
* List all the site-spaces variants published in a site.
* Get the published content site data for a site's published experience
*/
export const getSiteSpaces = cache({
name: 'api.getSiteSpaces',
export const getPublishedContentSite = cache({
name: 'api.getPublishedContentSite',
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 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(
const response = await api().orgs.getPublishedContentSite(
args.organizationId,
args.siteId,
{
...(args.siteShareKey ? { shareKey: args.siteShareKey } : {}),
shareKey: args.siteShareKey,
},
{
...noCacheFetchOptions,
@@ -785,89 +707,96 @@ export const getSiteStructure = cache({
);
return cacheResponse(response, {
revalidateBefore: 60 * 60,
data: response.data,
});
},
});
/**
* 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,
});
},
});
export type SectionsList = { list: SiteSection[]; section: SiteSection; index: number };
/**
* Fetch all the data to render the current site at once.
* Parse the site spaces into a list of spaces with their title and urls.
*/
export async function getSiteData(pointer: SiteContentPointer) {
const [{ space, pages, contentTarget }, { customization, scripts }] = await Promise.all([
getSpaceContentData(pointer, pointer.siteShareKey),
getSiteLayoutData(pointer),
]);
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);
}
return {
space,
pages,
contentTarget,
customization,
scripts,
};
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;
}
/**
* Fetch all the layout data about the current site at once.
* This function fetches the published content site data to render the published
* experience for the site (structure, customizations, scripts etc)
*/
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),
]);
export async function getSiteData(
pointer: Pick<
SiteContentPointer,
'organizationId' | 'siteId' | 'siteSectionId' | 'siteSpaceId' | 'siteShareKey'
>,
) {
const {
site: orgSite,
structure: siteStructure,
customizations,
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,
);
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 async function getSpaceCustomization(spaceId: string): Promise<CustomizationSettings> {
export function getSpaceCustomization(spaceId: string): { customization: CustomizationSettings } {
const headersList = headers();
const raw = defaultCustomizationForSpace();
@@ -875,7 +804,7 @@ export async function getSpaceCustomization(spaceId: string): Promise<Customizat
if (extend) {
try {
const parsed = rison.decode_object<Partial<CustomizationSettings>>(extend);
return { ...raw, ...parsed };
return { customization: { ...raw, ...parsed } };
} catch (error) {
console.error(
`Failed to parse x-gitbook-customization header (ignored): ${
@@ -885,7 +814,9 @@ export async function getSpaceCustomization(spaceId: string): Promise<Customizat
}
}
return raw;
return {
customization: raw,
};
}
/**
@@ -946,13 +877,11 @@ export async function getSpaceContentData(
spaceId: pointer.spaceId,
revisionId: changeRequest?.revision ?? pointer.revisionId ?? space.revision,
};
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,
}),
]);
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,
});
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:;
frame-ancestors https: ${process.env.NODE_ENV !== 'production' ? 'http:' : ''};
`;
const result = scripts
+28 -28
View File
@@ -4,7 +4,7 @@ import fnv1a from '@sindresorhus/fnv1a';
import { noCacheFetchOptions } from '@/lib/cache/http';
import { rootUrl } from './links';
import { host, rootUrl } from './links';
import { getImageAPIUrl } from './urls';
export interface CloudflareImageJsonFormat {
@@ -31,6 +31,8 @@ export interface CloudflareImageOptions {
quality?: number;
}
export const imagesResizingSignVersion = '2';
/**
* Return true if images resizing is enabled.
*/
@@ -53,17 +55,26 @@ 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;
}
return checkIsHttpURL(parsed);
if (!checkIsHttpURL(parsed)) {
return false;
}
return true;
}
interface ResizeImageOptions {
@@ -83,7 +94,7 @@ export function getResizedImageURLFactory(
return null;
}
const signature = generateSignatureV1(input);
const signature = generateSignature(input);
return (options) => {
const url = new URL('/~gitbook/image', rootUrl());
@@ -103,7 +114,7 @@ export function getResizedImageURLFactory(
}
url.searchParams.set('sign', signature);
url.searchParams.set('sv', '1');
url.searchParams.set('sv', imagesResizingSignVersion);
return url.toString();
};
@@ -123,11 +134,9 @@ export function getResizedImageURL(input: string, options: ResizeImageOptions):
*/
export async function verifyImageSignature(
input: string,
{ signature, version }: { signature: string; version: '1' | '0' },
{ signature }: { signature: string },
): Promise<boolean> {
const expectedSignature =
version === '1' ? generateSignatureV1(input) : await generateSignatureV0(input);
return expectedSignature === signature;
return generateSignature(input) === signature;
}
/**
@@ -229,26 +238,17 @@ function stringifyOptions(options: CloudflareImageOptions): string {
const fnv1aUtf8Buffer = new Uint8Array(512);
/**
* 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.
* 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.
*/
function generateSignatureV1(input: string): string {
const all = [input, process.env.GITBOOK_IMAGE_RESIZE_SIGNING_KEY].filter(Boolean).join(':');
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(':');
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;
}
+42
View File
@@ -1,3 +1,45 @@
import { AsyncLocalStorage } from 'node:async_hooks';
/**
* Set a header on the middleware response.
* We do this because of https://github.com/opennextjs/opennextjs-cloudflare/issues/92
* It can be removed as soon as we move to opennext where hopefully this is fixed.
*/
export function setMiddlewareHeader(response: Response, name: string, value: string) {
const responseHeadersLocalStorage =
// @ts-ignore
globalThis.responseHeadersLocalStorage as AsyncLocalStorage<Headers> | undefined;
const responseHeaders = responseHeadersLocalStorage?.getStore();
response.headers.set(name, value);
if (responseHeaders) {
responseHeaders.set(name, value);
}
}
/**
* Wrap some middleware with a the storage to store headers.
*/
export async function withMiddlewareHeadersStorage(
handler: () => Promise<Response>,
): Promise<Response> {
const responseHeadersLocalStorage =
// @ts-ignore
(globalThis.responseHeadersLocalStorage as AsyncLocalStorage<Headers>) ??
new AsyncLocalStorage<Headers>();
// @ts-ignore
globalThis.responseHeadersLocalStorage = responseHeadersLocalStorage;
const responseHeaders = new Headers();
const response = await responseHeadersLocalStorage.run(responseHeaders, handler);
for (const [name, value] of responseHeaders.entries()) {
response.headers.set(name, value);
}
return response;
}
/**
* For a given GitBook URL, return a list of alternative URLs that could be matched against to lookup the content.
* The approach is optimized to aim at reusing cached lookup results as much as possible.
+55 -8
View File
@@ -1,9 +1,11 @@
import {
ContentRef,
ContentRefSpace,
Revision,
RevisionFile,
RevisionPageDocument,
RevisionReusableContent,
SiteSpace,
Space,
} from '@gitbook/api';
import assertNever from 'assert-never';
@@ -16,12 +18,14 @@ 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';
@@ -205,12 +209,7 @@ export async function resolveContentRef(
const targetSpace =
contentRef.space === space.id
? space
: await ignoreAPIError(
getSpace(
contentRef.space,
siteContext?.siteShareKey ? siteContext.siteShareKey : undefined,
),
);
: await getBestTargetSpace(contentRef.space, siteContext);
if (!targetSpace) {
return {
@@ -287,6 +286,50 @@ 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,
@@ -296,12 +339,16 @@ async function resolveContentRefInSpace(
spaceId,
};
const result = await ignoreAPIError(getSpaceContentData(pointer, siteContext?.siteShareKey));
const [result, bestTargetSpace] = await Promise.all([
ignoreAPIError(getSpaceContentData(pointer, siteContext?.siteShareKey)),
getBestTargetSpace(spaceId, siteContext),
]);
if (!result) {
return null;
}
const { space, pages } = result;
const { pages } = result;
const space = bestTargetSpace ?? result.space;
// Base URL to use to prepend to relative URLs.
let baseUrl = space.urls.published ?? space.urls.app;
+52 -53
View File
@@ -14,13 +14,13 @@ import {
userAgent,
withAPI,
DEFAULT_API_ENDPOINT,
getSiteLayoutData,
getSite,
getPublishedContentSite,
getSiteData,
} from '@/lib/api';
import { race } from '@/lib/async';
import { buildVersion } from '@/lib/build';
import { createContentSecurityPolicyNonce, getContentSecurityPolicy } from '@/lib/csp';
import { getURLLookupAlternatives, normalizeURL } from '@/lib/middleware';
import { getURLLookupAlternatives, normalizeURL, setMiddlewareHeader } from '@/lib/middleware';
import {
VisitorAuthCookieValue,
getVisitorAuthCookieName,
@@ -161,26 +161,31 @@ export async function middleware(request: NextRequest) {
userAgent: userAgent(),
}),
async () => {
// 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 [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,
),
),
);
]);
const { scripts } = await ('site' in resolved
? getSiteLayoutData({
organizationId: resolved.organization,
siteId: resolved.site,
siteSpaceId: resolved.siteSpace,
})
: { scripts: [] });
const scripts = siteData?.scripts ?? [];
return getContentSecurityPolicy(scripts, nonce);
},
);
@@ -253,43 +258,31 @@ export async function middleware(request: NextRequest) {
resolved.cookies,
);
response.headers.set('x-gitbook-version', buildVersion());
setMiddlewareHeader(response, 'x-gitbook-version', buildVersion());
// Add Content Security Policy header
response.headers.set('content-security-policy', csp);
setMiddlewareHeader(response, 'content-security-policy', csp);
// Basic security headers
response.headers.set('strict-transport-security', 'max-age=31536000');
response.headers.set('referrer-policy', 'no-referrer-when-downgrade');
response.headers.set('x-content-type-options', 'nosniff');
setMiddlewareHeader(response, 'strict-transport-security', 'max-age=31536000');
setMiddlewareHeader(response, 'referrer-policy', 'no-referrer-when-downgrade');
setMiddlewareHeader(response, 'x-content-type-options', 'nosniff');
const isPrefetch = request.headers.has('x-middleware-prefetch');
if (typeof resolved.cacheMaxAge === 'number') {
const cacheControl = `public, max-age=0, s-maxage=${resolved.cacheMaxAge}, stale-if-error=0`;
if (isPrefetch) {
// To avoid cache poisoning, we don't cache prefetch requests
response.headers.set(
'cache-control',
'private, no-cache, no-store, max-age=0, must-revalidate',
);
} else {
if (typeof resolved.cacheMaxAge === 'number') {
const cacheControl = `public, max-age=0, s-maxage=${resolved.cacheMaxAge}, stale-if-error=0`;
if (
process.env.GITBOOK_OUTPUT_CACHE === 'true' &&
process.env.NODE_ENV !== 'development'
) {
response.headers.set('cache-control', cacheControl);
response.headers.set('Cloudflare-CDN-Cache-Control', cacheControl);
} else {
response.headers.set('x-gitbook-cache-control', cacheControl);
}
if (process.env.GITBOOK_OUTPUT_CACHE === 'true' && process.env.NODE_ENV !== 'development') {
setMiddlewareHeader(response, 'cache-control', cacheControl);
setMiddlewareHeader(response, 'Cloudflare-CDN-Cache-Control', cacheControl);
} else {
setMiddlewareHeader(response, 'x-gitbook-cache-control', cacheControl);
}
}
// }
if (resolved.cacheTags && resolved.cacheTags.length > 0) {
const headerCacheTag = resolved.cacheTags.join(',');
response.headers.set('cache-tag', headerCacheTag);
response.headers.set('x-gitbook-cache-tag', headerCacheTag);
}
if (resolved.cacheTags && resolved.cacheTags.length > 0) {
const headerCacheTag = resolved.cacheTags.join(',');
setMiddlewareHeader(response, 'cache-tag', headerCacheTag);
setMiddlewareHeader(response, 'x-gitbook-cache-tag', headerCacheTag);
}
return response;
@@ -492,7 +485,13 @@ 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, () => getSite.revalidate(decoded.organization, source.id));
await withAPI(gitbookAPI, () =>
getPublishedContentSite.revalidate({
organizationId: decoded.organization,
siteId: source.id,
siteShareKey: undefined,
}),
);
}
const cookies: LookupCookies = {
@@ -502,7 +501,7 @@ async function lookupSiteOrSpaceInMultiIdMode(
httpOnly: true,
maxAge: 60 * 30,
secure: process.env.NODE_ENV === 'production',
sameSite: 'none',
sameSite: process.env.NODE_ENV === 'production' ? 'none' : undefined,
},
},
};

Some files were not shown because too many files have changed in this diff Show More