Skip to content

Commit 474cfd1

Browse files
committed
beef up code output marker detection;
...warn on double-usage
1 parent 24e24d5 commit 474cfd1

File tree

1 file changed

+11
-3
lines changed

1 file changed

+11
-3
lines changed

src/components/code-block.js

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import React, { useState } from "react";
22
import { Button } from "react-bootstrap";
33
import { Tooltip } from "react-bootstrap";
44
import { OverlayTrigger } from "react-bootstrap";
5+
import { useLocation } from "@gatsbyjs/reach-router";
56

67
const childToString = (child) => {
78
if (typeof child === "string") {
@@ -22,13 +23,13 @@ const popExtraNewLines = (code) => {
2223
}
2324
};
2425

25-
const splitChildrenIntoCodeAndOutput = (rawChildren) => {
26+
const splitChildrenIntoCodeAndOutput = (rawChildren, urlpath) => {
2627
if (!rawChildren) {
2728
return [[], []];
2829
}
2930

3031
// Simplified regex to split on the __OUTPUT__ marker
31-
const splitRegex = /\n__OUTPUT__\n/;
32+
const splitRegex = /(?:\n|^)[ \t\f\v]*__OUTPUT__[ \t\f\v]*(?:\n|$)/;
3233
const code = [];
3334
const output = [];
3435

@@ -41,6 +42,12 @@ const splitChildrenIntoCodeAndOutput = (rawChildren) => {
4142
if (splitFound) {
4243
// we've already split, toss it into output and move on
4344
output.push(childToString(child));
45+
// warn if we do find another __OUTPUT__ marker - this is likely a mistake
46+
if (splitRegex.test(output.at(-1)))
47+
console.warn(
48+
urlpath +
49+
": Found another __OUTPUT__ marker after the first one, this is likely a mistake.",
50+
);
4451
continue;
4552
}
4653

@@ -152,10 +159,11 @@ const OutputPre = ({ content }) => (
152159
);
153160

154161
const CodeBlock = ({ children, codeLanguages, ...otherProps }) => {
162+
const location = useLocation();
155163
const childIsComponent = !!children.props; // true in normal usage, false if raw <pre> tags are used
156164

157165
const [codeContent, outputContent] = childIsComponent
158-
? splitChildrenIntoCodeAndOutput(children.props.children)
166+
? splitChildrenIntoCodeAndOutput(children.props.children, location.pathname)
159167
: [children, ""];
160168

161169
const startWrapped = false;

0 commit comments

Comments
 (0)