The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(docs): extracts code block component (#51661)
Anthony Lio8bcbe3dcc705
diff --git a/apps/design-system/app/(app)/docs/[[...slug]]/page.tsx b/apps/design-system/app/(app)/docs/[[...slug]]/page.tsxindex 0e59e898eb7..2cbe39f0589 100644--- a/apps/design-system/app/(app)/docs/[[...slug]]/page.tsx+++ b/apps/design-system/app/(app)/docs/[[...slug]]/page.tsx@@ -8,7 +8,6 @@ import { getTableOfContents } from '@/lib/toc'import { absoluteUrl } from '@/lib/utils'/* eslint-disable turbo/no-undeclared-env-vars */-import '@/styles/code-block-variables.css'import '@/styles/mdx.css'import { ChevronRight } from 'lucide-react'diff --git a/apps/design-system/config/docs.ts b/apps/design-system/config/docs.tsindex c8520fd3650..a65ac0b9049 100644--- a/apps/design-system/config/docs.ts+++ b/apps/design-system/config/docs.ts@@ -127,6 +127,11 @@ export const docsConfig: DocsConfig = {href: '/docs/fragments/admonition',items: [],},+ {+ title: 'Code Block',+ href: '/docs/fragments/code-block',+ items: [],+ },{title: 'Collapsible Card Section',href: '/docs/fragments/collapsible-card-section',diff --git a/apps/design-system/content/docs/fragments/code-block.mdx b/apps/design-system/content/docs/fragments/code-block.mdxnew file mode 100644index 00000000000..cc996ccae07--- /dev/null+++ b/apps/design-system/content/docs/fragments/code-block.mdx@@ -0,0 +1,93 @@+---+title: Code Block+description: Shows highlighted code with line numbers, a copy button, and a wrap button.+fragment: true+---++Code Block is the frame for code samples in the documentation and in knowledge base articles. The frame and the highlighted code render as static HTML. Users can see the code before JavaScript loads. The copy button and the wrap button are optional. They operate in the browser.++<ComponentPreview name="code-block-demo" peekCode wide />++## Without line numbers++For short code samples, such as a single command, set `lineNumbers={false}`.++Add `controls` only for code that users copy.++<ComponentPreview name="code-block-plain" peekCode />++## Annotations++A token can have annotations that show when you hold the pointer over it. For example, Twoslash supplies type information. Put the annotations in the third item of the token: `[content, className, annotations]`.++## Setup++### Highlight the code++```tsx+import { highlightCode } from 'ui-patterns/CodeBlock/CodeBlock.highlight'+import { getTokenClassName } from 'ui-patterns/CodeBlock/CodeBlock.tokens'+import { CodeBlockControls } from 'ui-patterns/CodeBlock/CodeBlockControls'+import { CodeBlockFrame, CodeBlockTokens } from 'ui-patterns/CodeBlock/CodeBlockFrame'+```++```tsx+const { tokens } = await highlightCode(code, 'ts')++<CodeBlockFrame+ lang="ts"+ lineCount={tokens.length}+ controls={<CodeBlockControls content={code} />}+>+ <CodeBlockTokens+ lineNumbers+ lines={tokens.map((line) =>+ line.map(({ content, color, fontStyle }) => [content, getTokenClassName(color, fontStyle)])+ )}+ />+</CodeBlockFrame>+```++Use `highlightCode` in a server component or during the build. It loads Shiki one time and uses it again for all other blocks. Do not import `highlightCode` into a client component.++`getTokenClassName` changes each Shiki color into a short class name, for example `s-k` for keywords. The token colors are CSS variables. When the theme changes between light and dark, the colors also change.++### Add the styles++Import the Code Block stylesheet one time. Put the import after the Tailwind config:++```css+@import 'config/tailwind.config.css';+@import 'ui-patterns/CodeBlock/code-block.css';+```++This stylesheet contains these styles:++- The line number gutter+- The token colors for the light theme and the dark theme+- The word wrap mode+- The space around code blocks in `prose` content++### Give the copy text++`CodeBlockControls` copies the `content` string. Give the source code that users can run. Do not give the rendered text, because it contains the line numbers and the annotations.++The button shows a check mark only after the clipboard write is successful. Then, screen readers announce "Code copied".++## Guidelines++### When to use++Use Code Block for code that users copy or read line by line, for example a setup step or a function.++Use inline `code` for a single name or value in a sentence.++For Studio and other app screens, use the `CodeBlock` component from `ui-patterns/CodeBlock`.++### Always set the language++Always set `lang` to the language of the code. `highlightCode` uses the language to color the tokens. The frame uses it to name the block for screen readers, for example "JavaScript, 3 lines".++### Keep the code runnable++Give code that users can run without changes. Do not use pseudo-code, and do not put a `$` prompt before shell commands.diff --git a/apps/design-system/registry/default/example/code-block-demo.tsx b/apps/design-system/registry/default/example/code-block-demo.tsxnew file mode 100644index 00000000000..ffe1714c493--- /dev/null+++ b/apps/design-system/registry/default/example/code-block-demo.tsx@@ -0,0 +1,68 @@+import { CodeBlockControls } from 'ui-patterns/CodeBlock/CodeBlockControls'+import {+ CodeBlockFrame,+ CodeBlockTokens,+ type CodeToken,+} from 'ui-patterns/CodeBlock/CodeBlockFrame'++// apps make these tokens with highlightCode and getTokenClassName, on the server or at build time+const LINES: Array<Array<CodeToken>> = [+ [+ ['import', 's-k'],+ [' { ', 's-p'],+ [+ 'createClient',+ 's-v',+ [{ text: 'function createClient(supabaseUrl: string, supabaseKey: string): SupabaseClient' }],+ ],+ [' } ', 's-p'],+ ['from', 's-k'],+ [' ', 's-f'],+ ["'@supabase/supabase-js'", 's-s'],+ ],+ [],+ [+ ['const', 's-k'],+ [' supabase ', 's-v'],+ ['=', 's-k'],+ [' ', 's-f'],+ ['createClient', 's-u'],+ ['(', 's-p'],+ ["'https://your-project-id.supabase.co'", 's-s'],+ [', ', 's-p'],+ ["'sb_publishable_...'", 's-s'],+ [')', 's-p'],+ ],+ [+ ['const', 's-k'],+ [' { ', 's-p'],+ ['data', 's-v'],+ [' } ', 's-p'],+ ['=', 's-k'],+ [' ', 's-f'],+ ['await', 's-k'],+ [' supabase', 's-v'],+ ['.', 's-p'],+ ['from', 's-u'],+ ['(', 's-p'],+ ["'countries'", 's-s'],+ [')', 's-p'],+ ['.', 's-p'],+ ['select', 's-u'],+ ['()', 's-p'],+ ],+]++const SOURCE = LINES.map((line) => line.map(([content]) => content).join('')).join('\n')++export default function CodeBlockDemo() {+ return (+ <CodeBlockFrame+ lang="ts"+ lineCount={LINES.length}+ controls={<CodeBlockControls content={SOURCE} />}+ >+ <CodeBlockTokens lineNumbers lines={LINES} />+ </CodeBlockFrame>+ )+}diff --git a/apps/design-system/registry/default/example/code-block-plain.tsx b/apps/design-system/registry/default/example/code-block-plain.tsxnew file mode 100644index 00000000000..8461e688a44--- /dev/null+++ b/apps/design-system/registry/default/example/code-block-plain.tsx@@ -0,0 +1,21 @@+import {+ CodeBlockFrame,+ CodeBlockTokens,+ type CodeToken,+} from 'ui-patterns/CodeBlock/CodeBlockFrame'++const LINES: Array<Array<CodeToken>> = [+ [+ ['npx', 's-u'],+ [' supabase ', 's-f'],+ ['init', 's-f'],+ ],+]++export default function CodeBlockPlain() {+ return (+ <CodeBlockFrame lang="sh" lineCount={LINES.length}>+ <CodeBlockTokens lineNumbers={false} lines={LINES} />+ </CodeBlockFrame>+ )+}diff --git a/apps/design-system/registry/examples.ts b/apps/design-system/registry/examples.tsindex 5092143650a..f929cd1705a 100644--- a/apps/design-system/registry/examples.ts+++ b/apps/design-system/registry/examples.ts@@ -67,6 +67,16 @@ export const examples: Registry = [registryDependencies: ['alert'],files: ['example/alert-demo.tsx'],},+ {+ name: 'code-block-demo',+ type: 'components:example',+ files: ['example/code-block-demo.tsx'],+ },+ {+ name: 'code-block-plain',+ type: 'components:example',+ files: ['example/code-block-plain.tsx'],+ },{name: 'collapsible-card-section-demo',type: 'components:example',diff --git a/apps/design-system/styles/globals.css b/apps/design-system/styles/globals.cssindex 2ea0813854f..2855205b0d5 100644--- a/apps/design-system/styles/globals.css+++ b/apps/design-system/styles/globals.css@@ -1,6 +1,7 @@@import 'config/tailwind.config.css';@import 'config/inline-code.css';@import 'config/typography.css';+@import 'ui-patterns/CodeBlock/code-block.css';@source '../app/**/*.{js,ts,jsx,tsx}';@source '../components/**/*.{js,ts,jsx,tsx}';diff --git a/apps/docs/.github/eslint-rule-baselines.json b/apps/docs/.github/eslint-rule-baselines.jsonindex 60d38d360f9..0cdad1f2a1e 100644--- a/apps/docs/.github/eslint-rule-baselines.json+++ b/apps/docs/.github/eslint-rule-baselines.json@@ -13,7 +13,6 @@"features/docs/Reference.sections.tsx": 4,"features/docs/Reference.ui.tsx": 4,"features/ui/AgentWatchSchedule.tsx": 2,- "features/ui/CodeBlock/CodeBlock.client.tsx": 7,"features/ui/PromptPanel.tsx": 3},"shadcn/no-unknown-classes": {diff --git a/apps/docs/content/guides/auth/auth-hooks.mdx b/apps/docs/content/guides/auth/auth-hooks.mdxindex 327d87456d1..01e03da8722 100644--- a/apps/docs/content/guides/auth/auth-hooks.mdx+++ b/apps/docs/content/guides/auth/auth-hooks.mdx@@ -105,7 +105,7 @@ When an HTTP hook is created, the secret generated should be of the `v1,whsec_<bThe secret is used to verify the payload received in your hook. Create an entry in your `.env.local` file to store the `<standard-base64-secret>` portion of the secret for each hook that you have. For example:-```ini+```dotenvSEND_SMS_HOOK_SECRETS=v1,whsec_<base64-secret>```@@ -251,7 +251,7 @@ secrets = "env(SEND_SMS_HOOK_SECRETS)"Fill in the Hook Secret in `supabase/functions/.env`-```ini+```dotenvSEND_SMS_HOOK_SECRETS='v1,whsec_<base64-secret>'```diff --git a/apps/docs/content/guides/auth/auth-hooks/before-user-created-hook.mdx b/apps/docs/content/guides/auth/auth-hooks/before-user-created-hook.mdxindex 5d9b56bcbef..395591cab8f 100644--- a/apps/docs/content/guides/auth/auth-hooks/before-user-created-hook.mdx+++ b/apps/docs/content/guides/auth/auth-hooks/before-user-created-hook.mdx@@ -463,7 +463,7 @@ The `before-user-created` hook solves this by:Create a `.env` file with the following environment variables:-```ini+```dotenvBEFORE_USER_CREATED_HOOK_SECRET="v1,whsec_<base64_secret>"```@@ -538,7 +538,7 @@ The `before-user-created` hook solves this by:Create a `.env` file with the following environment variables:-```ini+```dotenvBEFORE_USER_CREATED_HOOK_SECRET="v1,whsec_<base64_secret>"```@@ -697,7 +697,7 @@ revoke executeCreate a `.env` file with the following environment variables:-```ini+```dotenvBEFORE_USER_CREATED_HOOK_SECRET="v1,whsec_<base64_secret>"```diff --git a/apps/docs/content/guides/auth/auth-hooks/send-email-hook.mdx b/apps/docs/content/guides/auth/auth-hooks/send-email-hook.mdxindex 070ded918cc..3c50e8bc242 100644--- a/apps/docs/content/guides/auth/auth-hooks/send-email-hook.mdx+++ b/apps/docs/content/guides/auth/auth-hooks/send-email-hook.mdx@@ -542,7 +542,7 @@ If you want to send emails through the Supabase Resend integration, which uses RCreate a `.env` file with the following environment variables:-```ini+```dotenvRESEND_API_KEY="your_resend_api_key"SEND_EMAIL_HOOK_SECRET="v1,whsec_<base64_secret>"```diff --git a/apps/docs/content/guides/auth/quickstarts/astrojs.mdx b/apps/docs/content/guides/auth/quickstarts/astrojs.mdxindex c43992fc6ce..dbfdce8db94 100644--- a/apps/docs/content/guides/auth/quickstarts/astrojs.mdx+++ b/apps/docs/content/guides/auth/quickstarts/astrojs.mdx@@ -103,7 +103,7 @@ hideToc: true<StepHikeCompact.Code>- ```text name=.env.local+ ```dotenv name=.env.localPUBLIC_SUPABASE_URL=your-project-urlPUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_key```diff --git a/apps/docs/content/guides/auth/quickstarts/nextjs.mdx b/apps/docs/content/guides/auth/quickstarts/nextjs.mdxindex eb56a6c7710..385c934d326 100644--- a/apps/docs/content/guides/auth/quickstarts/nextjs.mdx+++ b/apps/docs/content/guides/auth/quickstarts/nextjs.mdx@@ -64,7 +64,7 @@ hideToc: true<StepHikeCompact.Code>- ```text name=.env.local+ ```dotenv name=.env.localNEXT_PUBLIC_SUPABASE_URL=your-project-urlNEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=sb_publishable_... key```diff --git a/apps/docs/content/guides/auth/social-login/auth-google.mdx b/apps/docs/content/guides/auth/social-login/auth-google.mdxindex ea892e4c37c..48ada3eac69 100644--- a/apps/docs/content/guides/auth/social-login/auth-google.mdx+++ b/apps/docs/content/guides/auth/social-login/auth-google.mdx@@ -193,7 +193,7 @@ Follow the same configuration guide as if your app was a Web application when buTo use the Google provider in local development:1. Add a new environment variable:- ```env+ ```dotenvSUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_SECRET="<client-secret>"```2. Configure the provider in `supabase/config.toml`:diff --git a/apps/docs/content/guides/database/connecting-to-postgres/serverless-drivers.mdx b/apps/docs/content/guides/database/connecting-to-postgres/serverless-drivers.mdxindex 7257bb0f77b..8dcb772d7a2 100644--- a/apps/docs/content/guides/database/connecting-to-postgres/serverless-drivers.mdx+++ b/apps/docs/content/guides/database/connecting-to-postgres/serverless-drivers.mdx@@ -52,7 +52,7 @@ Choose one of these Vercel Deploy Templates. They use the [Vercel Deploy Integra3. Add the suffix `?workaround=supabase-pooler.vercel` to the URI.4. Save the result as the `POSTGRES_URL` environment variable.-```txt .env.local+```dotenv .env.localPOSTGRES_URL="postgresql://postgres.[PROJECT-REF]:[YOUR-PASSWORD]@[POOLER-HOST]:6543/postgres?workaround=supabase-pooler.vercel"```diff --git a/apps/docs/content/guides/database/prisma.mdx b/apps/docs/content/guides/database/prisma.mdxindex f7b9b40d783..99d07447c4e 100644--- a/apps/docs/content/guides/database/prisma.mdx+++ b/apps/docs/content/guides/database/prisma.mdx@@ -144,7 +144,7 @@ If you plan to solely use Prisma instead of the Supabase Data API (PostgREST), t<Tabs type="underlined" size="small"><TabPanel id="serverful" label="server-based deployments">In your .env file, set the DATABASE_URL variable to your connection string- ```text .env+ ```dotenv .env# Used for Prisma Migrations and within your applicationDATABASE_URL="postgres://[DB-USER].[PROJECT-REF]:[PRISMA-PASSWORD]@[DB-REGION].pooler.supabase.com:5432/postgres"```@@ -160,7 +160,7 @@ If you plan to solely use Prisma instead of the Supabase Data API (PostgREST), tNext, create a DIRECT_URL variable in your .env file and assign the connection string that ends with port 5432 to it.- ```text .env # Used in your application (use transaction mode)+ ```dotenv .env # Used in your application (use transaction mode)DATABASE_URL="postgres://[DB-USER].[PROJECT-REF]:[PRISMA-PASSWORD]@aws-0-us-east-1.pooler.supabase.com:6543/postgres?pgbouncer=true"# Used for Prisma Migrations (use session mode or direct connection)diff --git a/apps/docs/content/guides/functions/examples/amazon-bedrock-image-generator.mdx b/apps/docs/content/guides/functions/examples/amazon-bedrock-image-generator.mdxindex 3ab5e0ab092..5275b78988f 100644--- a/apps/docs/content/guides/functions/examples/amazon-bedrock-image-generator.mdx+++ b/apps/docs/content/guides/functions/examples/amazon-bedrock-image-generator.mdx@@ -14,7 +14,7 @@ This guide will walk you through an example using the Amazon Bedrock JavaScript- In your AWS console, navigate to Amazon Bedrock and under "Request model access", select the Amazon Titan Image Generator G1 model.- In your Supabase project, create a `.env` file in the `supabase` directory with the following contents:-```txt+```dotenvAWS_DEFAULT_REGION="<your_region>"AWS_ACCESS_KEY_ID="<replace_your_own_credentials>"AWS_SECRET_ACCESS_KEY="<replace_your_own_credentials>"diff --git a/apps/docs/content/guides/functions/examples/elevenlabs-generate-speech-stream.mdx b/apps/docs/content/guides/functions/examples/elevenlabs-generate-speech-stream.mdxindex 23c4413a7c3..24055e410a0 100644--- a/apps/docs/content/guides/functions/examples/elevenlabs-generate-speech-stream.mdx+++ b/apps/docs/content/guides/functions/examples/elevenlabs-generate-speech-stream.mdx@@ -78,7 +78,7 @@ If you're using VS Code or Cursor, select `y` when the CLI prompts "Generate VSWithin the `supabase/functions` directory, create a new `.env` file and add the following variables:-```env supabase/functions/.env+```dotenv supabase/functions/.env# Find / create an API key at https://elevenlabs.io/app/settings/api-keysELEVENLABS_API_KEY=your_api_key```diff --git a/apps/docs/content/guides/functions/examples/elevenlabs-transcribe-speech.mdx b/apps/docs/content/guides/functions/examples/elevenlabs-transcribe-speech.mdxindex 3b7e5cc2814..2a39a6625dd 100644--- a/apps/docs/content/guides/functions/examples/elevenlabs-transcribe-speech.mdx+++ b/apps/docs/content/guides/functions/examples/elevenlabs-transcribe-speech.mdx@@ -81,7 +81,7 @@ If you're using VS Code or Cursor, select `y` when the CLI prompts "Generate VSWithin the `supabase/functions` directory, create a new `.env` file and add the following variables:-```env supabase/functions/.env+```dotenv supabase/functions/.env# Find / create an API key at https://elevenlabs.io/app/settings/api-keysELEVENLABS_API_KEY=your_api_keydiff --git a/apps/docs/content/guides/getting-started/quickstarts/astrojs.mdx b/apps/docs/content/guides/getting-started/quickstarts/astrojs.mdxindex 5038522c541..a55b22387c9 100644--- a/apps/docs/content/guides/getting-started/quickstarts/astrojs.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/astrojs.mdx@@ -55,7 +55,7 @@ Create a `.env.local` file and populate with your Supabase connection variables</a></Button>-```text name=.env.local+```dotenv name=.env.localPUBLIC_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>PUBLIC_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/expo-react-native.mdx b/apps/docs/content/guides/getting-started/quickstarts/expo-react-native.mdxindex ea17ebde125..3e6f6200a98 100644--- a/apps/docs/content/guides/getting-started/quickstarts/expo-react-native.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/expo-react-native.mdx@@ -42,7 +42,7 @@ Create a `.env` file in the root of your project and populate it with your SupabExpo requires environment variables to be prefixed with `EXPO_PUBLIC_` to be accessible in your app code.-```text name=.env+```dotenv name=.envEXPO_PUBLIC_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>EXPO_PUBLIC_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/flask.mdx b/apps/docs/content/guides/getting-started/quickstarts/flask.mdxindex b174c9300bc..3f5b05fc65b 100644--- a/apps/docs/content/guides/getting-started/quickstarts/flask.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/flask.mdx@@ -42,7 +42,7 @@ Create a `.env` file in your project root and populate it with your Supabase con</a></Button>-```text name=.env+```dotenv name=.envSUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/nextjs.mdx b/apps/docs/content/guides/getting-started/quickstarts/nextjs.mdxindex 57fdfd03fb4..509dc1de14c 100644--- a/apps/docs/content/guides/getting-started/quickstarts/nextjs.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/nextjs.mdx@@ -30,7 +30,7 @@ Rename `.env.example` to `.env.local` and populate with your Supabase connection</a></Button>-```text name=.env.local+```dotenv name=.env.localNEXT_PUBLIC_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>NEXT_PUBLIC_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/nuxtjs.mdx b/apps/docs/content/guides/getting-started/quickstarts/nuxtjs.mdxindex 3d282e492b9..37171f0cb52 100644--- a/apps/docs/content/guides/getting-started/quickstarts/nuxtjs.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/nuxtjs.mdx@@ -52,7 +52,7 @@ Create a `.env` file and populate with your Supabase connection variables that y<$CodeTabs>-```text name=.env+```dotenv name=.envSUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/reactjs.mdx b/apps/docs/content/guides/getting-started/quickstarts/reactjs.mdxindex 804bf92b434..8cf1645310a 100644--- a/apps/docs/content/guides/getting-started/quickstarts/reactjs.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/reactjs.mdx@@ -40,7 +40,7 @@ Create a `.env.local` file and populate it with your Supabase URL and publishabl</a></Button>-```text name=.env.local+```dotenv name=.env.localVITE_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>VITE_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/refine.mdx b/apps/docs/content/guides/getting-started/quickstarts/refine.mdxindex f3060abe91f..7d5dd43560f 100644--- a/apps/docs/content/guides/getting-started/quickstarts/refine.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/refine.mdx@@ -44,7 +44,7 @@ Create a `.env` file and populate it with your Supabase URL and publishable key,</a></Button>-```text name=.env+```dotenv name=.envVITE_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>VITE_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/reflex.mdx b/apps/docs/content/guides/getting-started/quickstarts/reflex.mdxindex efbf157d086..f56b147dd25 100644--- a/apps/docs/content/guides/getting-started/quickstarts/reflex.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/reflex.mdx@@ -41,7 +41,7 @@ Create a `.env` file in your project root and populate it with your Supabase con<a href="/dashboard/project/_?showConnect=true&connectTab=frameworks">Open Connect panel</a></Button>-```text name=.env+```dotenv name=.envSUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/solidjs.mdx b/apps/docs/content/guides/getting-started/quickstarts/solidjs.mdxindex be6fc3f1eca..7d2f0fdff0c 100644--- a/apps/docs/content/guides/getting-started/quickstarts/solidjs.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/solidjs.mdx@@ -46,7 +46,7 @@ Create a `.env.local` file and populate with your Supabase connection variables</a></Button>-```text name=.env.local+```dotenv name=.env.localVITE_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>VITE_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/sveltekit.mdx b/apps/docs/content/guides/getting-started/quickstarts/sveltekit.mdxindex d512f518dc0..7927c700c59 100644--- a/apps/docs/content/guides/getting-started/quickstarts/sveltekit.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/sveltekit.mdx@@ -40,7 +40,7 @@ Create a `.env` file at the root of your project and populate with your Supabase</a></Button>-```text name=.env+```dotenv name=.envPUBLIC_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>PUBLIC_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/tanstack.mdx b/apps/docs/content/guides/getting-started/quickstarts/tanstack.mdxindex c0cfcdfb3a3..cf57fb0410d 100644--- a/apps/docs/content/guides/getting-started/quickstarts/tanstack.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/tanstack.mdx@@ -38,7 +38,7 @@ Create a `.env.local` file in the root of your project and populate it with your</a></Button>-```text name=.env.local+```dotenv name=.env.localVITE_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>VITE_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/getting-started/quickstarts/vue.mdx b/apps/docs/content/guides/getting-started/quickstarts/vue.mdxindex 3de10fe7e21..fc4124ef680 100644--- a/apps/docs/content/guides/getting-started/quickstarts/vue.mdx+++ b/apps/docs/content/guides/getting-started/quickstarts/vue.mdx@@ -40,7 +40,7 @@ Create a `.env.local` file and populate with your Supabase connection variables</a></Button>-```text name=.env.local+```dotenv name=.env.localVITE_SUPABASE_URL=<SUBSTITUTE_SUPABASE_URL>VITE_SUPABASE_PUBLISHABLE_KEY=<SUBSTITUTE_SUPABASE_PUBLISHABLE_KEY>```diff --git a/apps/docs/content/guides/local-development/seeding-your-database.mdx b/apps/docs/content/guides/local-development/seeding-your-database.mdxindex c8b6bff0b42..6fb73216380 100644--- a/apps/docs/content/guides/local-development/seeding-your-database.mdx+++ b/apps/docs/content/guides/local-development/seeding-your-database.mdx@@ -192,7 +192,7 @@ npx @snaplet/seed syncYou can further enhance your seed script by using Large Language Models to generate more realistic data. To enable this feature, set one of the following environment variables in your `.env` file:-```plaintext+```dotenvOPENAI_API_KEY=<your_openai_api_key>GROQ_API_KEY=<your_groq_api_key>```diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx b/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsxdeleted file mode 100644index c407f0c6223..00000000000--- a/apps/docs/features/ui/CodeBlock/CodeBlock.client.tsx+++ /dev/null@@ -1,306 +0,0 @@-'use client'--import { ArrowRightFromLine, Check, Copy, WrapText, type LucideIcon } from 'lucide-react'-import { useCallback, useEffect, useRef, useState, type MouseEvent } from 'react'-import { type NodeHover } from 'twoslash'-import { Button, cn, copyToClipboard, Tooltip, TooltipContent, TooltipTrigger } from 'ui'--type CodeAnnotation = Pick<NodeHover, 'text' | 'docs' | 'tags'>-export type CodeToken = [- content: string,- className: string | undefined,- annotations?: Array<CodeAnnotation>,-]--export function CodeBlockTokens({- lines,- lineNumbers,-}: {- lines: Array<Array<CodeToken>>- lineNumbers: boolean-}) {- return (- <pre>- <code- className={cn(- '[contain:content]',- lineNumbers && 'grid grid-cols-[auto_1fr] w-fit min-w-full py-3',- '[--row-rest:var(--background-200)]',- '[--row-hover:color-mix(in_srgb,var(--foreground)_3%,var(--background-200))]'- )}- >- {lineNumbers ? (- lines.map((line, idx) => (- <div key={idx} className="group/row contents">- <div aria-hidden="true" className="code-line-number">- {idx + 1}- </div>- <div className="code-content code-line-content">- <CodeLine tokens={line} />- </div>- </div>- ))- ) : (- <div className="code-content p-6">- {lines.map((line, idx) => (- <CodeLine key={idx} tokens={line} />- ))}- </div>- )}- </code>- </pre>- )-}--function CodeLine({ tokens }: { tokens: Array<CodeToken> }) {- return (- <span className="block min-h-5 leading-5">- {tokens.map(([content, className, annotations], idx) =>- annotations ? (- <AnnotatedSpan- key={idx}- content={content}- className={className}- annotations={annotations}- />- ) : (- <span key={idx} className={className}>- {content}- </span>- )- )}- </span>- )-}--export function AnnotatedSpan({- content,- className,- annotations,-}: {- content: string- className: string | undefined- annotations: Array<CodeAnnotation>-}) {- const [open, setOpen] = useState(false)-- const [isTouchDevice, setIsTouchDevice] = useState(false)- useEffect(() => {- const touchDevice = !window.matchMedia('(pointer: fine)').matches- setIsTouchDevice(touchDevice)- }, [])-- const handleClick = useCallback(- (evt: MouseEvent) => {- if (isTouchDevice) {- evt.preventDefault()- evt.stopPropagation()- setOpen((open) => !open)- }- },- [isTouchDevice]- )- const onOpenChange = useCallback(- (open: boolean) => {- if (!isTouchDevice || !open) {- setOpen(open)- }- },- [isTouchDevice]- )-- return (- <Tooltip open={open} onOpenChange={onOpenChange}>- <TooltipTrigger asChild onClick={handleClick}>- <button- tabIndex={0}- className={cn(- className,- isTouchDevice &&- 'underline underline-offset-4 decoration-dashed decoration-[rgba(from_currentColor_r_g_b/0.5)]'- )}- >- {content}- </button>- </TooltipTrigger>- <TooltipContent className="max-w-[min(80vw,400px)] p-0 divide-y">- {annotations.map((annotation, idx) => (- <Annotation key={idx} annotation={annotation} />- ))}- </TooltipContent>- </Tooltip>- )-}--function Annotation({ annotation }: { annotation: CodeAnnotation }) {- const { text, docs, tags } = annotation- return (- <div data-code-style="plain" className="flex flex-col gap-2">- <code className={cn('block bg-200 p-2', (docs || tags) && 'border-b border-default')}>- {text}- </code>- {docs && <p className={cn('p-2', tags && 'border-b border-default')}>{docs}</p>}- {tags && (- <div className="p-2 flex flex-col">- {tags.map((tag, idx) => {- return (- <span key={idx}>- <code>@{tag[0]}</code> {tag[1]}- </span>- )- })}- </div>- )}- </div>- )-}--function CrossfadeIcon({- active,- activeIcon: ActiveIcon,- inactiveIcon: InactiveIcon,-}: {- active: boolean- activeIcon: LucideIcon- inactiveIcon: LucideIcon-}) {- const iconClass = (shown: boolean) =>- cn(- 'absolute inset-0 m-auto text-lighter group-hover/btn:text-foreground',- 'transition-[opacity,scale,filter,color] duration-300 [transition-timing-function:cubic-bezier(0.2,0,0,1)]',- 'motion-reduce:transition-none',- shown ? 'opacity-100 scale-100 blur-none' : 'opacity-0 scale-[0.25] blur-[4px]'- )-- return (- <span className="relative block size-3.5">- <ActiveIcon size={14} aria-hidden="true" className={iconClass(active)} />- <InactiveIcon size={14} aria-hidden="true" className={iconClass(!active)} />- </span>- )-}--export function CodeCopyButton({- className,- content,- label = 'Copy code',- copiedLabel = 'Code copied',- onCopied,-}: {- className?: string- content: string- label?: string- copiedLabel?: string- /** Runs after a successful clipboard write. */- onCopied?: () => void-}) {- const [copied, setCopied] = useState(false)-- useEffect(() => {- if (!copied) return-- const timeout = window.setTimeout(() => setCopied(false), 2000)- return () => window.clearTimeout(timeout)- }, [copied])-- const handleCopy = async () => {- copyToClipboard(content, () => {- setCopied(true)- onCopied?.()- })- }-- const resetStatus = () => {- setCopied(false)- }-- return (- <>- <span className="sr-only" aria-live="polite">- {copied ? copiedLabel : ''}- </span>- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="outline"- tabIndex={0}- onClick={handleCopy}- onBlur={resetStatus}- className={cn(- 'group/btn size-6 p-1 cursor-pointer bg-200 hover:border-strong',- copied && 'bg-[var(--btn-active)]',- 'hover:bg-[var(--btn-active)]',- className- )}- aria-label={label}- // Tooltip repeats the label; screen readers would read it twice- aria-describedby={undefined}- >- <CrossfadeIcon active={copied} activeIcon={Check} inactiveIcon={Copy} />- </Button>- </TooltipTrigger>- <TooltipContent>{label}</TooltipContent>- </Tooltip>- </>- )-}--export function CodeBlockControls({ content }: { content: string }) {- const [isWrapped, setIsWrapped] = useState(false)- // Empty until the first toggle, so nothing is announced on mount- const [wrapStatus, setWrapStatus] = useState('')- const wrapperRef = useRef<HTMLDivElement>(null)-- const toggleWrap = useCallback(() => {- const newValue = !isWrapped- setIsWrapped(newValue)- setWrapStatus(newValue ? 'Word wrap enabled' : 'Word wrap disabled')-- const codeBlock = wrapperRef.current?.closest('.shiki')- if (codeBlock) {- if (newValue) {- codeBlock.setAttribute('data-wrapped', 'true')- } else {- codeBlock.removeAttribute('data-wrapped')- }- }- }, [isWrapped])-- return (- <div- ref={wrapperRef}- className={cn(- 'opacity-0 flex group-hover:opacity-100 group-focus-within:opacity-100 absolute top-[9.5px] right-[9.5px] gap-1',- '[--btn-active:color-mix(in_srgb,var(--foreground)_4%,var(--background-200))]'- )}- >- <span className="sr-only" aria-live="polite">- {wrapStatus}- </span>- <Tooltip>- <TooltipTrigger asChild>- <Button- variant="outline"- tabIndex={0}- onClick={toggleWrap}- className={cn(- 'group/btn size-6 p-1 cursor-pointer bg-200 hover:border-strong',- 'hover:bg-[var(--btn-active)]'- )}- aria-label={isWrapped ? 'Disable word wrap' : 'Enable word wrap'}- // Tooltip repeats the label; screen readers would read it twice- aria-describedby={undefined}- >- <CrossfadeIcon- active={isWrapped}- activeIcon={ArrowRightFromLine}- inactiveIcon={WrapText}- />- </Button>- </TooltipTrigger>- <TooltipContent>{isWrapped ? 'Disable word wrap' : 'Enable word wrap'}</TooltipContent>- </Tooltip>- <CodeCopyButton content={content} />- </div>- )-}diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsx b/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsxindex 22d4df75829..10065bec129 100644--- a/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsx+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.test.tsx@@ -3,13 +3,14 @@ import { type ComponentProps, type PropsWithChildren } from 'react'import { renderToStaticMarkup } from 'react-dom/server'import { beforeEach, describe, expect, it, vi } from 'vitest'+import { highlightCode } from 'ui-patterns/CodeBlock/CodeBlock.highlight'+import { type CodeToken } from 'ui-patterns/CodeBlock/CodeBlockFrame'+import { CodeBlock } from './CodeBlock'-import { type CodeToken } from './CodeBlock.client'-import { highlightCode } from './CodeBlock.highlight'const { twoslasher } = vi.hoisted(() => ({ twoslasher: vi.fn() }))-vi.mock('./CodeBlock.highlight', () => ({ highlightCode: vi.fn() }))+vi.mock('ui-patterns/CodeBlock/CodeBlock.highlight', () => ({ highlightCode: vi.fn() }))vi.mock('twoslash', () => ({ createTwoslasher: () => twoslasher }))vi.mock('./types/lib.deno.d.ts.include', () => ({ default: '' }))@@ -26,9 +27,14 @@ vi.mock('ui', async () => {copyToClipboard: vi.fn(),}})+vi.mock('ui/src/components/shadcn/ui/tooltip', () => ({+ Tooltip: ({ children }: PropsWithChildren) => children,+ TooltipTrigger: ({ children }: PropsWithChildren) => children,+ TooltipContent: () => null,+}))function getLines(block: Awaited<ReturnType<typeof CodeBlock>>): Array<Array<CodeToken>> {- return block.props.children[0].props.children.props.lines+ return block.props.children.props.lines}describe('code block serialization and rendering', () => {diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.tsx b/apps/docs/features/ui/CodeBlock/CodeBlock.tsxindex 5c19b28757a..08a6adf0f51 100644--- a/apps/docs/features/ui/CodeBlock/CodeBlock.tsx+++ b/apps/docs/features/ui/CodeBlock/CodeBlock.tsx@@ -1,11 +1,14 @@import { type PropsWithChildren } from 'react'import { bundledLanguages, type BundledLanguage } from 'shiki'import { createTwoslasher, type ExtraFiles, type NodeHover } from 'twoslash'-import { cn } from 'ui'--import { CodeBlockControls, CodeBlockTokens, type CodeToken } from './CodeBlock.client'-import { highlightCode } from './CodeBlock.highlight'-import { getCodeBlockLabel, getTokenClassName } from './CodeBlock.utils'+import { highlightCode } from 'ui-patterns/CodeBlock/CodeBlock.highlight'+import { getTokenClassName } from 'ui-patterns/CodeBlock/CodeBlock.tokens'+import { CodeBlockControls } from 'ui-patterns/CodeBlock/CodeBlockControls'+import {+ CodeBlockFrame,+ CodeBlockTokens,+ type CodeToken,+} from 'ui-patterns/CodeBlock/CodeBlockFrame'import denoTypes from './types/lib.deno.d.ts.include'const extraFiles: ExtraFiles = { 'deno.d.ts': denoTypes }@@ -55,52 +58,30 @@ export async function CodeBlock({const { tokens } = await highlightCode(code, lang)return (- <div- className={cn(- 'shiki',- 'group',- 'relative has-[.code-scroll:focus-visible]:z-1',- 'has-[.code-scroll:focus-visible]:outline-2 has-[.code-scroll:focus-visible]:outline-ring',- 'not-prose',- 'w-full',- compact ? 'border-0 my-0!' : 'border border-default rounded-lg shadow-codeblock',- 'bg-200',- 'text-sm',- className- )}+ <CodeBlockFrame+ className={className}+ lang={lang}+ lineCount={tokens.length}+ compact={compact}+ controls={hideControls ? null : <CodeBlockControls content={code.trim()} />}>- <div- className={cn(- 'code-scroll',- 'w-full overflow-x-auto overscroll-x-none',- !compact && 'rounded-lg',- 'focus-visible:outline-hidden'- )}- role="group"- aria-roledescription="code block"- aria-label={getCodeBlockLabel(lang, tokens.length)}- tabIndex={0}- >- <CodeBlockTokens- lineNumbers={lineNumbers}- lines={tokens.map((line, lineIndex) => {- let offset = 0- return line.map(({ content, color, fontStyle }): CodeToken => {- const annotations = twoslashed- ?.get(lineIndex)- ?.get(offset)- ?.map(({ text, docs, tags }) => ({ text, docs, tags }))- offset += content.length- const className = getTokenClassName(color, fontStyle)+ <CodeBlockTokens+ lineNumbers={lineNumbers}+ lines={tokens.map((line, lineIndex) => {+ let offset = 0+ return line.map(({ content, color, fontStyle }): CodeToken => {+ const annotations = twoslashed+ ?.get(lineIndex)+ ?.get(offset)+ ?.map(({ text, docs, tags }) => ({ text, docs, tags }))+ offset += content.length+ const className = getTokenClassName(color, fontStyle)- return annotations ? [content, className, annotations] : [content, className]- })- })}- />- </div>- {/* After the code so the block is named before its controls, and outside the scroller so they stay pinned */}- {!hideControls && <CodeBlockControls content={code.trim()} />}- </div>+ return annotations ? [content, className, annotations] : [content, className]+ })+ })}+ />+ </CodeBlockFrame>)}diff --git a/apps/docs/features/ui/PromptPanel.tsx b/apps/docs/features/ui/PromptPanel.tsxindex 3f1500d0313..cb0510e0601 100644--- a/apps/docs/features/ui/PromptPanel.tsx+++ b/apps/docs/features/ui/PromptPanel.tsx@@ -8,7 +8,7 @@ import ReactMarkdown from 'react-markdown'// shadcn tabs from packages/ui/src/components/shadcn/ui/tabs.tsximport { cn, Tabs, TabsContent, TabsIndicator, TabsList, TabsTrigger } from 'ui'-import { CodeCopyButton } from './CodeBlock/CodeBlock.client'+import { CodeCopyButton } from 'ui-patterns/CodeBlock/CodeBlockControls'type PromptTitleProps = {children: ReactNodediff --git a/apps/docs/styles/code-block.css b/apps/docs/styles/code-block.cssindex 66bc752d432..0b4701e209c 100644--- a/apps/docs/styles/code-block.css+++ b/apps/docs/styles/code-block.css@@ -1,119 +1,3 @@-@utility code-line-number {- @apply select-none text-right text-muted/70 pl-3 pr-2 min-h-5 leading-5;- @apply bg-[var(--row-rest)] sticky left-0 z-10;- @apply group-hover/row:text-muted group-hover/row:bg-[var(--row-hover)];- @apply after:pointer-events-none after:absolute after:inset-y-0 after:left-full after:w-4;- @apply [--gutter-fade:var(--row-rest)] group-hover/row:[--gutter-fade:var(--row-hover)];- @apply after:bg-[image:linear-gradient(to_right,var(--gutter-fade)_0%,color-mix(in_srgb,var(--gutter-fade)_85%,transparent)_25%,color-mix(in_srgb,var(--gutter-fade)_50%,transparent)_50%,color-mix(in_srgb,var(--gutter-fade)_15%,transparent)_75%,transparent_100%)];-}--@utility code-line-content {- @apply min-h-5 leading-5 pl-3 pr-18 group-hover/row:bg-[var(--row-hover)];-}--/* Code blocks need margin applied when in content container */-.prose :where(.shiki, .shiki-wrapper):where(:not(.shiki-wrapper *)) {- margin-block: 2rem;-}--/* Code block theme colors for use with Supabase Theme */-[data-theme='dark'],-.dark {- --code-token-keyword: #bda4ff;- --code-foreground: #ffffff;- --code-token-constant: #3ecf8e;- --code-token-string: #ffcda1;- --code-token-comment: #949494;- --code-token-parameter: #ffffff;- --code-token-function: #3ecf8e;- --code-token-string-expression: #ffcda1;- --code-token-punctuation: #ffffff;- --code-token-link: #ffffff;- --code-token-number: #ffffff;- --code-token-property: #3ecf8e;- --code-token-variable: var(--code-foreground);- --code-highlight-color: #232323;- --shadow-codeblock:- 0 0 0 0 var(--border-default), 0 1px 2px 0 rgba(0, 0, 0, 0.3), 0 1px 3px 0 rgba(0, 0, 0, 0.3);- --drop-shadow-codeblock: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.5));-}-[data-theme='light'],-.light {- --shadow-codeblock: 0 0 #0000;- --code-token-keyword: #5f2fc4;- --code-foreground: oklch(from var(--foreground-light) l c h / 1);- --code-token-constant: #15593b;- --code-token-string: #9a5200;- --code-token-comment: #6a6a6a;- --code-token-parameter: oklch(from var(--foreground-light) l c h / 1);- --code-token-function: #15593b;- --code-token-string-expression: #9a5200;- --code-token-punctuation: oklch(from var(--foreground-light) l c h / 1);- --code-token-link: oklch(from var(--foreground-light) l c h / 1);- --code-token-number: oklch(from var(--foreground-light) l c h / 1);- --code-token-property: #15593b;- --code-token-variable: var(--code-foreground);- --code-highlight-color: #1c1c1c;-}--/* Token classes emitted by CodeBlock.utils.ts */-.shiki .s-f {- color: var(--code-foreground);-}-.shiki .s-c {- color: var(--code-token-comment);-}-.shiki .s-n {- color: var(--code-token-constant);-}-.shiki .s-u {- color: var(--code-token-function);-}-.shiki .s-k {- color: var(--code-token-keyword);-}-.shiki .s-a {- color: var(--code-token-parameter);-}-.shiki .s-r {- color: var(--code-token-property);-}-.shiki .s-p {- color: var(--code-token-punctuation);-}-.shiki .s-s {- color: var(--code-token-string);-}-.shiki .s-e {- color: var(--code-token-string-expression);-}-.shiki .s-v {- color: var(--code-token-variable);-}-.shiki .s-i {- font-style: italic;-}-.shiki .s-b {- font-weight: bold;-}-.shiki .s-l {- text-decoration: underline;-}--/* Word wrap styles for code blocks */-.shiki[data-wrapped='true'] .code-scroll {- overflow-x: hidden !important;-}--.shiki[data-wrapped='true'] .code-content {- white-space: pre-wrap !important;- overflow-wrap: anywhere !important;-}--.shadow-codeblock {- box-shadow: var(--shadow-codeblock, none);-}-.shiki-wrapper {--tab-flare-ring:transparent 6.75px, var(--border-color-default) 7.25px, var(--border-color-default) 7.75px,diff --git a/apps/docs/styles/globals.css b/apps/docs/styles/globals.cssindex bcbb3437aa6..6895f7bc4f6 100644--- a/apps/docs/styles/globals.css+++ b/apps/docs/styles/globals.css@@ -1,5 +1,6 @@@import 'config/tailwind.config.css';@import 'config/inline-code.css';+@import 'ui-patterns/CodeBlock/code-block.css';@import './code-block.css';@import './reference.css';@import './loading-beam.css';diff --git a/apps/kb/astro.config.mjs b/apps/kb/astro.config.mjsindex 7b3ddc79da6..a002665024b 100644--- a/apps/kb/astro.config.mjs+++ b/apps/kb/astro.config.mjs@@ -8,32 +8,31 @@ import sitemap from '@astrojs/sitemap'import tailwindcss from '@tailwindcss/vite'import { defineConfig } from 'astro/config'-import supabaseTheme from '../learn/lib/themes/supabase-2.json' with { type: 'json' }import { BASE_PATH } from './src/lib/constants.ts'import rehypeAdmonitions from './src/lib/mdx/rehype-admonitions.js'+import { sharedCodeBlock } from './src/lib/mdx/shiki-code-block.ts'+import { codeBlockTheme } from 'ui-patterns/CodeBlock/CodeBlock.theme'-// Absolute dir of lodash-es, for the SSR-only lodash alias below (same fix+// Absolute dir of lodash-es, for the lodash alias below (same fix// apps/studio/vite.config.ts uses). `packages/ui`'s clipboard util does// `import { noop } from 'lodash'` — under Vite's dev-mode SSR module runner,// that CJS import evaluates as pure ESM (no module/exports/require), so the// named import binds to undefined. lodash-es is real ESM and the same-// version, so swapping it in for SSR only (client bundles are untouched)-// fixes it without touching the shared `ui` package.+// version, so the alias fixes the import without changes to the shared `ui`+// package. The client build also uses the alias, so the code block controls+// island includes only the lodash code that it uses.const lodashEsDir = path.dirname(createRequire(import.meta.url).resolve('lodash-es/package.json'))// Not typed as `import('vite').Plugin` — kb's own `vite` (from the pnpm// catalog) and Astro's internal vite dependency resolve to distinct type// instances, and comparing them blows TS's structural-comparison stack depth.-const ssrLodashEs = {- name: 'kb-ssr-lodash-es',+const lodashEs = {+ name: 'kb-lodash-es',enforce: 'pre',/*** @param {string} source- * @param {string | undefined} _importer- * @param {{ ssr?: boolean } | undefined} options*/- resolveId(source, _importer, options) {- if (!options?.ssr) return+ resolveId(source) {if (source === 'lodash') return path.join(lodashEsDir, 'lodash.js')const subpath = source.match(/^lodash\/(.+?)(\.js)?$/)if (subpath) return path.join(lodashEsDir, `${subpath[1]}.js`)@@ -59,26 +58,13 @@ export default defineConfig({ssr: {noExternal: ['lodash'],},- plugins: [tailwindcss(), ssrLodashEs],+ plugins: [tailwindcss(), lodashEs],logLevel: 'error',},markdown: {shikiConfig: {- theme: supabaseTheme,- // Match the docs app's CodeBlock component (border + rounded-lg on the- // outer element), since Astro's own markdown pipeline renders code- // blocks straight to a `<pre>` with no wrapper we can add classes to.- transformers: [- {- name: 'kb-code-block-classes',- pre(node) {- this.addClassToHast(node, 'border border-default rounded-lg')- },- code(node) {- this.addClassToHast(node, 'inline-block p-6')- },- },- ],+ theme: codeBlockTheme,+ transformers: [sharedCodeBlock],},},})diff --git a/apps/kb/package.json b/apps/kb/package.jsonindex c28ef445732..98251f5e0ba 100644--- a/apps/kb/package.json+++ b/apps/kb/package.json@@ -33,6 +33,7 @@"common": "workspace:*","docs-search": "workspace:*","gray-matter": "^4.0.3",+ "hast-util-from-html": "^2.0.3","lucide-react": "catalog:","react": "catalog:","react-dom": "catalog:",@@ -47,6 +48,7 @@"yaml": "^2.9.0"},"devDependencies": {+ "@astrojs/markdown-satteri": "0.3.8","@tailwindcss/vite": "4.2.4","@types/node": "catalog:","@types/react": "catalog:",diff --git a/apps/kb/src/components/CodeBlockControlsIsland.test.tsx b/apps/kb/src/components/CodeBlockControlsIsland.test.tsxnew file mode 100644index 00000000000..066c33d4365--- /dev/null+++ b/apps/kb/src/components/CodeBlockControlsIsland.test.tsx@@ -0,0 +1,86 @@+// @vitest-environment jsdom+import { act } from 'react'+import { createRoot, type Root } from 'react-dom/client'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { CodeBlockControlsIsland } from './CodeBlockControlsIsland'++const SOURCES = ['select 1', 'echo "<hi>"']++const writeText = vi.fn<(text: string) => Promise<void>>()++// these frames match the output of shiki-code-block.ts. that output keeps the copy text separate from the rendered code+const seedFrames = (sources: Array<string>) => {+ for (const source of sources) {+ const frame = document.createElement('div')+ frame.className = 'shiki'+ frame.dataset.codeSource = source+ frame.innerHTML = '<div class="code-scroll"><pre><code>1 decorated text</code></pre></div>'+ document.body.append(frame)+ }+ return [...document.querySelectorAll<HTMLElement>('.shiki')]+}++const mountIsland = () => {+ const container = document.createElement('div')+ document.body.append(container)+ const root = createRoot(container)+ act(() => root.render(<CodeBlockControlsIsland />))+ return root+}++describe('CodeBlockControlsIsland', () => {+ let root: Root | undefined++ beforeEach(() => {+ Reflect.set(globalThis, 'IS_REACT_ACT_ENVIRONMENT', true)+ writeText.mockReset().mockResolvedValue()+ vi.spyOn(document, 'hasFocus').mockReturnValue(true)+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })+ })++ afterEach(() => {+ act(() => root?.unmount())+ root = undefined+ document.body.innerHTML = ''+ })++ it('mounts one set of controls into each frame and copies that frame’s own source', async () => {+ const frames = seedFrames(SOURCES)+ root = mountIsland()++ for (const [idx, frame] of frames.entries()) {+ const copy = frame.querySelectorAll<HTMLButtonElement>('button[aria-label="Copy code"]')+ expect(copy).toHaveLength(1)+ await act(async () => copy[0].click())+ expect(writeText).toHaveBeenLastCalledWith(SOURCES[idx])+ }+ })++ it('toggles wrapping on its own frame only', () => {+ const [first, second] = seedFrames(SOURCES)+ root = mountIsland()++ act(() =>+ first.querySelector<HTMLButtonElement>('button[aria-label="Enable word wrap"]')?.click()+ )++ expect(first.querySelector(":scope > [data-wrapped='true']")).not.toBeNull()+ expect(second.querySelector(":scope > [data-wrapped='true']")).toBeNull()+ })++ it('renders nothing without frames and removes its controls on unmount', () => {+ const [frame] = seedFrames(SOURCES.slice(0, 1))+ root = mountIsland()+ expect(frame.querySelector('button')).not.toBeNull()++ act(() => root?.unmount())+ root = undefined+ expect(frame.querySelector('button')).toBeNull()+ expect(frame.textContent).toContain('decorated text')++ document.body.innerHTML = ''+ root = mountIsland()+ expect(document.querySelector('button')).toBeNull()+ })+})diff --git a/apps/kb/src/components/CodeBlockControlsIsland.tsx b/apps/kb/src/components/CodeBlockControlsIsland.tsxnew file mode 100644index 00000000000..3f03aff82a5--- /dev/null+++ b/apps/kb/src/components/CodeBlockControlsIsland.tsx@@ -0,0 +1,24 @@+import { useState } from 'react'+import { createPortal } from 'react-dom'+import { TooltipProvider } from 'ui'+import { CodeBlockControls } from 'ui-patterns/CodeBlock/CodeBlockControls'++// markdown gives static html, so one react tree puts the controls into each frame with a portal+export function CodeBlockControlsIsland() {+ // client:only island: the browser parses the article dom before this first render.+ // src/lib/mdx/shiki-code-block.ts makes these frames and stores the copy text of each block+ const [frames] = useState(() => [...document.querySelectorAll<HTMLElement>('[data-code-source]')])++ return (+ <TooltipProvider>+ {frames.map((frame, idx) =>+ // the frame list is a fixed snapshot of static markup, so the index identifies each frame+ createPortal(+ <CodeBlockControls content={frame.dataset.codeSource ?? ''} />,+ frame,+ `${idx}`+ )+ )}+ </TooltipProvider>+ )+}diff --git a/apps/kb/src/layouts/ArticleLayout.astro b/apps/kb/src/layouts/ArticleLayout.astroindex 08f2239c4b6..854f0e93d31 100644--- a/apps/kb/src/layouts/ArticleLayout.astro+++ b/apps/kb/src/layouts/ArticleLayout.astro@@ -3,6 +3,7 @@ import { ExternalLink } from 'lucide-react'import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbSeparator, GithubIcon } from 'ui'import type { TOCItemType } from 'ui-patterns/Toc/types'+import { CodeBlockControlsIsland } from '../components/CodeBlockControlsIsland'import { FeaturedSection } from '../components/FeaturedSection'import { GuideSidebar } from '../components/GuideSidebar'import type { RelatedGuides } from '../lib/guides'@@ -80,6 +81,7 @@ const markdownUrl = `${pagePath.replace(import.meta.env.BASE_URL, `${import.meta{description && <p class="not-prose mt-3 text-xl leading-7 text-foreground-light">{description}</p>}</header><slot />+ <CodeBlockControlsIsland client:only="react" /><div class="not-prose mt-12 -ml-5 lg:hidden"><GuideSidebarclient:visiblediff --git a/apps/kb/src/lib/mdx/shiki-code-block.test.ts b/apps/kb/src/lib/mdx/shiki-code-block.test.tsnew file mode 100644index 00000000000..a7ee56b2a49--- /dev/null+++ b/apps/kb/src/lib/mdx/shiki-code-block.test.ts@@ -0,0 +1,57 @@+import { createMarkdownProcessor } from '@astrojs/markdown-remark'+import { createSatteriMarkdownProcessor } from '@astrojs/markdown-satteri'+import { fromHtml } from 'hast-util-from-html'+import { codeBlockTheme } from 'ui-patterns/CodeBlock/CodeBlock.theme'+import { visit } from 'unist-util-visit'+import { describe, expect, it } from 'vitest'++import { sharedCodeBlock } from './shiki-code-block'++type HastRoot = ReturnType<typeof fromHtml>+type HastNode = HastRoot | HastRoot['children'][number]+type HastElement = Extract<HastNode, { type: 'element' }>++const SOURCE = `const html = "<b>it's" + '&'\n\n// "done"`+const MARKDOWN = `Intro\n\n\`\`\`js\n${SOURCE}\n\`\`\`\n\n\`\`\`\nplain <text>\n\`\`\`\n`+const SHIKI_CONFIG = { theme: codeBlockTheme, transformers: [sharedCodeBlock] }++// sätteri renders .md files and the unified pipeline renders .mdx files+const PROCESSORS = {+ satteri: () => createSatteriMarkdownProcessor({ shikiConfig: SHIKI_CONFIG }),+ unified: () => createMarkdownProcessor({ shikiConfig: SHIKI_CONFIG }),+}++// the test queries hast because the sätteri native binding does not run under jsdom+const findAll = (node: HastNode, test: (element: HastElement) => boolean) => {+ const found: Array<HastElement> = []+ visit(node, 'element', (element: HastElement) => {+ if (test(element)) found.push(element)+ })+ return found+}++const hasClass = (name: string) => (element: HastElement) =>+ Array.isArray(element.properties.className) && element.properties.className.includes(name)++const textOf = (node: HastNode): string =>+ node.type === 'text' ? node.value : 'children' in node ? node.children.map(textOf).join('') : ''++describe.each(Object.entries(PROCESSORS))('shared code block through %s', (_, create) => {+ it('renders the shared frame with exact copy source and no shiki pre', async () => {+ const { code } = await (await create()).render(MARKDOWN)+ const tree = fromHtml(code, { fragment: true })+ const [frame, plain] = findAll(tree, hasClass('shiki'))+ const label = (element: HastElement) => findAll(element, hasClass('code-scroll'))[0]++ expect(findAll(tree, hasClass('astro-code'))).toHaveLength(0)+ expect(findAll(tree, (element) => element.tagName === 'pre')).toHaveLength(2)+ expect(findAll(tree, (element) => element.tagName === 'button')).toHaveLength(0)+ expect(frame.properties.dataCodeSource).toBe(SOURCE)+ expect(findAll(frame, hasClass('code-line-content')).map(textOf).join('\n')).toBe(SOURCE)+ expect(label(frame).properties.ariaLabel).toBe('JavaScript, 3 lines')+ expect(textOf(findAll(frame, hasClass('s-k'))[0])).toBe('const')+ expect(findAll(frame, (element) => 'style' in element.properties)).toHaveLength(0)+ expect(plain.properties.dataCodeSource).toBe('plain <text>')+ expect(label(plain).properties.ariaLabel).toBe('1 line')+ })+})diff --git a/apps/kb/src/lib/mdx/shiki-code-block.ts b/apps/kb/src/lib/mdx/shiki-code-block.tsnew file mode 100644index 00000000000..e6782799472--- /dev/null+++ b/apps/kb/src/lib/mdx/shiki-code-block.ts@@ -0,0 +1,45 @@+import type { ShikiConfig } from '@astrojs/markdown-remark'+import { fromHtml } from 'hast-util-from-html'+import { createElement } from 'react'+import { renderToStaticMarkup } from 'react-dom/server'+import { getTokenClassName } from 'ui-patterns/CodeBlock/CodeBlock.tokens'+import {+ CodeBlockFrame,+ CodeBlockTokens,+ type CodeToken,+} from 'ui-patterns/CodeBlock/CodeBlockFrame'+import { visit } from 'unist-util-visit'++type ShikiTransformer = NonNullable<ShikiConfig['transformers']>[number]++// the .md and .mdx processors keep only the first child of the root, so the frame is the only child+export const sharedCodeBlock: ShikiTransformer = {+ name: 'kb-shared-code-block',+ root() {+ const lines = this.tokens.map((line) =>+ line.map(+ ({ content, color, fontStyle }): CodeToken => [content, getTokenClassName(color, fontStyle)]+ )+ )+ // astro highlights these fences as plain text. the frame labels them by line count only+ const lang = ['plaintext', 'text', 'txt', 'plain'].includes(this.options.lang)+ ? null+ : this.options.lang+ const html = renderToStaticMarkup(+ createElement(CodeBlockFrame, {+ lang,+ lineCount: lines.length,+ children: createElement(CodeBlockTokens, { lines, lineNumbers: true }),+ })+ )+ const [frame] = fromHtml(html, { fragment: true }).children+ if (frame?.type !== 'element') throw new Error('CodeBlockFrame rendered no root element')+ // the positions refer to the rendered string, not the source file. they make the mdx sourcemaps incorrect+ visit(frame, (node) => {+ delete node.position+ })+ // CodeBlockControlsIsland copies this text. it does not read the text from the rendered dom+ frame.properties.dataCodeSource = this.source+ return { type: 'root', children: [frame] }+ },+}diff --git a/apps/kb/src/styles/globals.css b/apps/kb/src/styles/globals.cssindex 18b886db6fc..d02f024b102 100644--- a/apps/kb/src/styles/globals.css+++ b/apps/kb/src/styles/globals.css@@ -1,5 +1,6 @@@import 'config/tailwind.config.css';@import 'config/inline-code.css';+@import 'ui-patterns/CodeBlock/code-block.css';@import './utilities.css';@import './keyframes.css';@@ -98,42 +99,12 @@ h6:not(.font-mono),}}-/* Code block theme colors for use with Supabase Theme */[data-theme='dark'] {- --code-token-keyword: #bda4ff;- --code-foreground: #ffffff;- --code-token-constant: #3ecf8e;- --code-token-string: #ffcda1;- --code-token-comment: #949494;- --code-token-parameter: #ffffff;- --code-token-function: #3ecf8e;- --code-token-string-expression: #ffcda1;- --code-token-punctuation: #ffffff;- --code-token-link: #ffffff;- --code-token-number: #ffffff;- --code-token-property: #3ecf8e;- --code-highlight-color: #232323;--raised-shadow:0 0 0 0 var(--border-default), 0 1px 2px 0 rgba(0, 0, 0, 0.3), 0 1px 3px 0 rgba(0, 0, 0, 0.3);--raised-drop-shadow: 0 1px 1px rgba(0, 0, 0, 0.5);}-[data-theme='light'] {- --code-token-keyword: #5f2fc4;- --code-foreground: oklch(from var(--foreground-light) l c h / 1);- --code-token-constant: #15593b;- --code-token-string: #9a5200;- --code-token-comment: #6a6a6a;- --code-token-parameter: oklch(from var(--foreground-light) l c h / 1);- --code-token-function: #15593b;- --code-token-string-expression: #9a5200;- --code-token-punctuation: oklch(from var(--foreground-light) l c h / 1);- --code-token-link: oklch(from var(--foreground-light) l c h / 1);- --code-token-number: oklch(from var(--foreground-light) l c h / 1);- --code-token-property: #15593b;- --code-highlight-color: #1c1c1c;-}-.prose [role='alert'] {margin: 1.25rem 0;}diff --git a/apps/learn/app/(app)/[...slug]/page.tsx b/apps/learn/app/(app)/[...slug]/page.tsxindex cc17d93c4d4..0ca48470fa7 100644--- a/apps/learn/app/(app)/[...slug]/page.tsx+++ b/apps/learn/app/(app)/[...slug]/page.tsx@@ -10,7 +10,7 @@ import { getNextPage } from '@/lib/get-next-page'import { getTableOfContents } from '@/lib/toc'import { absoluteUrl, cn } from '@/lib/utils'-import '@/styles/code-block-variables.css'+import 'config/code-block-variables.css'import '@/styles/mdx.css'import { ChevronRight } from 'lucide-react'diff --git a/apps/learn/styles/code-block-variables.css b/apps/learn/styles/code-block-variables.cssdeleted file mode 100644index a21af6b3751..00000000000--- a/apps/learn/styles/code-block-variables.css+++ /dev/null@@ -1,33 +0,0 @@-[data-theme='dark'],-.dark {- --code-token-keyword: #bda4ff;- --code-foreground: #ffffff;- --code-token-constant: #3ecf8e;- --code-token-string: #ffcda1;- --code-token-comment: #7e7e7e;- --code-token-parameter: #ffffff;- --code-token-function: #3ecf8e;- --code-token-string-expression: #ffcda1;- --code-token-punctuation: #ffffff;- --code-token-link: #ffffff;- --code-token-number: #ffffff;- --code-token-property: #3ecf8e;- --code-highlight-color: #232323;-}--[data-theme='light'],-.light {- --code-token-keyword: #6b35dc;- --code-foreground: oklch(from var(--foreground-light) l c h / 1);- --code-token-constant: #15593b;- --code-token-string: #c46a0a;- --code-token-comment: #7e7e7e;- --code-token-parameter: oklch(from var(--foreground-light) l c h / 1);- --code-token-function: #15593b;- --code-token-string-expression: #c46a0a;- --code-token-punctuation: oklch(from var(--foreground-light) l c h / 1);- --code-token-link: oklch(from var(--foreground-light) l c h / 1);- --code-token-number: oklch(from var(--foreground-light) l c h / 1);- --code-token-property: #15593b;- --code-highlight-color: #1c1c1c;-}diff --git a/apps/ui-library/app/(app)/docs/[[...slug]]/page.tsx b/apps/ui-library/app/(app)/docs/[[...slug]]/page.tsxindex 5713413957b..7379a435f4a 100644--- a/apps/ui-library/app/(app)/docs/[[...slug]]/page.tsx+++ b/apps/ui-library/app/(app)/docs/[[...slug]]/page.tsx@@ -1,4 +1,4 @@-import '@/styles/code-block-variables.css'+import 'config/code-block-variables.css'import '@/styles/mdx.css'import '@/styles/library-doc.css'diff --git a/apps/ui-library/styles/code-block-variables.css b/apps/ui-library/styles/code-block-variables.cssdeleted file mode 100644index a21af6b3751..00000000000--- a/apps/ui-library/styles/code-block-variables.css+++ /dev/null@@ -1,33 +0,0 @@-[data-theme='dark'],-.dark {- --code-token-keyword: #bda4ff;- --code-foreground: #ffffff;- --code-token-constant: #3ecf8e;- --code-token-string: #ffcda1;- --code-token-comment: #7e7e7e;- --code-token-parameter: #ffffff;- --code-token-function: #3ecf8e;- --code-token-string-expression: #ffcda1;- --code-token-punctuation: #ffffff;- --code-token-link: #ffffff;- --code-token-number: #ffffff;- --code-token-property: #3ecf8e;- --code-highlight-color: #232323;-}--[data-theme='light'],-.light {- --code-token-keyword: #6b35dc;- --code-foreground: oklch(from var(--foreground-light) l c h / 1);- --code-token-constant: #15593b;- --code-token-string: #c46a0a;- --code-token-comment: #7e7e7e;- --code-token-parameter: oklch(from var(--foreground-light) l c h / 1);- --code-token-function: #15593b;- --code-token-string-expression: #c46a0a;- --code-token-punctuation: oklch(from var(--foreground-light) l c h / 1);- --code-token-link: oklch(from var(--foreground-light) l c h / 1);- --code-token-number: oklch(from var(--foreground-light) l c h / 1);- --code-token-property: #15593b;- --code-highlight-color: #1c1c1c;-}diff --git a/apps/design-system/styles/code-block-variables.css b/packages/config/code-block-variables.csssimilarity index 63%rename from apps/design-system/styles/code-block-variables.cssrename to packages/config/code-block-variables.cssindex a21af6b3751..56c5bd7c9e8 100644--- a/apps/design-system/styles/code-block-variables.css+++ b/packages/config/code-block-variables.css@@ -1,10 +1,11 @@+/* Code block theme colors for use with Supabase Theme */[data-theme='dark'],.dark {--code-token-keyword: #bda4ff;--code-foreground: #ffffff;--code-token-constant: #3ecf8e;--code-token-string: #ffcda1;- --code-token-comment: #7e7e7e;+ --code-token-comment: #949494;--code-token-parameter: #ffffff;--code-token-function: #3ecf8e;--code-token-string-expression: #ffcda1;@@ -12,22 +13,27 @@--code-token-link: #ffffff;--code-token-number: #ffffff;--code-token-property: #3ecf8e;+ --code-token-variable: var(--code-foreground);--code-highlight-color: #232323;+ --shadow-codeblock:+ 0 0 0 0 var(--border-default), 0 1px 2px 0 rgba(0, 0, 0, 0.3), 0 1px 3px 0 rgba(0, 0, 0, 0.3);+ --drop-shadow-codeblock: drop-shadow(0 1px 1px rgba(0, 0, 0, 0.5));}-[data-theme='light'],.light {- --code-token-keyword: #6b35dc;+ --shadow-codeblock: 0 0 #0000;+ --code-token-keyword: #5f2fc4;--code-foreground: oklch(from var(--foreground-light) l c h / 1);--code-token-constant: #15593b;- --code-token-string: #c46a0a;- --code-token-comment: #7e7e7e;+ --code-token-string: #9a5200;+ --code-token-comment: #6a6a6a;--code-token-parameter: oklch(from var(--foreground-light) l c h / 1);--code-token-function: #15593b;- --code-token-string-expression: #c46a0a;+ --code-token-string-expression: #9a5200;--code-token-punctuation: oklch(from var(--foreground-light) l c h / 1);--code-token-link: oklch(from var(--foreground-light) l c h / 1);--code-token-number: oklch(from var(--foreground-light) l c h / 1);--code-token-property: #15593b;+ --code-token-variable: var(--code-foreground);--code-highlight-color: #1c1c1c;}diff --git a/packages/ui-patterns/package.json b/packages/ui-patterns/package.jsonindex 9bae29ade1d..71d033ec65c 100644--- a/packages/ui-patterns/package.json+++ b/packages/ui-patterns/package.json@@ -86,6 +86,18 @@"import": "./src/Chart/index.tsx","types": "./src/Chart/index.tsx"},+ "./CodeBlock/CodeBlock.highlight": {+ "import": "./src/CodeBlock/CodeBlock.highlight.ts",+ "types": "./src/CodeBlock/CodeBlock.highlight.ts"+ },+ "./CodeBlock/CodeBlock.theme": {+ "import": "./src/CodeBlock/CodeBlock.theme.ts",+ "types": "./src/CodeBlock/CodeBlock.theme.ts"+ },+ "./CodeBlock/CodeBlock.tokens": {+ "import": "./src/CodeBlock/CodeBlock.tokens.ts",+ "types": "./src/CodeBlock/CodeBlock.tokens.ts"+ },"./CodeBlock/CodeBlock": {"import": "./src/CodeBlock/CodeBlock.tsx","types": "./src/CodeBlock/CodeBlock.tsx"@@ -94,6 +106,23 @@"import": "./src/CodeBlock/CodeBlock.utils.ts","types": "./src/CodeBlock/CodeBlock.utils.ts"},+ "./CodeBlock/CodeBlockAnnotation": {+ "import": "./src/CodeBlock/CodeBlockAnnotation.tsx",+ "types": "./src/CodeBlock/CodeBlockAnnotation.tsx"+ },+ "./CodeBlock/CodeBlockControls": {+ "import": "./src/CodeBlock/CodeBlockControls.tsx",+ "types": "./src/CodeBlock/CodeBlockControls.tsx"+ },+ "./CodeBlock/CodeBlockFrame": {+ "import": "./src/CodeBlock/CodeBlockFrame.tsx",+ "types": "./src/CodeBlock/CodeBlockFrame.tsx"+ },+ "./CodeBlock/code-block.css": {+ "style": "./src/CodeBlock/code-block.css",+ "import": "./src/CodeBlock/code-block.css",+ "types": "./src/CodeBlock/code-block.css"+ },"./CodeBlock": {"import": "./src/CodeBlock/index.tsx","types": "./src/CodeBlock/index.tsx"@@ -567,6 +596,7 @@"types": "./src/PromoToast/index.ts"},"./PromoToast/styles.css": {+ "style": "./src/PromoToast/styles.css","import": "./src/PromoToast/styles.css","types": "./src/PromoToast/styles.css"},@@ -587,6 +617,7 @@"types": "./src/SelectionListState/index.ts"},"./ShimmeringLoader/index.css": {+ "style": "./src/ShimmeringLoader/index.css","import": "./src/ShimmeringLoader/index.css","types": "./src/ShimmeringLoader/index.css"},@@ -799,6 +830,7 @@"remark": "^15.0.1","remark-gfm": "^4.0.0","scroll-into-view-if-needed": "^3.1.0",+ "shiki": "catalog:","smol-toml": "^1.6.1","sonner": "^1.5.0","sql-formatter": "^15.0.0",diff --git a/packages/ui-patterns/scripts/update-exports.ts b/packages/ui-patterns/scripts/update-exports.tsindex f9848d9dbf5..93497004c9b 100644--- a/packages/ui-patterns/scripts/update-exports.ts+++ b/packages/ui-patterns/scripts/update-exports.ts@@ -6,6 +6,7 @@ const SRC_DIR = path.resolve(__dirname, '..', 'src')interface ExportMap {[key: string]: {+ style?: stringimport: stringtypes: string}@@ -33,6 +34,8 @@ function getAllSourceFiles(dir: string): ExportMap {const filePath = `./src/${relativePath.replace(/\\/g, '/')}`exportsMap[subpath] = {+ // tailwind resolves css @import with the "style" condition only+ ...(relativePath.endsWith('.css') && { style: filePath }),import: filePath,types: filePath,}diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.ts b/packages/ui-patterns/src/CodeBlock/CodeBlock.highlight.test.tssimilarity index 95%rename from apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.tsrename to packages/ui-patterns/src/CodeBlock/CodeBlock.highlight.test.tsindex 15996104ccd..c61325f11a2 100644--- a/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.test.ts+++ b/packages/ui-patterns/src/CodeBlock/CodeBlock.highlight.test.ts@@ -58,7 +58,8 @@ describe('shared code block highlighting', () => {)it('shares pending initialization across concurrent languages and aliases', async () => {- const { promise, resolve } = Promise.withResolvers<typeof highlighter>()+ let resolve: (value: typeof highlighter) => void = () => {}+ const promise = new Promise<typeof highlighter>((done) => (resolve = done))create.mockReturnValue(promise)const { highlightCode } = await import('./CodeBlock.highlight')const pending = [diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.highlight.ts b/packages/ui-patterns/src/CodeBlock/CodeBlock.highlight.tssimilarity index 100%rename from apps/docs/features/ui/CodeBlock/CodeBlock.highlight.tsrename to packages/ui-patterns/src/CodeBlock/CodeBlock.highlight.tsdiff --git a/packages/ui-patterns/src/CodeBlock/CodeBlock.theme.ts b/packages/ui-patterns/src/CodeBlock/CodeBlock.theme.tsnew file mode 100644index 00000000000..1133e8f8caa--- /dev/null+++ b/packages/ui-patterns/src/CodeBlock/CodeBlock.theme.ts@@ -0,0 +1,3 @@+import theme from './supabase-2.json' with { type: 'json' }++export const codeBlockTheme = themediff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.utils.test.ts b/packages/ui-patterns/src/CodeBlock/CodeBlock.tokens.test.tssimilarity index 94%rename from apps/docs/features/ui/CodeBlock/CodeBlock.utils.test.tsrename to packages/ui-patterns/src/CodeBlock/CodeBlock.tokens.test.tsindex 39d7d4a7361..12d6c58d457 100644--- a/apps/docs/features/ui/CodeBlock/CodeBlock.utils.test.ts+++ b/packages/ui-patterns/src/CodeBlock/CodeBlock.tokens.test.ts@@ -1,7 +1,7 @@import { readFileSync } from 'node:fs'import { describe, expect, it } from 'vitest'-import { getCodeBlockLabel, getTokenClassName } from './CodeBlock.utils'+import { getCodeBlockLabel, getTokenClassName } from './CodeBlock.tokens'import theme from './supabase-2.json' with { type: 'json' }const themeColors = (): Array<string> => {@@ -31,7 +31,7 @@ describe('token class names', () => {const colors = themeColors()expect(colors.length).toBeGreaterThan(0)- const css = readFileSync(new URL('../../../styles/code-block.css', import.meta.url), 'utf8')+ const css = readFileSync(`${import.meta.dirname}/code-block.css`, 'utf8')for (const color of colors) {expect(getTokenClassName(color, 0), `${color} is missing from the class table`).toMatch(/^s-[a-z]$/diff --git a/apps/docs/features/ui/CodeBlock/CodeBlock.utils.ts b/packages/ui-patterns/src/CodeBlock/CodeBlock.tokens.tssimilarity index 100%rename from apps/docs/features/ui/CodeBlock/CodeBlock.utils.tsrename to packages/ui-patterns/src/CodeBlock/CodeBlock.tokens.tsdiff --git a/packages/ui-patterns/src/CodeBlock/CodeBlockAnnotation.test.tsx b/packages/ui-patterns/src/CodeBlock/CodeBlockAnnotation.test.tsxnew file mode 100644index 00000000000..7e284d4ad55--- /dev/null+++ b/packages/ui-patterns/src/CodeBlock/CodeBlockAnnotation.test.tsx@@ -0,0 +1,44 @@+import { fireEvent, render, screen } from '@testing-library/react'+import { TooltipProvider } from 'ui'+import { describe, expect, it } from 'vitest'++import { AnnotatedSpan } from './CodeBlockAnnotation'++const renderSpan = () =>+ render(+ <TooltipProvider delayDuration={0}>+ <AnnotatedSpan+ content="createClient"+ className="s-v"+ annotations={[{ text: 'function createClient(): SupabaseClient' }]}+ />+ </TooltipProvider>+ )++const tap = (element: HTMLElement) => {+ fireEvent.pointerDown(element, { pointerType: 'touch' })+ fireEvent.click(element)+}++describe('AnnotatedSpan', () => {+ it('opens on a touch tap and closes on the next tap', () => {+ renderSpan()+ const trigger = screen.getByRole('button', { name: 'createClient' })++ tap(trigger)+ expect(screen.getByRole('tooltip')).toHaveTextContent('function createClient(): SupabaseClient')++ tap(trigger)+ expect(screen.queryByRole('tooltip')).toBeNull()+ })++ it('leaves a mouse click to radix, which keeps the tooltip closed', () => {+ renderSpan()+ const trigger = screen.getByRole('button', { name: 'createClient' })++ fireEvent.pointerDown(trigger, { pointerType: 'mouse' })+ fireEvent.click(trigger)++ expect(screen.queryByRole('tooltip')).toBeNull()+ })+})diff --git a/packages/ui-patterns/src/CodeBlock/CodeBlockAnnotation.tsx b/packages/ui-patterns/src/CodeBlock/CodeBlockAnnotation.tsxnew file mode 100644index 00000000000..6b356ad7cc4--- /dev/null+++ b/packages/ui-patterns/src/CodeBlock/CodeBlockAnnotation.tsx@@ -0,0 +1,85 @@+'use client'++import { useRef, useState, type MouseEvent, type PointerEvent } from 'react'+import { Tooltip, TooltipContent, TooltipTrigger } from 'ui/src/components/shadcn/ui/tooltip'+import { cn } from 'ui/src/lib/utils/cn'++// this type copies the twoslash hover fields, so the renderers do not depend on twoslash+export interface CodeAnnotation {+ text: string+ docs?: string+ tags?: Array<[name: string, text: string | undefined]>+}++interface AnnotatedSpanProps {+ content: string+ className: string | undefined+ annotations: Array<CodeAnnotation>+}++export const AnnotatedSpan = ({ content, className, annotations }: AnnotatedSpanProps) => {+ const [open, setOpen] = useState(false)++ // a tap gives no hover. null means the last press was not a touch+ const touchTapWasOpen = useRef<boolean | null>(null)++ const handlePointerDown = (evt: PointerEvent) => {+ touchTapWasOpen.current = evt.pointerType === 'touch' ? open : null+ }++ const handleClick = (evt: MouseEvent) => {+ const wasOpen = touchTapWasOpen.current+ touchTapWasOpen.current = null+ if (wasOpen === null) return+ // radix closes the tooltip on pointerdown and on click. preventDefault stops the close on click+ evt.preventDefault()+ evt.stopPropagation()+ setOpen(!wasOpen)+ }++ return (+ <Tooltip open={open} onOpenChange={setOpen}>+ <TooltipTrigger asChild onPointerDown={handlePointerDown} onClick={handleClick}>+ <button+ tabIndex={0}+ className={cn(+ className,+ 'any-pointer-coarse:underline any-pointer-coarse:underline-offset-4',+ 'any-pointer-coarse:decoration-dashed',+ 'any-pointer-coarse:decoration-[rgba(from_currentColor_r_g_b/0.5)]'+ )}+ >+ {content}+ </button>+ </TooltipTrigger>+ <TooltipContent className="max-w-[min(80vw,400px)] p-0 divide-y">+ {annotations.map((annotation, idx) => (+ <Annotation key={idx} annotation={annotation} />+ ))}+ </TooltipContent>+ </Tooltip>+ )+}++const Annotation = ({ annotation }: { annotation: CodeAnnotation }) => {+ const { text, docs, tags } = annotation+ return (+ <div data-code-style="plain" className="flex flex-col gap-2">+ <code className={cn('block bg-200 p-2', (docs || tags) && 'border-b border-default')}>+ {text}+ </code>+ {docs && <p className={cn('p-2', tags && 'border-b border-default')}>{docs}</p>}+ {tags && (+ <div className="p-2 flex flex-col">+ {tags.map((tag, idx) => {+ return (+ <span key={idx}>+ <code>@{tag[0]}</code> {tag[1]}+ </span>+ )+ })}+ </div>+ )}+ </div>+ )+}diff --git a/packages/ui-patterns/src/CodeBlock/CodeBlockControls.test.tsx b/packages/ui-patterns/src/CodeBlock/CodeBlockControls.test.tsxnew file mode 100644index 00000000000..24e1e824bf8--- /dev/null+++ b/packages/ui-patterns/src/CodeBlock/CodeBlockControls.test.tsx@@ -0,0 +1,63 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { TooltipProvider } from 'ui'+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { CodeBlockControls } from './CodeBlockControls'++const writeText = vi.fn<(text: string) => Promise<void>>()++const renderControls = () =>+ render(+ <TooltipProvider>+ <div className="shiki">+ <CodeBlockControls content="select 1" />+ </div>+ </TooltipProvider>+ )++describe('CodeBlockControls', () => {+ beforeEach(() => {+ writeText.mockReset().mockResolvedValue()+ vi.spyOn(document, 'hasFocus').mockReturnValue(true)+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })+ })++ it('copies the explicit source and announces success until blur', async () => {+ renderControls()+ const copy = screen.getByRole('button', { name: 'Copy code' })++ fireEvent.click(copy)++ await waitFor(() => expect(screen.getByText('Code copied')).toBeInTheDocument())+ expect(writeText).toHaveBeenCalledExactlyOnceWith('select 1')++ fireEvent.blur(copy)+ expect(screen.queryByText('Code copied')).toBeNull()+ })++ it('does not announce success when the clipboard write fails', async () => {+ writeText.mockRejectedValue(new Error('denied'))+ renderControls()++ fireEvent.click(screen.getByRole('button', { name: 'Copy code' }))++ await waitFor(() => expect(writeText).toHaveBeenCalled())+ expect(screen.queryByText('Code copied')).toBeNull()+ })++ it('sets the wrap flag on a direct child of the frame and announces each change', () => {+ const { container } = renderControls()+ const frame = container.querySelector('.shiki')+ // code-block.css matches the frame with :has(> [data-wrapped='true'])+ const wrapFlag = () => frame?.querySelector(":scope > [data-wrapped='true']")++ fireEvent.click(screen.getByRole('button', { name: 'Enable word wrap' }))+ expect(wrapFlag()).not.toBeNull()+ expect(frame).not.toHaveAttribute('data-wrapped')+ expect(screen.getByText('Word wrap enabled')).toBeInTheDocument()++ fireEvent.click(screen.getByRole('button', { name: 'Disable word wrap' }))+ expect(wrapFlag()).toBeNull()+ expect(screen.getByText('Word wrap disabled')).toBeInTheDocument()+ })+})diff --git a/packages/ui-patterns/src/CodeBlock/CodeBlockControls.tsx b/packages/ui-patterns/src/CodeBlock/CodeBlockControls.tsxnew file mode 100644index 00000000000..07605e44130--- /dev/null+++ b/packages/ui-patterns/src/CodeBlock/CodeBlockControls.tsx@@ -0,0 +1,146 @@+'use client'++import { ArrowRightFromLine, Check, Copy, WrapText, type LucideIcon } from 'lucide-react'+import { useEffect, useState } from 'react'+import { Button, cn, copyToClipboard, Tooltip, TooltipContent, TooltipTrigger } from 'ui'++export function CodeCopyButton({+ className,+ content,+ label = 'Copy code',+ copiedLabel = 'Code copied',+ onCopied,+}: {+ className?: string+ content: string+ label?: string+ copiedLabel?: string+ /** Runs after a successful clipboard write. */+ onCopied?: () => void+}) {+ const [copied, setCopied] = useState(false)++ useEffect(() => {+ if (!copied) return++ const timeout = window.setTimeout(() => setCopied(false), 2000)+ return () => window.clearTimeout(timeout)+ }, [copied])++ const handleCopy = async () => {+ copyToClipboard(content, () => {+ setCopied(true)+ onCopied?.()+ })+ }++ const resetStatus = () => {+ setCopied(false)+ }++ return (+ <>+ <span className="sr-only" aria-live="polite">+ {copied ? copiedLabel : ''}+ </span>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="outline"+ tabIndex={0}+ onClick={handleCopy}+ onBlur={resetStatus}+ className={cn(+ 'group/btn size-6 p-1 cursor-pointer bg-200 hover:border-strong',+ copied && 'bg-[var(--btn-active)]',+ 'hover:bg-[var(--btn-active)]',+ className+ )}+ aria-label={label}+ // the tooltip repeats the label, so screen readers read it twice+ aria-describedby={undefined}+ >+ <CrossfadeIcon active={copied} activeIcon={Check} inactiveIcon={Copy} />+ </Button>+ </TooltipTrigger>+ <TooltipContent>{label}</TooltipContent>+ </Tooltip>+ </>+ )+}++export function CodeBlockControls({ content }: { content: string }) {+ const [isWrapped, setIsWrapped] = useState(false)+ // Empty until the first toggle, so nothing is announced on mount+ const [wrapStatus, setWrapStatus] = useState('')++ const handleWrapToggle = () => {+ const newValue = !isWrapped+ setIsWrapped(newValue)+ setWrapStatus(newValue ? 'Word wrap enabled' : 'Word wrap disabled')+ }++ return (+ // code-block.css finds the frame from this flag, so the controls do not change the frame+ <div+ data-wrapped={isWrapped ? 'true' : undefined}+ className={cn(+ 'opacity-0 flex group-hover:opacity-100 group-focus-within:opacity-100 absolute top-[9.5px] right-[9.5px] gap-1',+ '[--btn-active:color-mix(in_srgb,var(--foreground)_4%,var(--background-200))]'+ )}+ >+ <span className="sr-only" aria-live="polite">+ {wrapStatus}+ </span>+ <Tooltip>+ <TooltipTrigger asChild>+ <Button+ variant="outline"+ tabIndex={0}+ onClick={handleWrapToggle}+ className={cn(+ 'group/btn size-6 p-1 cursor-pointer bg-200 hover:border-strong',+ 'hover:bg-[var(--btn-active)]'+ )}+ aria-label={isWrapped ? 'Disable word wrap' : 'Enable word wrap'}+ // the tooltip repeats the label, so screen readers read it twice+ aria-describedby={undefined}+ >+ <CrossfadeIcon+ active={isWrapped}+ activeIcon={ArrowRightFromLine}+ inactiveIcon={WrapText}+ />+ </Button>+ </TooltipTrigger>+ <TooltipContent>{isWrapped ? 'Disable word wrap' : 'Enable word wrap'}</TooltipContent>+ </Tooltip>+ <CodeCopyButton content={content} />+ </div>+ )+}++function CrossfadeIcon({+ active,+ activeIcon: ActiveIcon,+ inactiveIcon: InactiveIcon,+}: {+ active: boolean+ activeIcon: LucideIcon+ inactiveIcon: LucideIcon+}) {+ const iconClass = (shown: boolean) =>+ cn(+ 'absolute inset-0 m-auto text-lighter group-hover/btn:text-foreground',+ 'transition-[opacity,scale,filter,color] duration-300 [transition-timing-function:cubic-bezier(0.2,0,0,1)]',+ 'motion-reduce:transition-none',+ shown ? 'opacity-100 scale-100 blur-none' : 'opacity-0 scale-[0.25] blur-[4px]'+ )++ return (+ <span className="relative block size-3.5">+ <ActiveIcon size={14} aria-hidden="true" className={iconClass(active)} />+ <InactiveIcon size={14} aria-hidden="true" className={iconClass(!active)} />+ </span>+ )+}diff --git a/packages/ui-patterns/src/CodeBlock/CodeBlockFrame.test.tsx b/packages/ui-patterns/src/CodeBlock/CodeBlockFrame.test.tsxnew file mode 100644index 00000000000..aca781ac8dc--- /dev/null+++ b/packages/ui-patterns/src/CodeBlock/CodeBlockFrame.test.tsx@@ -0,0 +1,53 @@+import { renderToStaticMarkup } from 'react-dom/server'+import { describe, expect, it } from 'vitest'++import { CodeBlockFrame, CodeBlockTokens, type CodeToken } from './CodeBlockFrame'++const LINES: Array<Array<CodeToken>> = [+ [+ ['const ', 's-k'],+ ["html = '<b>&</b>'", 's-s'],+ ],+ [],+ [['// done', 's-c s-i']],+]+const SOURCE = "const html = '<b>&</b>'\n\n// done"++const renderFrame = (lineNumbers: boolean) => {+ const container = document.createElement('div')+ container.innerHTML = renderToStaticMarkup(+ <CodeBlockFrame lang="ts" lineCount={LINES.length}>+ <CodeBlockTokens lines={LINES} lineNumbers={lineNumbers} />+ </CodeBlockFrame>+ )+ return container+}++describe('CodeBlockFrame', () => {+ it('renders readable, escaped, numbered code without controls or nested pre', () => {+ const container = renderFrame(true)+ const lines = [...container.querySelectorAll('.code-line-content')].map((el) => el.textContent)++ expect(lines.join('\n')).toBe(SOURCE)+ expect(+ [...container.querySelectorAll('.code-line-number')].map((el) => el.textContent)+ ).toEqual(['1', '2', '3'])+ expect(container.querySelectorAll('pre')).toHaveLength(1)+ expect(container.querySelector('button')).toBeNull()+ expect(container.querySelector('.code-scroll')).toHaveAttribute(+ 'aria-label',+ 'TypeScript, 3 lines'+ )+ expect(container.querySelector('[style]')).toBeNull()+ })++ it('keeps gutters out of the unnumbered layout', () => {+ const container = renderFrame(false)+ const lines = [...container.querySelectorAll('.code-content > span')].map(+ (el) => el.textContent+ )++ expect(lines.join('\n')).toBe(SOURCE)+ expect(container.querySelector('.code-line-number')).toBeNull()+ })+})diff --git a/packages/ui-patterns/src/CodeBlock/CodeBlockFrame.tsx b/packages/ui-patterns/src/CodeBlock/CodeBlockFrame.tsxnew file mode 100644index 00000000000..6af1d48e0b5--- /dev/null+++ b/packages/ui-patterns/src/CodeBlock/CodeBlockFrame.tsx@@ -0,0 +1,117 @@+import { type ReactNode } from 'react'+import { cn } from 'ui/src/lib/utils/cn'++import { getCodeBlockLabel } from './CodeBlock.tokens'+import { AnnotatedSpan, type CodeAnnotation } from './CodeBlockAnnotation'++export type CodeToken = [+ content: string,+ className: string | undefined,+ annotations?: Array<CodeAnnotation>,+]++export interface CodeBlockFrameProps {+ className?: string+ lang: string | null+ lineCount: number+ compact?: boolean+ controls?: ReactNode+ children: ReactNode+}++export interface CodeBlockTokensProps {+ lines: Array<Array<CodeToken>>+ lineNumbers: boolean+}++export const CodeBlockFrame = ({+ className,+ lang,+ lineCount,+ compact = false,+ controls,+ children,+}: CodeBlockFrameProps) => (+ <div+ className={cn(+ 'shiki',+ 'group',+ 'relative has-[.code-scroll:focus-visible]:z-1',+ 'has-[.code-scroll:focus-visible]:outline-2 has-[.code-scroll:focus-visible]:outline-ring',+ 'not-prose',+ 'w-full',+ compact ? 'border-0 my-0!' : 'border border-default rounded-lg shadow-codeblock',+ 'bg-200',+ 'text-sm',+ className+ )}+ >+ <div+ className={cn(+ 'code-scroll',+ 'w-full overflow-x-auto overscroll-x-none',+ !compact && 'rounded-lg',+ 'focus-visible:outline-hidden'+ )}+ role="group"+ aria-roledescription="code block"+ aria-label={getCodeBlockLabel(lang, lineCount)}+ tabIndex={0}+ >+ {children}+ </div>+ {/* After the code so the block is named before its controls, and outside the scroller so they stay pinned */}+ {controls}+ </div>+)++export const CodeBlockTokens = ({ lines, lineNumbers }: CodeBlockTokensProps) => (+ <pre>+ <code+ className={cn(+ '[contain:content]',+ lineNumbers && 'grid grid-cols-[auto_1fr] w-fit min-w-full py-3',+ '[--row-rest:var(--background-200)]',+ '[--row-hover:color-mix(in_srgb,var(--foreground)_3%,var(--background-200))]'+ )}+ >+ {lineNumbers ? (+ lines.map((line, idx) => (+ <div key={idx} className="group/row contents">+ <div aria-hidden="true" className="code-line-number">+ {idx + 1}+ </div>+ <div className="code-content code-line-content">+ <CodeLine tokens={line} />+ </div>+ </div>+ ))+ ) : (+ <div className="code-content p-6">+ {lines.map((line, idx) => (+ <CodeLine key={idx} tokens={line} />+ ))}+ </div>+ )}+ </code>+ </pre>+)++const CodeLine = ({ tokens }: { tokens: Array<CodeToken> }) => (+ <span className="block min-h-5 leading-5">+ {tokens.map(([content, className, annotations], idx) =>+ annotations ? (+ <AnnotatedSpan+ key={idx}+ content={content}+ className={className}+ annotations={annotations}+ />+ ) : (+ <span key={idx} className={className}>+ {content}+ </span>+ )+ )}+ </span>+)diff --git a/packages/ui-patterns/src/CodeBlock/code-block.css b/packages/ui-patterns/src/CodeBlock/code-block.cssnew file mode 100644index 00000000000..d6fecc3317b--- /dev/null+++ b/packages/ui-patterns/src/CodeBlock/code-block.css@@ -0,0 +1,77 @@+@import 'config/code-block-variables.css';++@utility code-line-number {+ @apply select-none text-right text-muted/70 pl-3 pr-2 min-h-5 leading-5;+ @apply bg-[var(--row-rest)] sticky left-0 z-10;+ @apply group-hover/row:text-muted group-hover/row:bg-[var(--row-hover)];+ @apply after:pointer-events-none after:absolute after:inset-y-0 after:left-full after:w-4;+ @apply [--gutter-fade:var(--row-rest)] group-hover/row:[--gutter-fade:var(--row-hover)];+ @apply after:bg-[image:linear-gradient(to_right,var(--gutter-fade)_0%,color-mix(in_srgb,var(--gutter-fade)_85%,transparent)_25%,color-mix(in_srgb,var(--gutter-fade)_50%,transparent)_50%,color-mix(in_srgb,var(--gutter-fade)_15%,transparent)_75%,transparent_100%)];+}++@utility code-line-content {+ @apply min-h-5 leading-5 pl-3 pr-18 group-hover/row:bg-[var(--row-hover)];+}++/* Code blocks need margin applied when in content container */+.prose :where(.shiki, .shiki-wrapper):where(:not(.shiki-wrapper *)) {+ margin-block: 2rem;+}++/* Token classes emitted by CodeBlock.tokens.ts */+.shiki .s-f {+ color: var(--code-foreground);+}+.shiki .s-c {+ color: var(--code-token-comment);+}+.shiki .s-n {+ color: var(--code-token-constant);+}+.shiki .s-u {+ color: var(--code-token-function);+}+.shiki .s-k {+ color: var(--code-token-keyword);+}+.shiki .s-a {+ color: var(--code-token-parameter);+}+.shiki .s-r {+ color: var(--code-token-property);+}+.shiki .s-p {+ color: var(--code-token-punctuation);+}+.shiki .s-s {+ color: var(--code-token-string);+}+.shiki .s-e {+ color: var(--code-token-string-expression);+}+.shiki .s-v {+ color: var(--code-token-variable);+}+.shiki .s-i {+ font-style: italic;+}+.shiki .s-b {+ font-weight: bold;+}+.shiki .s-l {+ text-decoration: underline;+}++/* Word wrap styles for code blocks */+.shiki:has(> [data-wrapped='true']) .code-scroll {+ overflow-x: hidden !important;+}++.shiki:has(> [data-wrapped='true']) .code-content {+ white-space: pre-wrap !important;+ overflow-wrap: anywhere !important;+}++.shadow-codeblock {+ box-shadow: var(--shadow-codeblock, none);+}diff --git a/apps/docs/features/ui/CodeBlock/supabase-2.json b/packages/ui-patterns/src/CodeBlock/supabase-2.jsonsimilarity index 100%rename from apps/docs/features/ui/CodeBlock/supabase-2.jsonrename to packages/ui-patterns/src/CodeBlock/supabase-2.jsondiff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8b9f6ab5d66..9e9fb6aa8a9 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -783,6 +783,9 @@ importers:gray-matter:specifier: ^4.0.3version: 4.0.3+ hast-util-from-html:+ specifier: ^2.0.3+ version: 2.0.3lucide-react:specifier: 'catalog:'version: 1.55.0(@types/[email protected])([email protected])@@ -820,6 +823,9 @@ importers:specifier: ^2.9.0version: 2.9.0devDependencies:+ '@astrojs/markdown-satteri':+ specifier: 0.3.8+ version: 0.3.8'@tailwindcss/vite':specifier: 4.2.4version: 4.2.4([email protected](@types/[email protected])([email protected])([email protected])([email protected])([email protected])([email protected])([email protected]))@@ -3029,6 +3035,9 @@ importers:scroll-into-view-if-needed:specifier: ^3.1.0version: 3.1.0+ shiki:+ specifier: 'catalog:'+ version: 4.5.0smol-toml:specifier: ^1.6.1version: 1.9.0@@ -13014,9 +13023,6 @@ packages:resolution: {integrity: sha512-zJfpXq44yff2hmE0XmwEOzdWin5xwH+QIhMLOScpX91e/NSGPsAzNCvLQDIEPyO2TXi+lBmU6hjLIhV8MwP2kw==}- resolution: {integrity: sha512-RXQBLMl9kjKVNkJTIO6bZyb2n+cUH8LFaSSzo82jiLT6Tfc+Pt7VQCS+/h3YwG4jaNE2TA2sdJisGWR+aJrp0g==}-resolution: {integrity: sha512-CUSRHXyKjzHov8yKsQjGOElXy/3EKpyX56ELnkHH34vDVw1N1XSQ1ZcAvTyAPtGqLTuKP/uxM+aLkSPqF/EtMw==}@@ -30911,18 +30917,9 @@ snapshots:dependencies:'@types/hast': 3.0.5hast-util-from-dom: 5.0.0- hast-util-from-html: 2.0.1+ hast-util-from-html: 2.0.3unist-util-remove-position: 5.0.0- dependencies:- '@types/hast': 3.0.5- devlop: 1.1.0- hast-util-from-parse5: 8.0.1- parse5: 7.3.0- vfile: 6.0.3- vfile-message: 4.0.2-dependencies:'@types/hast': 3.0.5