Created
March 18, 2021 13:33
-
-
Save ramyak-mehra/bc0da91187dc12c3ae40211430052e90 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Section { | |
int level; | |
Element titleNode; | |
List<Node> contentNodes; | |
List<Section> subSections; | |
void _addContentNodes(Node nodes) { | |
contentNodes = List.from(contentNodes)..add(nodes); | |
} | |
Section({this.level, this.titleNode, this.contentNodes}) { | |
contentNodes = []; | |
subSections = []; | |
} | |
} | |
class SectionMaker { | |
var path = 'markdown file path'; | |
Section _parentSection; | |
Section _currentParentSection; | |
Section _currentSection; | |
var level = 0; | |
SectionMaker(); | |
List<Node> _getNodes(String filePath) { | |
var file = io.File(filePath); | |
var document = Document(); | |
var markdown = file.readAsStringSync(); | |
var lines = markdown.replaceAll('\r\n', '\n').split('\n'); | |
return document.parseLines(lines); | |
} | |
Section _makeSection({int level, Node titleNode}) { | |
return Section(level: level, titleNode: titleNode); | |
} | |
Section generateSection() { | |
var nodes = _getNodes(path); | |
nodes.forEach((element) { | |
if (element is Element) { | |
if (element.tag == 'h1') { | |
_parentSection ??= _makeSection(level: -1); | |
_currentParentSection = | |
_makeSection(level: level, titleNode: element); | |
_currentSection = _currentParentSection; | |
level++; | |
_parentSection.subSections.add(_currentParentSection); | |
} | |
if (element.tag == 'h2') { | |
_currentSection = _makeSection(titleNode: element); | |
_currentParentSection.subSections.add(_currentSection); | |
} | |
_currentSection._addContentNodes(element); | |
} else { | |
_currentSection._addContentNodes(element); | |
} | |
}); | |
return _parentSection; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment