Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

Implement line highlighting for code blocks

Joshen Lim48c1e2846de4
diff --git a/apps/docs/components/CodeBlock/CodeBlock.tsx b/apps/docs/components/CodeBlock/CodeBlock.tsx
index 71b89056de2..463a6062c36 100644
--- a/apps/docs/components/CodeBlock/CodeBlock.tsx
+++ b/apps/docs/components/CodeBlock/CodeBlock.tsx
@@ -17,6 +17,7 @@ import { useTheme } from '../Providers'
interface Props {
title?: string
language: 'js' | 'jsx' | 'sql' | 'py' | 'bash' | 'ts' | 'dart'
+ linesToHighlight?: number[]
hideCopy?: boolean
hideLineNumbers?: boolean
className?: string
@@ -27,13 +28,13 @@ interface Props {
const CodeBlock: FC<Props> = ({
title,
language,
+ linesToHighlight = [],
className,
value,
children,
hideCopy = false,
hideLineNumbers = false,
}) => {
- console.log('CodeBlock', { title })
const { isDarkMode } = useTheme()
const monokaiTheme = monokaiCustomTheme(isDarkMode)
@@ -46,9 +47,9 @@ const CodeBlock: FC<Props> = ({
}, 1000)
}
- let xxxlang = language ? language : className ? className.replace('language-', '') : 'js'
+ let lang = language ? language : className ? className.replace('language-', '') : 'js'
// force jsx to be js highlighted
- if (xxxlang === 'jsx') xxxlang = 'js'
+ if (lang === 'jsx') lang = 'js'
SyntaxHighlighter.registerLanguage('js', js)
SyntaxHighlighter.registerLanguage('ts', ts)
SyntaxHighlighter.registerLanguage('py', py)
@@ -56,11 +57,9 @@ const CodeBlock: FC<Props> = ({
SyntaxHighlighter.registerLanguage('bash', bash)
SyntaxHighlighter.registerLanguage('dart', dart)
- // const large = props.size === 'large' ? true : false
const large = false
-
// don't show line numbers if bash == lang
- const showLineNumbers = hideLineNumbers || xxxlang !== 'bash'
+ const showLineNumbers = hideLineNumbers || lang !== 'bash'
return (
<div className="relative my-2">
@@ -71,7 +70,7 @@ const CodeBlock: FC<Props> = ({
)}
{className ? (
<SyntaxHighlighter
- language={xxxlang}
+ language={lang}
wrapLines={true}
style={monokaiTheme}
className={[
@@ -84,6 +83,14 @@ const CodeBlock: FC<Props> = ({
lineHeight: large ? 1.5 : 1.4,
}}
showLineNumbers={showLineNumbers}
+ lineProps={(lineNumber) => {
+ if (linesToHighlight.includes(lineNumber)) {
+ return {
+ style: { display: 'block', backgroundColor: 'var(--colors-scale6)' },
+ }
+ }
+ return {}
+ }}
lineNumberContainerStyle={{
paddingTop: '128px',
}}
diff --git a/apps/docs/components/CodeBlock/CodeBlock.utils.js b/apps/docs/components/CodeBlock/CodeBlock.utils.js
index e4e6aba3e26..48b62cffc1e 100644
--- a/apps/docs/components/CodeBlock/CodeBlock.utils.js
+++ b/apps/docs/components/CodeBlock/CodeBlock.utils.js
@@ -1,3 +1,32 @@
+// https://github.com/euank/node-parse-numeric-range/blob/master/index.js
+export function parseNumericRange(string) {
+ let res = []
+ let m
+
+ for (let str of string.split(',').map((str) => str.trim())) {
+ // just a number
+ if (/^-?\d+$/.test(str)) {
+ res.push(parseInt(str, 10))
+ } else if ((m = str.match(/^(-?\d+)(-|\.\.\.?|\u2025|\u2026|\u22EF)(-?\d+)$/))) {
+ // 1-5 or 1..5 (equivalent) or 1...5 (doesn't include 5)
+ let [_, lhs, sep, rhs] = m
+
+ if (lhs && rhs) {
+ lhs = parseInt(lhs)
+ rhs = parseInt(rhs)
+ const incr = lhs < rhs ? 1 : -1
+
+ // Make it inclusive by moving the right 'stop-point' away by one.
+ if (sep === '-' || sep === '..' || sep === '\u2025') rhs += incr
+
+ for (let i = lhs; i !== rhs; i += incr) res.push(i)
+ }
+ }
+ }
+
+ return res
+}
+
const monokaiCustomTheme = (isDarkMode) => {
return {
hljs: {
diff --git a/apps/docs/components/index.tsx b/apps/docs/components/index.tsx
index 967c94e5007..f97096022d1 100644
--- a/apps/docs/components/index.tsx
+++ b/apps/docs/components/index.tsx
@@ -4,6 +4,7 @@ import { Tabs, Alert } from 'ui'
import Admonition from './Admonition'
import ButtonCard from './ButtonCard'
import CodeBlock from './CodeBlock/CodeBlock'
+import { parseNumericRange } from './CodeBlock/CodeBlock.utils'
// Page specific components
import Frameworks from './Frameworks'
@@ -48,8 +49,8 @@ const components = {
</Heading>
),
code: (props: any) => {
- console.log('code', props)
- return <CodeBlock {...props} />
+ const linesToHighlight = parseNumericRange(props.lines ?? '')
+ return <CodeBlock {...props} linesToHighlight={linesToHighlight} />
},
mono: (props: any) => <code className="text-sm">{props.children}</code>,
}
diff --git a/apps/docs/docs/guides/auth/auth-helpers/auth-ui.mdx b/apps/docs/docs/guides/auth/auth-helpers/auth-ui.mdx
index 47deeed3b01..14e94ea0170 100644
--- a/apps/docs/docs/guides/auth/auth-helpers/auth-ui.mdx
+++ b/apps/docs/docs/guides/auth/auth-helpers/auth-ui.mdx
@@ -41,17 +41,17 @@ This renders the Auth component without any styling.
We recommend using one of the predefined themes to style the UI.
Import the theme you want to use and pass it to the `appearence.theme` prop.
-```js title=/src/index.js
+```js lines=4,11 title=/src/index.js
import {
Auth,
- // highlight-next-line
+ // Import predefined theme
ThemeSupa,
} from '@supabase/auth-ui-react'
const App = () => (
<Auth
supabaseClient={supabase}
- // highlight-next-line
+ {/* Apply predefined theme */}
appearance={{ theme: ThemeSupa }}
/>
)
@@ -72,9 +72,8 @@ There are several ways to customize Auth UI:
Auth UI comes with several themes to customize the appearance. Each predefined theme comes with at least two variations, a `default` variation, and a `dark` variation. You can switch between these themes using the `theme` prop. Import the theme you want to use and pass it to the `appearence.theme` prop.
-```js title=/src/index.js
+```js lines=2,10 title=/src/index.js
import { createClient } from '@supabase/supabase-js'
-//highlight-next-line
import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
const supabase = createClient('<INSERT PROJECT URL>', '<INSERT PROJECT ANON API KEY>')
@@ -82,7 +81,7 @@ const supabase = createClient('<INSERT PROJECT URL>', '<INSERT PROJECT ANON API
const App = () => (
<Auth
supabaseClient={supabase}
- // highlight-next-line
+ {/* Apply predefined theme */}
appearance={{ theme: ThemeSupa }}
/>
)
@@ -98,7 +97,7 @@ Currently there is only one predefined theme available, but we plan to add more.
Auth UI comes with two theme variations: `default` and `dark`. You can switch between these themes with the `theme` prop.
-```js title=/src/index.js
+```js lines=11 title=/src/index.js
import { createClient } from '@supabase/supabase-js'
import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
@@ -108,7 +107,7 @@ const App = () => (
<Auth
supabaseClient={supabase}
appearance={{ theme: ThemeSupa }}
- // highlight-next-line
+ {/* Set theme to dark */}
theme="dark"
/>
)
@@ -120,7 +119,7 @@ If you don't pass a value to `theme` it uses the `"default"` theme. You can pass
Auth UI themes can be overridden using variable tokens. See the [list of variable tokens](https://github.com/supabase-community/auth-ui/blob/main/packages/react/common/theming/Themes.tsx).
-```js title=/src/index.js
+```js lines=11-18 title=/src/index.js
import { createClient } from '@supabase/supabase-js'
import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
@@ -131,7 +130,6 @@ const App = () => (
supabaseClient={supabase}
appearance={{
theme: ThemeSupa,
- // highlight-start
variables: {
default: {
colors: {
@@ -140,7 +138,6 @@ const App = () => (
},
},
},
- // highlight-end
}}
/>
)
diff --git a/apps/docs/docs/guides/auth/auth-helpers/nextjs.mdx b/apps/docs/docs/guides/auth/auth-helpers/nextjs.mdx
index 075adea1150..6743884e577 100644
--- a/apps/docs/docs/guides/auth/auth-helpers/nextjs.mdx
+++ b/apps/docs/docs/guides/auth/auth-helpers/nextjs.mdx
@@ -104,16 +104,14 @@ function MyApp({ Component, pageProps }) {
Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:
-```tsx title=pages/_app.tsx
+```tsx lines=2,8 title=pages/_app.tsx
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
-// highlight-next-line
import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'
function MyApp({
Component,
pageProps,
}: AppProps<{
- // highlight-next-line
initialSession: Session
}>) {
// Create a new supabase browser client on every first render.
@@ -183,7 +181,7 @@ export default async (req: NextApiRequest, res: NextApiResponse) => {
For [row level security](https://supabase.com/docs/learn/auth-deep-dive/auth-row-level-security) to work properly when fetching data client-side, you need to make sure to use the `supabaseClient` from the `useSupabaseClient` hook and only run your query once the user is defined client-side in the `useUser()` hook:
-```jsx
+```jsx lines=10-17
import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
import { useUser, useSupabaseClient } from '@supabase/auth-helpers-react'
import { useEffect, useState } from 'react'
@@ -193,7 +191,6 @@ const LoginPage = () => {
const user = useUser()
const [data, setData] = useState()
- // highlight-start
useEffect(() => {
async function loadData() {
const { data } = await supabaseClient.from('test').select('*')
@@ -202,7 +199,6 @@ const LoginPage = () => {
// Only run query once user is logged in.
if (user) loadData()
}, [user])
- // highlight-end
if (!user)
return (
diff --git a/apps/docs/docs/guides/functions/auth.mdx b/apps/docs/docs/guides/functions/auth.mdx
index c3a5965732b..6918f10c040 100644
--- a/apps/docs/docs/guides/functions/auth.mdx
+++ b/apps/docs/docs/guides/functions/auth.mdx
@@ -17,7 +17,7 @@ By creating a supabase client with the auth context from the function, you can d
1. Get the user object.
2. Run queries in the context of the user with [Row Level Security (RLS)](/docs/guides/auth/row-level-security) policies enforced.
-```js title=supabase/functions/select-from-table-with-auth-rls/index.ts
+```js lines=14,17-19,22-23 title=supabase/functions/select-from-table-with-auth-rls/index.ts
import { serve } from 'https://deno.land/[email protected]/http/server.ts'
import { createClient } from 'https://esm.sh/@supabase/[email protected]'
@@ -31,21 +31,16 @@ serve(async (req: Request) => {
Deno.env.get('SUPABASE_ANON_KEY') ?? '',
// Create client with Auth context of the user that called the function.
// This way your row-level-security (RLS) policies are applied.
- // highlight-next-line
{ global: { headers: { Authorization: req.headers.get('Authorization')! } } }
)
// Now we can get the session or user object
- // highlight-start
const {
data: { user },
} = await supabaseClient.auth.getUser()
- // highlight-end
// And we can run queries in the context of our authenticated user
- // highlight-start
const { data, error } = await supabaseClient.from('users').select('*')
if (error) throw error
- // highlight-end
return new Response(JSON.stringify({ user, data }), {
headers: { 'Content-Type': 'application/json' },
diff --git a/apps/docs/docs/guides/with-nextjs.mdx b/apps/docs/docs/guides/with-nextjs.mdx
index bc2674fd0cb..030b1d41594 100644
--- a/apps/docs/docs/guides/with-nextjs.mdx
+++ b/apps/docs/docs/guides/with-nextjs.mdx
@@ -129,16 +129,14 @@ export default MyApp
Wrap your `pages/_app.tsx` component with the `SessionContextProvider` component:
-```jsx title=pages/_app.tsx
+```jsx lines=2,8 title=pages/_app.tsx
import { createBrowserSupabaseClient } from '@supabase/auth-helpers-nextjs'
-// highlight-next-line
import { SessionContextProvider, Session } from '@supabase/auth-helpers-react'
function MyApp({
Component,
pageProps,
}: AppProps<{
- // highlight-next-line
initialSession: Session,
}>) {
const [supabaseClient] = useState(() => createBrowserSupabaseClient())
@@ -454,10 +452,9 @@ export default function Account({ session }: { session: Session }) {
Now that we have all the components in place, let's update `pages/index.js`:
-```jsx title=pages/index.js
+```jsx lines=3,14 title=pages/index.js
import { Auth, ThemeSupa } from '@supabase/auth-ui-react'
import { useSession, useSupabaseClient } from '@supabase/auth-helpers-react'
-// highlight-next-line
import Account from '../components/Account'
const Home = () => {
@@ -469,7 +466,6 @@ const Home = () => {
{!session ? (
<Auth supabaseClient={supabase} appearance={{ theme: ThemeSupa }} theme="dark" />
) : (
- // highlight-next-line
<Account session={session} />
)}
</div>