From 74f3fa668958e18168f9773563ad1fc6d58e91d3 Mon Sep 17 00:00:00 2001 From: Andres Date: Tue, 9 Oct 2018 12:44:31 +0200 Subject: [PATCH] Add "id" to headings (#709) * Parses heading links * Move code to a different file --- .../components/ChartView/ChartReadme.test.tsx | 15 +++++++++++++- .../src/components/ChartView/ChartReadme.tsx | 3 ++- .../components/ChartView/HeadingRenderer.tsx | 20 +++++++++++++++++++ 3 files changed, 36 insertions(+), 2 deletions(-) create mode 100644 dashboard/src/components/ChartView/HeadingRenderer.tsx diff --git a/dashboard/src/components/ChartView/ChartReadme.test.tsx b/dashboard/src/components/ChartView/ChartReadme.test.tsx index a4e543c3c78..abbdc49d545 100644 --- a/dashboard/src/components/ChartView/ChartReadme.test.tsx +++ b/dashboard/src/components/ChartView/ChartReadme.test.tsx @@ -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"; @@ -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( + , + ); + const component = wrapper.find("#markdown-readme_or_not"); + expect(component).toExist(); +}); diff --git a/dashboard/src/components/ChartView/ChartReadme.tsx b/dashboard/src/components/ChartView/ChartReadme.tsx index 34927369fcf..f497faf6245 100644 --- a/dashboard/src/components/ChartView/ChartReadme.tsx +++ b/dashboard/src/components/ChartView/ChartReadme.tsx @@ -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"; @@ -35,7 +36,7 @@ class ChartReadme extends React.Component { {readme && (
- +
)}
diff --git a/dashboard/src/components/ChartView/HeadingRenderer.tsx b/dashboard/src/components/ChartView/HeadingRenderer.tsx new file mode 100644 index 00000000000..2b00d3250dc --- /dev/null +++ b/dashboard/src/components/ChartView/HeadingRenderer.tsx @@ -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;