Compare commits

..

2 Commits

Author SHA1 Message Date
Nicolas Dorseuil 47977e1c57 changeset
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 14:24:08 +01:00
Nicolas Dorseuil 30e2de45a6 Replace Tailwind utility strings with semantic classes on the hot path
Experiment to cut the class names shipped in HTML and RSC. The sidebar,
buttons and links, header and footer, page layout and document blocks now
render one short class per element; their styles moved to
RootLayout/styles/*.css via @apply with the same utilities, so output is
unchanged. Those stylesheets sit in the utilities layer ahead of Tailwind's
generated utilities, so caller overrides resolve as twMerge did. tcls is
replaced by a plain join (cx) in migrated code.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-16 14:24:03 +01:00
289 changed files with 5343 additions and 6731 deletions
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep links in generated Markdown usable outside the source page.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Handle optional emoji and icon values when rendering tags.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fade the bottom of collapsed code blocks so readers can tell there is more code, matching the editor.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Answer Assistant questions with medium reasoning instead of low, matching AI search.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Bump `@opennextjs/aws` to 4.2.0 and `@opennextjs/cloudflare` to 1.20.18.
-6
View File
@@ -1,6 +0,0 @@
---
"@gitbook/embed": minor
"gitbook": patch
---
Emit an `escape` event from the Docs Embed when Escape is pressed inside it and nothing in the embed used it, so the host can close its own panel.
@@ -1,6 +0,0 @@
---
"@gitbook/embed": minor
"gitbook": patch
---
Use the site's suggested questions when the embedded Assistant receives an empty or omitted list, including from older SDKs.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Reduce the wait after typing in site search to 100 ms.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix the table of contents keeping published pages busy in older Chrome versions such as Chrome 130.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Fix `'use cache'` entries never being stored in or read from R2 and the regional cache on Cloudflare.
@@ -1,5 +0,0 @@
---
"@gitbook/icons": minor
---
Add a `@gitbook/icons/validateIconName` entry that validates icon names without loading the icon labels and search terms.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Keep published pages available when an integration block needs its connection or settings checked.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Reduce memory and CPU use of the OpenNext workers: minify the middleware, resolve the site context once per request, cache parsed OpenAPI descriptions across a spec, drop the redis client and the unused force-revalidate route from the server bundle.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render the llms.txt directive as the first element in the page body so agents find it before the navigation.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Challenge MCP clients to authorize again when a visitor-auth site rejects their bearer token.
@@ -1,5 +0,0 @@
---
"@gitbook/react-openapi": patch
---
Copy the current spec's server in OpenAPI endpoint URLs instead of a server kept from a previously visited page.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Publish an OpenSearch description on every site so browsers can offer its search from the address bar.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show H3 headings in the page outline.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": minor
---
Open a link in the same or a new tab when its author chose one, instead of the site-wide external links setting.
-5
View File
@@ -1,5 +0,0 @@
---
'gitbook': patch
---
Respect disabled change request previews on published sites.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send change request and revision links to the site preview, where GitBook members can sign in, when a site turns off public change request previews.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send site searches straight to the search API when the site hands out a search pass, and use the site's search route when it does not or when the API refuses a search.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Send each search once on sites without a top header, and make search work between 768 and 1023 px wide.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show loading rows shaped like search results while search waits for the server.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Reduce background downloads during search by prefetching the result visitors hover or select.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show search results with one-line breadcrumbs and no icons or shortcut hints, and select the result under the mouse.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Stop caching site search results in the framework cache, so every search reaches the API.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Show one server-ordered search list and open its top result on Enter.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Load the data of the page actions menu from the menu itself, so it can be cached apart from the page body.
+5
View File
@@ -0,0 +1,5 @@
---
"gitbook": patch
---
Ship short semantic class names instead of Tailwind utility strings on the sidebar, buttons, header, page layout and document blocks, shrinking HTML and RSC payloads.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Follow the API's cache lifetime for site data, so a site preview shows layout changes soon after they are saved.
-5
View File
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Render small cards in a responsive four-column grid and carousel.
@@ -1,5 +0,0 @@
---
"gitbook": patch
---
Ignore tag category references when displaying assigned tags and update filters.
-28
View File
@@ -51,31 +51,3 @@ jobs:
- name: Outputs
run: |
echo "URL: ${{ steps.deploy.outputs.deployment-url }}"
linear-release:
name: Track the production release in Linear
needs: [deploy-v2-vercel, deploy-v2-cloudflare]
runs-on: ubuntu-latest
timeout-minutes: 10
# Release tracking must never fail a deployment that already succeeded.
continue-on-error: true
permissions:
contents: read
env:
LINEAR_ACCESS_KEY: ${{ secrets.PRODUCTION_LINEAR_RELEASE_ACCESS_KEY }}
steps:
- name: Skip release tracking without an access key
if: env.LINEAR_ACCESS_KEY == ''
run: echo "::warning::No Linear pipeline access key is configured, skipped tracking the release."
- name: Checkout
if: env.LINEAR_ACCESS_KEY != ''
uses: actions/checkout@v4
with:
# The Linear CLI scans commit metadata since the last release, so it needs history but no blobs.
fetch-depth: 0
filter: blob:none
persist-credentials: false
- name: Sync the release to Linear
if: env.LINEAR_ACCESS_KEY != ''
uses: linear/linear-release-action@dd4fc407f860b9460d2cf0b3fb1edd8985cf443f # v0.18.2
with:
access_key: ${{ env.LINEAR_ACCESS_KEY }}
-30
View File
@@ -59,36 +59,6 @@ Run a specific test file:
cd packages/gitbook && bun test src/lib/cache.test.ts
```
## Changes customers see on their live site
Published sites are our customers' product. If a change alters how their content looks or behaves without them changing anything, it needs a comms decision before it merges.
It counts if it ships on by default and any of these are true:
- It changes structure or navigation: outline/"On this page", sidebar, TOC, headings, breadcrumbs, pagination, header or footer.
- Something new appears on every page (or every page of a type), or something existing disappears or moves.
- Layout or typography shifts enough that a customer would notice in a screenshot.
- URLs, anchors, redirects, SEO/meta tags or search/Ask behaviour change.
- A default changes for existing sites.
It does not count when:
- It's behind a flag, a site setting or opt-in that stays off for existing sites until comms go out.
- It's a bug fix that restores the intended behaviour.
- It only affects the editor/app, not published content.
When it counts:
1. Warn the engineer before the PR is opened: "This changes customers' live sites. Have the support and sales leads agreed the rollout and announcement?"
2. Suggest a flag or staged rollout if there isn't one, so it can ship dark and be turned on after the notice goes out.
## Bumping Next.js or OpenNext
Type checks and unit tests miss runtime regressions: OpenNext 4.1.15 changed the composable cache key format, and every `'use cache'` call silently missed for days. Before committing a bump of `next`, `@opennextjs/aws` or `@opennextjs/cloudflare`, run both runtimes locally from `packages/gitbook`:
1. **Next**: `bun run build:local && bun run start`, then load several distinct pages under `http://localhost:3000/url/gitbook.com/docs`.
2. **OpenNext**: `bun run build:cloudflare`, delete `openNext/customWorkers/.wrangler` (stale cache hits otherwise skip the server), then run `bun run dev:cf:server` and `bun run dev:cf:middleware` and load several distinct pages under `http://127.0.0.1:8771/url/gitbook.com/docs`.
3. Diff the changed OpenNext versions' adapters that call our overrides in `openNext/` (incremental, composable and tag cache, queue), e.g. with `npm pack` of the old and new versions.
The bump is safe when every page returns 200 on both runtimes and the server logs show no cache errors (grep `Failed to` and `regional cache`). Report the pages checked and the log result in the PR.
## Changesets
After committing code changes, create a changeset for the affected package:
+6 -7
View File
@@ -128,8 +128,8 @@
"@gitbook/react-openapi": "workspace:*",
"@mermaid-js/mermaid-zenuml": "^0.2.2",
"@modelcontextprotocol/sdk": "1.17.5",
"@opennextjs/aws": "4.2.0",
"@opennextjs/cloudflare": "1.20.18",
"@opennextjs/aws": "4.1.16",
"@opennextjs/cloudflare": "1.20.17",
"@panzoom/panzoom": "^4.6.1",
"@sindresorhus/fnv1a": "^3.1.0",
"@tailwindcss/container-queries": "^0.1.1",
@@ -167,7 +167,6 @@
"openapi-types": "^12.1.3",
"p-map": "^7.0.3",
"p-retry": "^8.0.0",
"parse5": "7.2.0",
"quick-lru": "^7.0.1",
"react": "19.2.4",
"react-dom": "19.2.4",
@@ -357,7 +356,7 @@
},
"catalog": {
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.211.0",
"@gitbook/api": "0.208.0",
"@scalar/api-client-react": "^1.3.46",
"@tsconfig/node20": "^20.1.6",
"@tsconfig/strictest": "^2.0.6",
@@ -725,7 +724,7 @@
"@fortawesome/fontawesome-svg-core": ["@fortawesome/fontawesome-svg-core@7.2.0", "", { "dependencies": { "@fortawesome/fontawesome-common-types": "7.2.0" } }, "sha512-6639htZMjEkwskf3J+e6/iar+4cTNM9qhoWuRfj9F3eJD6r7iCzV1SWnQr2Mdv0QT0suuqU8BoJCZUyCtP9R4Q=="],
"@gitbook/api": ["@gitbook/api@0.211.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-G+rY2m7ZvyR1RA4oilarzrNDABDkYhARoIyfNCE5mYqZQgpgsLShn3rGgzTudO2iqwt/5iK6RcJc2enfj+37Jg=="],
"@gitbook/api": ["@gitbook/api@0.208.0", "", { "dependencies": { "event-iterator": "^2.0.0", "eventsource-parser": "^3.0.0" } }, "sha512-i5rnGYNvgp8PDGd9FRLUjOx5gS/D7mFfikwp0Lsem4pgEG8cqBtZsDaYbLBdAdupOuZBLJtmEut51zhttok6OQ=="],
"@gitbook/browser-types": ["@gitbook/browser-types@workspace:packages/browser-types"],
@@ -935,9 +934,9 @@
"@octokit/types": ["@octokit/types@14.1.0", "", { "dependencies": { "@octokit/openapi-types": "^25.1.0" } }, "sha512-1y6DgTy8Jomcpu33N+p5w58l6xyt55Ar2I91RPiIA0xCJBXyUAhXCcmZaDWSANiha7R9a6qJJ2CRomGPZ6f46g=="],
"@opennextjs/aws": ["@opennextjs/aws@4.2.0", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@aws-sdk/client-cloudfront": "3.984.0", "@aws-sdk/client-dynamodb": "3.984.0", "@aws-sdk/client-lambda": "3.984.0", "@aws-sdk/client-s3": "3.984.0", "@aws-sdk/client-sqs": "3.984.0", "@node-minify/core": "^10.5.0", "@node-minify/terser": "^10.5.0", "@tsconfig/node18": "^18.2.7", "aws4fetch": "^1.0.20", "chalk": "^5.6.2", "cookie": "^1.1.1", "esbuild": "0.28.2", "express": "^5.2.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.1.0", "yaml": "^2.9.1" }, "peerDependencies": { "diff": "^9.0.0", "next": ">=15.5.29 <16 || >=16.4.5" }, "optionalPeers": ["diff"], "bin": { "open-next": "dist/index.js" } }, "sha512-uWWER/P66CphCM+L0WlN9DSj3LauN/HjfK64V0+Hs+hjzKuQLGII/Q7FhkU1j/BEG4zbjIvkuJorzIyFwVWZiQ=="],
"@opennextjs/aws": ["@opennextjs/aws@4.1.16", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@aws-sdk/client-cloudfront": "3.984.0", "@aws-sdk/client-dynamodb": "3.984.0", "@aws-sdk/client-lambda": "3.984.0", "@aws-sdk/client-s3": "3.984.0", "@aws-sdk/client-sqs": "3.984.0", "@node-minify/core": "^10.5.0", "@node-minify/terser": "^10.5.0", "@tsconfig/node18": "^18.2.7", "aws4fetch": "^1.0.20", "chalk": "^5.6.2", "cookie": "^1.1.1", "esbuild": "0.28.2", "express": "^5.2.1", "path-to-regexp": "^6.3.0", "urlpattern-polyfill": "^10.1.0", "yaml": "^2.9.1" }, "peerDependencies": { "diff": "^9.0.0", "next": ">=15.5.29 <16 || >=16.4.5" }, "optionalPeers": ["diff"], "bin": { "open-next": "dist/index.js" } }, "sha512-eHb6/LCrpr+3DmbmE+/q5GkcrbSs5IRpO/O0kcay7FK5WYDhcML0K5NhO7I9H62z42wscVIi75Hv3ASsXDeEGw=="],
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@1.20.18", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@dotenvx/dotenvx": "^2.33.0", "@opennextjs/aws": "4.2.0", "ci-info": "^4.2.0", "cloudflare": "^4.4.1", "comment-json": "^4.5.1", "enquirer": "^2.4.1", "esbuild": "0.28.2", "glob": "^13.0.6", "resolve.exports": "^2.0.4", "ts-tqdm": "^0.8.6", "yargs": "^18.2.0" }, "peerDependencies": { "next": ">=15.5.29 <16 || >=16.4.5", "rclone.js": "^0.6.6", "wrangler": "^4.148.0" }, "optionalPeers": ["rclone.js"], "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }, "sha512-6hy3RJHP7+OMxUxYLRCgzQipuJJ1n7JowszTHn/i2KGxPXccQuvs42YI5ZchV7Fd0JGrtIDj0lhgvw+dp7yMrg=="],
"@opennextjs/cloudflare": ["@opennextjs/cloudflare@1.20.17", "", { "dependencies": { "@ast-grep/napi": "^0.45.3", "@dotenvx/dotenvx": "^2.33.0", "@opennextjs/aws": "4.1.16", "ci-info": "^4.2.0", "cloudflare": "^4.4.1", "comment-json": "^4.5.1", "enquirer": "^2.4.1", "glob": "^13.0.6", "resolve.exports": "^2.0.4", "ts-tqdm": "^0.8.6", "yargs": "^18.2.0" }, "peerDependencies": { "next": ">=15.5.29 <16 || >=16.4.5", "rclone.js": "^0.6.6", "wrangler": "^4.148.0" }, "optionalPeers": ["rclone.js"], "bin": { "opennextjs-cloudflare": "dist/cli/index.js" } }, "sha512-jGEC9ue8LLHvOFXp62LjDUSSz7JpD+PQB+Y3r0lU78PtQ84wI16+EMF9TXEDkTek3g3fGWTLTI07pbZt8/gj8w=="],
"@opentelemetry/api": ["@opentelemetry/api@1.9.0", "", {}, "sha512-3giAOQvZiH5F9bMlMiv8+GSPMeqg0dbaeo58/0SlA9sxSqZhnUtxzX9/2FzyhS9sWQf5S0GJE0AKBrFqjpeYcg=="],
+1 -1
View File
@@ -48,7 +48,7 @@
"@tsconfig/strictest": "^2.0.6",
"@tsconfig/node20": "^20.1.6",
"@base-ui/react": "^1.7.0",
"@gitbook/api": "0.211.0",
"@gitbook/api": "0.208.0",
"@scalar/api-client-react": "^1.3.46",
"@types/react": "^19.0.0",
"@types/react-dom": "^19.0.0",
+1 -8
View File
@@ -127,11 +127,6 @@ frame.configure({
frame.on('close', () => {
console.log('Frame closed');
});
// Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it
frame.on('escape', () => {
closeHelpPanel();
});
```
## As React components
@@ -227,7 +222,7 @@ function MyComponent() {
- `frame.postUserMessage(message: string)` → `void`
- `frame.clearChat()` → `void`
- `frame.configure(settings: Partial<GitBookEmbeddableConfiguration>)` → `void`
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe). Events: `close`, `escape`
- `frame.on(event: string, listener: Function)` → `() => void` (unsubscribe)
### React Components
@@ -399,8 +394,6 @@ Available in: Standalone script, NPM package, React components
Suggested questions displayed in the [Assistant](https://gitbook.com/docs/publishing-documentation/gitbook-ai-assistant) welcome screen.
Omit `suggestions` when creating the embed or pass an empty array to use the site's suggested questions. If the site has no suggested questions, the Assistant shows generic questions. Later `configure` calls keep the current setting unless you pass `suggestions`. To restore the site's questions, remove the React prop or pass `{ suggestions: [] }` or `{ suggestions: undefined }` to `configure`.
- **Type**: `string[]`
```javascript
@@ -38,10 +38,7 @@ export type GitBookFrameClient = {
configure: (settings: Partial<GitBookEmbeddableConfiguration>) => void;
/**
* Register an event listener and get back a function that removes it.
*
* - `close`: the built-in close button was clicked.
* - `escape`: Escape was pressed inside the frame and nothing in it (a menu, a dialog) used it.
* Register an event listener.
*/
on: (event: string, listener: (...args: any[]) => void) => () => void;
};
@@ -67,9 +64,11 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
channel.receive((message: FrameToParentMessage) => {
console.log('[gitbook:embed] received message', message);
if (message.type === 'close' || message.type === 'escape') {
const listeners = events.get(message.type) || [];
listeners.forEach((listener) => listener());
if (message.type === 'close') {
const listeners = events.get('close') || [];
if (listeners) {
listeners.forEach((listener) => listener());
}
}
});
@@ -84,7 +83,7 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
tabs: ['assistant', 'search', 'docs'],
actions: [],
greeting: { title: '', subtitle: '' },
suggestions: undefined,
suggestions: [],
tools: [],
trademark: true,
};
@@ -109,7 +108,7 @@ export function createGitBookFrame(iframe: HTMLIFrameElement): GitBookFrameClien
return () => {
events.set(
event,
(events.get(event) || []).filter((l) => l !== listener)
listeners.filter((l) => l !== listener)
);
};
},
+5 -10
View File
@@ -94,8 +94,8 @@ export type GitBookEmbeddableConfiguration = {
*/
assistantName?: string;
/** Welcome questions. Omit or pass [] to inherit the site's questions. */
suggestions?: string[] | undefined;
/** Suggestions of questions to be displayed in the welcome page. */
suggestions: string[];
/** Tools to be provided to the assistant. */
tools: GitBookToolDefinition[];
@@ -137,11 +137,6 @@ export type ParentToFrameMessage =
/**
* Messages sent from the frame to the parent.
*/
export type FrameToParentMessage =
| {
type: 'close';
}
| {
/** Escape was pressed inside the frame and nothing in the frame handled it. */
type: 'escape';
};
export type FrameToParentMessage = {
type: 'close';
};
+1 -1
View File
@@ -24,7 +24,7 @@ export function GitBookFrame(props: GitBookFrameProps) {
visitor,
actions = [],
greeting,
suggestions,
suggestions = [],
tools = [],
tabs = ['assistant', 'search', 'docs'],
defaultTab,
+1
View File
@@ -63,6 +63,7 @@ let frameConfiguration: GitBookEmbeddableConfiguration & StandaloneConfiguration
},
actions: [],
greeting: { title: '', subtitle: '' },
suggestions: [],
tools: [],
tabs: ['assistant', 'search', 'docs'],
trademark: true,
+5
View File
@@ -443,6 +443,11 @@ const testCases: TestsCase[] = [
contentBaseURL: 'https://help.openloyalty.io',
tests: [{ name: 'Home', url: '/', run: waitForCookiesDialog }],
},
{
name: 'retrozia.gitbook.io/retrozia',
contentBaseURL: 'https://retrozia.gitbook.io',
tests: [{ name: 'Home', url: '/retrozia' }],
},
{
name: 'helpcenter.channable.com',
contentBaseURL: 'https://helpcenter.channable.com',
File diff suppressed because it is too large Load Diff
-12
View File
@@ -1,7 +1,6 @@
// @ts-check
import { networkInterfaces } from 'node:os';
import { fileURLToPath } from 'node:url';
// Next blocks its dev client and HMR when a physical device opens the server over a LAN address.
// Needed to hydrate the dev client on physical phones/tablets over the internal network
@@ -120,17 +119,6 @@ const nextConfig = {
],
},
webpack(config, { isServer }) {
if (isServer) {
// mcp-handler only needs redis for SSE, which we disable: keep the client out of the server bundle.
config.resolve.alias = {
...config.resolve.alias,
redis$: fileURLToPath(new URL('./src/lib/mcp/redis-stub.ts', import.meta.url)),
};
}
return config;
},
async headers() {
return [
{
@@ -3,7 +3,6 @@
"name": "gitbook-open-v2",
"compatibility_date": "2026-04-02",
"keep_names": false,
"minify": true,
"compatibility_flags": [
"nodejs_compat",
"allow_importable_env",
@@ -1,23 +0,0 @@
import { describe, expect, it } from 'bun:test';
import { createHash } from 'node:crypto';
import { GitbookIncrementalCache } from './incrementalCache';
describe('GitbookIncrementalCache.getR2Key', () => {
const cache = new GitbookIncrementalCache();
it('accepts the hashed composable key passed by OpenNext', () => {
const storageKey = createHash('sha256').update('["build-id","action",[]]').digest('hex');
const key = cache.getR2Key(storageKey, 'composable');
const hash = createHash('sha256').update(storageKey).digest('hex');
expect(key).toBe(`incremental-cache/dataCache/${hash}.composable`);
});
it('maps distinct composable keys to distinct R2 keys', () => {
expect(cache.getR2Key('a'.repeat(64), 'composable')).not.toBe(
cache.getR2Key('b'.repeat(64), 'composable')
);
});
});
@@ -118,8 +118,15 @@ export class GitbookIncrementalCache implements IncrementalCache {
}
}
// OpenNext pre-hashes composable keys with the build ID in them: no reuse across deploys.
getR2Key(key: string, cacheType: CacheEntryType = 'cache'): string {
// Utility function to generate keys for R2/Cache API
getR2Key(initialKey: string, cacheType: CacheEntryType = 'cache'): string {
let key = initialKey;
if (cacheType === 'composable') {
// For composable cache, we need to discard the build ID from the key
const [_buildId, ...restOfTheKey] = JSON.parse(initialKey);
key = JSON.stringify([...restOfTheKey]);
}
const hash = createHash('sha256').update(key).digest('hex');
return `${DEFAULT_PREFIX}/${cacheType === 'cache' ? process.env?.NEXT_BUILD_ID : 'dataCache'}/${hash}.${cacheType}`.replace(
/\/+/g,
+3 -4
View File
@@ -20,8 +20,8 @@
"@gitbook/react-openapi": "workspace:*",
"@mermaid-js/mermaid-zenuml": "^0.2.2",
"@modelcontextprotocol/sdk": "1.17.5",
"@opennextjs/aws": "4.2.0",
"@opennextjs/cloudflare": "1.20.18",
"@opennextjs/aws": "4.1.16",
"@opennextjs/cloudflare": "1.20.17",
"@panzoom/panzoom": "^4.6.1",
"@sindresorhus/fnv1a": "^3.1.0",
"@tailwindcss/container-queries": "^0.1.1",
@@ -59,7 +59,6 @@
"openapi-types": "^12.1.3",
"p-map": "^7.0.3",
"p-retry": "^8.0.0",
"parse5": "7.2.0",
"quick-lru": "^7.0.1",
"react": "19.2.4",
"react-dom": "19.2.4",
@@ -136,7 +135,7 @@
"e2e": "playwright test e2e/internal.spec.ts e2e/cookie-banner.spec.ts e2e/pdf.spec.ts e2e/select.spec.ts e2e/tabs-overflow.spec.ts --project=chromium",
"e2e-customers": "playwright test e2e/customers.spec.ts --project=chromium",
"e2e-style-perf": "playwright test e2e/style-perf.spec.ts --project=chromium --reporter=list",
"unit": "bun run generate:assets && bun test {src,packages,openNext} --preload ./tests/preload-bun.ts",
"unit": "bun run generate:assets && bun test {src,packages} --preload ./tests/preload-bun.ts",
"e2e-browserless": "bun test ./tests/",
"typecheck": "tsc --noEmit"
},
@@ -50,7 +50,6 @@ export async function handleMcpRequest(
streamableHttpEndpoint: context.linker.toPathInSite(endpoint),
maxDuration: 60,
verboseLogs: true,
// SSE needs redis, which next.config.mjs stubs out of the server bundle.
disableSse: true,
}
);
@@ -1,18 +1,16 @@
import { type NextRequest, NextResponse } from 'next/server';
import { SEARCH_FALLBACK_HEADER } from '@/components/Search/search-pass-store';
import type { SearchSiteContentRequest } from '@/components/Search/search-types';
import { orderSearchResultGroups } from './orderSearchResults';
import type {
OrderedComputedResult,
SearchSiteContentRequest,
} from '@/components/Search/search-types';
import { throwIfDataError } from '@/lib/data';
import { getLogger } from '@/lib/logger';
import { getSiteURLDataFromMiddleware } from '@/lib/middleware';
import { transformSitePageResult } from '@/lib/search';
import { computeSearchResults } from '@/lib/search-results';
import { getServerActionBaseContext } from '@/lib/server-actions';
import { findSiteSpaceBy, getLinkerForSiteSpace } from '@/lib/sites';
const SEARCH_FALLBACK_REASON =
/^(\d{3}|expired|pass_request|network|timeout|invalid|unknown_space)$/;
export async function POST(request: NextRequest) {
const { asEmbeddable, query, scope } = (await request.json()) as SearchSiteContentRequest;
const [context, siteURLData] = await Promise.all([
@@ -20,15 +18,6 @@ export async function POST(request: NextRequest) {
getSiteURLDataFromMiddleware(),
]);
const fallback = request.headers.get(SEARCH_FALLBACK_HEADER);
if (fallback && SEARCH_FALLBACK_REASON.test(fallback)) {
getLogger()
.subLogger('search')
.info(
`Search pass fallback to the route (reason=${fallback}, organization=${siteURLData.organization}, site=${siteURLData.site})`
);
}
if (query.length <= 1) {
return NextResponse.json([]);
}
@@ -67,24 +56,49 @@ export async function POST(request: NextRequest) {
? getLinkerForSiteSpace(context.linker, currentSiteSpace.siteSpace, revision.pages)
: context.linker;
const results = computeSearchResults(searchResults, (spaceItem, pageItem) => {
const isCurrentRevisionSpace = Boolean(revision && spaceItem.id === siteURLData.space);
const found =
isCurrentRevisionSpace && currentSiteSpace
? currentSiteSpace
: findSiteSpaceBy(structure, (siteSpace) => siteSpace.space.id === spaceItem.id);
const results = orderSearchResultGroups<OrderedComputedResult>(
searchResults.map((resultItem) => {
if (resultItem.type === 'record') {
const result: OrderedComputedResult = {
type: 'record',
id: resultItem.id,
title: resultItem.title,
description: resultItem.description,
href: resultItem.url,
score: resultItem.score,
};
return transformSitePageResult({
asEmbeddable: Boolean(asEmbeddable),
linker: isCurrentRevisionSpace ? revisionLinker : context.linker,
pageItem,
spaceItem,
siteSpace: found?.siteSpace,
siteSection: found?.siteSection ?? undefined,
siteSectionGroup: found?.siteSectionGroup ?? undefined,
revisionPages: isCurrentRevisionSpace ? revision?.pages : undefined,
});
});
return { type: 'context' as const, results: [result] };
}
const isCurrentRevisionSpace = Boolean(revision && resultItem.id === siteURLData.space);
const found =
isCurrentRevisionSpace && currentSiteSpace
? currentSiteSpace
: findSiteSpaceBy(
structure,
(siteSpace) => siteSpace.space.id === resultItem.id
);
return {
type: 'pages' as const,
results: resultItem.pages.flatMap((pageItem) => {
const result = transformSitePageResult({
asEmbeddable: Boolean(asEmbeddable),
linker: isCurrentRevisionSpace ? revisionLinker : context.linker,
pageItem,
spaceItem: resultItem,
siteSpace: found?.siteSpace,
siteSection: found?.siteSection ?? undefined,
siteSectionGroup: found?.siteSectionGroup ?? undefined,
revisionPages: isCurrentRevisionSpace ? revision?.pages : undefined,
});
return result ? [{ rank: pageItem.rank, result }] : [];
}),
};
})
);
return NextResponse.json(results);
}
@@ -1,14 +0,0 @@
import type { NextRequest } from 'next/server';
import { type RouteLayoutParams, getStaticSiteContext } from '@/app/utils';
import { serveOpenSearchDescription } from '@/routes/opensearch';
export const dynamic = 'force-static';
export async function GET(
_request: NextRequest,
{ params }: { params: Promise<RouteLayoutParams> }
) {
const { context } = await getStaticSiteContext(await params);
return serveOpenSearchDescription(context);
}
+2 -21
View File
@@ -1,6 +1,5 @@
import { jwtDecode } from 'jwt-decode';
import { forbidden, notFound } from 'next/navigation';
import { cache } from 'react';
import rison from 'rison';
import type { SiteAPIToken } from '@gitbook/api';
@@ -28,17 +27,7 @@ export type RouteParams = RouteLayoutParams & {
/**
* Get the static context when rendering statically a site.
*/
export function getStaticSiteContext(params: RouteLayoutParams) {
return getStaticSiteContextCached(params.mode, params.siteURL, params.siteData);
}
// Layouts, pages and their metadata functions each resolve the context: share it per request.
// Keyed on the raw strings as `params` objects aren't guaranteed to be the same reference.
const getStaticSiteContextCached = cache((mode: string, siteURL: string, siteData: string) =>
resolveStaticSiteContext({ mode, siteURL, siteData })
);
async function resolveStaticSiteContext(params: RouteLayoutParams) {
export async function getStaticSiteContext(params: RouteLayoutParams) {
const siteURL = getSiteURLFromParams(params);
const siteURLData = getSiteURLDataFromParams(params);
@@ -68,15 +57,7 @@ async function resolveStaticSiteContext(params: RouteLayoutParams) {
* Get the site context when rendering dynamically.
* The context will depend on the request.
*/
export function getDynamicSiteContext(params: RouteLayoutParams) {
return getDynamicSiteContextCached(params.mode, params.siteURL, params.siteData);
}
const getDynamicSiteContextCached = cache((mode: string, siteURL: string, siteData: string) =>
resolveDynamicSiteContext({ mode, siteURL, siteData })
);
async function resolveDynamicSiteContext(params: RouteLayoutParams) {
export async function getDynamicSiteContext(params: RouteLayoutParams) {
const siteURL = getSiteURLFromParams(params);
const siteURLData = getSiteURLDataFromParams(params);
@@ -65,7 +65,7 @@ export async function* streamAIChatResponse({
},
]
: [],
model: AIModel.ReasoningMedium,
model: AIModel.ReasoningLow,
previousResponseId,
toolCall,
tools,
@@ -13,6 +13,7 @@ import { LinkStyles } from '../primitives/styles';
import { ANNOUNCEMENT_CSS_CLASS, ANNOUNCEMENT_STORAGE_KEY } from './constants';
import { tString, useLanguage } from '@/intl/client';
import { setLocalStorageItem } from '@/lib/browser';
import { cx } from '@/lib/classnames';
import type { ResolvedContentRef } from '@/lib/references';
import { getLocalizedMessage, getLocalizedTitle } from '@/lib/sites';
import { tcls } from '@/lib/tailwind';
@@ -38,20 +39,16 @@ export function AnnouncementBanner(props: {
const style = BANNER_STYLES[announcement.style];
return (
<div
data-gb-announcement-banner
className="pb-2 pt-4 theme-bold:bg-header-background"
data-nosnippet=""
>
<div className="lg:chat-open:pr-(--ai-chat-width) transition-all duration-300 motion-reduce:transition-none">
<div className={tcls('relative', CONTAINER_STYLE)}>
<div data-gb-announcement-banner className="announcement" data-nosnippet="">
<div className="chrome-shift">
<div className={cx(CONTAINER_STYLE, 'relative')}>
<Tag
href={contentRef?.href ?? ''}
className={tcls(
'flex w-full items-start justify-center overflow-hidden circular-corners:rounded-xl rounded-md straight-corners:rounded-none px-4 py-3 text-neutral-strong text-sm theme-bold:ring-1 theme-gradient:ring-1 ring-inset transition-colors',
style.container,
closeable && 'pr-12',
hasLink && style.hover
className={cx(
'announcement-box',
`announcement-${announcement.style}`,
closeable && 'announcement-closeable',
hasLink && 'announcement-linked'
)}
insights={
announcement.link
@@ -65,10 +62,7 @@ export function AnnouncementBanner(props: {
: undefined
}
>
<Icon
icon={style.icon as IconName}
className={`mr-3 mt-0.5 size-4 shrink-0 ${style.iconColor}`}
/>
<Icon icon={style.icon as IconName} className="announcement-icon" />
<div>
{message}
{hasLink ? (
@@ -85,7 +79,7 @@ export function AnnouncementBanner(props: {
? 'arrow-up-right'
: 'chevron-right'
}
className={tcls('mb-0.5 inline size-3')}
className="mb-0.5 inline size-3"
/>
</div>
) : null}
@@ -123,35 +117,23 @@ function dismissAnnouncement() {
const BANNER_STYLES = {
info: {
container: 'bg-info ring-info-subtle',
hover: 'hover:bg-info-hover active:bg-info-active',
icon: 'circle-info',
iconColor: 'text-info-subtle',
close: 'hover:bg-tint-base hover:ring-info-subtle',
close: 'hover:ring-info-subtle',
link: '',
},
warning: {
container: 'bg-warning decoration-warning/6 ring-warning-subtle',
hover: 'hover:bg-warning-hover',
icon: 'circle-exclamation',
iconColor: 'text-warning-subtle',
close: 'hover:bg-tint-base hover:ring-warning-subtle',
close: 'hover:ring-warning-subtle',
link: 'links-default:text-warning hover:links-default:text-warning-strong links-default:decoration-warning/6 links-accent:decoration-warning',
},
danger: {
container: 'bg-danger decoration-danger/6 ring-danger-subtle',
hover: 'hover:bg-danger-hover',
icon: 'triangle-exclamation',
iconColor: 'text-danger-subtle',
close: 'hover:bg-tint-base hover:ring-danger-subtle',
close: 'hover:ring-danger-subtle',
link: 'links-default:text-danger hover:links-default:text-danger-strong links-default:decoration-danger/6 links-accent:decoration-danger',
},
success: {
container: 'bg-success decoration-success/6 ring-success-subtle',
hover: 'hover:bg-success-hover',
icon: 'circle-check',
iconColor: 'text-success-subtle',
close: 'hover:bg-tint-base hover:ring-success-subtle',
close: 'hover:ring-success-subtle',
link: 'links-default:text-success hover:links-default:text-success-strong links-default:decoration-success/6 links-accent:decoration-success',
},
};
@@ -19,7 +19,7 @@ export function AnnotationPopover(props: { children: React.ReactNode; body: Reac
>
<dfn
data-annotation=""
className="not-italic cursor-help underline decoration-dotted decoration-1 underline-offset-2"
className="cursor-help not-italic underline decoration-dotted decoration-1 underline-offset-2"
// oxlint-disable-next-line jsx-a11y/no-noninteractive-tabindex -- we want to be able to focus the definition to open the tooltip
tabIndex={0}
>
@@ -34,7 +34,7 @@ import {
SkeletonParagraph,
SkeletonUpdate,
} from '@/components/primitives';
import type { ClassValue } from '@/lib/tailwind';
import type { ClassValue } from '@/lib/classnames';
import { nullIfNever } from '@/lib/typescript';
export interface BlockProps<Block extends DocumentBlock> extends DocumentContextProps {
@@ -1,18 +0,0 @@
@reference "../RootLayout/globals.css";
/* This file can be the first stylesheet a route loads, and layer order follows first
appearance. Without this, `components` would be created here and Tailwind's `base`
only later, letting preflight's `padding: 0` and `border: 0` win over the rules below. */
@layer theme, base, components, utilities;
/* Every block on every page carries these, so they live here rather than in each class attribute. */
@layer components {
.gb-block {
@apply decoration-primary/6;
}
/* Lists opt out: a long list is expected to break across printed pages. */
.gb-block:not(.gb-block-list) {
@apply print:break-inside-avoid;
}
}
@@ -1,11 +1,10 @@
import type { DocumentBlock, JSONDocument } from '@gitbook/api';
import { CONTENT_STYLE, CONTENT_STYLE_REDUCED } from '../layout';
import { CONTENT_STYLE } from '../layout';
import { Block } from './Block';
import './Blocks.css';
import type { DocumentContextProps } from './DocumentView';
import { isBlockOffscreen } from './utils';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { type ClassValue, cx } from '@/lib/classnames';
/**
* Renders a list of blocks with a wrapper element.
@@ -25,7 +24,7 @@ export function Blocks<TBlock extends DocumentBlock, Tag extends React.ElementTy
const { tag: Tag = 'div', style, wrapperProps, ...blocksProps } = props;
return (
<Tag {...wrapperProps} className={tcls(style)}>
<Tag {...wrapperProps} className={cx(style)}>
<UnwrappedBlocks {...blocksProps} />
</Tag>
);
@@ -94,9 +93,9 @@ export function UnwrappedBlocks<TBlock extends DocumentBlock>(props: UnwrappedBl
key={node.key || `${node.type}-${index}`}
block={node}
style={[
// `gb-block` carries the reduced content width.
'gb-block',
FULL_WIDTH_BLOCKS.has(node.type) ? CONTENT_STYLE : CONTENT_STYLE_REDUCED,
FULL_WIDTH_BLOCKS.has(node.type) && CONTENT_STYLE,
LIST_BLOCKS.has(node.type) && 'gb-block-list',
blockStyle,
]}
@@ -10,15 +10,15 @@ import type {
import type { DocumentContextProps } from './DocumentView';
import { Inlines } from './Inlines';
import { getCommentAnchorProps } from './utils';
import { type ClassValue, cx } from '@/lib/classnames';
import { getNodeFragmentByName, isNodeEmpty } from '@/lib/document';
import { type ClassValue, tcls } from '@/lib/tailwind';
export type CaptionAlign = NonNullable<DocumentBlockImages['data']['align']>;
const captionAlignStyles = {
center: 'mx-auto',
left: 'mr-auto ml-0',
right: 'mr-0 ml-auto',
center: 'gb-caption-center',
left: 'gb-caption-left',
right: 'gb-caption-right',
} satisfies Record<CaptionAlign, ClassValue>;
/**
@@ -51,17 +51,10 @@ export function Caption(
withBorder = false,
withFrame = false,
wrapperStyle = [
'relative',
'overflow-hidden',
'after:block',
'after:absolute',
'after:-inset-0',
'after:pointer-events-none',
fit ? 'w-fit' : null,
withBorder
? 'rounded-corners:rounded-sm circular-corners:rounded-2xl after:border-tint-subtle after:border after:rounded circular-corners:after:rounded-2xl rounded-corners:after:rounded-sm dark:after:mix-blend-plus-lighter after:pointer-events-none'
: null,
withFrame && 'p-2',
'gb-caption-media',
fit && 'gb-caption-fit',
withBorder && 'gb-caption-bordered',
withFrame && 'gb-caption-framed',
],
style,
align = 'center',
@@ -79,23 +72,16 @@ export function Caption(
isNodeEmpty(captionParagraph)
) {
return (
<div {...anchorProps} className={tcls(style, wrapperStyle)}>
<div {...anchorProps} className={cx(style, wrapperStyle)}>
{children}
</div>
);
}
return (
<picture {...anchorProps} className={tcls('relative', style)}>
<div className={tcls(wrapperStyle, captionAlignStyles[align])}>{children}</div>
<figcaption
className={tcls(
'text-xs',
'text-center',
'text-tint',
withFrame ? 'mt-0.5 mb-2.5' : 'mt-2'
)}
>
<picture {...anchorProps} className={cx('gb-caption', style)}>
<div className={cx(wrapperStyle, captionAlignStyles[align])}>{children}</div>
<figcaption className={cx('gb-caption-text', withFrame && 'gb-caption-text-framed')}>
<Inlines
nodes={captionParagraph.nodes}
document={document}
@@ -7,7 +7,7 @@ import { useTrackEvent } from '@/components/Insights';
import { Button } from '@/components/primitives';
import { isAIChatEnabled } from '@/components/utils/isAIChatEnabled';
import { t, useLanguage } from '@/intl/client';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { type ClassValue, cx } from '@/lib/classnames';
export function AskAICodeButton(props: {
codeId: string;
@@ -50,7 +50,7 @@ export function AskAICodeButton(props: {
variant="secondary"
icon={<AIChatIcon state="default" trademark={config.trademark} className="" />}
onClick={onClick}
className={tcls(style, 'translate-y-0!', 'print:hidden', '[[data-ai-chat]_&]:hidden')}
className={cx(style, 'codeblock-button-ask')}
>
{t(language, 'ask')}
</Button>
@@ -180,11 +180,7 @@ function CodeBlockExpandable(props: {
<div
className={tcls(
!isExpanded
? [
'[&_pre]:h-[calc(2rem+var(--line-count)*var(--line-height))] [&_pre]:overflow-y-hidden',
// Mask the code rather than the pre to keep its border, with stops on the visible lines.
'[&_code]:mask-b-from-[calc((var(--line-count)+1)*var(--line-height)*0.55)] [&_code]:mask-b-to-[calc((var(--line-count)+1)*var(--line-height))]',
]
? '[&_pre]:h-[calc(2rem+var(--line-count)*var(--line-height))] [&_pre]:overflow-y-hidden'
: ''
)}
style={
@@ -9,6 +9,7 @@ import { getCommentKeyAttributes } from '../utils/commentAnchors';
import { AskAICodeButton } from './AskAICodeButton';
import { CopyCodeButton } from './CopyCodeButton';
import type { HighlightLine, HighlightTheme, HighlightToken } from './highlight-tokens';
import { cx } from '@/lib/classnames';
import { tcls } from '@/lib/tailwind';
type CodeBlockRendererProps = Pick<BlockProps<DocumentBlockCode>, 'block' | 'style'> & {
@@ -55,28 +56,16 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
id={codeId}
{...getCommentKeyAttributes(commentKey)}
aria-busy={ariaBusy}
className={tcls(
'group/codeblock shiki relative flex shrink flex-col overflow-hidden print:overflow-visible',
!embedded &&
'circular-corners:rounded-2xl rounded-corners:rounded-xl straight-corners:rounded-xs',
!embedded &&
'[&:has([data-codeblock-focus]:focus)]:ring-2 [&:has([data-codeblock-focus]:focus)]:ring-primary-hover',
style
)}
className={cx('shiki codeblock', !embedded && 'codeblock-framed', tcls(style))}
/* Sets the code theme's mode (light or dark) for the site's theme mode (light or dark).
* Used to style UI elements (scrollbars, form controls) correctly and apply the right default to "plain" code blocks. */
data-color-scheme={`${theme.themes.light.type} ${theme.themes.dark.type}`}
>
<span
data-codeblock-focus
tabIndex={-1}
aria-hidden
className="pointer-events-none absolute size-0 outline-none"
/>
<div className="flex items-center justify-start gap-2 text-sm">
<span data-codeblock-focus tabIndex={-1} aria-hidden className="codeblock-focus" />
<div className="codeblock-header">
{withTitle ? (
<div
className="straight-corners:rounded-t-xs relative top-px z-20 inline-flex items-center justify-center border border-b-0 border-tint-subtle bg-tint-subtle px-3 py-2 text-xs leading-none tracking-wide text-tint theme-bold-tint:bg-tint-base theme-muted:bg-tint-base rounded-corners:rounded-t-lg circular-corners:rounded-t-xl contrast-more:border-tint contrast-more:bg-tint-base [html.theme-bold.sidebar-filled_&]:bg-tint-base"
className="codeblock-title"
style={{
backgroundColor: bg?.color,
...bg?.vars,
@@ -88,12 +77,12 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
</div>
) : null}
</div>
<div className="relative flex min-h-0 flex-col">
<div className="codeblock-body">
{!embedded ? (
<div
className={tcls(
'absolute right-2 z-2 flex items-center gap-1.5 font-sans leading-none opacity-0 group-hover/codeblock:opacity-11 has-[button:focus-visible]:opacity-11',
isSingleLine ? 'inset-y-0' : 'top-2'
className={cx(
'codeblock-actions',
isSingleLine && 'codeblock-actions-centered'
)}
>
{!isPrint ? (
@@ -101,21 +90,17 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
codeId={codeId}
title={title}
syntax={block.data.syntax}
style="backdrop-blur-md"
style="codeblock-button"
/>
) : null}
<CopyCodeButton codeId={codeId} style="backdrop-blur-md" />
<CopyCodeButton codeId={codeId} style="codeblock-button" />
</div>
) : null}
<pre
className={tcls(
'relative overflow-auto py-2.5 text-tint-strong print:overflow-visible',
embedded
? 'bg-tint-base'
: 'border border-tint-subtle bg-tint-subtle theme-bold-tint:bg-tint-base theme-muted:bg-tint-base contrast-more:border-tint contrast-more:bg-tint-base',
!embedded &&
'circular-corners:rounded-2xl rounded-corners:rounded-xl straight-corners:rounded-xs depth-subtle:shadow-xs',
withTitle && 'rounded-ss-none!'
className={cx(
'codeblock-pre',
embedded ? 'codeblock-pre-embedded' : 'codeblock-pre-framed',
withTitle && 'codeblock-pre-titled'
)}
style={{
backgroundColor: codeBackground?.color,
@@ -124,12 +109,7 @@ export const CodeBlockRenderer = forwardRef(function CodeBlockRenderer(
...fg?.vars,
}}
>
<code
className={tcls(
'table max-h-full w-fit min-w-full [counter-reset:line] print:max-h-none print:whitespace-pre-wrap',
withWrap && 'whitespace-pre-wrap'
)}
>
<code className={cx('codeblock-code', withWrap && 'codeblock-code-wrap')}>
{theme.lines.map((line, index) => (
<CodeHighlightLine
bg={codeBackground}
@@ -166,9 +146,9 @@ function CodeHighlightLine(props: {
};
return (
<span
className={tcls(
className={cx(
'highlight-line',
embeddedPlainLine && 'bg-transparent! hover:bg-tint-subtle!',
embeddedPlainLine && 'highlight-line-plain',
line.diff === 'added' && 'diff-added',
line.diff === 'deleted' && 'diff-deleted',
line.highlighted && 'highlighted'
@@ -4,7 +4,7 @@ import { getCodeTextFromId } from './utils';
import { useCopyToClipboard } from '@/components/hooks';
import { Button } from '@/components/primitives';
import { t, useLanguage } from '@/intl/client';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { type ClassValue, cx } from '@/lib/classnames';
/**
* Client component to copy the code of a code block.
@@ -26,12 +26,7 @@ export function CopyCodeButton(props: { codeId: string; style: ClassValue }) {
return (
<>
<Button
size="xsmall"
variant="secondary"
onClick={onClick}
className={tcls(style, 'translate-y-0!', 'print:hidden')}
>
<Button size="xsmall" variant="secondary" onClick={onClick} className={cx(style)}>
{t(language, copied ? 'code_copied' : 'code_copy')}
</Button>
{/* A label swap on the focused button isn't announced, the live region is. */}
@@ -5,6 +5,7 @@ import { type DocumentBlockColumns, type Length, VerticalAlignment } from '@gitb
import type { BlockProps } from '../Block';
import { Blocks } from '../Blocks';
import { getCommentMarkerProps } from '../utils';
import { cx } from '@/lib/classnames';
import { tcls } from '@/lib/tailwind';
export function Columns(props: BlockProps<DocumentBlockColumns>) {
@@ -40,10 +41,7 @@ export function Columns(props: BlockProps<DocumentBlockColumns>) {
<div
// The app doesn't allow comments inside columns.
{...getCommentMarkerProps(context, 'data-comment-ignore')}
className={tcls(
'grid w-full @2xl:grid-flow-col @2xl:grid-cols-[repeat(var(--grid-slices),minmax(0,1fr))] grid-cols-1 @2xl:grid-rows-1 gap-x-8 gap-y-4',
style
)}
className={cx('column-set', tcls(style))}
style={{ '--grid-slices': COLUMN_DIVISIONS } as React.CSSProperties}
>
{block.nodes.map((columnBlock, index) => {
@@ -65,7 +63,8 @@ export function Columns(props: BlockProps<DocumentBlockColumns>) {
document={document}
ancestorBlocks={[...ancestorBlocks, block, columnBlock]}
context={context}
style="group/column w-full space-y-4 *:max-w-full"
// `*:max-w-full` stays a utility to beat the blocks' own `max-w-*`.
style="group/column column-set-body *:max-w-full"
/>
</Column>
);
@@ -83,13 +82,10 @@ export function Column(props: {
const { className, style } = transformLengthToCSS(width) ?? {};
return (
<div
className={tcls(
'flex flex-col',
'@container/column',
(verticalAlignment === VerticalAlignment.Top || !verticalAlignment) &&
'justify-start',
verticalAlignment === VerticalAlignment.Middle && 'justify-center',
verticalAlignment === VerticalAlignment.Bottom && 'justify-end',
className={cx(
'column-set-item',
verticalAlignment === VerticalAlignment.Middle && 'column-set-item-middle',
verticalAlignment === VerticalAlignment.Bottom && 'column-set-item-bottom',
className
)}
style={style}
@@ -107,7 +103,7 @@ export function transformLengthToCSS(length: Length) {
}
if (length.unit === '%') {
return {
className: '@2xl:flex-shrink-0 @2xl:[grid-column:var(--grid-col)]',
className: 'column-set-item-sized',
style: {
'--grid-col': `auto / span ${Math.round(length.value * 0.01 * COLUMN_DIVISIONS)}`,
} as React.CSSProperties,
@@ -1,10 +1,10 @@
import type { DocumentBlockDivider } from '@gitbook/api';
import type { BlockProps } from './Block';
import { tcls } from '@/lib/tailwind';
import { cx } from '@/lib/classnames';
export function Divider(props: BlockProps<DocumentBlockDivider>) {
const { style } = props;
return <hr className={tcls(style, 'border-tint-subtle')} />;
return <hr className={cx(style, 'border-tint-subtle')} />;
}
@@ -2,8 +2,8 @@ import type { JSONDocument } from '@gitbook/api';
import { BlockSkeleton } from './Block';
import { Blocks } from './Blocks';
import type { ClassValue } from '@/lib/classnames';
import type { GitBookAnyContext } from '@/lib/context';
import type { ClassValue } from '@/lib/tailwind';
export interface DocumentContext {
/**
@@ -3,7 +3,7 @@
import React from 'react';
import { useHash } from '@/components/hooks';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { type ClassValue, cx } from '@/lib/classnames';
/**
* Details component rendered on client so it can expand dependent on url hash changes.
@@ -50,27 +50,7 @@ export function Details(props: {
id={id}
data-block-key={props.commentKey}
open={props.open || openFromHash}
className={tcls(
className,
'group/expandable',
'bg-tint-base',
'border',
'border-b-0',
'border-tint-subtle',
//all
'mt-0!',
'mb-0',
//select first child
'first:mt-5!',
'first:rounded-t-lg',
//select first in group
'[:not(&)_+_&]:mt-5!',
'[:not(&)_+_&]:rounded-t-lg',
//select last in group
'[&:not(:has(+_&))]:mb-5',
'[&:not(:has(+_&))]:rounded-b-lg',
'[&:not(:has(+_&))]:border-b'
)}
className={cx('expandable', className)}
>
{children}
</details>
@@ -10,6 +10,7 @@ import { Details } from './Details';
import { ToggleChevron } from '@/components/primitives';
import { getSpaceLanguage, tString } from '@/intl/server';
import { defaultLanguage } from '@/intl/translations';
import { cx } from '@/lib/classnames';
import { getNodeFragmentByType } from '@/lib/document';
import { tcls } from '@/lib/tailwind';
@@ -40,37 +41,16 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
id={id}
{...getCommentKeyProp(context, block.key)}
open={context.mode === 'print' || isDefaultExpanded}
className={tcls('scroll-mt-(--content-scroll-margin)', style)}
className={tcls(style)}
>
<summary
{...getCommentAnchorProps(context, titleParagraph.key)}
className={tcls(
'cursor-pointer',
'px-4',
// Reserve room for the anchor icon pinned to the right edge
showHashLink && 'pr-10',
'py-4',
'relative',
'list-none',
'select-none',
'transition-colors',
'text-tint',
'group-hover/expandable:text-tint-strong',
'group-open/expandable:text-tint-strong',
'[&::-webkit-details-marker]:hidden'
)}
className={cx('expandable-summary', showHashLink && 'expandable-summary-anchored')}
>
<ToggleChevron
orientation="right-to-down"
open={context.mode === 'print'}
className={tcls(
'inline-block',
'size-3',
'mr-3',
'mb-1',
'shrink-0',
'group-open/expandable:rotate-90'
)}
className="expandable-chevron"
/>
<Inlines
nodes={titleParagraph.nodes}
@@ -82,28 +62,9 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
<a
href={`#${id}`}
aria-label={tString(language, 'direct_link_to_heading')}
className={tcls(
'absolute',
'top-2',
'bottom-2',
'right-4',
'flex',
'items-center',
'dark:shadow-none',
'dark:ring-0'
)}
className="expandable-anchor"
>
<Icon
icon="hashtag"
className={tcls(
'inline-block',
'size-3',
'transition-colors',
'text-transparent',
'group-hover/expandable:text-tint-subtle',
'contrast-more:group-hover/expandable:text-tint-strong'
)}
/>
<Icon icon="hashtag" className="expandable-anchor-icon" />
</a>
) : null}
</summary>
@@ -112,7 +73,7 @@ export async function Expandable(props: BlockProps<DocumentBlockExpandable>) {
document={document}
ancestorBlocks={[...ancestorBlocks, block]}
context={context}
style="space-y-4 px-10 pb-5"
style="expandable-body"
/>
</Details>
);
@@ -41,12 +41,12 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
return (
<Caption {...props} withBorder withBlockKey>
<div className="flex flex-wrap items-center gap-5 px-5 py-3">
<div className="flex min-h-8 min-w-14 flex-col items-center justify-center gap-1 border-r border-tint-subtle pr-4">
<div className="file-block">
<div className="file-block-preview">
{contentType === 'image' ? (
<Image
alt={file.name}
className="h-auto max-h-10 w-auto max-w-10 rounded object-contain"
className="file-block-image"
sizes={[{ width: 40 }]}
resize={context.contentContext?.imageResizer}
sources={{
@@ -58,11 +58,11 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
loading="lazy"
/>
) : (
<FileIcon contentType={contentType} className="size-5 text-primary" />
<FileIcon contentType={contentType} className="file-block-icon" />
)}
</div>
<div className="min-w-24 flex-1">
<div className="text-base">
<div className="file-block-info">
<div className="file-block-name">
<Link
href={file.downloadURL}
target="_blank"
@@ -72,13 +72,13 @@ export async function File(props: BlockProps<DocumentBlockFile>) {
{file.name}
</Link>
</div>
<div className="text-sm text-tint-subtle">
<div className="file-block-meta">
{contentType
? `${contentType} · ${getHumanFileSize(file.size)}`
: getHumanFileSize(file.size)}
</div>
</div>
<div className="flex shrink-0 flex-wrap gap-2">
<div className="file-block-actions">
<DownloadButton
icon="download"
size="xsmall"
@@ -1,30 +0,0 @@
@reference "../RootLayout/globals.css";
/* This file can be the first stylesheet a route loads, and layer order follows first
appearance. Without this, `components` would be created here and Tailwind's `base`
only later, letting preflight's `padding: 0` and `border: 0` win over the rules below. */
@layer theme, base, components, utilities;
/* A page carries one of these per heading, so the shared utilities live here instead of in a class
attribute repeated hundreds of times — on a large page that repetition is most of the HTML.
They sit in `components` so the utilities passed as props still override them. */
@layer components {
.hash {
@apply relative inline-grid grid-area-1-1 border-0 rounded site-background;
@apply pointer-events-none opacity-0 transition-opacity;
@apply pointer-fine:h-[1em] pointer-fine:pointer-events-auto;
@apply pointer-fine:group-hover/hash:opacity-100 pointer-fine:group-focus-within/hash:opacity-100;
@apply [.hash-revealed_&]:pointer-events-auto [.hash-revealed_&]:opacity-100;
}
.hash-link {
@apply inline-flex items-center p-1 pointer-fine:h-full pointer-fine:p-0;
}
.hash-icon {
@apply size-3 self-center text-transparent transition-colors;
@apply pointer-fine:group-hover/hash:text-tint-subtle contrast-more:pointer-fine:group-hover/hash:text-tint-strong;
@apply pointer-fine:group-focus-within/hash:text-tint-subtle contrast-more:pointer-fine:group-focus-within/hash:text-tint-strong;
@apply [.hash-revealed_&]:text-tint-subtle contrast-more:[.hash-revealed_&]:text-tint-strong;
}
}
@@ -3,9 +3,7 @@ import { Icon } from '@gitbook/icons';
import { Link } from '../primitives';
import type { DocumentContext } from './DocumentView';
import './HashLinkButton.css';
import { getBlockTextStyle } from './spacing';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { type ClassValue, cx } from '@/lib/classnames';
/**
* Whether blocks should render a visible anchor link icon.
@@ -21,10 +19,8 @@ export function shouldShowHashLinks(context: DocumentContext): boolean {
/**
* A hash icon which adds the block or active block item's ID in the URL hash.
* The button needs to be wrapped in a container with `hashLinkButtonWrapperStyles`.
* Styled in `styles/blocks.css`, it is revealed when hovering its `.heading` parent.
*/
export const hashLinkButtonWrapperStyles = tcls('relative', 'group/hash');
export function HashLinkButton(props: {
id: string;
block: DocumentBlockTabs | DocumentBlockHeading;
@@ -32,17 +28,12 @@ export function HashLinkButton(props: {
className?: ClassValue;
iconClassName?: ClassValue;
}) {
const { id, block, className, iconClassName, label } = props;
const textStyle = getBlockTextStyle(block);
const { id, className, iconClassName, label } = props;
return (
<span className={tcls('hash', className)}>
<Link
href={`#${id}`}
aria-label={label}
className={tcls('hash-link', textStyle.lineHeight)}
>
<Icon icon="hashtag" className={tcls('hash-icon', iconClassName)} />
<span className={cx('hash', className)}>
<Link href={`#${id}`} aria-label={label} className="hash-link">
<Icon icon="hashtag" className={cx('hash-icon', iconClassName)} />
</Link>
</span>
);
@@ -1,20 +1,17 @@
import type { DocumentBlockHeading } from '@gitbook/api';
import type { BlockProps } from './Block';
import { HashLinkButton, hashLinkButtonWrapperStyles, shouldShowHashLinks } from './HashLinkButton';
import { HashLinkButton, shouldShowHashLinks } from './HashLinkButton';
import { HeadingRevealWrapper } from './HeadingRevealWrapper';
import { Inlines } from './Inlines';
import { getBlockTextStyle } from './spacing';
import { getCommentAnchorProps, getTextAlignment } from './utils';
import { getSpaceLanguage, tString } from '@/intl/server';
import { defaultLanguage } from '@/intl/translations';
import { tcls } from '@/lib/tailwind';
import { cx } from '@/lib/classnames';
export async function Heading(props: BlockProps<DocumentBlockHeading>) {
const { block, style, context, ...rest } = props;
const textStyle = getBlockTextStyle(block);
const Tag = TAGS[block.type];
let id = block.meta?.id ?? '';
@@ -31,38 +28,20 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
as={Tag}
id={id}
{...getCommentAnchorProps(context, block.key)}
className={tcls(
textStyle.textSize,
className={cx(
'heading',
block.type,
'font-heading',
'pdf-heading',
'block',
// Reserve room for the absolutely positioned anchor icon on coarse pointers
showHashLink && 'pr-6',
'pointer-fine:flex',
'pointer-fine:items-baseline',
'pointer-fine:pr-0',
'scroll-mt-(--content-scroll-margin)',
getTextAlignment(block.data.align),
hashLinkButtonWrapperStyles,
style,
textStyle.marginTop
style
)}
>
<span
// Cover-aware contrast text applies only to the page body, not to documents
// rendered in overlays (search answers, AI chat) on a background-cover page.
data-cover-aware-text={context.isPageBody ? '' : undefined}
className={tcls(
'pointer-fine:flex-1',
'z-1',
'justify-self-start',
'max-w-full',
'break-words',
// Cover-aware contrast text applies only to the page body, not to documents
// rendered in overlays (search answers, AI chat) on a background-cover page.
context.isPageBody && 'page-cover-background:text-contrast-cover',
getTextAlignment(block.data.align),
textStyle.lineHeight
)}
className={cx('heading-text', getTextAlignment(block.data.align))}
>
<Inlines {...rest} context={context} nodes={block.nodes} ancestorInlines={[]} />
</span>
@@ -71,15 +50,6 @@ export async function Heading(props: BlockProps<DocumentBlockHeading>) {
<HashLinkButton
id={id}
block={block}
className={tcls(
'absolute',
block.type === 'heading-1'
? '[transform:translateY(0.125em)]'
: '[transform:translateY(0.17em)]',
'pointer-fine:-ml-6 pointer-fine:relative pointer-fine:order-first pointer-fine:self-center pointer-fine:pr-2 pointer-fine:[transform:none]',
'pointer-fine:[.flip-heading-hash_&]:order-last pointer-fine:[.flip-heading-hash_&]:ml-1 pointer-fine:[.flip-heading-hash_&]:pl-2'
)}
iconClassName={tcls('size-4')}
label={tString(language, 'direct_link_to_heading')}
/>
) : null}
@@ -2,7 +2,7 @@
import { useSyncExternalStore } from 'react';
import { type ClassValue, tcls } from '@/lib/tailwind';
import { type ClassValue, cx } from '@/lib/classnames';
const HEADING_ATTR = 'data-heading-reveal-wrapper';
@@ -87,7 +87,7 @@ export function HeadingRevealWrapper(props: {
return (
<Tag
id={id}
className={tcls(className, revealed && 'hash-revealed')}
className={cx(className, revealed && 'hash-revealed')}
onPointerUp={handlePointerUp}
{...{ [HEADING_ATTR]: true }}
{...rest}
@@ -1,14 +1,14 @@
import type { DocumentBlockHint } from '@gitbook/api';
import { Icon, type IconName } from '@gitbook/icons';
import { validateIconName } from '@gitbook/icons/validateIconName';
import { validateIconName } from '@gitbook/icons/icons';
import { Block, type BlockProps } from './Block';
import { Blocks } from './Blocks';
import { getBlockTextStyle } from './spacing';
import { BLOCK_LINE_HEIGHT, getBlockTextKind } from './spacing';
import { getSpaceLanguage, tString } from '@/intl/server';
import { defaultLanguage } from '@/intl/translations';
import { type ClassValue, cx } from '@/lib/classnames';
import { isHeadingBlock } from '@/lib/document';
import { type ClassValue, tcls } from '@/lib/tailwind';
export async function Hint({
block,
@@ -22,7 +22,7 @@ export async function Hint({
const icon = customIcon && validateIconName(customIcon) ? customIcon : hintStyle.icon;
const firstNode = block.nodes[0]!;
const firstLine = getBlockTextStyle(firstNode);
const firstLineHeight = BLOCK_LINE_HEIGHT[getBlockTextKind(firstNode)];
const hasHeading = isHeadingBlock(firstNode);
const language = contextProps.context.contentContext
@@ -33,42 +33,25 @@ export async function Hint({
return (
<div
className={tcls(
className={cx(
'hint',
'transition-colors',
'rounded-corners:rounded-md',
'circular-corners:rounded-xl',
hasHeading ? 'circular-corners:rounded-l-none rounded-corners:rounded-l-none' : '',
'overflow-hidden',
hasHeading ? ['border-l-2', hintStyle.containerWithHeader] : hintStyle.container,
'text-sm',
'grid',
'grid-cols-[auto_1fr]',
hasHeading ? 'grid-rows-[auto_auto]' : '',
hasHeading && 'hint-titled',
// Kept as utilities: `AskAIParagraphButton` matches `.hint.bg-*`.
hasHeading ? hintStyle.containerWithHeader : hintStyle.container,
style
)}
aria-label={label}
role="note"
>
<div
className={tcls(
'py-4',
'pl-4',
hasHeading ? hintStyle.header : null,
hintStyle.iconColor
)}
>
<Icon icon={icon} className={tcls('size-[1.2em]', 'mt-px', firstLine.lineHeight)} />
<div className={cx('hint-aside', hasHeading && hintStyle.header, hintStyle.iconColor)}>
<Icon icon={icon} className={cx('hint-icon', firstLineHeight)} />
</div>
{hasHeading ? (
<Block
style={tcls(
'w-full items-start py-4! pl-3 text-[1em]! *:flex-none',
// Heading hash styles
'flip-heading-hash pr-8 [&_.hash]:bg-transparent',
style={cx(
'hint-heading flip-heading-hash',
// A utility, to beat the themed backgrounds of `.hash`.
'[&_.hash]:bg-transparent',
hintStyle.header
)}
ancestorBlocks={[...ancestorBlocks, block]}
@@ -80,27 +63,13 @@ export async function Hint({
{...contextProps}
ancestorBlocks={[...ancestorBlocks, block]}
nodes={hasHeading ? block.nodes.slice(1) : block.nodes}
blockStyle={tcls(
blockStyle={cx(
hintStyle.body,
// render hash icon on the other side of the heading
'flip-heading-hash'
)}
style={[
'p-4',
'pl-3',
'empty:p-0',
'-row-end-1',
'-col-end-1',
// Allow the grid track to shrink below its content's min-content size so wide
// nested blocks (e.g. code blocks, tables) scroll internally instead of
// overflowing the hint. Without this, the `1fr` column keeps its default
// `min-width: auto` and grows past the hint's width.
'min-w-0',
'space-y-3',
'[&_.hint]:border',
'[&_pre]:border',
'[&_pre]:border-neutral',
]}
// Descendant rules stay utilities so they keep beating the nested blocks' own classes.
style="hint-content [&_.hint]:border [&_pre]:border [&_pre]:border-neutral"
/>
</div>
);
@@ -5,8 +5,8 @@ import { Caption, type CaptionAlign } from './Caption';
import type { DocumentContext } from './DocumentView';
import { getCommentAnchorProps } from './utils';
import { Image, type ImageResponsiveSize } from '@/components/utils';
import { type ClassValue, cx } from '@/lib/classnames';
import { resolveContentRefInDocument } from '@/lib/references';
import { type ClassValue, tcls } from '@/lib/tailwind';
export function Images(props: BlockProps<DocumentBlockImages>) {
const { document, block, style, context, isEstimatedOffscreen } = props;
@@ -17,30 +17,18 @@ export function Images(props: BlockProps<DocumentBlockImages>) {
return (
<div
{...getCommentAnchorProps(context, block.key)}
className={tcls(
className={cx(
style,
'flex',
'w-full',
align === 'center' && 'justify-center',
align === 'right' && 'justify-end',
align === 'left' && 'justify-start'
'gb-images',
align === 'right' && 'gb-images-right',
align === 'left' && 'gb-images-left'
)}
>
<div
className={tcls(
'flex',
'flex-row',
'gap-3',
hasMultipleImages && ['grid', 'grid-flow-col'],
withFrame && [
'rounded-2xl',
'border',
'border-[rgb(234,235,238)]',
'dark:border-[rgb(45,50,58)]',
'relative',
'overflow-hidden',
'w-fit',
]
className={cx(
'gb-images-row',
hasMultipleImages && 'gb-images-multi',
withFrame && 'gb-images-framed'
)}
>
{block.nodes.map((node: any, _i: number) => (
@@ -100,7 +88,7 @@ async function ImageBlock(props: {
}
return (
<div className={tcls('relative', 'overflow-hidden')}>
<div className="gb-image">
<Caption {...props} fit align={align}>
<Image
alt={block.data.alt ?? ''}
@@ -2,8 +2,8 @@ import type { DocumentInlineIcon } from '@gitbook/api';
import { Icon, type IconName } from '@gitbook/icons';
import type { InlineProps } from './Inline';
import { cx } from '@/lib/classnames';
import { textColorToStyle } from '@/lib/colors';
import { tcls } from '@/lib/tailwind';
export async function InlineIcon(props: InlineProps<DocumentInlineIcon>) {
const { inline } = props;
@@ -12,7 +12,7 @@ export async function InlineIcon(props: InlineProps<DocumentInlineIcon>) {
return (
<Icon
icon={icon as IconName}
className={tcls('inline size-[1em]', color ? textColorToStyle[color] : null)}
className={cx('inline-icon', color ? textColorToStyle[color] : null)}
/>
);
}
@@ -4,9 +4,9 @@ import type { DocumentInlineImage } from '@gitbook/api';
import { Image } from '../utils';
import type { InlineProps } from './Inline';
import { cx } from '@/lib/classnames';
import type { GitBookBaseContext } from '@/lib/context';
import { type ResolvedContentRef, resolveContentRefInDocument } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
export async function InlineImage(props: InlineProps<DocumentInlineImage>) {
const { document, inline, context, ancestorInlines } = props;
@@ -30,11 +30,7 @@ export async function InlineImage(props: InlineProps<DocumentInlineImage>) {
return (
/* Ensure images dont expand to the size of the container where this Image may be nested in. Now it's always nested in a size-restricted container */
<span
className={tcls(
size !== 'line' ? ['inline-flex', 'max-w-[300px]', 'align-middle'] : null
)}
>
<span className={cx(size !== 'line' && 'inline-flex max-w-[300px] align-middle')}>
<Image
alt={inline.data.alt ?? inline.data.caption ?? ''}
sizes={sizes}
@@ -40,12 +40,7 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
return (
<NotFoundRefHoverCard context={context}>
{fallback ? (
<InlineLinkAnchor
href={fallback.href}
contentRef={inline.data.ref}
target={inline.data.target}
isExternal
>
<InlineLinkAnchor href={fallback.href} contentRef={inline.data.ref} isExternal>
{inlinesElement}
</InlineLinkAnchor>
) : (
@@ -58,7 +53,6 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
<InlineLinkAnchor
href={resolved.href}
contentRef={resolved.resolvedRef ?? inline.data.ref}
target={inline.data.target}
isExternal={(resolved.resolvedRef ?? inline.data.ref).kind === 'url'}
>
{inlinesElement}
@@ -81,16 +75,14 @@ export async function InlineLink(props: InlineProps<DocumentInlineLink>) {
function InlineLinkAnchor(props: {
href: string;
contentRef: ContentRef;
target: DocumentInlineLink['data']['target'];
isExternal?: boolean;
children: React.ReactNode;
}) {
const { href, isExternal, contentRef, target, children } = props;
const { href, isExternal, contentRef, children } = props;
const isMailto = href.startsWith('mailto:');
return (
<StyledLink
href={href}
target={target ? `_${target}` : undefined}
insights={{
type: 'link_click',
link: {
@@ -101,15 +93,9 @@ function InlineLinkAnchor(props: {
>
{children}
{isMailto ? (
<Icon
icon="envelope"
className="ml-1 inline size-3 links-accent:text-tint-subtle"
/>
<Icon icon="envelope" className="inline-link-icon inline-link-mail" />
) : isExternal ? (
<Icon
icon="arrow-up-right"
className="ml-0.5 inline size-3 links-accent:text-tint-subtle"
/>
<Icon icon="arrow-up-right" className="inline-link-icon" />
) : null}
</StyledLink>
);
@@ -1,5 +1,4 @@
import type { DocumentBlockIntegration, RenderIntegrationUI } from '@gitbook/api';
import { Icon } from '@gitbook/icons';
import { ContentKitOutput } from '@gitbook/react-contentkit';
import type { BlockProps } from '../Block';
@@ -54,7 +53,6 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
{
integrationName: block.data.integration,
request: initialInput,
allowFailedDependency: true,
}
);
@@ -68,29 +66,12 @@ export async function IntegrationBlock(props: BlockProps<DocumentBlockIntegratio
// Integration output can render blocks with generated keys.
{...getCommentAnchorProps(context, block.key)}
{...getCommentMarkerProps(context, 'data-comment-block')}
role="note"
className={tcls(
'flex items-start gap-3 p-4 text-sm',
'rounded-corners:rounded-md circular-corners:rounded-xl',
'bg-warning border-warning text-neutral-strong',
style
)}
className={tcls(style)}
>
<Icon
icon="circle-exclamation"
className="mt-0.5 size-4 shrink-0 text-warning-subtle contrast-more:text-warning"
aria-hidden="true"
/>
<div className="wrap-anywhere min-w-0">
<p className="font-medium">
Could not load the {block.data.integration} integration
</p>
<p>
{initialResponse.error.code === 424
? 'Ask an administrator to check its connection and settings.'
: initialResponse.error.message}
</p>
</div>
<pre>
Unexpected error with integration {block.data.integration}:{' '}
{initialResponse.error.message}
</pre>
</div>
);
}
@@ -11,11 +11,9 @@ export async function fetchSafeIntegrationUI(
{
integrationName,
request,
allowFailedDependency = false,
}: {
integrationName: string;
request: RenderIntegrationUI;
allowFailedDependency?: boolean;
}
) {
const output = await ignoreDataFetcherErrors(
@@ -29,7 +27,6 @@ export async function fetchSafeIntegrationUI(
404, // Integration has been uninstalled
400, // Integration is rejecting its own request
422, // Integration is triggering an invalid request, failing at the validation step
...(allowFailedDependency ? [424] : []),
502, // Integration is failing in an unexpected way
]
);
@@ -22,7 +22,7 @@ export function List(
tag={getListTag(block.type)}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={['min-w-0 space-y-2', style]}
style={['gb-list', style]}
/>
);
}
@@ -10,10 +10,10 @@ import type {
import type { BlockProps } from './Block';
import { Blocks } from './Blocks';
import { getBlockTextStyle } from './spacing';
import { getBlockTextKind } from './spacing';
import { getCommentAnchorProps } from './utils';
import { Checkbox } from '@/components/primitives';
import { tcls } from '@/lib/tailwind';
import { cx } from '@/lib/classnames';
export function ListItem(props: BlockProps<DocumentBlockListItem>) {
const { block, ancestorBlocks, ...contextProps } = props;
@@ -32,16 +32,8 @@ export function ListItem(props: BlockProps<DocumentBlockListItem>) {
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
blockStyle={tcls(
'min-h-lh',
// remove margin-top for the first heading in a list
'[h2]:pt-0',
'[h3]:pt-0',
'[h4]:pt-0',
// Override the "mx-auto" class from UnwrappedBlocks
'mx-0'
)}
style="flex min-w-0 flex-1 flex-col space-y-2"
blockStyle="gb-list-child"
style="gb-list-body"
/>
);
@@ -59,7 +51,7 @@ export function ListItem(props: BlockProps<DocumentBlockListItem>) {
/>
</ListItemPrefix>
<label htmlFor={block.key} className={tcls('flex-1')}>
<label htmlFor={block.key} className="flex-1">
{blocksElement}
</label>
</ListItemLI>
@@ -130,27 +122,20 @@ function ListItemLI(props: {
anchorProps: ReturnType<typeof getCommentAnchorProps>;
children: React.ReactNode;
}) {
const textStyle = getBlockTextStyle(props.block);
const kind = getBlockTextKind(props.block);
return (
<li {...props.anchorProps} className={tcls(textStyle.lineHeight, 'flex items-start')}>
<li
{...props.anchorProps}
className={cx('gb-list-item', kind !== 'body' && `gb-list-item-${kind}`)}
>
{props.children}
</li>
);
}
// Sized after the item's first line through the `gb-list-item-*` modifier of its parent.
function ListItemPrefix(props: { block: DocumentBlockListItem; children: React.ReactNode }) {
const textStyle = getBlockTextStyle(props.block);
return (
<div
className={tcls(
textStyle.textSize,
textStyle.lineHeight,
'mr-1 flex min-h-lh min-w-6 items-center justify-center text-tint'
)}
>
{props.children}
</div>
);
return <div className="gb-list-prefix">{props.children}</div>;
}
function getUnorderedListItemsPrefixContent(input: { depth: number }): string {
@@ -173,7 +158,7 @@ function PseudoBefore(props: {
}) {
return (
<div
className="before:content-(--pseudoBefore--content) before:font-var"
className="gb-list-marker"
style={
{
'--pseudoBefore--content': `'${props.content}'`,
@@ -5,8 +5,8 @@ import type { BlockProps } from './Block';
import { Inlines } from './Inlines';
import { getTextAlignment } from './utils';
import { getCommentAnchorProps } from './utils';
import { cx } from '@/lib/classnames';
import { getNodeText } from '@/lib/document';
import { tcls } from '@/lib/tailwind';
export function Paragraph(props: BlockProps<DocumentBlockParagraph>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
@@ -21,7 +21,7 @@ export function Paragraph(props: BlockProps<DocumentBlockParagraph>) {
// rendered in overlays (search answers, AI chat) on a background-cover page.
data-cover-aware-text={context.isPageBody ? '' : undefined}
// Paragraph styles live in globals.css (`.paragraph`) to keep the class attribute short.
className={tcls('paragraph', style, getTextAlignment(block.data?.align))}
className={cx('paragraph', style, getTextAlignment(block.data?.align))}
>
<Inlines {...contextProps} nodes={block.nodes} ancestorInlines={[]} />
</p>
@@ -45,11 +45,7 @@ export function Paragraph(props: BlockProps<DocumentBlockParagraph>) {
<div
// The shared `AskAIParagraphButton` portals itself into the hovered wrapper.
data-ask-ai-paragraph=""
className={tcls(
'group/ask-ai relative',
style,
getTextAlignment(block.data?.align)
)}
className={cx('group/ask-ai relative', style, getTextAlignment(block.data?.align))}
>
{paragraph}
</div>
@@ -4,14 +4,14 @@ import {
type DocumentBlockPrompt,
type SiteCustomizationSettings,
} from '@gitbook/api';
import { validateIconName } from '@gitbook/icons/validateIconName';
import { validateIconName } from '@gitbook/icons/icons';
import type { BlockProps } from '../Block';
import { CodeBlock } from '../CodeBlock';
import { getPlainCodeBlock } from '../CodeBlock/highlight-tokens';
import { COMMENT_IGNORE_CLASSNAME, getCommentKeyProp } from '../utils';
import { PromptClient } from './PromptClient';
import { tcls } from '@/lib/tailwind';
import { cx } from '@/lib/classnames';
const PROMPT_COLLAPSED_LINE_COUNT = 10;
@@ -44,7 +44,7 @@ export function Prompt(props: BlockProps<DocumentBlockPrompt>) {
{...getCommentKeyProp(context, block.key)}
// Only the comment marker: the prompt keeps its own width rather than the block styles.
className={
tcls(style).split(' ').includes(COMMENT_IGNORE_CLASSNAME)
cx(style).split(' ').includes(COMMENT_IGNORE_CLASSNAME)
? COMMENT_IGNORE_CLASSNAME
: undefined
}
@@ -15,7 +15,6 @@ import {
} from '@/components/primitives';
import { tString, useLanguage } from '@/intl/client';
import { AI_AGENTS, getAIAgent } from '@/lib/ai-agents';
import { tcls } from '@/lib/tailwind';
/** How long the copy button shows its confirmation. */
const COPIED_MESSAGE_DURATION = 1000;
@@ -64,7 +63,7 @@ export function PromptActions(props: { prompt: string; openInAIProviders: boolea
return (
// Lifted above the header's overlay button, which otherwise swallows the clicks.
<div className="relative z-20 flex shrink-0 items-center gap-2">
<div className="prompt-actions">
{openInAIProviders ? (
<ButtonGroup>
{mainButton}
@@ -124,16 +123,8 @@ export function PromptActions(props: { prompt: string; openInAIProviders: boolea
function AgentIconStack() {
return (
<span className="flex items-center">
{AI_AGENTS.map((agent, index) => (
<span
key={agent.id}
className={tcls(
'flex size-4 shrink-0 items-center justify-center rounded-full border border-tint bg-tint-base',
// Each chip's border cuts into the one behind it, so the marks stay legible
// however tightly they are stacked.
index > 0 && '-ms-1.5'
)}
>
{AI_AGENTS.map((agent) => (
<span key={agent.id} className="prompt-agent">
<Icon icon={agent.icon} className="size-2.5" />
</span>
))}
@@ -8,7 +8,7 @@ import { Icon, type IconName } from '@gitbook/icons';
import { PromptActions } from './PromptActions';
import { ToggleChevron } from '@/components/primitives';
import { tString, useLanguage } from '@/intl/client';
import { tcls } from '@/lib/tailwind';
import { cx } from '@/lib/classnames';
type PromptClientProps = DocumentBlockPrompt['data'] & {
contentIcon: IconName | null;
@@ -44,18 +44,13 @@ export function PromptClient(props: PromptClientProps) {
<div
data-block-key={commentKey}
data-comment-block={commentKey ? '' : undefined}
className={tcls(
'relative flex w-full flex-col overflow-hidden circular-corners:rounded-2xl rounded-corners:rounded-xl straight-corners:rounded-xs text-tint-strong',
'border border-tint-subtle contrast-more:border-tint',
'transition',
expanded ? 'bg-tint depth-subtle:shadow-xs' : 'bg-tint-base',
className
)}
className={cx('prompt-block', expanded && 'prompt-block-expanded', className)}
>
<div
className={tcls(
'group/prompt-header relative flex min-h-9 flex-row items-center justify-between gap-4 p-3 transition-colors',
!isPartiallyExpanded && (open ? 'hover:bg-tint-hover' : 'hover:bg-tint-subtle')
className={cx(
// The marker stays for the chevron's `group-hover/prompt-header`.
'group/prompt-header prompt-header',
!isPartiallyExpanded && (open ? 'prompt-header-open' : 'prompt-header-closed')
)}
>
{!isPartiallyExpanded ? (
@@ -64,15 +59,12 @@ export function PromptClient(props: PromptClientProps) {
aria-controls={promptId}
aria-expanded={open}
aria-label={tString(language, 'view')}
className={tcls(
'absolute inset-0 z-10 cursor-pointer outline-hidden',
'focus-visible:ring-2 focus-visible:ring-primary-hover'
)}
className="prompt-toggle"
disabled={!prompt}
onClick={() => setOpen((prev) => !prev)}
/>
) : null}
<div className="pointer-events-none relative z-0 flex min-w-0 flex-row items-center gap-2 text-tint-strong">
<div className="prompt-title">
{!isPartiallyExpanded ? (
<ToggleChevron
open={open}
@@ -86,7 +78,7 @@ export function PromptClient(props: PromptClientProps) {
<PromptActions prompt={prompt} openInAIProviders={openInAIProviders} />
</div>
{isPartiallyExpanded || open ? (
<div id={promptId} className="border-t border-tint-subtle bg-tint-base">
<div id={promptId} className="prompt-body">
{children}
</div>
) : null}
@@ -2,6 +2,7 @@ import type { DocumentBlockQuote } from '@gitbook/api';
import type { BlockProps } from './Block';
import { Blocks } from './Blocks';
import { tcls } from '@/lib/tailwind';
export function Quote(props: BlockProps<DocumentBlockQuote>) {
const { block, style, ancestorBlocks, ...contextProps } = props;
@@ -12,7 +13,8 @@ export function Quote(props: BlockProps<DocumentBlockQuote>) {
tag="blockquote"
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={[style, 'text-tint', 'border-l-2', 'pl-6', 'py-3', 'border-tint', 'space-y-4']}
// Merged here: `text-tint` must beat a hint's `text-neutral-strong` passed in `style`.
style={tcls(style, 'text-tint border-l-2 pl-6 py-3 border-tint space-y-4')}
/>
);
}
@@ -5,6 +5,7 @@ import type { DocumentBlockStepperStep } from '@gitbook/api';
import type { BlockProps } from './Block';
import { Blocks } from './Blocks';
import { getCommentAnchorProps } from './utils';
import { cx } from '@/lib/classnames';
import { tcls } from '@/lib/tailwind';
export function StepperStep(props: BlockProps<DocumentBlockStepperStep>) {
@@ -36,24 +37,19 @@ export function StepperStep(props: BlockProps<DocumentBlockStepperStep>) {
return (
<div
{...getCommentAnchorProps(context, block.key)}
className={tcls('flex flex-row gap-4 md:gap-8', style)}
className={cx('stepper-item', tcls(style))}
>
<div className="relative select-none">
<div
className={tcls(
'can-override-bg can-override-text flex size-[calc(1.75rem+1px)] items-center justify-center rounded-full bg-primary-solid theme-muted:bg-tint-base tabular-nums contrast-more:bg-primary-11',
'font-medium text-contrast-primary-solid theme-muted:text-tint contrast-more:text-contrast-primary-11'
)}
>
<div className="stepper-step-marker">
<div className="can-override-bg can-override-text stepper-step-number">
{index + 1}
</div>
<div className="can-override-bg absolute bottom-2 left-3.5 top-9 w-px bg-primary-7 theme-muted:bg-tint-6" />
<div className="can-override-bg stepper-step-line" />
</div>
<Blocks
{...contextProps}
nodes={block.nodes}
ancestorBlocks={[...ancestorBlocks, block]}
style={['min-w-0 flex-1 pb-6 [&>*+*]:mt-5', marginAdjustClassName]}
style={['stepper-step-body', marginAdjustClassName]}
/>
</div>
);
@@ -7,6 +7,7 @@ import type { TableGridViewProps } from './Table';
import { TableHoverTable } from './TableHoverTable';
import { TableSearchTableBody } from './TableSearch';
import { getColumnAlignment, getColumnVerticalAlignment, type VerticalAlignment } from './utils';
import { cx } from '@/lib/classnames';
import { tcls } from '@/lib/tailwind';
/** Semantic table renderer used when a cell spans multiple records. */
@@ -26,7 +27,7 @@ export function NativeViewGrid(props: TableGridViewProps) {
{...props}
stickyHeader={withStickyHeader}
stickyFirstColumn={withStickyFirstColumn}
className={tcls(
className={cx(
withStickyHeader
? [
'mb-0 border-t border-r border-l',
@@ -50,7 +51,7 @@ export function NativeViewGrid(props: TableGridViewProps) {
if (withStickyHeader || withStickyFirstColumn) {
return (
<StickyViewGrid
className={tcls(style, 'relative mx-auto grid w-full min-w-0')}
className={cx(tcls(style), 'table-view')}
stickyHeader={withStickyHeader}
tableClassName={tableContainerClassName}
withTableRole={false}
@@ -62,9 +63,9 @@ export function NativeViewGrid(props: TableGridViewProps) {
}
return (
<div className={tcls(style, 'relative mx-auto grid w-full min-w-0')}>
<div className="w-full min-w-0 overflow-x-auto overflow-y-hidden overscroll-x-none border-tint-subtle">
<div className={tcls('flex flex-col', tableContainerClassName)}>
<div className={cx(tcls(style), 'table-view')}>
<div className="table-scroll">
<div className={cx('table-stack', tableContainerClassName)}>
{header}
{body}
</div>
@@ -86,13 +87,13 @@ function NativeViewGridHeader(
return (
<div
aria-hidden="true"
className={tcls(
'mb-1 rounded-lg border border-tint-subtle bg-tint',
stickyHeader || !stickyFirstColumn ? 'overflow-hidden' : undefined,
className={cx(
'table-native-header',
(stickyHeader || !stickyFirstColumn) && 'table-header-clip',
className
)}
>
<table className="w-full table-fixed border-separate border-spacing-0">
<table className="table-native">
<NativeViewGridColumns {...props} />
<thead>
<tr>
@@ -108,12 +109,12 @@ function NativeViewGridHeader(
<th
key={column}
scope="col"
className={tcls(
'relative px-3 py-2 font-medium text-sm text-tint-strong',
className={cx(
'table-header-cell',
isStickyFirstColumn
? stickyHeader
? 'z-20 bg-tint'
: 'sticky left-0 z-20 bg-tint'
? 'table-header-cell-pinned'
: 'table-header-cell-sticky'
: undefined,
getColumnAlignment(definition)
)}
@@ -149,14 +150,7 @@ function NativeViewGridBody(
const recordIndexes = new Map(records.map((record, index) => [record[0], index] as const));
return (
<TableHoverTable
className={tcls(
'w-full table-fixed border-separate border-spacing-0',
'[&>tbody>tr>td[data-table-hovered]]:bg-tint-hover',
'[&>tbody>tr+tr>td]:border-t',
'[&>tbody+tbody>tr:first-child>td]:border-t'
)}
>
<TableHoverTable className="table-native table-native-body">
<NativeViewGridColumns {...props} />
{withHeader ? (
<thead className="sr-only">
@@ -225,15 +219,11 @@ function NativeViewGridBody(
data-table-row-end={
recordIndex + (cellMerge?.merge.rowSpan ?? 1) - 1
}
className={tcls(
'relative px-3 py-2 text-sm transition-colors',
!isLastColumn
? 'border-tint-subtle border-r'
: undefined,
className={cx(
'table-native-cell',
!isLastColumn && 'table-native-cell-divider',
getNativeCellVerticalAlignment(verticalAlignment),
isStickyFirstColumn
? 'sticky left-0 z-10 bg-tint-base'
: undefined
isStickyFirstColumn && 'table-native-cell-sticky'
)}
>
<RecordColumnValue
@@ -7,13 +7,12 @@ import {
import { isRecordColumnEmpty } from './isRecordColumnEmpty';
import { RecordColumnValue } from './RecordColumnValue';
import { RecordCardStyles } from './styles';
import type { TableRecordKV, TableViewProps } from './Table';
import { getRecordCardCovers } from './utils';
import { LinkBox, LinkOverlay } from '@/components/primitives';
import { Image } from '@/components/utils';
import { cx } from '@/lib/classnames';
import { type ResolvedContentRef, resolveContentRefInDocument } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
export async function RecordCard(
props: TableViewProps<DocumentTableViewCards> & {
@@ -57,36 +56,14 @@ export async function RecordCard(
// Marks the card body so overflow-clipped affordances (e.g. the paragraph "Ask"
// button) can opt out of rendering inside it.
data-card=""
className={tcls(
'grid-area-1-1',
'relative',
'grid',
'bg-tint-base',
'w-[calc(100%+2px)]',
'h-[calc(100%+2px)]',
'-inset-px',
'rounded-sm',
'straight-corners:rounded-none',
'circular-corners:rounded-xl',
'overflow-hidden',
'[&_.heading>div:first-child]:hidden',
'[&_.heading>div]:text-[.8em]',
'@xl:[&_.heading>div]:text-[1em]',
'[&_.blocks:first-child_.heading]:pt-0', // Remove padding-top on first heading in card
// On mobile, check if we can display the cover responsively or not:
// - If the file has a landscape aspect ratio, we display it normally
// - If the file is square or portrait, we display it left with 40% of the card width
className={cx(
'record-card-body',
lightCoverIsSquareOrPortrait || darkCoverIsSquareOrPortrait
? [
lightCoverIsSquareOrPortrait
? '@sm:grid-cols-none grid-cols-[40%__1fr] @sm:grid-rows-[auto_1fr]'
: '',
darkCoverIsSquareOrPortrait
? 'dark:@sm:grid-cols-none dark:grid-cols-[40%__1fr] dark:@sm:grid-rows-[auto_1fr]'
: '',
].filter(Boolean)
: 'grid-rows-[auto_1fr]'
lightCoverIsSquareOrPortrait && 'record-card-body-portrait',
darkCoverIsSquareOrPortrait && 'record-card-body-portrait-dark',
]
: 'record-card-body-landscape'
)}
>
{lightCover ? (
@@ -116,37 +93,20 @@ export async function RecordCard(
},
]}
resize={context.contentContext?.imageResizer}
className={tcls(
'min-w-0',
'w-full',
'h-full',
'bg-tint-subtle',
className={cx(
'record-card-cover',
lightCoverIsSquareOrPortrait || darkCoverIsSquareOrPortrait
? [
lightCoverIsSquareOrPortrait ? '@sm:aspect-video @sm:h-auto' : '',
darkCoverIsSquareOrPortrait
? 'dark:@sm:aspect-video dark:@sm:h-auto'
: '',
].filter(Boolean)
: ['h-auto', 'aspect-video'],
lightCoverIsSquareOrPortrait && 'record-card-cover-portrait',
darkCoverIsSquareOrPortrait && 'record-card-cover-portrait-dark',
]
: 'record-card-cover-landscape',
objectFits
)}
loading={isOffscreen && context.mode !== 'print' ? 'lazy' : 'eager'}
/>
) : null}
<div
className={tcls(
'min-w-0',
'w-full',
'flex',
'flex-col',
'place-self-start',
'gap-3',
'p-4',
'text-sm',
'text-tint-strong'
)}
>
<div className="record-card-content">
{view.columns.map((column) => {
const definition = block.data.definition[column];
@@ -163,8 +123,8 @@ export async function RecordCard(
if (!view.hideColumnTitle && definition.title) {
const ariaLabelledBy = `${block.key}-${column}-title`;
return (
<div key={column} className="flex flex-col gap-1">
<div id={ariaLabelledBy} className="text-sm text-tint">
<div key={column} className="record-card-field">
<div id={ariaLabelledBy} className="record-card-field-title">
{definition.title}
</div>
<RecordColumnValue
@@ -203,7 +163,7 @@ export async function RecordCard(
);
}
return <div className={tcls(RecordCardStyles)}>{body}</div>;
return <div className="record-card">{body}</div>;
}
/**
@@ -22,10 +22,10 @@ import {
import { Checkbox } from '@/components/primitives';
import { StyledLink } from '@/components/primitives';
import { Image } from '@/components/utils';
import { cx } from '@/lib/classnames';
import { getNodeFragmentByName } from '@/lib/document';
import { getSimplifiedContentType } from '@/lib/files';
import { resolveContentRefInDocument } from '@/lib/references';
import { tcls } from '@/lib/tailwind';
import { filterOutNullable } from '@/lib/typescript';
const alignmentMap: Record<'text-left' | 'text-center' | 'text-right', string> = {
@@ -75,7 +75,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
}
return (
<Checkbox
className={tcls('w-5', 'h-5')}
className="h-5 w-5"
checked={value}
disabled={true}
aria-labelledby={ariaLabelledBy}
@@ -90,16 +90,12 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
const max = definition.max;
return (
<Tag className={tcls('inline-grid')}>
<Tag className="record-rating">
{value ? (
<>
<span className={tcls('inline-flex', 'grid-area-1-1', 'gap-0.5')}>
<span className="record-rating-stars">
{Array.from({ length: max }).map((_, i) => (
<Icon
key={i}
icon="star"
className={tcls('size-[15px]', 'text-primary/5')}
/>
<Icon key={i} icon="star" className="record-rating-star" />
))}
</span>
<span
@@ -109,14 +105,14 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
aria-valuenow={rating}
aria-valuemin={1}
aria-valuemax={definition.max}
className={tcls('inline-flex', 'grid-area-1-1', 'gap-0.5')}
className="record-rating-stars"
>
{Array.from({ length: rating }).map((_, i) => (
<Icon
key={i}
icon="star"
iconStyle={IconStyle.SharpSolid}
className={tcls('size-[15px]', 'text-primary')}
className="record-rating-star-filled"
/>
))}
</span>
@@ -130,10 +126,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
return null;
}
return (
<Tag
className={tcls('text-base', 'tabular-nums', 'tracking-tighter')}
aria-labelledby={ariaLabelledBy}
>{`${value}`}</Tag>
<Tag className="record-number" aria-labelledby={ariaLabelledBy}>{`${value}`}</Tag>
);
}
case 'text': {
@@ -142,7 +135,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
}
const fragment = getNodeFragmentByName(block, value);
if (!fragment) {
return <Tag className={tcls(['w-full', verticalAlignment])}>{''}</Tag>;
return <Tag className={cx('w-full', verticalAlignment)}>{''}</Tag>;
}
const horizontalAlignment = getColumnAlignment(definition);
@@ -154,15 +147,8 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
document={document}
ancestorBlocks={[...ancestorBlocks, block]}
nodes={fragment.nodes}
style={[
'blocks',
'w-full',
'space-y-2',
'lg:space-y-3',
'leading-normal',
verticalAlignment,
horizontalClasses,
]}
// Alignment stays as utilities: they must beat the alignment set by the blocks inside.
style={['blocks record-text', verticalAlignment, horizontalClasses]}
context={context}
blockStyle={['w-full', 'max-w-[unset]']}
wrapperProps={{
@@ -191,7 +177,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
);
return (
<Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}>
<Tag className="text-base" aria-labelledby={ariaLabelledBy}>
{files.filter(filterOutNullable).map((ref, index) => {
const contentType = ref.file
? getSimplifiedContentType(ref.file.contentType)
@@ -201,7 +187,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
<StyledLink
key={index}
href={ref.href}
className="flex flex-row items-center gap-2"
className="record-file-link"
insights={
ref.file
? {
@@ -235,10 +221,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
loading={context.mode === 'print' ? 'eager' : 'lazy'}
/>
) : (
<FileIcon
contentType={contentType}
className={tcls('size-4')}
/>
<FileIcon contentType={contentType} className="size-4" />
)}
{ref.text}
</StyledLink>
@@ -259,10 +242,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
})
: null;
return (
<Tag
className={tcls('text-base', 'text-balance', 'flex', 'items-center')}
aria-labelledby={ariaLabelledBy}
>
<Tag className="record-ref" aria-labelledby={ariaLabelledBy}>
{resolved?.icon ?? null}
{resolved ? (
<StyledLink
@@ -311,7 +291,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
);
return (
<Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}>
<Tag className="text-base" aria-labelledby={ariaLabelledBy}>
{resolved.filter(filterOutNullable).map(([contentRef, resolved], index) => (
<StyledLink
key={index}
@@ -336,7 +316,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
}
return (
<Tag aria-labelledby={ariaLabelledBy}>
<span className={tcls('inline-flex', 'gap-2', 'flex-wrap')}>
<span className="record-select">
{value.map((selectId) => {
const option = definition.options.find(
(option) => option.value === selectId
@@ -347,18 +327,7 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
}
return (
<span
key={option.value}
className={tcls(
'text-sm',
'whitespace-pre',
'rounded-sm',
'py-1',
'px-2',
'bg-primary',
'text-primary-strong'
)}
>
<span key={option.value} className="record-select-option">
{option.label}
</span>
);
@@ -385,10 +354,10 @@ export async function RecordColumnValue<Tag extends React.ElementType = 'div'>(
}
return (
<Tag className={tcls('text-base')} aria-labelledby={ariaLabelledBy}>
<Tag className="text-base" aria-labelledby={ariaLabelledBy}>
<StyledLink
href={image.href}
className="flex flex-row items-center gap-2"
className="record-file-link"
insights={
image.file
? {
@@ -6,7 +6,7 @@ import type { TableGridViewProps, TableRecordKV } from './Table';
import { TableSearchRecord } from './TableSearch';
import './styles.css';
import { getColumnVerticalAlignment } from './utils';
import { tcls } from '@/lib/tailwind';
import { cx } from '@/lib/classnames';
export function RecordRow(
props: TableGridViewProps & {
@@ -24,7 +24,7 @@ export function RecordRow(
role="row"
recordId={record[0]}
visibleClassName="flex"
className={tcls('group/row', 'table-grid-row')}
className="table-grid-row"
>
{view.columns.map((column) => {
const cellMerge = getTableCellMerge(cellMergeLayout, record[0], column);
@@ -53,7 +53,7 @@ export function RecordRow(
role="cell"
{...getCommentCellProps(context, record[0], column)}
aria-colspan={cellMerge?.merge.colSpan}
className={tcls(
className={cx(
'table-grid-cell',
isStickyFirstColumnCell ? 'table-grid-cell-sticky' : undefined
)}
@@ -2,7 +2,7 @@
import { type ReactNode, useCallback, useEffect, useLayoutEffect, useRef } from 'react';
import { useScrollListener } from '@/components/hooks/useScrollListener';
import { tcls } from '@/lib/tailwind';
import { cx } from '@/lib/classnames';
interface StickyViewGridProps {
className?: string;
@@ -31,12 +31,9 @@ function DefaultHeaderScrollGrid({
return (
<div className={className}>
<div
role={withTableRole ? 'table' : undefined}
className="group/table relative flex w-full min-w-0 max-w-full flex-col rounded-lg border-tint-subtle"
>
<div className="w-full min-w-0 overflow-x-auto overflow-y-hidden overscroll-x-none border-tint-subtle">
<div className={tcls('flex', 'flex-col', resolvedTableClassName)}>
<div role={withTableRole ? 'table' : undefined} className="group/table table-sticky">
<div className="table-scroll">
<div className={cx('table-stack', resolvedTableClassName)}>
{header}
{children}
</div>
@@ -142,27 +139,14 @@ function StickyHeaderOverlayScrollGrid({
<div className={className}>
<div
ref={rootRef}
className="group/table relative flex w-full min-w-0 max-w-full flex-col rounded-lg border-tint-subtle data-[scrollable=true]:border"
className="group/table table-sticky"
data-scrollable="false"
role={withTableRole ? 'table' : undefined}
>
{header ? (
<div
ref={stickyHeaderRef}
className={tcls(
'sticky z-20 w-full min-w-0 max-w-full overflow-hidden rounded-t-[inherit]',
'[top:var(--toc-top-offset,var(--outline-top-offset,0px))]'
)}
>
<div ref={stickyHeaderRef} className="table-sticky-header">
<div
className={tcls(
'flex',
'flex-col',
resolvedTableClassName,
// The sticky header is rendered outside the scroll container, so it
// needs to mirror the body's horizontal scroll position.
'[transform:translateX(var(--table-sticky-scroll-left,0px))]'
)}
className={cx('table-sticky-header-track', resolvedTableClassName)}
style={{ width: 'var(--table-sticky-table-width)' }}
>
{header}
@@ -170,14 +154,8 @@ function StickyHeaderOverlayScrollGrid({
</div>
) : null}
<div
ref={bodyScrollRef}
className="w-full min-w-0 overflow-x-auto overflow-y-hidden overscroll-x-none border-tint-subtle group-data-[scrollable=true]/table:mx-px group-data-[scrollable=true]/table:rounded-none group-data-[scrollable=true]/table:border-0"
>
<div
ref={bodyTableRef}
className={tcls('flex', 'flex-col', resolvedTableClassName)}
>
<div ref={bodyScrollRef} className="table-scroll table-sticky-scroll">
<div ref={bodyTableRef} className={cx('table-stack', resolvedTableClassName)}>
{children}
</div>
</div>
@@ -23,6 +23,7 @@ import {
} from './TableSearch';
import { ViewCards } from './ViewCards';
import { ViewGrid, ViewGridHeader } from './ViewGrid';
import { cx } from '@/lib/classnames';
import { tcls } from '@/lib/tailwind';
export type { TableRecordKV };
@@ -78,7 +79,7 @@ export function Table(props: BlockProps<DocumentBlockTable>) {
{...getCommentAnchorProps(context, block.key)}
// Owns clicks inside, e.g. on blocks of a record's own document; cells still win.
{...getCommentMarkerProps(context, 'data-comment-block')}
className={tcls(style, 'flex flex-col gap-3')}
className={cx(tcls(style), 'table-block')}
>
{showSearch ? (
<TableSearchInput
@@ -155,7 +156,7 @@ function TableView({
if (withStickyHeader || withStickyFirstColumn) {
return (
<StickyViewGrid
className={tcls(style, 'relative mx-auto grid w-full min-w-0')}
className={cx(tcls(style), 'table-view')}
stickyHeader={withStickyHeader}
tableClassName={tableContainerClassName}
header={
@@ -163,7 +164,7 @@ function TableView({
<ViewGridHeader
{...gridProps}
tableClassName={tableContainerClassName}
className={tcls(
className={cx(
withStickyHeader
? [
'mb-0 border-t border-r border-l',
@@ -184,21 +185,13 @@ function TableView({
}
return (
<div className={tcls(style, 'relative mx-auto grid w-full min-w-0')}>
<div
className={tcls(
'w-full min-w-0 overflow-x-auto overflow-y-hidden overscroll-x-none border-tint-subtle '
)}
>
<div
className={tcls('flex', 'flex-col', tableContainerClassName)}
role="table"
>
<div className={cx(tcls(style), 'table-view')}>
<div className="table-scroll">
<div className={cx('table-stack', tableContainerClassName)} role="table">
{withHeader ? (
<ViewGridHeader
{...gridProps}
tableClassName={tableContainerClassName}
className={tableContainerClassName}
/>
) : null}
<ViewGrid {...gridProps} tableClassName={tableContainerClassName} />
@@ -12,13 +12,7 @@ mock.module('./RecordCard', () => ({
}));
mock.module('./TableSearch', () => ({
TableSearchRecord: ({
children,
visibleClassName,
}: {
children: React.ReactNode;
visibleClassName: string;
}) => <div className={visibleClassName}>{children}</div>,
TableSearchRecord: ({ children }: { children: React.ReactNode }) => <>{children}</>,
}));
const { ViewCards } = await import('./ViewCards');
@@ -53,47 +47,18 @@ describe('ViewCards', () => {
expect(markup).toContain('-mx-4 sm:-mx-6 md:-mx-8 2xl:-mx-12');
expect(markup).toContain('scroll-px-4');
expect(markup).toContain('2xl:scroll-px-12');
expect(markup).toContain('left-0');
expect(markup).toContain('scroll-container-prev-x');
expect(markup).toContain('2xl:ml-8');
expect(markup).toContain('right-0');
expect(markup).toContain('scroll-container-next-x');
expect(markup).toContain('2xl:mr-8');
expect(markup).not.toContain('before:bg-linear-to-r');
expect(markup).not.toContain('after:bg-linear-to-l');
expect(markup).toContain('snap-mandatory');
});
it.each([true, undefined])('renders the wrapping grid with wrap=%s', (wrap) => {
const props = makeProps(true);
props.view.wrap = wrap;
const markup = renderWithContext(<ViewCards {...props} />);
it('renders the wrapping grid by default', () => {
const markup = renderWithContext(<ViewCards {...makeProps(true)} />);
expect(markup).toContain('inline-grid');
});
it('renders small cards in four columns and uses the grid for print', () => {
const props = makeProps(true);
props.view.cardSize = 'small';
expect(renderWithContext(<ViewCards {...props} />)).toContain('@3xl:grid-cols-4');
props.view.wrap = false;
const carousel = renderWithContext(<ViewCards {...props} />);
expect(carousel).toContain('@3xl:w-[calc(22.5%-0.75rem)]');
expect(carousel).toContain('@5xl:w-[calc(25%-0.75rem)]');
props.context.mode = 'print';
const printed = renderWithContext(<ViewCards {...props} />);
expect(printed).toContain('@3xl:grid-cols-4');
expect(printed).not.toContain('snap-mandatory');
});
it.each([
['medium', '@2xl:grid-cols-3 @sm:grid-cols-2', '@5xl:w-[calc(33.33%-0.66rem)]'],
['large', '@xl:grid-cols-2', '@5xl:w-[calc(50%-0.5rem)]'],
['unknown', '@2xl:grid-cols-3 @sm:grid-cols-2', '@5xl:w-[calc(33.33%-0.66rem)]'],
])('preserves %s card layouts', (cardSize, grid, carousel) => {
const props = makeProps(true);
props.view.cardSize = cardSize;
expect(renderWithContext(<ViewCards {...props} />)).toContain(grid);
props.view.wrap = false;
expect(renderWithContext(<ViewCards {...props} />)).toContain(carousel);
expect(markup).toContain('record-cards');
});
});
@@ -4,20 +4,9 @@ import { RecordCard } from './RecordCard';
import type { TableViewProps } from './Table';
import { TableSearchRecord } from './TableSearch';
import { ScrollContainer } from '@/components/primitives/ScrollContainer';
import { cx } from '@/lib/classnames';
import { tcls } from '@/lib/tailwind';
const gridColumns = {
small: '@sm:grid-cols-2 @2xl:grid-cols-3 @3xl:grid-cols-4',
medium: '@2xl:grid-cols-3 @sm:grid-cols-2',
large: '@xl:grid-cols-2',
};
const carouselWidths = {
small: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @xl:w-[calc(30%-0.66rem)] @3xl:w-[calc(22.5%-0.75rem)] @5xl:w-[calc(25%-0.75rem)]',
medium: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @xl:w-[calc(30%-0.66rem)] @5xl:w-[calc(33.33%-0.66rem)]',
large: 'w-[90%] @sm:w-[calc(45%-0.5rem)] @5xl:w-[calc(50%-0.5rem)]',
};
export function ViewCards(props: TableViewProps<DocumentTableViewCards>) {
// `wrap` defaults to `true` (a wrapping grid); only an explicit `false` opts into the
// horizontally-scrolling carousel row. Fall back to the grid in print mode: a PDF can't
@@ -37,12 +26,10 @@ function CardsGrid(props: TableViewProps<DocumentTableViewCards>) {
return (
<div
className={tcls(
style,
'inline-grid',
'gap-4',
'grid-cols-1',
gridColumns[view.cardSize] ?? gridColumns.medium,
className={cx(
tcls(style),
'record-cards',
view.cardSize === 'large' ? 'record-cards-large' : 'record-cards-medium',
block.data.fullWidth ? 'large:flex-column' : null
)}
>
@@ -82,6 +69,11 @@ const PEEK = {
function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
const { view, records } = props;
const itemClassName = cx(
'record-carousel-item',
view.cardSize === 'large' ? 'record-carousel-item-large' : 'record-carousel-item-medium'
);
return (
<ScrollContainer
orientation="horizontal"
@@ -113,15 +105,7 @@ function CardsCarousel(props: TableViewProps<DocumentTableViewCards>) {
<TableSearchRecord
key={record[0]}
recordId={record[0]}
// `grid grid-cols-1` stretches the card to fill the fixed-width,
// equal-height track; `snap-start` aligns it to the left edge.
visibleClassName={tcls(
'grid',
'grid-cols-1',
'shrink-0',
'snap-start',
carouselWidths[view.cardSize] ?? carouselWidths.medium
)}
visibleClassName={itemClassName}
>
<RecordCard {...props} record={record} />
</TableSearchRecord>
@@ -2,7 +2,7 @@ import { getColumnWidth, getViewGridLayout } from './layout';
import { RecordRow } from './RecordRow';
import type { TableGridViewProps } from './Table';
import { getColumnAlignment } from './utils';
import { tcls } from '@/lib/tailwind';
import { cx } from '@/lib/classnames';
interface ViewGridHeaderProps extends TableGridViewProps {
className?: string;
@@ -27,14 +27,14 @@ export function ViewGridHeader(props: ViewGridHeaderProps) {
return (
<div
role="rowgroup"
className={tcls(
className={cx(
tableClassName ?? tableWidth,
'mb-1 flex flex-col rounded-lg border border-tint-subtle bg-tint',
withStickyHeader || !stickyFirstColumn ? 'overflow-hidden' : undefined,
'table-grid-header',
(withStickyHeader || !stickyFirstColumn) && 'table-header-clip',
className
)}
>
<div role="row" className={tcls('flex', 'w-full')}>
<div role="row" className="table-grid-header-row">
{view.columns.map((column) => {
const definition = block.data.definition[column];
if (!definition) {
@@ -45,12 +45,12 @@ export function ViewGridHeader(props: ViewGridHeaderProps) {
<div
key={column}
role="columnheader"
className={tcls(
'relative px-3 py-2 font-medium text-sm text-tint-strong',
className={cx(
'table-header-cell',
stickyFirstColumn && column === firstVisibleColumn
? withStickyHeader
? 'z-20 bg-tint'
: 'sticky left-0 z-20 bg-tint'
? 'table-header-cell-pinned'
: 'table-header-cell-sticky'
: undefined,
getColumnAlignment(definition)
)}
@@ -89,10 +89,7 @@ export function ViewGrid(props: ViewGridProps) {
});
const body = (
<div
role="rowgroup"
className={tcls('flex', 'flex-col', tableClassName ?? tableWidth, '[&>*+*]:border-t')}
>
<div role="rowgroup" className={cx('table-grid-body', tableClassName ?? tableWidth)}>
{records.map((record) => (
<RecordRow
key={record[0]}
@@ -105,5 +102,5 @@ export function ViewGrid(props: ViewGridProps) {
</div>
);
return <div className={tcls('flex', 'flex-col', tableClassName ?? tableWidth)}>{body}</div>;
return <div className={cx('table-stack', tableClassName ?? tableWidth)}>{body}</div>;
}
@@ -23,6 +23,12 @@
}
.table-grid-cell-sticky {
@apply sticky left-0 z-10 bg-tint-base group-hover/row:bg-tint-hover;
@apply sticky left-0 z-10 bg-tint-base;
@media (hover: hover) {
.table-grid-row:hover > & {
@apply bg-tint-hover;
}
}
}
}
@@ -1,26 +0,0 @@
import type { ClassValue } from '@/lib/tailwind';
export const RecordCardStyles = [
'group',
'grid',
'shadow-1xs',
'shadow-tint-9/1',
'depth-flat:shadow-none',
'rounded-sm',
'straight-corners:rounded-none',
'circular-corners:rounded-xl',
'dark:shadow-transparent',
'before:pointer-events-none',
'before:grid-area-1-1',
'before:transition-shadow',
'before:w-full',
'before:h-full',
'before:rounded-[inherit]',
'before:ring-1',
'before:ring-tint-12/2',
'before:z-10',
'before:relative',
] as ClassValue;
export const RecordCardLinkStyles = ['hover:before:ring-primary-hover'] as ClassValue;

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