Compare commits

...

81 Commits

Author SHA1 Message Date
Claire Chabas 0780396e81 keep useless import to keep PR in scope 2025-01-30 19:01:19 +01:00
Claire Chabas ce082549d8 Merge branch 'main' into claire/update-node-version-required
* main:
  Avoid dereferencing before caching (#2793)
2025-01-30 18:56:30 +01:00
Greg Bergé d9c8d57e8e Avoid dereferencing before caching (#2793) 2025-01-30 17:15:19 +01:00
Claire Chabas bae43d08ff Update Node version required 2025-01-30 17:05:35 +01:00
Greg Bergé 0d615e3888 Highlight code client-side (#2786) 2025-01-30 16:08:39 +01:00
Greg Bergé 68287d3df4 Cache API spec for 24 hours, revalidated every 2 hours (#2792) 2025-01-30 15:16:45 +01:00
Greg Bergé dff08ae3e3 Load Scalar only when the button is pressed (#2790) 2025-01-30 15:01:59 +01:00
Zeno Kapitein 8cfa67c1dd Fix default outline list styling (#2788) 2025-01-30 13:56:43 +01:00
Greg Bergé b41d425993 Improve OpenAPI performances (#2784) 2025-01-30 11:13:01 +01:00
Greg Bergé 12c7862250 Use Scalar OpenAPI parser (#2780) 2025-01-30 08:44:08 +01:00
Greg Bergé 6f54826296 Replace highlight colors (#2781) 2025-01-29 15:00:01 +01:00
Steven H ccf2cffc4b Hotfix docs.radiantdrift.com crashing in production. (#2782) 2025-01-29 12:42:01 +00:00
Zeno Kapitein f7b801b4c8 Support user comments after rating (#2771)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2025-01-28 09:39:32 +01:00
Samy Pessé 95f2aa45eb Integration with new site insights (#2777) 2025-01-28 09:18:50 +01:00
Samy Pessé 9524ff5f5a Migrate to bun text-based lockfile (#2770) 2025-01-28 08:47:40 +01:00
Steven H 1823101b03 Fix internal properties appearing in OpenAPI docs. (#2774) 2025-01-23 21:35:06 +00:00
Samy Pessé 1a8cfd2a8b Hide toolbar when previewing (#2773) 2025-01-23 21:58:02 +01:00
Greg Bergé 5b4e710770 Support llms.txt (#2768) 2025-01-23 16:37:45 +01:00
Zeno Kapitein 1762f85ef9 Reduce gap between subsequent header buttons (#2765) 2025-01-23 14:10:47 +01:00
Samy Pessé d370a3f0e3 Align the revisions/changes path for multi-id with the normal one (#2769) 2025-01-23 10:00:11 +01:00
Greg Bergé d3e573c2e9 Generate sitemap for all sections and spaces (#2767) 2025-01-22 16:57:57 +01:00
Zeno Kapitein 94876e3ad1 Fix regression issue with page icons for multi-line titles (#2764) 2025-01-21 17:03:33 +01:00
Zeno Kapitein ad190602c7 Tweak card background, better margins for card headings (#2763) 2025-01-21 17:03:22 +01:00
Scott Cazan 162b4b78b6 Add HTTP examples to API blocks (#2759) 2025-01-21 15:34:42 +01:00
Zeno Kapitein e5dc05e994 Restyle footer, allow >4 link groups (#2761) 2025-01-21 14:50:33 +01:00
Samy Pessé b46cff70c0 Fix insights prop passed to Link (#2760) 2025-01-21 07:52:00 +01:00
Greg Bergé b6c3870eda Add support for keyboard marks (#2758) 2025-01-20 12:06:38 +01:00
Taran Vohra 1c1f504601 Fix Image zoom e2e test (#2757) 2025-01-20 16:13:23 +05:30
Taran Vohra 1b8a45678c Fix image blocks zoomable behaviour (#2756) 2025-01-20 13:22:12 +05:30
Viktor Renkema 38de9eb9d7 Restore borders on embed blocks with Captions (#2755) 2025-01-17 12:50:23 +01:00
Greg Bergé eac1314a7d Lazy load iframely script (#2753) 2025-01-17 08:28:38 +01:00
Greg Bergé 29d59793dc Disable C/C++ highlight temporarily (#2754) 2025-01-17 08:28:10 +01:00
Greg Bergé 128ad20280 Ignore cache invalidation error from local backend (#2752) 2025-01-15 14:13:10 +01:00
Viktor Renkema 994ebff8c1 Remove borders on Caption wrapper (#2742) 2025-01-15 12:05:13 +01:00
Greg Bergé 142938401c Fix error when accessing some not found pages (#2751) 2025-01-15 12:04:27 +01:00
Greg Bergé 65cc4afb23 Fix error when accessing a change request not found (#2723) 2025-01-14 19:52:26 +01:00
Greg Bergé e000f23c44 Fix visual testing flakiness (#2750) 2025-01-14 18:03:29 +01:00
Claire Chabas 1de9d1aa33 Antialias text but not code/pre elements (#2747) 2025-01-14 15:48:05 +01:00
Zeno Kapitein 0e601e277b Header button styling (#2748) 2025-01-14 15:20:26 +01:00
Greg Bergé e582a47f37 Remove screenshot from VA test (#2749) 2025-01-14 15:05:04 +01:00
Greg Bergé 1b251a78b0 Fix visitor authentication end-to-end tests (#2746) 2025-01-14 14:42:58 +01:00
Zeno Kapitein 24f5249ae9 Fix vertical section overflow (#2744) 2025-01-14 12:49:20 +01:00
Greg Bergé 17c1631013 Visual testing stabilization (#2741) 2025-01-14 12:39:12 +01:00
Greg Bergé cb100d5e00 Allow only valid values for theme query string (#2745) 2025-01-14 12:33:59 +01:00
Greg Bergé 1fcc807513 Fix customization not found (#2734) 2025-01-14 12:09:43 +01:00
Zeno Kapitein 5664e5a30f Fix variant dropdown styling in header (#2730) 2025-01-14 12:09:04 +01:00
Taran Vohra 26e64019d8 Remove KV cache backend and only use DO cache (#2743) 2025-01-14 16:29:48 +05:30
Zeno Kapitein 56331d2e74 Fix breadcrumbs emoji display + add contrast styles (#2735) 2025-01-14 11:46:26 +01:00
Greg Bergé 55b095e503 Wait for icons to be loaded before screenshot (#2740) 2025-01-14 10:35:44 +01:00
Scott Cazan 6a073e1dd5 Enable anti-aliasing for published docs (#2736) 2025-01-14 10:13:40 +01:00
Viktor Renkema 960e25a3f6 Apply vertical alignment to Tables as configured in-app (#2627) 2025-01-14 09:45:15 +01:00
Greg Bergé 1de338c312 Remove useless animation on section tabs (#2739) 2025-01-14 08:57:08 +01:00
Steven H dbba50cea4 Fix an issue where search and Ask AI triggers unnecessary renders when in a Visitor Authenticated site. (#2738) 2025-01-13 21:31:40 +00:00
Zeno Kapitein 8f046a9cd6 Start using tint in more places: TOC and PageAside (#2733) 2025-01-13 15:00:19 +01:00
Greg Bergé 2906e6038a Downgrade to Next.js v14 (#2732) 2025-01-13 14:50:31 +01:00
Greg Bergé 87b8ea8c05 Revert reading a context from headers and passing it (#2727) 2025-01-13 12:44:00 +01:00
Greg Bergé 47971dce31 Fix OG image generation (#2729) 2025-01-13 12:20:24 +01:00
Greg Bergé 528a05398c Fix server actions stability (#2728)
Co-authored-by: Steven Hall <steven@gitbook.io>
2025-01-13 10:04:14 +00:00
Taran Vohra f584148ab9 temporarily add back cloudflare KV cache backend (#2726) 2025-01-12 12:57:38 +05:30
Zeno Kapitein 0de22f7a96 Fix padding of ads box (#2724) 2025-01-10 21:49:54 +01:00
Greg Bergé 09c7c30779 Try to fix error on og image generation (#2722) 2025-01-10 21:38:25 +01:00
Greg Bergé fde32e26bf Force route handler to be dynamic to avoid errors (#2721) 2025-01-10 16:26:25 +01:00
Greg Bergé a6f65916f1 Separate cache for HTTP methods (#2720) 2025-01-10 16:09:35 +01:00
Claire Chabas 6059efe094 Fix no results showing while there are results (#2719) 2025-01-10 16:08:45 +01:00
Zeno Kapitein 16194c50ba Vertical orientation for sections list on sites without header (#2714) 2025-01-10 14:40:10 +01:00
Steven H af3c6a971c Reintroduce a safety check around search whilst we continue investigating caching. (#2718)
Co-authored-by: Greg Bergé <berge.greg@gmail.com>
2025-01-10 13:32:44 +00:00
Greg Bergé ecfdb976a3 Cleanup headers usage (#2717) 2025-01-10 14:15:39 +01:00
Steven H 08acea651a Log an exception if an empty cache object is returned (#2716)
Co-authored-by: Greg Bergé <berge.greg@gmail.com>
2025-01-10 09:25:40 +00:00
Greg Bergé 6b503608cd Fix view transition error on Safari (#2715) 2025-01-10 07:27:49 +01:00
Greg Bergé d8763997a5 Fix UI search with no ask (#2713) 2025-01-09 17:22:06 +01:00
Greg Bergé 32aa1f99c1 Handle security issue with cookies on Safari (#2711) 2025-01-09 17:04:26 +01:00
Valentino Hudhra 718a8a54b1 Position the variant picker in the ToC (#2632)
Co-authored-by: Zeno Kapitein <admin@zeno.zone>
Co-authored-by: Zeno Kapitein <zenomilan@me.com>
2025-01-09 16:47:20 +01:00
Zeno Kapitein 741dd490d4 Bump heading-3 font size to differentiate it from paragraphs (#2706) 2025-01-09 16:43:04 +01:00
Greg Bergé 02d876e6d8 Fix search UI behaviour (#2712) 2025-01-09 16:27:04 +01:00
Greg Bergé 56c52e0bb0 Handle Firefox security error on localStorage (#2710) 2025-01-09 15:36:08 +01:00
Greg Bergé 6036becf93 Fix header menu scroll ref logic (#2708) 2025-01-09 14:22:34 +01:00
Greg Bergé 3a7210d514 Fix zoom image view transition on Safari (#2709) 2025-01-09 14:08:45 +01:00
Greg Bergé 6088fa582d Simplify search results logic (#2707) 2025-01-09 13:53:21 +01:00
Greg Bergé 6691492ef7 Fix viewing pdf from space (#2705) 2025-01-09 12:28:48 +01:00
Zeno Kapitein 7ee9158cd3 Restyle PageAside to use sidebar list styles (#2680)
Co-authored-by: Valentino Hudhra <v.hudhra@gmail.com>
Co-authored-by: Valentino Hudhra <2587839+valentin0h@users.noreply.github.com>
2025-01-09 11:21:30 +01:00
Claire Chabas 5ae1b883ab Fix shrinking page icons (#2702) 2025-01-08 16:59:32 +01:00
239 changed files with 63499 additions and 2371 deletions
+1 -1
View File
@@ -1 +1 @@
1.1.40
1.2.1
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix UI search without ask AI enabled and fix error with questions not returned from API
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Support llms.txt
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Add support for keyboard marks
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix search no results error showing while there are results
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Reintroduce a safety check around search whilst we continue investigating caching.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Track new events for site insights when ads are being clicked
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Apply antialiasing on any text that are not code inline/blocks to avoid contrast issues
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Handle security issue with cookies on Safari
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': minor
---
Add in HTTP example code blocks
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Investigate an issue causing caches to return empty objects instead of null/undefined.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix vertical section overflow color
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Reduce gap between subsequent header buttons
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix shrinking page icons
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Start using tint in more places, TOC and PageAside
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Remove KV cache backend and only rely on DO as an external cache backend
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix default outline list styling
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Simplify search results logic to investigate a bug
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Cache API spec for 24 hours, revalidated every 2 hours
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Try to fix error on og image generation
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Downgrade to Next.js v14 to fix incompatibilities with next-on-pages causing multiple bugs.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix zoom image view transition on Safari
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Position the variant picker in the ToC
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Update footer styling and allow for more than 4 footer groups
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix Image blocks zoomable behaviour
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Handle Firefox security error on localStorage
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix errors from customization not found
+6
View File
@@ -0,0 +1,6 @@
---
'@gitbook/react-openapi': patch
'gitbook': patch
---
Do not dereference before caching OpenAPI spec.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix regression issue with page icons for multi-line titles
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix OG image generation for non-latin characters
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Ignore cache invalidation error from local backend
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Fix an issue where a response object using a special ref would crash the page.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Allow only good values for theme query parameter. Avoid having a 500 error when we pass an invalid value.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Restyle PageAside to use sidebar list styles
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Generate sitemap for all sections and spaces
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix an issue where search and Ask AI triggers unnecessary renders when in a Visitor Authenticated site.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Add feedback form to page rating control
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Update the routes for changes/revisions in multi-id mode to match the normal mode
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix server actions stability leading to no results found sometimes on search
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Lazy load iframely script to make page more responsive
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Cards stand out slighly more on tinted and dark mode sites, and have better support for headings inside them
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
New highlight colors
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix search UI behaviour
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix error when accessing a change request not found
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Improve performances by loading Scalar API Client only when the button is clicked
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix issue leading to increase the storage write and the stability of the platform
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Force route handler to be dynamic to avoid errors
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Disable C/C++ highlight temporarily
+6
View File
@@ -0,0 +1,6 @@
---
'@gitbook/react-openapi': minor
'gitbook': minor
---
Fix internal properties appearing in OpenAPI docs.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Add antialiasing for text rendering
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Improve styling of header buttons with shadows and high-contrast styles
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix viewing PDF from space
+8
View File
@@ -0,0 +1,8 @@
---
'@gitbook/react-openapi': major
---
Use `@scalar/openapi-parser` to be more resilient and perf on OpenAPI spec parsing:
- `fetcher.fetch` must now returns a valid OpenAPI document
- `parseOpenAPIV3` has been replaced by `parseOpenAPI`
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Vertical orientation for sections list on sites without header
+6
View File
@@ -0,0 +1,6 @@
---
'@gitbook/react-openapi': patch
'gitbook': patch
---
Improve OpenAPI rendering performances by caching markdown parsing
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Improve performances by highlighting code client-side if the code block is offscreen
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix error when accessing some not found pages.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix breadcrumbs emoji display + add contrast styles
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix server actions cache compromised. Leading to some bugs on frontend.
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix variant dropdown styling in header
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix view transition error on Safari
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Bump `heading-3` font size to offset it from paragraphs
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Remove animation on section tabs. Page is reloaded (for technical reasons), so the animation is not accurate here.
+1
View File
@@ -41,6 +41,7 @@ jobs:
run: bun run build:cloudflare
env:
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: ${{ secrets.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY }}
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
SENTRY_DSN: ${{ vars.SENTRY_DSN }}
+1 -1
View File
@@ -1 +1 @@
v20.6
v20.8
+3
View File
@@ -8,3 +8,6 @@ packages/icons/src/data/*.json
# Build files
dist/
README.md
CHANGELOG.md
+4 -2
View File
@@ -35,8 +35,10 @@ To run a local version of this project, please follow these simple steps.
### Prerequisites
- Node.js (Version: >=18.x)
- Bun
- Node.js (Version: >=20.8)
- Use nvm for easy Node management
- Bun (Version: >=1.2.1)
- We use a text-based lockfile which isn't supported below 1.2.1
### Set up
+3587
View File
File diff suppressed because it is too large Load Diff
BIN
View File
Binary file not shown.
+6 -3
View File
@@ -4,17 +4,20 @@
"devDependencies": {
"@changesets/cli": "^2.27.7",
"prettier": "^3.0.3",
"turbo": "^2.1.2"
"turbo": "^2.3.4"
},
"packageManager": "bun@1.1.18",
"overrides": {
"@codemirror/state": "6.4.1"
"@codemirror/state": "6.4.1",
"react": "18.3.1",
"react-dom": "18.3.1"
},
"private": true,
"scripts": {
"dev": "turbo run dev --ui=stream",
"build": "turbo run build",
"build:cloudflare": "turbo run build:cloudflare",
"clean-deps": "rm -rf node_modules && rm -rf packages/*/node_modules",
"lint": "turbo run lint",
"lint:fix": "turbo run lint -- --fix",
"typecheck": "turbo run typecheck",
@@ -33,6 +36,6 @@
],
"patchedDependencies": {
"decode-named-character-reference@1.0.2": "patches/decode-named-character-reference@1.0.2.patch",
"@vercel/next@4.3.15": "patches/@vercel%2Fnext@4.3.15.patch"
"@vercel/next@4.4.2": "patches/@vercel%2Fnext@4.4.2.patch"
}
}
+192 -21
View File
@@ -27,12 +27,40 @@ import { getContentTestURL } from '../tests/utils';
interface Test {
name: string;
url: string; // URL to visit for testing
/**
* URL to visit for testing.
*/
url: string;
cookies?: Parameters<BrowserContext['addCookies']>[0];
run?: (page: Page) => Promise<unknown>; // The test to run
fullPage?: boolean; // Whether the test should be fullscreened during testing
screenshot?: false; // Should a screenshot be stored
only?: boolean; // Only run this test
/**
* Test to run
*/
run?: (page: Page) => Promise<unknown>;
/**
* Whether the test should be fullscreened during testing.
*/
fullPage?: boolean;
/**
* Whether to take a screenshot of the test or set a threshold for the screenshot.
*/
screenshot?:
| false
| {
/**
* Screenshot threshold.
* From 0 to 1, where 0 is the most strict and 1 is the most permissive.
* @default 0.5
*/
threshold?: number;
/**
* Whether to wait for the table of contents to finish scrolling before taking the screenshot.
*/
waitForTOCScrolling?: boolean;
};
/**
* Whether to only run this test.
*/
only?: boolean;
}
interface TestsCase {
@@ -95,19 +123,28 @@ const testCases: TestsCase[] = [
{
name: 'Search',
url: '?q=',
screenshot: false,
run: async (page) => {
await expect(page.getByTestId('search-results')).toBeVisible();
const allItems = await page.getByTestId('search-result-item').all();
// Expect at least 3 questions
await expect(allItems.length).toBeGreaterThan(2);
},
},
{
name: 'Search Results',
url: '?q=gitbook',
run: async (page) => {
await page.waitForSelector('[data-test="search-results"]');
await expect(page.getByTestId('search-results')).toBeVisible();
},
},
{
name: 'AI Search',
url: '?q=What+is+GitBook%3F&ask=true',
run: async (page) => {
await page.waitForSelector('[data-test="search-ask-answer"]');
await expect(page.getByTestId('search-ask-answer')).toBeVisible({
timeout: 15_000,
});
},
screenshot: false,
},
@@ -268,19 +305,28 @@ const testCases: TestsCase[] = [
{
name: 'Search',
url: '?q=',
screenshot: false,
run: async (page) => {
await expect(page.getByTestId('search-results')).toBeVisible();
const allItems = await page.getByTestId('search-result-item').all();
// Expect at least 3 questions
await expect(allItems.length).toBeGreaterThan(2);
},
},
{
name: 'Search Results',
url: '?q=gitbook',
run: async (page) => {
await page.waitForSelector('[data-test="search-results"]');
await expect(page.getByTestId('search-results')).toBeVisible();
},
},
{
name: 'AI Search',
url: '?q=What+is+GitBook%3F&ask=true',
run: async (page) => {
await page.waitForSelector('[data-test="search-ask-answer"]');
await expect(page.getByTestId('search-ask-answer')).toBeVisible({
timeout: 15_000,
});
},
screenshot: false,
},
@@ -309,6 +355,9 @@ const testCases: TestsCase[] = [
{
name: 'PDF',
url: '~gitbook/pdf?limit=10',
screenshot: {
waitForTOCScrolling: false,
},
},
],
},
@@ -331,11 +380,38 @@ const testCases: TestsCase[] = [
url: 'blocks/block-images',
run: waitForCookiesDialog,
fullPage: true,
screenshot: { threshold: 0.8 },
},
{
name: 'Images (with zoom)',
url: 'blocks/block-images',
run: async (page) => {
await waitForCookiesDialog(page);
const zoomImage = page.getByTestId('zoom-image');
await zoomImage.first().click();
await expect(page.getByTestId('zoom-image-modal')).toBeVisible();
},
fullPage: true,
screenshot: { threshold: 0.8 },
},
{
name: 'Inline Images',
url: 'blocks/inline-images',
run: waitForCookiesDialog,
run: async (page) => {
await waitForCookiesDialog(page);
// Make the text invisible to fix flakiness due to the text position.
await page.evaluate(() => {
for (const p of document.querySelectorAll('p')) {
if (
p.textContent?.includes(
'This image has intrinsic 400px width, but renders as 300px:',
)
) {
p.style.color = 'transparent';
}
}
});
},
},
{
name: 'Tabs',
@@ -406,6 +482,18 @@ const testCases: TestsCase[] = [
{
name: 'Math',
url: 'blocks/math',
run: async (page) => {
await page.waitForFunction(() => {
const fonts = Array.from(document.fonts.values());
const mjxFonts = fonts.filter(
(font) => font.family === 'MJXZERO' || font.family === 'MJXTEX',
);
return (
mjxFonts.length === 2 &&
mjxFonts.every((font) => font.status === 'loaded')
);
});
},
},
{
name: 'Files',
@@ -459,6 +547,9 @@ const testCases: TestsCase[] = [
name: 'With cover and no TOC',
url: 'page-options/page-with-cover-and-no-toc',
run: waitForCookiesDialog,
screenshot: {
waitForTOCScrolling: false,
},
},
{
name: 'With icon',
@@ -642,11 +733,14 @@ const testCases: TestsCase[] = [
run: async (page) => {
const sharedSpaceLink = page.locator('a.underline');
await sharedSpaceLink.click();
expect(page.locator('h1')).toHaveText('shared');
await expect(
page.getByRole('heading', { level: 1, name: 'shared' }),
).toBeVisible();
const url = page.url();
expect(url.includes('shared-space-uno')).toBeTruthy(); // same uno site
expect(url.endsWith('/shared')).toBeTruthy(); // correct page
},
screenshot: false,
},
],
},
@@ -658,13 +752,15 @@ const testCases: TestsCase[] = [
name: 'Navigation to shared space',
url: '',
run: async (page) => {
const sharedSpaceLink = page.locator('a.underline');
await sharedSpaceLink.click();
expect(page.locator('h1')).toHaveText('shared');
await page.locator('a.underline').click();
await expect(
page.getByRole('heading', { level: 1, name: 'shared' }),
).toBeVisible();
const url = page.url();
expect(url.includes('shared-space-dos')).toBeTruthy(); // same dos site
expect(url.endsWith('/shared')).toBeTruthy(); // correct page
},
screenshot: false,
},
],
},
@@ -678,6 +774,7 @@ const testCases: TestsCase[] = [
run: async (page) => {
await expect(page.locator('h1')).toHaveText('SSO');
},
screenshot: false,
},
],
},
@@ -697,6 +794,7 @@ const testCases: TestsCase[] = [
page.getByText('Authentication missing to access this content'),
).toBeVisible();
},
screenshot: false,
},
],
},
@@ -719,7 +817,12 @@ const testCases: TestsCase[] = [
);
return `first?jwt_token=${token}`;
})(),
run: waitForCookiesDialog,
run: async (page) => {
await expect(
page.getByRole('heading', { level: 1, name: 'first' }),
).toBeVisible();
},
screenshot: false,
},
{
name: 'Second',
@@ -736,7 +839,12 @@ const testCases: TestsCase[] = [
);
return `second?jwt_token=${token}`;
})(),
run: waitForCookiesDialog,
run: async (page) => {
await expect(
page.getByRole('heading', { level: 1, name: 'second' }),
).toBeVisible();
},
screenshot: false,
},
],
},
@@ -850,7 +958,12 @@ const testCases: TestsCase[] = [
);
return `first?jwt_token=${token}`;
})(),
run: waitForCookiesDialog,
run: async (page) => {
await expect(
page.getByRole('heading', { level: 1, name: 'first' }),
).toBeVisible();
},
screenshot: false,
},
{
name: 'Custom page',
@@ -1346,16 +1459,24 @@ for (const testCase of testCases) {
if (testEntry.run) {
await testEntry.run(page);
}
if (testEntry.screenshot !== false) {
const screenshotOptions = testEntry.screenshot;
if (screenshotOptions !== false) {
await argosScreenshot(page, `${testCase.name} - ${testEntry.name}`, {
viewports: ['macbook-16', 'macbook-13', 'iphone-x', 'ipad-2'],
viewports: ['macbook-16', 'macbook-13', 'ipad-2', 'iphone-x'],
argosCSS: `
/* Hide Intercom */
.intercom-lightweight-app {
display: none !important;
}
`,
}
`,
threshold: screenshotOptions?.threshold ?? undefined,
fullPage: testEntry.fullPage ?? false,
beforeScreenshot: async () => {
await waitForIcons(page);
if (screenshotOptions?.waitForTOCScrolling !== false) {
await waitForTOCScrolling(page);
}
},
});
}
});
@@ -1433,3 +1554,53 @@ function getCustomizationURL(partial: DeepPartial<SiteCustomizationSettings>): s
return `?${searchParams.toString()}`;
}
/**
* Wait for all icons present on the page to be loaded.
*/
async function waitForIcons(page: Page) {
await page.waitForFunction(async () => {
function loadImage(src: string) {
return new Promise((resolve, reject) => {
const img = new Image();
img.onload = () => resolve(img);
img.onerror = (error) => reject(new Error(`Failed to load image: ${src}`));
img.src = src;
});
}
const icons = Array.from(document.querySelectorAll('svg.gb-icon'));
await Promise.all(
icons.map(async (icon) => {
// url("https://ka-p.fontawesome.com/releases/v6.6.0/svgs/light/moon.svg?v=2&token=a463935e93")
const maskImage = window.getComputedStyle(icon).getPropertyValue('mask-image');
const urlMatch = maskImage.match(/url\("([^"]+)"\)/);
const url = urlMatch ? urlMatch[1] : null;
if (!url) {
throw new Error('No mask-image');
}
await loadImage(url);
}),
);
});
}
/**
* Wait for TOC to be correctly scrolled into view.
*/
async function waitForTOCScrolling(page: Page) {
const viewport = await page.viewportSize();
if (viewport && viewport.width >= 1024) {
const toc = page.getByTestId('table-of-contents');
await expect(toc).toBeVisible();
await page.evaluate(() => {
const tocScrollContainer = document.querySelector(
'[data-testid="table-of-contents"] [data-testid="toc-scroll-container"]',
);
if (!tocScrollContainer) {
throw new Error('TOC scroll container not found');
}
tocScrollContainer.scrollTo(0, 0);
});
}
}
+1
View File
@@ -10,6 +10,7 @@ module.exports = withSentryConfig(
GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
GITBOOK_ICONS_URL: process.env.GITBOOK_ICONS_URL,
GITBOOK_ICONS_TOKEN: process.env.GITBOOK_ICONS_TOKEN,
NEXT_SERVER_ACTIONS_ENCRYPTION_KEY: process.env.NEXT_SERVER_ACTIONS_ENCRYPTION_KEY,
},
webpack(config, { dev, webpack }) {
+10 -7
View File
@@ -16,7 +16,7 @@
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
},
"dependencies": {
"@gitbook/api": "^0.85.0",
"@gitbook/api": "^0.89.0",
"@gitbook/cache-do": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*",
"@gitbook/icons": "workspace:*",
@@ -40,8 +40,9 @@
"jsontoxml": "^1.0.1",
"katex": "^0.16.9",
"mathjax": "^3.2.2",
"mdast-util-to-markdown": "^2.1.2",
"memoizee": "^0.4.15",
"next": "15.1.3",
"next": "14.2.23",
"next-themes": "^0.2.1",
"nuqs": "^2.2.3",
"object-hash": "^3.0.0",
@@ -49,8 +50,8 @@
"p-map": "^7.0.0",
"parse-cache-control": "^1.0.1",
"postcss-color-contrast": "^1.1.0",
"react": "19.0.0",
"react-dom": "19.0.0",
"react": "18.3.1",
"react-dom": "18.3.1",
"react-hotkeys-hook": "^4.4.1",
"rehype-sanitize": "^6.0.0",
"rehype-stringify": "^10.0.0",
@@ -59,7 +60,7 @@
"remark-rehype": "^11.1.0",
"rison": "^0.1.1",
"server-only": "^0.0.1",
"shiki": "^1.26.1",
"shiki": "^1.27.2",
"tailwind-merge": "^2.2.0",
"tailwind-shades": "^1.1.2",
"unified": "^11.0.4",
@@ -67,13 +68,15 @@
"usehooks-ts": "^3.1.0"
},
"devDependencies": {
"@argos-ci/playwright": "^2.0.0",
"@argos-ci/playwright": "^3.10.0",
"@cloudflare/next-on-pages": "1.13.7",
"vercel": "^39.3.0",
"@cloudflare/workers-types": "^4.20241230.0",
"@playwright/test": "^1.42.1",
"@playwright/test": "^1.49.1",
"@types/js-cookie": "^3.0.6",
"@types/jsontoxml": "^1.0.5",
"@types/jsonwebtoken": "^9.0.6",
"@types/mdast": "^4.0.4",
"@types/node": "^20",
"@types/object-hash": "^3.0.6",
"@types/parse-cache-control": "^1.0.4",
-18
View File
@@ -1,18 +0,0 @@
import { init } from '@sentry/nextjs';
const dsn = process.env.SENTRY_DSN;
if (dsn) {
init({
dsn,
release: process.env.SENTRY_RELEASE,
// Disable tracing as it creates additional requests in an env where subrequests are limited.
tracesSampleRate: 0,
// Disable transactions as it creates additional requests in an env where subrequests are limited.
// https://docs.sentry.io/platforms/node/configuration/filtering/#using--3
beforeSendTransaction: () => {
return null;
},
});
}
@@ -1,97 +0,0 @@
import { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
import jsontoxml from 'jsontoxml';
import { NextRequest } from 'next/server';
import { getSpaceContentData } from '@/lib/api';
import { getAbsoluteHref } from '@/lib/links';
import { getPagePath } from '@/lib/pages';
import { getSiteContentPointer } from '@/lib/pointer';
import { isPageIndexable } from '@/lib/seo';
export const runtime = 'edge';
/**
* Generate a sitemap.xml for the current space.
*/
export async function GET(req: NextRequest) {
const pointer = await getSiteContentPointer();
const { pages: rootPages } = await getSpaceContentData(pointer, pointer.siteShareKey);
const pages = flattenPages(rootPages, (page) => !page.hidden && isPageIndexable([], page));
const urls = await Promise.all(
pages.map(async ({ page, depth }) => {
// Decay priority with depth
const priority = Math.pow(2, -0.25 * depth);
// Normalize to keep 2 decimals
const normalizedPriority = Math.floor(100 * priority) / 100;
const lastModified = page.updatedAt || page.createdAt;
return {
url: {
loc: await getAbsoluteHref(getPagePath(rootPages, page), true),
priority: normalizedPriority,
...(lastModified
? {
// lastmod format is YYYY-MM-DD
lastmod: new Date(lastModified).toISOString().split('T')[0],
}
: {}),
},
};
}),
);
const xml = jsontoxml(
[
{
name: 'urlset',
children: urls,
attrs: {
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',
'xsi:schemaLocation':
'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd',
},
},
],
{
xmlHeader: true,
prettyPrint: true,
},
);
return new Response(xml, {
headers: {
'Content-Type': 'application/xml',
},
});
}
type FlatPageEntry = { page: RevisionPageDocument; depth: number };
function flattenPages(
rootPags: RevisionPage[],
filter: (page: RevisionPageDocument | RevisionPageGroup) => boolean,
): FlatPageEntry[] {
const flattenPage = (
page: RevisionPageDocument | RevisionPageGroup,
depth: number,
): FlatPageEntry[] => {
const allowed = filter(page);
if (!allowed) {
return [];
}
return [
...(page.type === 'document' ? [{ page, depth }] : []),
...page.pages.flatMap((child) =>
child.type === 'document' ? flattenPage(child, depth + 1) : [],
),
];
};
return rootPags.flatMap((page) =>
page.type === 'group' || page.type === 'document' ? flattenPage(page, 0) : [],
);
}
@@ -15,6 +15,7 @@ import { PageClientLayout } from './PageClientLayout';
import { PagePathParams, fetchPageData, getPathnameParam, normalizePathname } from '../../fetch';
export const runtime = 'edge';
export const dynamic = 'force-dynamic';
/**
* Fetch and render a page.
@@ -108,10 +109,7 @@ export default async function Page(props: {
page={page}
ancestors={ancestors}
document={document}
withPageFeedback={
// Display the page feedback in the page footer if the aside is not visible
withPageFeedback && !page.layout.outline
}
withPageFeedback={withPageFeedback}
/>
</div>
<React.Suspense fallback={null}>
@@ -22,6 +22,7 @@ import { RocketLoaderDetector } from './RocketLoaderDetector';
import { fetchContentData } from '../fetch';
export const runtime = 'edge';
export const dynamic = 'force-dynamic';
/**
* Layout when rendering the content.
@@ -0,0 +1,153 @@
import { SiteSection, SiteSpace, SiteStructure } from '@gitbook/api';
import assertNever from 'assert-never';
import { Heading, ListItem, Paragraph, Root, RootContent } from 'mdast';
import { toMarkdown } from 'mdast-util-to-markdown';
import { NextRequest } from 'next/server';
import { getPublishedContentSite, getRevisionPages } from '@/lib/api';
import { getAbsoluteHref } from '@/lib/links';
import { getPagePath } from '@/lib/pages';
import { joinPath } from '@/lib/paths';
import { checkIsRootPointer, getSiteContentPointer } from '@/lib/pointer';
import { getIndexablePages } from '@/lib/sitemap';
export const runtime = 'edge';
/**
* Generate a llms.txt file for the site.
*/
export async function GET(req: NextRequest) {
const pointer = await getSiteContentPointer();
const { structure: siteStructure, site } = await getPublishedContentSite({
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
});
if (!checkIsRootPointer(pointer, siteStructure)) {
return new Response('llms.txt is only served from the root of the site', { status: 404 });
}
const tree: Root = {
type: 'root',
children: [
{
type: 'heading',
depth: 1,
children: [{ type: 'text', value: site.title }],
},
...(await getNodesFromSiteStructure(siteStructure)),
],
};
return new Response(
toMarkdown(tree, {
bullet: '-',
}),
{
headers: {
'Content-Type': 'text/plain; charset=utf-8',
},
},
);
}
/**
* Get MDAST nodes from site structure.
*/
async function getNodesFromSiteStructure(siteStructure: SiteStructure): Promise<RootContent[]> {
switch (siteStructure.type) {
case 'sections':
return getNodesFromSections(siteStructure.structure);
case 'siteSpaces':
return getNodesFromSiteSpaces(siteStructure.structure, { heading: true });
default:
assertNever(siteStructure);
}
}
/**
* Get MDAST nodes from site sections.
*/
async function getNodesFromSections(siteSections: SiteSection[]): Promise<RootContent[]> {
const all = await Promise.all(
siteSections.map(async (siteSection): Promise<RootContent[]> => {
const siteSpaceNodes = await getNodesFromSiteSpaces(siteSection.siteSpaces, {
heading: false,
});
return [
{
type: 'heading',
depth: 2,
children: [{ type: 'text', value: siteSection.title }],
},
...siteSpaceNodes,
];
}),
);
return all.flat();
}
/**
* Get MDAST nodes from site spaces.
*/
async function getNodesFromSiteSpaces(
siteSpaces: SiteSpace[],
options: {
/**
* Includes a heading for each site space.
*/
heading?: boolean;
},
): Promise<RootContent[]> {
const all = await Promise.all(
siteSpaces.map(async (siteSpace): Promise<RootContent[]> => {
const siteSpaceUrl = siteSpace.urls.published;
if (!siteSpaceUrl) {
return [];
}
const rootPages = await getRevisionPages(siteSpace.space.id, siteSpace.space.revision, {
metadata: false,
});
const pages = getIndexablePages(rootPages);
const listChildren = await Promise.all(
pages.map(async ({ page }): Promise<ListItem> => {
const url = await getAbsoluteHref(
joinPath(new URL(siteSpaceUrl).pathname, getPagePath(rootPages, page)),
true,
);
const children: Paragraph['children'] = [
{
type: 'link',
url,
children: [{ type: 'text', value: page.title }],
},
];
if (page.description) {
children.push({ type: 'text', value: `: ${page.description}` });
}
return {
type: 'listItem',
children: [{ type: 'paragraph', children }],
};
}),
);
const nodes: RootContent[] = [];
if (options.heading) {
nodes.push({
type: 'heading',
depth: 2,
children: [{ type: 'text', value: siteSpace.title }],
});
}
nodes.push({
type: 'list',
spread: false,
children: listChildren,
});
return nodes;
}),
);
return all.flat();
}
@@ -0,0 +1,66 @@
import jsontoxml from 'jsontoxml';
import { getRevisionPages, getSpace } from '@/lib/api';
import { getAbsoluteHref } from '@/lib/links';
import { getPagePath } from '@/lib/pages';
import { getSiteContentPointer } from '@/lib/pointer';
import { getIndexablePages } from '@/lib/sitemap';
export const runtime = 'edge';
/**
* Generate a sitemap.xml for the current section / space.
*/
export async function GET() {
const pointer = await getSiteContentPointer();
const revisionId =
pointer.revisionId ?? (await getSpace(pointer.spaceId, pointer.siteShareKey)).revision;
const rootPages = await getRevisionPages(pointer.spaceId, revisionId, { metadata: false });
const pages = getIndexablePages(rootPages);
const urls = await Promise.all(
pages.map(async ({ page, depth }) => {
// Decay priority with depth
const priority = Math.pow(2, -0.25 * depth);
// Normalize to keep 2 decimals
const normalizedPriority = Math.floor(100 * priority) / 100;
const lastModified = page.updatedAt || page.createdAt;
const url: { loc: string; priority: number; lastmod?: string } = {
priority: normalizedPriority,
loc: await getAbsoluteHref(getPagePath(rootPages, page), true),
};
if (lastModified) {
url.lastmod = new Date(lastModified).toISOString();
}
return { url };
}),
);
const xml = jsontoxml(
[
{
name: 'urlset',
children: urls,
attrs: {
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',
},
},
],
{
xmlHeader: true,
prettyPrint: true,
},
);
return new Response(xml, {
headers: {
'Content-Type': 'application/xml',
},
});
}
@@ -0,0 +1,98 @@
import { SiteSection, SiteSpace, SiteStructure } from '@gitbook/api';
import assertNever from 'assert-never';
import jsontoxml from 'jsontoxml';
import { getPublishedContentSite, SiteContentPointer } from '@/lib/api';
import { getAbsoluteHref } from '@/lib/links';
import { joinPath } from '@/lib/paths';
import { checkIsRootPointer, getSiteContentPointer } from '@/lib/pointer';
import { filterOutNullable } from '@/lib/typescript';
export const runtime = 'edge';
/**
* Generate a root sitemap that point to all sitemap-pages.xml.
*/
export async function GET() {
const pointer = await getSiteContentPointer();
const { structure: siteStructure } = await getPublishedContentSite({
organizationId: pointer.organizationId,
siteId: pointer.siteId,
siteShareKey: pointer.siteShareKey,
});
if (!checkIsRootPointer(pointer, siteStructure)) {
return new Response('Root sitemap is only served from the root of the site', {
status: 404,
});
}
const urls = await getUrlsFromSiteStructure(siteStructure);
const xml = jsontoxml(
[
{
name: 'sitemapindex',
children: urls.map((url) => ({
name: 'sitemap',
children: [{ name: 'loc', text: url }],
})),
attrs: {
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',
},
},
],
{
xmlHeader: true,
prettyPrint: true,
},
);
return new Response(xml, {
headers: {
'Content-Type': 'application/xml',
},
});
}
/**
* Get Sitemap URLs from site structure.
*/
async function getUrlsFromSiteStructure(siteStructure: SiteStructure): Promise<string[]> {
switch (siteStructure.type) {
case 'sections':
return getUrlsFromSiteSections(siteStructure.structure);
case 'siteSpaces':
return getUrlsFromSiteSpaces(siteStructure.structure);
default:
assertNever(siteStructure);
}
}
/**
* Get Sitemap URLs from site sections.
*/
async function getUrlsFromSiteSections(siteSections: SiteSection[]): Promise<string[]> {
const urls = await Promise.all(
siteSections.map(async (siteSection) => getUrlsFromSiteSpaces(siteSection.siteSpaces), []),
);
return urls.flat();
}
/**
* Get Sitemap URLs from site spaces.
*/
async function getUrlsFromSiteSpaces(siteSpaces: SiteSpace[]): Promise<string[]> {
const urls = await Promise.all(
siteSpaces.map(async (siteSpace) => {
if (!siteSpace.urls.published) {
return null;
}
const url = new URL(siteSpace.urls.published);
url.pathname = joinPath(url.pathname, 'sitemap-pages.xml');
return url.toString();
}, []),
);
return urls.filter(filterOutNullable);
}
@@ -5,44 +5,97 @@ import { NextRequest } from 'next/server';
import colorContrast from 'postcss-color-contrast/js';
import React from 'react';
import { googleFontsMap } from '@/fonts';
import { getAbsoluteHref } from '@/lib/links';
import { tcls } from '@/lib/tailwind';
import { filterOutNullable } from '@/lib/typescript';
import { getContentTitle } from '@/lib/utils';
import { PageIdParams, fetchPageData } from '../../../../fetch';
export const runtime = 'edge';
async function loadGoogleFont(input: { fontFamily: string; text: string; weight: 400 | 700 }) {
const { fontFamily, text, weight } = input;
if (!text.trim()) {
return null;
}
const url = new URL('https://fonts.googleapis.com/css2');
url.searchParams.set('family', `${fontFamily}:wght@${weight}`);
url.searchParams.set('text', text);
const result = await fetch(url.href);
if (!result.ok) {
return null;
}
const css = await result.text();
const resource = css.match(/src: url\((.+)\) format\('(opentype|truetype)'\)/);
const resourceUrl = resource ? resource[1] : null;
if (resourceUrl) {
const response = await fetch(resourceUrl);
if (response.ok) {
const data = await response.arrayBuffer();
return {
name: fontFamily,
data,
style: 'normal' as const,
weight,
};
}
}
// If for some reason we can't load the font, we'll just use the default one
return null;
}
/**
* Render the OpenGraph image for a space.
*/
export async function GET(req: NextRequest, { params }: { params: Promise<PageIdParams> }) {
const { space, page, customization, site } = await fetchPageData(await params);
// If user configured a custom social preview, we redirect to it.
if (customization.socialPreview.url) {
// If user configured a custom social preview, we redirect to it.
redirect(customization.socialPreview.url);
}
// TODO: Support all fonts available in GitBook
// Right now this is impossible since next/font/google does not expose the cached font file
// Another option would be to use the Satori prop `loadAdditionalAsset` [example](https://github.com/vercel/satori/blob/main/playground/pages/index.tsx),
// but this prop isn't (yet) exposed through `ImageResponse`.
const interRegular = await fetch(
new URL('../../../../../../fonts/Inter/Inter-Regular.ttf', import.meta.url),
).then((res) => res.arrayBuffer());
const interBold = await fetch(
new URL('../../../../../../fonts/Inter/Inter-Bold.ttf', import.meta.url),
).then((res) => res.arrayBuffer());
// Compute all text to load only the necessary fonts
const contentTitle = customization.header.logo
? ''
: getContentTitle(space, customization, site ?? null);
const pageTitle = page
? page.title.length > 64
? page.title.slice(0, 64) + '...'
: page.title
: 'Not found';
const pageDescription =
page?.description && page?.title.length <= 64
? page.description.length > 164
? page.description.slice(0, 164) + '...'
: page.description
: '';
const fontFamily = googleFontsMap[customization.styling.font] ?? 'Inter';
const regularText = pageDescription;
const boldText = `${contentTitle}${pageTitle}`;
const fonts = (
await Promise.all([
loadGoogleFont({ fontFamily, text: regularText, weight: 400 }),
loadGoogleFont({ fontFamily, text: boldText, weight: 700 }),
])
).filter(filterOutNullable);
const theme = customization.themes.default;
const useLightTheme = theme === 'light';
// We have no access to CSS variables, so we'll have to hardcode some values
const baseColors = {
light: '#ffffff',
dark: '#111827',
};
const baseColors = { light: '#ffffff', dark: '#111827' };
let colors = {
background: baseColors[theme],
@@ -99,13 +152,13 @@ export async function GET(req: NextRequest, { params }: { params: Promise<PageId
src={customization.favicon.icon[theme]}
width={40}
height={40}
tw={tcls('mr-4')}
tw="mr-4"
alt="Icon"
/>
);
if ('emoji' in customization.favicon)
return (
<span tw={tcls('text-4xl', 'mr-4')}>
<span tw="text-4xl mr-4">
{String.fromCodePoint(parseInt('0x' + customization.favicon.emoji))}
</span>
);
@@ -113,27 +166,20 @@ export async function GET(req: NextRequest, { params }: { params: Promise<PageId
`~gitbook/icon?size=medium&theme=${customization.themes.default}`,
true,
);
return <img src={src} alt="Icon" width={40} height={40} tw={tcls('mr-4')} />;
return <img src={src} alt="Icon" width={40} height={40} tw="mr-4" />;
})();
return new ImageResponse(
(
<div
tw={tcls(
'justify-between',
'p-20',
'relative',
'w-full',
'h-full',
'flex',
'flex-col',
`bg-[${colors.background}]`,
`text-[${colors.body}]`,
)}
tw={`justify-between p-20 relative w-full h-full flex flex-col bg-[${colors.background}] text-[${colors.body}]`}
style={{
fontFamily,
}}
>
{/* Gradient */}
<div
tw={tcls('absolute', 'inset-0')}
tw="absolute inset-0"
style={{
backgroundImage: `radial-gradient(ellipse 100% 100% at top right , ${colors.gradient}, ${colors.gradient}00)`,
opacity: 0.5,
@@ -141,11 +187,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<PageId
></div>
{/* Grid */}
<img
tw={tcls('absolute', 'inset-0', 'w-[100vw]', 'h-[100vh]')}
src={gridAsset}
alt="Grid"
/>
<img tw="absolute inset-0 w-[100vw] h-[100vh]" src={gridAsset} alt="Grid" />
{/* Logo */}
{customization.header.logo ? (
@@ -159,39 +201,21 @@ export async function GET(req: NextRequest, { params }: { params: Promise<PageId
}
/>
) : (
<div tw={tcls('flex')}>
<div tw="flex">
{favicon}
<h3 tw={tcls('text-4xl', 'my-0')}>
{getContentTitle(space, customization, site ?? null)}
</h3>
<h3 tw="text-4xl my-0 font-bold">{contentTitle}</h3>
</div>
)}
{/* Title and description */}
<div tw={tcls('flex', 'flex-col')}>
<div tw="flex flex-col">
<h1
tw={tcls(
'text-8xl',
'my-0',
'tracking-tight',
'leading-none',
'text-left',
`text-[${colors.title}]`,
'font-bold',
)}
tw={`text-8xl my-0 tracking-tight leading-none text-left text-[${colors.title}] font-bold`}
>
{page
? page.title.length > 64
? page.title.slice(0, 64) + '...'
: page.title
: 'Not found'}
{pageTitle}
</h1>
{page?.description && page?.title.length <= 64 ? (
<h2 tw={tcls('text-4xl', 'mb-0', 'mt-8', 'w-[75%]', 'font-normal')}>
{page.description.length > 164
? page.description.slice(0, 164) + '...'
: page.description}
</h2>
{pageDescription ? (
<h2 tw="text-4xl mb-0 mt-8 w-[75%] font-normal">{pageDescription}</h2>
) : null}
</div>
</div>
@@ -199,20 +223,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<PageId
{
width: 1200,
height: 630,
fonts: [
{
name: 'Inter',
data: interRegular,
weight: 400,
style: 'normal',
},
{
name: 'Inter',
data: interBold,
weight: 700,
style: 'normal',
},
],
fonts: fonts.length ? fonts : undefined,
},
);
}
@@ -4,6 +4,7 @@ import {
RevisionPageDocument,
RevisionPageGroup,
SiteCustomizationSettings,
SiteInsightsTrademarkPlacement,
Space,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
@@ -37,6 +38,7 @@ import { PrintButton } from './PrintButton';
const DEFAULT_LIMIT = 100;
export const runtime = 'edge';
export const dynamic = 'force-dynamic';
export async function generateMetadata(): Promise<Metadata> {
const pointer = await getSiteOrSpacePointerForPDF();
@@ -145,7 +147,11 @@ export default async function PDFHTMLOutput(props: {
limit={pdfParams.limit ?? DEFAULT_LIMIT}
trademark={
customization.trademark.enabled ? (
<TrademarkLink space={space} customization={customization} />
<TrademarkLink
space={space}
customization={customization}
placement={SiteInsightsTrademarkPlacement.Footer}
/>
) : null
}
/>
@@ -12,7 +12,7 @@ export async function getSiteOrSpacePointerForPDF(): Promise<
SiteContentPointer | SpaceContentPointer
> {
try {
return getSiteContentPointer();
return await getSiteContentPointer();
} catch (error) {
return getSpacePointer();
}
@@ -1,5 +1,6 @@
import { Space } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { headers } from 'next/headers';
import React from 'react';
import { getChangeRequest, getRevision, SiteContentPointer } from '@/lib/api';
@@ -14,33 +15,7 @@ interface AdminToolbarProps {
space: Space;
}
/**
* Toolbar with information for the content admin when previewing a revision or change-request.
*/
export function AdminToolbar(props: AdminToolbarProps) {
const { content } = props;
const toolbar = (() => {
if (content.changeRequestId) {
return (
<ChangeRequestToolbar
spaceId={content.spaceId}
changeRequestId={content.changeRequestId}
/>
);
}
if (content.revisionId) {
return <RevisionToolbar spaceId={content.spaceId} revisionId={content.revisionId} />;
}
return null;
})();
if (!toolbar) {
return null;
}
function ToolbarLayout(props: { children: React.ReactNode }) {
return (
<div
className={tcls(
@@ -61,41 +36,75 @@ export function AdminToolbar(props: AdminToolbarProps) {
'backdrop-blur-sm',
)}
>
<React.Suspense fallback={null}>{toolbar}</React.Suspense>
<React.Suspense fallback={null}>{props.children}</React.Suspense>
</div>
);
}
/**
* Toolbar with information for the content admin when previewing a revision or change-request.
*/
export async function AdminToolbar(props: AdminToolbarProps) {
const { content } = props;
const mode = await headers().get('x-gitbook-mode');
if (mode === 'multi-id') {
// We don't show the admin toolbar in multi-id mode, as it's used for previewing in the dashboard.
return null;
}
if (content.changeRequestId) {
return (
<ChangeRequestToolbar
spaceId={content.spaceId}
changeRequestId={content.changeRequestId}
/>
);
}
if (content.revisionId) {
return <RevisionToolbar spaceId={content.spaceId} revisionId={content.revisionId} />;
}
return null;
}
async function ChangeRequestToolbar(props: { spaceId: string; changeRequestId: string }) {
const { spaceId, changeRequestId } = props;
const changeRequest = await getChangeRequest(spaceId, changeRequestId);
if (!changeRequest) {
return null;
}
return (
<Toolbar>
<ToolbarButton title="Open in application" href={changeRequest.urls.app}>
<Icon icon="code-branch" className="size-4" />
</ToolbarButton>
<ToolbarBody>
<p>
#{changeRequest.number}: {changeRequest.subject ?? 'No subject'}
</p>
<p className="text-xs text-light/8 dark:text-light/8">
Change request updated <DateRelative value={changeRequest.updatedAt} />
</p>
</ToolbarBody>
<ToolbarButtonGroups>
<ToolbarLayout>
<Toolbar>
<ToolbarButton title="Open in application" href={changeRequest.urls.app}>
<Icon icon="arrow-up-right-from-square" className="size-4" />
<Icon icon="code-branch" className="size-4" />
</ToolbarButton>
<RefreshChangeRequestButton
spaceId={spaceId}
changeRequestId={changeRequestId}
revisionId={changeRequest.revision}
updatedAt={new Date(changeRequest.updatedAt).getTime()}
/>
</ToolbarButtonGroups>
</Toolbar>
<ToolbarBody>
<p>
#{changeRequest.number}: {changeRequest.subject ?? 'No subject'}
</p>
<p className="text-xs text-light/8 dark:text-light/8">
Change request updated <DateRelative value={changeRequest.updatedAt} />
</p>
</ToolbarBody>
<ToolbarButtonGroups>
<ToolbarButton title="Open in application" href={changeRequest.urls.app}>
<Icon icon="arrow-up-right-from-square" className="size-4" />
</ToolbarButton>
<RefreshChangeRequestButton
spaceId={spaceId}
changeRequestId={changeRequestId}
revisionId={changeRequest.revision}
updatedAt={new Date(changeRequest.updatedAt).getTime()}
/>
</ToolbarButtonGroups>
</Toolbar>
</ToolbarLayout>
);
}
@@ -107,31 +116,35 @@ async function RevisionToolbar(props: { spaceId: string; revisionId: string }) {
});
return (
<Toolbar>
<ToolbarButton title="Open in application" href={revision.urls.app}>
<Icon icon="code-commit" className="size-4" />
</ToolbarButton>
<ToolbarBody>
<p>
Revision created <DateRelative value={revision.createdAt} />
</p>
{revision.git ? (
<p className="text-xs text-light/8 dark:text-light/8">{revision.git.message}</p>
) : null}
</ToolbarBody>
<ToolbarButtonGroups>
<ToolbarLayout>
<Toolbar>
<ToolbarButton title="Open in application" href={revision.urls.app}>
<Icon icon="arrow-up-right-from-square" className="size-4" />
<Icon icon="code-commit" className="size-4" />
</ToolbarButton>
{revision.git?.url ? (
<ToolbarButton title="Open git commit" href={revision.git.url}>
<Icon
icon={revision.git.url.includes('github.com') ? 'github' : 'gitlab'}
className="size-4"
/>
<ToolbarBody>
<p>
Revision created <DateRelative value={revision.createdAt} />
</p>
{revision.git ? (
<p className="text-xs text-light/8 dark:text-light/8">
{revision.git.message}
</p>
) : null}
</ToolbarBody>
<ToolbarButtonGroups>
<ToolbarButton title="Open in application" href={revision.urls.app}>
<Icon icon="arrow-up-right-from-square" className="size-4" />
</ToolbarButton>
) : null}
</ToolbarButtonGroups>
</Toolbar>
{revision.git?.url ? (
<ToolbarButton title="Open git commit" href={revision.git.url}>
<Icon
icon={revision.git.url.includes('github.com') ? 'github' : 'gitlab'}
className="size-4"
/>
</ToolbarButton>
) : null}
</ToolbarButtonGroups>
</Toolbar>
</ToolbarLayout>
);
}
+36 -6
View File
@@ -1,12 +1,20 @@
'use client';
import { SiteAds, SiteAdsStatus } from '@gitbook/api';
import {
SiteAds,
SiteAdsStatus,
SiteInsightsAdPlacement,
SiteInsightsAd,
SiteInsightsTrademarkPlacement,
} from '@gitbook/api';
import * as React from 'react';
import { t, useLanguage } from '@/intl/client';
import { ClassValue, tcls } from '@/lib/tailwind';
import { renderAd } from './renderAd';
import { useTrackEvent } from '../Insights';
import { Link } from '../primitives';
/**
* Zone ID provided by BuySellAds for the preview.
@@ -28,7 +36,7 @@ export function Ad({
}: {
zoneId: string | null;
spaceId: string;
placement: string;
placement: SiteInsightsAdPlacement;
ignore: boolean;
style?: ClassValue;
siteAdsStatus?: SiteAds['status'];
@@ -36,7 +44,20 @@ export function Ad({
}) {
const containerRef = React.useRef<HTMLDivElement>(null);
const [visible, setVisible] = React.useState(false);
const [ad, setAd] = React.useState<React.ReactNode | undefined>(undefined);
const [ad, setAd] = React.useState<
{ children: React.ReactNode; insightsAd: SiteInsightsAd | null } | undefined
>(undefined);
const trackEvent = useTrackEvent();
// Track display of the ad
React.useEffect(() => {
if (ad?.insightsAd) {
trackEvent({
type: 'ad_display',
ad: ad.insightsAd,
});
}
}, [ad]);
// Observe the container visibility
React.useEffect(() => {
@@ -121,7 +142,7 @@ export function Ad({
<div ref={containerRef} className={tcls(style)} data-visual-test="removed">
{ad ? (
<>
{ad}
{ad.children}
<AdSponsoredLink spaceId={spaceId} />
</>
) : null}
@@ -132,6 +153,7 @@ export function Ad({
function AdSponsoredLink(props: { spaceId: string }) {
const { spaceId } = props;
const language = useLanguage();
const trackEvent = useTrackEvent();
const viaUrl = new URL('https://www.gitbook.com');
viaUrl.searchParams.set('utm_source', 'content');
@@ -149,9 +171,17 @@ function AdSponsoredLink(props: { spaceId: string }) {
'dark:text-light/5',
)}
>
<a target="_blank" href={viaUrl.toString()} className={tcls('hover:underline')}>
<Link
target="_blank"
href={viaUrl.toString()}
className={tcls('hover:underline')}
insights={{
type: 'trademark_click',
placement: SiteInsightsTrademarkPlacement.Ad,
}}
>
{t(language, 'sponsored_via_gitbook')}
</a>
</Link>
</p>
);
}
@@ -1,20 +1,38 @@
import { SiteInsightsAd } from '@gitbook/api';
import * as React from 'react';
import { getResizedImageURL } from '@/lib/images';
import { tcls } from '@/lib/tailwind';
import { AdItem } from './types';
import { Link } from '../primitives';
/**
* Classic rendering for an ad.
*/
export async function AdClassicRendering({ ad }: { ad: AdItem }) {
export async function AdClassicRendering({
ad,
insightsAd,
}: {
ad: AdItem;
insightsAd: SiteInsightsAd | null;
}) {
const smallImgSrc =
'smallImage' in ad ? await getResizedImageURL(ad.smallImage, { width: 192, dpr: 2 }) : null;
const logoSrc =
'logo' in ad ? await getResizedImageURL(ad.logo, { width: 192 - 48, dpr: 2 }) : null;
return (
<a
<Link
rel="sponsored noopener"
target="_blank"
insights={
insightsAd
? {
type: 'ad_click',
ad: insightsAd,
}
: undefined
}
className={tcls(
'flex',
'flex-col',
@@ -29,8 +47,6 @@ export async function AdClassicRendering({ ad }: { ad: AdItem }) {
'p-4',
)}
href={ad.statlink}
rel="sponsored noopener"
target="_blank"
>
{smallImgSrc && 'smallImage' in ad ? (
<div>
@@ -47,6 +63,6 @@ export async function AdClassicRendering({ ad }: { ad: AdItem }) {
<div className={tcls('flex', 'flex-col')}>
<div className={tcls('text-xs')}>{ad.description}</div>
</div>
</a>
</Link>
);
}

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