Skip to content

Commit

Permalink
chore: undraft line numbers transformer
Browse files Browse the repository at this point in the history
  • Loading branch information
o-az committed Nov 3, 2024
1 parent ce259f5 commit 562bd7f
Show file tree
Hide file tree
Showing 9 changed files with 151 additions and 140 deletions.
24 changes: 0 additions & 24 deletions docs/astro.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,6 @@ import {
rehypePrettyCode,
type RehypePrettyCodeOptions,
} from 'rehype-pretty-code';
import {
transformerNotationDiff,
transformerNotationFocus,
transformerMetaHighlight,
transformerRenderWhitespace,
transformerNotationHighlight,
transformerCompactLineOptions,
transformerNotationErrorLevel,
transformerNotationWordHighlight,
} from '@shikijs/transformers';
import {
transformerCopyButton,
transformerLineNumbers,
Expand All @@ -27,7 +17,6 @@ import { rehypeHeadingIds } from '@astrojs/markdown-remark';
import rehypeAutolinkHeadings from 'rehype-autolink-headings';
import starlightHeadingBadges from 'starlight-heading-badges';
import starlightLinksValidator from 'starlight-links-validator';
import { transformerTwoslash, rendererRich } from '@shikijs/twoslash';
import moonlightTheme from './public/theme/moonlight-ii.json' with {
type: 'json',
};
Expand Down Expand Up @@ -55,24 +44,11 @@ export default defineConfig({
keepBackground: true,
theme: moonlightTheme as unknown as RawTheme,
transformers: [
// twoslash is WIP
transformerTwoslash({
explicitTrigger: true,
renderer: rendererRich(),
}),
transformerCopyButton({
visibility: 'always',
feedbackDuration: 2_500,
}),
transformerLineNumbers({ autoApply: false }),
transformerNotationDiff(),
transformerNotationFocus(),
transformerMetaHighlight(),
transformerRenderWhitespace(),
transformerNotationHighlight(),
transformerCompactLineOptions(),
transformerNotationErrorLevel(),
transformerNotationWordHighlight(),
],
} satisfies RehypePrettyCodeOptions,
],
Expand Down
3 changes: 1 addition & 2 deletions docs/src/content/docs/plugins/line-numbers.mdx
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
---
title: Line Numbers
draft: true
description: A shiki transformer that adds line numbers to code blocks
---
import { Aside, Badge } from '@astrojs/starlight/components';
Expand Down Expand Up @@ -31,7 +30,7 @@ You can use this as a [`shiki` transformer](https://shiki.style/guide/transforme

### Examples

#### with `rehype-pretty-code`
###### with `rehype-pretty-code`

```ts
import { unified } from 'unified'
Expand Down
11 changes: 6 additions & 5 deletions examples/next/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,14 @@
* @typedef {import('webpack').Configuration} WebpackConfiguration
*/

import { rehypePrettyCode } from 'rehype-pretty-code';
import nextMDX from '@next/mdx';
import rehypeSlug from 'rehype-slug';
import { transformerCopyButton } from '@rehype-pretty/transformers';
import { rehypePrettyCode } from 'rehype-pretty-code';
import moonlightTheme from './assets/moonlight-ii.json' with { type: 'json' };
import {
transformerCopyButton,
transformerLineNumbers,
} from '@rehype-pretty/transformers';

/** @type {NextConfigPlugins} */
const plugins = [];
Expand All @@ -19,9 +22,6 @@ const nextConfig = {
cleanDistDir: true,
reactStrictMode: true,
poweredByHeader: false,
experimental: {
useLightningcss: false, // lightningcss doesn't work with postcss-loader
},
pageExtensions: ['md', 'mdx', 'tsx', 'ts', 'jsx', 'js'],
env: {
NEXT_TELEMETRY_DISABLED: '1',
Expand All @@ -39,6 +39,7 @@ const options = {
visibility: 'always',
feedbackDuration: 2_500,
}),
transformerLineNumbers({ autoApply: false }),
],
};

Expand Down
14 changes: 7 additions & 7 deletions examples/sveltekit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,13 @@
"tailwindcss": "4.0.0-alpha.20"
},
"devDependencies": {
"@sveltejs/adapter-static": "^3.0.4",
"@sveltejs/kit": "^2.5.26",
"@sveltejs/vite-plugin-svelte": "^3.1.2",
"magic-string": "^0.30.11",
"svelte": "5.0.0-next.242",
"svelte-check": "^4.0.1",
"tslib": "^2.7.0",
"@sveltejs/adapter-static": "^3.0.6",
"@sveltejs/kit": "^2.7.4",
"@sveltejs/vite-plugin-svelte": "^4.0.0",
"magic-string": "^0.30.12",
"svelte": "^5.1.9",
"svelte-check": "^4.0.5",
"tslib": "^2.8.1",
"typescript": "^5.6.3",
"vite": "^5.4.10"
}
Expand Down
2 changes: 1 addition & 1 deletion examples/sveltekit/src/routes/+page.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export const load = (async (_event) => {
import: 'default',
});

const parsedSnippets = [];
const parsedSnippets: Array<{ filename: string; code: string }> = [];
for await (const [path, snippetPromise] of Object.entries(rawSnippets)) {
const filename = path.split('/').pop();
if (!filename) throw new Error('Invalid filename');
Expand Down
88 changes: 67 additions & 21 deletions packages/transformers/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ You can use this as a [`shiki` transformer](https://shiki.style/guide/transforme
- `feedbackDuration`: `number` (default: `3_000`)
- `copyIcon`: `string` (default: an inline SVG of a copy icon)
- `successIcon`: `string` (default: an inline SVG of a green checkmark icon)
- `jsx`: `boolean` (default: `false`) (required as `true` for React-based usage)

### `transformerLineNumbers`

Expand All @@ -38,15 +39,15 @@ You can use this as a [`shiki` transformer](https://shiki.style/guide/transforme

#### Examples

##### with `rehype-pretty-code`
##### direct

```ts
import { unified } from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
import rehypePrettyCode from 'rehype-pretty-code'
import { transformerCopyButton, transformerLineNumbers } from '@rehype-pretty/transformers'
import { rehypePrettyCode } from 'rehype-pretty-code'
import { transformerCopyButton } from '@rehype-pretty/transformers'

const file = await unified()
.use(remarkParse)
Expand All @@ -57,7 +58,7 @@ You can use this as a [`shiki` transformer](https://shiki.style/guide/transforme
visibility: 'always',
feedbackDuration: 3_000,
}),
transformerLineNumbers({ autoApply: true }),
transformerLineNumbers({ autoApply: false }),
],
})
.use(rehypeStringify)
Expand All @@ -66,21 +67,66 @@ You can use this as a [`shiki` transformer](https://shiki.style/guide/transforme
console.log(String(file))
```

##### with `shiki`
##### In React / Next.js

In Next.js you st it up in `next.config.js` as you'd expect with `jsx: true`

```js
// next.config.js
import nextMDX from '@next/mdx';
import rehypeSlug from 'rehype-slug';
import { rehypePrettyCode } from 'rehype-pretty-code';
import { transformerCopyButton } from '@rehype-pretty/transformers';
const plugins = [];
const nextConfig = {
output: 'export',
pageExtensions: ['md', 'mdx', 'tsx', 'ts', 'jsx', 'js'],
};
const const rehypePrettyCodeOptions = {
theme: 'github-dark',
keepBackground: false,
transformers: [
transformerCopyButton({
jsx: true, // required for React
visibility: 'always',
feedbackDuration: 2_500,
}),
],
};
plugins.push(
nextMDX({
extension: /\.(md|mdx)$/,
options: {
remarkPlugins: [],
rehypePlugins: [[rehypePrettyCode, rehypePrettyCodeOptions], rehypeSlug],
},
}),
);
export default () => plugins.reduce((_, plugin) => plugin(_), nextConfig);
```

```ts
import { codeToHtml } from 'shiki'
import { transformerCopyButton, transformerLineNumbers } from '@rehype-pretty/transformers'
const code = await codeToHtml('console.log("Hello World")', {
lang: 'ts',
theme: 'vitesse-light',
transformers: [
transformerCopyButton({
visibility: 'always',
feedbackDuration: 3_000,
}),
transformerLineNumbers({ autoApply: true }),
]
})
```
Then in your client component, import the `registerCopyButton` function and call it in your the outermost **client** component.

```tsx
'use client';
import { registerCopyButton } from '@rehype-pretty/transformers';
export default function Home() {
React.useEffect(() => {
registerCopyButton();
}, []);
return (
<MDXProvider disableParentContext={false}>
<Index />
</MDXProvider>
);
}
```
4 changes: 2 additions & 2 deletions packages/transformers/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@rehype-pretty/transformers",
"description": "Shiki transformer that adds a copy button to code blocks",
"description": "Shiki transformers to add interactivity to code blocks",
"version": "0.13.2",
"homepage": "https://rehype-pretty.pages.dev",
"type": "module",
Expand Down Expand Up @@ -33,8 +33,8 @@
"devDependencies": {
"@arethetypeswrong/cli": "^0.16.4",
"@types/node": "^22.8.6",
"shiki": "^1.22.2",
"tsup": "^8.3.5",
"tsx": "^4.19.2",
"typescript": "^5.6.3"
},
"engines": {
Expand Down
23 changes: 23 additions & 0 deletions packages/transformers/src/line-numbers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,26 @@ interface LineNumbersOptions {
autoApply?: boolean;
}

/**
* A transformer that adds line numbers to code blocks.
* @param {Object} options - Options for the line numbers behavior and appearance.
* @param {boolean} options.autoApply - Whether to apply line numbers automatically to every code block.
* @returns A Shiki transformer.
*
* @example
* ```ts
* import { codeToHtml } from 'shiki'
* import { transformerLineNumbers } from '@rehype-pretty/transformers'
*
* const html = await codeToHtml(`console.log('hello, world')`, {
* lang: 'ts',
* theme: 'vitesse-light',
* transformers: [
* transformerLineNumbers({ autoApply: true }),
* ]
* })
* ```
*/
export function transformerLineNumbers(
options: LineNumbersOptions = { autoApply: true },
): ShikiTransformer {
Expand Down Expand Up @@ -84,6 +104,9 @@ export function transformerLineNumbers(
};
}

/**
* Returns the CSS styles for line numbers.
*/
function lineNumbersStyle() {
return /* css */ `
pre[data-show-line-numbers='true'], code[data-show-line-numbers='true'] {
Expand Down
Loading

0 comments on commit 562bd7f

Please sign in to comment.