aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Markdown/Section.tsx
diff options
context:
space:
mode:
authorEug-VS <eug-vs@keemail.me>2020-04-04 22:05:40 +0300
committerEug-VS <eug-vs@keemail.me>2020-04-04 22:05:40 +0300
commitbdcc2edb38fb0e57604fa12d25b2a4b478261e18 (patch)
tree71aaedf7f4500cfcab9bd4f344b326dadd71d392 /src/lib/Markdown/Section.tsx
parent464b5fbef2f58cbcd134b7200c5f7c2f904202a0 (diff)
downloadreact-benzin-bdcc2edb38fb0e57604fa12d25b2a4b478261e18.tar.gz
refactor: structurize Markdown component :recycle:
Diffstat (limited to 'src/lib/Markdown/Section.tsx')
-rw-r--r--src/lib/Markdown/Section.tsx39
1 files changed, 39 insertions, 0 deletions
diff --git a/src/lib/Markdown/Section.tsx b/src/lib/Markdown/Section.tsx
new file mode 100644
index 0000000..c902379
--- /dev/null
+++ b/src/lib/Markdown/Section.tsx
@@ -0,0 +1,39 @@
+import React from 'react';
+import ContentSection from '../ContentSection/ContentSection';
+import Content from './Content';
+import { ParserPropTypes } from './types';
+
+interface PropTypes extends ParserPropTypes {
+ level?: number;
+}
+
+const matchHeaderLevel = (line: string, level: number): boolean => {
+ return line.match(`^#{${level}} .*$`) !== null;
+}
+
+const Section: React.FC<PropTypes> = ({ rawLines, level = 0 }) => {
+ const sectionName = rawLines.splice(0, 1)[0].slice(level).trim();
+ const contentSize = rawLines.findIndex(line => matchHeaderLevel(line, level + 1));
+ const rawContent = rawLines.splice(0, (contentSize < 0) ? rawLines.length : contentSize);
+
+ const childrenSectionLines = rawLines.reduce((sections: string[][], line: string) => {
+ if (matchHeaderLevel(line, level + 1)) sections.push([]);
+ if (sections.length) sections[sections.length - 1].push(line);
+ return sections;
+ }, []);
+ const children = childrenSectionLines.map(sectionLines => <Section rawLines={sectionLines} level={level + 1}/>)
+
+ return level ? (
+ <ContentSection sectionName={sectionName}>
+ <Content rawLines={rawContent} />
+ {children}
+ </ContentSection>
+ ) : (
+ <>
+ {children}
+ </>
+ );
+}
+
+export default Section;
+