mirror of
https://github.com/GitbookIO/gitbook.git
synced 2026-09-12 14:00:28 +00:00
Compare commits
525 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d1bd02a6f5 | |||
| 24cd72e088 | |||
| 47f7558c38 | |||
| de747b7b33 | |||
| 8e8b73fbd9 | |||
| e966e33e8f | |||
| bd0ca5babd | |||
| f6bacea1ae | |||
| ba2a523722 | |||
| 57adb3e54a | |||
| 7377928c8a | |||
| 5f8a8fe9b1 | |||
| 29a0bf25c4 | |||
| 92bb016576 | |||
| c8810ea002 | |||
| aa8bbaddc4 | |||
| b8c136e9c0 | |||
| 46d54172b0 | |||
| 68dc2de190 | |||
| 81b372f372 | |||
| 966e520640 | |||
| 12702930ec | |||
| 6ce57bcda1 | |||
| d99b453bc4 | |||
| aaf5793cb7 | |||
| 9b1762d2ab | |||
| 8d38d000fd | |||
| 4cf9cdd56d | |||
| 39406bbf54 | |||
| 9c5c1e5b68 | |||
| 6929b0b98b | |||
| 7c26d491b1 | |||
| 97035a054a | |||
| db45c6d773 | |||
| e3f5f81e62 | |||
| f5df40e17d | |||
| e13c76efed | |||
| 4a11d8d9eb | |||
| 009ed8cc6e | |||
| 106cbbd987 | |||
| 56e5c3c3f8 | |||
| 1dc3234003 | |||
| 22dc0d4ff5 | |||
| 3a4caf062c | |||
| 8ad0657159 | |||
| d8a4ecd0c6 | |||
| 65c7968438 | |||
| 3914f11150 | |||
| d363908297 | |||
| 414556ac7a | |||
| c768e9a90a | |||
| 553f1f228f | |||
| 30986528a7 | |||
| c70c2ddad8 | |||
| cf74d00758 | |||
| c2256bfd14 | |||
| 5d73a0f062 | |||
| 8f5f6c61f8 | |||
| 9a86965ba1 | |||
| c8d5f825fc | |||
| 5db3cbc2ce | |||
| f8d148bec4 | |||
| 198dd9f158 | |||
| 2b63bc158a | |||
| 4a8097d968 | |||
| f1440ca7ef | |||
| 7ef2eeed13 | |||
| 4005895337 | |||
| bf450e5cc7 | |||
| 4c12722c0a | |||
| ac124a7ea5 | |||
| 1de25056fa | |||
| bf3d2032ab | |||
| bfb2342ab3 | |||
| 76cbc3c10f | |||
| c80c76d50d | |||
| 263c89391e | |||
| ebf742e81a | |||
| 685317f508 | |||
| 0c224861e3 | |||
| a007604ab1 | |||
| 3076e96061 | |||
| a3741dd65f | |||
| 07085a5b89 | |||
| 36600bc0c7 | |||
| 5b7488b066 | |||
| c1ef7f2782 | |||
| f26ab0cf80 | |||
| 7c570a008e | |||
| 1d71d85ed7 | |||
| 4f728c0137 | |||
| 844a3e1845 | |||
| 3144b2fec1 | |||
| 5805c24255 | |||
| d0ef225ea3 | |||
| 5f1d82cb5a | |||
| 0894a740ff | |||
| 14012d92f9 | |||
| 4be6eada62 | |||
| 0ddbe5c0ee | |||
| 3a7864d731 | |||
| 73d806a796 | |||
| d40568c8f4 | |||
| a6789513dc | |||
| ee7a74fe43 | |||
| 0d99906774 | |||
| d3f9131af4 | |||
| 30bae7c877 | |||
| 0c99a57b3c | |||
| ad9e8f2232 | |||
| 4c286b503c | |||
| c5a28f884a | |||
| 2ed5445af8 | |||
| 755291d1b7 | |||
| 7421d1c6c3 | |||
| ff773233dd | |||
| 44983f8495 | |||
| 435ccb10ce | |||
| ef8eb72364 | |||
| 2a28f28421 | |||
| be45f23cc8 | |||
| fff6dce8fc | |||
| cfcfbdf16c | |||
| b029b1e23d | |||
| 1dc81fc56a | |||
| 31799038dd | |||
| db4ecbc747 | |||
| 0ad7bf561e | |||
| dc2d50e455 | |||
| 10fc27ba4e | |||
| 2e6e96728c | |||
| e1de340fc5 | |||
| fc9238498d | |||
| 2420f9b730 | |||
| d12aad6867 | |||
| 37be6f3164 | |||
| 4f039ecb2b | |||
| 71e993d0ca | |||
| 6695de7b79 | |||
| cf958bacd1 | |||
| 85a32fda4f | |||
| 706aa42a6e | |||
| 4dcca8b3ec | |||
| d0b92dd408 | |||
| 718452728f | |||
| 9b6d34bdbc | |||
| 3c96bf84b5 | |||
| cc4a86cc23 | |||
| c87197bb98 | |||
| 69dcf75083 | |||
| 66dcaf850f | |||
| 5f70ed73b9 | |||
| bda3080b94 | |||
| 9f5c68acfe | |||
| df92c72164 | |||
| a27fa68ae6 | |||
| 9e8cde48d4 | |||
| 9f75929269 | |||
| 5c7c17fe02 | |||
| 66506143ef | |||
| 50346135f9 | |||
| f98146f5b6 | |||
| 88a7ab21a2 | |||
| a4099dff9e | |||
| 98f91d9e82 | |||
| 4c2625c277 | |||
| 77b6228677 | |||
| ff93689d4e | |||
| d8ffa5d69c | |||
| f77b2b6cd7 | |||
| 5dec1a1f0e | |||
| e462ac837e | |||
| a21673e4c1 | |||
| c6537422a4 | |||
| 654a9e6227 | |||
| 80d45c3ff7 | |||
| 8c75bd364b | |||
| 06b94d4525 | |||
| e5a9d16d7e | |||
| d0eebceacf | |||
| ee3221885c | |||
| 76dbf0f0d3 | |||
| fc11ffdc8b | |||
| 9f83b0e783 | |||
| b0a9361cbd | |||
| e34b923e4a | |||
| cf4b1249a9 | |||
| 221d85cc4d | |||
| 658eb4d13f | |||
| 3725239e92 | |||
| bdbd14c560 | |||
| 0da4e9a926 | |||
| 1eb4bff09b | |||
| 147719c19b | |||
| c13f676ea8 | |||
| d326822b9d | |||
| 111ec45357 | |||
| e39e1db484 | |||
| 6849df49ec | |||
| a697dc4fcd | |||
| a8d15555c8 | |||
| 7d53a2c849 | |||
| 270f8b55a5 | |||
| 56a9d5601b | |||
| ea7ff33f3a | |||
| 642e33444a | |||
| 0e858b1a43 | |||
| 510a6f39d7 | |||
| f9e3835c2f | |||
| 5a5b4bb93c | |||
| 55d1e538d9 | |||
| 7d04336b5f | |||
| 79f420eb8e | |||
| 2742d961ee | |||
| f41b0c7ba1 | |||
| 77527f0a4e | |||
| 9436549510 | |||
| 76d6a2009e | |||
| 46c3ec6699 | |||
| 203e9103de | |||
| d22944419f | |||
| a9f9f18e66 | |||
| fdaf722ba1 | |||
| 6c64841325 | |||
| 44f4afdf94 | |||
| a22bb55715 | |||
| 44945f887a | |||
| cf20c5ff3b | |||
| c8935c62c8 | |||
| 1e1d202b5a | |||
| d304c853fb | |||
| 7278d7868d | |||
| cb91fb9df8 | |||
| 826ddbc533 | |||
| 10375bae51 | |||
| f26e856170 | |||
| 2df5d68eae | |||
| 70c6c9df42 | |||
| 8eb2850bdd | |||
| 887e99c8ed | |||
| 46b3e461dd | |||
| 76ba5d043e | |||
| 5e12c0a9be | |||
| 7ed89fe0fe | |||
| a3af78031f | |||
| 05de8109bb | |||
| 41278bad68 | |||
| 884f5aabb0 | |||
| eea1323c17 | |||
| 341264e879 | |||
| 345a2ea964 | |||
| 56143277b7 | |||
| aeeb9b0305 | |||
| 64bb5ebf5a | |||
| 98d44f01c7 | |||
| 1fc9f17f76 | |||
| 9a25c8c19c | |||
| 09de40002a | |||
| a2d967e98e | |||
| 258ef413b1 | |||
| cf1f281119 | |||
| 773fa50d41 | |||
| b0725eb852 | |||
| 6bd6ddd031 | |||
| 9b285625d9 | |||
| 8c0970d3d9 | |||
| 1ad9bfd6f3 | |||
| 1a37b17a68 | |||
| c5455d4498 | |||
| a82c548f42 | |||
| eead1dba66 | |||
| a7d4896484 | |||
| fa734fb217 | |||
| 46a1b58d01 | |||
| 12520ccede | |||
| ebdec4966b | |||
| 0b620640fa | |||
| 06fb56edc7 | |||
| 49a1561801 | |||
| b2acfab7c0 | |||
| cf193f1738 | |||
| 6edd2648a4 | |||
| ec1769fc32 | |||
| e9432c9486 | |||
| c3d9e85823 | |||
| 3e2327c707 | |||
| f2e5ad97ab | |||
| 45dd16b146 | |||
| 9e5f717fbe | |||
| be46c5db4b | |||
| 97dafa5580 | |||
| f62656ed9f | |||
| 46a3543a5e | |||
| 2470a40531 | |||
| 34e339b5e4 | |||
| dfb8d4e8d4 | |||
| 4826c9e012 | |||
| 6441f8a05e | |||
| 6cab31faf6 | |||
| 1c0ea074b3 | |||
| caa74cf48f | |||
| c829555f1b | |||
| 53299ce829 | |||
| 260305759d | |||
| b5e6673976 | |||
| e5fc5c2d2a | |||
| a8379be4c1 | |||
| 75876474a2 | |||
| f8fde8cec8 | |||
| 4bbd86aeca | |||
| aeab122d54 | |||
| 85ec1884e6 | |||
| 86a436645a | |||
| 0096947c72 | |||
| ee35796576 | |||
| 7045675eda | |||
| 730b444403 | |||
| d4e3c6d597 | |||
| f1f91a6816 | |||
| b5986e833a | |||
| eabc46b86e | |||
| aec74d68fd | |||
| 22a68a71c4 | |||
| 9d9040f24e | |||
| 613d67c14e | |||
| 5f7b29bbc8 | |||
| 756b5a766f | |||
| 29f2177357 | |||
| 0e4ba13065 | |||
| 05f206a7a5 | |||
| e660432227 | |||
| 56b8b86f58 | |||
| da215347f4 | |||
| ec075af455 | |||
| 1f7530aaf8 | |||
| 8c44653292 | |||
| a6f7a71af9 | |||
| b16636c180 | |||
| 64a9e27ca7 | |||
| 3c44eb4f80 | |||
| 6e5208d3ae | |||
| 3c2dbb7b10 | |||
| 59a8e74e39 | |||
| 2a1e491fee | |||
| 7d60c75dd8 | |||
| f4ac246a09 | |||
| e7c184cc99 | |||
| 28be5aaeca | |||
| 5f6ca7af56 | |||
| 46a726f3a8 | |||
| a1fca33947 | |||
| ccfcaa590b | |||
| 87e67866a4 | |||
| 0c80f96579 | |||
| 22eeaca92c | |||
| 66ba1c244f | |||
| 0668d8a287 | |||
| 2fdf3e3838 | |||
| 1c2d68c518 | |||
| c8358feeeb | |||
| 6cf73e4962 | |||
| 67b20138dd | |||
| 83f4cb5968 | |||
| 24f5e73bbe | |||
| 1fde857aee | |||
| 4d38479a0f | |||
| db4d4a3408 | |||
| 7267398d5b | |||
| 2d4c9880fd | |||
| 231654e43b | |||
| bfdf6640c8 | |||
| 528a06c65a | |||
| f7cb622863 | |||
| 6f6dde1aa4 | |||
| 3188795a52 | |||
| e681aa6ba1 | |||
| 215c724a9b | |||
| c1d3f990f1 | |||
| 6a62f42521 | |||
| e81d65dc2e | |||
| c5f75116d3 | |||
| c18ec51a4a | |||
| 5f690af5fb | |||
| fbc2ae10a0 | |||
| ca3ab044c3 | |||
| 2888b95b36 | |||
| b11566dfb1 | |||
| be198045b1 | |||
| 720c2ca909 | |||
| c935700672 | |||
| e04d03c696 | |||
| 4f84011f6b | |||
| 93aa1cfabf | |||
| 522eaa4319 | |||
| 772d120e3a | |||
| bfe91f71f9 | |||
| e903bb7752 | |||
| 196e8bcfc0 | |||
| eb8baffcf8 | |||
| f3ecb69404 | |||
| 86fe37f968 | |||
| 953c6bd194 | |||
| fc68dbdd4e | |||
| 705ea6c997 | |||
| 13b9f6b07f | |||
| afcb0ecba6 | |||
| 046e74b4a8 | |||
| 4dfb7c1e61 | |||
| 594a1d18a7 | |||
| 909a6e76f5 | |||
| 5103686d7f | |||
| dae7f704fa | |||
| 87c38f9091 | |||
| ece7f421b4 | |||
| 7a87cc1bb1 | |||
| 2001e4dba5 | |||
| f13e6cb55b | |||
| fff0ea8c34 | |||
| ee0b3c2032 | |||
| a4ae7140f2 | |||
| 7cdf04d2da | |||
| 9138b18a68 | |||
| 632ac7bbab | |||
| ff8a343a54 | |||
| b7a4721d66 | |||
| 9e0aabc8bd | |||
| 860bc02aa8 | |||
| e880bce80b | |||
| eea8aa306e | |||
| cf925fd21c | |||
| 0d15b052ab | |||
| 5761b1914a | |||
| d38752433f | |||
| 8e5b28d2e0 | |||
| ba0d38c220 | |||
| 5d236c138a | |||
| bc6244bb58 | |||
| 0cdb5fdf61 | |||
| 78f2469a53 | |||
| c0f7ccfe3f | |||
| 28915e906f | |||
| 92451dba91 | |||
| 02715436e7 | |||
| b8af0cb4af | |||
| b2b2a8c23c | |||
| 808f10d428 | |||
| ee0d45fa8b | |||
| 315954dffc | |||
| bb8b039c1a | |||
| fbd17713fe | |||
| 2a03461a21 | |||
| 84fd934fe1 | |||
| aab7d0bd7a | |||
| a4ec3c8c53 | |||
| 88795e35d9 | |||
| 2fe11a35d4 | |||
| 257f7cd62a | |||
| 462b2b6e65 | |||
| 77f769c9c2 | |||
| df2e267fb2 | |||
| 55b29ca608 | |||
| 61718847b0 | |||
| 1d44267958 | |||
| f190139d5d | |||
| cf54430651 | |||
| d786e1332f | |||
| 9ed5dc490e | |||
| 926fa0f52c | |||
| 0eab4389a4 | |||
| a7c323a023 | |||
| e5d94dbd23 | |||
| 288e5db8dc | |||
| f84a5a2214 | |||
| 208dca6bab | |||
| f45735798a | |||
| abb3ed132a | |||
| 13df0d69f4 | |||
| cdddebb931 | |||
| 47cc664b4f | |||
| df84dda36a | |||
| 84dd482430 | |||
| 1e389fca86 | |||
| 2d4faaf396 | |||
| 85af5fd4e2 | |||
| 8a08f5ae94 | |||
| af646b05af | |||
| 07ad0d3909 | |||
| 12da9e27bb | |||
| 2b56afb848 | |||
| 117721f5f6 | |||
| 9ab6bf0cec | |||
| 2e28affa93 | |||
| 55464029d4 | |||
| d9b8ae95bd | |||
| 80e4d7186c | |||
| 62ddeaa6bf | |||
| 2d278e612c | |||
| 4b46eac5ba | |||
| 73fcc0f9ae | |||
| b5b7090bb9 | |||
| af09b108d1 | |||
| 66157393ea | |||
| e62f91dc0d | |||
| cca37bc9e8 | |||
| 873570543f | |||
| dd0e6db171 | |||
| 7295d25e4e | |||
| e1372b0ede | |||
| 4ab6e6272e | |||
| cdf17b2d80 | |||
| e675454117 | |||
| cde014a355 | |||
| cfb197067a | |||
| 6786f64c9f | |||
| 3443ed3e82 | |||
| cef72dca61 | |||
| 3cb826de96 | |||
| 5f01b90f55 | |||
| b41ab9115d | |||
| 970731b38a | |||
| 02bbb39765 | |||
| e29fb2091e | |||
| 68d198f255 | |||
| 0b6910951d | |||
| 0e90584911 |
@@ -0,0 +1,8 @@
|
||||
# Changesets
|
||||
|
||||
Hello and welcome! This folder has been automatically generated by `@changesets/cli`, a build tool that works
|
||||
with multi-package repos, or single-package repos to help you version and publish your code. You can
|
||||
find the full documentation for it [in our repository](https://github.com/changesets/changesets)
|
||||
|
||||
We have a quick list of common questions to get you started engaging with this project in
|
||||
[our documentation](https://github.com/changesets/changesets/blob/main/docs/common-questions.md)
|
||||
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"$schema": "https://unpkg.com/@changesets/config@3.0.2/schema.json",
|
||||
"changelog": "@changesets/cli/changelog",
|
||||
"commit": false,
|
||||
"fixed": [],
|
||||
"linked": [],
|
||||
"access": "public",
|
||||
"baseBranch": "main",
|
||||
"updateInternalDependencies": "patch",
|
||||
"ignore": []
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
# 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.
|
||||
|
||||
## Types of Contributions
|
||||
|
||||
This repository contains code related to the rendering engine of GitBook's published content. Depending on what you'd like to contribute to, head to the section below to find the necessary steps.
|
||||
|
||||
### Add a feature
|
||||
|
||||
Because this portion of GitBook is open source and available for you to use - if you think you can provide extra value through a new feature - you're welcome to add it! If you plan to distribute the code, keep the source code public to comply with GNU GPLv3. To clone in a private repository, you must first acquire a [commercial license](https://www.gitbook.com/pricing).
|
||||
|
||||
### Create a new issue
|
||||
|
||||
If you spot a problem within a repository, [search if an issue already exists](https://docs.github.com/en/github/searching-for-information-on-github/searching-on-github/searching-issues-and-pull-requests#search-by-the-title-body-or-comments). If a related issue doesn't exist, you can open a new issue here!Please make sure any added issues are
|
||||
|
||||
- Descriptive
|
||||
- Thoughtful
|
||||
- Organized
|
||||
|
||||
We recommend adding as many relevant links, minimal reproductions of the issue, and other materials that will help our team solve the issue fast.
|
||||
|
||||
### Solve an issue
|
||||
|
||||
If you're interested in solving an issue in our repository, start by scanning through it's exisiting issues to find one that you're interested in working on. If you find an issue to work on, you are welcome to open a PR with a fix. See the following sections below for more information on contributing for specific sections.
|
||||
|
||||
### Documentation
|
||||
|
||||
The official documentation on GitBook open can be found directly in this Readme. Any updates or changes you would like to make, you can make directly to the README of this repository.
|
||||
|
||||
## Contributing
|
||||
|
||||
### Make changes locally
|
||||
|
||||
Any contribution you make can be made to the code located in this repository. In order to contribute, you'll need to start off of a local version of this repository.
|
||||
|
||||
#### 1. Fork the repository
|
||||
|
||||
##### Using GitHub Desktop:
|
||||
|
||||
- [Getting started with GitHub Desktop](https://docs.github.com/en/desktop/installing-and-configuring-github-desktop/getting-started-with-github-desktop) will guide you through setting up Desktop.
|
||||
- Once Desktop is set up, you can use it to [fork the repo](https://docs.github.com/en/desktop/contributing-and-collaborating-using-github-desktop/cloning-and-forking-repositories-from-github-desktop)!
|
||||
|
||||
##### Using the command line:
|
||||
|
||||
- [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!
|
||||
|
||||
### Commit your update
|
||||
|
||||
[Commit your changes](https://github.com/git-guides/git-commit) once you are happy with them. See [Atom's contributing guide](https://github.com/atom/atom/blob/master/CONTRIBUTING.md#git-commit-messages) to know how to use emoji for commit messages!
|
||||
|
||||
Once your changes are ready, don't forget to self-review your code to double check that your chagnes are ready to be added.
|
||||
|
||||
### Pull Request
|
||||
|
||||
When you're finished with the changes, [create a pull request](https://docs.github.com/en/pull-requests/collaborating-with-pull-requests/proposing-changes-to-your-work-with-pull-requests/creating-a-pull-request), also known as a PR.
|
||||
|
||||
- Don't forget to [link PR to issue](https://docs.github.com/en/issues/tracking-your-work-with-issues/linking-a-pull-request-to-an-issue) if you are solving one.
|
||||
- Enable the checkbox to [allow maintainer edits](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/allowing-changes-to-a-pull-request-branch-created-from-a-fork) so the branch can be updated for a merge. Once you submit your PR, a GitBook team member will review your proposal. We may ask questions or request for additional information.
|
||||
- We may ask for changes to be made before a PR can be merged, either using [suggested changes](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/incorporating-feedback-in-your-pull-request) or pull request comments. You can apply suggested changes directly through the UI. You can make any other changes in your fork, then commit them to your branch.
|
||||
- As you update your PR and apply changes, mark each conversation as [resolved](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/commenting-on-a-pull-request#resolving-conversations).
|
||||
- If you run into any merge issues, checkout this [git tutorial](https://lab.github.com/githubtraining/managing-merge-conflicts) to help you resolve merge conflicts and other issues.
|
||||
|
||||
### 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.
|
||||
@@ -0,0 +1,18 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Something not working as expected? Let us look into it
|
||||
labels: bug
|
||||
---
|
||||
|
||||
## Bug description
|
||||
|
||||
_Please describe._
|
||||
_If this affects the front-end, screenshots would be of great help._
|
||||
|
||||
## How to reproduce
|
||||
|
||||
1.
|
||||
2.
|
||||
3.
|
||||
|
||||
## Additional context
|
||||
@@ -0,0 +1,35 @@
|
||||
name: 'Setup Playwright'
|
||||
description: 'Install Playwright and dependencies'
|
||||
runs:
|
||||
using: 'composite'
|
||||
steps:
|
||||
# Run npm ci and get Playwright version
|
||||
- name: 🏗 Prepare Playwright env
|
||||
shell: bash
|
||||
run: |
|
||||
PLAYWRIGHT_VERSION=$(npm ls --json @playwright/test | jq --raw-output '.dependencies["@playwright/test"].version')
|
||||
echo "PLAYWRIGHT_VERSION=$PLAYWRIGHT_VERSION" >> $GITHUB_ENV
|
||||
|
||||
# Cache browser binaries, cache key is based on Playwright version and OS
|
||||
- name: 🧰 Cache Playwright browser binaries
|
||||
uses: actions/cache@v3
|
||||
id: playwright-cache
|
||||
with:
|
||||
path: '~/.cache/ms-playwright'
|
||||
key: '${{ runner.os }}-playwright-${{ env.PLAYWRIGHT_VERSION }}'
|
||||
restore-keys: |
|
||||
${{ runner.os }}-playwright-
|
||||
|
||||
# Install browser binaries & OS dependencies if cache missed
|
||||
- name: 🏗 Install Playwright browser binaries & OS dependencies
|
||||
if: steps.playwright-cache.outputs.cache-hit != 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
bun x playwright install --with-deps chromium
|
||||
|
||||
# Install only the OS dependencies if cache hit
|
||||
- name: 🏗 Install Playwright OS dependencies
|
||||
if: steps.playwright-cache.outputs.cache-hit == 'true'
|
||||
shell: bash
|
||||
run: |
|
||||
bun x playwright install-deps
|
||||
@@ -0,0 +1,174 @@
|
||||
name: CI
|
||||
on:
|
||||
pull_request:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
jobs:
|
||||
deploy:
|
||||
name: Deploy to Cloudflare Pages
|
||||
runs-on: ubuntu-latest
|
||||
permissions:
|
||||
contents: read
|
||||
deployments: write
|
||||
outputs:
|
||||
deployment_url: ${{ steps.cloudflare.outputs.url }}
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- 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: Cache Next.js build
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: |
|
||||
${{ github.workspace }}/.next/cache
|
||||
# Generate a new cache whenever packages or source files change.
|
||||
key: ${{ runner.os }}-nextjs-${{ hashFiles('**/bun.lockb') }}-${{ hashFiles('**/*.js', '**/*.jsx', '**/*.ts', '**/*.tsx') }}
|
||||
# If source files changed but packages didn't, rebuild from a prior cache.
|
||||
restore-keys: |
|
||||
${{ runner.os }}-nextjs-${{ hashFiles('**/bun.lockb') }}-
|
||||
- name: Sets env vars for production
|
||||
run: |
|
||||
echo "SENTRY_ENVIRONMENT=production" >> $GITHUB_ENV
|
||||
echo "GITBOOK_ASSETS_PREFIX=https://static.gitbook.com" >> $GITHUB_ENV
|
||||
if: startsWith(github.ref, 'refs/heads/main')
|
||||
- name: Sets env vars for preview
|
||||
run: |
|
||||
echo "SENTRY_ENVIRONMENT=preview" >> $GITHUB_ENV
|
||||
if: 1 && !startsWith(github.ref, 'refs/heads/main')
|
||||
- name: Build Next.js with next-on-pages
|
||||
run: bun run build:cloudflare
|
||||
env:
|
||||
SENTRY_AUTH_TOKEN: ${{ secrets.SENTRY_AUTH_TOKEN }}
|
||||
SENTRY_ORG: ${{ vars.SENTRY_ORG }}
|
||||
SENTRY_PROJECT: ${{ vars.SENTRY_PROJECT }}
|
||||
SENTRY_DSN: ${{ vars.SENTRY_DSN }}
|
||||
- id: cloudflare
|
||||
name: Publish to Cloudflare Pages
|
||||
uses: cloudflare/pages-action@v1
|
||||
with:
|
||||
apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
|
||||
accountId: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
|
||||
projectName: ${{ vars.CLOUDFLARE_PROJECT_NAME }}
|
||||
directory: ./packages/gitbook/.vercel/output/static
|
||||
gitHubToken: ${{ secrets.GITHUB_TOKEN }}
|
||||
workingDirectory: ./
|
||||
- name: Outputs
|
||||
run: |
|
||||
echo "ID: ${{ steps.cloudflare.outputs.id }}"
|
||||
echo "URL: ${{ steps.cloudflare.outputs.url }}"
|
||||
echo "Environment: ${{ steps.cloudflare.outputs.environment }}"
|
||||
echo "Alias: ${{ steps.cloudflare.outputs.alias }}"
|
||||
- name: Archive build output
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: build-output
|
||||
path: .vercel/
|
||||
visual-testing:
|
||||
runs-on: ubuntu-latest
|
||||
name: Visual Testing
|
||||
needs: deploy
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- name: Setup bun
|
||||
uses: oven-sh/setup-bun@v1
|
||||
with:
|
||||
bun-version: 1.1.18
|
||||
- name: Install dependencies
|
||||
run: bun install --frozen-lockfile
|
||||
- name: Setup Playwright
|
||||
uses: ./.github/actions/setup-playwright
|
||||
- name: Run Playwright tests
|
||||
run: bun e2e
|
||||
env:
|
||||
BASE_URL: ${{needs.deploy.outputs.deployment_url}}
|
||||
ARGOS_TOKEN: ${{ secrets.ARGOS_TOKEN }}
|
||||
pagespeed-testing:
|
||||
runs-on: ubuntu-latest
|
||||
name: PageSpeed Testing
|
||||
needs: deploy
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- 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: Run pagespeed tests
|
||||
run: bun ./packages/gitbook/tests/pagespeed-testing.ts $DEPLOYMENT_URL
|
||||
env:
|
||||
DEPLOYMENT_URL: ${{needs.deploy.outputs.deployment_url}}
|
||||
PAGESPEED_API_KEY: ${{ secrets.PAGESPEED_API_KEY }}
|
||||
format:
|
||||
runs-on: ubuntu-latest
|
||||
name: Format
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- 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
|
||||
- run: bun format:check
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
name: Lint
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- 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
|
||||
- run: bun lint --no-cache
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
name: Test
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- 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
|
||||
- run: bun unit
|
||||
typecheck:
|
||||
runs-on: ubuntu-latest
|
||||
name: Typecheck
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
- 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
|
||||
- run: bun typecheck
|
||||
@@ -0,0 +1,37 @@
|
||||
name: Publish
|
||||
|
||||
on:
|
||||
push:
|
||||
branches:
|
||||
- main
|
||||
|
||||
concurrency: ${{ github.workflow }}-${{ github.ref }}
|
||||
|
||||
jobs:
|
||||
publish:
|
||||
name: Publish
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout Repo
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
# This makes Actions fetch all Git history so that Changesets can generate changelogs with the correct commits
|
||||
fetch-depth: 0
|
||||
- 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: Create Release Pull Request or Publish to npm
|
||||
id: changesets
|
||||
uses: changesets/action@v1
|
||||
with:
|
||||
publish: npm run release
|
||||
env:
|
||||
# Using a PAT instead of GITHUB_TOKEN because we need to run workflows when releases are created
|
||||
# https://github.com/orgs/community/discussions/26875#discussioncomment-3253761
|
||||
GITHUB_TOKEN: ${{ secrets.GH_PERSONAL_TOKEN }}
|
||||
NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
|
||||
+20
-23
@@ -1,25 +1,22 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
|
||||
.grunt
|
||||
|
||||
# Compiled binary addons (http://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directory
|
||||
# Deployed apps should consider commenting this line out:
|
||||
# see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git
|
||||
# dependencies
|
||||
node_modules
|
||||
/.pnp
|
||||
.pnp.js
|
||||
|
||||
# misc
|
||||
.DS_Store
|
||||
*.pem
|
||||
|
||||
# debug
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Turbo
|
||||
.turbo
|
||||
|
||||
# Vercel
|
||||
.vercel
|
||||
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
.next
|
||||
.vercel
|
||||
|
||||
# Generated
|
||||
packages/emoji-codepoints/index.ts
|
||||
packages/gitbook/public/~gitbook/static/
|
||||
@@ -0,0 +1,5 @@
|
||||
{
|
||||
"printWidth": 100,
|
||||
"singleQuote": true,
|
||||
"tabWidth": 4
|
||||
}
|
||||
@@ -1,5 +0,0 @@
|
||||
language: node_js
|
||||
node_js:
|
||||
- "0.11"
|
||||
- "0.10"
|
||||
- "0.8"
|
||||
Vendored
+11
@@ -0,0 +1,11 @@
|
||||
{
|
||||
"tailwindCSS.experimental.classRegex": [
|
||||
["Style \\=([^;]*);", "'([^']*)'"],
|
||||
["Style \\=([^;]*);", "\"([^\"]*)\""],
|
||||
["Style \\=([^;]*);", "\\`([^\\`]*)\\`"],
|
||||
["style \\=([^;]*);", "'([^']*)'"],
|
||||
["style \\=([^;]*);", "\"([^\"]*)\""],
|
||||
["style \\=([^;]*);", "\\`([^\\`]*)\\`"]
|
||||
],
|
||||
"tailwindCSS.classAttributes": ["class", "className", "style", ".*Style"]
|
||||
}
|
||||
-17
@@ -1,17 +0,0 @@
|
||||
Authors
|
||||
=======
|
||||
|
||||
Also see https://github.com/GitbookIO/gitbook/graphs/contributors.
|
||||
Names below are ordered by first contribution.
|
||||
|
||||
Author
|
||||
------
|
||||
|
||||
- Samy Pessé <samypesse@gmail.com>
|
||||
- Aaron O'Mullan <aaron.omullan@gmail.com>
|
||||
|
||||
|
||||
Contributors
|
||||
------------
|
||||
|
||||
- Nijiko Yonskai
|
||||
@@ -1,68 +0,0 @@
|
||||
module.exports = function (grunt) {
|
||||
var path = require("path");
|
||||
|
||||
// Load NPM tasks
|
||||
grunt.loadNpmTasks('grunt-contrib-less');
|
||||
grunt.loadNpmTasks('grunt-contrib-requirejs');
|
||||
|
||||
// Init GRUNT configuraton
|
||||
grunt.initConfig({
|
||||
pkg: grunt.file.readJSON('package.json'),
|
||||
less: {
|
||||
development: {
|
||||
options: {
|
||||
compress: true,
|
||||
yuicompress: true,
|
||||
optimization: 2
|
||||
},
|
||||
files: {
|
||||
"theme/assets/style.css": "theme/stylesheets/main.less",
|
||||
"theme/assets/print.css": "theme/stylesheets/print.less"
|
||||
}
|
||||
}
|
||||
},
|
||||
requirejs: {
|
||||
compile: {
|
||||
options: {
|
||||
name: "app",
|
||||
baseUrl: "theme/javascript/",
|
||||
out: "theme/assets/app.js",
|
||||
preserveLicenseComments: false,
|
||||
optimize: "uglify", //"uglify",
|
||||
include: ["requireLib"],
|
||||
paths: {
|
||||
"jQuery": 'vendors/jquery',
|
||||
"lodash": 'vendors/lodash',
|
||||
"requireLib": 'vendors/require',
|
||||
"Mousetrap": 'vendors/mousetrap',
|
||||
"lunr": path.join(__dirname, "node_modules/lunr/lunr")
|
||||
},
|
||||
shim: {
|
||||
'jQuery': {
|
||||
exports: '$'
|
||||
},
|
||||
'lodash': {
|
||||
exports: '_'
|
||||
},
|
||||
'Mousetrap': {
|
||||
exports: 'Mousetrap'
|
||||
},
|
||||
'lunr': {
|
||||
exports: 'lunr'
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Build
|
||||
grunt.registerTask('build', [
|
||||
'less',
|
||||
'requirejs'
|
||||
]);
|
||||
|
||||
grunt.registerTask('default', [
|
||||
'build'
|
||||
]);
|
||||
};
|
||||
@@ -1,201 +1,674 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
1. Definitions.
|
||||
Preamble
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
0. Definitions.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
1. Source Code.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
2. Basic Permissions.
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<https://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<https://www.gnu.org/licenses/why-not-lgpl.html>.
|
||||
|
||||
@@ -1,135 +1,130 @@
|
||||
GitBook
|
||||
=======
|
||||
<h1 align="center">GitBook</h1>
|
||||
|
||||
[](https://travis-ci.org/GitbookIO/gitbook)
|
||||
<p align="center">
|
||||
<a href="https://docs.gitbook.com/">Docs</a> - <a href="https://github.com/GitbookIO/community">Community</a> - <a href="https://developer.gitbook.com/">Developer Docs</a> - <a href="https://changelog.gitbook.com/">Changelog</a> - <a href="https://github.com/GitbookIO/gitbook/issues/new?assignees=&labels=bug&template=bug_report.md">Bug reports</a>
|
||||
</p>
|
||||
|
||||
GitBook is a command line tool (and Node.js library) for building beautiful programming books and exercises using GitHub/Git and Markdown. You can see an example: [Learn Javascript](http://gitbookio.github.io/javascript/). An [editor](https://github.com/GitbookIO/editor) is available for Windows, Mac and Linux. You can follow [@GitBookIO](https://twitter.com/GitBookIO) on Twitter.
|
||||
<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="#"><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>
|
||||
<a href="https://github.com/gitbookIO/gitbook/issues"><img src="https://img.shields.io/github/issues/gitbookIO/gitbook"/></a>
|
||||
</p>
|
||||
|
||||

|
||||
<p align="center">Welcome to GitBook, the platform for managing technical knowledge for teams.</p>
|
||||
|
||||
## How to use it:
|
||||
<p align="center">This repository contains the open-source code used to render GitBook's published content.</p>
|
||||
|
||||
GitBook can be installed from **NPM** using:
|
||||
<p align="center">
|
||||
<img alt="GitBook Open Published Site" src="./assets/published-site.png">
|
||||
</p>
|
||||
|
||||
## Table of Contents
|
||||
|
||||
- [Getting Started](#getting-started)
|
||||
- [Contributing](#contributing)
|
||||
- [Types of contributions](#types-of-contributions)
|
||||
- [Licensing](#license)
|
||||
- [Acknowledgements](#acknowledgements)
|
||||
- [Legacy GitBook](#legacy-gitbook-deprecated)
|
||||
|
||||
## Getting Started
|
||||
|
||||
To run a local version of this project, please follow these simple steps.
|
||||
|
||||
### Prerequisites
|
||||
|
||||
- Node.js (Version: >=18.x)
|
||||
- Bun
|
||||
|
||||
### Set up
|
||||
|
||||
1. Clone the repo into a **public** GitHub repository. If you plan to distribute the code, keep the source code public to comply with GNU GPLv3. To clone in a private repository, acquire a [commercial license](https://www.gitbook.com/pricing).
|
||||
|
||||
```
|
||||
$ npm install gitbook -g
|
||||
git clone https://github.com/gitbookIO/gitbook.git
|
||||
```
|
||||
|
||||
You can serve a repository as a book using:
|
||||
2. Install the project's dependencies through Bun.
|
||||
|
||||
```
|
||||
$ gitbook serve ./repository
|
||||
bun install
|
||||
```
|
||||
|
||||
Or simply build the static website using:
|
||||
3. Start your local development server.
|
||||
|
||||
```
|
||||
$ gitbook build ./repository --output=./outputFolder
|
||||
bun dev
|
||||
```
|
||||
|
||||
Options for commands `build` and `serve` are:
|
||||
Then open the space in your web browser, using http://localhost:3000/<host>/<path> (example: http://localhost:3000/docs.gitbook.com).
|
||||
|
||||
```
|
||||
-t, --title <name> Name of the book to generate, defaults to repo name
|
||||
-i, --intro <intro> Description of the book to generate
|
||||
-g, --github <repo_path> ID of github repo like : username/repo
|
||||
-o, --output <directory> Path to output directory, defaults to ./_book
|
||||
-f, --format <name> Change generation format, defaults to site, availables are: site, page, pdf, json
|
||||
--githubHost <url> The url of the github host (defaults to https://github.com/)
|
||||
--theme <path> Path to theme directory
|
||||
```
|
||||
### Other development commands
|
||||
|
||||
You can publish your books to our index by visiting [GitBook.io](http://www.gitbook.io)
|
||||
- `bun format`: format the code
|
||||
- `bun lint`: lint the code
|
||||
|
||||
## Output Formats
|
||||
### CI and testing
|
||||
|
||||
GitBook can generate your book in the following formats:
|
||||
All pull-requests will be tested against both visual and performances testing to prevent regressions.
|
||||
|
||||
* **Static Website**: This is the default format, it generates a complete interactive static website that can be for example hosted on GitHub Pages.
|
||||
* **PDF**: A complete PDF book with exercise solutions at the end of the book. Generate to this format using: ```gitbook pdf ./myrepo```, you need to have [gitbook-pdf](https://github.com/GitbookIO/gitbook-pdf) installed.
|
||||
* **eBook**: A complete eBook with exercise solutions at the end of the book. Generate to this format using: ```gitbook ebook ./myrepo```, you need to have [ebook-convert](http://manual.calibre-ebook.com/cli/ebook-convert.html) installed.
|
||||
* **Single Page**: The book will be stored in a single printable HTML page, this format is used for conversion to PDF or eBook. Generate to this format using: ```gitbook build ./myrepo -f page```.
|
||||
* **JSON**: This format is used for debugging or extracting metadata from a book. Generate to this format using: ```gitbook build ./myrepo -f json```.
|
||||
## Contributing
|
||||
|
||||
## Book Format
|
||||
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.
|
||||
|
||||
A book is a GitHub repository containing at least 2 files: `README.md` and `SUMMARY.md`.
|
||||
### Types of contributions
|
||||
|
||||
#### README.md
|
||||
We encourage you to contribute to GitBook to help us build the best tool for documenting technical knowledge. If you're looking for some quick ways to contribute, continue reading to learn more about popular contributions.
|
||||
|
||||
As usual, it should contains an introduction for your book. It will be automatically added to the final summary.
|
||||
#### Translations
|
||||
|
||||
#### SUMMARY.md
|
||||
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 `SUMMARY.md` defines your book's structure. It should contain a list of chapters, linking to their respective pages.
|
||||
#### Bugs
|
||||
|
||||
Example:
|
||||
Encounter a bug or find an issue you'd like to fix? Helping us fix issues related to GitBook greatly improves the experience for everyone. Head to the issues section of this repository to learn more about the types of bugs you can already help out with.
|
||||
|
||||
```
|
||||
# Summary
|
||||
## Deployment
|
||||
|
||||
This is the summary of my book.
|
||||
> [!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._
|
||||
>
|
||||
> 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.
|
||||
>
|
||||
> We want to make it as easy as possible for our community to collaborate and push the future of GitBook, which is why we encourage you to contribute to our product directly instead of creating your own version.
|
||||
|
||||
* [section 1](section1/README.md)
|
||||
* [example 1](section1/example1.md)
|
||||
* [example 2](section1/example2.md)
|
||||
* [section 2](section2/README.md)
|
||||
* [example 1](section2/example1.md)
|
||||
```
|
||||
This project allows you to self-host the rendering portion of your GitBook published content. Self-hosting has pros and cons.
|
||||
|
||||
Files that are not included in the `SUMMARY.md` will not be processed by `gitbook`.
|
||||
On the pro side, you can customize the look and feel of your content, and better embed your documentation in your application.
|
||||
|
||||
#### Exercises
|
||||
On the con side, you become responsible for the reliability of your published site, and keeping the renderer up-to-date with the changes made to the GitBook platform.
|
||||
|
||||
A book can contain interactive exercises (currently only in Javascript but Python and Ruby are coming soon ;) ). An exercise is a code challenge provided to the reader, which is given a code editor to write a solution which is checked against the book author's validation code.
|
||||
## License
|
||||
|
||||
An exercise is defined by 4 simple parts:
|
||||
Distributed under the [GNU GPLv3 License](https://github.com/GitBookIO/gitbook/blob/main/LICENSE).
|
||||
|
||||
* Exercise **Message**/Goals (in markdown/text)
|
||||
* **Initial** code to show to the user, providing a starting point
|
||||
* **Solution** code, being a correct solution to the exercise
|
||||
* **Validation** code that tests the correctness of the user's input
|
||||
If you plan to distribute the code, you must the source code public to comply with GNU GPLv3. To clone in a private repository, acquire a [commercial license](https://www.gitbook.com/pricing).
|
||||
|
||||
Exercises need to start and finish with a separation bar (```---``` or ```***```). It should contain 3 code elements (**base**, **solution** and **validation**). It can contain a 4th element that provides **context** code (functions, imports of libraries etc ... that shouldn't be displayed to the user).
|
||||
See `LICENSE` for more information.
|
||||
|
||||
---
|
||||
## Acknowledgements
|
||||
|
||||
Define a variable `x` equal to 10.
|
||||
GitBook wouldn't be possible without these projects:
|
||||
|
||||
```js
|
||||
var x =
|
||||
```
|
||||
- [Next.js](https://nextjs.org/)
|
||||
- [Bun](https://bun.sh/)
|
||||
- [Tailwind CSS](https://tailwindcss.com/)
|
||||
- [Framer Motion](https://www.npmjs.com/package/framer-motion)
|
||||
|
||||
```js
|
||||
var x = 10;
|
||||
```
|
||||
## Contributors
|
||||
|
||||
```js
|
||||
assert(x == 10);
|
||||
```
|
||||
<a href="https://github.com/gitbookIO/gitbook/graphs/contributors">
|
||||
<img src="https://contrib.rocks/image?repo=gitbookIO/gitbook" />
|
||||
</a>
|
||||
|
||||
```js
|
||||
// This is context code available everywhere
|
||||
// The user will be able to call magicFunc in his code
|
||||
function magicFunc() {
|
||||
return 3;
|
||||
}
|
||||
```
|
||||
## Legacy GitBook (Deprecated)
|
||||
|
||||
---
|
||||
|
||||
#### Multi-Languages
|
||||
|
||||
GitBook supports building books written in multiple languages. Each language should be a sub-directory following the normal GitBook format, and a file named `LANGS.md` should be present at the root of the repository with the following format:
|
||||
|
||||
```
|
||||
* [English](en/)
|
||||
* [French](fr/)
|
||||
* [Español](es/)
|
||||
```
|
||||
|
||||
You can see a complete example with the [Learn Git](https://github.com/GitbookIO/git) book.
|
||||
|
||||
#### Ignoring files & folders
|
||||
|
||||
GitBook will read the `.gitignore`, `.bookignore` and `.ignore` files to get a list of files and folders to skip. (The format inside those files, follows the same convention as `.gitignore`)
|
||||
Our previous version of GitBook and it's CLI tool are now deprecated. You can still view the old repository and it's commits on this [branch](https://github.com/GitbookIO/gitbook/tree/legacy).
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 622 KiB |
@@ -1,50 +0,0 @@
|
||||
var path = require('path');
|
||||
var Q = require('q');
|
||||
var _ = require('lodash');
|
||||
|
||||
var utils = require('./utils');
|
||||
|
||||
var generate = require("../lib/generate");
|
||||
var parse = require("../lib/parse");
|
||||
var fs = require('../lib/generate/fs');
|
||||
var generators = require("../lib/generate").generators;
|
||||
|
||||
var makeBuildFunc = function(converter) {
|
||||
return function(dir, options) {
|
||||
dir = dir || process.cwd();
|
||||
outputDir = options.output
|
||||
|
||||
console.log('Starting build ...');
|
||||
// Get repo's URL
|
||||
return utils.gitURL(dir)
|
||||
.then(function(url) {
|
||||
// Get ID of repo
|
||||
return utils.githubID(url);
|
||||
}, function(err) {
|
||||
return null;
|
||||
})
|
||||
.then(function(repoID) {
|
||||
return converter(
|
||||
_.extend(options || {}, {
|
||||
input: dir,
|
||||
output: outputDir,
|
||||
title: options.title,
|
||||
description: options.intro,
|
||||
github: options.github || repoID,
|
||||
githubHost: options.githubHost,
|
||||
generator: options.format,
|
||||
theme: options.theme
|
||||
})
|
||||
);
|
||||
})
|
||||
.then(function(output) {
|
||||
console.log("Successfuly built !");
|
||||
return output;
|
||||
}, utils.logError);
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = {
|
||||
folder: makeBuildFunc(generate.folder),
|
||||
file: makeBuildFunc(generate.file)
|
||||
};
|
||||
@@ -1,86 +0,0 @@
|
||||
#! /usr/bin/env node
|
||||
|
||||
var Q = require('q');
|
||||
var _ = require('lodash');
|
||||
var path = require('path');
|
||||
var prog = require('commander');
|
||||
|
||||
var pkg = require('../package.json');
|
||||
var generators = require("../lib/generate").generators;
|
||||
var initDir = require("../lib/generate/init");
|
||||
var fs = require('../lib/generate/fs');
|
||||
|
||||
var utils = require('./utils');
|
||||
var build = require('./build');
|
||||
|
||||
// General options
|
||||
prog
|
||||
.version(pkg.version);
|
||||
|
||||
var buildCommand = function(command) {
|
||||
return command
|
||||
.option('-o, --output <directory>', 'Path to output directory, defaults to ./_book')
|
||||
.option('-f, --format <name>', 'Change generation format, defaults to site, availables are: '+_.keys(generators).join(", "))
|
||||
.option('-t, --title <name>', 'Name of the book to generate, default is extracted from readme')
|
||||
.option('-i, --intro <intro>', 'Description of the book to generate, default is extracted from readme')
|
||||
.option('-g, --github <repo_path>', 'ID of github repo like : username/repo')
|
||||
.option('--githubHost <url>', 'The url of the github host (defaults to https://github.com/')
|
||||
.option('--theme <path>', 'Path to theme directory');
|
||||
};
|
||||
|
||||
buildCommand(prog.command('build [source_dir]'))
|
||||
.description('Build a gitbook from a directory')
|
||||
.action(build.folder);
|
||||
|
||||
buildCommand(prog.command('serve [source_dir]'))
|
||||
.description('Build then serve a gitbook from a directory')
|
||||
.option('-p, --port <port>', 'Port for server to listen on', 4000)
|
||||
.action(function(dir, options) {
|
||||
build.folder(dir, options || {})
|
||||
.then(function(_options) {
|
||||
console.log();
|
||||
console.log('Starting server ...');
|
||||
return utils.serveDir(_options.output, options.port)
|
||||
.fail(utils.logError);
|
||||
})
|
||||
.then(function() {
|
||||
console.log('Serving book on http://localhost:'+options.port);
|
||||
console.log();
|
||||
console.log('Press CTRL+C to quit ...');
|
||||
});
|
||||
});
|
||||
|
||||
buildCommand(prog.command('pdf [source_dir]'))
|
||||
.description('Build a gitbook as a PDF')
|
||||
.option('-pf, --paperformat <format>', 'PDF paper format (default is A4): "5in*7.5in", "10cm*20cm", "A4", "Letter"')
|
||||
.action(function(dir, options) {
|
||||
build.file(dir, _.extend(options, {
|
||||
extension: "pdf",
|
||||
format: "pdf"
|
||||
}));
|
||||
});
|
||||
|
||||
buildCommand(prog.command('ebook [source_dir]'))
|
||||
.description('Build a gitbook as a eBook')
|
||||
.option('-c, --cover <path>', 'Cover image, default is cover.png if exists')
|
||||
.action(function(dir, options) {
|
||||
var ext = options.output ? path.extname(options.output) : "epub";
|
||||
|
||||
build.file(dir, _.extend(options, {
|
||||
extension: ext,
|
||||
format: "ebook"
|
||||
}));
|
||||
});
|
||||
|
||||
prog
|
||||
.command('init [source_dir]')
|
||||
.description('Create files and folders based on contents of SUMMARY.md')
|
||||
.action(function(dir) {
|
||||
dir = dir || process.cwd();
|
||||
return initDir(dir);
|
||||
});
|
||||
|
||||
// Parse and fallback to help if no args
|
||||
if(_.isEmpty(prog.parse(process.argv).args) && process.argv.length === 2) {
|
||||
prog.help();
|
||||
}
|
||||
-101
@@ -1,101 +0,0 @@
|
||||
var Q = require('q');
|
||||
var _ = require('lodash');
|
||||
|
||||
var http = require('http');
|
||||
var send = require('send');
|
||||
|
||||
var url = require('url');
|
||||
var cp = require('child_process');
|
||||
|
||||
|
||||
// Get the remote of a given repo
|
||||
function gitURL(path) {
|
||||
var d = Q.defer();
|
||||
|
||||
cp.exec("git config --get remote.origin.url", {
|
||||
cwd: path,
|
||||
env: process.env,
|
||||
}, function(err, stdout, stderr) {
|
||||
if(err) {
|
||||
return d.reject(err);
|
||||
}
|
||||
|
||||
return d.resolve(stdout);
|
||||
});
|
||||
|
||||
return d.promise
|
||||
.then(function(output) {
|
||||
return output.replace(/(\r\n|\n|\r)/gm, "");
|
||||
});
|
||||
}
|
||||
|
||||
// Poorman's parsing
|
||||
// Parse a git URL to a github ID : username/reponame
|
||||
function githubID(_url) {
|
||||
// Remove .git if it's in _url
|
||||
var sliceEnd = _url.slice(-4) === '.git' ? -4 : _url.length;
|
||||
|
||||
// Detect HTTPS repos
|
||||
var parsed = url.parse(_url);
|
||||
if(parsed.protocol === 'https:' && parsed.host === 'github.com') {
|
||||
return parsed.path.slice(1, sliceEnd);
|
||||
}
|
||||
|
||||
// Detect SSH repos
|
||||
if(_url.indexOf('git@') === 0) {
|
||||
return _url.split(':', 2)[1].slice(0, sliceEnd);
|
||||
}
|
||||
|
||||
// None found
|
||||
return null;
|
||||
}
|
||||
|
||||
function titleCase(str)
|
||||
{
|
||||
return str.replace(/\w\S*/g, function(txt){return txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase();});
|
||||
}
|
||||
|
||||
function serveDir(dir, port) {
|
||||
var d = Q.defer();
|
||||
|
||||
var server = http.createServer(function(req, res){
|
||||
// Render error
|
||||
function error(err) {
|
||||
res.statusCode = err.status || 500;
|
||||
res.end(err.message);
|
||||
}
|
||||
|
||||
// Redirect to directory's index.html
|
||||
function redirect() {
|
||||
res.statusCode = 301;
|
||||
res.setHeader('Location', req.url + '/');
|
||||
res.end('Redirecting to ' + req.url + '/');
|
||||
}
|
||||
|
||||
// Send file
|
||||
send(req, url.parse(req.url).pathname)
|
||||
.root(dir)
|
||||
.on('error', error)
|
||||
.on('directory', redirect)
|
||||
.pipe(res);
|
||||
}).listen(port);
|
||||
|
||||
d.resolve(server);
|
||||
|
||||
return d.promise;
|
||||
}
|
||||
|
||||
function logError(err) {
|
||||
console.log(err.stack || err.message || err);
|
||||
return Q.reject(err);
|
||||
};
|
||||
|
||||
|
||||
// Exports
|
||||
module.exports = {
|
||||
gitURL: gitURL,
|
||||
githubID: githubID,
|
||||
titleCase: titleCase,
|
||||
serveDir: serveDir,
|
||||
logError: logError
|
||||
};
|
||||
@@ -0,0 +1,22 @@
|
||||
# Caching
|
||||
|
||||
## Revalidating the cache
|
||||
|
||||
Invalidate cache can be done at two levels using tags:
|
||||
|
||||
- Data fetching cache
|
||||
- Rendering cache
|
||||
|
||||
To invalidate and refetch the data cache, you can execute a POST request to `/~/gitbook/revalidate`:
|
||||
|
||||
```bash
|
||||
curl --location --request POST 'https://gitbook/mycompany.com/~gitbook/revalidate' \
|
||||
--header 'Content-Type: application/json' \
|
||||
--data-raw '{"tags": ["space.id"]}'
|
||||
```
|
||||
|
||||
To invalidate the rendering cache, the implementation mainly depends on the infrastructure serving the content, GitBook outputs a `Cache-Tag` header on every requests. The value of the header is a comma separated list of tags.
|
||||
|
||||
## Purging the cache
|
||||
|
||||
Purging the cache, without revalidating, is done by passing `"purge": true` in the request body.
|
||||
@@ -1,70 +0,0 @@
|
||||
var util = require("util");
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
var _ = require("lodash");
|
||||
var exec = require('child_process').exec;
|
||||
|
||||
var fs = require("fs");
|
||||
var parse = require("../../parse");
|
||||
var BaseGenerator = require("../page");
|
||||
|
||||
/*
|
||||
* This generator inherits from the single page generator
|
||||
* and convert the page output to ebook
|
||||
*/
|
||||
var Generator = function() {
|
||||
BaseGenerator.apply(this, arguments);
|
||||
|
||||
// Options for eBook generation
|
||||
this.options = _.defaults(this.options, {
|
||||
extension: "epub"
|
||||
});
|
||||
|
||||
if (!this.options.cover && fs.existsSync(path.join(this.options.input, "cover.png"))) {
|
||||
this.options.cover = path.join(this.options.input, "cover.png")
|
||||
}
|
||||
};
|
||||
util.inherits(Generator, BaseGenerator);
|
||||
|
||||
Generator.prototype.finish = function() {
|
||||
var that = this;
|
||||
|
||||
return BaseGenerator.prototype.finish.apply(this)
|
||||
.then(function() {
|
||||
var d = Q.defer();
|
||||
|
||||
var _options = {
|
||||
"--cover": that.options.cover
|
||||
};
|
||||
|
||||
var command = [
|
||||
"ebook-convert",
|
||||
path.join(that.options.output, "index.html"),
|
||||
path.join(that.options.output, "index."+that.options.extension),
|
||||
_.chain(_options)
|
||||
.map(function(value, key) {
|
||||
if (value == null) return null;
|
||||
return key+"="+value;
|
||||
})
|
||||
.compact()
|
||||
.value()
|
||||
.join(" ")
|
||||
].join(" ");
|
||||
|
||||
exec(command, function (error, stdout, stderr) {
|
||||
if (error) {
|
||||
if (error.code == 127) {
|
||||
error.message = "Need to install ebook-convert from Calibre";
|
||||
} else {
|
||||
error.message = error.message + " "+stdout;
|
||||
}
|
||||
return d.reject(error);
|
||||
}
|
||||
d.resolve();
|
||||
});
|
||||
|
||||
return d.promise;
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = Generator;
|
||||
@@ -1,60 +0,0 @@
|
||||
var Q = require("q");
|
||||
var fs = require("fs");
|
||||
var fsExtra = require("fs-extra");
|
||||
var Ignore = require("fstream-ignore");
|
||||
|
||||
var getFiles = function(path) {
|
||||
var d = Q.defer();
|
||||
|
||||
// Our list of files
|
||||
var files = [];
|
||||
|
||||
var ig = Ignore({
|
||||
path: path,
|
||||
ignoreFiles: ['.ignore', '.gitignore', '.bookignore']
|
||||
});
|
||||
|
||||
// Add extra rules to ignore common folders
|
||||
ig.addIgnoreRules([
|
||||
'.git/',
|
||||
'.gitignore',
|
||||
], '__custom_stuff');
|
||||
|
||||
// Push each file to our list
|
||||
ig.on('child', function (c) {
|
||||
files.push(
|
||||
c.path.substr(c.root.path.length + 1) + (c.props.Directory === true ? '/' : '')
|
||||
);
|
||||
});
|
||||
|
||||
ig.on('end', function() {
|
||||
// Normalize paths on Windows
|
||||
if(process.platform === 'win32') {
|
||||
return d.resolve(files.map(function(file) {
|
||||
return file.replace(/\\/g, '/');
|
||||
}));
|
||||
}
|
||||
|
||||
// Simply return paths otherwise
|
||||
return d.resolve(files);
|
||||
});
|
||||
|
||||
ig.on('error', d.reject);
|
||||
|
||||
return d.promise;
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
list: getFiles,
|
||||
readFile: Q.denodeify(fs.readFile),
|
||||
writeFile: Q.denodeify(fs.writeFile),
|
||||
mkdirp: Q.denodeify(fsExtra.mkdirp),
|
||||
copy: Q.denodeify(fsExtra.copy),
|
||||
remove: Q.denodeify(fsExtra.remove),
|
||||
symlink: Q.denodeify(fsExtra.symlink),
|
||||
exists: function(path) {
|
||||
var d = Q.defer();
|
||||
fs.exists(path, d.resolve);
|
||||
return d.promise;
|
||||
},
|
||||
};
|
||||
@@ -1,36 +0,0 @@
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
var fs = require("./fs");
|
||||
|
||||
var BaseGenerator = function(options) {
|
||||
this.options = options;
|
||||
};
|
||||
|
||||
BaseGenerator.prototype.convertFile = function(content, input) {
|
||||
return Q.reject(new Error("Could not convert "+input));
|
||||
};
|
||||
|
||||
BaseGenerator.prototype.transferFile = function(input) {
|
||||
return fs.copy(
|
||||
path.join(this.options.input, input),
|
||||
path.join(this.options.output, input)
|
||||
);
|
||||
};
|
||||
|
||||
BaseGenerator.prototype.transferFolder = function(input) {
|
||||
return fs.mkdirp(
|
||||
path.join(this.options.output, input)
|
||||
);
|
||||
};
|
||||
|
||||
BaseGenerator.prototype.langsIndex = function(langs) {
|
||||
return Q.reject(new Error("Langs index is not supported in this generator"));
|
||||
};
|
||||
|
||||
BaseGenerator.prototype.finish = function() {
|
||||
return Q.reject(new Error("Could not finish generation"));
|
||||
};
|
||||
|
||||
|
||||
|
||||
module.exports = BaseGenerator;
|
||||
@@ -1,238 +0,0 @@
|
||||
var Q = require("q");
|
||||
var _ = require("lodash");
|
||||
var path = require("path");
|
||||
var swig = require('swig');
|
||||
var tmp = require('tmp');
|
||||
|
||||
var fs = require("./fs");
|
||||
var parse = require("../parse");
|
||||
|
||||
var generators = {
|
||||
"site": require("./site"),
|
||||
"page": require("./page"),
|
||||
"pdf": require("./pdf"),
|
||||
"ebook": require("./ebook"),
|
||||
"json": require("./json")
|
||||
};
|
||||
|
||||
var defaultDescription = "Book generated using GitBook";
|
||||
|
||||
/*
|
||||
* Use a specific generator to convert a gitbook to a site/pdf/ebook/
|
||||
* output is always a folder
|
||||
*/
|
||||
var generate = function(options) {
|
||||
var generator = null;
|
||||
var files;
|
||||
|
||||
options = _.defaults(options || {}, {
|
||||
// Folders to use
|
||||
input: null,
|
||||
output: null,
|
||||
|
||||
// Output generator
|
||||
generator: "site",
|
||||
|
||||
// Book title, keyword, description
|
||||
title: null,
|
||||
description: null,
|
||||
|
||||
// Origin github repository id
|
||||
github: null,
|
||||
githubHost: 'https://github.com/',
|
||||
|
||||
// Theming
|
||||
theme: path.resolve(__dirname, '../../theme')
|
||||
});
|
||||
|
||||
if (!options.input) {
|
||||
return Q.reject(new Error("Need option input (book input directory)"));
|
||||
}
|
||||
|
||||
if (!generators[options.generator]) {
|
||||
return Q.reject(new Error("Invalid generator (availables are: "+_.keys(generators).join(", ")));
|
||||
}
|
||||
|
||||
options.output = options.output || path.join(options.input, "_book");
|
||||
|
||||
// Clean output folder
|
||||
return fs.remove(options.output)
|
||||
|
||||
.then(function() {
|
||||
return fs.mkdirp(options.output);
|
||||
})
|
||||
|
||||
// List all files in the repository
|
||||
.then(function() {
|
||||
return fs.list(options.input)
|
||||
.then(function(_files) {
|
||||
files = _files;
|
||||
})
|
||||
})
|
||||
|
||||
// Create the generator
|
||||
.then(function() {
|
||||
generator = new generators[options.generator](options);
|
||||
})
|
||||
|
||||
// Detect multi-languages book
|
||||
.then(function() {
|
||||
if (_.contains(files, "LANGS.md")) {
|
||||
// Multi-languages book
|
||||
return fs.readFile(path.join(options.input, "LANGS.md"), "utf-8")
|
||||
|
||||
// Generate sub-books
|
||||
.then(function(_langsSummary) {
|
||||
options.langsSummary = parse.langs(_langsSummary);
|
||||
|
||||
// Generated a book for each valid entry
|
||||
return Q.all(
|
||||
_.map(options.langsSummary.list, function(entry) {
|
||||
return generate(_.extend({}, options, {
|
||||
input: path.join(options.input, entry.path),
|
||||
output: path.join(options.output, entry.path)
|
||||
}));
|
||||
})
|
||||
);
|
||||
})
|
||||
|
||||
// Generate languages index
|
||||
.then(function() {
|
||||
return generator.langsIndex(options.langsSummary);
|
||||
});
|
||||
} else if (!_.contains(files, "SUMMARY.md") || !_.contains(files, "README.md")) {
|
||||
// Invalid book
|
||||
return Q.reject(new Error("Invalid gitbook repository, need SUMMARY.md and README.md"));
|
||||
} else {
|
||||
// Generate the book
|
||||
return Q()
|
||||
|
||||
// Read readme
|
||||
.then(function() {
|
||||
return fs.readFile(path.join(options.input, "README.md"), "utf-8")
|
||||
.then(function(_readme) {
|
||||
_readme = parse.readme(_readme);
|
||||
|
||||
options.title = options.title || _readme.title;
|
||||
options.description = options.description || _readme.description || defaultDescription;
|
||||
});
|
||||
})
|
||||
|
||||
// Get summary
|
||||
.then(function() {
|
||||
return fs.readFile(path.join(options.input, "SUMMARY.md"), "utf-8")
|
||||
.then(function(_summary) {
|
||||
options.summary = parse.summary(_summary);
|
||||
|
||||
// Parse navigation
|
||||
options.navigation = parse.navigation(options.summary);
|
||||
});
|
||||
})
|
||||
|
||||
// Skip processing some files
|
||||
.then(function() {
|
||||
files = _.filter(files, function (file) {
|
||||
return !(
|
||||
file === 'SUMMARY.md'
|
||||
);
|
||||
});
|
||||
})
|
||||
|
||||
// Copy file and replace markdown file
|
||||
.then(function() {
|
||||
return Q.all(
|
||||
_.chain(files)
|
||||
.map(function(file) {
|
||||
if (!file) return;
|
||||
|
||||
if (file[file.length -1] == "/") {
|
||||
return Q(generator.transferFolder(file));
|
||||
} else if (path.extname(file) == ".md" && options.navigation[file] != null) {
|
||||
return fs.readFile(path.join(options.input, file), "utf-8")
|
||||
.then(function(content) {
|
||||
return Q(generator.convertFile(content, file));
|
||||
});
|
||||
} else {
|
||||
return Q(generator.transferFile(file));
|
||||
}
|
||||
})
|
||||
.value()
|
||||
);
|
||||
})
|
||||
|
||||
// Finish gneration
|
||||
.then(function() {
|
||||
return generator.finish();
|
||||
});
|
||||
}
|
||||
})
|
||||
|
||||
// Return all options
|
||||
.then(function() {
|
||||
return options;
|
||||
});
|
||||
};
|
||||
|
||||
/*
|
||||
* Extract files from generate output in a temporary folder
|
||||
*/
|
||||
var generateFile = function(options) {
|
||||
options = _.defaults(options || {}, {
|
||||
input: null,
|
||||
output: null,
|
||||
extension: null
|
||||
});
|
||||
|
||||
return Q.nfcall(tmp.dir)
|
||||
.then(function(tmpDir) {
|
||||
return generate(
|
||||
_.extend({},
|
||||
options,
|
||||
{
|
||||
output: tmpDir
|
||||
})
|
||||
)
|
||||
.then(function(_options) {
|
||||
var ext = options.extension;
|
||||
var outputFile = options.output || path.resolve(options.input, "book."+ext);
|
||||
|
||||
var copyFile = function(lang) {
|
||||
var _outputFile = outputFile;
|
||||
var _tmpDir = tmpDir;
|
||||
|
||||
if (lang) {
|
||||
_outputFile = _outputFile.slice(0, -path.extname(_outputFile).length)+"_"+lang+path.extname(_outputFile);
|
||||
_tmpDir = path.join(_tmpDir, lang);
|
||||
}
|
||||
|
||||
return fs.copy(
|
||||
path.join(_tmpDir, "index."+ext),
|
||||
_outputFile
|
||||
);
|
||||
};
|
||||
|
||||
// Multi-langs book
|
||||
return Q()
|
||||
.then(function() {
|
||||
if (_options.langsSummary) {
|
||||
return Q.all(
|
||||
_.map(_options.langsSummary.list, function(lang) {
|
||||
return copyFile(lang.lang);
|
||||
})
|
||||
);
|
||||
} else {
|
||||
return copyFile();
|
||||
}
|
||||
})
|
||||
.then(function() {
|
||||
return fs.remove(tmpDir);
|
||||
});
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
generators: generators,
|
||||
folder: generate,
|
||||
file: generateFile
|
||||
};
|
||||
@@ -1,69 +0,0 @@
|
||||
var Q = require('q');
|
||||
var _ = require('lodash');
|
||||
|
||||
var path = require('path');
|
||||
|
||||
var fs = require('./fs');
|
||||
var parse = require('../parse');
|
||||
|
||||
|
||||
// Extract paths out of a summary
|
||||
function paths(summary) {
|
||||
return _.reduce(summary.chapters, function(accu, chapter) {
|
||||
return accu.concat(
|
||||
_.filter([chapter.path].concat(_.pluck(chapter.articles, 'path')))
|
||||
);
|
||||
}, []);
|
||||
}
|
||||
|
||||
// Get the parent folders out of a group of files
|
||||
function folders(files) {
|
||||
return _.chain(files)
|
||||
.map(function(file) {
|
||||
return path.dirname(file);
|
||||
})
|
||||
.uniq()
|
||||
.value();
|
||||
}
|
||||
|
||||
function initDir(dir) {
|
||||
return fs.readFile(path.join(dir, 'SUMMARY.md'), 'utf8')
|
||||
.then(function(src) {
|
||||
// Parse summary
|
||||
return parse.summary(src);
|
||||
})
|
||||
.then(function(summary) {
|
||||
// Extract paths from summary
|
||||
return paths(summary);
|
||||
})
|
||||
.then(function(paths) {
|
||||
// Convert to absolute paths
|
||||
return _.map(paths, function(file) {
|
||||
return path.resolve(file);
|
||||
});
|
||||
})
|
||||
.then(function(files) {
|
||||
// Create folders
|
||||
return Q.all(_.map(folders(files), function(folder) {
|
||||
return fs.mkdirp(folder);
|
||||
}))
|
||||
.then(_.constant(files));
|
||||
})
|
||||
.then(function(files) {
|
||||
// Create files that don't exist
|
||||
return Q.all(_.map(files, function(file) {
|
||||
return fs.exists(file)
|
||||
.then(function(exists) {
|
||||
if(exists) return;
|
||||
return fs.writeFile(file, '');
|
||||
});
|
||||
}));
|
||||
})
|
||||
.fail(function(err) {
|
||||
console.error(err.stack);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
// Exports
|
||||
module.exports = initDir;
|
||||
@@ -1,47 +0,0 @@
|
||||
var util = require("util");
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
|
||||
var fs = require("../fs");
|
||||
var parse = require("../../parse");
|
||||
var BaseGenerator = require("../generator");
|
||||
|
||||
|
||||
var Generator = function() {
|
||||
BaseGenerator.apply(this, arguments);
|
||||
};
|
||||
util.inherits(Generator, BaseGenerator);
|
||||
|
||||
Generator.prototype.transferFile = function(input) {
|
||||
// ignore
|
||||
};
|
||||
|
||||
Generator.prototype.convertFile = function(content, input) {
|
||||
var that = this;
|
||||
var json = {
|
||||
progress: parse.progress(this.options.navigation, input)
|
||||
};
|
||||
|
||||
return Q()
|
||||
.then(function() {
|
||||
return parse.page(content, {
|
||||
repo: that.options.githubId,
|
||||
dir: path.dirname(input) || '/'
|
||||
});
|
||||
})
|
||||
.then(function(sections) {
|
||||
json.sections = sections;
|
||||
})
|
||||
.then(function() {
|
||||
return fs.writeFile(
|
||||
path.join(that.options.output, input.replace(".md", ".json")),
|
||||
JSON.stringify(json, null, 4)
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
Generator.prototype.finish = function() {
|
||||
// ignore
|
||||
};
|
||||
|
||||
module.exports = Generator;
|
||||
@@ -1,84 +0,0 @@
|
||||
var _ = require("lodash");
|
||||
var util = require("util");
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
var swig = require('swig');
|
||||
var hljs = require('highlight.js');
|
||||
|
||||
var fs = require("../fs");
|
||||
var parse = require("../../parse");
|
||||
var BaseGenerator = require("../site");
|
||||
|
||||
// Swig filter: highlight coloration
|
||||
swig.setFilter('code', function(code, lang) {
|
||||
try {
|
||||
return hljs.highlight(lang, code).value;
|
||||
} catch(e) {
|
||||
return hljs.highlightAuto(code).value;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
/*
|
||||
* This generator will generate a simple index.html which can be converted as a PDF
|
||||
*/
|
||||
var Generator = function() {
|
||||
BaseGenerator.apply(this, arguments);
|
||||
|
||||
// Load base template
|
||||
this.template = swig.compileFile(path.resolve(this.options.theme, 'templates/page.html'));
|
||||
|
||||
// List of pages content
|
||||
this.pages = {};
|
||||
};
|
||||
util.inherits(Generator, BaseGenerator);
|
||||
|
||||
Generator.prototype.convertFile = function(content, input) {
|
||||
var that = this;
|
||||
var json = {
|
||||
path: input,
|
||||
progress: parse.progress(this.options.navigation, input)
|
||||
};
|
||||
|
||||
return Q()
|
||||
.then(function() {
|
||||
return parse.page(content, {
|
||||
repo: that.options.githubId,
|
||||
dir: path.dirname(input) || '/',
|
||||
outdir: './',
|
||||
});
|
||||
})
|
||||
.then(function(sections) {
|
||||
json.content = sections;
|
||||
})
|
||||
.then(function() {
|
||||
that.pages[input] = json;
|
||||
});
|
||||
};
|
||||
|
||||
Generator.prototype.finish = function() {
|
||||
var that = this;
|
||||
var basePath = ".";
|
||||
var output = path.join(this.options.output, "index.html");
|
||||
|
||||
return Q()
|
||||
// Generate html
|
||||
.then(function(pages) {
|
||||
return that._writeTemplate(that.template, {
|
||||
pages: that.pages,
|
||||
|
||||
basePath: basePath,
|
||||
staticBase: path.join(basePath, "gitbook"),
|
||||
}, output);
|
||||
})
|
||||
|
||||
// Copy assets
|
||||
.then(function() {
|
||||
return fs.copy(
|
||||
path.join(that.options.theme, "assets"),
|
||||
path.join(that.options.output, "gitbook")
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = Generator;
|
||||
@@ -1,56 +0,0 @@
|
||||
var util = require("util");
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
var _ = require("lodash");
|
||||
var exec = require('child_process').exec;
|
||||
|
||||
var fs = require("../fs");
|
||||
var parse = require("../../parse");
|
||||
var BaseGenerator = require("../page");
|
||||
|
||||
/*
|
||||
* This generator inherits from the single page generator
|
||||
* and convert the page output to pdf using gitbook-pdf
|
||||
*/
|
||||
var Generator = function() {
|
||||
BaseGenerator.apply(this, arguments);
|
||||
|
||||
// Options for PDF generation
|
||||
this.options = _.defaults(this.options, {
|
||||
paperformat: "A4"
|
||||
});
|
||||
};
|
||||
util.inherits(Generator, BaseGenerator);
|
||||
|
||||
Generator.prototype.finish = function() {
|
||||
var that = this;
|
||||
|
||||
return BaseGenerator.prototype.finish.apply(this)
|
||||
.then(function() {
|
||||
var d = Q.defer();
|
||||
|
||||
var command = [
|
||||
"gitbook-pdf",
|
||||
"generate",
|
||||
path.join(that.options.output, "index.html"),
|
||||
path.join(that.options.output, "index.pdf"),
|
||||
"--format="+that.options.paperformat
|
||||
].join(" ");
|
||||
|
||||
exec(command, function (error, stdout, stderr) {
|
||||
if (error) {
|
||||
if (error.code == 127) {
|
||||
error.message = "Need to install gitbook-pdf using: npm install gitbook-pdf -g";
|
||||
} else {
|
||||
error.message = error.message + " "+stdout;
|
||||
}
|
||||
return d.reject(error);
|
||||
}
|
||||
d.resolve();
|
||||
});
|
||||
|
||||
return d.promise;
|
||||
});
|
||||
};
|
||||
|
||||
module.exports = Generator;
|
||||
@@ -1,156 +0,0 @@
|
||||
var util = require("util");
|
||||
var path = require("path");
|
||||
var Q = require("q");
|
||||
var _ = require("lodash");
|
||||
var swig = require('swig');
|
||||
|
||||
var fs = require("../fs");
|
||||
var parse = require("../../parse");
|
||||
var BaseGenerator = require("../generator");
|
||||
|
||||
var indexer = require('./search_indexer');
|
||||
|
||||
// Swig filter for returning the count of lines in a code section
|
||||
swig.setFilter('lines', function(content) {
|
||||
return content.split('\n').length;
|
||||
});
|
||||
|
||||
// Swig filter for returning a link to the associated html file of a markdown file
|
||||
swig.setFilter('mdLink', function(link) {
|
||||
var link = link.replace(".md", ".html");
|
||||
if (link == "README.html") link = "index.html";
|
||||
return link;
|
||||
});
|
||||
|
||||
var Generator = function() {
|
||||
BaseGenerator.apply(this, arguments);
|
||||
|
||||
// Attach methods to instance
|
||||
_.bindAll(this);
|
||||
|
||||
this.revision = Date.now();
|
||||
this.indexer = indexer();
|
||||
|
||||
// Load base template
|
||||
this.template = swig.compileFile(path.resolve(this.options.theme, 'templates/site.html'));
|
||||
this.langsTemplate = swig.compileFile(path.resolve(this.options.theme, 'templates/langs.html'));
|
||||
};
|
||||
util.inherits(Generator, BaseGenerator);
|
||||
|
||||
|
||||
// Generate a template
|
||||
Generator.prototype._writeTemplate = function(tpl, options, output) {
|
||||
var that = this;
|
||||
return Q()
|
||||
.then(function(sections) {
|
||||
return tpl(_.extend({
|
||||
revision: that.revision,
|
||||
|
||||
title: that.options.title,
|
||||
description: that.options.description,
|
||||
|
||||
githubAuthor: that.options.github ? that.options.github.split("/")[0] : "",
|
||||
githubId: that.options.github,
|
||||
githubHost: that.options.githubHost,
|
||||
|
||||
summary: that.options.summary,
|
||||
allNavigation: that.options.navigation
|
||||
}, options));
|
||||
})
|
||||
.then(function(html) {
|
||||
return fs.writeFile(
|
||||
output,
|
||||
html
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
Generator.prototype.indexPage = function(lexed, pagePath) {
|
||||
this.indexer.add(lexed, pagePath);
|
||||
return Q();
|
||||
};
|
||||
|
||||
// Convert a markdown file to html
|
||||
Generator.prototype.convertFile = function(content, _input) {
|
||||
var that = this;
|
||||
var progress = parse.progress(this.options.navigation, _input);
|
||||
|
||||
_output = _input.replace(".md", ".html");
|
||||
if (_output == "README.html") _output = "index.html";
|
||||
|
||||
var input = path.join(this.options.input, _input);
|
||||
var output = path.join(this.options.output, _output);
|
||||
var basePath = path.relative(path.dirname(output), this.options.output) || ".";
|
||||
|
||||
return Q()
|
||||
.then(function() {
|
||||
// Lex page
|
||||
return parse.lex(content);
|
||||
})
|
||||
.then(function(lexed) {
|
||||
// Index page in search
|
||||
return that.indexPage(lexed, _output)
|
||||
.then(_.constant(lexed));
|
||||
})
|
||||
.then(function(lexed) {
|
||||
// Get HTML generated sections
|
||||
return parse.page(lexed, {
|
||||
repo: that.options.githubId,
|
||||
dir: path.dirname(_input) || '/',
|
||||
outdir: path.dirname(_input) || '/',
|
||||
});
|
||||
})
|
||||
.then(function(sections) {
|
||||
return that._writeTemplate(that.template, {
|
||||
progress: progress,
|
||||
|
||||
_input: _input,
|
||||
content: sections,
|
||||
|
||||
basePath: basePath,
|
||||
staticBase: path.join(basePath, "gitbook"),
|
||||
}, output);
|
||||
});
|
||||
};
|
||||
|
||||
// Generate languages index
|
||||
Generator.prototype.langsIndex = function(langs) {
|
||||
var that = this;
|
||||
var basePath = ".";
|
||||
|
||||
return this._writeTemplate(this.langsTemplate, {
|
||||
langs: langs.list,
|
||||
|
||||
basePath: basePath,
|
||||
staticBase: path.join(basePath, "gitbook"),
|
||||
}, path.join(this.options.output, "index.html"))
|
||||
.then(function() {
|
||||
// Copy assets
|
||||
return that.copyAssets();
|
||||
});
|
||||
};
|
||||
|
||||
// Copy assets
|
||||
Generator.prototype.copyAssets = function() {
|
||||
var that = this;
|
||||
|
||||
return fs.copy(
|
||||
path.join(that.options.theme, "assets"),
|
||||
path.join(that.options.output, "gitbook")
|
||||
);
|
||||
};
|
||||
|
||||
// Dump search index to disk
|
||||
Generator.prototype.writeSearchIndex = function() {
|
||||
return fs.writeFile(
|
||||
path.join(this.options.output, 'search_index.json'),
|
||||
this.indexer.dump()
|
||||
);
|
||||
};
|
||||
|
||||
Generator.prototype.finish = function() {
|
||||
return this.copyAssets()
|
||||
.then(this.writeSearchIndex);
|
||||
};
|
||||
|
||||
module.exports = Generator;
|
||||
@@ -1,71 +0,0 @@
|
||||
var Q = require("q");
|
||||
var _ = require("lodash");
|
||||
|
||||
var lunr = require('lunr');
|
||||
var marked = require('marked');
|
||||
var textRenderer = require('marked-text-renderer');
|
||||
|
||||
|
||||
function Indexer() {
|
||||
if(!(this instanceof Indexer)) {
|
||||
return new Indexer();
|
||||
}
|
||||
|
||||
_.bindAll(this);
|
||||
|
||||
// Setup lunr index
|
||||
this.idx = lunr(function () {
|
||||
this.ref('url');
|
||||
|
||||
this.field('title', { boost: 10 });
|
||||
this.field('body');
|
||||
});
|
||||
|
||||
this.renderer = textRenderer();
|
||||
}
|
||||
|
||||
Indexer.prototype.text = function(nodes) {
|
||||
// Copy section
|
||||
var section = _.toArray(nodes);
|
||||
|
||||
// marked's Render expects this, we don't use it yet
|
||||
section.links = {};
|
||||
|
||||
var options = _.extend({}, marked.defaults, {
|
||||
renderer: this.renderer
|
||||
});
|
||||
|
||||
return marked.parser(section, options);
|
||||
};
|
||||
|
||||
Indexer.prototype.addSection = function(path, section) {
|
||||
var url = [path, section.id].join('#');
|
||||
|
||||
var title = this.text(
|
||||
_.filter(section, {'type': 'heading'})
|
||||
);
|
||||
|
||||
var body = this.text(
|
||||
_.omit(section, {'type': 'heading'})
|
||||
);
|
||||
|
||||
// Add to lunr index
|
||||
this.idx.add({
|
||||
url: url,
|
||||
title: title,
|
||||
body: body,
|
||||
});
|
||||
};
|
||||
|
||||
Indexer.prototype.add = function(lexedPage, url) {
|
||||
var sections = lexedPage;
|
||||
|
||||
_.map(sections, _.partial(this.addSection, url));
|
||||
};
|
||||
|
||||
Indexer.prototype.dump = function() {
|
||||
return JSON.stringify(this.idx);
|
||||
};
|
||||
|
||||
// Exports
|
||||
module.exports = Indexer;
|
||||
@@ -1,5 +0,0 @@
|
||||
module.exports = {
|
||||
parse: require('./parse/'),
|
||||
generate: require('./generate/')
|
||||
};
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
module.exports = {
|
||||
summary: require('./summary'),
|
||||
langs: require('./langs'),
|
||||
page: require('./page'),
|
||||
lex: require('./lex'),
|
||||
progress: require('./progress'),
|
||||
navigation: require('./navigation'),
|
||||
readme: require('./readme')
|
||||
};
|
||||
@@ -1,23 +0,0 @@
|
||||
var _ = require("lodash")
|
||||
var parseSummary = require("./summary");
|
||||
|
||||
var parseLangs = function(content) {
|
||||
var summary = parseSummary(content);
|
||||
|
||||
return {
|
||||
list: _.chain(summary.chapters)
|
||||
.filter(function(entry) {
|
||||
return entry.path != null;
|
||||
})
|
||||
.map(function(entry) {
|
||||
return {
|
||||
title: entry.title,
|
||||
path: entry.path,
|
||||
lang: entry.path.replace("/", "")
|
||||
};
|
||||
})
|
||||
.value()
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = parseLangs;
|
||||
@@ -1,125 +0,0 @@
|
||||
var _ = require('lodash');
|
||||
var marked = require('marked');
|
||||
|
||||
// Split a page up into sections (lesson, exercises, ...)
|
||||
function splitSections(nodes) {
|
||||
var section = [];
|
||||
|
||||
return _.reduce(nodes, function(sections, el) {
|
||||
if(el.type === 'hr') {
|
||||
sections.push(section);
|
||||
section = [];
|
||||
} else {
|
||||
section.push(el);
|
||||
}
|
||||
|
||||
return sections;
|
||||
}, []).concat([section]); // Add remaining nodes
|
||||
}
|
||||
|
||||
function isQuizNode(node) {
|
||||
return (/^[(\[][ x][)\]]/).test(node.text || node);
|
||||
}
|
||||
|
||||
function isExercise(nodes) {
|
||||
var codeType = { type: 'code' };
|
||||
|
||||
// Number of code nodes in section
|
||||
var len = _.filter(nodes, codeType).length;
|
||||
|
||||
return (
|
||||
// Got 3 or 4 code blocks
|
||||
(len === 3 || len === 4) &&
|
||||
// Ensure all nodes are at the end
|
||||
_.all(_.last(nodes, len), codeType)
|
||||
);
|
||||
}
|
||||
|
||||
function isQuiz(nodes) {
|
||||
if (nodes.length < 3) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Support having a first paragraph block
|
||||
// before our series of questions
|
||||
var quizNodes = nodes.slice(nodes[0].type === 'paragraph' ? 1 : 0);
|
||||
|
||||
// No questions
|
||||
if (!_.some(quizNodes, { type: 'blockquote_start' })) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if section has list of questions
|
||||
// or table of questions
|
||||
var listIdx = _.findIndex(quizNodes, { type: 'list_item_start' });
|
||||
var tableIdx = _.findIndex(quizNodes, { type: 'table' });
|
||||
|
||||
if(
|
||||
// List of questions
|
||||
listIdx !== -1 && isQuizNode(quizNodes[listIdx + 1]) ||
|
||||
|
||||
// Table of questions
|
||||
(
|
||||
tableIdx !== -1 &&
|
||||
_.every(quizNodes[tableIdx].cells[0].slice(1), isQuizNode)
|
||||
)
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
// What is the type of this section
|
||||
function sectionType(nodes, idx) {
|
||||
if(isExercise(nodes)) {
|
||||
return 'exercise';
|
||||
} else if(isQuiz(nodes)) {
|
||||
return 'quiz';
|
||||
}
|
||||
|
||||
return 'normal';
|
||||
}
|
||||
|
||||
// Generate a uniqueId to identify this section in our code
|
||||
function sectionId(section, idx) {
|
||||
return _.uniqueId('gitbook_');
|
||||
}
|
||||
|
||||
function lexPage(src) {
|
||||
// Lex file
|
||||
var nodes = marked.lexer(src);
|
||||
|
||||
return _.chain(splitSections(nodes))
|
||||
.map(function(section, idx) {
|
||||
// Detect section type
|
||||
section.type = sectionType(section, idx);
|
||||
return section;
|
||||
})
|
||||
.map(function(section, idx) {
|
||||
// Give each section an ID
|
||||
section.id = sectionId(section, idx);
|
||||
return section;
|
||||
|
||||
})
|
||||
.filter(function(section) {
|
||||
return !_.isEmpty(section);
|
||||
})
|
||||
.reduce(function(sections, section) {
|
||||
var last = _.last(sections);
|
||||
|
||||
// Merge normal sections together
|
||||
if(last && last.type === section.type && last.type === 'normal') {
|
||||
last.push.apply(last, [{'type': 'hr'}].concat(section));
|
||||
} else {
|
||||
// Add to list of sections
|
||||
sections.push(section);
|
||||
}
|
||||
|
||||
return sections;
|
||||
}, [])
|
||||
.value();
|
||||
}
|
||||
|
||||
// Exports
|
||||
module.exports = lexPage;
|
||||
@@ -1,70 +0,0 @@
|
||||
var _ = require('lodash');
|
||||
|
||||
// Cleans up an article/chapter object
|
||||
// remove 'articles' attributes
|
||||
function clean(obj) {
|
||||
return obj && _.omit(obj, ['articles']);
|
||||
}
|
||||
|
||||
function flattenChapters(chapters) {
|
||||
return _.reduce(chapters, function(accu, chapter) {
|
||||
return accu.concat([clean(chapter)].concat(chapter.articles));
|
||||
}, []);
|
||||
}
|
||||
|
||||
// Returns from a summary a map of
|
||||
/*
|
||||
{
|
||||
"file/path.md": {
|
||||
prev: ...,
|
||||
next: ...,
|
||||
},
|
||||
...
|
||||
}
|
||||
*/
|
||||
function navigation(summary, files) {
|
||||
// Support single files as well as list
|
||||
files = _.isArray(files) ? files : (_.isString(files) ? [files] : null);
|
||||
|
||||
// Special README nav
|
||||
var README_NAV = {
|
||||
path: 'README.md',
|
||||
title: 'Introduction',
|
||||
level: '0',
|
||||
};
|
||||
|
||||
// List of all navNodes
|
||||
var navNodes = [README_NAV].concat(flattenChapters(summary.chapters));
|
||||
var prevNodes = [null].concat(navNodes.slice(0, -1));
|
||||
var nextNodes = navNodes.slice(1).concat([null]);
|
||||
|
||||
// Mapping of prev/next for a give path
|
||||
var mapping = _.chain(_.zip(navNodes, prevNodes, nextNodes))
|
||||
.map(function(nodes) {
|
||||
var current = nodes[0], prev = nodes[1], next = nodes[2];
|
||||
|
||||
// Skip if no path
|
||||
if(!current.path) return null;
|
||||
|
||||
return [current.path, {
|
||||
title: current.title,
|
||||
prev: prev,
|
||||
next: next,
|
||||
level: current.level,
|
||||
}];
|
||||
})
|
||||
.filter()
|
||||
.object()
|
||||
.value();
|
||||
|
||||
// Filter for only files we want
|
||||
if(files) {
|
||||
return _.pick(mapping, files);
|
||||
}
|
||||
|
||||
return mapping;
|
||||
}
|
||||
|
||||
|
||||
// Exports
|
||||
module.exports = navigation;
|
||||
@@ -1,156 +0,0 @@
|
||||
var _ = require('lodash');
|
||||
var marked = require('marked');
|
||||
var hljs = require('highlight.js');
|
||||
|
||||
var lex = require('./lex');
|
||||
var renderer = require('./renderer');
|
||||
|
||||
var lnormalize = require('../utils/lang').normalize;
|
||||
|
||||
|
||||
|
||||
// Render a section using our custom renderer
|
||||
function render(section, _options) {
|
||||
// Copy section
|
||||
section = _.toArray(section);
|
||||
|
||||
// marked's Render expects this, we don't use it yet
|
||||
section.links = {};
|
||||
|
||||
// Build options using defaults and our custom renderer
|
||||
var options = _.extend({}, marked.defaults, {
|
||||
renderer: renderer(null, _options),
|
||||
|
||||
// Synchronous highlighting with highlight.js
|
||||
highlight: function (code, lang) {
|
||||
if(!lang) return code;
|
||||
|
||||
// Normalize lang
|
||||
lang = lnormalize(lang);
|
||||
|
||||
try {
|
||||
return hljs.highlight(lang, code).value;
|
||||
} catch(e) { }
|
||||
|
||||
return code;
|
||||
}
|
||||
});
|
||||
|
||||
return marked.parser(section, options);
|
||||
}
|
||||
|
||||
function quizQuestion(node) {
|
||||
if (node.text) {
|
||||
node.text = node.text.replace(/^([\[(])x([\])])/, "$1 $2");
|
||||
} else {
|
||||
return node.replace(/^([\[(])x([\])])/, "$1 $2");
|
||||
}
|
||||
}
|
||||
|
||||
function parsePage(src, options) {
|
||||
options = options || {};
|
||||
|
||||
// Lex if not already lexed
|
||||
return (_.isArray(src) ? src : lex(src))
|
||||
.map(function(section) {
|
||||
// Transform given type
|
||||
if(section.type === 'exercise') {
|
||||
var nonCodeNodes = _.reject(section, {
|
||||
'type': 'code'
|
||||
});
|
||||
|
||||
var codeNodes = _.filter(section, {
|
||||
'type': 'code'
|
||||
});
|
||||
|
||||
// Languages in code blocks
|
||||
var langs = _.pluck(codeNodes, 'lang').map(lnormalize);
|
||||
|
||||
// Check that they are all the same
|
||||
var validLangs = _.all(_.map(langs, function(lang) {
|
||||
return lang && lang === langs[0];
|
||||
}));
|
||||
|
||||
// Main language
|
||||
var lang = validLangs ? langs[0] : null;
|
||||
|
||||
return {
|
||||
id: section.id,
|
||||
type: section.type,
|
||||
content: render(nonCodeNodes),
|
||||
lang: lang,
|
||||
code: {
|
||||
base: codeNodes[0].text,
|
||||
solution: codeNodes[1].text,
|
||||
validation: codeNodes[2].text,
|
||||
// Context is optional
|
||||
context: codeNodes[3] ? codeNodes[3].text : null,
|
||||
}
|
||||
};
|
||||
} else if (section.type === 'quiz') {
|
||||
var quiz = [], question, foundFeedback = false;
|
||||
var nonQuizNodes = section[0].type === 'paragraph' && section[1].type !== 'list_start' ? [section[0]] : [];
|
||||
var quizNodes = section.slice(0);
|
||||
quizNodes.splice(0, nonQuizNodes.length);
|
||||
|
||||
for (var i = 0; i < quizNodes.length; i++) {
|
||||
var node = quizNodes[i];
|
||||
|
||||
if (question && (((node.type === 'list_end' || node.type === 'blockquote_end') && i === quizNodes.length - 1)
|
||||
|| node.type === 'table' || (node.type === 'paragraph' && !foundFeedback))) {
|
||||
quiz.push({
|
||||
base: render(question.questionNodes),
|
||||
solution: render(question.solutionNodes),
|
||||
feedback: render(question.feedbackNodes)
|
||||
});
|
||||
}
|
||||
|
||||
if (node.type === 'table' || (node.type === 'paragraph' && !foundFeedback)) {
|
||||
question = { questionNodes: [], solutionNodes: [], feedbackNodes: [] };
|
||||
}
|
||||
|
||||
if (node.type === 'blockquote_start') {
|
||||
foundFeedback = true;
|
||||
} else if (node.type === 'blockquote_end') {
|
||||
foundFeedback = false;
|
||||
}
|
||||
|
||||
if (node.type === 'table') {
|
||||
question.solutionNodes.push(_.cloneDeep(node));
|
||||
node.cells = node.cells.map(function(row) {
|
||||
return row.map(quizQuestion);
|
||||
});
|
||||
question.questionNodes.push(node);
|
||||
} else if (!/blockquote/.test(node.type)) {
|
||||
if (foundFeedback) {
|
||||
question.feedbackNodes.push(node);
|
||||
} else if (node.type === 'paragraph' || node.type === 'text'){
|
||||
question.solutionNodes.push(_.cloneDeep(node));
|
||||
quizQuestion(node);
|
||||
question.questionNodes.push(node);
|
||||
} else {
|
||||
question.solutionNodes.push(node);
|
||||
question.questionNodes.push(node);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id: section.id,
|
||||
type: section.type,
|
||||
content: render(nonQuizNodes),
|
||||
quiz: quiz
|
||||
};
|
||||
}
|
||||
|
||||
// Render normal pages
|
||||
return {
|
||||
id: section.id,
|
||||
type: section.type,
|
||||
content: render(section, options)
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// Exports
|
||||
module.exports = parsePage;
|
||||
@@ -1,50 +0,0 @@
|
||||
var _ = require("lodash");
|
||||
|
||||
// Returns from a navigation and a current file, a snapshot of current detailed state
|
||||
var calculProgress = function(navigation, current) {
|
||||
var n = _.size(navigation);
|
||||
var percent = 0, prevPercent = 0, currentChapter = null;
|
||||
var done = true;
|
||||
|
||||
var chapters = _.chain(navigation)
|
||||
.map(function(nav, path) {
|
||||
nav.path = path;
|
||||
return nav;
|
||||
})
|
||||
.sortBy(function(nav) {
|
||||
return nav.level;
|
||||
})
|
||||
.map(function(nav, i) {
|
||||
// Calcul percent
|
||||
nav.percent = (i * 100) / Math.max((n - 1), 1);
|
||||
|
||||
// Is it done
|
||||
nav.done = done;
|
||||
if (nav.path == current) {
|
||||
currentChapter = nav;
|
||||
percent = nav.percent;
|
||||
done = false;
|
||||
} else if (done) {
|
||||
prevPercent = nav.percent;
|
||||
}
|
||||
|
||||
return nav;
|
||||
})
|
||||
.value();
|
||||
|
||||
return {
|
||||
// Previous percent
|
||||
prevPercent: prevPercent,
|
||||
|
||||
// Current percent
|
||||
percent: percent,
|
||||
|
||||
// List of chapter with progress
|
||||
chapters: chapters,
|
||||
|
||||
// Current chapter
|
||||
current: currentChapter
|
||||
};
|
||||
}
|
||||
|
||||
module.exports = calculProgress;
|
||||
@@ -1,32 +0,0 @@
|
||||
var _ = require('lodash');
|
||||
var marked = require('marked');
|
||||
|
||||
function extractFirstNode(nodes, nType) {
|
||||
return _.chain(nodes)
|
||||
.filter(function(node) {
|
||||
return node.type == nType;
|
||||
})
|
||||
.pluck("text")
|
||||
.first()
|
||||
.value();
|
||||
}
|
||||
|
||||
|
||||
function parseReadme(src) {
|
||||
var nodes, title, description;
|
||||
|
||||
// Parse content
|
||||
nodes = marked.lexer(src);
|
||||
|
||||
var title = extractFirstNode(nodes, "heading");
|
||||
var description = extractFirstNode(nodes, "paragraph");
|
||||
|
||||
return {
|
||||
title: title,
|
||||
description: description
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
// Exports
|
||||
module.exports = parseReadme;
|
||||
@@ -1,121 +0,0 @@
|
||||
var url = require('url');
|
||||
var inherits = require('util').inherits;
|
||||
|
||||
var path = require('path');
|
||||
|
||||
var marked = require('marked');
|
||||
|
||||
var rendererId = 0;
|
||||
|
||||
function GitBookRenderer(options, extra_options) {
|
||||
if(!(this instanceof GitBookRenderer)) {
|
||||
return new GitBookRenderer(options, extra_options);
|
||||
}
|
||||
GitBookRenderer.super_.call(this, options);
|
||||
|
||||
this._extra_options = extra_options;
|
||||
this.quizRowId = 0;
|
||||
this.id = rendererId++;
|
||||
}
|
||||
inherits(GitBookRenderer, marked.Renderer);
|
||||
|
||||
GitBookRenderer.prototype._unsanitized = function(href) {
|
||||
var prot = '';
|
||||
try {
|
||||
prot = decodeURIComponent(unescape(href))
|
||||
.replace(/[^\w:]/g, '')
|
||||
.toLowerCase();
|
||||
|
||||
} catch (e) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if(prot.indexOf('javascript:') === 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
GitBookRenderer.prototype.link = function(href, title, text) {
|
||||
// Don't build if it looks malicious
|
||||
if (this.options.sanitize && this._unsanitized(href)) {
|
||||
return '';
|
||||
}
|
||||
|
||||
// Parsed version of the url
|
||||
var parsed = url.parse(href);
|
||||
|
||||
var o = this._extra_options;
|
||||
// Relative link, rewrite it to point to github repo
|
||||
if(!parsed.protocol && parsed.path && parsed.path[0] != '/' && o && o.repo && o.dir) {
|
||||
href = url.resolve('https://github.com/' + o.repo + '/blob/', [o.dir, href].join("/"));
|
||||
parsed = url.parse(href);
|
||||
}
|
||||
|
||||
// Generate HTML for link
|
||||
var out = '<a href="' + parsed.href + '"';
|
||||
// Title if no null
|
||||
if (title) {
|
||||
out += ' title="' + title + '"';
|
||||
}
|
||||
// Target blank if external
|
||||
if(parsed.protocol) {
|
||||
out += ' target="_blank"';
|
||||
}
|
||||
out += '>' + text + '</a>';
|
||||
return out;
|
||||
};
|
||||
|
||||
GitBookRenderer.prototype.image = function(href, title, text) {
|
||||
// Our "fixed" href
|
||||
var _href = href;
|
||||
|
||||
// Parsed version of the url
|
||||
var parsed = url.parse(href);
|
||||
|
||||
// Options
|
||||
var o = this._extra_options;
|
||||
|
||||
// Relative image, rewrite it depending output
|
||||
if(!parsed.protocol && parsed.path && parsed.path[0] != '/' && o && o.dir && o.outdir) {
|
||||
// o.dir: directory parent of the file currently in rendering process
|
||||
// o.outdir: directory parent from the html output
|
||||
|
||||
// Absolute file in source
|
||||
_href = path.join(o.dir, _href);
|
||||
|
||||
// make it relative to output
|
||||
_href = path.relative(o.outdir, _href);
|
||||
}
|
||||
|
||||
return GitBookRenderer.super_.prototype.image.call(this, _href, title, text);
|
||||
};
|
||||
|
||||
GitBookRenderer.prototype.tablerow = function(content) {
|
||||
this.quizRowId += 1;
|
||||
return GitBookRenderer.super_.prototype.tablerow(content);
|
||||
};
|
||||
|
||||
var fieldRegex = /^([(\[])([ x])[\])]/;
|
||||
GitBookRenderer.prototype._createCheckboxAndRadios = function(text) {
|
||||
var match = fieldRegex.exec(text);
|
||||
if (!match) {
|
||||
return text;
|
||||
}
|
||||
var field = "<input name='quiz-row-" + this.id + "-" + this.quizRowId + "' type='";
|
||||
field += match[1] === '(' ? "radio" : "checkbox";
|
||||
field += match[2] === 'x' ? "' checked/>" : "'/>";
|
||||
return text.replace(fieldRegex, field);
|
||||
}
|
||||
|
||||
GitBookRenderer.prototype.tablecell = function(content, flags) {
|
||||
return GitBookRenderer.super_.prototype.tablecell(this._createCheckboxAndRadios(content), flags);
|
||||
};
|
||||
|
||||
GitBookRenderer.prototype.listitem = function(text) {
|
||||
return GitBookRenderer.super_.prototype.listitem(this._createCheckboxAndRadios(text));
|
||||
};
|
||||
|
||||
// Exports
|
||||
module.exports = GitBookRenderer;
|
||||
@@ -1,117 +0,0 @@
|
||||
var _ = require('lodash');
|
||||
var marked = require('marked');
|
||||
|
||||
|
||||
// Utility function for splitting a list into groups
|
||||
function splitBy(list, starter, ender) {
|
||||
var starts = 0;
|
||||
var ends = 0;
|
||||
var group = [];
|
||||
|
||||
// Groups
|
||||
return _.reduce(list, function(groups, value) {
|
||||
// Ignore start and end delimiters in resulted groups
|
||||
if(starter(value)) {
|
||||
starts++;
|
||||
} else if(ender(value)) {
|
||||
ends++;
|
||||
}
|
||||
|
||||
// Add current value to group
|
||||
group.push(value);
|
||||
|
||||
// We've got a matching
|
||||
if(starts === ends && starts !== 0) {
|
||||
// Add group to end groups
|
||||
// (remove starter and ender token)
|
||||
groups.push(group.slice(1, -1));
|
||||
|
||||
// Reset group
|
||||
group = [];
|
||||
}
|
||||
|
||||
return groups;
|
||||
}, []);
|
||||
}
|
||||
|
||||
function listSplit(nodes, start_type, end_type) {
|
||||
return splitBy(nodes, function(el) {
|
||||
return el.type === start_type;
|
||||
}, function(el) {
|
||||
return el.type === end_type;
|
||||
});
|
||||
}
|
||||
|
||||
// Get the biggest list
|
||||
// out of a list of marked nodes
|
||||
function filterList(nodes) {
|
||||
return _.chain(nodes)
|
||||
.toArray()
|
||||
.rest(function(el) {
|
||||
// Get everything after list_start
|
||||
return el.type !== 'list_start';
|
||||
})
|
||||
.reverse()
|
||||
.rest(function(el) {
|
||||
// Get everything after list_end (remember we're reversed)
|
||||
return el.type !== 'list_end';
|
||||
})
|
||||
.reverse()
|
||||
.value().slice(1, -1);
|
||||
}
|
||||
|
||||
// Parses an Article or Chapter title
|
||||
// supports extracting links
|
||||
function parseTitle(src, nums) {
|
||||
// Check if it's a link
|
||||
var matches = marked.InlineLexer.rules.link.exec(src);
|
||||
|
||||
var level = nums.join('.');
|
||||
|
||||
// Not a link, return plain text
|
||||
if(!matches) {
|
||||
return {
|
||||
title: src,
|
||||
level: level,
|
||||
path: null,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
title: matches[1],
|
||||
level: level,
|
||||
|
||||
// Replace .md references with .html
|
||||
path: matches[2],
|
||||
};
|
||||
}
|
||||
|
||||
function parseArticle(chapterNum, nodes, idx) {
|
||||
return parseTitle(_.first(nodes).text, [chapterNum, idx+1]);
|
||||
}
|
||||
|
||||
function parseChapter(nodes, idx) {
|
||||
return _.extend(parseTitle(_.first(nodes).text, [idx+1]), {
|
||||
articles: _.map(listSplit(filterList(nodes), 'list_item_start', 'list_item_end'), parseArticle.bind(null, idx+1))
|
||||
});
|
||||
}
|
||||
|
||||
function parseSummary(src) {
|
||||
var nodes = marked.lexer(src);
|
||||
|
||||
// Get out list of chapters
|
||||
var chapterList = filterList(nodes);
|
||||
|
||||
// Split out chapter sections
|
||||
var chapters = _.chain(listSplit(chapterList, 'list_item_start', 'list_item_end'))
|
||||
.map(parseChapter)
|
||||
.value();
|
||||
|
||||
return {
|
||||
chapters: chapters
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
// Exports
|
||||
module.exports = parseSummary;
|
||||
@@ -1,3 +0,0 @@
|
||||
module.exports = {
|
||||
lang: require('./lang'),
|
||||
};
|
||||
@@ -1,18 +0,0 @@
|
||||
var MAP = {
|
||||
'py': 'python',
|
||||
'js': 'javascript',
|
||||
'rb': 'ruby',
|
||||
};
|
||||
|
||||
function normalize(lang) {
|
||||
if(!lang) { return null; }
|
||||
|
||||
var lower = lang.toLowerCase();
|
||||
return MAP[lower] || lower;
|
||||
}
|
||||
|
||||
// Exports
|
||||
module.exports = {
|
||||
normalize: normalize,
|
||||
MAP: MAP
|
||||
};
|
||||
+21
-52
@@ -1,58 +1,27 @@
|
||||
{
|
||||
"name": "gitbook",
|
||||
"version": "0.2.3",
|
||||
"homepage": "http://www.gitbook.io/",
|
||||
"description": "Library and cmd utility to generate GitBooks",
|
||||
"main": "lib/index.js",
|
||||
"dependencies": {
|
||||
"q": "1.0.1",
|
||||
"lodash": "2.4.1",
|
||||
"marked": "0.3.2",
|
||||
"marked-text-renderer": "0.0.1",
|
||||
"lunr": "0.5.2",
|
||||
"swig": "1.3.2",
|
||||
"send": "0.2.0",
|
||||
"fstream-ignore": "0.0.7",
|
||||
"commander": "2.2.0",
|
||||
"fs-extra": "0.8.1",
|
||||
"highlight.js": "8.0.0",
|
||||
"tmp": "0.0.23"
|
||||
},
|
||||
"devDependencies": {
|
||||
"mocha": "1.18.2",
|
||||
"grunt": "~0.4.2",
|
||||
"grunt-cli": "0.1.11",
|
||||
"grunt-contrib-less": "~0.5.0",
|
||||
"grunt-contrib-requirejs": "0.4.1"
|
||||
},
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"packageManager": "bun@1.1.18",
|
||||
"scripts": {
|
||||
"test": "export TESTING=true; mocha --reporter list"
|
||||
"dev": "turbo run dev",
|
||||
"build": "turbo run build",
|
||||
"build:cloudflare": "turbo run build:cloudflare",
|
||||
"lint": "turbo run lint",
|
||||
"typecheck": "turbo run typecheck",
|
||||
"format": "prettier ./ --ignore-unknown --write",
|
||||
"format:check": "prettier ./ --ignore-unknown --list-different",
|
||||
"unit": "turbo run unit",
|
||||
"e2e": "turbo run e2e",
|
||||
"changeset": "changeset",
|
||||
"release": "turbo run build && changeset publish"
|
||||
},
|
||||
"bin": {
|
||||
"gitbook": "./bin/gitbook.js"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/GitbookIO/gitbook.git"
|
||||
},
|
||||
"keywords": [
|
||||
"git",
|
||||
"book",
|
||||
"gitbook"
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
],
|
||||
"author": "FriendCode <contact@friendco.de>",
|
||||
"license": "Apache 2",
|
||||
"bugs": {
|
||||
"url": "https://github.com/GitbookIO/gitbook/issues"
|
||||
},
|
||||
"contributors": [
|
||||
{
|
||||
"name": "Aaron O'Mullan",
|
||||
"email": "aaron.omullan@gmail.com"
|
||||
},
|
||||
{
|
||||
"name": "Samy Pessé",
|
||||
"email": "samypesse@gmail.com"
|
||||
}
|
||||
]
|
||||
"devDependencies": {
|
||||
"@changesets/cli": "^2.27.7",
|
||||
"prettier": "^3.0.3",
|
||||
"turbo": "^2.0.9"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
index.ts
|
||||
@@ -0,0 +1,13 @@
|
||||
# @gitbook/emoji-codepoints
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 57adb3e: Second release to fix publishing with changeset
|
||||
|
||||
## 0.1.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- 5f8a8fe: Initial release
|
||||
@@ -0,0 +1,26 @@
|
||||
import fs from 'fs';
|
||||
import emojisRaws from 'emoji-assets/emoji.json';
|
||||
|
||||
interface EmojiData {
|
||||
code_points: {
|
||||
base: string;
|
||||
fully_qualified: string;
|
||||
};
|
||||
}
|
||||
|
||||
const emojis = emojisRaws as Record<string, EmojiData>;
|
||||
const output: Record<string, string> = {};
|
||||
|
||||
Object.entries(emojis).forEach(([key, value]) => {
|
||||
const emoji = value.code_points?.fully_qualified;
|
||||
if (emoji && key !== emoji) {
|
||||
output[key] = emoji;
|
||||
} else if (!emoji) {
|
||||
console.log('No emoji for', key);
|
||||
}
|
||||
});
|
||||
|
||||
fs.writeFileSync(
|
||||
'index.ts',
|
||||
`export const emojiCodepoints: Record<string, string> = ${JSON.stringify(output, null, 4)};`,
|
||||
);
|
||||
@@ -0,0 +1,14 @@
|
||||
{
|
||||
"name": "@gitbook/emoji-codepoints",
|
||||
"description": "Optimized mapping of codepoints to the fully qualified emoji codepoints",
|
||||
"version": "0.2.0",
|
||||
"private": true,
|
||||
"exports": "./index.ts",
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"emoji-assets": "^8.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"postinstall": "bun ./build.ts"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
# Configurations
|
||||
|
||||
### API ###
|
||||
|
||||
## API token to use when looking up the published content
|
||||
# GITBOOK_API_URL=https://api.gitbook.com
|
||||
# GITBOOK_TOKEN=xxx
|
||||
|
||||
## User agent to use when making requests to the API
|
||||
# GITBOOK_USER_AGENT=GitBook/1.0.0
|
||||
# GITBOOK_USER_AGENT_COMMENT=something
|
||||
|
||||
### URL of the application ###
|
||||
# NEXT_PUBLIC_GITBOOK_APP_URL=https://app.gitbook.com
|
||||
|
||||
### Image resizing ###
|
||||
# GITBOOK_IMAGE_RESIZE_SIGNING_KEY=1234567890
|
||||
# GITBOOK_IMAGE_RESIZE_URL=https://mycompany.com/cdn-cgi/image/
|
||||
|
||||
### SEO ###
|
||||
# GITBOOK_BLOCK_SEARCH_INDEXATION=true
|
||||
|
||||
## Caching
|
||||
# GITBOOK_OUTPUT_CACHE=true
|
||||
|
||||
### Sentry ###
|
||||
# SENTRY_DSN=xxx
|
||||
@@ -0,0 +1,31 @@
|
||||
{
|
||||
"extends": "next/core-web-vitals",
|
||||
"plugins": ["import"],
|
||||
"rules": {
|
||||
"import/order": [
|
||||
"error",
|
||||
{
|
||||
"groups": ["builtin", "external", ["internal", "parent", "sibling", "index"]],
|
||||
"newlines-between": "always",
|
||||
"distinctGroup": true,
|
||||
"pathGroups": [
|
||||
{
|
||||
"pattern": "@/**",
|
||||
"group": "external",
|
||||
"position": "after"
|
||||
},
|
||||
{
|
||||
"pattern": "@gitbook/**",
|
||||
"group": "external",
|
||||
"position": "after"
|
||||
}
|
||||
],
|
||||
"alphabetize": {
|
||||
"order": "asc",
|
||||
"caseInsensitive": true
|
||||
}
|
||||
}
|
||||
],
|
||||
"@next/next/no-img-element": ["off"]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
|
||||
|
||||
# testing
|
||||
/coverage
|
||||
|
||||
# next.js
|
||||
/.next/
|
||||
/out/
|
||||
|
||||
# production
|
||||
/build
|
||||
|
||||
# local env files
|
||||
.env*.local
|
||||
|
||||
# vercel
|
||||
.vercel
|
||||
|
||||
# typescript
|
||||
*.tsbuildinfo
|
||||
next-env.d.ts
|
||||
|
||||
# visual tests
|
||||
screenshots/
|
||||
|
||||
# Sentry Config File
|
||||
.sentryclirc
|
||||
|
||||
/test-results/
|
||||
/playwright-report/
|
||||
/blob-report/
|
||||
/playwright/.cache/
|
||||
|
||||
# Generated public files
|
||||
/public/~gitbook/static/
|
||||
@@ -0,0 +1,24 @@
|
||||
# gitbook
|
||||
|
||||
## 0.2.1
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [24cd72e]
|
||||
- @gitbook/react-contentkit@0.4.0
|
||||
- @gitbook/react-math@0.4.0
|
||||
- @gitbook/react-openapi@0.4.0
|
||||
|
||||
## 0.2.0
|
||||
|
||||
### Minor Changes
|
||||
|
||||
- de747b7: Refactor the repository to be a proper monorepo and publish JS files on NPM instead of TypeScript files.
|
||||
|
||||
### Patch Changes
|
||||
|
||||
- Updated dependencies [de747b7]
|
||||
- Updated dependencies [de747b7]
|
||||
- @gitbook/react-contentkit@0.3.0
|
||||
- @gitbook/react-openapi@0.3.0
|
||||
- @gitbook/react-math@0.3.0
|
||||
@@ -0,0 +1,668 @@
|
||||
import { argosScreenshot } from '@argos-ci/playwright';
|
||||
import {
|
||||
CustomizationHeaderPreset,
|
||||
CustomizationLocale,
|
||||
CustomizationSettings,
|
||||
} from '@gitbook/api';
|
||||
import { test, expect, Page } from '@playwright/test';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import rison from 'rison';
|
||||
|
||||
import { getContentTestURL } from '../tests/utils';
|
||||
|
||||
interface Test {
|
||||
name: string;
|
||||
url: string;
|
||||
run?: (page: Page) => Promise<unknown>;
|
||||
fullPage?: boolean;
|
||||
screenshot?: false;
|
||||
}
|
||||
|
||||
interface TestsCase {
|
||||
name: string;
|
||||
baseUrl: string;
|
||||
tests: Array<Test>;
|
||||
}
|
||||
|
||||
const allLocales: CustomizationLocale[] = [
|
||||
CustomizationLocale.Fr,
|
||||
CustomizationLocale.Es,
|
||||
CustomizationLocale.Ja,
|
||||
CustomizationLocale.Zh,
|
||||
];
|
||||
|
||||
async function waitForCookiesDialog(page: Page) {
|
||||
const dialog = page.getByRole('dialog', { name: 'Cookies' });
|
||||
const accept = dialog.getByRole('button', { name: 'Accept' });
|
||||
const reject = dialog.getByRole('button', { name: 'Reject' });
|
||||
await expect(accept).toBeVisible();
|
||||
await expect(reject).toBeVisible();
|
||||
}
|
||||
|
||||
const testCases: TestsCase[] = [
|
||||
{
|
||||
name: 'GitBook Site (Single Variant)',
|
||||
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/gitbook-doc/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Home',
|
||||
url: '',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'No variants dropdown',
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
await expect(page.locator('[data-testid="space-dropdown-button"]')).toHaveCount(
|
||||
0,
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Search',
|
||||
url: '?q=',
|
||||
},
|
||||
{
|
||||
name: 'Search Results',
|
||||
url: '?q=gitbook',
|
||||
run: async (page) => {
|
||||
await page.waitForSelector('[data-test="search-results"]');
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'AI Search',
|
||||
url: '?q=What+is+GitBook%3F&ask=true',
|
||||
run: async (page) => {
|
||||
await page.waitForSelector('[data-test="search-ask-answer"]');
|
||||
},
|
||||
screenshot: false,
|
||||
},
|
||||
{
|
||||
name: 'Not found',
|
||||
url: 'content-not-found',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'GitBook Site (Multi Variants)',
|
||||
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/multi-variants/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Variants dropdown',
|
||||
url: '',
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = page.locator('[data-testid="space-dropdown-button"]');
|
||||
await spaceDrowpdown.waitFor();
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Default variant',
|
||||
url: '',
|
||||
},
|
||||
{
|
||||
name: 'RFC variant',
|
||||
url: 'v/rfcs',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'GitBook Site (Navigation when switching variant)',
|
||||
baseUrl: 'https://gitbook-open-e2e-sites.gitbook.io/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Keep navigation path/route when switching variant (Public)',
|
||||
url: 'api-multi-versions/reference/api-reference/pets',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
await page
|
||||
.getByRole('link', {
|
||||
name: '2.0',
|
||||
})
|
||||
.click();
|
||||
|
||||
// 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',
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Keep navigation path/route when switching variant (Share link)',
|
||||
url: 'api-multi-versions-share-links/bRfQbzwsK8rbN1GRxx7K/reference/api-reference/pets',
|
||||
screenshot: false,
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
await page
|
||||
.getByRole('link', {
|
||||
name: '2.0',
|
||||
})
|
||||
.click();
|
||||
|
||||
// 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',
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'Keep navigation path/route when switching variant (VA)',
|
||||
screenshot: false,
|
||||
url: (() => {
|
||||
const privateKey = 'c26190fc-74b2-4b54-9fc7-df9941104953';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `api-multi-versions-va/reference/api-reference/pets?jwt_token=${token}`;
|
||||
})(),
|
||||
run: async (page) => {
|
||||
const spaceDrowpdown = await page.waitForSelector(
|
||||
'[data-testid="space-dropdown-button"]',
|
||||
);
|
||||
await spaceDrowpdown.click();
|
||||
|
||||
// Click the second variant in the dropdown
|
||||
await page
|
||||
.getByRole('link', {
|
||||
name: '2.0',
|
||||
})
|
||||
.click();
|
||||
|
||||
// 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',
|
||||
);
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'GitBook',
|
||||
baseUrl: 'https://docs.gitbook.com',
|
||||
tests: [
|
||||
{
|
||||
name: 'Home',
|
||||
url: '',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Search',
|
||||
url: '?q=',
|
||||
},
|
||||
{
|
||||
name: 'Search Results',
|
||||
url: '?q=gitbook',
|
||||
run: async (page) => {
|
||||
await page.waitForSelector('[data-test="search-results"]');
|
||||
},
|
||||
},
|
||||
{
|
||||
name: 'AI Search',
|
||||
url: '?q=What+is+GitBook%3F&ask=true',
|
||||
run: async (page) => {
|
||||
await page.waitForSelector('[data-test="search-ask-answer"]');
|
||||
},
|
||||
screenshot: false,
|
||||
},
|
||||
{
|
||||
name: 'Not found',
|
||||
url: 'content-not-found',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Versioning',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-1-1/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Revision',
|
||||
url: '~/revisions/S55pwsEr5UVoroaOiWnP/blocks/headings',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'PDF',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-1-1/',
|
||||
tests: [
|
||||
{
|
||||
name: 'PDF',
|
||||
url: '~gitbook/pdf?limit=10',
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Content tests',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-1-1/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Text',
|
||||
url: 'text-page',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Long text',
|
||||
url: 'text-page/long-text',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Images',
|
||||
url: 'blocks/block-images',
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Inline Images',
|
||||
url: 'blocks/inline-images',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Tabs',
|
||||
url: 'blocks/tabs',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Hints',
|
||||
url: 'blocks/hints',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Integration Blocks',
|
||||
url: 'blocks/integrations',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Tables',
|
||||
url: 'blocks/tables',
|
||||
run: waitForCookiesDialog,
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Expandables',
|
||||
url: 'blocks/expandables',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'API Blocks',
|
||||
url: 'blocks/api-blocks',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Headings',
|
||||
url: 'blocks/headings',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Marks',
|
||||
url: 'blocks/marks',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Emojis',
|
||||
url: 'blocks/emojis',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Links',
|
||||
url: 'blocks/links',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Lists',
|
||||
url: 'blocks/lists',
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Code',
|
||||
url: 'blocks/code',
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Cards',
|
||||
url: 'blocks/cards',
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Math',
|
||||
url: 'blocks/math',
|
||||
},
|
||||
{
|
||||
name: 'Embeds',
|
||||
url: 'blocks/embeds',
|
||||
fullPage: true,
|
||||
},
|
||||
{
|
||||
name: 'Annotations',
|
||||
url: 'blocks/annotations',
|
||||
run: async (page) => {
|
||||
await page.waitForSelector('[data-testid="annotation-button"]');
|
||||
await page.click('[data-testid="annotation-button"]');
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Page options',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-1-1/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Hidden',
|
||||
url: 'page-options/page-hidden',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'With cover',
|
||||
url: 'page-options/page-with-cover',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'With hero cover',
|
||||
url: 'page-options/page-with-hero-cover',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'With cover and no TOC',
|
||||
url: 'page-options/page-with-cover-and-no-toc',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Customization',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-1-1/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Without header',
|
||||
url: getCustomizationURL({
|
||||
header: {
|
||||
preset: CustomizationHeaderPreset.None,
|
||||
links: [],
|
||||
},
|
||||
}),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Share links',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-share-links/',
|
||||
tests: [
|
||||
{
|
||||
name: 'Valid link',
|
||||
url: 'Fc6mMII9FKgnwm7qqynx/',
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Invalid link',
|
||||
url: 'invalid/',
|
||||
run: async (page) => {
|
||||
await expect(
|
||||
page.getByText('Authentication missing to access this content'),
|
||||
).toBeVisible();
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Visitor Auth - Space',
|
||||
baseUrl: `https://gitbook.gitbook.io/gbo-va-space/`,
|
||||
tests: [
|
||||
{
|
||||
name: 'First',
|
||||
url: (() => {
|
||||
const privateKey = '70b844d0-c519-4532-8586-5970ce48c537';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `first?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Second',
|
||||
url: (() => {
|
||||
const privateKey = '70b844d0-c519-4532-8586-5970ce48c537';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `second?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Visitor Auth - Collection',
|
||||
baseUrl: `https://gitbook.gitbook.io/gbo-va-collection/`,
|
||||
tests: [
|
||||
{
|
||||
name: 'Root',
|
||||
url: (() => {
|
||||
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Primary (Space A)',
|
||||
url: (() => {
|
||||
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `v/spacea?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Space B',
|
||||
url: (() => {
|
||||
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `v/spaceb?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Space C',
|
||||
url: (() => {
|
||||
const privateKey = 'af5688dc-f0b6-4146-9b1d-6d834c62c980';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `v/spacec?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Visitor Auth - Space (custom domain)',
|
||||
baseUrl: `https://test.gitbook.community/`,
|
||||
tests: [
|
||||
{
|
||||
name: 'Root',
|
||||
url: (() => {
|
||||
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'First',
|
||||
url: (() => {
|
||||
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `first?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Custom page',
|
||||
url: (() => {
|
||||
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `custom-page?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
{
|
||||
name: 'Inner page',
|
||||
url: (() => {
|
||||
const privateKey = '19c8166f-c436-4ed1-a24e-60954b804021';
|
||||
const token = jwt.sign(
|
||||
{
|
||||
name: 'gitbook-open-tests',
|
||||
},
|
||||
privateKey,
|
||||
{
|
||||
expiresIn: '24h',
|
||||
},
|
||||
);
|
||||
return `custom-page/inner-page?jwt_token=${token}`;
|
||||
})(),
|
||||
run: waitForCookiesDialog,
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
name: 'Languages',
|
||||
baseUrl: 'https://gitbook.gitbook.io/test-1-1/',
|
||||
tests: allLocales.map((locale) => ({
|
||||
name: locale,
|
||||
url: getCustomizationURL({
|
||||
internationalization: {
|
||||
locale,
|
||||
inherit: false,
|
||||
},
|
||||
}),
|
||||
run: async (page) => {
|
||||
const dialog = page.getByTestId('cookies-dialog');
|
||||
await expect(dialog).toBeVisible();
|
||||
},
|
||||
})),
|
||||
},
|
||||
];
|
||||
|
||||
for (const testCase of testCases) {
|
||||
test.describe(testCase.name, () => {
|
||||
for (const testEntry of testCase.tests) {
|
||||
test(testEntry.name, async ({ page, baseURL }) => {
|
||||
const contentUrl = new URL(testEntry.url, testCase.baseUrl);
|
||||
const url = getContentTestURL(contentUrl.toString(), baseURL);
|
||||
await page.goto(url);
|
||||
if (testEntry.run) {
|
||||
await testEntry.run(page);
|
||||
}
|
||||
if (testEntry.screenshot !== false) {
|
||||
await argosScreenshot(page, `${testCase.name} - ${testEntry.name}`, {
|
||||
viewports: ['macbook-16', 'macbook-13', 'iphone-x', 'ipad-2'],
|
||||
argosCSS: `
|
||||
/* Hide Intercom */
|
||||
.intercom-lightweight-app {
|
||||
display: none !important;
|
||||
}
|
||||
`,
|
||||
fullPage: testEntry.fullPage ?? false,
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a URL with customization settings.
|
||||
*/
|
||||
function getCustomizationURL(partial: Partial<CustomizationSettings>): string {
|
||||
const encoded = rison.encode_object(partial);
|
||||
|
||||
const searchParams = new URLSearchParams();
|
||||
searchParams.set('customization', encoded);
|
||||
|
||||
return `?${searchParams.toString()}`;
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
const { withSentryConfig } = require('@sentry/nextjs');
|
||||
|
||||
module.exports = withSentryConfig(
|
||||
{
|
||||
env: {
|
||||
BUILD_VERSION: (process.env.GITHUB_SHA ?? '').slice(0, 7),
|
||||
SENTRY_DSN: process.env.SENTRY_DSN ?? '',
|
||||
SENTRY_ENVIRONMENT: process.env.SENTRY_ENVIRONMENT ?? 'development',
|
||||
GITBOOK_ASSETS_PREFIX: process.env.GITBOOK_ASSETS_PREFIX,
|
||||
},
|
||||
|
||||
webpack(config, { dev, webpack }) {
|
||||
config.resolve.fallback = {
|
||||
...config.resolve.fallback,
|
||||
|
||||
// Required for `swagger2openapi` to work:
|
||||
fs: false,
|
||||
path: false,
|
||||
http: false,
|
||||
};
|
||||
|
||||
// Tree shake debug code for Sentry
|
||||
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/tree-shaking/#tree-shaking-with-nextjs
|
||||
if (!dev) {
|
||||
config.plugins.push(
|
||||
new webpack.DefinePlugin({
|
||||
__SENTRY_DEBUG__: false,
|
||||
// We always init Sentry with enableTracing: false for now, so this is useless
|
||||
__SENTRY_TRACING__: false,
|
||||
__RRWEB_EXCLUDE_IFRAME__: true,
|
||||
__RRWEB_EXCLUDE_SHADOW_DOM__: true,
|
||||
__SENTRY_EXCLUDE_REPLAY_WORKER__: true,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
return config;
|
||||
},
|
||||
|
||||
async headers() {
|
||||
return [
|
||||
// Cache all static assets for 1 year
|
||||
{
|
||||
source: '/~gitbook/static/:path*',
|
||||
headers: [
|
||||
{
|
||||
key: 'Cache-Control',
|
||||
value: 'public, max-age=31536000, immutable',
|
||||
},
|
||||
],
|
||||
},
|
||||
];
|
||||
},
|
||||
|
||||
assetPrefix: process.env.GITBOOK_ASSETS_PREFIX,
|
||||
poweredByHeader: false,
|
||||
|
||||
images: {
|
||||
remotePatterns: [
|
||||
{
|
||||
protocol: 'https',
|
||||
hostname: '*.gitbook.io',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
{
|
||||
silent: true,
|
||||
org: process.env.SENTRY_ORG,
|
||||
project: process.env.SENTRY_PROJECT,
|
||||
},
|
||||
{
|
||||
// Upload a larger set of source maps for prettier stack traces (increases build time)
|
||||
widenClientFileUpload: true,
|
||||
transpileClientSDK: false,
|
||||
// Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers (increases server load)
|
||||
tunnelRoute: '/~gitbook/monitoring',
|
||||
// Don't hide source maps from generated client bundles
|
||||
hideSourceMaps: false,
|
||||
disableLogger: true,
|
||||
automaticVercelMonitors: false,
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"name": "gitbook",
|
||||
"version": "0.2.1",
|
||||
"private": true,
|
||||
"scripts": {
|
||||
"dev": "next dev",
|
||||
"build": "next build",
|
||||
"build:cloudflare": "next-on-pages",
|
||||
"start": "next start",
|
||||
"lint": "next lint",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"e2e": "playwright test",
|
||||
"unit": "bun test {src,packages}",
|
||||
"postinstall": "rm -rf ./public/~gitbook/static/mathjax@3.2.2 && mkdir -p ./public/~gitbook/static/ && cp -R ../../node_modules/mathjax/es5 ./public/~gitbook/static/mathjax@3.2.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@geist-ui/icons": "^1.0.2",
|
||||
"@gitbook/api": "^0.56.0",
|
||||
"@gitbook/react-math": "workspace:*",
|
||||
"@gitbook/react-openapi": "workspace:*",
|
||||
"@gitbook/react-contentkit": "workspace:*",
|
||||
"@radix-ui/react-checkbox": "^1.0.4",
|
||||
"@radix-ui/react-popover": "^1.0.7",
|
||||
"@sentry/nextjs": "^7.94.1",
|
||||
"@sindresorhus/fnv1a": "^3.1.0",
|
||||
"@tailwindcss/container-queries": "^0.1.1",
|
||||
"@tailwindcss/typography": "^0.5.10",
|
||||
"@upstash/redis": "^1.27.1",
|
||||
"ajv": "^8.12.0",
|
||||
"assert-never": "^1.2.1",
|
||||
"bun-types": "^1.1.20",
|
||||
"classnames": "^2.5.1",
|
||||
"content-security-policy-merger": "^1.0.0",
|
||||
"framer-motion": "^10.16.14",
|
||||
"js-cookie": "^3.0.5",
|
||||
"jsontoxml": "^1.0.1",
|
||||
"katex": "^0.16.9",
|
||||
"mathjax": "^3.2.2",
|
||||
"memoizee": "^0.4.15",
|
||||
"next": "^14.1.3",
|
||||
"next-themes": "^0.2.1",
|
||||
"nuqs": "^1.17.4",
|
||||
"object-hash": "^3.0.0",
|
||||
"openapi-types": "^12.1.3",
|
||||
"p-map": "^7.0.0",
|
||||
"parse-cache-control": "^1.0.1",
|
||||
"react": "^18",
|
||||
"react-dom": "^18",
|
||||
"react-hotkeys-hook": "^4.4.1",
|
||||
"recoil": "^0.7.7",
|
||||
"rehype-sanitize": "^6.0.0",
|
||||
"rehype-stringify": "^10.0.0",
|
||||
"remark-gfm": "^4.0.0",
|
||||
"remark-parse": "^11.0.0",
|
||||
"remark-rehype": "^11.1.0",
|
||||
"rison": "^0.1.1",
|
||||
"server-only": "^0.0.1",
|
||||
"shiki": "^1.2.0",
|
||||
"tailwind-merge": "^2.2.0",
|
||||
"tailwind-shades": "^1.1.2",
|
||||
"unified": "^11.0.4",
|
||||
"url-join": "^5.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@argos-ci/playwright": "^2.0.0",
|
||||
"@playwright/test": "^1.42.1",
|
||||
"@cloudflare/next-on-pages": "^1.11.3",
|
||||
"@cloudflare/workers-types": "^4.20231218.0",
|
||||
"@types/js-cookie": "^3.0.6",
|
||||
"@types/jsontoxml": "^1.0.5",
|
||||
"@types/jsonwebtoken": "^9.0.6",
|
||||
"@types/node": "^20",
|
||||
"@types/object-hash": "^3.0.6",
|
||||
"@types/parse-cache-control": "^1.0.4",
|
||||
"@types/psi": "^4.1.6",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@types/rison": "^0.0.9",
|
||||
"autoprefixer": "^10",
|
||||
"eslint": "^8",
|
||||
"eslint-config-next": "^14.2.5",
|
||||
"eslint-plugin-import": "^2.29.1",
|
||||
"jsonwebtoken": "^9.0.2",
|
||||
"postcss": "^8",
|
||||
"psi": "^4.1.0",
|
||||
"tailwindcss": "^3.4.0",
|
||||
"typescript": "^5.5.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { defineConfig, devices } from '@playwright/test';
|
||||
|
||||
export default defineConfig({
|
||||
testDir: './e2e',
|
||||
fullyParallel: true,
|
||||
forbidOnly: !!process.env.CI,
|
||||
retries: process.env.CI ? 2 : 0,
|
||||
reporter: [
|
||||
process.env.CI ? ['dot'] : ['list'],
|
||||
['@argos-ci/playwright/reporter', { uploadToArgos: !!process.env.CI }],
|
||||
],
|
||||
projects: [
|
||||
{
|
||||
name: 'chromium',
|
||||
use: { ...devices['Desktop Chrome'] },
|
||||
},
|
||||
],
|
||||
use: {
|
||||
baseURL: process.env.BASE_URL || 'http://localhost:3000',
|
||||
trace: 'on-first-retry',
|
||||
screenshot: 'only-on-failure',
|
||||
},
|
||||
});
|
||||
@@ -0,0 +1,6 @@
|
||||
module.exports = {
|
||||
plugins: {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import {
|
||||
BrowserClient,
|
||||
makeFetchTransport,
|
||||
defaultStackParser,
|
||||
getCurrentScope,
|
||||
} from '@sentry/nextjs';
|
||||
|
||||
const dsn = process.env.SENTRY_DSN;
|
||||
if (dsn) {
|
||||
// To tree shake default integrations that we don't use
|
||||
// https://docs.sentry.io/platforms/javascript/guides/nextjs/configuration/tree-shaking/#tree-shaking-default-integrations
|
||||
const client = new BrowserClient({
|
||||
debug: false,
|
||||
dsn,
|
||||
integrations: [],
|
||||
sampleRate: 0.1,
|
||||
enableTracing: false,
|
||||
beforeSendTransaction: () => {
|
||||
return null;
|
||||
},
|
||||
transport: makeFetchTransport,
|
||||
stackParser: defaultStackParser,
|
||||
});
|
||||
|
||||
getCurrentScope().setClient(client);
|
||||
client.init();
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { init } from '@sentry/nextjs';
|
||||
|
||||
const dsn = process.env.SENTRY_DSN;
|
||||
if (dsn) {
|
||||
init({
|
||||
debug: false,
|
||||
dsn,
|
||||
|
||||
sampleRate: 0.1,
|
||||
|
||||
// Disable tracing as it creates additional requests in an env where subrequests are limited.
|
||||
enableTracing: false,
|
||||
|
||||
// Disable transactions as it creates additional requests in an env where subrequests are limited.
|
||||
// https://docs.sentry.io/platforms/node/configuration/filtering/#using--3
|
||||
beforeSendTransaction: () => {
|
||||
return null;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { init } from '@sentry/nextjs';
|
||||
|
||||
const dsn = process.env.SENTRY_DSN;
|
||||
if (dsn) {
|
||||
init({
|
||||
debug: false,
|
||||
dsn,
|
||||
|
||||
sampleRate: 0.1,
|
||||
|
||||
// Disable tracing as it creates additional requests in an env where subrequests are limited.
|
||||
enableTracing: false,
|
||||
|
||||
// Disable transactions as it creates additional requests in an env where subrequests are limited.
|
||||
// https://docs.sentry.io/platforms/node/configuration/filtering/#using--3
|
||||
beforeSendTransaction: () => {
|
||||
return null;
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
import {
|
||||
verifyImageSignature,
|
||||
resizeImage,
|
||||
CloudflareImageOptions,
|
||||
checkIsSizableImageURL,
|
||||
} from '@/lib/images';
|
||||
import { parseImageAPIURL } from '@/lib/urls';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
/**
|
||||
* Only on Cloudflare Workers:
|
||||
*
|
||||
* Fetch and resize an image.
|
||||
*/
|
||||
export async function GET(request: NextRequest) {
|
||||
let urlParam = request.nextUrl.searchParams.get('url');
|
||||
const signature = request.nextUrl.searchParams.get('sign');
|
||||
// The current signature algorithm sets version as 1, but we need to support the older version as well
|
||||
// for previously generated content. In this case, we default to version 0.
|
||||
const signatureVersion = (request.nextUrl.searchParams.get('sv') as '1') || '0';
|
||||
if (!urlParam || !signature) {
|
||||
return new Response('Missing url/sign parameters', { status: 400 });
|
||||
}
|
||||
|
||||
const url = parseImageAPIURL(urlParam);
|
||||
|
||||
// Prevent infinite loops
|
||||
if (url.includes('/~gitbook/image')) {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// Check again if the image can be sized, even though we checked when rendering the Image component
|
||||
// Otherwise, it's possible to pass just any link to this endpoint and trigger HTML injection on the domain
|
||||
if (!checkIsSizableImageURL(url)) {
|
||||
return new Response('Invalid url parameter', { status: 400 });
|
||||
}
|
||||
|
||||
// Verify the signature
|
||||
const verified = await verifyImageSignature(url, { signature, version: signatureVersion });
|
||||
if (!verified) {
|
||||
return new Response(`Invalid signature "${signature ?? ''}" for "${url}"`, { status: 400 });
|
||||
}
|
||||
|
||||
// Cloudflare-specific options are in the cf object.
|
||||
const options: CloudflareImageOptions = {
|
||||
fit: 'scale-down',
|
||||
format: 'jpeg',
|
||||
quality: 100,
|
||||
};
|
||||
|
||||
const width = request.nextUrl.searchParams.get('width');
|
||||
if (width) {
|
||||
options.width = Number(width);
|
||||
}
|
||||
|
||||
const height = request.nextUrl.searchParams.get('height');
|
||||
if (height) {
|
||||
options.height = Number(height);
|
||||
}
|
||||
|
||||
const dpr = request.nextUrl.searchParams.get('dpr');
|
||||
if (dpr) {
|
||||
options.dpr = Number(dpr);
|
||||
}
|
||||
|
||||
const quality = request.nextUrl.searchParams.get('quality');
|
||||
if (quality) {
|
||||
options.quality = Number(quality);
|
||||
}
|
||||
|
||||
// Check the Accept header to handle content negotiation
|
||||
const accept = request.headers.get('accept');
|
||||
if (accept && /image\/avif/.test(accept)) {
|
||||
options.format = 'avif';
|
||||
} else if (accept && /image\/webp/.test(accept)) {
|
||||
options.format = 'webp';
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await resizeImage(url, options);
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to resize image');
|
||||
}
|
||||
|
||||
return response;
|
||||
} catch (error) {
|
||||
// Redirect to the original image if resizing fails
|
||||
return Response.redirect(url, 302);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
import { revalidateTags } from '@/lib/cache';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
interface JsonBody {
|
||||
tags: string[];
|
||||
purge?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revalidate cached data based on tags.
|
||||
* The body should be a JSON with { tags: string[] }
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const json = (await req.json()) as JsonBody;
|
||||
|
||||
if (!json.tags || !Array.isArray(json.tags)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
error: 'tags must be an array',
|
||||
},
|
||||
{ status: 400 },
|
||||
);
|
||||
}
|
||||
|
||||
const result = await revalidateTags(json.tags);
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
keys: result.keys,
|
||||
stats: result.stats,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
'use client';
|
||||
|
||||
import { CustomizationThemeMode } from '@gitbook/api';
|
||||
import { ThemeProvider } from 'next-themes';
|
||||
import React from 'react';
|
||||
|
||||
export function ClientContexts(props: {
|
||||
nonce: string;
|
||||
forcedTheme: CustomizationThemeMode | undefined;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { children, forcedTheme } = props;
|
||||
|
||||
/**
|
||||
* A bug in ThemeProvider is causing the nonce to be included incorrectly
|
||||
* on the client-side. Original issue: https://github.com/pacocoursey/next-themes/issues/218
|
||||
*
|
||||
* This is a workaround for it, until next-themes fixes it in their library. There is already
|
||||
* a PR: https://github.com/pacocoursey/next-themes/pull/223
|
||||
*/
|
||||
const nonce = typeof window === 'undefined' ? props.nonce : '';
|
||||
|
||||
return (
|
||||
<ThemeProvider nonce={nonce} attribute="class" enableSystem forcedTheme={forcedTheme}>
|
||||
{children}
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Insert inline JS to detect Cloudflare Rocket Loader and notify the user that the content will not load correctly.
|
||||
* It needs to be inserted as a script tag so that we can pass `data-cfasync="false"` to avoid being processed by Rocket Loader.
|
||||
*/
|
||||
export function RocketLoaderDetector(props: { nonce: string }) {
|
||||
const { nonce } = props;
|
||||
|
||||
return (
|
||||
<script
|
||||
nonce={nonce}
|
||||
suppressHydrationWarning
|
||||
data-cfasync="false"
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: `
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
if (Array.from(document.scripts).find(script => script.src.includes('rocket-loader.min.js'))) {
|
||||
const alert = document.createElement('div');
|
||||
alert.className = 'p-4 mb-4 text-sm text-red-800 rounded-lg bg-red-50 dark:bg-gray-800 dark:text-red-400 mt-8 mx-8';
|
||||
alert.innerHTML = \`
|
||||
<strong>Error in site configuration:</strong>
|
||||
It looks like \${window.location.hostname} has been incorrectly configured in Cloudflare. This may lead to unexpected behavior or issues with the page loading. If you are the owner of this site, please refer to <a href="https://docs.gitbook.com/published-documentation/custom-domain/configure-dns#are-you-using-cloudflare" class="underline">GitBook's documentation</a> for steps to fix the problem.
|
||||
\`;
|
||||
|
||||
document.body.prepend(alert);
|
||||
}
|
||||
});`,
|
||||
}}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
'use client';
|
||||
|
||||
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
|
||||
import React from 'react';
|
||||
|
||||
import { useScrollToHash } 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();
|
||||
|
||||
useStripFallbackQueryParam();
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Strip the fallback query parameter from current URL.
|
||||
*
|
||||
* When the user switches variants using the space dropdown, we pass a fallback=true parameter.
|
||||
* This parameter indicates that we should redirect to the root page if the path from the
|
||||
* previous variant doesn't exist in the new variant. If the path does exist, no redirect occurs,
|
||||
* so we need to remove the fallback parameter.
|
||||
*/
|
||||
function useStripFallbackQueryParam() {
|
||||
const router = useRouter();
|
||||
const pathname = usePathname();
|
||||
const searchParams = useSearchParams();
|
||||
|
||||
React.useEffect(() => {
|
||||
if (searchParams.has('fallback')) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
params.delete('fallback');
|
||||
router.push(`${pathname}?${params.toString()}${window.location.hash ?? ''}`);
|
||||
}
|
||||
}, [router, pathname, searchParams]);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { SkeletonHeading, SkeletonParagraph } from '@/components/primitives';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
/**
|
||||
* Placeholder when loading a page.
|
||||
*/
|
||||
export default function PageSkeleton() {
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
'flex-1',
|
||||
'relative',
|
||||
'py-8',
|
||||
'lg:px-16',
|
||||
'xl:mr-56',
|
||||
'items-center',
|
||||
'lg:items-start',
|
||||
)}
|
||||
>
|
||||
<div className={tcls('flex-1', 'max-w-3xl', 'mx-auto')}>
|
||||
<SkeletonHeading style={tcls('mb-8')} />
|
||||
<SkeletonParagraph style={tcls('mb-4')} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import { getSpaceLanguage, t } from '@/intl/server';
|
||||
import { getCurrentSiteLayoutData, getSpaceLayoutData } from '@/lib/api';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { getContentPointer } from '../../fetch';
|
||||
|
||||
export default async function NotFound() {
|
||||
const pointer = getContentPointer();
|
||||
const { customization } = await ('siteId' in pointer
|
||||
? getCurrentSiteLayoutData(pointer)
|
||||
: getSpaceLayoutData(pointer.spaceId));
|
||||
|
||||
const language = getSpaceLanguage(customization);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={tcls('flex-1', 'flex', 'flex-row', 'items-center', 'justify-center', 'py-9')}
|
||||
>
|
||||
<div className={tcls('max-w-80')}>
|
||||
<h2 className={tcls('text-2xl', 'font-semibold', 'mb-2')}>
|
||||
{t(language, 'notfound_title')}
|
||||
</h2>
|
||||
<p className={tcls('text-base', 'mb-4')}>{t(language, 'notfound')}</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
import { CustomizationHeaderPreset, CustomizationThemeMode } from '@gitbook/api';
|
||||
import { Metadata, Viewport } from 'next';
|
||||
import { notFound, redirect } from 'next/navigation';
|
||||
import React from 'react';
|
||||
|
||||
import { PageAside } from '@/components/PageAside';
|
||||
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 { tcls } from '@/lib/tailwind';
|
||||
import { getContentTitle } from '@/lib/utils';
|
||||
|
||||
import { PageClientLayout } from './PageClientLayout';
|
||||
import { PagePathParams, fetchPageData, getPathnameParam, normalizePathname } from '../../fetch';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
/**
|
||||
* Fetch and render a page.
|
||||
*/
|
||||
export default async function Page(props: {
|
||||
params: PagePathParams;
|
||||
searchParams: { fallback?: string };
|
||||
}) {
|
||||
const { params, searchParams } = props;
|
||||
|
||||
const {
|
||||
content: contentPointer,
|
||||
contentTarget,
|
||||
space,
|
||||
parent,
|
||||
customization,
|
||||
pages,
|
||||
page,
|
||||
document,
|
||||
} = await getPageDataWithFallback({
|
||||
pagePathParams: params,
|
||||
searchParams,
|
||||
redirectOnFallback: true,
|
||||
});
|
||||
|
||||
const linksContext: PageHrefContext = {};
|
||||
const rawPathname = getPathnameParam(params);
|
||||
if (!page) {
|
||||
const pathname = normalizePathname(rawPathname);
|
||||
if (pathname !== rawPathname) {
|
||||
// If the pathname was not normalized, redirect to the normalized version
|
||||
// before trying to resolve the page again
|
||||
redirect(absoluteHref(pathname));
|
||||
} else {
|
||||
notFound();
|
||||
}
|
||||
} else if (getPagePath(pages, page) !== rawPathname) {
|
||||
redirect(pageHref(pages, page, linksContext));
|
||||
}
|
||||
|
||||
const withTopHeader = customization.header.preset !== CustomizationHeaderPreset.None;
|
||||
const withFullPageCover = !!(
|
||||
page.cover &&
|
||||
page.layout.cover &&
|
||||
page.layout.coverSize === 'full'
|
||||
);
|
||||
const withPageFeedback = customization.feedback.enabled;
|
||||
|
||||
const contentRefContext: ContentRefContext = {
|
||||
space,
|
||||
revisionId: contentTarget.revisionId,
|
||||
pages,
|
||||
page,
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{withFullPageCover && page.cover ? (
|
||||
<PageCover as="full" page={page} cover={page.cover} context={contentRefContext} />
|
||||
) : null}
|
||||
<div className={tcls('flex', 'flex-row')}>
|
||||
<PageBody
|
||||
space={space}
|
||||
contentPointer={contentPointer}
|
||||
contentTarget={contentTarget}
|
||||
customization={customization}
|
||||
context={contentRefContext}
|
||||
page={page}
|
||||
document={document}
|
||||
withPageFeedback={
|
||||
// Display the page feedback in the page footer if the aside is not visible
|
||||
withPageFeedback && !page.layout.outline
|
||||
}
|
||||
/>
|
||||
{page.layout.outline ? (
|
||||
<PageAside
|
||||
space={space}
|
||||
site={parent?.object === 'site' ? parent : undefined}
|
||||
customization={customization}
|
||||
page={page}
|
||||
document={document}
|
||||
withHeaderOffset={withTopHeader}
|
||||
withFullPageCover={withFullPageCover}
|
||||
withPageFeedback={withPageFeedback}
|
||||
context={contentRefContext}
|
||||
/>
|
||||
) : null}
|
||||
</div>
|
||||
<React.Suspense fallback={null}>
|
||||
<PageClientLayout />
|
||||
</React.Suspense>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateViewport({ params }: { params: PagePathParams }): Promise<Viewport> {
|
||||
const { customization } = await fetchPageData(params);
|
||||
return {
|
||||
colorScheme: customization.themes.toggeable
|
||||
? customization.themes.default === CustomizationThemeMode.Dark
|
||||
? 'dark light'
|
||||
: 'light dark'
|
||||
: customization.themes.default,
|
||||
};
|
||||
}
|
||||
|
||||
export async function generateMetadata({
|
||||
params,
|
||||
searchParams,
|
||||
}: {
|
||||
params: PagePathParams;
|
||||
searchParams: { fallback?: string };
|
||||
}): Promise<Metadata> {
|
||||
const { space, pages, page, customization, parent } = await getPageDataWithFallback({
|
||||
pagePathParams: params,
|
||||
searchParams,
|
||||
});
|
||||
|
||||
if (!page) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return {
|
||||
title: [page.title, getContentTitle(space, customization, parent)]
|
||||
.filter(Boolean)
|
||||
.join(' | '),
|
||||
description: page.description ?? '',
|
||||
alternates: {
|
||||
canonical: absoluteHref(getPagePath(pages, page), true),
|
||||
},
|
||||
openGraph: {
|
||||
images: [
|
||||
customization.socialPreview.url ??
|
||||
absoluteHref(`~gitbook/ogimage/${page.id}`, true),
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches the page data matching the requested pathname and fallback to root page when page is not found.
|
||||
*/
|
||||
async function getPageDataWithFallback(args: {
|
||||
pagePathParams: PagePathParams;
|
||||
searchParams: { fallback?: string };
|
||||
redirectOnFallback?: boolean;
|
||||
}) {
|
||||
const { pagePathParams, searchParams, redirectOnFallback = false } = args;
|
||||
|
||||
const { pages, page: targetPage, ...otherPageData } = await fetchPageData(pagePathParams);
|
||||
|
||||
let page = targetPage;
|
||||
const canFallback = !!searchParams.fallback;
|
||||
if (!page && canFallback) {
|
||||
const rootPage = resolveFirstDocument(pages, []);
|
||||
|
||||
if (redirectOnFallback && rootPage?.page) {
|
||||
redirect(pageHref(pages, rootPage?.page));
|
||||
}
|
||||
|
||||
page = rootPage?.page;
|
||||
}
|
||||
|
||||
return {
|
||||
...otherPageData,
|
||||
pages,
|
||||
page,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,153 @@
|
||||
import { CustomizationThemeMode } from '@gitbook/api';
|
||||
import { Metadata, Viewport } from 'next';
|
||||
import { headers } from 'next/headers';
|
||||
import React from 'react';
|
||||
import * as ReactDOM from 'react-dom';
|
||||
|
||||
import { AdminToolbar } from '@/components/AdminToolbar';
|
||||
import { CookiesToast } from '@/components/Cookies';
|
||||
import { LoadIntegrations } from '@/components/Integrations';
|
||||
import { SpaceLayout } from '@/components/SpaceLayout';
|
||||
import { api } from '@/lib/api';
|
||||
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 { getContentTitle } from '@/lib/utils';
|
||||
|
||||
import { ClientContexts } from './ClientContexts';
|
||||
import { RocketLoaderDetector } from './RocketLoaderDetector';
|
||||
import { fetchSpaceData } from '../fetch';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
/**
|
||||
* Layout when rendering the content.
|
||||
*/
|
||||
export default async function ContentLayout(props: { children: React.ReactNode }) {
|
||||
const { children } = props;
|
||||
|
||||
const nonce = getContentSecurityPolicyNonce();
|
||||
const {
|
||||
content,
|
||||
space,
|
||||
contentTarget,
|
||||
customization,
|
||||
pages,
|
||||
parent,
|
||||
spaces,
|
||||
ancestors,
|
||||
scripts,
|
||||
} = await fetchSpaceData();
|
||||
|
||||
ReactDOM.preconnect(api().endpoint);
|
||||
if (assetsDomain) {
|
||||
ReactDOM.preconnect(assetsDomain);
|
||||
}
|
||||
|
||||
scripts.forEach(({ script }) => {
|
||||
ReactDOM.preload(script, {
|
||||
as: 'script',
|
||||
nonce,
|
||||
});
|
||||
});
|
||||
|
||||
return (
|
||||
<ClientContexts
|
||||
nonce={nonce}
|
||||
forcedTheme={
|
||||
getQueryStringTheme() ??
|
||||
(customization.themes.toggeable ? undefined : customization.themes.default)
|
||||
}
|
||||
>
|
||||
<SpaceLayout
|
||||
space={space}
|
||||
contentTarget={contentTarget}
|
||||
parent={parent}
|
||||
spaces={spaces}
|
||||
customization={customization}
|
||||
pages={pages}
|
||||
ancestors={ancestors}
|
||||
content={content}
|
||||
>
|
||||
{children}
|
||||
</SpaceLayout>
|
||||
|
||||
{scripts.length > 0 ? (
|
||||
<>
|
||||
<LoadIntegrations />
|
||||
{scripts.map(({ script }) => (
|
||||
<script key={script} async src={script} nonce={nonce} />
|
||||
))}
|
||||
</>
|
||||
) : null}
|
||||
|
||||
{scripts.some((script) => script.cookies) || customization.privacyPolicy.url ? (
|
||||
<React.Suspense fallback={null}>
|
||||
<CookiesToast privacyPolicy={customization.privacyPolicy.url} />
|
||||
</React.Suspense>
|
||||
) : null}
|
||||
|
||||
<RocketLoaderDetector nonce={nonce} />
|
||||
|
||||
<AdminToolbar space={space} content={content} />
|
||||
</ClientContexts>
|
||||
);
|
||||
}
|
||||
|
||||
export async function generateViewport(): Promise<Viewport> {
|
||||
const { customization } = await fetchSpaceData();
|
||||
return {
|
||||
colorScheme: customization.themes.toggeable
|
||||
? customization.themes.default === CustomizationThemeMode.Dark
|
||||
? 'dark light'
|
||||
: 'light dark'
|
||||
: customization.themes.default,
|
||||
};
|
||||
}
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const { space, parent, customization } = await fetchSpaceData();
|
||||
const customIcon = 'icon' in customization.favicon ? customization.favicon.icon : null;
|
||||
|
||||
return {
|
||||
title: getContentTitle(space, customization, parent),
|
||||
generator: `GitBook (${buildVersion()})`,
|
||||
metadataBase: new URL(baseUrl()),
|
||||
icons: {
|
||||
icon: [
|
||||
{
|
||||
url:
|
||||
customIcon?.light ??
|
||||
absoluteHref('~gitbook/icon?size=small&theme=light', true),
|
||||
type: 'image/png',
|
||||
media: '(prefers-color-scheme: light)',
|
||||
},
|
||||
{
|
||||
url:
|
||||
customIcon?.dark ??
|
||||
absoluteHref('~gitbook/icon?size=small&theme=dark', true),
|
||||
type: 'image/png',
|
||||
media: '(prefers-color-scheme: dark)',
|
||||
},
|
||||
],
|
||||
},
|
||||
robots: shouldIndexSpace({ space, parent }) ? 'index, follow' : 'noindex, nofollow',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* For preview, the theme can be set via query string (?theme=light).
|
||||
*/
|
||||
function getQueryStringTheme() {
|
||||
const headersList = headers();
|
||||
const queryStringTheme = headersList.get('x-gitbook-theme');
|
||||
if (!queryStringTheme) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return queryStringTheme === 'light'
|
||||
? CustomizationThemeMode.Light
|
||||
: CustomizationThemeMode.Dark;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
import { ContentVisibility } from '@gitbook/api';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
import { getCollection, getSite, getSpace } from '@/lib/api';
|
||||
import { absoluteHref } from '@/lib/links';
|
||||
import { shouldIndexSpace } from '@/lib/seo';
|
||||
|
||||
import { getContentPointer } from '../../fetch';
|
||||
|
||||
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);
|
||||
const parent =
|
||||
'siteId' in pointer
|
||||
? await getSite(pointer.organizationId, pointer.siteId)
|
||||
: space.visibility === ContentVisibility.InCollection && space.parent
|
||||
? await getCollection(space.parent)
|
||||
: null;
|
||||
|
||||
const lines = [
|
||||
`User-agent: *`,
|
||||
'Disallow: /~gitbook/',
|
||||
...(shouldIndexSpace({ space, parent })
|
||||
? [`Allow: /`, `Sitemap: ${absoluteHref(`/sitemap.xml`, true)}`]
|
||||
: [`Disallow: /`]),
|
||||
];
|
||||
const content = lines.join('\n');
|
||||
|
||||
return new Response(content, {
|
||||
headers: {
|
||||
'Content-Type': 'text/plain',
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import { RevisionPage, RevisionPageDocument, RevisionPageGroup } from '@gitbook/api';
|
||||
import jsontoxml from 'jsontoxml';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
import { getSpaceContentData } from '@/lib/api';
|
||||
import { absoluteHref } from '@/lib/links';
|
||||
import { getPagePath } from '@/lib/pages';
|
||||
|
||||
import { getContentPointer } from '../../fetch';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
/**
|
||||
* Generate a sitemap.xml for the current space.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
const { pages: rootPages } = await getSpaceContentData(getContentPointer());
|
||||
const pages = flattenPages(rootPages, (page) => !page.hidden);
|
||||
const urls = pages.map(({ page, depth }) => {
|
||||
// Decay priority with depth
|
||||
const priority = Math.pow(2, -0.25 * depth);
|
||||
// Normalize to keep 2 decimals
|
||||
const normalizedPriority = Math.floor(100 * priority) / 100;
|
||||
|
||||
const lastModified = page.updatedAt || page.createdAt;
|
||||
|
||||
return {
|
||||
url: {
|
||||
loc: absoluteHref(getPagePath(rootPages, page), true),
|
||||
priority: normalizedPriority,
|
||||
...(lastModified
|
||||
? {
|
||||
// lastmod format is YYYY-MM-DD
|
||||
lastmod: new Date(lastModified).toISOString().split('T')[0],
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
const xml = jsontoxml(
|
||||
[
|
||||
{
|
||||
name: 'urlset',
|
||||
children: urls,
|
||||
attrs: {
|
||||
'xmlns:xsi': 'http://www.w3.org/2001/XMLSchema-instance',
|
||||
xmlns: 'http://www.sitemaps.org/schemas/sitemap/0.9',
|
||||
'xsi:schemaLocation':
|
||||
'http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/sitemap.xsd',
|
||||
},
|
||||
},
|
||||
],
|
||||
{
|
||||
xmlHeader: true,
|
||||
prettyPrint: true,
|
||||
},
|
||||
);
|
||||
|
||||
return new Response(xml, {
|
||||
headers: {
|
||||
'Content-Type': 'application/xml',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
type FlatPageEntry = { page: RevisionPageDocument; depth: number };
|
||||
|
||||
function flattenPages(
|
||||
rootPags: RevisionPage[],
|
||||
filter: (page: RevisionPageDocument) => boolean,
|
||||
): FlatPageEntry[] {
|
||||
const flattenPage = (
|
||||
page: RevisionPageDocument | RevisionPageGroup,
|
||||
depth: number,
|
||||
): FlatPageEntry[] => {
|
||||
return [
|
||||
...(page.type === 'document' && filter(page) ? [{ page, depth }] : []),
|
||||
...page.pages.flatMap((child) =>
|
||||
child.type === 'link' ? [] : flattenPage(child, depth + 1),
|
||||
),
|
||||
];
|
||||
};
|
||||
|
||||
return rootPags.flatMap((page) => (page.type === 'link' ? [] : flattenPage(page, 0)));
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
import { ContentVisibility } from '@gitbook/api';
|
||||
import { notFound } from 'next/navigation';
|
||||
import { ImageResponse } from 'next/og';
|
||||
import { NextRequest } from 'next/server';
|
||||
import React from 'react';
|
||||
|
||||
import { getContentPointer } from '@/app/(space)/fetch';
|
||||
import {
|
||||
getCollection,
|
||||
getCurrentSiteCustomization,
|
||||
getSite,
|
||||
getSpace,
|
||||
getSpaceCustomization,
|
||||
} from '@/lib/api';
|
||||
import { getEmojiForCode } from '@/lib/emojis';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { getContentTitle } from '@/lib/utils';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
const SIZES = {
|
||||
/** Size for a favicon */
|
||||
small: {
|
||||
width: 48,
|
||||
height: 48,
|
||||
textSize: 'text-[32px]',
|
||||
boxStyle: 'rounded-[8px]',
|
||||
},
|
||||
/** Size for display as an app icon or in the header */
|
||||
medium: {
|
||||
width: 256,
|
||||
height: 256,
|
||||
textSize: 'text-[164px]',
|
||||
boxStyle: 'rounded-[32px]',
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* Render an icon for the space.
|
||||
*/
|
||||
export async function GET(req: NextRequest) {
|
||||
const options = getOptions(req.url);
|
||||
const size = SIZES[options.size];
|
||||
|
||||
const pointer = getContentPointer();
|
||||
const spaceId = pointer.spaceId;
|
||||
|
||||
const [space, customization] = await Promise.all([
|
||||
getSpace(spaceId),
|
||||
'siteId' in pointer ? getCurrentSiteCustomization(pointer) : getSpaceCustomization(spaceId),
|
||||
]);
|
||||
const parent =
|
||||
'siteId' in pointer
|
||||
? await getSite(pointer.organizationId, pointer.siteId)
|
||||
: space.visibility === ContentVisibility.InCollection && space.parent
|
||||
? await getCollection(space.parent)
|
||||
: null;
|
||||
const contentTitle = getContentTitle(space, customization, parent);
|
||||
|
||||
return new ImageResponse(
|
||||
(
|
||||
<div
|
||||
tw={tcls(options.theme === 'light' ? 'bg-white' : 'bg-gray-900', size.boxStyle)}
|
||||
style={{
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
display: 'flex',
|
||||
alignItems: 'center',
|
||||
justifyContent: 'center',
|
||||
}}
|
||||
>
|
||||
<h2
|
||||
tw={tcls(
|
||||
size.textSize,
|
||||
'font-bold',
|
||||
'tracking-tight',
|
||||
options.theme === 'light' ? 'text-gray-900' : 'text-white',
|
||||
)}
|
||||
>
|
||||
{'emoji' in customization.favicon
|
||||
? getEmojiForCode(customization.favicon.emoji)
|
||||
: contentTitle.slice(0, 1).toUpperCase()}
|
||||
</h2>
|
||||
</div>
|
||||
),
|
||||
{
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function getOptions(inputUrl: string): {
|
||||
size: keyof typeof SIZES;
|
||||
theme: 'light' | 'dark';
|
||||
} {
|
||||
const url = new URL(inputUrl);
|
||||
const sizeParam = (url.searchParams.get('size') ?? 'small') as keyof typeof SIZES;
|
||||
const themeParam = url.searchParams.get('theme') ?? 'light';
|
||||
|
||||
if (!SIZES[sizeParam] || !['light', 'dark'].includes(themeParam)) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
return {
|
||||
// @ts-ignore
|
||||
size: sizeParam,
|
||||
// @ts-ignore
|
||||
theme: themeParam,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { redirect } from 'next/navigation';
|
||||
import { ImageResponse } from 'next/og';
|
||||
import { NextRequest } from 'next/server';
|
||||
import React from 'react';
|
||||
|
||||
import { getContentTitle } from '@/lib/utils';
|
||||
|
||||
import { PageIdParams, fetchPageData } from '../../../../fetch';
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
/**
|
||||
* Render the OpenGraph image for a space.
|
||||
*/
|
||||
export async function GET(req: NextRequest, { params }: { params: PageIdParams }) {
|
||||
const { space, page, customization, parent } = await fetchPageData(params);
|
||||
const url = new URL(space.urls.published ?? space.urls.app);
|
||||
|
||||
if (customization.socialPreview.url) {
|
||||
// If user configured a custom social preview, we redirect to it.
|
||||
redirect(customization.socialPreview.url);
|
||||
}
|
||||
|
||||
return new ImageResponse(
|
||||
(
|
||||
<div
|
||||
tw="bg-gray-50 py-16 px-14"
|
||||
style={{
|
||||
height: '100%',
|
||||
width: '100%',
|
||||
display: 'flex',
|
||||
flexDirection: 'column',
|
||||
}}
|
||||
>
|
||||
<h2 tw="text-7xl font-bold tracking-tight text-left">
|
||||
{getContentTitle(space, customization, parent)}
|
||||
</h2>
|
||||
<div tw="flex flex-1">
|
||||
<p tw="text-4xl">{page ? page.title : 'Not found'}</p>
|
||||
</div>
|
||||
<div tw="flex">
|
||||
<p tw="text-4xl">
|
||||
{url.hostname + (url.pathname.length > 1 ? url.pathname : '')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
),
|
||||
{
|
||||
width: 1200,
|
||||
height: 630,
|
||||
},
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
'use client';
|
||||
|
||||
import { AlertTriangle } from '@geist-ui/icons';
|
||||
import React from 'react';
|
||||
|
||||
import { useScrollActiveId } from '@/components/hooks';
|
||||
import { Button } from '@/components/primitives';
|
||||
import { t, useLanguage } from '@/intl/client';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { getPDFUrl } from '@/lib/urls';
|
||||
|
||||
const limitExtend = 50;
|
||||
|
||||
/**
|
||||
* Dynamic controls to show active page and to let the user select between modes.
|
||||
*/
|
||||
export function PageControlButtons(props: {
|
||||
pdfHref: string;
|
||||
singlePageMode: boolean;
|
||||
/** Array of the [pageId, divId] */
|
||||
pageIds: Array<[string, string]>;
|
||||
/** Current limit */
|
||||
limit: number;
|
||||
/** Total number of pages targetted by the generation */
|
||||
total: number;
|
||||
/** Trademark to display */
|
||||
trademark?: React.ReactNode;
|
||||
}) {
|
||||
const { pdfHref, singlePageMode, pageIds, limit, total, trademark } = props;
|
||||
|
||||
const language = useLanguage();
|
||||
|
||||
const divIds = React.useMemo(() => {
|
||||
return pageIds.map((entry) => entry[1]);
|
||||
}, [pageIds]);
|
||||
const activeDivId = useScrollActiveId(divIds, {
|
||||
threshold: 0,
|
||||
});
|
||||
const activeIndex = (activeDivId ? divIds.indexOf(activeDivId) : 0) + 1;
|
||||
const activePageId = pageIds[activeIndex - 1]?.[0];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div
|
||||
className={tcls(
|
||||
'fixed',
|
||||
'left-12',
|
||||
'bottom-12',
|
||||
'flex',
|
||||
'flex-col',
|
||||
'gap-2',
|
||||
'print:hidden',
|
||||
'z-50',
|
||||
)}
|
||||
>
|
||||
{singlePageMode ? null : (
|
||||
<Button
|
||||
href={getPDFUrl(new URL(pdfHref), {
|
||||
page: activePageId,
|
||||
only: true,
|
||||
}).toString()}
|
||||
variant="secondary"
|
||||
>
|
||||
{t(language, 'pdf_mode_only_page')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
href={getPDFUrl(new URL(pdfHref), { page: undefined, only: false }).toString()}
|
||||
variant="secondary"
|
||||
>
|
||||
{t(language, 'pdf_mode_all')}
|
||||
</Button>
|
||||
|
||||
{trademark ? <div className={tcls('mt-5')}>{trademark}</div> : null}
|
||||
</div>
|
||||
|
||||
<div
|
||||
className={tcls(
|
||||
'fixed',
|
||||
'right-12',
|
||||
'bottom-12',
|
||||
'flex',
|
||||
'flex-col',
|
||||
'items-end',
|
||||
'gap-2',
|
||||
'print:hidden',
|
||||
'z-50',
|
||||
)}
|
||||
>
|
||||
{total !== pageIds.length ? (
|
||||
<div
|
||||
role="banner"
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
'items-start',
|
||||
'mb-5',
|
||||
'bg-yellow-100',
|
||||
'border-yellow-400',
|
||||
'text-yellow-800',
|
||||
'shadow-sm',
|
||||
'border',
|
||||
'rounded-md',
|
||||
'p-4',
|
||||
'max-w-sm',
|
||||
)}
|
||||
>
|
||||
<AlertTriangle className={tcls('size-6', 'mr-3', 'mt-1')} />{' '}
|
||||
<div>
|
||||
<div>{t(language, 'pdf_limit_reached', total, pageIds.length)}</div>
|
||||
<div>
|
||||
<a
|
||||
href={getPDFUrl(new URL(pdfHref), {
|
||||
page: undefined,
|
||||
only: false,
|
||||
limit: limit + limitExtend,
|
||||
}).toString()}
|
||||
className={tcls('underline')}
|
||||
>
|
||||
{t(language, 'pdf_limit_reached_continue', limitExtend)}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
'items-center',
|
||||
'justify-center',
|
||||
'text-lg',
|
||||
'text-dark/6',
|
||||
'px-6',
|
||||
'py-2',
|
||||
'bg-slate-100',
|
||||
'rounded-full',
|
||||
'shadow-sm',
|
||||
'border-slate-300',
|
||||
'border',
|
||||
)}
|
||||
>
|
||||
{t(language, 'pdf_page_of', activeIndex, pageIds.length)}
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
'use client';
|
||||
|
||||
import * as React from 'react';
|
||||
|
||||
import { PolymorphicComponentProp } from '@/components/utils/types';
|
||||
|
||||
export function PrintButton(props: PolymorphicComponentProp<'button'>) {
|
||||
const { className, children, ...rest } = props;
|
||||
|
||||
const onClick = React.useCallback(() => {
|
||||
window.print();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<button {...rest} onClick={onClick} className={className}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
import { ArrowLeft, Printer } from '@geist-ui/icons';
|
||||
import {
|
||||
CustomizationSettings,
|
||||
Revision,
|
||||
RevisionPageDocument,
|
||||
RevisionPageGroup,
|
||||
RevisionPageLink,
|
||||
SiteCustomizationSettings,
|
||||
Space,
|
||||
} from '@gitbook/api';
|
||||
import { Metadata } from 'next';
|
||||
import { notFound } from 'next/navigation';
|
||||
import * as React from 'react';
|
||||
|
||||
import { getContentPointer } from '@/app/(space)/fetch';
|
||||
import { DocumentView, createHighlightingContext } from '@/components/DocumentView';
|
||||
import { TrademarkLink } from '@/components/TableOfContents/Trademark';
|
||||
import { PolymorphicComponentProp } from '@/components/utils/types';
|
||||
import { getSpaceLanguage } from '@/intl/server';
|
||||
import { tString } from '@/intl/translate';
|
||||
import {
|
||||
getDocument,
|
||||
getSpace,
|
||||
getSpaceCustomization,
|
||||
getSpaceContentData,
|
||||
getCurrentSiteCustomization,
|
||||
} from '@/lib/api';
|
||||
import { pagePDFContainerId, PageHrefContext, absoluteHref } from '@/lib/links';
|
||||
import { resolvePageId } from '@/lib/pages';
|
||||
import { ContentRefContext, resolveContentRef } from '@/lib/references';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
import { PDFSearchParams, getPDFSearchParams } from '@/lib/urls';
|
||||
|
||||
import './pdf.css';
|
||||
import { PageControlButtons } from './PageControlButtons';
|
||||
import { PrintButton } from './PrintButton';
|
||||
|
||||
const DEFAULT_LIMIT = 100;
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const contentPointer = getContentPointer();
|
||||
const [space, customization] = await Promise.all([
|
||||
getSpace(contentPointer.spaceId),
|
||||
'siteId' in contentPointer
|
||||
? getCurrentSiteCustomization(contentPointer)
|
||||
: getSpaceCustomization(contentPointer.spaceId),
|
||||
]);
|
||||
|
||||
return {
|
||||
title: customization.title ?? space.title,
|
||||
robots: 'noindex, nofollow',
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 searchParams = new URLSearchParams(props.searchParams);
|
||||
const pdfParams = getPDFSearchParams(new URLSearchParams(searchParams));
|
||||
|
||||
// Build current PDF URL and preserve all search params
|
||||
let currentPDFUrl = absoluteHref('~gitbook/pdf', true);
|
||||
currentPDFUrl += '?' + searchParams.toString();
|
||||
|
||||
// Load the content,
|
||||
const [customization, { space, contentTarget, pages: rootPages }] = await Promise.all([
|
||||
'siteId' in contentPointer
|
||||
? getCurrentSiteCustomization(contentPointer)
|
||||
: getSpaceCustomization(contentPointer.spaceId),
|
||||
getSpaceContentData(contentPointer),
|
||||
]);
|
||||
const language = getSpaceLanguage(customization);
|
||||
|
||||
// Compute the pages to render
|
||||
const { pages, total } = selectPages(rootPages, pdfParams);
|
||||
const pageIds = pages.map(
|
||||
({ page }) => [page.id, pagePDFContainerId(page)] as [string, string],
|
||||
);
|
||||
const linksContext: PageHrefContext = {
|
||||
pdf: pages.map(({ page }) => page.id),
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="print-mode">
|
||||
{pdfParams.back !== 'false' ? (
|
||||
<div className={tcls('fixed', 'left-12', 'top-12', 'print:hidden', 'z-50')}>
|
||||
<a
|
||||
title={tString(language, 'pdf_goback')}
|
||||
href={pdfParams.back ?? absoluteHref('')}
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
'items-center',
|
||||
'justify-center',
|
||||
'text-sm',
|
||||
'text-dark/6',
|
||||
'hover:text-primary',
|
||||
'p-4',
|
||||
'dark:text-light/5',
|
||||
'rounded-full',
|
||||
'bg-white',
|
||||
'shadow-sm',
|
||||
'hover:shadow-md',
|
||||
'border-slate-300',
|
||||
'border',
|
||||
)}
|
||||
>
|
||||
<ArrowLeft className={tcls('size-6')} />
|
||||
</a>
|
||||
</div>
|
||||
) : null}
|
||||
|
||||
<div className={tcls('fixed', 'right-12', 'top-12', 'print:hidden', 'z-50')}>
|
||||
<PrintButton
|
||||
title={tString(language, 'pdf_print')}
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-row',
|
||||
'items-center',
|
||||
'justify-center',
|
||||
'text-sm',
|
||||
'text-dark/6',
|
||||
'hover:text-primary',
|
||||
'p-4',
|
||||
'dark:text-light/5',
|
||||
'rounded-full',
|
||||
'bg-white',
|
||||
'shadow-sm',
|
||||
'hover:shadow-md',
|
||||
'border-slate-300',
|
||||
'border',
|
||||
)}
|
||||
>
|
||||
<Printer className={tcls('size-6')} />
|
||||
</PrintButton>
|
||||
</div>
|
||||
|
||||
<PageControlButtons
|
||||
pageIds={pageIds}
|
||||
pdfHref={currentPDFUrl}
|
||||
singlePageMode={!!pdfParams.only}
|
||||
total={total}
|
||||
limit={pdfParams.limit ?? DEFAULT_LIMIT}
|
||||
trademark={
|
||||
customization.trademark.enabled ? (
|
||||
<TrademarkLink space={space} customization={customization} />
|
||||
) : null
|
||||
}
|
||||
/>
|
||||
|
||||
{pdfParams.only ? null : <PDFSpaceIntro space={space} customization={customization} />}
|
||||
{pages.map(({ page }) =>
|
||||
page.type === 'group' ? (
|
||||
<PDFPageGroup key={page.id} space={space} page={page} />
|
||||
) : (
|
||||
<React.Suspense
|
||||
key={page.id}
|
||||
fallback={
|
||||
<PrintPage id={pagePDFContainerId(page)}>
|
||||
<p>Loading...</p>
|
||||
</PrintPage>
|
||||
}
|
||||
>
|
||||
<PDFPageDocument
|
||||
space={space}
|
||||
page={page}
|
||||
refContext={{
|
||||
space,
|
||||
revisionId: contentTarget.revisionId,
|
||||
pages: rootPages,
|
||||
page,
|
||||
...linksContext,
|
||||
}}
|
||||
/>
|
||||
</React.Suspense>
|
||||
),
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function PDFSpaceIntro(props: {
|
||||
space: Space;
|
||||
customization: CustomizationSettings | SiteCustomizationSettings;
|
||||
}) {
|
||||
const { space, customization } = props;
|
||||
|
||||
return (
|
||||
<PrintPage isFirst>
|
||||
<div className={tcls('flex', 'items-center', 'justify-center', 'py-12')}>
|
||||
<h1 className={tcls('text-6xl', 'font-bold')}>
|
||||
{customization.title ?? space.title}
|
||||
</h1>
|
||||
</div>
|
||||
</PrintPage>
|
||||
);
|
||||
}
|
||||
|
||||
async function PDFPageGroup(props: { space: Space; page: RevisionPageGroup }) {
|
||||
const { page } = props;
|
||||
|
||||
return (
|
||||
<PrintPage id={pagePDFContainerId(page)}>
|
||||
<div
|
||||
className={tcls(
|
||||
'break-before-page',
|
||||
'mt-10',
|
||||
'print:mt-0',
|
||||
'flex',
|
||||
'items-center',
|
||||
'justify-center',
|
||||
'py-12',
|
||||
)}
|
||||
>
|
||||
<h1 className={tcls('text-5xl', 'font-bold')}>{page.title}</h1>
|
||||
</div>
|
||||
</PrintPage>
|
||||
);
|
||||
}
|
||||
|
||||
async function PDFPageDocument(props: {
|
||||
space: Space;
|
||||
page: RevisionPageDocument;
|
||||
refContext: ContentRefContext;
|
||||
}) {
|
||||
const { space, page, refContext } = props;
|
||||
|
||||
const document = page.documentId ? await getDocument(space.id, page.documentId) : null;
|
||||
const shouldHighlightCode = createHighlightingContext();
|
||||
|
||||
return (
|
||||
<PrintPage id={pagePDFContainerId(page)}>
|
||||
<h1 className={tcls('text-4xl', 'font-bold')}>{page.title}</h1>
|
||||
{page.description ? (
|
||||
<p className={tcls('decoration-primary/6', 'mt-2', 'mb-3')}>{page.description}</p>
|
||||
) : null}
|
||||
|
||||
{document ? (
|
||||
<DocumentView
|
||||
document={document}
|
||||
style={'mt-6 space-y-6'}
|
||||
blockStyle={['max-w-full']}
|
||||
context={{
|
||||
mode: 'print',
|
||||
content: {
|
||||
spaceId: space.id,
|
||||
revisionId: refContext.revisionId,
|
||||
},
|
||||
contentRefContext: refContext,
|
||||
resolveContentRef: (ref) => resolveContentRef(ref, refContext),
|
||||
getId: (id) => pagePDFContainerId(page, id),
|
||||
shouldHighlightCode,
|
||||
}}
|
||||
/>
|
||||
) : null}
|
||||
</PrintPage>
|
||||
);
|
||||
}
|
||||
|
||||
function PrintPage(
|
||||
props: PolymorphicComponentProp<
|
||||
'div',
|
||||
{
|
||||
isFirst?: boolean;
|
||||
}
|
||||
>,
|
||||
) {
|
||||
const { children, isFirst, className, ...rest } = props;
|
||||
|
||||
return (
|
||||
<div
|
||||
{...rest}
|
||||
className={tcls(
|
||||
className,
|
||||
'my-11',
|
||||
'print:my-0',
|
||||
'mx-auto',
|
||||
'max-w-4xl',
|
||||
'w-full',
|
||||
'p-12',
|
||||
'print:p-0',
|
||||
'shadow-xl',
|
||||
'print:shadow-none',
|
||||
'rounded-sm',
|
||||
'bg-white',
|
||||
'min-h-[29.7cm]',
|
||||
'print:min-h-0',
|
||||
isFirst ? null : 'break-before-page',
|
||||
'break-anywhere',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
type FlatPageEntry = { page: RevisionPageDocument | RevisionPageGroup; depth: number };
|
||||
|
||||
/**
|
||||
* Compute the ordered flat set of pages to render.
|
||||
*/
|
||||
function selectPages(
|
||||
rootPages: Revision['pages'],
|
||||
params: PDFSearchParams,
|
||||
): { pages: FlatPageEntry[]; total: number } {
|
||||
const flattenPage = (
|
||||
page: RevisionPageDocument | RevisionPageGroup,
|
||||
depth: number,
|
||||
): FlatPageEntry[] => {
|
||||
return [
|
||||
{ page, depth },
|
||||
...page.pages.flatMap((child) => {
|
||||
if (child.type === 'link') {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (child.hidden) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return flattenPage(child, depth + 1);
|
||||
}),
|
||||
];
|
||||
};
|
||||
|
||||
const limitTo = (entries: FlatPageEntry[]) => {
|
||||
return {
|
||||
// Apply a soft-limit, the limit can be controlled by the URL to allow testing
|
||||
pages: entries.slice(0, params.limit ?? DEFAULT_LIMIT),
|
||||
total: entries.length,
|
||||
};
|
||||
};
|
||||
|
||||
if (params.page) {
|
||||
const found = resolvePageId(rootPages, params.page);
|
||||
if (!found) {
|
||||
notFound();
|
||||
}
|
||||
|
||||
if (!params.only) {
|
||||
return limitTo([{ page: found.page, depth: 0 }]);
|
||||
}
|
||||
|
||||
return limitTo(flattenPage(found.page, 0));
|
||||
}
|
||||
|
||||
const allPages = rootPages.flatMap((page) => {
|
||||
if (page.type === 'link') {
|
||||
return [];
|
||||
}
|
||||
|
||||
if (page.hidden) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return flattenPage(page, 0);
|
||||
});
|
||||
return limitTo(allPages);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
@page {
|
||||
size: A4;
|
||||
margin: 60pt 60pt;
|
||||
|
||||
@bottom-right {
|
||||
content: counter(page);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
'use client';
|
||||
|
||||
import React from 'react';
|
||||
import { RecoilRoot } from 'recoil';
|
||||
|
||||
import { TranslateContext } from '@/intl/client';
|
||||
import { TranslationLanguage } from '@/intl/translations';
|
||||
|
||||
export function ClientContexts(props: {
|
||||
language: TranslationLanguage;
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
const { children, language } = props;
|
||||
|
||||
return (
|
||||
<RecoilRoot>
|
||||
<TranslateContext.Provider value={language}>{children}</TranslateContext.Provider>
|
||||
</RecoilRoot>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
'use client';
|
||||
|
||||
import { captureException } from '@sentry/nextjs';
|
||||
import React from 'react';
|
||||
|
||||
import { Button } from '@/components/primitives/Button';
|
||||
import { t, useLanguage } from '@/intl/client';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
export default function ErrorPage(props: {
|
||||
error: Error & { digest?: string };
|
||||
reset: () => void;
|
||||
}) {
|
||||
const { error, reset } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
React.useEffect(() => {
|
||||
captureException(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
'fixed',
|
||||
'w-full',
|
||||
'h-full',
|
||||
'flex',
|
||||
'items-center',
|
||||
'justify-center',
|
||||
'p-7',
|
||||
)}
|
||||
>
|
||||
<div>
|
||||
<h2 className={tcls('text-2xl', 'font-semibold', 'mb-2')}>
|
||||
{t(language, 'unexpected_error_title')}
|
||||
</h2>
|
||||
<p className={tcls('text-base', 'mb-4')}>{t(language, 'unexpected_error')}</p>
|
||||
<div>
|
||||
<Button
|
||||
onClick={() => {
|
||||
reset();
|
||||
}}
|
||||
variant="secondary"
|
||||
size="small"
|
||||
>
|
||||
{t(language, 'unexpected_error_retry')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,227 @@
|
||||
import { ContentVisibility, RevisionPage, Space } from '@gitbook/api';
|
||||
import { headers } from 'next/headers';
|
||||
|
||||
import {
|
||||
getCollectionSpaces,
|
||||
getCollection,
|
||||
ContentPointer,
|
||||
getRevisionPageByPath,
|
||||
getDocument,
|
||||
getSpaceData,
|
||||
ContentTarget,
|
||||
SiteContentPointer,
|
||||
getCurrentSiteData,
|
||||
getSite,
|
||||
getSiteSpaces,
|
||||
} from '@/lib/api';
|
||||
import { resolvePagePath, resolvePageId } from '@/lib/pages';
|
||||
|
||||
export interface PagePathParams {
|
||||
pathname?: string[];
|
||||
}
|
||||
|
||||
export interface PageIdParams {
|
||||
pageId: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current content pointer from the params.
|
||||
*/
|
||||
export function getContentPointer(): ContentPointer | 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',
|
||||
);
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all the data needed to render the space layout.
|
||||
*/
|
||||
export async function fetchSpaceData() {
|
||||
const content = getContentPointer();
|
||||
|
||||
const [{ space, contentTarget, pages, customization, scripts }, parentSite] = await Promise.all(
|
||||
'siteId' in content
|
||||
? [
|
||||
getCurrentSiteData(content),
|
||||
fetchParentSite({
|
||||
organizationId: content.organizationId,
|
||||
siteId: content.siteId,
|
||||
siteShareKey: content.siteShareKey,
|
||||
}),
|
||||
]
|
||||
: [getSpaceData(content)],
|
||||
);
|
||||
|
||||
const parent = await (parentSite ?? fetchParentCollection(space));
|
||||
|
||||
return {
|
||||
content,
|
||||
contentTarget,
|
||||
space,
|
||||
pages,
|
||||
customization,
|
||||
scripts,
|
||||
ancestors: [],
|
||||
...parent,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch all the data needed to render the content.
|
||||
* Optimized to fetch in parallel as much as possible.
|
||||
*/
|
||||
export async function fetchPageData(params: PagePathParams | PageIdParams) {
|
||||
const content = getContentPointer();
|
||||
const { space, contentTarget, pages, customization, scripts } = await ('siteId' in content
|
||||
? getCurrentSiteData(content)
|
||||
: getSpaceData(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),
|
||||
page?.page.documentId ? getDocument(space.id, page.page.documentId) : null,
|
||||
]);
|
||||
|
||||
return {
|
||||
content,
|
||||
contentTarget,
|
||||
space,
|
||||
pages,
|
||||
customization,
|
||||
scripts,
|
||||
ancestors: [],
|
||||
...page,
|
||||
...parent,
|
||||
document,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a page from the params.
|
||||
* If the path can't be found, we try to resolve it from the API to handle redirects.
|
||||
*/
|
||||
async function resolvePage(
|
||||
contentTarget: ContentTarget,
|
||||
pages: RevisionPage[],
|
||||
params: PagePathParams | PageIdParams,
|
||||
) {
|
||||
if ('pageId' in params) {
|
||||
return resolvePageId(pages, params.pageId);
|
||||
}
|
||||
|
||||
const rawPathname = getPathnameParam(params);
|
||||
const pathname = normalizePathname(rawPathname);
|
||||
|
||||
// When resolving a page, we use the lowercased pathname
|
||||
const page = resolvePagePath(pages, pathname);
|
||||
if (page) {
|
||||
return page;
|
||||
}
|
||||
|
||||
// If page can't be found, we try with the API, in case we have a redirect
|
||||
// We use the raw pathname to handle special/malformed redirects setup by users in the GitSync.
|
||||
// The page rendering will take care of redirecting to a normalized pathname.
|
||||
//
|
||||
// We don't test path that are too long as GitBook doesn't support them and will return a 404 anyway.
|
||||
if (rawPathname.length <= 512) {
|
||||
const resolved = await getRevisionPageByPath(
|
||||
contentTarget.spaceId,
|
||||
contentTarget.revisionId,
|
||||
rawPathname,
|
||||
);
|
||||
if (resolved) {
|
||||
return resolvePageId(pages, resolved.id);
|
||||
}
|
||||
}
|
||||
|
||||
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([
|
||||
getSite(organizationId, siteId),
|
||||
getSiteSpaces({ organizationId, siteId, siteShareKey }),
|
||||
]);
|
||||
|
||||
const spaces: Record<string, Space> = {};
|
||||
siteSpaces.forEach((siteSpace) => {
|
||||
spaces[siteSpace.space.id] = {
|
||||
...siteSpace.space,
|
||||
urls: {
|
||||
...siteSpace.space.urls,
|
||||
published: siteSpace.urls.published,
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
return { parent: site, spaces: Object.values(spaces) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the page path from the params.
|
||||
*/
|
||||
export function getPathnameParam(params: PagePathParams): string {
|
||||
const { pathname } = params;
|
||||
return pathname ? pathname.map((part) => decodeURIComponent(part)).join('/') : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the URL pathname into the format used in the revision page path.
|
||||
*/
|
||||
export function normalizePathname(pathname: string) {
|
||||
return pathname.toLowerCase();
|
||||
}
|
||||
@@ -0,0 +1,235 @@
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
@layer base {
|
||||
:root {
|
||||
--scrollbar-width: calc(100vw - 100%);
|
||||
|
||||
--dark-base: 20 20 20;
|
||||
--light-base: 251 252 252;
|
||||
|
||||
--light-1: color-mix(in srgb, rgb(var(--primary-base-600)), rgb(var(--light-base)) 99%);
|
||||
--light-DEFAULT: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-700)),
|
||||
rgb(var(--light-base)) 96%
|
||||
);
|
||||
--light-2: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 92%);
|
||||
--light-3: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 88%);
|
||||
--light-4: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 72%);
|
||||
|
||||
--dark-1: color-mix(in srgb, rgb(var(--primary-base-100)), rgb(1 1 1) 96%);
|
||||
--dark-DEFAULT: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-300)),
|
||||
rgb(var(--dark-base)) 94.5%
|
||||
);
|
||||
--dark-2: color-mix(in srgb, rgb(var(--primary-base-200)), rgb(var(--dark-base)) 92%);
|
||||
--dark-3: color-mix(in srgb, rgb(var(--primary-base-200)), rgb(25 25 25) 91%);
|
||||
--dark-4: color-mix(in srgb, rgb(var(--primary-base-200)), rgb(var(--dark-base)) 64%);
|
||||
@apply leading-relaxed;
|
||||
}
|
||||
body {
|
||||
@apply text-dark dark:text-light;
|
||||
}
|
||||
html {
|
||||
@apply gutter-stable;
|
||||
}
|
||||
html:is(.plain-background) {
|
||||
--dark-base: 22 22 22;
|
||||
--light-base: 255 255 255;
|
||||
/* reset primaries as greys */
|
||||
--primary-base-50: 239 239 239;
|
||||
--primary-base-100: 222 222 222;
|
||||
--primary-base-200: 200 200 200;
|
||||
--primary-base-300: 180 180 180;
|
||||
--primary-base-400: 150 150 150;
|
||||
--primary-base-500: 120 120 120;
|
||||
--primary-base-600: 90 90 90;
|
||||
--primary-base-700: 70 70 70;
|
||||
--primary-base-800: 30 30 30;
|
||||
--primary-base-900: 19 19 19;
|
||||
|
||||
--light-DEFAULT: color-mix(
|
||||
in srgb,
|
||||
rgb(var(--primary-base-700)),
|
||||
rgb(var(--light-base)) 100%
|
||||
);
|
||||
--light-2: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 96%);
|
||||
--light-3: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 90%);
|
||||
--light-4: color-mix(in srgb, rgb(var(--primary-base-800)), rgb(var(--light-base)) 76%);
|
||||
}
|
||||
h1 {
|
||||
@apply tracking-[-0.025em] text-dark dark:text-light text-balance;
|
||||
}
|
||||
h2,
|
||||
h3,
|
||||
h4,
|
||||
h5,
|
||||
h6 {
|
||||
@apply tracking-[-0.0125em] text-dark dark:text-light;
|
||||
}
|
||||
|
||||
a,
|
||||
button,
|
||||
input,
|
||||
textarea {
|
||||
@apply outline-2 outline-primary/6;
|
||||
}
|
||||
|
||||
/* Light mode */
|
||||
::-webkit-scrollbar {
|
||||
@apply bg-dark/1;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb {
|
||||
@apply bg-dark/4;
|
||||
border-radius: 8px;
|
||||
}
|
||||
|
||||
::-webkit-scrollbar-thumb:hover {
|
||||
@apply bg-dark/5;
|
||||
}
|
||||
|
||||
/* Dark mode */
|
||||
.dark ::-webkit-scrollbar {
|
||||
@apply bg-light/1;
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb {
|
||||
@apply bg-light/3;
|
||||
}
|
||||
|
||||
.dark ::-webkit-scrollbar-thumb:hover {
|
||||
@apply bg-light/4;
|
||||
}
|
||||
|
||||
/* Inverted theme light mode */
|
||||
.inverted-theme-scroll::-webkit-scrollbar {
|
||||
@apply bg-transparent;
|
||||
}
|
||||
|
||||
.inverted-theme-scroll::-webkit-scrollbar-thumb {
|
||||
@apply bg-dark/5;
|
||||
}
|
||||
|
||||
.inverted-theme-scroll::-webkit-scrollbar-thumb:hover {
|
||||
@apply bg-dark/6;
|
||||
}
|
||||
|
||||
.flip-heading-hash {
|
||||
@apply [&:is(h1,h2,h3,h4)]:content-start;
|
||||
@apply [&:is(h1,h2,h3,h4)]:[grid-auto-columns:auto_1fr];
|
||||
@apply [&:is(h1,h2,h3,h4)>div:first-child]:[grid-area:1/2];
|
||||
@apply [&:is(h1,h2,h3,h4)>div:first-child]:ml-1;
|
||||
}
|
||||
|
||||
/* bullet icons */
|
||||
.bullet-dash {
|
||||
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjEiIHk9IjIuNSIgd2lkdGg9IjgiIGhlaWdodD0iMS41IiByeD0iMC42NiIgZmlsbD0id2hpdGUiLz4KPC9zdmc+Cg==")];
|
||||
}
|
||||
.bullet-circleFilled {
|
||||
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjIiIHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHJ4PSIzIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K")];
|
||||
}
|
||||
.bullet-circle {
|
||||
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjIuNzUiIHk9IjAuNzUiIHdpZHRoPSI1LjUiIGhlaWdodD0iNS41IiByeD0iMi43NSIgc3Ryb2tlPSJ3aGl0ZSIgc3Ryb2tlLXdpZHRoPSIxLjUiLz4KPC9zdmc+Cg==")];
|
||||
}
|
||||
.bullet-squareFilled {
|
||||
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxyZWN0IHg9IjIiIHdpZHRoPSI2IiBoZWlnaHQ9IjYiIHJ4PSIxIiBmaWxsPSJ3aGl0ZSIvPgo8L3N2Zz4K")];
|
||||
}
|
||||
.bullet-square {
|
||||
@apply [mask-image:url("data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAiIGhlaWdodD0iNyIgdmlld0JveD0iMCAwIDEwIDciIGZpbGw9Im5vbmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyI+CjxtYXNrIGlkPSJwYXRoLTEtaW5zaWRlLTFfOV80OCIgZmlsbD0id2hpdGUiPgo8cmVjdCB4PSIyIiB3aWR0aD0iNyIgaGVpZ2h0PSI3IiByeD0iMSIvPgo8L21hc2s+CjxyZWN0IHg9IjIiIHdpZHRoPSI3IiBoZWlnaHQ9IjciIHJ4PSIxIiBzdHJva2U9IndoaXRlIiBzdHJva2Utd2lkdGg9IjMiIG1hc2s9InVybCgjcGF0aC0xLWluc2lkZS0xXzlfNDgpIi8+Cjwvc3ZnPgo=")];
|
||||
}
|
||||
}
|
||||
|
||||
@layer utilities {
|
||||
/* hide scroll bar but still scroll */
|
||||
.hide-scroll::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
.hide-scroll {
|
||||
scrollbar-width: none;
|
||||
-ms-overflow-style: none;
|
||||
}
|
||||
|
||||
.linear-mask-gradient {
|
||||
mask-image: linear-gradient(to bottom, rgba(0, 0, 0, 1) 96px, rgba(0, 0, 0, 0));
|
||||
}
|
||||
.linear-mask-util {
|
||||
mask-image: linear-gradient(to bottom, white, white);
|
||||
}
|
||||
.grid-area-1-1 {
|
||||
grid-area: 1/1;
|
||||
}
|
||||
.gutter-stable {
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
.triangle {
|
||||
position: relative;
|
||||
background-color: orange;
|
||||
text-align: left;
|
||||
transform: rotate(-60deg) skewX(-30deg) scale(1, 0.866);
|
||||
}
|
||||
.triangle:before,
|
||||
.triangle:after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
background-color: inherit;
|
||||
}
|
||||
.triangle,
|
||||
.triangle:before,
|
||||
.triangle:after {
|
||||
width: inherit;
|
||||
height: inherit;
|
||||
border-top-right-radius: 30%;
|
||||
}
|
||||
|
||||
.triangle:before {
|
||||
transform: rotate(-135deg) skewX(-45deg) scale(1.414, 0.707) translate(0, -50%);
|
||||
}
|
||||
.triangle:after {
|
||||
transform: rotate(135deg) skewY(-45deg) scale(0.707, 1.414) translate(50%);
|
||||
}
|
||||
|
||||
.break-anywhere {
|
||||
word-break: break-word;
|
||||
}
|
||||
@supports (overflow-wrap: anywhere) {
|
||||
.break-anywhere {
|
||||
word-break: break-word;
|
||||
overflow-wrap: anywhere;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Utility to prevent horizontal jumps when the vertical scrollbar appears
|
||||
* It should be used on main containers of the layout, while preserving horizontal delimiters.
|
||||
* It basically adds a margin-left with the width of the scrollbar, and a width that compensates for it; when a scrollbar is displayed.
|
||||
* Inspired by https://aykevl.nl/2014/09/fix-jumping-scrollbar, but adapted to work on child elements of "html"
|
||||
*/
|
||||
.scroll-nojump {
|
||||
width: 100%;
|
||||
}
|
||||
@media screen and (min-width: 1536px) {
|
||||
.scroll-nojump {
|
||||
margin-left: var(--scrollbar-width);
|
||||
margin-right: 0;
|
||||
width: calc(100% - var(--scrollbar-width));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
html {
|
||||
color-scheme: light;
|
||||
|
||||
/** Ensure PDF export and print correctly displays the background colors */
|
||||
print-color-adjust: exact;
|
||||
-webkit-print-color-adjust: exact;
|
||||
}
|
||||
html.dark {
|
||||
color-scheme: dark light;
|
||||
}
|
||||
@@ -0,0 +1,190 @@
|
||||
import {
|
||||
CustomizationBackground,
|
||||
CustomizationCorners,
|
||||
CustomizationHeaderPreset,
|
||||
CustomizationSettings,
|
||||
SiteCustomizationSettings,
|
||||
} from '@gitbook/api';
|
||||
import assertNever from 'assert-never';
|
||||
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 { hexToRgb, shadesOfColor } from '@/lib/colors';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { ClientContexts } from './ClientContexts';
|
||||
import './globals.css';
|
||||
import { getContentPointer } from './fetch';
|
||||
|
||||
/**
|
||||
* Layout shared between the content and the PDF renderer.
|
||||
* It takes care of setting the theme and the language.
|
||||
*/
|
||||
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 headerTheme = generateHeaderTheme(customization);
|
||||
const language = getSpaceLanguage(customization);
|
||||
|
||||
return (
|
||||
<html
|
||||
suppressHydrationWarning
|
||||
lang={customization.internationalization.locale}
|
||||
className={
|
||||
tcls(
|
||||
customization.header.preset === CustomizationHeaderPreset.None
|
||||
? null
|
||||
: [
|
||||
// Take the sticky header in consideration for the scrolling
|
||||
`scroll-pt-[76px]`,
|
||||
],
|
||||
) +
|
||||
(customization.styling.corners === CustomizationCorners.Straight
|
||||
? ' straight-corners'
|
||||
: '') +
|
||||
(customization.styling.background === CustomizationBackground.Plain
|
||||
? ' plain-background'
|
||||
: '')
|
||||
}
|
||||
>
|
||||
<head>
|
||||
{customization.privacyPolicy.url ? (
|
||||
<link rel="privacy-policy" href={customization.privacyPolicy.url} />
|
||||
) : null}
|
||||
<style
|
||||
nonce={
|
||||
//Since I can't get the nonce to work for inline styles, we need to allow unsafe-inline
|
||||
undefined
|
||||
}
|
||||
>{`
|
||||
:root {
|
||||
${generateColorVariable(
|
||||
'primary-color',
|
||||
customization.styling.primaryColor.light,
|
||||
)}
|
||||
${generateColorVariable(
|
||||
'primary-base',
|
||||
customization.styling.primaryColor.light,
|
||||
)}
|
||||
${generateColorVariable(
|
||||
'header-background',
|
||||
headerTheme.backgroundColor.light,
|
||||
)}
|
||||
${generateColorVariable('header-link', headerTheme.linkColor.light)}
|
||||
}
|
||||
.dark {
|
||||
${generateColorVariable(
|
||||
'primary-color',
|
||||
customization.styling.primaryColor.dark,
|
||||
)}
|
||||
${generateColorVariable(
|
||||
'primary-base',
|
||||
customization.styling.primaryColor.dark,
|
||||
)}
|
||||
${generateColorVariable(
|
||||
'header-background',
|
||||
headerTheme.backgroundColor.dark,
|
||||
)}
|
||||
${generateColorVariable('header-link', headerTheme.linkColor.dark)}
|
||||
}
|
||||
`}</style>
|
||||
</head>
|
||||
<body
|
||||
className={tcls(
|
||||
emojiFontClassName,
|
||||
`${fonts[customization.styling.font].className}`,
|
||||
`${ibmPlexMono.variable}`,
|
||||
'bg-light',
|
||||
'dark:bg-dark',
|
||||
)}
|
||||
>
|
||||
<ClientContexts language={language}>{children}</ClientContexts>
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
type ColorInput = string | Record<string, string>;
|
||||
function generateColorVariable(name: string, color: ColorInput) {
|
||||
const shades: Record<string, string> = typeof color === 'string' ? shadesOfColor(color) : color;
|
||||
|
||||
return Object.entries(shades)
|
||||
.map(([key, value]) => {
|
||||
// Check the original hex value
|
||||
const rgbValue = hexToRgb(value);
|
||||
return `--${name}-${key}: ${rgbValue};`;
|
||||
})
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
function generateHeaderTheme(customization: CustomizationSettings | SiteCustomizationSettings): {
|
||||
backgroundColor: { light: ColorInput; dark: ColorInput };
|
||||
linkColor: { light: ColorInput; dark: ColorInput };
|
||||
} {
|
||||
switch (customization.header.preset) {
|
||||
case CustomizationHeaderPreset.None:
|
||||
case CustomizationHeaderPreset.Default: {
|
||||
return {
|
||||
backgroundColor: {
|
||||
light: colors.white,
|
||||
dark: colors.black,
|
||||
},
|
||||
linkColor: {
|
||||
light: customization.styling.primaryColor.light,
|
||||
dark: customization.styling.primaryColor.dark,
|
||||
},
|
||||
};
|
||||
}
|
||||
case CustomizationHeaderPreset.Bold: {
|
||||
return {
|
||||
backgroundColor: {
|
||||
light: customization.styling.primaryColor.light,
|
||||
dark: customization.styling.primaryColor.dark,
|
||||
},
|
||||
linkColor: {
|
||||
// TODO: should depend on the color of the background
|
||||
light: colors.white,
|
||||
dark: colors.black,
|
||||
},
|
||||
};
|
||||
}
|
||||
case CustomizationHeaderPreset.Contrast: {
|
||||
return {
|
||||
backgroundColor: {
|
||||
light: colors.black,
|
||||
dark: colors.white,
|
||||
},
|
||||
linkColor: {
|
||||
light: colors.white,
|
||||
dark: colors.black,
|
||||
},
|
||||
};
|
||||
}
|
||||
case CustomizationHeaderPreset.Custom: {
|
||||
return {
|
||||
backgroundColor: {
|
||||
light: customization.header.backgroundColor?.light ?? colors.white,
|
||||
dark: customization.header.backgroundColor?.dark ?? colors.black,
|
||||
},
|
||||
linkColor: {
|
||||
light:
|
||||
customization.header.linkColor?.light ??
|
||||
customization.styling.primaryColor.light,
|
||||
dark:
|
||||
customization.header.linkColor?.dark ??
|
||||
customization.styling.primaryColor.dark,
|
||||
},
|
||||
};
|
||||
}
|
||||
default: {
|
||||
assertNever(customization.header.preset);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
'use client';
|
||||
|
||||
import { captureException } from '@sentry/nextjs';
|
||||
import Error from 'next/error';
|
||||
import { useEffect } from 'react';
|
||||
|
||||
export default function GlobalError({ error }: { error: Error }) {
|
||||
useEffect(() => {
|
||||
captureException(error);
|
||||
}, [error]);
|
||||
|
||||
return (
|
||||
<html>
|
||||
<body>
|
||||
<Error statusCode={undefined as any} />
|
||||
</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { NextRequest, NextResponse } from 'next/server';
|
||||
|
||||
type ProxyRequest = {
|
||||
url: string;
|
||||
method: string;
|
||||
headers: Record<string, string>;
|
||||
data: Record<string, any>;
|
||||
};
|
||||
|
||||
export const runtime = 'edge';
|
||||
|
||||
/**
|
||||
* Taken from https://github.com/scalar/scalar/tree/main/packages/api-client-proxy
|
||||
*/
|
||||
export async function POST(req: NextRequest) {
|
||||
const requestBody: ProxyRequest = await req.json();
|
||||
|
||||
const isGetOrHeadRequest = ['get', 'head'].includes(requestBody.method.trim().toLowerCase());
|
||||
const body = isGetOrHeadRequest
|
||||
? null
|
||||
: requestBody.data
|
||||
? JSON.stringify(requestBody.data)
|
||||
: null;
|
||||
|
||||
// Default options are marked with *
|
||||
try {
|
||||
const response = await fetch(requestBody.url.trim(), {
|
||||
// *GET, POST, PUT, DELETE, etc.
|
||||
method: requestBody.method.trim(),
|
||||
// no-cors, *cors, same-origin
|
||||
// mode: 'cors', // Not supported on Cloudflare Workers
|
||||
// *default, no-cache, reload, force-cache, only-if-cached
|
||||
cache: 'no-cache',
|
||||
// include, *same-origin, omit
|
||||
// credentials: 'include', // Not supported on Cloudflare Workers
|
||||
headers: requestBody.headers,
|
||||
// manual, *follow, error
|
||||
redirect: 'follow',
|
||||
// no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url
|
||||
// referrerPolicy: 'no-referrer', // Not supported on Cloudflare Workers
|
||||
// body data type must match "Content-Type" header
|
||||
body,
|
||||
});
|
||||
|
||||
const headers: Record<string, string> = {};
|
||||
|
||||
const proxyHeaders = [...response.headers];
|
||||
proxyHeaders.forEach(([key, value]) => {
|
||||
if (['access-control-allow-origin'].includes(key.toLowerCase())) {
|
||||
return;
|
||||
}
|
||||
|
||||
headers[key] = value;
|
||||
});
|
||||
|
||||
const text = await response.text();
|
||||
|
||||
return NextResponse.json({
|
||||
statusCode: response.status,
|
||||
// TODO: Do we need body?
|
||||
// body: …
|
||||
data: text,
|
||||
headers: {
|
||||
...headers,
|
||||
'X-API-Client-Content-Length': text.length,
|
||||
},
|
||||
// TODO: transform cookie data
|
||||
cookies: response.headers.get('cookies'),
|
||||
});
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'Scalar API Client Proxy Error',
|
||||
(error as Error).stack ?? (error as Error).message ?? error,
|
||||
);
|
||||
return NextResponse.json({
|
||||
data: 'Scalar API Client Proxy Error',
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,113 @@
|
||||
import { Space } from '@gitbook/api';
|
||||
import React from 'react';
|
||||
|
||||
import { ContentPointer, getChangeRequest, getRevision } from '@/lib/api';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
interface AdminToolbarProps {
|
||||
content: ContentPointer;
|
||||
space: Space;
|
||||
}
|
||||
|
||||
/**
|
||||
* Toolbar with information for the content admin when previewing a revision or change-request.
|
||||
*/
|
||||
export function AdminToolbar(props: AdminToolbarProps) {
|
||||
const { content } = props;
|
||||
|
||||
const toolbar = (() => {
|
||||
if (content.changeRequestId) {
|
||||
return (
|
||||
<ChangeRequestToolbar
|
||||
spaceId={content.spaceId}
|
||||
changeRequestId={content.changeRequestId}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
if (content.revisionId) {
|
||||
return <RevisionToolbar spaceId={content.spaceId} revisionId={content.revisionId} />;
|
||||
}
|
||||
|
||||
return null;
|
||||
})();
|
||||
|
||||
if (!toolbar) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
'fixed',
|
||||
'bottom-5',
|
||||
'left-1/2',
|
||||
'z-50',
|
||||
'transform',
|
||||
'-translate-x-1/2',
|
||||
'rounded-full',
|
||||
'bg-dark-1/9',
|
||||
'shadow-lg',
|
||||
'min-h-10',
|
||||
'min-w-40',
|
||||
'p-2',
|
||||
'max-w-md',
|
||||
'border-dark-1',
|
||||
'backdrop-blur-sm',
|
||||
)}
|
||||
>
|
||||
<React.Suspense fallback={null}>{toolbar}</React.Suspense>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
async function ChangeRequestToolbar(props: { spaceId: string; changeRequestId: string }) {
|
||||
const { spaceId, changeRequestId } = props;
|
||||
|
||||
const changeRequest = await getChangeRequest(spaceId, changeRequestId);
|
||||
|
||||
return (
|
||||
<ToolbarButton href={changeRequest.urls.app}>
|
||||
Change request #{changeRequest.number}: {changeRequest.subject ?? 'No subject'}
|
||||
</ToolbarButton>
|
||||
);
|
||||
}
|
||||
|
||||
async function RevisionToolbar(props: { spaceId: string; revisionId: string }) {
|
||||
const { spaceId, revisionId } = props;
|
||||
|
||||
const revision = await getRevision(spaceId, revisionId, {
|
||||
metadata: false,
|
||||
});
|
||||
|
||||
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>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './AdminToolbar';
|
||||
@@ -0,0 +1,200 @@
|
||||
'use client';
|
||||
|
||||
import IconHeart from '@geist-ui/icons/heart';
|
||||
import * as React from 'react';
|
||||
|
||||
import { ClassValue, tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AdClassicRendering } from './AdClassicRendering';
|
||||
import { AdCoverRendering } from './AdCoverRendering';
|
||||
import { AdItem, AdsResponse } from './types';
|
||||
|
||||
/**
|
||||
* Fetch and render the Ad placement.
|
||||
* https://docs.buysellads.com/ad-serving-api
|
||||
*/
|
||||
export function Ad({
|
||||
zoneId,
|
||||
spaceId,
|
||||
placement,
|
||||
ignore,
|
||||
style,
|
||||
mode = 'auto',
|
||||
}: {
|
||||
zoneId: string;
|
||||
spaceId: string;
|
||||
placement: string;
|
||||
ignore: boolean;
|
||||
style?: ClassValue;
|
||||
mode?: 'classic' | 'auto' | 'cover';
|
||||
}) {
|
||||
const containerRef = React.useRef<HTMLDivElement>(null);
|
||||
const [visible, setVisible] = React.useState(false);
|
||||
const [failed, setFailed] = React.useState(false);
|
||||
const [ad, setAd] = React.useState<AdItem | undefined>(undefined);
|
||||
|
||||
// Observe the container visibility
|
||||
React.useEffect(() => {
|
||||
if (!containerRef.current) {
|
||||
return;
|
||||
}
|
||||
|
||||
const observer = new IntersectionObserver(
|
||||
([entry]) => {
|
||||
if (entry.isIntersecting) {
|
||||
setVisible(true);
|
||||
}
|
||||
},
|
||||
{
|
||||
root: null,
|
||||
rootMargin: '0px',
|
||||
threshold: 0.1,
|
||||
},
|
||||
);
|
||||
|
||||
observer.observe(containerRef.current);
|
||||
|
||||
return () => {
|
||||
observer.disconnect();
|
||||
};
|
||||
}, []);
|
||||
|
||||
// When the container is visible,
|
||||
// track an impression on the ad and fetch it
|
||||
React.useEffect(() => {
|
||||
if (!visible) {
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
(async () => {
|
||||
const url = new URL(`https://srv.buysellads.com/ads/${zoneId}.json`);
|
||||
url.searchParams.set('segment', `placement:${placement}`);
|
||||
url.searchParams.set('v', 'true');
|
||||
if (ignore) {
|
||||
url.searchParams.set('ignore', 'true');
|
||||
}
|
||||
|
||||
try {
|
||||
const res = await fetch(url);
|
||||
const json: AdsResponse = await res.json();
|
||||
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
const first = json.ads[0];
|
||||
if (first && 'active' in first) {
|
||||
setAd(first);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(
|
||||
'Failed to fetch ad, it might have been blocked by a ad-blocker',
|
||||
error,
|
||||
);
|
||||
setFailed(true);
|
||||
}
|
||||
})();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [visible, zoneId, ignore, placement]);
|
||||
|
||||
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);
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className={tcls(style)}>
|
||||
{ad && ad.description && ad.statlink ? (
|
||||
<>
|
||||
{mode === 'classic' || !('callToAction' in ad) ? (
|
||||
<AdClassicRendering ad={ad} />
|
||||
) : (
|
||||
<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',
|
||||
)}
|
||||
>
|
||||
<a
|
||||
target="_blank"
|
||||
href={viaUrl.toString()}
|
||||
className={tcls('hover:underline')}
|
||||
>
|
||||
Ads via GitBook
|
||||
</a>
|
||||
</p>
|
||||
</>
|
||||
) : failed ? (
|
||||
<AdBlockerPlaceholder />
|
||||
) : null}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render attribution or verification pixels.
|
||||
* https://docs.buysellads.com/ad-serving-api#pixels
|
||||
*/
|
||||
function AdPixels({ rawPixel }: { rawPixel: string }) {
|
||||
const pixels = rawPixel.split('||');
|
||||
const time = String(Math.round(Date.now() / 1e4) | 0);
|
||||
|
||||
return (
|
||||
<div className={tcls('hidden')}>
|
||||
{pixels.map((pixel, index) => {
|
||||
return (
|
||||
<img
|
||||
key={index}
|
||||
src={pixel.replace('[timestamp]', time)}
|
||||
width="1"
|
||||
height="1"
|
||||
style={{ display: 'none' }}
|
||||
alt="Ads tracking pixel"
|
||||
/>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Placeholder when visitor has an ad-blocker.
|
||||
*/
|
||||
function AdBlockerPlaceholder() {
|
||||
return (
|
||||
<div
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-col',
|
||||
'gap-3',
|
||||
'bg-light-2',
|
||||
'text-dark/7',
|
||||
'dark:bg-dark-2',
|
||||
'dark:text-light/7',
|
||||
'rounded-lg',
|
||||
'p-4',
|
||||
)}
|
||||
>
|
||||
<div className={tcls('flex', 'flex-row', 'gap-2', 'items-center')}>
|
||||
<IconHeart className={tcls('w-4', 'h-4', 'text-primary-500')} />
|
||||
<p className={tcls('text-xs', 'font-semibold')}>Ad disabled</p>
|
||||
</div>
|
||||
<p className={tcls('text-xs')}>
|
||||
{`It looks like you're using an adblocker. Whitelist this site to help support this
|
||||
project.`}
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
import * as React from 'react';
|
||||
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AdItem } from './types';
|
||||
|
||||
/**
|
||||
* Classic rendering for an ad.
|
||||
*/
|
||||
export function AdClassicRendering({ ad }: { ad: AdItem }) {
|
||||
return (
|
||||
<a
|
||||
className={tcls(
|
||||
'flex',
|
||||
'flex-col',
|
||||
'gap-4',
|
||||
'bg-light-2',
|
||||
'text-dark/7',
|
||||
'dark:bg-dark-2',
|
||||
'dark:text-light/7',
|
||||
'hover:text-dark/9',
|
||||
'dark:hover:text-light/9',
|
||||
'rounded-lg',
|
||||
'p-4',
|
||||
)}
|
||||
href={ad.statlink}
|
||||
rel="sponsored noopener"
|
||||
target="_blank"
|
||||
>
|
||||
{'smallImage' in ad ? (
|
||||
<div>
|
||||
<img alt="Ads logo" className={tcls('rounded-md')} src={ad.smallImage} />
|
||||
</div>
|
||||
) : (
|
||||
<div
|
||||
className={tcls('px-6', 'py-4', 'rounded-md')}
|
||||
style={{ backgroundColor: ad.backgroundColor }}
|
||||
>
|
||||
<img alt="Ads logo" src={ad.logo} />
|
||||
</div>
|
||||
)}
|
||||
<div className={tcls('flex', 'flex-col')}>
|
||||
<div className={tcls('text-xs')}>{ad.description}</div>
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import * as React from 'react';
|
||||
|
||||
import { hexToRgba } from '@/lib/colors';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
import { AdCover } from './types';
|
||||
|
||||
/**
|
||||
* Cover rendering for an ad.
|
||||
*/
|
||||
export function AdCoverRendering({ ad }: { ad: AdCover }) {
|
||||
return (
|
||||
<a
|
||||
className={tcls(
|
||||
'group/ad',
|
||||
'relative',
|
||||
'flex',
|
||||
'flex-col',
|
||||
'gap-4',
|
||||
'bg-light-2',
|
||||
'text-dark/7',
|
||||
'dark:bg-dark-2',
|
||||
'dark:text-light/7',
|
||||
'hover:text-dark/9',
|
||||
'dark:hover:text-light/9',
|
||||
'rounded-lg',
|
||||
'p-4',
|
||||
'overflow-hidden',
|
||||
'shadow-sm',
|
||||
)}
|
||||
style={{ backgroundColor: ad.backgroundColor, color: ad.textColor ?? '#ffffff' }}
|
||||
href={ad.statlink}
|
||||
rel="sponsored noopener"
|
||||
target="_blank"
|
||||
>
|
||||
<div
|
||||
className={tcls(
|
||||
'absolute',
|
||||
'inset-0',
|
||||
'bg-center',
|
||||
'bg-cover',
|
||||
'bg-no-repeat',
|
||||
'z-0',
|
||||
)}
|
||||
style={{
|
||||
backgroundImage: `url(${ad.largeImage})`,
|
||||
}}
|
||||
/>
|
||||
|
||||
<div className={tcls('z-[2]')}>
|
||||
<img
|
||||
alt="Large image"
|
||||
src={ad.largeImage}
|
||||
className={tcls(
|
||||
'rounded-md',
|
||||
'shadow-md',
|
||||
'max-h-32',
|
||||
'group-hover/ad:max-h-16',
|
||||
'transition-all',
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className={tcls('z-[2]')}>
|
||||
<img alt={ad.company} src={ad.logo} className={tcls('max-w-36', 'max-h-12')} />
|
||||
</div>
|
||||
<div className={tcls('flex', 'flex-col', 'z-[2]')}>
|
||||
<div className={tcls('text-sm', 'font-semibold', 'mb-2')}>{ad.companyTagline}</div>
|
||||
<div
|
||||
className={tcls(
|
||||
'text-xs',
|
||||
'h-0',
|
||||
'opacity-0',
|
||||
'group-hover/ad:h-16',
|
||||
'group-hover/ad:opacity-10',
|
||||
'transition-all',
|
||||
)}
|
||||
>
|
||||
{ad.description}
|
||||
</div>
|
||||
</div>
|
||||
<div className={tcls('z-[2]')}>
|
||||
<span
|
||||
className={tcls(
|
||||
'text-sm',
|
||||
'font-semibold',
|
||||
'shadow-lg',
|
||||
'rounded-md',
|
||||
'bg-white',
|
||||
'py-2',
|
||||
'px-4',
|
||||
)}
|
||||
style={{
|
||||
backgroundColor: ad.ctaBackgroundColor,
|
||||
color: ad.ctaTextColor ?? ad.backgroundColor,
|
||||
}}
|
||||
>
|
||||
{ad.callToAction}
|
||||
</span>
|
||||
</div>
|
||||
<div
|
||||
className={tcls('absolute', 'inset-0', 'backdrop-blur', 'z-[1]')}
|
||||
style={{
|
||||
backgroundColor: hexToRgba(ad.backgroundColor, 0.8),
|
||||
}}
|
||||
/>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './Ad';
|
||||
@@ -0,0 +1,51 @@
|
||||
export interface AdGeneric {
|
||||
active: string;
|
||||
ad_via_link: string;
|
||||
bannerid: string;
|
||||
creativeid: string;
|
||||
evenodd: string;
|
||||
external_id: string;
|
||||
height: string;
|
||||
i: string;
|
||||
identifier: string;
|
||||
longimp: string;
|
||||
longlink: string;
|
||||
num_slots: string;
|
||||
statimp: string;
|
||||
statlink: string;
|
||||
timestamp: string;
|
||||
width: string;
|
||||
zoneid: string;
|
||||
zonekey: string;
|
||||
rendering: 'carbon';
|
||||
pixel?: string;
|
||||
}
|
||||
|
||||
export interface AdClassic extends AdGeneric {
|
||||
description: string;
|
||||
smallImage: string;
|
||||
}
|
||||
|
||||
export interface AdCover extends AdGeneric {
|
||||
backgroundColor: string;
|
||||
backgroundHoverColor?: string;
|
||||
textColor?: string;
|
||||
textColorHover?: string;
|
||||
callToAction: string;
|
||||
company: string;
|
||||
companyTagline: string;
|
||||
description: string;
|
||||
largeImage: string;
|
||||
image?: string;
|
||||
logo: string;
|
||||
ctaBackgroundColor?: string;
|
||||
ctaBackgroundHoverColor?: string;
|
||||
ctaTextColor?: string;
|
||||
ctaTextColorHover?: string;
|
||||
}
|
||||
|
||||
export type AdItem = AdClassic | AdCover;
|
||||
|
||||
export interface AdsResponse {
|
||||
ads: Array<AdItem | {}>;
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
'use client';
|
||||
|
||||
import IconX from '@geist-ui/icons/x';
|
||||
import * as React from 'react';
|
||||
|
||||
import { Button } from '@/components/primitives';
|
||||
import { useLanguage } from '@/intl/client';
|
||||
import { t, tString } from '@/intl/translate';
|
||||
import { isCookiesTrackingDisabled, setCookiesTracking } from '@/lib/analytics';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
/**
|
||||
* Toast to accept or reject the use of cookies.
|
||||
*/
|
||||
export function CookiesToast(props: { privacyPolicy?: string }) {
|
||||
const { privacyPolicy = 'https://policies.gitbook.com/privacy/cookies' } = props;
|
||||
const [show, setShow] = React.useState(false);
|
||||
const language = useLanguage();
|
||||
|
||||
React.useEffect(() => {
|
||||
setShow(isCookiesTrackingDisabled() === undefined);
|
||||
}, []);
|
||||
|
||||
if (!show) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const onUpdateState = (enabled: boolean) => {
|
||||
setCookiesTracking(enabled);
|
||||
|
||||
// Reload the page to take the change in consideration
|
||||
window.location.reload();
|
||||
};
|
||||
|
||||
const describedById = 'cookies-description';
|
||||
|
||||
return (
|
||||
<div
|
||||
role="dialog"
|
||||
data-testid="cookies-dialog"
|
||||
aria-modal="true"
|
||||
aria-label={tString(language, 'cookies_title')}
|
||||
aria-describedby={describedById}
|
||||
className={tcls(
|
||||
'fixed',
|
||||
'z-10',
|
||||
'bg-white',
|
||||
'rounded',
|
||||
'straight-corners:rounded-none',
|
||||
'ring-1',
|
||||
'ring-dark/2',
|
||||
'shadow-1xs',
|
||||
'p-4',
|
||||
'pr-8',
|
||||
'bottom-4',
|
||||
'right-4',
|
||||
'left-16',
|
||||
'max-w-md',
|
||||
'text-balance',
|
||||
'sm:left-auto',
|
||||
'dark:ring-light/2',
|
||||
'dark:bg-dark',
|
||||
)}
|
||||
>
|
||||
<p id={describedById} className={tcls('text-sm')}>
|
||||
{t(
|
||||
language,
|
||||
'cookies_prompt',
|
||||
<a
|
||||
href={privacyPolicy}
|
||||
className={tcls('text-primary-500', 'hover:text-primary-600', 'underline')}
|
||||
>
|
||||
{t(language, 'cookies_prompt_privacy')}
|
||||
</a>,
|
||||
)}
|
||||
</p>
|
||||
<button
|
||||
onClick={() => setShow(false)}
|
||||
aria-label={tString(language, 'cookies_close')}
|
||||
className={tcls(
|
||||
'absolute',
|
||||
'top-3',
|
||||
'right-3',
|
||||
'w-6',
|
||||
'h-6',
|
||||
'flex',
|
||||
'justify-center',
|
||||
'items-center',
|
||||
'rounded-sm',
|
||||
'hover:bg-dark/2',
|
||||
'dark:hover:bg-light/1',
|
||||
)}
|
||||
title={tString(language, 'cookies_close')}
|
||||
>
|
||||
<IconX className={tcls('w-4')} />
|
||||
</button>
|
||||
<div className={tcls('mt-3', 'flex', 'flex-row', 'gap-2')}>
|
||||
<Button
|
||||
variant="primary"
|
||||
size="small"
|
||||
aria-label={tString(language, 'cookies_accept')}
|
||||
onClick={() => {
|
||||
onUpdateState(true);
|
||||
}}
|
||||
>
|
||||
{t(language, 'cookies_accept')}
|
||||
</Button>
|
||||
<Button
|
||||
variant="secondary"
|
||||
size="small"
|
||||
aria-label={tString(language, 'cookies_reject')}
|
||||
onClick={() => {
|
||||
onUpdateState(false);
|
||||
}}
|
||||
>
|
||||
{t(language, 'cookies_reject')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './CookiesToast';
|
||||
@@ -0,0 +1,36 @@
|
||||
import { DocumentInlineAnnotation } from '@gitbook/api';
|
||||
|
||||
import { getNodeFragmentByType } from '@/lib/document';
|
||||
|
||||
import { AnnotationPopover } from './AnnotationPopover';
|
||||
import { Blocks } from '../Blocks';
|
||||
import { InlineProps } from '../Inline';
|
||||
import { Inlines } from '../Inlines';
|
||||
|
||||
export async function Annotation(props: InlineProps<DocumentInlineAnnotation>) {
|
||||
const { inline, context, document, children } = props;
|
||||
|
||||
const fragment = getNodeFragmentByType(inline, 'annotation-body');
|
||||
const content = children ?? (
|
||||
<Inlines document={document} context={context} nodes={inline.nodes} ancestorInlines={[]} />
|
||||
);
|
||||
|
||||
if (!fragment) {
|
||||
return <>{content}</>;
|
||||
}
|
||||
|
||||
return (
|
||||
<AnnotationPopover
|
||||
body={
|
||||
<Blocks
|
||||
document={document}
|
||||
ancestorBlocks={[]}
|
||||
context={context}
|
||||
nodes={fragment.nodes}
|
||||
/>
|
||||
}
|
||||
>
|
||||
{content}
|
||||
</AnnotationPopover>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
'use client';
|
||||
|
||||
import * as Popover from '@radix-ui/react-popover';
|
||||
import React from 'react';
|
||||
|
||||
import { useLanguage, tString } from '@/intl/client';
|
||||
import { tcls } from '@/lib/tailwind';
|
||||
|
||||
export function AnnotationPopover(props: { children: React.ReactNode; body: React.ReactNode }) {
|
||||
const { children, body } = props;
|
||||
const language = useLanguage();
|
||||
|
||||
return (
|
||||
<Popover.Root>
|
||||
<Popover.Trigger asChild>
|
||||
<button
|
||||
data-testid="annotation-button"
|
||||
aria-label={tString(language, 'annotation_button_label')}
|
||||
className={tcls(
|
||||
'decoration-dotted',
|
||||
'decoration-1',
|
||||
'underline',
|
||||
'underline-offset-2',
|
||||
)}
|
||||
>
|
||||
{children}
|
||||
</button>
|
||||
</Popover.Trigger>
|
||||
<Popover.Portal>
|
||||
<Popover.Content
|
||||
className={tcls(
|
||||
'text-sm',
|
||||
'max-w-[280px]',
|
||||
'bg-light',
|
||||
'ring-1',
|
||||
'ring-dark/2',
|
||||
'rounded',
|
||||
'shadow-1xs',
|
||||
'shadow-dark/1',
|
||||
'p-3',
|
||||
'[&_p]:leading-snug',
|
||||
'dark:bg-dark',
|
||||
'dark:ring-light/2',
|
||||
'dark:shadow-dark/4',
|
||||
'-outline-offset-2',
|
||||
'outline-2',
|
||||
'outline-primary/8',
|
||||
'z-20',
|
||||
)}
|
||||
sideOffset={5}
|
||||
>
|
||||
{body}
|
||||
<Popover.Arrow asChild>
|
||||
<svg
|
||||
width="100%"
|
||||
viewBox="0 0 8 5"
|
||||
preserveAspectRatio="xMaxYMid meet"
|
||||
className={tcls(
|
||||
'relative',
|
||||
'z-[2]',
|
||||
'fill-light',
|
||||
'stroke-dark/2',
|
||||
'[paint-order:stroke_fill]',
|
||||
'dark:fill-dark',
|
||||
'dark:stroke-light/2',
|
||||
)}
|
||||
fill="none"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
>
|
||||
<g clip-path="url(#clipAnnotation)">
|
||||
<path
|
||||
d="M0 0L4 4L8 0"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
stroke="inherit"
|
||||
fill="inherit"
|
||||
/>
|
||||
</g>
|
||||
<defs>
|
||||
<clipPath id="clipAnnotation">
|
||||
<rect width="8" height="5" fill="white" />
|
||||
</clipPath>
|
||||
</defs>
|
||||
</svg>
|
||||
</Popover.Arrow>
|
||||
</Popover.Content>
|
||||
</Popover.Portal>
|
||||
</Popover.Root>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
export * from './Annotation';
|
||||
@@ -0,0 +1,153 @@
|
||||
import { DocumentBlock, JSONDocument } from '@gitbook/api';
|
||||
import assertNever from 'assert-never';
|
||||
import React from 'react';
|
||||
|
||||
import {
|
||||
SkeletonParagraph,
|
||||
SkeletonHeading,
|
||||
SkeletonCard,
|
||||
SkeletonImage,
|
||||
SkeletonSmall,
|
||||
} from '@/components/primitives';
|
||||
import { ClassValue } from '@/lib/tailwind';
|
||||
|
||||
import { BlockContentRef } from './BlockContentRef';
|
||||
import { BlockSyncedBlock } from './BlockSyncedBlock';
|
||||
import { CodeBlock } from './CodeBlock';
|
||||
import { Divider } from './Divider';
|
||||
import { DocumentContextProps } from './DocumentView';
|
||||
import { Drawing } from './Drawing';
|
||||
import { Embed } from './Embed';
|
||||
import { Expandable } from './Expandable';
|
||||
import { File } from './File';
|
||||
import { Heading } from './Heading';
|
||||
import { Hint } from './Hint';
|
||||
import { Images } from './Images';
|
||||
import { IntegrationBlock } from './Integration';
|
||||
import { ListItem } from './ListItem';
|
||||
import { ListOrdered } from './ListOrdered';
|
||||
import { ListTasks } from './ListTasks';
|
||||
import { ListUnordered } from './ListUnordered';
|
||||
import { BlockMath } from './Math';
|
||||
import { OpenAPI } from './OpenAPI';
|
||||
import { Paragraph } from './Paragraph';
|
||||
import { Quote } from './Quote';
|
||||
import { Table } from './Table';
|
||||
import { Tabs } from './Tabs';
|
||||
|
||||
export interface BlockProps<Block extends DocumentBlock> extends DocumentContextProps {
|
||||
block: Block;
|
||||
document: JSONDocument;
|
||||
ancestorBlocks: DocumentBlock[];
|
||||
style?: ClassValue;
|
||||
}
|
||||
|
||||
export function Block<T extends DocumentBlock>(props: BlockProps<T>) {
|
||||
const { block, style, ...contextProps } = props;
|
||||
|
||||
const content = (() => {
|
||||
switch (block.type) {
|
||||
case 'paragraph':
|
||||
return <Paragraph {...props} {...contextProps} block={block} />;
|
||||
case 'heading-1':
|
||||
case 'heading-2':
|
||||
case 'heading-3':
|
||||
return <Heading {...props} {...contextProps} block={block} />;
|
||||
case 'list-ordered':
|
||||
return <ListOrdered {...props} {...contextProps} block={block} />;
|
||||
case 'list-unordered':
|
||||
return <ListUnordered {...props} {...contextProps} block={block} />;
|
||||
case 'list-tasks':
|
||||
return <ListTasks {...props} {...contextProps} block={block} />;
|
||||
case 'list-item':
|
||||
return <ListItem {...props} {...contextProps} block={block} />;
|
||||
case 'code':
|
||||
return <CodeBlock {...props} {...contextProps} block={block} />;
|
||||
case 'hint':
|
||||
return <Hint {...props} {...contextProps} block={block} />;
|
||||
case 'images':
|
||||
return <Images {...props} {...contextProps} block={block} />;
|
||||
case 'tabs':
|
||||
return <Tabs {...props} {...contextProps} block={block} />;
|
||||
case 'expandable':
|
||||
return <Expandable {...props} {...contextProps} block={block} />;
|
||||
case 'table':
|
||||
return <Table {...props} {...contextProps} block={block} />;
|
||||
case 'swagger':
|
||||
return <OpenAPI {...props} {...contextProps} block={block} />;
|
||||
case 'embed':
|
||||
return <Embed {...props} {...contextProps} block={block} />;
|
||||
case 'blockquote':
|
||||
return <Quote {...props} {...contextProps} block={block} />;
|
||||
case 'math':
|
||||
return <BlockMath {...props} {...contextProps} block={block} />;
|
||||
case 'file':
|
||||
return <File {...props} {...contextProps} block={block} />;
|
||||
case 'divider':
|
||||
return <Divider {...props} {...contextProps} block={block} />;
|
||||
case 'drawing':
|
||||
return <Drawing {...props} {...contextProps} block={block} />;
|
||||
case 'content-ref':
|
||||
return <BlockContentRef {...props} {...contextProps} block={block} />;
|
||||
case 'image':
|
||||
case 'code-line':
|
||||
case 'tabs-item':
|
||||
throw new Error('Blocks should be directly rendered by parent');
|
||||
case 'integration':
|
||||
return <IntegrationBlock {...props} {...contextProps} block={block} />;
|
||||
case 'synced-block':
|
||||
return <BlockSyncedBlock {...props} {...contextProps} block={block} />;
|
||||
default:
|
||||
assertNever(block);
|
||||
}
|
||||
})();
|
||||
|
||||
return (
|
||||
<React.Suspense fallback={<BlockPlaceholder block={block} style={style} />}>
|
||||
{content}
|
||||
</React.Suspense>
|
||||
);
|
||||
}
|
||||
|
||||
function BlockPlaceholder(props: { block: DocumentBlock; style: ClassValue }) {
|
||||
const { block, style } = props;
|
||||
const id = 'meta' in block && block.meta && 'id' in block.meta ? block.meta.id : undefined;
|
||||
|
||||
switch (block.type) {
|
||||
case 'heading-1':
|
||||
case 'heading-2':
|
||||
case 'heading-3':
|
||||
case 'file':
|
||||
return <SkeletonHeading id={id} style={style} />;
|
||||
case 'paragraph':
|
||||
return <SkeletonSmall id={id} style={style} />;
|
||||
case 'list-ordered':
|
||||
case 'list-unordered':
|
||||
case 'list-tasks':
|
||||
case 'list-item':
|
||||
case 'blockquote':
|
||||
case 'code':
|
||||
case 'hint':
|
||||
case 'tabs':
|
||||
case 'synced-block':
|
||||
return <SkeletonParagraph id={id} style={style} />;
|
||||
case 'expandable':
|
||||
case 'table':
|
||||
case 'swagger':
|
||||
case 'math':
|
||||
case 'divider':
|
||||
case 'content-ref':
|
||||
case 'integration':
|
||||
return <SkeletonCard id={id} style={style} />;
|
||||
case 'embed':
|
||||
case 'images':
|
||||
case 'drawing':
|
||||
return <SkeletonImage id={id} style={style} />;
|
||||
case 'image':
|
||||
case 'code-line':
|
||||
case 'tabs-item':
|
||||
throw new Error('Blocks should be directly rendered by parent');
|
||||
default:
|
||||
assertNever(block);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
import { DocumentBlockContentRef } from '@gitbook/api';
|
||||
|
||||
import { LogoIcon } from '@/components/icons';
|
||||
import { Card, Emoji } from '@/components/primitives';
|
||||
import { getSpaceCustomization, ignoreAPIError } from '@/lib/api';
|
||||
import { ResolvedContentRef } from '@/lib/references';
|
||||
|
||||
import { BlockProps } from './Block';
|
||||
|
||||
export async function BlockContentRef(props: BlockProps<DocumentBlockContentRef>) {
|
||||
const { block, context, style } = props;
|
||||
|
||||
const resolved = await context.resolveContentRef(block.data.ref, {
|
||||
resolveAnchorText: true,
|
||||
});
|
||||
|
||||
if (!resolved) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const isContentInOtherSpace =
|
||||
context.contentRefContext?.space &&
|
||||
'space' in block.data.ref &&
|
||||
context.contentRefContext.space.id !== block.data.ref.space;
|
||||
const kind = block?.data?.ref?.kind;
|
||||
if ((resolved.active && kind === 'space') || isContentInOtherSpace) {
|
||||
return <SpaceRefCard {...props} resolved={resolved} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Card
|
||||
leadingIcon={resolved.emoji ? <Emoji code={resolved.emoji} style="text-xl" /> : null}
|
||||
href={resolved.href}
|
||||
title={resolved.text}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
async function SpaceRefCard(
|
||||
props: { resolved: ResolvedContentRef } & BlockProps<DocumentBlockContentRef>,
|
||||
) {
|
||||
const { context, style, resolved } = props;
|
||||
const spaceId = context.contentRefContext?.space.id;
|
||||
|
||||
if (!spaceId) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const spaceCustomization = await ignoreAPIError(getSpaceCustomization(spaceId));
|
||||
const customFavicon = spaceCustomization?.favicon;
|
||||
const customEmoji = customFavicon && 'emoji' in customFavicon ? customFavicon.emoji : undefined;
|
||||
const customIcon = customFavicon && 'icon' in customFavicon ? customFavicon.icon : undefined;
|
||||
|
||||
return (
|
||||
<Card
|
||||
leadingIcon={
|
||||
<LogoIcon
|
||||
icon={customIcon}
|
||||
emoji={customEmoji}
|
||||
alt=""
|
||||
sizes={[{ width: 24 }]}
|
||||
style={['object-contain', 'size-6']}
|
||||
/>
|
||||
}
|
||||
href={resolved.href}
|
||||
title={resolved.text}
|
||||
postTitle={resolved.subText}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { DocumentBlockSyncedBlock } from '@gitbook/api';
|
||||
|
||||
import { getSyncedBlockContent } from '@/lib/api';
|
||||
import { resolveContentRefWithFiles } from '@/lib/references';
|
||||
|
||||
import { BlockProps } from './Block';
|
||||
import { Blocks } from './Blocks';
|
||||
|
||||
export async function BlockSyncedBlock(props: BlockProps<DocumentBlockSyncedBlock>) {
|
||||
const { block, ancestorBlocks, context, style } = props;
|
||||
|
||||
const apiToken = block.meta?.apiToken;
|
||||
if (!apiToken) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// We can't resolve the synced block without an organization context.
|
||||
if (!context.contentRefContext) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const syncedBlock = await getSyncedBlockContent(
|
||||
apiToken,
|
||||
context.contentRefContext.space.organization,
|
||||
block.data.ref.syncedBlock,
|
||||
);
|
||||
|
||||
if (!syncedBlock) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Blocks
|
||||
nodes={syncedBlock.document.nodes}
|
||||
document={syncedBlock.document}
|
||||
ancestorBlocks={[...ancestorBlocks, block]}
|
||||
context={{
|
||||
...context,
|
||||
resolveContentRef: async (ref, options) => {
|
||||
if (!syncedBlock?.files) {
|
||||
return context.resolveContentRef(ref, options);
|
||||
}
|
||||
const result = resolveContentRefWithFiles(syncedBlock.files, ref);
|
||||
if (result !== undefined) {
|
||||
return result;
|
||||
}
|
||||
return context.resolveContentRef(ref, options);
|
||||
},
|
||||
}}
|
||||
style={style}
|
||||
/>
|
||||
);
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user