Skip to content

Commit

Permalink
Add "id" to headings (#709)
Browse files Browse the repository at this point in the history
* Parses heading links

* Move code to a different file
  • Loading branch information
andresmgot authored Oct 9, 2018
1 parent 008c6bd commit 74f3fa6
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 2 deletions.
15 changes: 14 additions & 1 deletion dashboard/src/components/ChartView/ChartReadme.test.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { shallow } from "enzyme";
import { mount, shallow } from "enzyme";
import context from "jest-plugin-context";
import * as React from "react";
import * as ReactMarkdown from "react-markdown";
Expand Down Expand Up @@ -57,3 +57,16 @@ it("renders an error when hasError is set", () => {
);
expect(wrapper.text()).toContain("No README found");
});

it("renders the ReactMarkdown content adding IDs for the titles", () => {
const wrapper = mount(
<ChartReadme
getChartReadme={jest.fn()}
hasError={false}
version="1.2.3"
readme="# _Markdown_ 'Readme_or_not'!"
/>,
);
const component = wrapper.find("#markdown-readme_or_not");
expect(component).toExist();
});
3 changes: 2 additions & 1 deletion dashboard/src/components/ChartView/ChartReadme.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { FileText } from "react-feather";
import * as ReactMarkdown from "react-markdown";

import LoadingWrapper from "../LoadingWrapper";
import HeadingRenderer from "./HeadingRenderer";

import "./ChartReadme.css";

Expand Down Expand Up @@ -35,7 +36,7 @@ class ChartReadme extends React.Component<IChartReadmeProps> {
<LoadingWrapper loaded={!!readme}>
{readme && (
<div className="ChartReadme">
<ReactMarkdown source={readme} />
<ReactMarkdown source={readme} renderers={{ heading: HeadingRenderer }} />
</div>
)}
</LoadingWrapper>
Expand Down
20 changes: 20 additions & 0 deletions dashboard/src/components/ChartView/HeadingRenderer.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import * as React from "react";

// Code from https://github.com/rexxars/react-markdown/issues/69
function flatten(text: string, child: any): any {
return typeof child === "string"
? text + child
: React.Children.toArray(child.props.children).reduce(flatten, text);
}

const HeadingRenderer: React.SFC<{}> = (props: any) => {
const children = React.Children.toArray(props.children);
const text = children.reduce(flatten, "");
const slug = text
.toLowerCase()
.replace(/[^a-zA-Z0-9_\s]/g, "") // remove punctuation
.replace(/\s/g, "-"); // replace spaces with dash
return React.createElement("h" + props.level, { id: slug }, props.children);
};

export default HeadingRenderer;

0 comments on commit 74f3fa6

Please sign in to comment.