This repository has been archived by the owner on Apr 15, 2018. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsections.coffee
83 lines (68 loc) · 2.32 KB
/
sections.coffee
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
md = require('markdown').markdown
class SectionParser
constructor: (@nodes) ->
# reference to last main section or subsection
# all following content should go its `text` property
@currentSection = null
# reference to current open main section
@mainSection = null
@mainSectionLevel = null
# reference to current open subsection
@subsection = null
@subsectionLevel = null
# position in tree where content of @currentSection starts
@contentStart = 0
# position in nodes which we are currently considering
@currentPosition = 0
# output array holding the main sections
@mainSections = []
parse: ->
while @currentPosition < @nodes.length
node = @nodes[@currentPosition]
if node[0] == 'header'
level = node[1].level
@processHeader node[1].level,
if node.length == 3 && !Array.isArray(node[2])
node[2]
else
node.slice 2
@currentPosition++
@closeCurrentSection()
@mainSections
processHeader: (level, headingContent) ->
if @mainSectionLevel == null || level <= @mainSectionLevel
@closeCurrentSection()
@mainSectionLevel = level
@subsectionLevel = null
@mainSection = @currentSection = {name: headingContent}
@mainSections.push @currentSection
else if @subsectionLevel == null || level <= @subsectionLevel
@closeCurrentSection()
@subsectionLevel = level
@currentSection = { name: headingContent }
unless 'subsections' of @mainSection
@mainSection.subsections = []
@mainSection.subsections.push @currentSection
closeCurrentSection: ->
if @currentPosition != 0
if @currentSection == null
@currentSection = {name: null}
@mainSections.push @currentSection
if @contentStart == @currentPosition - 1
# place single node directly
@currentSection.text = @nodes[@contentStart]
else if @contentStart != @currentPosition
@currentSection.text = @nodes.slice @contentStart
@contentStart = @currentPosition + 1
parseSections = (markdown) ->
tree = md.parse markdown
# empty text is returned as ['markdown']
if tree.length == 1
return {
sections: []
}
parser = new SectionParser(tree.slice(1))
{
sections: parser.parse()
}
module.exports = parseSections