Skip to content

Commit

Permalink
Allow arrays in markdown template literal (#410)
Browse files Browse the repository at this point in the history
* Allow arrays in markdown template literal

Fixes #403

* Don't allocate unnecessary array
  • Loading branch information
jstcki authored Apr 27, 2018
1 parent d75475d commit 9d58c3c
Show file tree
Hide file tree
Showing 4 changed files with 24 additions and 6 deletions.
11 changes: 10 additions & 1 deletion docs/test/testtemplate.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { markdown } from "catalog";
import React from "react";
import { markdown, ReactSpecimen } from "catalog";
import logo from "../catalog_logo.svg";

export default () => markdown`
Expand All @@ -14,4 +15,12 @@ title: Neat!
Super nice stuff here!
Foo bar
${["foo", "bar"].map(d => [
`### ${d}`,
<ReactSpecimen key="foo">
<div>{d}</div>
</ReactSpecimen>
])}
`;
8 changes: 7 additions & 1 deletion src/__snapshots__/markdownPage.test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,13 @@ exports[`Catalog markdown page template literal with arbitrary values 1`] = `
A paragraph 123
~~~
[{"a":"some"},{"a":"data"}]
foo
bar
<div>
hello
</div>
~~~
</Page>
Expand Down
9 changes: 6 additions & 3 deletions src/markdownPage.js
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,19 @@ import Page from "./components/Page/Page";
// > ${<MyComponent isCustomComponent={'AWESOME'} />}
// > `;

const replaceLast = (f, arr) => arr.slice(0, -1).concat(f(arr[arr.length - 1]));
const replaceLast = (f, arr) => {
arr[arr.length - 1] = f(arr[arr.length - 1]);
return arr;
};

const markdownPage = (strings, ...values) =>
createElement(
Page,
{},
...values.reduce(
(a, v, i) => {
// If it's a valid React element, just concat to the end of the array
if (isValidElement(v)) {
// If it's a valid React element or array, just concat to the end of the array
if (isValidElement(v) || Array.isArray(v)) {
return a.concat(v, strings[i + 1]);
}

Expand Down
2 changes: 1 addition & 1 deletion src/markdownPage.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ test("Catalog markdown page template literal with arbitrary values", () => {
A paragraph ${123}
~~~
${[{ a: "some" }, { a: "data" }]}
${["foo", "bar", <div>hello</div>]}
~~~
`;
expect(page).toMatchSnapshot();
Expand Down

0 comments on commit 9d58c3c

Please sign in to comment.