diff options
author | Eugene Sokolov <eug-vs@keemail.me> | 2020-04-06 17:47:20 +0300 |
---|---|---|
committer | GitHub <noreply@github.com> | 2020-04-06 17:47:20 +0300 |
commit | 62df0ff96fc9ab832212d223150862c7667d9ffc (patch) | |
tree | 9159c443e970ea2a0819edffbe2fe5cc101c1001 /src/lib/Markdown/Section.tsx | |
parent | a72027d21154ba94e26d6b96092afc9704b8288c (diff) | |
parent | 400330fe5ebd6951a97f07b6147b3af6113e034f (diff) | |
download | react-benzin-62df0ff96fc9ab832212d223150862c7667d9ffc.tar.gz |
Merge pull request #8 from eug-vs/developv3.1.0
Markdown parser
Diffstat (limited to 'src/lib/Markdown/Section.tsx')
-rw-r--r-- | src/lib/Markdown/Section.tsx | 46 |
1 files changed, 46 insertions, 0 deletions
diff --git a/src/lib/Markdown/Section.tsx b/src/lib/Markdown/Section.tsx new file mode 100644 index 0000000..5ce8954 --- /dev/null +++ b/src/lib/Markdown/Section.tsx @@ -0,0 +1,46 @@ +import React from 'react'; +import ContentSection from '../ContentSection/ContentSection'; +import Content from './Content'; +import { ParserPropTypes } from './types'; + +interface PropTypes extends ParserPropTypes { + level?: number; +} + +const getHeaderLevel = (header: string): number => { + if (!header) return 0; + let level = 0; + while(header[level] === '#') level++; + return level; +} + +const ChildrenSections: React.FC<PropTypes> = ({ rawLines, level = 0 }) => { + const childrenSectionLines = rawLines.reduce((sections: string[][], line: string) => { + if (line) { + if (getHeaderLevel(line) === level) sections.push([]); + if (sections.length) sections[sections.length - 1].push(line); + } + return sections; + }, []); + const children = childrenSectionLines.map(sectionLines => <Section rawLines={sectionLines} level={level}/>); + return <> {children} </>; +} + +const Section: React.FC<PropTypes> = ({ rawLines, level = 0 }) => { + const deeperLevelIndex = rawLines.findIndex(line => line.match(`^#{${level + 1},} .*$`)); + const rawContent = rawLines.splice(0, (deeperLevelIndex < 0) ? rawLines.length : deeperLevelIndex); + + if (!level) return <ChildrenSections rawLines={rawLines} level={getHeaderLevel(rawLines[0])}/>; + + const sectionName = rawContent.splice(0, 1)[0].slice(level).trim(); + const deeperLevel = getHeaderLevel(rawLines[0]); + return ( + <ContentSection sectionName={sectionName} level={level}> + <Content rawLines={rawContent} /> + <ChildrenSections rawLines={rawLines} level={deeperLevel} /> + </ContentSection> + ); +} + +export default Section; + |