Skip to content

Commit

Permalink
Fix: code blocks in mdx + issues/868 (#1422)
Browse files Browse the repository at this point in the history
  • Loading branch information
muditjuneja committed Mar 3, 2024
1 parent 46a0af4 commit 7aa23ec
Show file tree
Hide file tree
Showing 7 changed files with 77 additions and 29 deletions.
19 changes: 11 additions & 8 deletions packages/example/src/pages/components/code-blocks.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ description: Usage instructions for the Code blocks component

When authoring markdown using the Carbon Gatsby theme, code blocks have some
extra super powers you can take advantage of. We provide carbon-themed syntax
highlighting as well as optional `path` and `src` features.
highlighting as well as optional `path`, `src` and `hideCode` features.

</PageDescription>

Expand All @@ -26,8 +26,8 @@ This example overflows to demonstrate the text fading out under the side bar.

<Title>Vertical overflow</Title>

```markdown path=/directory/file.mdx src=https://gatsby.carbondesignsystem.com
## Path and src w/ overflow
```markdown path=/directory/file.mdx src=https://gatsby.carbondesignsystem.com hideCode=true
## Path, src, hideCode w/ overflow

This example demonstrates the show more button. This example demonstrates the
show more button. This example demonstrates the show more button. This example
Expand All @@ -36,16 +36,18 @@ button. This example demonstrates the show more button. This example
demonstrates the show more button. This example demonstrates the show more
button. This example demonstrates the show more button. This example
demonstrates the show more button. This example demonstrates the show more
button. This example demonstrates the show more button.
button. This example demonstrates the show more button. This example demonstrates the show more button.
This example demonstrates the show more button. This example demonstrates the show more button.
This example demonstrates the show more button. This example demonstrates the show more button.
```

## Code

````
```markdown path=/directory/file.mdx src=https://gatsby.carbondesignsystem.com
### Path and src
````mdx
```markdown path=/directory/file.mdx src=https://gatsby.carbondesignsystem.com hideCode=true

This code snippet provides both a `path` and a `src`.
### Path, src and hideCode
This code snippet provides a `path`, a `src` and `hideCode` prop.
```
````

Expand All @@ -56,3 +58,4 @@ This code snippet provides both a `path` and a `src`.
| language | string | [Available languages.](https://github.com/FormidableLabs/prism-react-renderer/blob/master/src/vendor/prism/includeLangs.js) |
| src | string | The full url of a relevant link (source) |
| path | string | A string indicating the filename or path. Due to markdown limitations this can only be a single word |
| hideCode | boolean | A boolean indicating if the code block should have a Show More button. Code block should have more than 9 lines to display the button. Default value = `false`|
4 changes: 2 additions & 2 deletions packages/example/src/pages/guides/configuration.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -298,7 +298,7 @@ work, you can try calling the (underlying) remark plugin directly using the

For the below markdown snippet:

````
````mdx
```mermaid
graph LR
install[Install Plugin]
Expand Down Expand Up @@ -346,7 +346,7 @@ project:

For the below markdown snippet:

```
```mdx
+-------+----------+------+
| Table Headings | Here |
+-------+----------+------+
Expand Down
11 changes: 11 additions & 0 deletions packages/gatsby-theme-carbon/gatsby-config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ import remarkGfm from 'remark-gfm';
import { fileURLToPath } from 'url';
import defaultLunrOptions from './config/lunr-options.mjs';

/*
This is a rehype plugin that adds support for metadata to the fenced code block
For eg:
```jsx path=/directory/file.mdx src=https://gatsby.carbondesignsystem.com
const a = 10;
```
A metaData prop of format path=/directory/file.mdx src=https://gatsby.carbondesignsystem.com is added to the code block
*/
import rehypeAddCodeMetaData from 'rehype-mdx-fenced-code-meta-support';

const __dirname = dirname(fileURLToPath(import.meta.url));
const carbonThemes = {
white: './src/styles/internal/white.scss',
Expand Down Expand Up @@ -119,6 +129,7 @@ export default (themeOptions) => {
],
mdxOptions: {
remarkPlugins: [remarkGfm, ...remarkPlugins],
rehypePlugins: [rehypeAddCodeMetaData],
},
// defaultLayouts: {
// default: require.resolve('./src/templates/Default.js'),
Expand Down
1 change: 1 addition & 0 deletions packages/gatsby-theme-carbon/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
"react-helmet": "^6.1.0",
"react-transition-group": "^4.4.5",
"react-use": "^17.5.0",
"rehype-mdx-fenced-code-meta-support": "^1.0.4",
"remark-gfm": "3.0.1",
"sass": "^1.71.1",
"slugify": "^1.6.6",
Expand Down
60 changes: 41 additions & 19 deletions packages/gatsby-theme-carbon/src/components/Code/Code.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import React, { useEffect, useState } from 'react';
import { Highlight, defaultProps } from 'prism-react-renderer';
import { Highlight } from 'prism-react-renderer';
import { ChevronDown, ChevronUp } from '@carbon/react/icons';

import cx from 'classnames';
Expand All @@ -14,7 +14,10 @@ import Sidebar from './Sidebar';

import useMetadata from '../../util/hooks/useMetadata';

const Code = ({ children, className: classNameProp = '', path, src }) => {
const Code = ({ children, className: classNameProp = '', metaData }) => {
const [path, setPath] = useState('');
const [src, setSrc] = useState('');
const [hideCode, setHideCode] = useState(false);
const [hasMoreThanNineLines, setHasMoreThanNineLines] = useState(false);
const [shouldShowMore, setShouldShowMore] = useState(false);
const [isInlineCode, setIsInlineCode] = useState(false);
Expand All @@ -25,32 +28,52 @@ const Code = ({ children, className: classNameProp = '', path, src }) => {
}
}, [classNameProp]);

const { interiorTheme } = useMetadata();
useEffect(() => {
// metaData string is of format: path=/directory/file.mdx src=https://gatsby.carbondesignsystem.com
if (metaData) {
const metaDataObject = metaData.split(' ').reduce((obj, item) => {
const [key, value] = item.split('=');
obj[key] = value;
return obj;
}, {});

if (metaDataObject.path) {
setPath(metaDataObject.path);
}

if (metaDataObject.src) {
setSrc(metaDataObject.src);
}

if (metaDataObject.hideCode) {
setHideCode(true);
}
}
}, [metaData]);

const { interiorTheme } = useMetadata();
const language = classNameProp.replace(/language-/, '').replace('mdx', 'jsx');

const removeTrailingEmptyLine = (lines) => {
if (lines && lines.length) {
const [lastLine] = lines.splice(-1);
if (lastLine[0].empty) {
return lines;
}
return [...lines, lastLine];
const [lastLine] = lines[lines.length - 1];

// empty is a boolean property coming inside the lastLine object
if (lastLine.empty) {
lines.splice(-1);
return lines;
}
return [...lines];
};

const getLines = (lines) => {
const withoutTrailingEmpty = removeTrailingEmptyLine(lines);

if (withoutTrailingEmpty && withoutTrailingEmpty.length > 9) {
const withoutTrailingEmptyLines = removeTrailingEmptyLine(lines);
if (withoutTrailingEmptyLines && withoutTrailingEmptyLines.length > 9) {
setHasMoreThanNineLines(true);
}

if (shouldShowMore) {
return withoutTrailingEmpty;
if (shouldShowMore || !hideCode) {
return withoutTrailingEmptyLines;
}

return withoutTrailingEmpty ? withoutTrailingEmpty.slice(0, 9) : [];
return withoutTrailingEmptyLines.slice(0, 9);
};

// TODO - remove this once we have a better way of handling inline code. This seems like a hack
Expand All @@ -64,7 +87,6 @@ const Code = ({ children, className: classNameProp = '', path, src }) => {
{children}
</PathRow>
<Highlight
{...defaultProps}
code={children}
language={language}
theme={getTheme(interiorTheme)}>
Expand All @@ -90,7 +112,7 @@ const Code = ({ children, className: classNameProp = '', path, src }) => {
</div>
)}
</Highlight>
{hasMoreThanNineLines && (
{hideCode && hasMoreThanNineLines && (
<button
className={cx(styles.showMoreButton, {
[styles.dark]: interiorTheme === 'dark',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ li .row {
position: relative;
overflow: auto;
width: 100%;
text-wrap: wrap;
}

.sideBarMinHeight {
Expand Down
10 changes: 10 additions & 0 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -11291,6 +11291,7 @@ __metadata:
react-helmet: "npm:^6.1.0"
react-transition-group: "npm:^4.4.5"
react-use: "npm:^17.5.0"
rehype-mdx-fenced-code-meta-support: "npm:^1.0.4"
remark-gfm: "npm:3.0.1"
sass: "npm:^1.71.1"
slugify: "npm:^1.6.6"
Expand Down Expand Up @@ -19717,6 +19718,15 @@ __metadata:
languageName: node
linkType: hard

"rehype-mdx-fenced-code-meta-support@npm:^1.0.4":
version: 1.0.4
resolution: "rehype-mdx-fenced-code-meta-support@npm:1.0.4"
dependencies:
unist-util-visit: "npm:^5.0.0"
checksum: 10/8292b57d980e460c1f3258840f950d5043ab6aa66bf2120df170482c521b1d1e954d976a4e2cdfa17f39c04e53261102c6f444030564a9b1896f03fddd074561
languageName: node
linkType: hard

"relay-runtime@npm:12.0.0":
version: 12.0.0
resolution: "relay-runtime@npm:12.0.0"
Expand Down

0 comments on commit 7aa23ec

Please sign in to comment.