functions/Read-EBMarkdown.ps1

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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
function Read-EBMarkdown {
    <#
    .SYNOPSIS
        Reads a markdown file and converts it to a page to be built into an ebook
     
    .DESCRIPTION
        Reads a markdown file and converts it to a page to be built into an ebook
     
    .PARAMETER Path
        Path to the file to read.
         
    .PARAMETER InlineStyles
        Hashtable mapping inline decorators to span classes.
        Used to enable inline style customizations.
        For example, when providing a hashtable like this:
        @{ 1 = 'spellcast' }
        It will convert this line:
        "Let me show you my #1#Fireball#1#!"
        into
        "Let me show you my <span class="spellcast">Fireball</span>!"
     
    .EXAMPLE
        PS C:\> Get-ChildItem *.md | Read-EBMarkdown
 
        Reads and converts all markdown files in he current folder
    #>

    [OutputType([EbookBuilder.Page])]
    [CmdletBinding()]
    param (
        [parameter(ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true)]
        [Alias('FullName')]
        [string[]]
        $Path,
        
        [hashtable]
        $InlineStyles = @{ }
    )
    
    begin {
        function ConvertFrom-Markdown {
            [OutputType([EbookBuilder.Page])]
            [CmdletBinding()]
            param (
                [string]
                $Path,
                
                [int]
                $Index,
                
                [hashtable]
                $InlineStyles = @{ }
            )
            
            $lines = Get-Content -Path $Path -Encoding UTF8 | ConvertFrom-InlineStyle -InlineStyles $InlineStyles
            $stringBuilder = New-SBStringBuilder -Name ebook
            $PSDefaultParameterValues['Add-SBLine:Name'] = 'ebook'
            
            $inBlock = $false
            $inCode = $false
            $inBullet = $false
            $inNote = $false
            $inParagraph = $false
            
            $blockData = [pscustomobject]@{
                Attributes = @{ }
                Type       = $null
                Lines       = @()
                File       = $Path
            }
            $paragraph = @()
            $firstPar = $true
            
            foreach ($line in $lines) {
                #region Process Block Content
                if ($inBlock) {
                    if ($line -like '## <*') {
                        try { $firstPar = ConvertFrom-MdBlock -Type $blockData.Type -Lines $blockData.Lines -Attributes $blockData.Attributes -StringBuilder $stringBuilder }
                        catch { Stop-PSFFunction -Message 'Failed to convert block' -ErrorRecord $_ -Target $blockData -EnableException $true -Cmdlet $PSCmdlet }
                        $inBlock = $false
                    }
                    else { $blockData.Lines += $line }
                    
                    continue
                }
                #endregion Process Block Content
                
                #region Process Code Content
                if ($inCode) {
                    if ($line -like '``````*') {
                        $paragraph = @()
                        Add-SBLine '</pre>'
                        $inCode = $false
                        $firstPar = $true
                        continue
                    }
                    Add-SBLine $line
                    continue
                }
                #endregion Process Code Content
                
                #region Process Bullet Point
                if ($inBullet) {
                    if (-not $line.Trim()) {
                        Add-SBLine '<li class="defaultLI">{0}</li>' -Values ($paragraph -join ' ')
                        Add-SBLine '</ul>'
                        $paragraph = @()
                        $inBullet = $false
                        $firstPar = $true
                        continue
                    }
                    if ($line -notlike '+ *') {
                        $paragraph += $line
                        continue
                    }
                    
                    if ($paragraph) {
                        Add-SBLine '<li class="defaultLI">{0}</li>' -Values ($paragraph -join ' ')
                        $paragraph = @()
                    }
                    $paragraph += $line -replace '^\+ '
                    continue
                }
                #endregion Process Bullet Point
                
                #region Process Notes
                if ($inNote) {
                    if ($line.Trim()) {
                        $paragraph += $line -replace '^>\s{0,1}'
                        continue
                    }
                    
                    foreach ($text in ConvertFrom-EBMarkdown -Line $paragraph -ClassFirstParagraph noteFirstPar -ClassParagraph noteText -EmphasisClass noteEmphasis) {
                        Add-SBLine $text
                    }
                    Add-SBLine '<hr/></div>'
                    $inNote = $false
                    $firstPar = $true
                    $paragraph = @()
                    continue
                }
                #endregion Process Notes
                
                #region Process Paragraph
                if ($inParagraph) {
                    if ($line.Trim()) {
                        $paragraph += $line
                        continue
                    }
                    
                    $class = 'text'
                    if ($firstPar) {
                        $class = 'firstpar'
                        $firstPar = $false
                    }
                    
                    foreach ($text in ConvertFrom-EBMarkdown -Line $paragraph -ClassFirstParagraph $class -ClassParagraph $class) {
                        Add-SBLine $text
                    }
                    $paragraph = @()
                    $inParagraph = $false
                    continue
                }
                #endregion Process Paragraph
                
                #region Region Starters
                # Handle begin of a Block
                if ($line -like '## <*') {
                    $inBlock = $true
                    $blockData = New-Block -Line $line -Path $Path
                    continue
                }
                
                # Handle begin of a Code section
                if ($line -like '``````*') {
                    $inCode = $true
                    $firstPar = $true
                    Add-SBLine '<pre>'
                    continue
                }
                
                # Handle begin of a Bullet-Points section
                if ($line -like '+ *') {
                    $inBullet = $true
                    Add-SBLine '<ul>'
                    $paragraph += $line -replace '^\+ '
                    continue
                }
                
                # Handle begin of a Notes section
                if ($line -like '> *') {
                    $inNote = $true
                    Add-SBLine '<div class="notes"><hr/>'
                    $paragraph += $line -replace '^> '
                    continue
                }
                
                # Handle Chapter Title
                if ($line -like '# *') {
                    $null = $stringBuilder.AppendLine("<h2>$($line -replace '^# ')</h2>")
                    continue
                }
                
                # Handle begin of a Paragraph section
                if ($line.Trim()) {
                    $inParagraph = $true
                    $paragraph += $line
                }
                #endregion Region Starters
            }
            
            #region Cleanup
            
            #region Process Block Content
            if ($inBlock) {
                try { $firstPar = ConvertFrom-MdBlock -Type $blockData.Type -Lines $blockData.Lines -Attributes $blockData.Attributes -StringBuilder $stringBuilder }
                catch { Stop-PSFFunction -Message 'Failed to convert block' -ErrorRecord $_ -Target $blockData -EnableException $true -Cmdlet $PSCmdlet }
                $inBlock = $false
            }
            #endregion Process Block Content
            
            #region Process Code Content
            if ($inCode) {
                Add-SBLine '</pre>'
                $inCode = $false
                $firstPar = $true
            }
            #endregion Process Code Content
            
            #region Process Bullet Point
            if ($inBullet) {
                Add-SBLine '<li class="defaultLI">{0}</li>' -Values ($paragraph -join ' ')
                Add-SBLine '</ul>'
                $paragraph = @()
                $inBullet = $false
                $firstPar = $true
            }
            #endregion Process Bullet Point
            
            #region Process Notes
            if ($inNote) {
                foreach ($text in ConvertFrom-EBMarkdown -Line $paragraph -ClassFirstParagraph noteFirstPar -ClassParagraph noteText -EmphasisClass noteEmphasis) {
                    Add-SBLine $text
                }
                Add-SBLine '<hr/></div>'
                $inNote = $false
                $firstPar = $true
                $paragraph = @()
            }
            #endregion Process Notes
            
            #region Process Paragraph
            if ($inParagraph) {
                $class = 'text'
                if ($firstPar) {
                    $class = 'firstpar'
                    $firstPar = $false
                }
                
                foreach ($text in ConvertFrom-EBMarkdown -Line $paragraph -ClassFirstParagraph $class -ClassParagraph $class) {
                    Add-SBLine $text
                }
                $paragraph = @()
                $inParagraph = $false
            }
            #endregion Process Paragraph
            #endregion Cleanup
            
            New-Object EbookBuilder.Page -Property @{
                Index = $Index
                Name  = (Get-Item -Path $Path).BaseName
                Content = Close-SBStringBuilder -Name ebook
                SourceName = $Path
                TimeCreated = Get-Date
                MetaData = @{ }
            }
        }
        
        function ConvertFrom-InlineStyle {
            [OutputType([string])]
            [CmdletBinding()]
            param (
                [Parameter(ValueFromPipeline = $true)]
                [string[]]
                $Line,
                
                [hashtable]
                $InlineStyles = @{ }
            )
            
            begin {
                $replaceHash = @{ }
                
                foreach ($pair in $InlineStyles.GetEnumerator()) {
                    $replaceHash["#$($pair.Key)#(.+?)#$($pair.Key)#"] = '<span class="{0}">$1</span>' -f $pair.Value
                }
            }
            process {
                foreach ($string in $Line) {
                    foreach ($pair in $replaceHash.GetEnumerator()) {
                        $string = $string -replace $pair.Key, $pair.Value
                    }
                    $string
                }
            }
        }
        
        function New-Block {
            [Diagnostics.CodeAnalysis.SuppressMessageAttribute('PSUseShouldProcessForStateChangingFunctions', '')]
            [CmdletBinding()]
            param (
                [string]
                $Line,
                
                [string]
                $Path
            )
            
            $type = $Line -replace '## <(\w+).+$', '$1'
            $attributes = @{ }
            $entries = $Line | Select-String '(\w+)="(.+?)"' -AllMatches
            foreach ($match in $entries.Matches) {
                $attributes[$match.Groups[1].Value] = $match.Groups[2].Value
            }
            
            [pscustomobject]@{
                Attributes = $attributes
                Type       = $type
                Lines       = @()
                File       = $Path
            }
        }
        
        $Index = 1
    }
    process {
        foreach ($pathItem in $Path) {
            Write-PSFMessage -Message "Processing: $pathItem"
            ConvertFrom-Markdown -Path $pathItem -Index $Index -InlineStyles $InlineStyles
            $Index++
        }
    }
}