-
-
Notifications
You must be signed in to change notification settings - Fork 241
/
document.coffee
executable file
·628 lines (498 loc) · 13.9 KB
/
document.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
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
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
# Necessary
pathUtil = require('path')
balUtil = require('bal-util')
_ = require('underscore')
mime = require('mime')
# Optional
CSON = null
yaml = null
# Local
FileModel = require(__dirname+'/file')
# ---------------------------------
# Document Model
class DocumentModel extends FileModel
# Model Type
type: 'document'
# ---------------------------------
# Attributes
defaults:
# ---------------------------------
# Special variables
# outExtension
# The final extension used for our file
# Takes into accounts layouts
# "layout.html", "post.md.eco" -> "html"
# already defined in file.coffee
# Whether or not we reference other doucments
referencesOthers: false
# ---------------------------------
# Content variables
# The file meta data (header) in string format before it has been parsed
header: null
# The parser to use for the file's meta data (header)
parser: null
# The file content (body) before rendering, excludes the meta data (header)
body: null
# Have we been rendered yet?
rendered: false
# The rendered content (after it has been wrapped in the layouts)
contentRendered: false
# The rendered content (before being passed through the layouts)
contentRenderedWithoutLayouts: null
# ---------------------------------
# User set variables
# Whether or not this file should be re-rendered on each request
dynamic: false
# The tags for this document
tags: null # Array
# Whether or not we want to render single extensions
renderSingleExtensions: false
# ---------------------------------
# Functions
# Initialize
initialize: (attrs,opts) ->
# Prepare
{@layouts,meta} = opts
# Forward
super
# Get Meta
getMeta: ->
return @meta
# To JSON
toJSON: ->
data = super
data.meta = @getMeta().toJSON()
return data
# References Others
referencesOthers: (flag) ->
flag ?= true
@set({referencesOthers:flag})
@
# Parse data
# Parses some data, and loads the meta data and content from it
# next(err)
parseData: (data,next) ->
# Prepare
meta = @getMeta()
# Wipe any meta attributes that we've copied over to our file
reset = {}
for own key,value of meta.attributes
reset[key] = @defaults[key]
reset = balUtil.dereference(reset)
@set(reset)
# Then wipe the layout and clear the meta attributes from the meta model
@layout = null
meta.clear()
# Reparse the data and extract the content
# With the content, fetch the new meta data, header, and body
super data, =>
# Content
content = @get('content')
# Meta Data
match = /^\s*([^\s\d\w]{3,})(?: ([a-z]+))?([\s\S]*?)\1/.exec(content)
if match
# Extract
seperator = match[1]
parser = match[2] or 'yaml'
header = match[3].trim()
body = content.substring(match[0].length).trim()
# Parse
try
switch parser
when 'cson', 'coffee', 'coffeescript', 'coffee-script'
CSON = require('cson') unless CSON
meta = CSON.parseSync(header)
@meta.set(meta)
when 'yaml'
yaml = require('yaml') unless yaml
meta = yaml.eval(header)
@meta.set(meta)
else
err = new Error("Unknown meta parser: #{parser}")
return next(err)
catch err
return next(err)
else
body = content
# Update meta data
body = body.replace(/^\n+/,'')
@set(
source: content
content: body
header: header
body: body
parser: parser
name: @get('name') or @get('title') or @get('basename')
)
# Correct data format
metaDate = @meta.get('date')
if metaDate
metaDate = new Date(metaDate)
@meta.set({date:metaDate})
# Correct ignore
ignored = @meta.get('ignored') or @meta.get('ignore') or @meta.get('skip') or @meta.get('draft') or (@meta.get('published') is false)
@meta.set({ignored:true}) if ignored
# Handle urls
metaUrls = @meta.get('urls')
metaUrl = @meta.get('url')
@addUrl(metaUrls) if metaUrls
@addUrl(metaUrl) if metaUrl
# Apply meta to us
@set(@meta.toJSON())
# Next
next()
@
# Write the rendered file
# next(err)
writeRendered: (next) ->
# Prepare
file = @
fileOutPath = @get('outPath')
contentRendered = @get('contentRendered')
encoding = @get('encoding')
# Log
file.log 'debug', "Writing the rendered file: #{fileOutPath} #{encoding}"
# Write data
balUtil.writeFile fileOutPath, contentRendered, (err) ->
# Check
return next(err) if err
# Log
file.log 'debug', "Wrote the rendered file: #{fileOutPath} #{encoding}"
# Next
return next()
# Chain
@
# Write the file
# next(err)
writeSource: (next) ->
# Prepare
file = @
CSON = require('cson') unless CSON
# Fetch
fullPath = @get('fullPath')
content = @get('content')
parser = 'cson'
seperator = '---'
# Log
file.log 'debug', "Writing the source file: #{fullPath}"
# Adjust
header = CSON.stringifySync(@meta.toJSON())
content = body = content.replace(/^\s+/,'')
source = "#{seperator} #{parser}\n#{header}\n#{seperator}\n\n#{body}"
# Apply
@set({parser,header,body,content,source})
# Write content
balUtil.writeFile fileOutPath, source, (err) ->
# Check
return next(err) if err
# Log
file.log 'info', "Wrote the source file: #{fullPath}"
# Next
next()
# Chain
@
# Normalize data
# Normalize any parsing we have done, as if a value has updates it may have consequences on another value. This will ensure everything is okay.
# next(err)
normalize: (opts={},next) ->
# Prepare
{opts,next} = @getActionArgs(opts,next)
# Super
super =>
# Extract
extensions = @get('extensions')
# Extension Rendered
if extensions? and extensions.length
outExtension = extensions[0]
@set({outExtension})
# Next
next()
# Chain
@
# Contextualize data
# Put our data into perspective of the bigger picture. For instance, generate the url for it's rendered equivalant.
# next(err)
contextualize: (opts={},next) ->
# Prepare
{opts,next} = @getActionArgs(opts,next)
# Super
super =>
# Get our highest ancestor
@getEve (err,eve) =>
# Check
return next(err) if err
# Prepare
changes = {}
# Fetch
meta = @getMeta()
fullPath = @get('fullPath')
basename = @get('basename')
relativeDirPath = @get('relativeDirPath')
extensions = @get('extensions')
outExtension = @get('outExtension')
url = meta.get('url') or null
name = meta.get('name') or null
outPath = meta.get('outPath') or null
outFilename = null
# Use our eve's rendered extension if it exists
if eve?
outExtension = eve.get('outExtension')
# Figure out the rendered filename
if basename and outExtension
if basename[0] is '.' and outExtension is extensions[0]
outFilename = basename
else
outFilename = "#{basename}.#{outExtension}"
changes.outFilename = outFilename
# Figure out the rendered url
if outFilename
if relativeDirPath
relativeOutPath = "#{relativeDirPath}/#{outFilename}"
else
relativeOutPath = "#{outFilename}"
changes.relativeOutPath = relativeOutPath
unless url
changes.url = url = "/#{relativeOutPath}"
# Set name if it doesn't exist already
if !name and outFilename?
changes.name = name = outFilename
# Create the outPath if we have a outpute directory
if @outDirPath
changes.outPath = outPath = pathUtil.join(@outDirPath,relativeOutPath)
# Update the URL
if url
@removeUrl(@get('url'))
@setUrl(url)
# Content Types
if outPath or fullPath
changes.outContentType = outContentType = mime.lookup(outPath or fullPath)
# Apply
@set(changes)
# Forward
next()
# Chain
@
# Has Layout
# Checks if the file has a layout
hasLayout: ->
return @get('layout')?
# Get Layout
# The the layout object that this file references (if any)
# next(err,layout)
getLayout: (next) ->
# Prepare
file = @
layoutId = @get('layout')
# No layout
unless layoutId
return next(null,null)
# Cached layout
else if @layout and layoutId is @layout.id
# Forward
return next(null,@layout)
# Uncached layout
else
# Find parent
@emit 'getLayout', {layoutId}, (err,opts) ->
# Prepare
{layout} = opts
# Error
if err
return next(err)
# Not Found
else unless layout
err = new Error "Could not find the specified layout: #{layoutId}"
return next(err)
# Found
else
# Update our layout id with the definitive correct one
file.set('layout': layout.id)
# Cache our layout
file.layout = layout
# Forward
return next(null,layout)
# Chain
@
# Get Eve
# Get the most ancestoral layout we have (the very top one)
# next(err,layout)
getEve: (next) ->
if @hasLayout()
@getLayout (err,layout) ->
if err
return next(err,null)
else
layout.getEve(next)
else
next(null,@)
@
# Render extensions
# next(err,result)
renderExtensions: (opts,next) ->
# Prepare
file = @
extensions = @get('extensions')
filename = @get('filename')
{content,templateData,renderSingleExtensions} = opts
content ?= @get('body')
templateData ?= {}
renderSingleExtensions ?= @get('renderSingleExtensions')
# Prepare result
result = content
# Prepare extensions
extensionsReversed = []
if extensions.length is 0 and filename
extensionsReversed.push(filename)
for extension in extensions
extensionsReversed.unshift(extension)
# If we want to allow rendering of single extensions, then add null to the extension list
if renderSingleExtensions and extensionsReversed.length is 1
if renderSingleExtensions isnt 'auto' or filename.replace(/^\./,'') is extensionsReversed[0]
extensionsReversed.push(null)
# If we only have one extension, then skip ahead to rendering layouts
return next(null,result) if extensionsReversed.length <= 1
# Prepare the tasks
tasks = new balUtil.Group (err) ->
# Forward with result
return next(err,result)
# Cycle through all the extension groups and render them
for extension,index in extensionsReversed[1..]
# Push the task
context =
inExtension: extensionsReversed[index]
outExtension: extension
tasks.push context, (complete) ->
# Prepare
eventData =
inExtension: @inExtension
outExtension: @outExtension
templateData: templateData
file: file
content: result
# Render
file.trigger 'render', eventData, (err) ->
return complete(err) if err
result = eventData.content
return complete()
# Run tasks synchronously
tasks.sync()
# Chain
@
# Render Document
# next(err,result)
renderDocument: (opts,next) ->
# Prepare
file = @
extension = @get('extensions')[0]
{opts,next} = @getActionArgs(opts,next)
{content,templateData} = opts
content ?= @get('body')
templateData ?= {}
# Prepare event data
eventData = {extension,templateData,file,content}
# Render via plugins
file.trigger 'renderDocument', eventData, (err) ->
# Forward
return next(err,eventData.content)
# Chain
@
# Render Layouts
# next(err,result)
renderLayouts: (opts,next) ->
# Prepare
file = @
{opts,next} = @getActionArgs(opts,next)
{content,templateData} = opts
content ?= @get('body')
templateData ?= {}
# Grab the layout
file.getLayout (err,layout) ->
# Check
return next(err,content) if err
# Check if we have a layout
if layout
# Assign the current rendering to the templateData.content
templateData.content = content
# Merge in the layout meta data into the document JSON
# and make the result available via documentMerged
# templateData.document.metaMerged = _.extend({}, layout.getMeta().toJSON(), file.getMeta().toJSON())
# Render the layout with the templateData
layout.render {templateData}, (err,result) ->
return next(err,result)
# We don't have a layout, nothing to do here
else
return next(null,content)
# Render
# Render this file
# next(err,result,document)
render: (opts={},next) ->
# Prepare
file = @
contentRenderedWithoutLayouts = null
fullPath = @get('fullPath')
# Prepare options
{opts,next} = @getActionArgs(opts,next)
opts = _.clone(opts or {})
opts.actions ?= ['renderExtensions','renderDocument','renderLayouts']
# Prepare content
opts.content ?= @get('body')
# Prepare templateData
opts.templateData = _.clone(opts.templateData or {})
opts.templateData.document ?= file.toJSON()
opts.templateData.documentModel ?= file
# Prepare result
# file.set({contentRendered:null, contentRenderedWithoutLayouts:null, rendered:false})
# Log
file.log 'debug', "Rendering the file: #{fullPath}"
# Prepare the tasks
tasks = new balUtil.Group (err) ->
# Error?
if err
file.log 'warn', "Something went wrong while rendering: #{fullPath}"
return next(err, opts.content, file)
# Apply
contentRendered = opts.content
contentRenderedWithoutLayouts ?= contentRendered
rendered = true
file.set({contentRendered, contentRenderedWithoutLayouts, rendered})
# Log
file.log 'debug', "Rendering completed for: #{fullPath}"
# Success
return next(null, opts.content, file)
# Render Extensions Task
if 'renderExtensions' in opts.actions
tasks.push (complete) ->
file.renderExtensions opts, (err,result) ->
# Check
return complete(err) if err
# Apply the result
opts.content = result
# Done
return complete()
# Render Document Task
if 'renderDocument' in opts.actions
tasks.push (complete) ->
file.renderDocument opts, (err,result) ->
# Check
return complete(err) if err
# Apply the result
opts.content = result
contentRenderedWithoutLayouts = result
# Done
return complete()
# Render Layouts Task
if 'renderLayouts' in opts.actions
tasks.push (complete) ->
file.renderLayouts opts, (err,result) ->
# Check
return complete(err) if err
# Apply the result
opts.content = result
# Done
return complete()
# Fire the tasks
tasks.sync()
# Chain
@
# Export
module.exports = DocumentModel