Compare commits

...

61 Commits

Author SHA1 Message Date
taranvohra d6b9fe6643 Bump api package 2024-10-11 12:58:44 +05:30
taranvohra 766c97a100 Merge remote-tracking branch 'origin/main' into cleanup-legacy-code 2024-10-11 12:58:05 +05:30
Greg Bergé 32e4193557 Implement header link style (#2513) 2024-10-09 15:25:47 +02:00
Zeno Kapitein 133c3e7c0a Update Checkbox component (#2511) 2024-10-08 11:02:51 +02:00
taranvohra 29fca1e835 bun.lockb 2024-10-07 02:01:02 +05:30
taranvohra 48b5c0707b Merge main 2024-10-07 01:52:50 +05:30
Samy Pessé 6ce3cea682 Stop using KV cache backend for now, but also improves it for higher performances (#2510) 2024-10-03 15:46:58 +02:00
Greg Bergé 250e77d18b Fix synced blocks display (#2508) 2024-10-03 10:30:21 +02:00
Addison e3bfe006e9 Add badges section to readme (#2507) 2024-10-02 18:15:37 +09:00
Taran Vohra 76aeecdc68 Remove /v/ from e2e tests (#2505) 2024-10-01 12:04:08 +05:30
Samy Pessé 15d2ee3e76 Show captions for file blocks (#2506) 2024-09-30 17:54:25 +02:00
Taran Vohra b066db479f Bump the cache key for api.getPublishedContentByUrl (#2502) 2024-09-30 15:04:30 +02:00
Samy Pessé a69ff2789a Fix locationHint not being passed when purging the cache (#2504) 2024-09-30 14:45:17 +02:00
Taran Vohra 4df235d64a Add more visitor auth cookie combinations with /v/ for backwards compatibility (#2503) 2024-09-30 17:33:33 +05:30
Taran Vohra 11524457e3 URL alternative resolution criteria (#2497) 2024-09-30 14:18:44 +05:30
Addison 8f7364293e Update Documented on GB badge from encoded to uploaded icon (#2501) 2024-09-30 15:44:45 +08:00
Samy Pessé 56f5fa1fbe Lower usage of KV cache to 30% of tags (#2500) 2024-09-29 10:31:27 +02:00
Samy Pessé b075f0f7e9 Switch to aria-current="page" for the TOC items (#2499) 2024-09-27 12:54:11 +02:00
Samy Pessé 0ca32afe8d Lower usage of KV cache to 60% of tags (#2498) 2024-09-27 11:46:15 +02:00
Samy Pessé 32c2f257a9 Lower usage of KV cache to 80% of tags (#2496) 2024-09-26 19:28:25 +02:00
Brett Jephson a7066ccbe1 Fix: mobile navigation scroll (#2486)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-09-26 14:42:09 +01:00
Taran Vohra 09248e0efe Revert "generate upto URL with 3 segments to support the new site url format" (#2494) 2024-09-26 18:29:01 +05:30
Taran Vohra e2ef22fc5f generate upto URL with 3 segments to support the new site url format (#2493)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-09-26 17:16:22 +05:30
Samy Pessé 75f825e4f8 Disable KV cache for 5% of the cache tags (#2490) 2024-09-26 10:23:25 +02:00
Samy Pessé 9b8d5198e4 Experiment with lower DO billable duration by using direct RPC methods (#2492) 2024-09-25 23:57:43 +02:00
Samy Pessé e09f747727 Refresh change request cache when click refresh button (#2489) 2024-09-25 16:15:42 +02:00
Samy Pessé 16e6171750 Cache embeds for faster rendering (#2488) 2024-09-25 13:33:40 +02:00
Samy Pessé f885e887ea Improve change request previews: consistency and toolbar (#2487) 2024-09-25 12:54:15 +02:00
Samy Pessé 5096f7fbc5 Disable KV cache for docs.gitbook.com and change requests (#2485) 2024-09-25 11:53:53 +02:00
Brett Jephson f16560c1ee Scroll offset (#2484) 2024-09-25 08:52:44 +01:00
Samy Pessé d0f4860759 Refresh icons urls to purge cache of 500 (#2483) 2024-09-24 18:16:35 +02:00
Samy Pessé 34d36c6de1 Fix next-on-pages configuration for ~gitbook/static (#2482) 2024-09-24 17:25:58 +02:00
Brett Jephson 042b850b5d RND-2147: automatically scroll TOC (#2478) 2024-09-24 16:24:55 +01:00
Samy Pessé 73892f4fc2 Fix release preview CI workflow (#2481) 2024-09-24 13:13:45 +02:00
Samy Pessé 636b868bf1 Experimental new cache backend powered by DO (#2479)
Co-authored-by: Johan Preynat <johan.preynat@gmail.com>
2024-09-24 12:55:49 +02:00
Addison b144368e3f Update Dutch "Ask or Search" terminology to fit on one line (#2480) 2024-09-24 16:30:30 +09:00
Scott Cazan 683b4193d1 Don't use customized site title for space in search selector (#2367) 2024-09-23 12:43:03 +02:00
Samy Pessé f4c953665a Optimize layout shift while transitioning between pages with full width blocks (#2477) 2024-09-23 06:19:49 +02:00
Samy Pessé 0f990c772a Show definition title when visible in cards (#2476) 2024-09-22 19:04:23 +02:00
Samy Pessé 0bf985af61 Don't show hidden pages in the empty state of a page (#2475) 2024-09-19 15:17:13 +02:00
Samy Pessé 42473611d3 Add required query parameters to the code sample (#2474) 2024-09-19 14:31:22 +02:00
Samy Pessé 2c437f7d94 Fix linking to tabs itself (#2473) 2024-09-19 10:52:34 +02:00
vibhanshub aa8c49eb0c Display pattern if available in OpenAPI params (#2461)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-09-19 09:59:10 +02:00
Samy Pessé b32e40c72a Persist state of tabs and dynamically sync them based on title (#2472) 2024-09-19 09:40:54 +02:00
Samy Pessé 2ff7ed1b52 Hide button on mobile to open toc if disabled at the page level (#2471) 2024-09-18 19:49:02 +02:00
Samy Pessé bfbed1a69b Use translation for "Sponsored via GitBook" (#2469) 2024-09-17 13:41:53 +02:00
Samy Pessé ef9d012be9 Fix generation of icons package and add task "clean" (#2470) 2024-09-17 13:41:18 +02:00
Nichlas f12a2155c0 Added the Norwegian language (#2467)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-09-17 12:15:21 +02:00
Taran Vohra 43f696c4a8 use samesite none for tracking cookie (#2299) 2024-09-17 11:57:28 +05:30
Samy Pessé 4c19014dcd Prevent robots indexation for pages where it's disabled (#2464) 2024-09-13 13:52:15 +02:00
Samy Pessé 0e7f9d6778 Fix TS error when adding support for a locale not yet supported by API (#2465) 2024-09-13 10:30:20 +02:00
Rens Reinders 00a0bf3c1b Add Dutch Locale support (#2450) 2024-09-13 10:12:44 +02:00
taranvohra 434cfd7a08 WIP 2024-09-12 18:02:33 +02:00
taranvohra e3587d59aa use gitbook/api version 0.61 2024-09-12 17:40:55 +02:00
Brett Jephson e9149036f6 RND-3387: synchronize response tabs (#2457)
Co-authored-by: Samy Pessé <samypesse@gmail.com>
2024-09-12 11:01:29 +01:00
Addison b6a9967959 Update search/ask wording for Japanese localization to fit UI better (#2462) 2024-09-12 09:58:58 +02:00
Addison 8bbc3caf3e Update Readme & Contributing Guide (#2459) 2024-09-09 15:28:19 +02:00
Samy Pessé 237b703a6c Fix crash in OpenAPI block because of undefined examples (#2458) 2024-09-06 16:55:04 +02:00
vibhanshub cf3045a718 Add Python support in code samples (#2453) 2024-09-06 14:29:50 +01:00
vibhanshub a679e7283f Render mandatory headers in the code sample (#2445) 2024-09-06 13:24:52 +01:00
Samy Pessé 13c75341e2 Use ellipsis and fix icon color for more links in the header on small screen (#2455) 2024-09-06 11:57:42 +02:00
169 changed files with 3044 additions and 1334 deletions
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/cache-do': minor
---
Experiment with optimizing billable duration in Cloudflare by using multiple RPC sessions instead of one
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix scroll position when navigating pages on mobile
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': minor
---
Add Python support in Code Samples
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Use ellipsis and fix icon color for more links in the header on small screen
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Improve consistency of change request preview by removing cache-control on response
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/icons': patch
---
Update version for static assets to fix invalid caching
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Revalidate change request cached content when pressing refresh button
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/icons': patch
---
Fix first run of the package in development mode
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Improve performances of loading pages with embeds by caching them
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/cache-do': minor
---
First version of a new cache backend powered by Cloudflare Durable Objects
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Add support for Norwegian language
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Optimize layout shift while transitioning between pages with full width blocks (ex: OpenAPI blocks)
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix GitBook specific static assets not being served correctly when deployed on Cloudflare
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/cache-do': patch
---
Enable Workers observability with a sampling of 0.1
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Automatically scroll to active item in TOC
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Persist state of tabs and dynamically sync them based on title
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Ensure "Sponsored via GitBook" can be translated in all languages
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Show the caption for file blocks
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Use new cache backend, powered by Durable Objects, alongside the existing ones (KV, etc).
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Include offset in calculations of whether scrollable element is in view
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': minor
---
Add required query parameters to the code sample
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': minor
---
Display pattern if available in parmas in OpenAPI block
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Stop using KV cache backend for now, but also improves it for higher performances
+6
View File
@@ -0,0 +1,6 @@
---
'@gitbook/react-openapi': minor
'gitbook': patch
---
Synchronize response and response example tabs
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Show definition title when visible in cards
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Update design of Checkbox to be more consistent and readable
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Disable KV cache for docs.gitbook.com as a test, also disable it for change-request to improve consistency
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Fix crash when `example` is undefined for a response
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Improve the toolbar for change-requests and revisions to show more actions
+5
View File
@@ -0,0 +1,5 @@
---
'@gitbook/react-openapi': patch
---
Render mandatory headers in code sample
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Prevent search indexation for pages where it's configured as disabled
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix table of contents being visible on mobile when disabled at the page level
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Fix accessibility of the table of contents by using `aria-current` instead of `aria-selected`
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Changed the alternative URL resolution criteria in order to support site URLs without /v/ prefix
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': patch
---
Don't show hidden pages in the empty state of a page
+5
View File
@@ -0,0 +1,5 @@
---
'gitbook': minor
---
Fix linking to a tab itself
+21 -7
View File
@@ -1,6 +1,8 @@
# Welcome to GitBook's contributing guide!
Thank you for investing your time in contributing to GitBook. Any contribution you make will be reviewed by our team.In this guide, you'll learn the different ways you can contribute.
> _For help, support, feature requests, and product questions - head to our [GitHub Community](https://github.com/orgs/GitbookIO/discussions) 🤖_
Thank you for investing your time in contributing to GitBook. Any contribution you make will be reviewed by our team. In this guide, you'll learn the different ways you can contribute.
## Types of Contributions
@@ -45,13 +47,25 @@ Any contribution you make can be made to the code located in this repository. In
- [Fork the repo](https://docs.github.com/en/github/getting-started-with-github/fork-a-repo#fork-an-example-repository) so that you can make your changes without affecting the original project until you're ready to merge them.
##### GitHub Codespaces:
- [Fork, edit, and preview](https://docs.github.com/en/free-pro-team@latest/github/developing-online-with-codespaces/creating-a-codespace) using [GitHub Codespaces](https://github.com/features/codespaces) without having to install and run the project locally.
#### 2. Create a working branch and start with your changes
After forking this repository, you'll want to [create a branch](https://docs.github.com/en/issues/tracking-your-work-with-issues/creating-a-branch-for-an-issue) to work off of. After creating the branch, you can start making changes!
After forking this repository, you'll want to [create a branch](https://docs.github.com/en/issues/tracking-your-work-with-issues/creating-a-branch-for-an-issue) to work off of.
#### 3. Install dependencies and run the project locally
GitBook uses [Bun](https://bun.sh/) to run the project. Make sure you're using the specified version of `node` before running any of the development commands to ensure a smooth development experience.
You can easily do this by running the command `nvm use`.
To start your local version of GitBook, run the command `bun dev`.
#### 4. Preview your changes
When running the development server, published GitBook sites can be rendered through your local version at `http://localhost:3000/`.
For example, our published docs can be viewed using the local version by visiting `http://localhost:3000/docs.gitbook.com` after running the development server.
You can visit any published GitBook site behind your development server. Please make sure your site is [published publicly](https://docs.gitbook.com/published-documentation/publish-your-content-as-a-docs-site) to ensure you can view the site correctly in your development version.
### Commit your update
@@ -71,4 +85,4 @@ When you're finished with the changes, [create a pull request](https://docs.gith
### Your PR is merged
Congratulations 🎉Thank you for your contribution! Once your PR is merged, your contributions will be publicly visible on the relevant repository.
Congratulations 🎉 Thank you for your contribution! Once your PR is merged, your contributions will be publicly visible on the relevant repository.
+6
View File
@@ -93,6 +93,12 @@ jobs:
env:
BASE_URL: ${{needs.deploy.outputs.deployment_url}}
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
- uses: actions/upload-artifact@v4
if: ${{ !cancelled() }}
with:
name: playwright-test-results
path: packages/gitbook/test-results/
retention-days: 3
pagespeed-testing:
runs-on: ubuntu-latest
name: PageSpeed Testing
+23
View File
@@ -35,3 +35,26 @@ jobs:
# https://github.com/orgs/community/discussions/26875#discussioncomment-3253761
GITHUB_TOKEN: ${{ secrets.GH_PERSONAL_TOKEN }}
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
release-preview:
# For now it releases the cache-do to both preview and production
# Once we changed to deploy the app only on release, we should change `release:preview` in `cache-do`
name: Release Preview
runs-on: ubuntu-latest
steps:
- name: Checkout Repo
uses: actions/checkout@v3
- name: Setup bun
uses: oven-sh/setup-bun@v1
with:
bun-version: 1.1.18
- name: Install dependencies
run: bun install --frozen-lockfile
env:
PUPPETEER_SKIP_DOWNLOAD: 1
- name: Release preview packages
run: bun run release:preview
env:
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
+37 -8
View File
@@ -5,7 +5,7 @@
</p>
<p align="center">
<a href="https://gitbook.com"><img src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=data:image/svg%2bxml;base64,PHN2ZyB3aWR0aD0iNjUiIGhlaWdodD0iNjUiIHZpZXdCb3g9IjAgMCA2NSA2NSIgZmlsbD0ibm9uZSIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj4KPHBhdGggZD0iTTI3LjM5NjQgMzMuNjc2NEMzMC41MjU1IDM1LjQ4MjQgMzIuMDkgMzYuMzg1NCAzMy44MDgzIDM2LjM4NjlDMzUuNTI2NSAzNi4zODg0IDM3LjA5MjYgMzUuNDg4MiA0MC4yMjQ5IDMzLjY4NzdMNjAuMTkxNCAyMi4yMTA0QzYxLjA5MjcgMjEuNjkyMiA2MS42NDg0IDIwLjczMTggNjEuNjQ4NCAxOS42OTIxQzYxLjY0ODQgMTguNjUyNCA2MS4wOTI3IDE3LjY5MiA2MC4xOTE0IDE3LjE3MzlMNDAuMjE3NyA1LjY5MjQ1QzM3LjA4ODggMy44OTM4NiAzNS41MjQzIDIuOTk0NTcgMzMuODA3OCAyLjk5NTI0QzMyLjA5MTIgMi45OTU5MSAzMC41Mjc1IDMuODk2NDIgMjcuNCA1LjY5NzQ0TDEwLjIyOTMgMTUuNTg1NUMxMC4xMDIgMTUuNjU4OCAxMC4wMzg0IDE1LjY5NTQgOS45NzkwOCAxNS43MzAxQzQuMTEzNzEgMTkuMTYzNyAwLjQ4OTg5MiAyNS40MzIzIDAuNDQxNDM4IDMyLjIyODZDMC40NDA5NDggMzIuMjk3MyAwLjQ0MDk0OCAzMi4zNzA4IDAuNDQwOTQ4IDMyLjUxNzZDMC40NDA5NDggMzIuNjY0MyAwLjQ0MDk0OCAzMi43Mzc2IDAuNDQxNDM3IDMyLjgwNjNDMC40ODk3ODUgMzkuNTk0OSA0LjEwNTUyIDQ1Ljg1NzcgOS45NjA0NCA0OS4yOTRDMTAuMDE5NiA0OS4zMjg3IDEwLjA4MzIgNDkuMzY1NCAxMC4yMTAyIDQ5LjQzODdMMjAuOTY1OSA1NS42NDg3QzI3LjIzMzIgNTkuMjY3MyAzMC4zNjY4IDYxLjA3NjYgMzMuODA4MSA2MS4wNzc3QzM3LjI0OTMgNjEuMDc4OSA0MC4zODQyIDU5LjI3MTcgNDYuNjUzOSA1NS42NTc0TDU4LjAwOCA0OS4xMTIxQzYxLjE0NzQgNDcuMzAyMyA2Mi43MTcxIDQ2LjM5NzQgNjMuNTc5IDQ0LjkwNTZDNjQuNDQwOSA0My40MTM5IDY0LjQ0MDkgNDEuNjAyIDY0LjQ0MDkgMzcuOTc4NFYzMC45NzgxQzY0LjQ0MDkgMjkuOTcyOCA2My44OTY1IDI5LjA0NjQgNjMuMDE4MiAyOC41NTczQzYyLjE2ODQgMjguMDgzOSA2MS4xMzI1IDI4LjA5MSA2MC4yODkxIDI4LjU3NThMMzcuMDA3NCA0MS45NTg4QzM1LjQ0NTQgNDIuODU2NyAzNC42NjQzIDQzLjMwNTYgMzMuODA3MyA0My4zMDU5QzMyLjk1MDIgNDMuMzA2MiAzMi4xNjg5IDQyLjg1NzcgMzAuNjA2MyA0MS45NjA3TDE0Ljg0ODcgMzIuOTE1NUMxNC4wNTk0IDMyLjQ2MjQgMTMuNjY0NyAzMi4yMzU5IDEzLjM0NzcgMzIuMTk1QzEyLjYyNSAzMi4xMDE3IDExLjkzMDEgMzIuNTA2NiAxMS42NTQ4IDMzLjE4MTNDMTEuNTM0MSAzMy40NzcyIDExLjUzNjUgMzMuOTMyMiAxMS41NDE0IDM0Ljg0MjRDMTEuNTQ1IDM1LjUxMjQgMTEuNTQ2OCAzNS44NDc0IDExLjYwOTQgMzYuMTU1NkMxMS43NDk3IDM2Ljg0NTYgMTIuMTEyNyAzNy40NzA1IDEyLjY0MjggMzcuOTM0MUMxMi44Nzk1IDM4LjE0MTEgMTMuMTY5NiAzOC4zMDg1IDEzLjc1IDM4LjY0MzVMMzAuNTk3NCA0OC4zNjcyQzMyLjE2NDEgNDkuMjcxNCAzMi45NDc0IDQ5LjcyMzUgMzMuODA3NSA0OS43MjM3QzM0LjY2NzcgNDkuNzIzOSAzNS40NTEzIDQ5LjI3MjMgMzcuMDE4NCA0OC4zNjg5TDU3LjY2ODQgMzYuNDY1NEM1OC4yMDM3IDM2LjE1NjkgNTguNDcxNCAzNi4wMDI2IDU4LjY3MjEgMzYuMTE4NUM1OC44NzI3IDM2LjIzNDUgNTguODcyNyAzNi41NDM0IDU4Ljg3MjcgMzcuMTYxM1Y0MC4zMzY1QzU4Ljg3MjcgNDEuMjQyNCA1OC44NzI3IDQxLjY5NTQgNTguNjU3MiA0Mi4wNjgzQzU4LjQ0MTggNDIuNDQxMyA1OC4wNDkzIDQyLjY2NzUgNTcuMjY0NCA0My4xMTk5TDQwLjIzMjIgNTIuOTM4QzM3LjA5NjYgNTQuNzQ1NCAzNS41Mjg4IDU1LjY0OTIgMzMuODA3OSA1NS42NDg0QzMyLjA4NjkgNTUuNjQ3NiAzMC41MTk5IDU0Ljc0MjQgMjcuMzg2IDUyLjkzMjFMMTEuNDUwOSA0My43MjdDMTEuNDAwMyA0My42OTc4IDExLjM3NSA0My42ODMyIDExLjM1MTQgNDMuNjY5NEM4LjAxMDIzIDQxLjcxNyA1Ljk0ODU5IDM4LjE0NTEgNS45MjkyNSAzNC4yNzU0QzUuOTI5MTIgMzQuMjQ4IDUuOTI5MTIgMzQuMjE4OCA1LjkyOTEyIDM0LjE2MDRWMzEuMjQ1OEM1LjkyOTEyIDI5LjEwOTUgNy4wNjY4OSAyNy4xMzQ5IDguOTE1MTMgMjYuMDYzNkMxMC41NDgzIDI1LjExNjkgMTIuNTYyOCAyNS4xMTUxIDE0LjE5NzcgMjYuMDU4N0wyNy4zOTY0IDMzLjY3NjRaIiBmaWxsPSIjRjJGN0Y3Ii8+Cjwvc3ZnPgo=&labelColor=5c5c5c&color=3F89A1&label=%20" alt="Documented on GitBook"></a>
<a href="https://gitbook.com"><img src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=3F89A1"></a>
<a href="#"><img src="https://img.shields.io/badge/Open_Source-❤️-FDA599?"/></a>
<a href="/LICENSE"><img src="https://img.shields.io/badge/License-GNU_GPLv3-F4E28D"/></a>
<a href="/.github/CONTRIBUTING.md"><img src="https://img.shields.io/github/contributors/gitbookIO/gitbook"/></a>
@@ -14,7 +14,7 @@
<p align="center">Welcome to GitBook, the platform for managing technical knowledge for teams.</p>
<p align="center">This repository contains the open-source code used to render GitBook's published content.</p>
<p align="center">This repository contains the open source code used to render GitBook's published content.</p>
<p align="center">
<img alt="GitBook Open Published Site" src="./assets/published-site.png">
@@ -46,19 +46,28 @@ To run a local version of this project, please follow these simple steps.
git clone https://github.com/gitbookIO/gitbook.git
```
2. Install the project's dependencies through Bun.
2. Ensure you are using the project's version of `node`. Running `nvm use` will change your local version to the correct one.
3. Install the project's dependencies through Bun.
```
bun install
```
3. Start your local development server.
4. Start your local development server.
```
bun dev
```
Then open the space in your web browser, using http://localhost:3000/<host>/<path> (example: http://localhost:3000/docs.gitbook.com).
5. Open a published GitBook space in your web browser, prefixing it with `http://localhost:3000/`.
examples:
- http://localhost:3000/docs.gitbook.com
- http://localhost:3000/open-source.gitbook.io/midjourney
Any published GitBook site can be accessed through your local development instance, and any updates you make to the codebase will be reflected in your browser.
### Other development commands
@@ -71,7 +80,7 @@ All pull-requests will be tested against both visual and performances testing to
## Contributing
GitBook's rendering engine is fully open-source and built on top of [Next.js](https://nextjs.org/). Head to our [contributing guide](https://github.com/GitbookIO/gitbook/.github/CONTRIBUTING.md) to learn more about the workflow on adding your first Pull Request.
GitBook's rendering engine is fully open source and built on top of [Next.js](https://nextjs.org/). Head to our [contributing guide](https://github.com/GitbookIO/gitbook/blob/main/.github/CONTRIBUTING.md) to learn more about the workflow on adding your first Pull Request.
### Types of contributions
@@ -79,7 +88,7 @@ We encourage you to contribute to GitBook to help us build the best tool for doc
#### Translations
The GitBook UI is rendered using a set of translation files found in [`src/intl/translations`](/src/intl/translations/). We welcome all additional translations for the UI.
The GitBook UI is rendered using a set of translation files found in [`packages/gitbook/src/intl/translations`](/packages/gitbook/src/intl/translations/). We welcome all additional translations for the UI.
#### Bugs
@@ -90,7 +99,7 @@ Encounter a bug or find an issue you'd like to fix? Helping us fix issues relate
> [!WARNING]
> While it is possible to self-host this project, we do not recommend this unless you are certain this option fits your need.
>
> _Looking to add a specific feature in GitBook? Head to our [contributing guide](/.github/CONTRIBUTING.md) to get started._
> _Looking to add a specific feature in GitBook? Head to our [contributing guide](https://github.com/GitbookIO/gitbook/blob/main/.github/CONTRIBUTING.md) to get started._
>
> Self-hosting this project puts the responsibility of maintaining and merging future updates on **you**. We cannot guarantee support, maintenance, or updates to forked and self-hosted instances of this project.
>
@@ -110,6 +119,26 @@ If you plan to distribute the code, you must make the source code public to comp
See `LICENSE` for more information.
## Badges
<p align="left">
<a href="https://gitbook.com"><img src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=3F89A1"></a>
<a href="https://gitbook.com"><img src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=F4E28D"></a>
<a href="https://gitbook.com"><img src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=FDA599"></a>
</p>
```md
[![GitBook](https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=3F89A1)](https://gitbook.com/)
```
```html
<a href="https://gitbook.com">
<img
src="https://img.shields.io/static/v1?message=Documented%20on%20GitBook&logo=gitbook&logoColor=ffffff&label=%20&labelColor=5c5c5c&color=3F89A1"
/>
</a>
```
## Acknowledgements
GitBook wouldn't be possible without these projects:
BIN
View File
Binary file not shown.
+13 -14
View File
@@ -1,8 +1,16 @@
{
"name": "gitbook",
"version": "0.1.0",
"private": true,
"devDependencies": {
"@changesets/cli": "^2.27.7",
"prettier": "^3.0.3",
"turbo": "^2.1.2"
},
"packageManager": "bun@1.1.18",
"patchedDependencies": {
"@vercel/next@4.3.6": "patches/@vercel%2Fnext@4.3.6.patch"
},
"private": true,
"scripts": {
"dev": "turbo run dev",
"build": "turbo run build",
@@ -16,20 +24,11 @@
"e2e": "turbo run e2e",
"changeset": "changeset",
"release": "turbo run release && changeset publish",
"download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local"
"release:preview": "turbo run release:preview",
"download:env": "op read op://gitbook-x-dev/gitbook-open/.env.local >> .env.local",
"clean": "turbo run clean"
},
"workspaces": [
"packages/*"
],
"devDependencies": {
"@changesets/cli": "^2.27.7",
"prettier": "^3.0.3",
"turbo": "^2.0.9"
},
"patchedDependencies": {
"@vercel/next@4.3.6": "patches/@vercel%2Fnext@4.3.6.patch"
},
"dependencies": {
"@scalar/api-client-react": "0.3.7"
}
]
}
+3
View File
@@ -0,0 +1,3 @@
.wrangler
worker-configuration.d.ts
dist/
+22
View File
@@ -0,0 +1,22 @@
# `@gitbook/cache-do`
Cache backend, powered by Cloudflare Durable Objects. The cache is optimized for GitBook use-cases.
### Performances
The cache backend is optimized for performances by being distributed and accessible close to the worker locations that are reading it.
### Geo-distribution
To achieve a good balance between **performances** and **consistency**, cache objects are distributed over 7 locations, representing continents.
It makes it possible to purge all 7 locations in one go and achieve fast consistency.
### Concepts
**Cache tag**: unique tag in the cache environment. A cache tag groups multiple keys that should be purged together in one operation.
Cache tags should not contain a large set of unique keys. Exceeding thousands could lead to performances or reliability issues.
**Cache key**: unique key in the cache environment. Each key should be assigned to a `tag`.
**Location**: cache is distributed over 7 unique locations, one for each continent.
+42
View File
@@ -0,0 +1,42 @@
{
"name": "@gitbook/cache-do",
"type": "module",
"private": true,
"exports": {
".": {
"types": "./dist/index.d.ts",
"development": "./src/index.ts",
"default": "./dist/index.js"
},
"./api": {
"types": "./dist/api.d.ts",
"development": "./src/api.ts",
"default": "./dist/api.js"
}
},
"version": "0.0.0",
"dependencies": {
"@msgpack/msgpack": "^3.0.0-beta2",
"lru_map": "^0.4.1"
},
"devDependencies": {
"typescript": "^5.5.3",
"wrangler": "^3.78.7"
},
"scripts": {
"generate": "wrangler types --experimental-include-runtime",
"build": "tsc",
"typecheck": "tsc --noEmit",
"dev": "tsc -w",
"release": "wrangler deploy",
"release:preview": "wrangler deploy && wrangler deploy --env preview"
},
"files": [
"dist",
"src",
"bin",
"data",
"README.md",
"CHANGELOG.md"
]
}
+299
View File
@@ -0,0 +1,299 @@
import { encode, decode } from '@msgpack/msgpack';
import { DurableObject } from 'cloudflare:workers';
import { LRUMap } from 'lru_map';
export interface CacheObjectDescriptor {
get: <Value = unknown>(key: string) => Promise<Value | undefined>;
set: <Value = unknown>(key: string, value: Value, expiresAt: number) => Promise<void>;
}
/**
* Value stored in a chunked binary msgpack format.
* Stored under the key `prop.${key}.${index}`.
*/
interface CacheObjectProp<Value = unknown> {
value: Value;
expiresAt: number;
}
/**
* Expiration clock stored under the key `exp.${expiresAt}.${key}`.
*/
interface CacheObjectExp {
/** Key of the property */
k: string;
/** Number of chunks */
c: number;
}
/**
* Durable Object class being deployed as a distributed cache.
*/
export class CacheObject extends DurableObject {
private lru = new LRUMap<string, { match: CacheObjectProp | undefined }>(500);
/**
* Open a descriptor to access the cache object.
* The goal is to minimize the amount of RPC sessions between the client and the cache object.
* One session is opened per request on the client side and used to perform multiple operations.
* https://developers.cloudflare.com/workers/runtime-apis/rpc/#return-functions-from-rpc-methods
*/
public open(): CacheObjectDescriptor {
return {
get: async <Value = unknown>(key: string) => {
return this.get<Value>(key);
},
set: async <Value = unknown>(key: string, value: Value, expiresAt: number) => {
await this.set(key, value, expiresAt);
},
};
}
/**
* Get the value of a property.
*/
public async get<Value = unknown>(key: string) {
return this.logOperation({ operation: 'get', key }, async (setLog) => {
// Try the memory state first.
const memoryEntry = this.lru.get(key);
if (memoryEntry) {
setLog({ memory: true });
setLog({ memoryMatch: !!memoryEntry.match });
if (!memoryEntry.match) {
return;
}
const isExpired = memoryEntry.match.expiresAt < Date.now();
setLog({ memoryExpired: isExpired });
if (!isExpired) {
return memoryEntry.match.value as Value;
}
}
return await this.getFromStorage<Value>(key);
});
}
/**
* Get the value of a property from the DO storage.
*/
public async getFromStorage<Value = unknown>(key: string) {
return this.logOperation({ operation: 'getFromStorage', key }, async (setLog) => {
const entries = await this.ctx.storage.list<Uint8Array>({
prefix: getStoragePropKey(key),
noCache: true,
});
if (entries.size) {
const entry = decodeChunks<CacheObjectProp<Value>>(entries);
setLog({ chunks: entries.size, chunksSize: entry?.size ?? 0 });
if (entry && entry.value.expiresAt > Date.now()) {
// Found
this.lru.set(key, { match: entry.value });
return entry.value.value;
}
}
// Not found
this.lru.set(key, { match: undefined });
});
}
/**
* Set a value in the cache object.
*/
public async set<Value = unknown>(key: string, value: Value, expiresAt: number) {
return this.logOperation({ operation: 'set', key }, async (setLog) => {
const prop: CacheObjectProp<Value> = {
value,
expiresAt,
};
this.lru.set(key, { match: prop });
await this.ctx.storage.transaction(async (tx) => {
const entries = encodeChunks(key, prop);
const chunks = Object.keys(entries).length;
setLog({ chunks });
const clockValue: CacheObjectExp = {
k: key,
c: chunks,
};
await tx.put(getGCClockKey(key, expiresAt), clockValue);
await tx.put(entries);
const currentAlarm = await tx.getAlarm();
if (!currentAlarm) {
// Set an alarm to garbage collect all entries that have expired in 12h.
await tx.setAlarm(Date.now() + 12 * 60 * 60 * 1000);
}
});
});
}
/**
* Purge all keys in the cache object.
*/
public async purge() {
return this.logOperation({ operation: 'purge' }, async (setLog) => {
let result = new Set<string>();
try {
// List all the keys in the cache object.
const entries = await this.ctx.storage.list<CacheObjectExp>({
prefix: 'exp.',
noCache: true,
});
setLog({ entries: entries.size });
entries.forEach((exp) => {
result.add(exp.k);
});
} catch (error) {
// If an error occurs, reset the cache object.
// This is a safety mechanism to prevent the cache object from being stuck in a bad state.
console.error('Error during purge, resetting the cache object', error);
}
await this.reset();
return Array.from(result);
});
}
/**
* Alarm to garbage collect all entries that have expired.
*/
async alarm() {
return this.logOperation({ operation: 'alarm' }, async (setLog) => {
try {
const entries = await this.ctx.storage.list<CacheObjectExp>({
prefix: 'exp.',
noCache: true,
});
setLog({ entries: entries.size });
const toDeleteSet = new Set<string>();
for (const [key, exp] of entries) {
const timestamp = parseInt(key.split('.')[1]);
if (timestamp < Date.now()) {
toDeleteSet.add(key);
for (let i = 0; i < exp.c; i++) {
toDeleteSet.add(getStoragePropChunkKey(exp.k, i));
}
}
}
// Delete the keys by batch of 128.
const toDelete = Array.from(toDeleteSet);
setLog({ toDelete: toDelete.length });
for (let i = 0; i < toDelete.length; i += 128) {
await this.ctx.storage.delete(toDelete.slice(i, i + 128));
}
// If there are still keys to delete, set an alarm to continue the deletion in 12h.
if (toDelete.length) {
await this.ctx.storage.setAlarm(Date.now() + 12 * 60 * 60 * 1000);
}
} catch (error) {
// If an error occurs, reset the cache object.
// This is a safety mechanism to prevent the cache object from being stuck in a bad state.
console.error('Error during alarm, reset the cache object', error);
await this.reset();
}
});
}
/**
* Reset the cache object.
*/
async reset() {
return this.logOperation({ operation: 'reset' }, async () => {
this.lru.clear();
await this.ctx.storage.deleteAll();
});
}
/**
* Time and log an operation.
*/
async logOperation<T>(
log: Record<string, unknown>,
fn: (update: (log: Record<string, unknown>) => void) => Promise<T>,
): Promise<T> {
const objectId = this.ctx.id.name ?? this.ctx.id.toString();
let update: Record<string, unknown> = {};
const start = performance.now();
try {
return await fn((arg) => {
Object.assign(update, arg);
});
} finally {
const duration = performance.now() - start;
console.log({ ...log, ...update, objectId, duration });
}
}
}
function getStoragePropKey(key: string): string {
return `prop.${key}.`;
}
function getStoragePropChunkKey(key: string, index: number): string {
return `${getStoragePropKey(key)}${index}`;
}
function getGCClockRootKey(timestamp: number): string {
return `exp.${timestamp}.`;
}
function getGCClockKey(key: string, expiresAt: number): string {
return `${getGCClockRootKey(expiresAt)}${key}`;
}
function encodeChunks<T>(key: string, value: T): Record<string, Uint8Array> {
const buf = encode(value);
const entries: Record<string, Uint8Array> = {};
const chunks = chunkUint8Array(buf, 128 * 1024);
for (let index = 0; index < chunks.length; index++) {
entries[getStoragePropChunkKey(key, index)] = chunks[index];
}
return entries;
}
function decodeChunks<T>(entries: Map<string, Uint8Array>): { value: T; size: number } | undefined {
const chunks = Array.from(entries.entries())
.map(([key, value]) => {
const index = parseInt(key.split('.').pop()!);
return [index, value] as const;
})
.sort(([a], [b]) => a - b)
.map(([, value]) => value);
if (chunks.length === 0) {
return;
}
const buf = mergeUint8Array(chunks);
return { value: decode(buf) as T, size: buf.length };
}
function chunkUint8Array(input: Uint8Array, chunkSize: number): Uint8Array[] {
const chunks: Uint8Array[] = [];
for (let i = 0; i < input.length; i += chunkSize) {
chunks.push(input.slice(i, i + chunkSize));
}
return chunks;
}
function mergeUint8Array(chunks: Uint8Array[]): Uint8Array {
const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);
const result = new Uint8Array(totalLength);
let offset = 0;
for (const chunk of chunks) {
result.set(chunk, offset);
offset += chunk.length;
}
return result;
}
+97
View File
@@ -0,0 +1,97 @@
import type { CacheObject, CacheObjectDescriptor } from './CacheObject';
export type CacheLocationId = ContinentCode;
const allLocations: CacheLocationId[] = ['AF', 'AS', 'NA', 'SA', 'AN', 'EU', 'OC'];
/**
* Location hint for the CacheObject durable object.
*/
const doLocationHints: {
[key in CacheLocationId]: DurableObjectLocationHint;
} = {
AF: 'afr',
AS: 'apac',
NA: 'wnam',
SA: 'sam',
AN: 'oc',
EU: 'weur',
OC: 'oc',
};
/**
* Client to access a cache tag.
*/
export class CacheObjectStub {
private stub: DurableObjectStub<CacheObject>;
constructor(
/** Binding to the CacheObject durable object */
private doNamespace: DurableObjectNamespace<CacheObject>,
/** ID of the location to target */
private locationId: CacheLocationId,
/** Name of the tag */
private tag: string,
) {
const groupId = getCacheObjectIdName(this.locationId, this.tag);
this.stub = this.doNamespace.get(this.doNamespace.idFromName(groupId), {
// Initialize the object with a locaiton hint,
// as we might want to purge all locations before the object is created.
// https://developers.cloudflare.com/durable-objects/reference/data-location/
locationHint: doLocationHints[this.locationId],
});
}
/**
* Open a descriptor to the cache object.
* It can be used to perform multiple operations in a single RPC session.
* Ex:
* ```ts
* using desc = cache.open();
* await desc.set('key', 'value', Date.now() + 1000);
* await desc.get('key');
* ```
*/
async open() {
return await this.stub.open();
}
/**
* Get a value from the cache.
*/
async get<Value = unknown>(key: string) {
return (await this.stub.get(key)) as Value | undefined;
}
/**
* Set a value in the cache.
*/
async set<Value = unknown>(key: string, value: Value, expiresAt: number) {
return await this.stub.set(key, value, expiresAt);
}
/**
* Purge all keys in the cache tag.
*/
async purge() {
const keys = new Set<string>();
await Promise.all(
allLocations.map(async (locationId) => {
const groupId = getCacheObjectIdName(locationId, this.tag);
const cacheGroup = this.doNamespace.get(this.doNamespace.idFromName(groupId), {
// Initialize the object with a locaiton hint,
// as we might want to purge all locations before the object is created.
// https://developers.cloudflare.com/durable-objects/reference/data-location/
locationHint: doLocationHints[this.locationId],
});
const locationkeys = await cacheGroup.purge();
locationkeys.forEach((key) => keys.add(key));
}),
);
return keys;
}
}
function getCacheObjectIdName(locationId: CacheLocationId, tag: string): string {
return `${locationId}:${tag}`;
}
+1
View File
@@ -0,0 +1 @@
export * from './CacheObjectStub';
+9
View File
@@ -0,0 +1,9 @@
import { WorkerEntrypoint } from 'cloudflare:workers';
export * from './CacheObject';
export default class Worker extends WorkerEntrypoint {
fetch() {
return new Response('Hello, world!');
}
}
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "esnext",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": false,
"declaration": true,
"outDir": "dist",
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"incremental": true,
"types": ["./.wrangler/types/runtime.d.ts"]
},
"include": ["src/**/*.ts"],
"exclude": ["node_modules"]
}
+28
View File
@@ -0,0 +1,28 @@
main = "./src/index.ts"
name = "gitbook-open-cache"
compatibility_date = "2024-09-02"
durable_objects.bindings = [
{name = "CACHE", class_name = "CacheObject"}
]
migrations = [
{tag = "v1", new_classes = ["CacheObject"]}
]
[observability]
enabled = true
head_sampling_rate = 0.01
[env.preview]
name = "gitbook-open-cache-preview"
durable_objects.bindings = [
{name = "CACHE", class_name = "CacheObject"}
]
migrations = [
{tag = "v1", new_classes = ["CacheObject"]}
]
[env.preview.observability]
enabled = true
head_sampling_rate = 1
+2 -1
View File
@@ -9,6 +9,7 @@
"emoji-assets": "^8.0.0"
},
"scripts": {
"generate": "bun ./build.ts"
"generate": "bun ./build.ts",
"clean": "rm -rf ./dist"
}
}
+3
View File
@@ -25,3 +25,6 @@
### Sentry ###
# SENTRY_DSN=xxx
### Silent logs
# SILENT=true
+4
View File
@@ -0,0 +1,4 @@
{
"version": 1,
"exclude": ["/~gitbook/static/*"]
}
+7
View File
@@ -0,0 +1,7 @@
import type { CacheObject } from '@gitbook/cache-do';
declare global {
interface CloudflareEnv {
CACHE?: DurableObjectNamespace<CacheObject>;
}
}
+120 -14
View File
@@ -1,4 +1,3 @@
import { DeepPartial } from 'ts-essentials';
import { argosScreenshot } from '@argos-ci/playwright';
import {
CustomizationHeaderPreset,
@@ -9,15 +8,17 @@ import {
import { test, expect, Page } from '@playwright/test';
import jwt from 'jsonwebtoken';
import rison from 'rison';
import { DeepPartial } from 'ts-essentials';
import { getContentTestURL } from '../tests/utils';
interface Test {
name: string;
url: string;
run?: (page: Page) => Promise<unknown>;
fullPage?: boolean;
screenshot?: false;
url: string; // URL to visit for testing
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
}
interface TestsCase {
@@ -104,7 +105,32 @@ const testCases: TestsCase[] = [
},
{
name: 'RFC variant',
url: 'v/rfcs',
url: 'rfcs',
},
{
name: 'Customized variant titles are displayed',
url: '',
run: async (page) => {
const spaceDrowpdown = page.locator('[data-testid="space-dropdown-button"]');
await spaceDrowpdown.click();
const variantSelectionDropdown = page.locator(
'css=[data-testid="space-dropdown-button"] + div',
);
// the customized space title
await expect(
variantSelectionDropdown.getByRole('link', {
name: 'Multi-Variants',
}),
).toBeVisible();
// the NON-customized space title
await expect(
variantSelectionDropdown.getByRole('link', {
name: 'RFCs',
}),
).toBeVisible();
},
},
],
},
@@ -131,13 +157,13 @@ const testCases: TestsCase[] = [
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/v/2.0/reference/api-reference/pets?fallback=true',
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions/2.0/reference/api-reference/pets?fallback=true',
);
},
},
{
name: 'Keep navigation path/route when switching variant (Share link)',
url: 'api-multi-versions-share-links/bRfQbzwsK8rbN1GRxx7K/reference/api-reference/pets',
url: 'api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/reference/api-reference/pets',
screenshot: false,
run: async (page) => {
const spaceDrowpdown = await page.waitForSelector(
@@ -154,7 +180,7 @@ const testCases: TestsCase[] = [
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/bRfQbzwsK8rbN1GRxx7K/v/2.0/reference/api-reference/pets?fallback=true',
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-share-links/8tNo6MeXg7CkFMzSSz81/2.0/reference/api-reference/pets?fallback=true',
);
},
},
@@ -189,7 +215,7 @@ const testCases: TestsCase[] = [
// It should keep the current page path, i.e "reference/api-reference/pets" when navigating to the new variant
await page.waitForURL(
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/v/2.0/reference/api-reference/pets?fallback=true',
'https://gitbook-open-e2e-sites.gitbook.io/api-multi-versions-va/2.0/reference/api-reference/pets?fallback=true',
);
},
},
@@ -346,6 +372,11 @@ const testCases: TestsCase[] = [
name: 'Math',
url: 'blocks/math',
},
{
name: 'Files',
url: 'blocks/files',
fullPage: true,
},
{
name: 'Embeds',
url: 'blocks/embeds',
@@ -422,6 +453,29 @@ const testCases: TestsCase[] = [
}),
run: waitForCookiesDialog,
},
{
name: 'With header buttons',
url: getCustomizationURL({
header: {
preset: CustomizationHeaderPreset.Default,
links: [
{
title: 'Secondary button',
to: { kind: 'url', url: 'https://www.gitbook.com' },
// @ts-ignore Remove once we upgrade to the latest version of the API
style: 'button-secondary',
},
{
title: 'Primary button',
to: { kind: 'url', url: 'https://www.gitbook.com' },
// @ts-ignore Remove once we upgrade to the latest version of the API
style: 'button-primary',
},
],
},
}),
run: waitForCookiesDialog,
},
],
},
{
@@ -528,7 +582,7 @@ const testCases: TestsCase[] = [
expiresIn: '24h',
},
);
return `v/spacea?jwt_token=${token}`;
return `spacea?jwt_token=${token}`;
})(),
run: waitForCookiesDialog,
},
@@ -545,7 +599,7 @@ const testCases: TestsCase[] = [
expiresIn: '24h',
},
);
return `v/spaceb?jwt_token=${token}`;
return `spaceb?jwt_token=${token}`;
})(),
run: waitForCookiesDialog,
},
@@ -562,7 +616,7 @@ const testCases: TestsCase[] = [
expiresIn: '24h',
},
);
return `v/spacec?jwt_token=${token}`;
return `spacec?jwt_token=${token}`;
})(),
run: waitForCookiesDialog,
},
@@ -658,12 +712,64 @@ const testCases: TestsCase[] = [
},
})),
},
{
name: 'SEO',
baseUrl: 'https://gitbook.gitbook.io/test-gitbook-open/',
tests: [
{
name: `Index by default`,
url: '?x-gitbook-search-indexation=true',
screenshot: false,
run: async (page) => {
const metaRobots = page.locator('meta[name="robots"]');
await expect(metaRobots).toHaveAttribute('content', 'index, follow');
},
},
{
name: `Don't index noIndex`,
url: 'page-options/page-no-index?x-gitbook-search-indexation=true',
screenshot: false,
run: async (page) => {
const metaRobots = page.locator('meta[name="robots"]');
await expect(metaRobots).toHaveAttribute('content', 'noindex, nofollow');
},
},
{
name: `Don't index descendant of noIndex`,
url: 'page-options/page-no-index/descendant-of-page-no-index?x-gitbook-search-indexation=true',
screenshot: false,
run: async (page) => {
const metaRobots = page.locator('meta[name="robots"]');
await expect(metaRobots).toHaveAttribute('content', 'noindex, nofollow');
},
},
{
name: `Don't index noRobotsIndex`,
url: 'page-options/page-no-robots-index?x-gitbook-search-indexation=true',
screenshot: false,
run: async (page) => {
const metaRobots = page.locator('meta[name="robots"]');
await expect(metaRobots).toHaveAttribute('content', 'noindex, nofollow');
},
},
{
name: `Don't index descendant of noRobotsIndex`,
url: 'page-options/page-no-robots-index/descendant-of-page-no-robots-index?x-gitbook-search-indexation=true',
screenshot: false,
run: async (page) => {
const metaRobots = page.locator('meta[name="robots"]');
await expect(metaRobots).toHaveAttribute('content', 'noindex, nofollow');
},
},
],
},
];
for (const testCase of testCases) {
test.describe(testCase.name, () => {
for (const testEntry of testCase.tests) {
test(testEntry.name, async ({ page, baseURL }) => {
const testFn = testEntry.only ? test.only : test;
testFn(testEntry.name, async ({ page, baseURL }) => {
const contentUrl = new URL(testEntry.url, testCase.baseUrl);
const url = getContentTestURL(contentUrl.toString(), baseURL);
await page.goto(url);
+8 -5
View File
@@ -12,15 +12,17 @@
"e2e": "playwright test",
"unit": "bun test {src,packages}",
"generate": "gitbook-icons ./public/~gitbook/static/icons custom-icons && gitbook-math ./public/~gitbook/static/math",
"copy:icons": "gitbook-icons ./public/~gitbook/static/icons"
"copy:icons": "gitbook-icons ./public/~gitbook/static/icons",
"clean": "rm -rf ./.next && rm -rf ./public/~gitbook/static"
},
"dependencies": {
"@gitbook/api": "^0.60.0",
"@gitbook/api": "0.64.1",
"@gitbook/cache-do": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*",
"@gitbook/icons": "workspace:*",
"@gitbook/react-contentkit": "workspace:*",
"@gitbook/react-math": "workspace:*",
"@gitbook/react-openapi": "workspace:*",
"@gitbook/react-contentkit": "workspace:*",
"@gitbook/emoji-codepoints": "workspace:*",
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-popover": "^1.0.7",
"@sentry/nextjs": "^7.94.1",
@@ -46,6 +48,7 @@
"openapi-types": "^12.1.3",
"p-map": "^7.0.0",
"parse-cache-control": "^1.0.1",
"postcss-color-contrast": "^1.1.0",
"react": "^18",
"react-dom": "^18",
"react-hotkeys-hook": "^4.4.1",
@@ -66,7 +69,7 @@
"devDependencies": {
"@argos-ci/playwright": "^2.0.0",
"@playwright/test": "^1.42.1",
"@cloudflare/next-on-pages": "^1.12.1",
"@cloudflare/next-on-pages": "^1.13.3",
"@cloudflare/workers-types": "^4.20240725.0",
"@types/js-cookie": "^3.0.6",
"@types/jsontoxml": "^1.0.5",
+3
View File
@@ -0,0 +1,3 @@
# GitBook immutable static assets
/~gitbook/static/*
cache-control: public,max-age=31536000,immutable
@@ -29,7 +29,6 @@ export async function POST(req: NextRequest) {
return NextResponse.json({
success: true,
keys: result.keys,
stats: result.stats,
});
}
@@ -3,15 +3,15 @@
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
import React from 'react';
import { useScrollToHash } from '@/components/hooks';
import { useScrollPage } from '@/components/hooks';
/**
* Client component to initialize interactivity for a page.
*/
export function PageClientLayout(props: {}) {
// We use this hook in the page layout to ensure the elements for the blocks
// are rendered before we scroll to the hash.
useScrollToHash();
// are rendered before we scroll to a hash or to the top of the page
useScrollPage();
useStripFallbackQueryParam();
return null;
@@ -19,7 +19,7 @@ export default function PageSkeleton() {
'lg:items-start',
)}
>
<div className={tcls('flex-1', 'max-w-3xl', 'mx-auto')}>
<div className={tcls('flex-1', 'max-w-3xl', 'mx-auto', 'page-full-width:mx-0')}>
<SkeletonHeading style={tcls('mb-8')} />
<SkeletonParagraph style={tcls('mb-4')} />
</div>
@@ -1,14 +1,12 @@
import { getSpaceLanguage, t } from '@/intl/server';
import { getCurrentSiteLayoutData, getSpaceLayoutData } from '@/lib/api';
import { getCurrentSiteLayoutData } from '@/lib/api';
import { tcls } from '@/lib/tailwind';
import { getContentPointer } from '../../fetch';
import { getSiteContentPointer } from '../../fetch';
export default async function NotFound() {
const pointer = getContentPointer();
const { customization } = await ('siteId' in pointer
? getCurrentSiteLayoutData(pointer)
: getSpaceLayoutData(pointer.spaceId));
const pointer = getSiteContentPointer();
const { customization } = await getCurrentSiteLayoutData(pointer);
const language = getSpaceLanguage(customization);
@@ -8,6 +8,7 @@ import { PageBody, PageCover } from '@/components/PageBody';
import { PageHrefContext, absoluteHref, pageHref } from '@/lib/links';
import { getPagePath, resolveFirstDocument } from '@/lib/pages';
import { ContentRefContext } from '@/lib/references';
import { isSpaceIndexable, isPageIndexable } from '@/lib/seo';
import { tcls } from '@/lib/tailwind';
import { getContentTitle } from '@/lib/utils';
@@ -64,7 +65,7 @@ export default async function Page(props: {
const withPageFeedback = customization.feedback.enabled;
const contentRefContext: ContentRefContext = {
siteContext: 'siteId' in contentPointer ? contentPointer : null,
siteContext: contentPointer,
space,
revisionId: contentTarget.revisionId,
pages,
@@ -129,7 +130,7 @@ export async function generateMetadata({
params: PagePathParams;
searchParams: { fallback?: string };
}): Promise<Metadata> {
const { space, pages, page, customization, parent } = await getPageDataWithFallback({
const { space, pages, page, customization, parent, ancestors } = await getPageDataWithFallback({
pagePathParams: params,
searchParams,
});
@@ -152,6 +153,10 @@ export async function generateMetadata({
absoluteHref(`~gitbook/ogimage/${page.id}`, true),
],
},
robots:
isSpaceIndexable({ space, parent }) && isPageIndexable(ancestors, page)
? 'index, follow'
: 'noindex, nofollow',
};
}
@@ -13,7 +13,7 @@ import { assetsDomain } from '@/lib/assets';
import { buildVersion } from '@/lib/build';
import { getContentSecurityPolicyNonce } from '@/lib/csp';
import { absoluteHref, baseUrl } from '@/lib/links';
import { shouldIndexSpace } from '@/lib/seo';
import { isSpaceIndexable } from '@/lib/seo';
import { getContentTitle } from '@/lib/utils';
import { ClientContexts } from './ClientContexts';
@@ -133,7 +133,7 @@ export async function generateMetadata(): Promise<Metadata> {
},
],
},
robots: shouldIndexSpace({ space, parent }) ? 'index, follow' : 'noindex, nofollow',
robots: isSpaceIndexable({ space, parent }) ? 'index, follow' : 'noindex, nofollow',
};
}
@@ -3,9 +3,9 @@ import { NextRequest } from 'next/server';
import { getCollection, getSite, getSpace } from '@/lib/api';
import { absoluteHref } from '@/lib/links';
import { shouldIndexSpace } from '@/lib/seo';
import { isSpaceIndexable } from '@/lib/seo';
import { getContentPointer } from '../../fetch';
import { getSiteContentPointer } from '../../fetch';
export const runtime = 'edge';
@@ -13,22 +13,14 @@ export const runtime = 'edge';
* Generate a robots.txt for the current space.
*/
export async function GET(req: NextRequest) {
const pointer = getContentPointer();
const space = await getSpace(
pointer.spaceId,
'siteId' in pointer ? pointer.siteShareKey : undefined,
);
const parent =
'siteId' in pointer
? await getSite(pointer.organizationId, pointer.siteId)
: space.visibility === ContentVisibility.InCollection && space.parent
? await getCollection(space.parent)
: null;
const pointer = getSiteContentPointer();
const space = await getSpace(pointer.spaceId, pointer.siteShareKey);
const parent = await getSite(pointer.organizationId, pointer.siteId);
const lines = [
`User-agent: *`,
'Disallow: /~gitbook/',
...(shouldIndexSpace({ space, parent })
...(isSpaceIndexable({ space, parent })
? [`Allow: /`, `Sitemap: ${absoluteHref(`/sitemap.xml`, true)}`]
: [`Disallow: /`]),
];
@@ -5,8 +5,9 @@ import { NextRequest } from 'next/server';
import { getSpaceContentData } from '@/lib/api';
import { absoluteHref } from '@/lib/links';
import { getPagePath } from '@/lib/pages';
import { isPageIndexable } from '@/lib/seo';
import { getContentPointer } from '../../fetch';
import { getSiteContentPointer } from '../../fetch';
export const runtime = 'edge';
@@ -19,7 +20,8 @@ export async function GET(req: NextRequest) {
pointer,
'siteId' in pointer ? pointer.siteShareKey : undefined,
);
const pages = flattenPages(rootPages, (page) => !page.hidden);
const pages = flattenPages(rootPages, (page) => !page.hidden && isPageIndexable([], page));
const urls = pages.map(({ page, depth }) => {
// Decay priority with depth
const priority = Math.pow(2, -0.25 * depth);
@@ -72,14 +74,19 @@ type FlatPageEntry = { page: RevisionPageDocument; depth: number };
function flattenPages(
rootPags: RevisionPage[],
filter: (page: RevisionPageDocument) => boolean,
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' && filter(page) ? [{ page, depth }] : []),
...(page.type === 'document' ? [{ page, depth }] : []),
...page.pages.flatMap((child) =>
child.type === 'link' ? [] : flattenPage(child, depth + 1),
),
@@ -4,7 +4,7 @@ import { ImageResponse } from 'next/og';
import { NextRequest } from 'next/server';
import React from 'react';
import { getContentPointer } from '@/app/(space)/fetch';
import { getSiteContentPointer } from '@/app/(space)/fetch';
import {
getCollection,
getCurrentSiteCustomization,
@@ -42,19 +42,15 @@ export async function GET(req: NextRequest) {
const options = getOptions(req.url);
const size = SIZES[options.size];
const pointer = getContentPointer();
const pointer = getSiteContentPointer();
const spaceId = pointer.spaceId;
const [space, customization] = await Promise.all([
getSpace(spaceId, 'siteId' in pointer ? pointer.siteShareKey : undefined),
'siteId' in pointer ? getCurrentSiteCustomization(pointer) : getSpaceCustomization(spaceId),
getSpace(spaceId, pointer.siteShareKey),
getCurrentSiteCustomization(pointer),
]);
const parent =
'siteId' in pointer
? await getSite(pointer.organizationId, pointer.siteId)
: space.visibility === ContentVisibility.InCollection && space.parent
? await getCollection(space.parent)
: null;
const parent = await getSite(pointer.organizationId, pointer.siteId);
const contentTitle = getContentTitle(space, customization, parent);
return new ImageResponse(
@@ -11,7 +11,7 @@ import { Metadata } from 'next';
import { notFound } from 'next/navigation';
import * as React from 'react';
import { getContentPointer } from '@/app/(space)/fetch';
import { getSiteContentPointer } from '@/app/(space)/fetch';
import { DocumentView, createHighlightingContext } from '@/components/DocumentView';
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
import { PolymorphicComponentProp } from '@/components/utils/types';
@@ -39,15 +39,10 @@ const DEFAULT_LIMIT = 100;
export const runtime = 'edge';
export async function generateMetadata(): Promise<Metadata> {
const contentPointer = getContentPointer();
const contentPointer = getSiteContentPointer();
const [space, customization] = await Promise.all([
getSpace(
contentPointer.spaceId,
'siteId' in contentPointer ? contentPointer.siteShareKey : undefined,
),
'siteId' in contentPointer
? getCurrentSiteCustomization(contentPointer)
: getSpaceCustomization(contentPointer.spaceId),
getSpace(contentPointer.spaceId, contentPointer.siteShareKey),
getCurrentSiteCustomization(contentPointer),
]);
return {
@@ -60,7 +55,7 @@ export async function generateMetadata(): Promise<Metadata> {
* Render a space as a standalone HTML page that can be printed as a PDF.
*/
export default async function PDFHTMLOutput(props: { searchParams: { [key: string]: string } }) {
const contentPointer = getContentPointer();
const contentPointer = getSiteContentPointer();
const searchParams = new URLSearchParams(props.searchParams);
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams));
@@ -71,13 +66,8 @@ export default async function PDFHTMLOutput(props: { searchParams: { [key: strin
// Load the content,
const [customization, { space, contentTarget, pages: rootPages }] = await Promise.all([
'siteId' in contentPointer
? getCurrentSiteCustomization(contentPointer)
: getSpaceCustomization(contentPointer.spaceId),
getSpaceContentData(
contentPointer,
'siteId' in contentPointer ? contentPointer.siteShareKey : undefined,
),
getCurrentSiteCustomization(contentPointer),
getSpaceContentData(contentPointer),
]);
const language = getSpaceLanguage(customization);
@@ -175,7 +165,7 @@ export default async function PDFHTMLOutput(props: { searchParams: { [key: strin
space={space}
page={page}
refContext={{
siteContext: 'siteId' in contentPointer ? contentPointer : null,
siteContext: contentPointer,
space,
revisionId: contentTarget.revisionId,
pages: rootPages,
+50 -58
View File
@@ -4,15 +4,14 @@ import { headers } from 'next/headers';
import {
getCollectionSpaces,
getCollection,
ContentPointer,
getRevisionPageByPath,
getDocument,
getSpaceData,
ContentTarget,
SiteContentPointer,
getCurrentSiteData,
getSite,
getSiteSpaces,
getCurrentSiteCustomization,
} from '@/lib/api';
import { resolvePagePath, resolvePageId } from '@/lib/pages';
@@ -25,53 +24,48 @@ export interface PageIdParams {
}
/**
* Get the current content pointer from the params.
* Get the current site content pointer from the params.
*/
export function getContentPointer(): ContentPointer | SiteContentPointer {
export function getSiteContentPointer(): SiteContentPointer {
const headerSet = headers();
const spaceId = headerSet.get('x-gitbook-content-space');
if (!spaceId) {
throw new Error(
'getContentPointer is called outside the scope of a request processed by the middleware',
'getSiteContentPointer is called outside the scope of a request processed by the middleware',
);
}
const siteId = headerSet.get('x-gitbook-content-site');
if (siteId) {
const organizationId = headerSet.get('x-gitbook-content-organization');
const siteSpaceId = headerSet.get('x-gitbook-content-site-space');
const siteShareKey = headerSet.get('x-gitbook-content-site-share-key');
if (!organizationId) {
throw new Error('Missing site content headers');
}
const siteContent: SiteContentPointer = {
siteId,
spaceId,
siteSpaceId: siteSpaceId ?? undefined,
siteShareKey: siteShareKey ?? undefined,
organizationId,
revisionId: headerSet.get('x-gitbook-content-revision') ?? undefined,
changeRequestId: headerSet.get('x-gitbook-content-changerequest') ?? undefined,
};
return siteContent;
} else {
const content: ContentPointer = {
spaceId,
revisionId: headerSet.get('x-gitbook-content-revision') ?? undefined,
changeRequestId: headerSet.get('x-gitbook-content-changerequest') ?? undefined,
};
return content;
if (!siteId) {
throw new Error('Expected site content headers');
}
const organizationId = headerSet.get('x-gitbook-content-organization');
const siteSpaceId = headerSet.get('x-gitbook-content-site-space');
const siteShareKey = headerSet.get('x-gitbook-content-site-share-key');
if (!organizationId) {
throw new Error('Missing site content headers');
}
const siteContent: SiteContentPointer = {
siteId,
spaceId,
siteSpaceId: siteSpaceId ?? undefined,
siteShareKey: siteShareKey ?? undefined,
organizationId,
revisionId: headerSet.get('x-gitbook-content-revision') ?? undefined,
changeRequestId: headerSet.get('x-gitbook-content-changerequest') ?? undefined,
};
return siteContent;
}
/**
* Fetch all the data needed to render the space layout.
*/
export async function fetchSpaceData() {
const content = getContentPointer();
const content = getSiteContentPointer();
const siteShareKey = 'siteId' in content ? content.siteShareKey : undefined;
const siteShareKey = content.siteShareKey;
const [{ space, contentTarget, pages, customization, scripts }, parentSite] = await Promise.all(
'siteId' in content
@@ -87,11 +81,13 @@ export async function fetchSpaceData() {
);
const parent = await (parentSite ?? fetchParentCollection(space));
// we grab the space attached to the parent as it contains overriden customizations
const spaceRelativeToParent = parent?.spaces.find((space) => space.id === content.spaceId);
return {
content,
contentTarget,
space,
space: spaceRelativeToParent ?? space,
pages,
customization,
scripts,
@@ -105,21 +101,17 @@ export async function fetchSpaceData() {
* Optimized to fetch in parallel as much as possible.
*/
export async function fetchPageData(params: PagePathParams | PageIdParams) {
const content = getContentPointer();
const siteShareKey = 'siteId' in content ? content.siteShareKey : undefined;
const { space, contentTarget, pages, customization, scripts } = await ('siteId' in content
? getCurrentSiteData(content)
: getSpaceData(content, siteShareKey));
const content = getSiteContentPointer();
const { space, contentTarget, pages, customization, scripts } =
await getCurrentSiteData(content);
const page = await resolvePage(contentTarget, pages, params);
const [parent, document] = await Promise.all([
'siteId' in content
? fetchParentSite({
organizationId: content.organizationId,
siteId: content.siteId,
siteShareKey: content.siteShareKey,
})
: fetchParentCollection(space),
fetchParentSite({
organizationId: content.organizationId,
siteId: content.siteId,
siteShareKey: content.siteShareKey,
}),
page?.page.documentId ? getDocument(space.id, page.page.documentId) : null,
]);
@@ -178,32 +170,23 @@ async function resolvePage(
return undefined;
}
async function fetchParentCollection(space: Space) {
const parentCollectionId =
space.visibility === ContentVisibility.InCollection ? space.parent : undefined;
const [collection, spaces] = await Promise.all([
parentCollectionId ? getCollection(parentCollectionId) : null,
parentCollectionId ? getCollectionSpaces(parentCollectionId) : ([] as Space[]),
]);
return { parent: collection, spaces };
}
async function fetchParentSite(args: {
organizationId: string;
siteId: string;
siteShareKey: string | undefined;
}) {
const { organizationId, siteId, siteShareKey } = args;
const [site, siteSpaces] = await Promise.all([
const [site, siteSpaces, siteParentCustomizations] = await Promise.all([
getSite(organizationId, siteId),
getSiteSpaces({ organizationId, siteId, siteShareKey }),
getCurrentSiteCustomization({ organizationId, siteId, siteSpaceId: undefined }),
]);
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,
@@ -211,7 +194,16 @@ async function fetchParentSite(args: {
};
});
return { parent: site, spaces: Object.values(spaces) };
// override the title with the customization title
const parent = {
...site,
...(siteParentCustomizations?.title ? { title: siteParentCustomizations.title } : {}),
};
return {
parent,
spaces: Object.values(spaces),
};
}
/**
+37 -6
View File
@@ -8,12 +8,13 @@ import {
} from '@gitbook/api';
import { IconsProvider, IconStyle } from '@gitbook/icons';
import assertNever from 'assert-never';
import colorContrast from 'postcss-color-contrast/js';
import colors from 'tailwindcss/colors';
import { emojiFontClassName } from '@/components/primitives';
import { fonts, ibmPlexMono } from '@/fonts';
import { getSpaceLanguage } from '@/intl/server';
import { getCurrentSiteLayoutData, getSpaceLayoutData } from '@/lib/api';
import { getCurrentSiteLayoutData } from '@/lib/api';
import { getStaticFileURL } from '@/lib/assets';
import { hexToRgb, shadesOfColor } from '@/lib/colors';
import { tcls } from '@/lib/tailwind';
@@ -21,7 +22,7 @@ import { tcls } from '@/lib/tailwind';
import { ClientContexts } from './ClientContexts';
import './globals.css';
import '@gitbook/icons/style.css';
import { getContentPointer } from './fetch';
import { getSiteContentPointer } from './fetch';
/**
* Layout shared between the content and the PDF renderer.
@@ -30,10 +31,9 @@ import { getContentPointer } from './fetch';
export default async function SpaceRootLayout(props: { children: React.ReactNode }) {
const { children } = props;
const pointer = getContentPointer();
const { customization } = await ('siteId' in pointer
? getCurrentSiteLayoutData(pointer)
: getSpaceLayoutData(pointer.spaceId));
const pointer = getSiteContentPointer();
const { customization } = await getCurrentSiteLayoutData(pointer);
const headerTheme = generateHeaderTheme(customization);
const language = getSpaceLanguage(customization);
@@ -73,6 +73,21 @@ export default async function SpaceRootLayout(props: { children: React.ReactNode
'primary-color',
customization.styling.primaryColor.light,
)}
${
// Generate the right contrast color for each shade of primary-color
generateColorVariable(
'contrast-primary',
Object.fromEntries(
Object.entries(
shadesOfColor(customization.styling.primaryColor.light),
).map(([index, color]) => [
index,
colorContrast(color, ['#000', '#fff']),
]),
),
)
}
${generateColorVariable(
'primary-base',
customization.styling.primaryColor.light,
@@ -82,6 +97,7 @@ export default async function SpaceRootLayout(props: { children: React.ReactNode
headerTheme.backgroundColor.light,
)}
${generateColorVariable('header-link', headerTheme.linkColor.light)}
${generateColorVariable('header-button-text', colorContrast(headerTheme.linkColor.light as string, ['#000', '#fff']))}
}
.dark {
${generateColorVariable(
@@ -92,11 +108,26 @@ export default async function SpaceRootLayout(props: { children: React.ReactNode
'primary-base',
customization.styling.primaryColor.dark,
)}
${
// Generate the right contrast color for each shade of primary-color
generateColorVariable(
'contrast-primary',
Object.fromEntries(
Object.entries(
shadesOfColor(customization.styling.primaryColor.dark),
).map(([index, color]) => [
index,
colorContrast(color, ['#000', '#fff']),
]),
),
)
}
${generateColorVariable(
'header-background',
headerTheme.backgroundColor.dark,
)}
${generateColorVariable('header-link', headerTheme.linkColor.dark)}
${generateColorVariable('header-button-text', colorContrast(headerTheme.linkColor.dark as string, ['#000', '#fff']))}
}
`}</style>
</head>
@@ -1,11 +1,16 @@
import { Space } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import React from 'react';
import { ContentPointer, getChangeRequest, getRevision } from '@/lib/api';
import { SiteContentPointer, getChangeRequest, getRevision } from '@/lib/api';
import { tcls } from '@/lib/tailwind';
import { RefreshChangeRequestButton } from './RefreshChangeRequestButton';
import { Toolbar, ToolbarBody, ToolbarButton, ToolbarButtonGroups } from './Toolbar';
import { DateRelative } from '../primitives';
interface AdminToolbarProps {
content: ContentPointer;
content: SiteContentPointer;
space: Space;
}
@@ -67,9 +72,30 @@ async function ChangeRequestToolbar(props: { spaceId: string; changeRequestId: s
const changeRequest = await getChangeRequest(spaceId, changeRequestId);
return (
<ToolbarButton href={changeRequest.urls.app}>
Change request #{changeRequest.number}: {changeRequest.subject ?? 'No subject'}
</ToolbarButton>
<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>
<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>
);
}
@@ -77,37 +103,35 @@ async function RevisionToolbar(props: { spaceId: string; revisionId: string }) {
const { spaceId, revisionId } = props;
const revision = await getRevision(spaceId, revisionId, {
metadata: false,
metadata: true,
});
return (
<ToolbarButton href={revision.urls.app}>
Revision created on {new Date(revision.createdAt).toLocaleDateString()}
</ToolbarButton>
);
}
function ToolbarButton(props: { href: string; children: React.ReactNode }) {
const { href, children } = props;
return (
<a
href={href}
className={tcls(
'block',
'text-sm',
'px-4',
'py-1',
'rounded-full',
'hover:bg-dark-1',
'hover:text-white',
'truncate',
'text-light',
'dark:text-light',
'dark:hover:bg-dark-2',
)}
>
{children}
</a>
<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>
<ToolbarButton title="Open in application" href={revision.urls.app}>
<Icon icon="arrow-up-right-from-square" 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"
/>
</ToolbarButton>
) : null}
</ToolbarButtonGroups>
</Toolbar>
);
}
@@ -0,0 +1,70 @@
'use client';
import { Icon } from '@gitbook/icons';
import React from 'react';
import { useCheckForContentUpdate } from '@/components/AutoRefreshContent';
import { tcls } from '@/lib/tailwind';
import { ToolbarButton } from './Toolbar';
// We don't show the button if the content has been updated 30s ago or less.
const minInterval = 1000 * 30; // 5 minutes
/**
* Button to refresh the page if the content has been updated.
*/
export function RefreshChangeRequestButton(props: {
spaceId: string;
changeRequestId: string;
revisionId: string;
updatedAt: number;
}) {
const { updatedAt } = props;
const [visible, setVisible] = React.useState(false);
const [loading, setLoading] = React.useState(false);
const checkForUpdates = useCheckForContentUpdate(props);
const refresh = React.useCallback(async () => {
setLoading(true);
try {
await checkForUpdates();
} finally {
setLoading(false);
setVisible(false);
}
}, [checkForUpdates]);
// Show the button if the content has been updated more than 30s ago.
React.useEffect(() => {
if (updatedAt < Date.now() - minInterval) {
setVisible(true);
}
}, [updatedAt]);
// 30sec after being hidden, we show the button again
React.useEffect(() => {
if (!visible) {
const timeout = setTimeout(() => {
setVisible(true);
}, minInterval);
return () => clearTimeout(timeout);
}
}, [visible]);
if (!visible) {
return null;
}
return (
<ToolbarButton
title="Refresh"
onClick={(event) => {
event.preventDefault();
refresh();
}}
>
<Icon icon="rotate" className={tcls('size-4', loading ? 'animate-spin' : null)} />
</ToolbarButton>
);
}
@@ -0,0 +1,66 @@
'use client';
import * as React from 'react';
import { tcls } from '@/lib/tailwind';
export function Toolbar(props: { children: React.ReactNode }) {
const { children } = props;
return (
<div
className={tcls(
'flex',
'flex-row',
'items-center',
'gap-4',
'text-sm',
'px-4',
'py-1',
'rounded-full',
'truncate',
'text-light',
'dark:text-light',
)}
>
{children}
</div>
);
}
export function ToolbarBody(props: { children: React.ReactNode }) {
return <div className="flex flex-col gap-1">{props.children}</div>;
}
export function ToolbarButtonGroups(props: { children: React.ReactNode }) {
return <div className="flex flex-row gap-2">{props.children}</div>;
}
export function ToolbarButton(props: React.HTMLProps<HTMLAnchorElement>) {
const { children, ...rest } = props;
return (
<a
{...rest}
className={tcls(
'flex',
'flex-col',
'items-center',
'justify-center',
'size-11',
'gap-1',
'text-sm',
'rounded-full',
'hover:bg-dark-1',
'hover:text-white',
'truncate',
'text-light',
'dark:text-light',
'dark:hover:bg-dark-2',
'hover:shadow-lg',
'cursor-pointer',
)}
>
{children}
</a>
);
}
+35 -3
View File
@@ -2,6 +2,7 @@
import * as React from 'react';
import { t, useLanguage } from '@/intl/client';
import { ClassValue, tcls } from '@/lib/tailwind';
import { renderAd } from './renderAd';
@@ -78,7 +79,6 @@ export function Ad({
(async () => {
const result = await renderAd({
spaceId,
placement,
ignore: ignore || preview,
zoneId: realZoneId,
@@ -97,7 +97,7 @@ export function Ad({
return () => {
cancelled = true;
};
}, [visible, spaceId, zoneId, ignore, placement, mode]);
}, [visible, zoneId, ignore, placement, mode]);
const viaUrl = new URL('https://www.gitbook.com');
viaUrl.searchParams.set('utm_source', 'content');
@@ -106,7 +106,39 @@ export function Ad({
return (
<div ref={containerRef} className={tcls(style)}>
{ad ? ad : null}
{ad ? (
<>
{ad}
<AdSponsoredLink spaceId={spaceId} />
</>
) : null}
</div>
);
}
function AdSponsoredLink(props: { spaceId: string }) {
const { spaceId } = props;
const language = useLanguage();
const viaUrl = new URL('https://www.gitbook.com');
viaUrl.searchParams.set('utm_source', 'content');
viaUrl.searchParams.set('utm_medium', 'sponsoring');
viaUrl.searchParams.set('utm_campaign', spaceId);
return (
<p
className={tcls(
'mt-2',
'mr-2',
'text-xs',
'text-right',
'text-dark/5',
'dark:text-light/5',
)}
>
<a target="_blank" href={viaUrl.toString()} className={tcls('hover:underline')}>
{t(language, 'sponsored_via_gitbook')}
</a>
</p>
);
}
@@ -2,8 +2,6 @@
import { headers } from 'next/headers';
import { tcls } from '@/lib/tailwind';
import { AdClassicRendering } from './AdClassicRendering';
import { AdCoverRendering } from './AdCoverRendering';
import { AdPixels } from './AdPixels';
@@ -12,8 +10,6 @@ import { AdItem, AdsResponse } from './types';
interface FetchAdOptions {
/** ID of the zone to fetch Ads for */
zoneId: string;
/** ID of the space */
spaceId: string;
/** Mode to render the Ad */
mode: 'classic' | 'auto' | 'cover';
/** Name of the placement for the ad */
@@ -28,18 +24,13 @@ interface FetchAdOptions {
* and properly access user-agent and IP.
*/
export async function renderAd(options: FetchAdOptions) {
const { spaceId, mode } = options;
const { mode } = options;
const result = await fetchAd(options);
if (!result || !result.ad.description || !result.ad.statlink) {
return null;
}
const { ad, ip } = result;
const viaUrl = new URL('https://www.gitbook.com');
viaUrl.searchParams.set('utm_source', 'content');
viaUrl.searchParams.set('utm_medium', 'ads');
viaUrl.searchParams.set('utm_campaign', spaceId);
const { ad } = result;
return (
<>
@@ -49,21 +40,6 @@ export async function renderAd(options: FetchAdOptions) {
<AdCoverRendering ad={ad} />
)}
{ad.pixel ? <AdPixels rawPixel={ad.pixel} /> : null}
<p
className={tcls(
'mt-2',
'mr-2',
'text-xs',
'text-right',
'text-dark/5',
'dark:text-light/5',
)}
data-debug-ip={ip}
>
<a target="_blank" href={viaUrl.toString()} className={tcls('hover:underline')}>
Sponsored via GitBook
</a>
</p>
</>
);
}
@@ -0,0 +1 @@
export * from './useCheckForContentUpdate';
@@ -0,0 +1,15 @@
'use server';
import { getChangeRequest } from '@/lib/api';
/**
* Return true if a change-request has been updated.
*/
export async function hasContentBeenUpdated(props: {
spaceId: string;
changeRequestId: string;
revisionId: string;
}) {
const changeRequest = await getChangeRequest.revalidate(props.spaceId, props.changeRequestId);
return changeRequest.revision !== props.revisionId;
}
@@ -0,0 +1,24 @@
'use client';
import React from 'react';
import { hasContentBeenUpdated } from './server-actions';
/**
* Return a callback to check if a change request has been updated and to refresh the page if it has.
*/
export function useCheckForContentUpdate(props: {
spaceId: string;
changeRequestId: string;
revisionId: string;
}) {
const { spaceId, changeRequestId, revisionId } = props;
return React.useCallback(async () => {
const updated = await hasContentBeenUpdated({ spaceId, changeRequestId, revisionId });
if (updated) {
window.location.reload();
}
}, [spaceId, changeRequestId, revisionId]);
}
@@ -4,7 +4,7 @@ import { getSyncedBlockContent } from '@/lib/api';
import { resolveContentRefWithFiles } from '@/lib/references';
import { BlockProps } from './Block';
import { Blocks } from './Blocks';
import { Blocks, UnwrappedBlocks } from './Blocks';
export async function BlockSyncedBlock(props: BlockProps<DocumentBlockSyncedBlock>) {
const { block, ancestorBlocks, context, style } = props;
@@ -30,7 +30,7 @@ export async function BlockSyncedBlock(props: BlockProps<DocumentBlockSyncedBloc
}
return (
<Blocks
<UnwrappedBlocks
nodes={syncedBlock.document.nodes}
document={syncedBlock.document}
ancestorBlocks={[...ancestorBlocks, block]}
@@ -47,7 +47,6 @@ export async function BlockSyncedBlock(props: BlockProps<DocumentBlockSyncedBloc
return context.resolveContentRef(ref, options);
},
}}
style={style}
/>
);
}
@@ -5,47 +5,66 @@ import { tcls, ClassValue } from '@/lib/tailwind';
import { Block } from './Block';
import { DocumentContextProps } from './DocumentView';
export function Blocks<T extends DocumentBlock, Tag extends React.ElementType = 'div'>(
props: DocumentContextProps & {
/** Blocks to render */
nodes: T[];
/** Document being rendered */
document: JSONDocument;
/** Ancestors of the blocks */
ancestorBlocks: DocumentBlock[];
/** HTML tag to use */
/**
* Renders a list of blocks with a wrapper element.
*/
export function Blocks<TBlock extends DocumentBlock, Tag extends React.ElementType = 'div'>(
props: UnwrappedBlocksProps<TBlock> & {
/** HTML tag to use for the wrapper */
tag?: Tag;
/** Style passed to the wrapper */
style?: ClassValue;
/** Style passed to all blocks */
blockStyle?: ClassValue;
/** Props to pass to the wrapper element */
wrapperProps?: React.ComponentProps<Tag>;
},
) {
const { nodes, tag: Tag = 'div', style, blockStyle, ...contextProps } = props;
const { tag: Tag = 'div', style, wrapperProps, ...blocksProps } = props;
return (
<Tag className={tcls(style)}>
{nodes.map((node, index) => (
<Tag {...wrapperProps} className={tcls(style)}>
<UnwrappedBlocks {...blocksProps} />
</Tag>
);
}
type UnwrappedBlocksProps<TBlock extends DocumentBlock> = DocumentContextProps & {
/** Blocks to render */
nodes: TBlock[];
/** Document being rendered */
document: JSONDocument;
/** Ancestors of the blocks */
ancestorBlocks: DocumentBlock[];
/** Style passed to all blocks */
blockStyle?: ClassValue;
};
/**
* Renders a list of blocks without a wrapper element.
*/
export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBlocksProps<TBlock>) {
const { nodes, blockStyle, ...contextProps } = props;
return (
<>
{nodes.map((node) => (
<Block
key={node.key}
block={node}
style={[
'w-full mx-auto decoration-primary/6',
node.data && 'fullWidth' in node.data && node.data.fullWidth
? 'max-w-screen-xl'
: 'max-w-3xl',
'w-full',
'mx-auto',
'decoration-primary/6',
blockStyle,
]}
{...contextProps}
/>
))}
</Tag>
</>
);
}
@@ -1,6 +1,7 @@
import {
DocumentBlockDrawing,
DocumentBlockEmbed,
DocumentBlockFile,
DocumentBlockImage,
JSONDocument,
} from '@gitbook/api';
@@ -21,7 +22,7 @@ export function Caption(
style?: ClassValue;
fit?: boolean;
wrapperStyle?: ClassValue;
block: DocumentBlockImage | DocumentBlockDrawing | DocumentBlockEmbed;
block: DocumentBlockImage | DocumentBlockDrawing | DocumentBlockEmbed | DocumentBlockFile;
} & DocumentContextProps,
) {
const {
@@ -4,7 +4,7 @@ import Script from 'next/script';
import ReactDOM from 'react-dom';
import { Card } from '@/components/primitives';
import { api } from '@/lib/api';
import { getEmbedByUrlInSpace, getEmbedByUrl } from '@/lib/api';
import { tcls } from '@/lib/tailwind';
import { BlockProps } from './Block';
@@ -17,9 +17,9 @@ export async function Embed(props: BlockProps<gitbookAPI.DocumentBlockEmbed>) {
ReactDOM.preload('https://cdn.iframe.ly/embed.js', { as: 'script', nonce });
const { data: embed } = await (context.content
? api().spaces.getEmbedByUrlInSpace(context.content.spaceId, { url: block.data.url })
: api().urls.getEmbedByUrl({ url: block.data.url }));
const embed = await (context.content
? getEmbedByUrlInSpace(context.content.spaceId, block.data.url)
: getEmbedByUrl(block.data.url));
return (
<Caption {...props}>
@@ -4,10 +4,11 @@ import { getSimplifiedContentType } from '@/lib/files';
import { tcls } from '@/lib/tailwind';
import { BlockProps } from './Block';
import { Caption } from './Caption';
import { FileIcon } from './FileIcon';
export async function File(props: BlockProps<DocumentBlockFile>) {
const { block, context, style } = props;
const { block, context } = props;
const contentRef = await context.resolveContentRef(block.data.ref);
const file = contentRef?.file;
@@ -19,76 +20,65 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
const contentType = getSimplifiedContentType(file.contentType);
return (
<a
href={file.downloadURL}
download={file.name}
className={tcls(
'group/file',
'flex',
'flex-row',
'items-center',
'border',
'border-b-0',
'px-5',
'py-3',
'border-dark/3',
//all
'[&]:mt-[0px]',
//select first child
'[&:first-child]:mt-5',
'[&:first-child]:rounded-t-lg',
//select first in group
'[:not(&)_+&]:mt-5',
'[:not(&)_+&]:rounded-t-lg',
//select last in group
'[&:not(:has(+_&))]:mb-5',
'[&:not(:has(+_&))]:rounded-b-lg',
'[&:not(:has(+_&))]:border-b',
'hover:text-primary-600',
'dark:border-light/3',
'dark:hover:text-primary-300',
style,
)}
>
<div
<Caption {...props} wrapperStyle={[]}>
<a
href={file.downloadURL}
download={file.name}
className={tcls(
'min-w-14',
'mr-5',
'pr-5',
'group/file',
'flex',
'flex-col',
'flex-row',
'items-center',
'gap-1',
'border-r',
'border-dark/2',
'dark:border-light/2',
'border',
'px-5',
'py-3',
'border-dark/3',
'rounded-lg',
'hover:text-primary-600',
'dark:border-light/3',
'dark:hover:text-primary-300',
)}
>
<div>
<FileIcon
contentType={contentType}
className={tcls('size-5', 'text-primary')}
/>
</div>
<div
className={tcls(
'text-xs',
'text-dark-4/8',
'group-hover/file:text-dark',
'dark:text-light-4/7',
'dark:group-hover/file:text-light',
'min-w-14',
'mr-5',
'pr-5',
'flex',
'flex-col',
'items-center',
'gap-1',
'border-r',
'border-dark/2',
'dark:border-light/2',
)}
>
{getHumanFileSize(file.size)}
<div>
<FileIcon
contentType={contentType}
className={tcls('size-5', 'text-primary')}
/>
</div>
<div
className={tcls(
'text-xs',
'text-dark-4/8',
'group-hover/file:text-dark',
'dark:text-light-4/7',
'dark:group-hover/file:text-light',
)}
>
{getHumanFileSize(file.size)}
</div>
</div>
</div>
<div>
<div className={tcls('text-base')}>{file.name}</div>
<div className={tcls('text-sm', 'opacity-9', 'dark:opacity-8')}>{contentType}</div>
</div>
</a>
<div>
<div className={tcls('text-base')}>{file.name}</div>
<div className={tcls('text-sm', 'opacity-9', 'dark:opacity-8')}>
{contentType}
</div>
</div>
</a>
</Caption>
);
}
@@ -56,6 +56,7 @@ async function OpenAPIBody(props: BlockProps<DocumentBlockSwagger>) {
CodeBlock: PlainCodeBlock,
defaultInteractiveOpened: context.mode === 'print',
id: block.meta?.id,
blockKey: block.key,
}}
className="openapi-block"
/>
@@ -174,7 +174,8 @@
@apply prose-sm;
}
.openapi-schema-example {
.openapi-schema-example,
.openapi-schema-pattern {
@apply prose-sm mt-2 text-dark/10 dark:text-light/10;
}
@@ -1,4 +1,5 @@
import { ContentRef, DocumentTableViewCards } from '@gitbook/api';
import React from 'react';
import { Image } from '@/components/utils';
import { ClassValue, tcls } from '@/lib/tailwind';
@@ -12,7 +13,7 @@ export async function RecordCard(
record: TableRecordKV;
},
) {
const { view, record, context, isOffscreen } = props;
const { view, record, context, block, isOffscreen } = props;
const coverFile = view.coverDefinition
? getRecordValue<string[]>(record[1], view.coverDefinition)?.[0]
@@ -99,6 +100,31 @@ export async function RecordCard(
)}
>
{view.columns.map((column) => {
const definition = block.data.definition[column];
if (!definition) {
return null;
}
if (!view.hideColumnTitle && definition.title) {
const ariaLabelledBy = `${block.key}-${column}-title`;
return (
<div key={column} className="flex flex-col gap-1">
<div
id={ariaLabelledBy}
className="text-sm text-dark/8 dark:text-light/8"
>
{definition.title}
</div>
<RecordColumnValue
{...props}
column={column}
ariaLabelledBy={ariaLabelledBy}
/>
</div>
);
}
return <RecordColumnValue key={column} {...props} column={column} />;
})}
</div>
@@ -22,11 +22,12 @@ import { FileIcon } from '../FileIcon';
export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
props: BlockProps<DocumentBlockTable> & {
tag?: Tag;
ariaLabelledBy?: string;
record: TableRecordKV;
column: string;
},
) {
const { tag: Tag = 'div', block, document, record, column, context } = props;
const { tag: Tag = 'div', ariaLabelledBy, block, document, record, column, context } = props;
const definition = block.data.definition[column];
const value = record[1].values[column];
@@ -42,6 +43,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
className={tcls('w-5', 'h-5')}
checked={value as boolean}
disabled={true}
aria-labelledby={ariaLabelledBy}
/>
);
case 'rating':
@@ -67,7 +69,8 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
</span>
<span
role="meter"
aria-label={definition.title ?? ''}
aria-label={ariaLabelledBy ? undefined : (definition.title ?? '')}
aria-labelledby={ariaLabelledBy}
aria-valuenow={rating}
aria-valuemin={1}
aria-valuemax={definition.max}
@@ -89,6 +92,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
return (
<Tag
className={tcls('text-base', 'tabular-nums', 'tracking-tighter')}
aria-labelledby={ariaLabelledBy}
>{`${value}`}</Tag>
);
case 'text':
@@ -116,6 +120,9 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
]}
context={context}
blockStyle={['w-full', 'max-w-[unset]']}
wrapperProps={{
'aria-labelledby': ariaLabelledBy,
}}
/>
);
case 'files':
@@ -129,7 +136,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
);
return (
<Tag className={tcls('text-base')}>
<Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}>
{files.filter(filterOutNullable).map((ref, index) => {
const contentType = ref.file
? getSimplifiedContentType(ref.file.contentType)
@@ -178,7 +185,10 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
})
: null;
return (
<Tag className={tcls('text-base', 'text-balance', 'flex', 'items-center')}>
<Tag
className={tcls('text-base', 'text-balance', 'flex', 'items-center')}
aria-labelledby={ariaLabelledBy}
>
{resolved?.icon ?? null}
{resolved ? (
<StyledLink href={resolved.href}>{resolved.text}</StyledLink>
@@ -197,7 +207,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
);
return (
<Tag className={tcls('text-base')}>
<Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}>
{resolved.filter(filterOutNullable).map((file, index) => (
<StyledLink key={index} href={file.href}>
{file.text}
@@ -208,7 +218,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
}
case 'select': {
return (
<Tag className={tcls()}>
<Tag aria-labelledby={ariaLabelledBy}>
<span className={tcls('inline-flex', 'gap-2', 'flex-wrap')}>
{(value as string[]).map((selectId) => {
const option = definition.options.find(
@@ -1,23 +1,107 @@
'use client';
import React from 'react';
import { atom, selectorFamily, useRecoilValue, useSetRecoilState } from 'recoil';
import { useHash, useIsMounted } from '@/components/hooks';
import { ClassValue, tcls } from '@/lib/tailwind';
// How many titles are remembered:
const TITLES_MAX = 5;
export interface TabsItem {
id: string;
title: string;
}
// https://github.com/facebookexperimental/Recoil/issues/629#issuecomment-914273925
type SelectorMapper<Type> = {
[Property in keyof Type]: Type[Property];
};
type TabsInput = {
id: string;
tabs: SelectorMapper<TabsItem>[];
};
interface TabsState {
activeIds: {
[tabsBlockId: string]: string;
};
activeTitles: string[];
}
/**
* Client side component for the tabs, taking care of interactions.
*/
export function DynamicTabs(props: {
tabs: Array<{
id: string;
title: string;
children: React.ReactNode;
}>;
style: ClassValue;
}) {
const { tabs, style } = props;
export function DynamicTabs(
props: TabsInput & {
tabsBody: React.ReactNode[];
style: ClassValue;
},
) {
const { id, tabs, tabsBody, style } = props;
const [active, setActive] = React.useState<null | string>(tabs[0].id);
const hash = useHash();
const activeState = useRecoilValue(tabsActiveSelector({ id, tabs }));
// To avoid issue with hydration, we only use the state from recoil (which is loaded from localstorage),
// once the component has been mounted.
// Otherwise because of the streaming/suspense approach, tabs can be first-rendered at different time
// and get stuck into an inconsistent state.
const mounted = useIsMounted();
const active = mounted ? activeState : tabs[0];
const setTabsState = useSetRecoilState(tabsAtom);
/**
* When clicking to select a tab, we:
* - mark this specific ID as selected
* - store the ID to auto-select other tabs with the same title
*/
const onSelectTab = React.useCallback(
(tab: TabsItem) => {
setTabsState((prev) => ({
activeIds: {
...prev.activeIds,
[id]: tab.id,
},
activeTitles: tab.title
? prev.activeTitles
.filter((t) => t !== tab.title)
.concat([tab.title])
.slice(-TITLES_MAX)
: prev.activeTitles,
}));
},
[id, setTabsState],
);
/**
* When the hash changes, we try to select the tab containing the targetted element.
*/
React.useEffect(() => {
if (!hash) {
return;
}
const activeElement = document.getElementById(hash);
if (!activeElement) {
return;
}
const tabAncestor = activeElement.closest('[role="tabpanel"]');
if (!tabAncestor) {
return;
}
const tab = tabs.find((tab) => getTabPanelId(tab.id) === tabAncestor.id);
if (!tab) {
return;
}
onSelectTab(tab);
}, [hash, tabs, onSelectTab]);
return (
<div
@@ -52,11 +136,11 @@ export function DynamicTabs(props: {
<button
key={tab.id}
role="tab"
aria-selected={active === tab.id}
aria-controls={`tabpanel-${tab.id}`}
id={`tab-${tab.id}`}
aria-selected={active.id === tab.id}
aria-controls={getTabPanelId(tab.id)}
id={getTabButtonId(tab.id)}
onClick={() => {
setActive(tab.id);
onSelectTab(tab);
}}
className={tcls(
//prev from active-tab
@@ -102,7 +186,7 @@ export function DynamicTabs(props: {
'truncate',
'max-w-full',
active === tab.id
active.id === tab.id
? [
'shrink-0',
'active-tab',
@@ -121,17 +205,97 @@ export function DynamicTabs(props: {
</button>
))}
</div>
{tabs.map((tab) => (
{tabs.map((tab, index) => (
<div
key={tab.id}
role="tabpanel"
id={`tabpanel-${tab.id}`}
aria-labelledby={`tab-${tab.id}`}
className={tcls('p-4', tab.id !== active ? 'hidden' : null)}
id={getTabPanelId(tab.id)}
aria-labelledby={getTabButtonId(tab.id)}
className={tcls('p-4', tab.id !== active.id ? 'hidden' : null)}
>
{tab.children}
{tabsBody[index]}
</div>
))}
</div>
);
}
const tabsAtom = atom<TabsState>({
key: 'tabsAtom',
default: {
activeIds: {},
activeTitles: [],
},
effects: [
// Persist the state to local storage
({ trigger, setSelf, onSet }) => {
if (typeof localStorage === 'undefined') {
return;
}
const localStorageKey = '@gitbook/tabsState';
if (trigger === 'get') {
const stored = localStorage.getItem(localStorageKey);
if (stored) {
setSelf(JSON.parse(stored));
}
}
onSet((newState) => {
localStorage.setItem(localStorageKey, JSON.stringify(newState));
});
},
],
});
const tabsActiveSelector = selectorFamily<TabsItem, SelectorMapper<TabsInput>>({
key: 'tabsActiveSelector',
get:
(input) =>
({ get }) => {
const state = get(tabsAtom);
return getTabBySelection(input, state) ?? getTabByTitle(input, state) ?? input.tabs[0];
},
});
/**
* Get the ID for a tab button.
*/
function getTabButtonId(tabId: string) {
return `tab-${tabId}`;
}
/**
* Get the ID for a tab panel.
* We use the ID of the tab itself as links can be pointing to this ID.
*/
function getTabPanelId(tabId: string) {
return tabId;
}
/**
* Get explicitly selected tab in a set of tabs.
*/
function getTabBySelection(input: TabsInput, state: TabsState): TabsItem | null {
const activeId = state.activeIds[input.id];
return activeId ? (input.tabs.find((child) => child.id === activeId) ?? null) : null;
}
/**
* Get the best selected tab in a set of tabs by taking only title into account.
*/
function getTabByTitle(input: TabsInput, state: TabsState): TabsItem | null {
return (
input.tabs
.map((item) => {
return {
item,
score: state.activeTitles.indexOf(item.title),
};
})
.filter(({ score }) => score >= 0)
// .sortBy(({ score }) => -score)
.sort(({ score: a }, { score: b }) => b - a)
.map(({ item }) => item)[0] ?? null
);
}
@@ -2,17 +2,23 @@ import { DocumentBlockTabs } from '@gitbook/api';
import { tcls } from '@/lib/tailwind';
import { DynamicTabs } from './DynamicTabs';
import { DynamicTabs, TabsItem } from './DynamicTabs';
import { BlockProps } from '../Block';
import { Blocks } from '../Blocks';
export function Tabs(props: BlockProps<DocumentBlockTabs>) {
const { block, ancestorBlocks, document, style, context } = props;
const tabs = block.nodes.map((tab, index) => ({
id: tab.key!,
title: tab.data.title ?? '',
children: (
const tabs: TabsItem[] = [];
const tabsBody: React.ReactNode[] = [];
block.nodes.forEach((tab, index) => {
tabs.push({
id: tab.meta?.id ?? tab.key!,
title: tab.data.title ?? '',
});
tabsBody.push(
<Blocks
nodes={tab.nodes}
document={document}
@@ -20,20 +26,26 @@ export function Tabs(props: BlockProps<DocumentBlockTabs>) {
context={context}
blockStyle={tcls('flip-heading-hash')}
style={tcls('w-full', 'space-y-4')}
/>
),
}));
/>,
);
});
if (context.mode === 'print') {
// When printing, we display the tab, one after the other
return (
<>
{tabs.map((tab) => (
<DynamicTabs key={tab.id} tabs={[tab]} style={style} />
{tabs.map((tab, index) => (
<DynamicTabs
key={tab.id}
id={block.key!}
tabs={[tab]}
tabsBody={[tabsBody[index]]}
style={style}
/>
))}
</>
);
}
return <DynamicTabs tabs={tabs} style={style} />;
return <DynamicTabs id={block.key!} tabs={tabs} tabsBody={tabsBody} style={style} />;
}
@@ -20,15 +20,13 @@ import { SearchButton } from '../Search';
*/
export function CompactHeader(props: {
space: Space;
parent: Site | Collection | null;
parent: Site;
spaces: Space[];
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { space, spaces, parent, customization } = props;
const isMultiVariants =
parent?.object === 'collection' ||
(parent && parent.object === 'site' && spaces.length > 1);
const isMultiVariants = parent.object === 'site' && spaces.length > 1;
return (
<div
@@ -25,7 +25,7 @@ export function Dropdown<E extends HTMLElement>(props: {
const dropdownId = useId();
return (
<div className={tcls('group/dropdown', 'relative')}>
<div className={tcls('group/dropdown', 'relative flex')}>
{button({
id: dropdownId,
tabIndex: 0,
@@ -24,7 +24,7 @@ import { SearchButton } from '../Search';
*/
export function Header(props: {
space: Space;
parent: Site | Collection | null;
parent: Site;
spaces: Space[];
context: ContentRefContext;
customization: CustomizationSettings | SiteCustomizationSettings;
@@ -34,9 +34,7 @@ export function Header(props: {
const isCustomizationDefault =
customization.header.preset === CustomizationHeaderPreset.Default;
const isMultiVariants =
parent?.object === 'collection' ||
(parent && parent.object === 'site' && spaces.length > 1);
const isMultiVariants = parent.object === 'site' && spaces.length > 1;
return (
<header
@@ -95,6 +93,7 @@ export function Header(props: {
label={t(getSpaceLanguage(customization), 'more')}
links={customization.header.links}
context={context}
customization={customization}
/>
</HeaderLinks>
<div
@@ -5,6 +5,7 @@ import {
CustomizationHeaderPreset,
SiteCustomizationSettings,
} from '@gitbook/api';
import assertNever from 'assert-never';
import { ContentRefContext, resolveContentRef } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
@@ -16,56 +17,95 @@ import {
DropdownMenu,
DropdownMenuItem,
} from './Dropdown';
import { Link } from '../primitives';
import { Button, Link } from '../primitives';
// @TODO Remove it once we have the proper types in API
type CustomizationHeaderLinkWithStyle = CustomizationHeaderLink & {
style?: 'link' | 'button-primary' | 'button-secondary';
};
export async function HeaderLink(props: {
context: ContentRefContext;
link: CustomizationHeaderLink;
link: CustomizationHeaderLinkWithStyle;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { context, link, customization } = props;
const isCustomizationCustom = customization.header.preset === CustomizationHeaderPreset.Custom;
const isCustomizationDefault =
customization.header.preset === CustomizationHeaderPreset.Default;
const target = await resolveContentRef(link.to, context);
if (!target) {
return null;
}
const renderLink = (linkProps: DropdownButtonProps<HTMLAnchorElement>) => (
<Link
{...linkProps}
href={target.href}
className={tcls(
'overflow-hidden',
'text-sm',
'flex',
'flex-row',
'items-center',
'whitespace-nowrap',
'lg:text-base',
const headerPreset = customization.header.preset;
!isCustomizationDefault
? ['text-header-link-500']
: ['text-dark/8', 'dark:text-light/8', 'dark:hover:text-light'],
target.active
? [
isCustomizationCustom
? ['shadow-header-link-500/7']
: ['shadow-dark/6', 'dark:shadow-light/7'],
]
: ['hover:text-header-link-400'],
)}
>
<span className={tcls('truncate')}> {link.title}</span>
const renderLink = (linkProps: DropdownButtonProps<HTMLAnchorElement>) => {
const linkStyle = link.style ?? 'link';
{link.links && link.links.length > 0 ? <DropdownChevron /> : null}
</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}
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(
'dark:bg-transparent dark:hover:bg-transparent',
'ring-header-link-500 hover:ring-header-link-300 dark:ring-header-link-500 dark:hover:ring-header-link-300 text-header-link-500 dark:text-header-link-500',
),
}[linkStyle],
)}
>
{link.title}
</Button>
);
}
case 'link': {
return (
<Link
{...linkProps}
href={target.href}
className={tcls(
'overflow-hidden',
'text-sm lg:text-base',
'flex flex-row items-center',
'whitespace-nowrap',
'hover:text-header-link-400 dark:hover:text-light',
headerPreset === CustomizationHeaderPreset.Default
? ['text-dark/8', 'dark:text-light/8']
: ['text-header-link-500 hover:text-header-link-400'],
)}
>
<span className={tcls('truncate')}>{link.title}</span>
{link.links && link.links.length > 0 ? <DropdownChevron /> : null}
</Link>
);
}
default:
assertNever(linkStyle);
}
};
if (link.links && link.links.length > 0) {
return (
@@ -1,9 +1,16 @@
import { CustomizationHeaderLink } from '@gitbook/api';
import {
CustomizationHeaderLink,
CustomizationHeaderPreset,
CustomizationSettings,
SiteCustomizationSettings,
} from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import React from 'react';
import { ContentRefContext, resolveContentRef } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
import { Dropdown, DropdownChevron, DropdownMenu, DropdownMenuItem } from './Dropdown';
import { Dropdown, DropdownMenu, DropdownMenuItem } from './Dropdown';
import styles from './headerLinks.module.css';
/**
@@ -13,13 +20,25 @@ export function HeaderLinkMore(props: {
label: React.ReactNode;
links: CustomizationHeaderLink[];
context: ContentRefContext;
customization: CustomizationSettings | SiteCustomizationSettings;
}) {
const { label, links, context } = props;
const { label, links, context, customization } = props;
const isCustomizationDefault =
customization.header.preset === CustomizationHeaderPreset.Default;
const renderButton = () => (
<button className="px-1">
<button
className={tcls(
'px-1',
!isCustomizationDefault
? ['text-header-link-500']
: ['text-dark/8', 'dark:text-light/8', 'dark:hover:text-light'],
'hover:text-header-link-400',
)}
>
<span className="sr-only">{label}</span>
<DropdownChevron />
<Icon icon="ellipsis" className={tcls('opacity-6', 'size-3', 'ms-1')} />
</button>
);
@@ -10,21 +10,13 @@ interface HeaderLinksProps {
export async function HeaderLinks({ children }: HeaderLinksProps) {
return (
<div className={tcls('w-full', 'h-full', 'inline-flex', 'tracking-[-0.02em]')}>
<div
className={`${styles.containerHeaderlinks} ${tcls(
'flex',
'w-full',
'h-full',
'justify-end',
'gap-x-2.5',
'mr-2.5',
'lg:gap-x-5',
'*:max-w-56',
)}`}
>
{children}
</div>
<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',
)}
>
{children}
</div>
);
}
@@ -17,7 +17,7 @@ import { Link } from '../primitives';
import { SpaceIcon } from '../Space/SpaceIcon';
interface HeaderLogoProps {
parent: Site | Collection | null;
parent: Site;
space: Space;
customization: CustomizationSettings | SiteCustomizationSettings;
}
@@ -85,9 +85,7 @@ export function HeaderLogo(props: HeaderLogoProps) {
)}
/>
) : (
<>
<LogoFallback {...props} />
</>
<LogoFallback {...props} />
)}
</Link>
</div>
@@ -98,6 +96,7 @@ function LogoFallback(props: HeaderLogoProps) {
const { parent, space, customization } = props;
const customIcon = 'icon' in customization.favicon ? customization.favicon.icon : undefined;
const customEmoji = 'emoji' in customization.favicon ? customization.favicon.emoji : undefined;
return (
<>
<SpaceIcon
@@ -63,6 +63,7 @@ export function HeaderMobileMenu(props: Partial<React.ButtonHTMLAttributes<HTMLB
'dark:hover:bg-light/2',
'rounded',
'straight-corners:rounded-sm',
'page-no-toc:hidden',
props.className,
)}
>
@@ -3,9 +3,6 @@
container-name: headerlinks;
}
.containerHeaderlinks > * {
display: flex;
}
.linkEllipsis {
display: none;
& div > a {
@@ -79,8 +76,3 @@
}
}
}
@container headerlinks ( width > 900px ) {
.containerHeaderlinks > *:not(.linkEllipsis) {
display: flex;
}
}
@@ -9,7 +9,7 @@ import React from 'react';
import { getSpaceLanguage } from '@/intl/server';
import { t } from '@/intl/translate';
import { ContentPointer, ContentTarget, SiteContentPointer, api } from '@/lib/api';
import { ContentTarget, SiteContentPointer, api } from '@/lib/api';
import { hasFullWidthBlock, isNodeEmpty } from '@/lib/document';
import { ContentRefContext, resolveContentRef } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
@@ -19,6 +19,7 @@ import { PageBodyBlankslate } from './PageBodyBlankslate';
import { PageCover } from './PageCover';
import { PageFooterNavigation } from './PageFooterNavigation';
import { PageHeader } from './PageHeader';
import { PreservePageLayout } from './PreservePageLayout';
import { TrackPageView } from './TrackPageView';
import { DocumentView, createHighlightingContext } from '../DocumentView';
import { PageFeedbackForm } from '../PageFeedback';
@@ -26,7 +27,7 @@ import { DateRelative } from '../primitives';
export function PageBody(props: {
space: Space;
contentPointer: ContentPointer | SiteContentPointer;
contentPointer: SiteContentPointer;
contentTarget: ContentTarget;
customization: CustomizationSettings | SiteCustomizationSettings;
page: RevisionPageDocument;
@@ -49,10 +50,6 @@ export function PageBody(props: {
const language = getSpaceLanguage(customization);
const updatedAt = page.updatedAt ?? page.createdAt;
const shouldHighlightCode = createHighlightingContext();
const sitePointer =
'siteId' in contentPointer
? { organizationId: contentPointer.organizationId, siteId: contentPointer.siteId }
: undefined;
return (
<>
@@ -78,6 +75,7 @@ export function PageBody(props: {
(!page.layout.tableOfContents ? ' page-no-toc' : '')
}
>
<PreservePageLayout asFullWidth={asFullWidth} />
{page.cover && page.layout.cover && page.layout.coverSize === 'hero' ? (
<PageCover as="hero" page={page} cover={page.cover} context={context} />
) : null}
@@ -144,7 +142,7 @@ export function PageBody(props: {
</main>
{shouldTrackPageViews() ? (
<TrackPageView
sitePointer={sitePointer}
sitePointer={contentPointer}
spaceId={space.id}
pageId={page.id}
apiHost={api().endpoint}
@@ -17,7 +17,8 @@ export async function PageBodyBlankslate(props: {
}) {
const { page, rootPages, context } = props;
if (!page.pages.length) {
const pages = page.pages.filter((child) => (child.type === 'document' ? !child.hidden : true));
if (!pages.length) {
return null;
}
@@ -34,7 +35,7 @@ export async function PageBodyBlankslate(props: {
)}
>
{await Promise.all(
page.pages.map(async (child) => {
pages.map(async (child) => {
const icon = (
<PageIcon
page={child}

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