blob: fb2933daeb381268d0aee42998f507136bd6058f (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
|
import React from 'react';
import { Typography } from '@material-ui/core';
import ContentSection from '../ContentSection/ContentSection';
import Content from './Content';
import { ParserPropTypes } from './types';
interface PropTypes extends ParserPropTypes {
level?: number;
}
interface MapperPropTypes extends PropTypes {
SectionComponent: React.FC<PropTypes>;
}
const getHeaderLevel = (header: string): number => {
if (!header) return 0;
let level = 0;
while (header[level] === '#') level += 1;
return level;
};
const SectionMapper: React.FC<MapperPropTypes> = ({ rawLines, level = 0, SectionComponent }) => {
const children = 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;
}, [])
.map(sectionLines => <SectionComponent 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 (
<>
<Typography><Content rawLines={rawContent} /></Typography>
<SectionMapper rawLines={rawLines} level={getHeaderLevel(rawLines[0])} SectionComponent={Section} />
</>
);
}
const sectionName = rawContent.splice(0, 1)[0].slice(level).trim();
const deeperLevel = getHeaderLevel(rawLines[0]);
return (
<ContentSection sectionName={sectionName} level={level}>
<Content rawLines={rawContent} />
<SectionMapper rawLines={rawLines} level={deeperLevel} SectionComponent={Section} />
</ContentSection>
);
};
export default Section;
|