8000 feat(theme-classic): code block showLineNumbers by lex111 · Pull Request #7007 · facebook/docusaurus · GitHub
[go: up one dir, main page]
More Web Proxy on the site http://driver.im/
Skip to content

feat(theme-classic): code block showLineNumbers #7007

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Apr 13, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions packages/docusaurus-theme-classic/src/theme-classic.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,7 @@ declare module '@theme/CodeBlock' {
readonly metastring?: string;
readonly title?: string;
readonly language?: string;
readonly showLineNumbers?: boolean;
}

export default function CodeBlock(props: Props): JSX.Element;
Expand Down
37 changes: 31 additions & 6 deletions packages/docusaurus-theme-classic/src/theme/CodeBlock/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import {
parseCodeBlockTitle,
parseLanguage,
parseLines,
containsLineNumbers,
ThemeClassNames,
usePrismTheme,
} from '@docusaurus/theme-common';
Expand All @@ -26,6 +27,7 @@ export default function CodeBlock({
className: blockClassName = '',
metastring,
title,
showLineNumbers,
language: languageProp,
}: Props): JSX.Element {
const {prism} = useThemeConfig();
Expand Down Expand Up @@ -87,6 +89,8 @@ export default function CodeBlock({
const language =
languageProp ?? parseLanguage(blockClassName) ?? prism.defaultLanguage;
const {highlightLines, code} = parseLines(content, metastring, language);
const shouldShowLineNumbers =
showLineNumbers || containsLineNumbers(metastring);

return (
<Highlight
Expand Down Expand Up @@ -116,24 +120,45 @@ export default function CodeBlock({
/* eslint-disable-next-line jsx-a11y/no-noninteractive-tabindex */
tabIndex={0}
className={clsx(className, styles.codeBlock, 'thin-scrollbar')}>
<code className={styles.codeBlockLines}>
<code
className={clsx(
styles.codeBlockLines,
shouldShowLineNumbers && styles.codeBlockLinesWithNumbering,
)}>
{tokens.map((line, i) => {
if (line.length === 1 && line[0]!.content === '\n') {
line[0]!.content = '';
}

const lineProps = getLineProps({line, key: i});
const lineProps = getLineProps({
line,
key: i,
...(shouldShowLineNumbers && {className: styles.codeLine}),
});

if (highlightLines.includes(i)) {
lineProps.className += ' docusaurus-highlight-code-line';
}

const lineTokens = line.map((token, key) => (
<span key={key} {...getTokenProps({token, key})} />
));

return (
<span key={i} {...lineProps}>
{line.map((token, key) => (
<span key={key} {...getTokenProps({token, key})} />
))}
<br />
{shouldShowLineNumbers ? (
<>
<span className={styles.codeLineNumber} />
<span className={styles.codeLineContent}>
{lineTokens}
</span>
</>
) : (
<>
{lineTokens}
<br />
</>
)}
</span>
);
})}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@
}

.codeBlock {
--ifm-pre-background: inherit;
margin: 0;
padding: 0;
background-color: inherit;
}

.codeBlockTitle + .codeBlockContent .codeBlock {
Expand All @@ -44,14 +44,48 @@

.codeBlockLines {
font: inherit;
background: var(--ifm-pre-background);
/* rtl:ignore */
float: left;
min-width: 100%;
padding: var(--ifm-pre-padding);
}

.codeBlockLinesWithNumbering {
display: table;
padding: var(--ifm-pre-padding) 0;
}

@media print {
.codeBlockLines {
white-space: pre-wrap;
}
}

.codeLine {
display: table-row;
counter-increment: line-count;
}

.codeLineNumber {
display: table-cell;
text-align: right;
width: 1%;
position: sticky;
left: 0;
padding: 0 var(--ifm-pre-padding);
background: var(--ifm-pre-background);
}

.codeLineNumber::before {
content: counter(line-count);
opacity: 0.4;
}

:global(.docusaurus-highlight-code-line) .codeLineNumber::before {
opacity: 0.8;
}

.codeLineContent {
padding-right: var(--ifm-pre-padding);
}
1 change: 1 addition & 0 deletions packages/docusaurus-theme-common/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ export {
parseCodeBlockTitle,
parseLanguage,
parseLines,
containsLineNumbers,
} from './utils/codeBlockUtils';

export {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,10 @@ export function parseCodeBlockTitle(metastring?: string): string {
return metastring?.match(codeBlockTitleRegex)?.groups!.title ?? '';
}

export function containsLineNumbers(metastring?: string): boolean {
return metastring?.includes('showLineNumbers') || false;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

was thinking maybe we should make it possible to have it enabled by default, and disable on a case-by-case basis?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not see the need for this, in most cases it is not necessary.

Copy link
Collaborator
@Josh-Cena Josh-Cena Apr 7, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, I think opt-in is better than opt-out in most cases. It usually adds unnecessary noise, because unless you want to reference one line of code in the main text, you don't need numbering. Another option is to add a default-false theme config option that adds line numbers to all code blocks, but IMO we don't have a strong use-case

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Another option is to add a default-false theme config option that adds line numbers to all code blocks, but IMO we don't have a strong use-case

That's what I was thinking about, but we can add later if requested 👍

}

/**
* Gets the language name from the class name (set by MDX).
* e.g. `"language-javascript"` => `"javascript"`.
Expand Down
48 changes: 48 additions & 0 deletions website/_dogfooding/_pages tests/code-block-tests.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -142,3 +142,51 @@ Multi-line text inside `pre` will turn into one-liner, but it's okay (https://gi
</strong>cd", at which time b is a substring.
<br />
</CodeBlock>

## Code blocks with line numbering tests

```jsx
function PageLayout(props) {
// highlight-next-line
return <Layout title="Awesome Docusaurus page" description="Test Test Test Test Test Test Test Test Test Test Test Test Test Test ">;
}
```

```jsx showLineNumbers
function PageLayout(props) {
// highlight-next-line
return <Layout title="Awesome Docusaurus page" description="Test Test Test Test Test Test Test Test Test Test Test Test Test Test ">;
}
```

```jsx {1,3,6} showLineNumbers
function PageLayout(props) {
console.log(
'Test Test Test Test Test Test Test Test Test Test Test Test Test Test ',
);
console.log(
'Test Test Test Test Test Test Test Test Test Test Test Test Test Test ',
);
console.log(
'Test Test Test Test Test Test Test Test Test Test Test Test Test Test ',
);
console.log(
'Test Test Test Test Test Test Test Test Test Test Test Test Test Test ',
);
console.log(
'Test Test Test Test Test Test Test Test Test Test Test Test Test Test ',
);
console.log(
'Test Test Test Test Test Test Test Test Test Test Test Test Test Test ',
);
console.log(
'Test Test Test Test Test Test Test Test Test Test Test Test Test Test ',
);
console.log(
'Test Test Test Test Test Test Test Test Test Test Test Test Test Test ',
);
console.log(
'Test Test Test Test Test Test Test Test Test Test Test Test Test Test ',
);
}
```
52 changes: 48 additions & 4 deletions website/docs/guides/markdown-features/markdown-features-code-blocks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,44 @@ In the future, we may extend the magic comment system and let you define custom

:::

## Line numbering {#line-numbering}

You can enable line numbering for your code block by using `showLineNumbers` key within the language meta string (don't forget to add space directly before the key).

````md
```jsx {1,4-6,11} showLineNumbers
import React from 'react';

function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}

return <div>Foo</div>;
}

export default MyComponent;
```
````

<BrowserWindow>

```jsx {1,4-6,11} showLineNumbers
import React from 'react';

function MyComponent(props) {
if (props.isBar) {
return <div>Bar</div>;
}

return <div>Foo</div>;
}

export default MyComponent;
```

</BrowserWindow>

## Interactive code editor {#interactive-code-editor}

(Powered by [React Live](https://github.com/FormidableLabs/react-live))
Expand Down Expand Up @@ -596,7 +634,10 @@ export default function MyReactPage() {
return (
<div>
{/* highlight-start */}
<CodeBlock language="jsx" title="/src/components/HelloCodeTitle.js">
<CodeBlock
language="jsx"
title="/src/components/HelloCodeTitle.js"
showLineNumbers>
{`function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}`}
Expand All @@ -608,15 +649,18 @@ export default function MyReactPage() {
```

<BrowserWindow>
<CodeBlock language="jsx" title="/src/components/HelloCodeTitle.js">
<CodeBlock
language="jsx"
title="/src/components/HelloCodeTitle.js"
showLineNumbers>
{`function HelloCodeTitle(props) {
return <h1>Hello, {props.name}</h1>;
}`}
</CodeBlock>
</BrowserWindow>

The props accepted are `language` and `title`, in the same way as you write Markdown code blocks.
The props accepted are `language`, `title` and `showLineNumbers`, in the same way as you write Markdown code blocks.

Although discouraged, you can also pass in a `metastring` prop like `metastring='{1-2} title="/src/components/HelloCodeTitle.js"'`, which is how Markdown code blocks are handled under the hood. However, we recommend you [use comments for highlighting lines](#highlighting-with-comments).
Although discouraged, you can also pass in a `metastring` prop like `metastring='{1-2} title="/src/components/HelloCodeTitle.js" showLineNumbers'`, which is how Markdown code blocks are handled under the hood. However, we recommend you [use comments for highlighting lines](#highlighting-with-comments).

As [previously stated](#using-jsx-markup), syntax highlighting is only applied when the children is a simple string.
0