-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathpartials.plugin.coffee
More file actions
259 lines (207 loc) · 6.57 KB
/
partials.plugin.coffee
File metadata and controls
259 lines (207 loc) · 6.57 KB
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
# Export Plugin
module.exports = (BasePlugin) ->
# Requires
extendr = require('extendr')
{Task,TaskGroup} = require('taskgroup')
pathUtil = require('path')
util = require('util')
# Define Plugin
class PartialsPlugin extends BasePlugin
# Plugin Name
name: 'partials'
# Default Configuration
config:
partialsPath: 'partials'
collectionName: 'partials'
performanceFirst: false
# Locale
locale:
addingPartial: "Adding partial: %s"
partialNotFound: "The partial \"%s\" was not found, as such it will not be rendered."
renderPartial: "Rendering partial: %s"
renderedPartial: "Rendered partial: %s"
renderPartialFailed: "Rendering partial failed: %s. The error follows:"
# Partial helpers
foundPartials: null # Object
partialsCache: null # Object
# -----------------------------
# Initialize
# Prepare our Configuration
constructor: ->
# Prepare
super
docpadConfig = @docpad.getConfig()
config = @getConfig()
# Creatte our found partials object
@partialsCache = {}
@foundPartials = {}
# DocPad -v6.24.0 Compatible
config.partialsPath = pathUtil.resolve(docpadConfig.srcPath, config.partialsPath)
# DocPad v6.24.0+ Compatible
# Configuration
setConfig: ->
# Prepare
super
docpadConfig = @docpad.getConfig()
config = @getConfig()
# Adjust
config.partialsPath = pathUtil.resolve(docpadConfig.srcPath, config.partialsPath)
# Chain
@
# -----------------------------
# Events
# Populate Collections
populateCollections: (opts,next) ->
# Prepare
config = @config
docpad = @docpad
# Load our partials directory
docpad.parseDocumentDirectory({path: config.partialsPath}, next)
# Chain
@
# Extend Collections
extendCollections: (opts) ->
# Prepare
config = @getConfig()
docpad = @docpad
locale = @locale
database = docpad.getDatabase()
# Add our partials collection
docpad.setCollection(config.collectionName, database.createLiveChildCollection()
.setQuery('isPartial', {
$or:
isPartial: true
fullPath: $startsWith: config.partialsPath
})
.on('add', (model) ->
docpad.log('debug', util.format(locale.addingPartial, model.getFilePath()))
model.setDefaults(
isPartial: true
render: false
write: false
)
)
)
# Chain
@
# -----------------------------
# Rendering
# Render Partial
# Render a partial asynchronously
# next(err,result,document)
renderPartial: (partial,next) ->
# Prepare
docpad = @docpad
locale = @locale
partialsCache = @partialsCache
result = null
# Check if our partial is cacheable
cacheable = partial.document.getMeta().get('cacheable') ? false
if cacheable is true
result = partialsCache[partial.cacheId] ? null
# Got from cache, so use that
return next(null, result) if result?
# Render
docpad.renderDocument partial.document, {templateData:partial.data}, (err,result,document) ->
# Check
return next(err) if err
# Cache
if cacheable is true
partialsCache[partial.cacheId] = result
# Forward
return next(null, result)
# Chain
@
# Extend Template Data
# Inject our partial methods
extendTemplateData: ({templateData}) ->
# Prepare
me = @
docpad = @docpad
locale = @locale
# Apply
templateData.partial = (partialName, objs...) ->
# Reference others
config = me.getConfig()
@referencesOthers?()
# Prepare
file = @documentModel
partial = {}
# Fetch our partial
partialFuzzyPath = pathUtil.join(config.partialsPath, partialName)
partial.document ?= docpad.getCollection('partials').fuzzyFindOne(partialFuzzyPath)
unless partial.document
# Partial was not found
message = util.format(locale.partialNotFound, partialName)
err = new Error(message)
partial.err ?= err
return message
# Prepare the initial partial data
partial.data = {}
# If no object is provided then provide the current template data as the first thing
# if the performance first option is set to false (the default)
if config.performanceFirst is false
objs.unshift(@) unless objs[0] in [false, @]
# Cycle through the objects merging them together
# ignore boolean values
for obj in objs
continue unless obj or obj is true
extendr.shallowExtendPlainObjects(partial.data, obj)
# ^ why do we just do a shallow extend here instead of a deep extend?
# Prepare our partial id
partial.path = partial.document.getFilePath()
partial.cacheId = partial.document.id
partial.id = Math.random() # require('crypto').createHash('md5').update(partial.cacheId+'|'+JSON.stringify(partial.data)).digest('hex')
partial.container = '[partial:'+partial.id+']'
# Check if a partial with this id already exists!
if me.foundPartials[partial.id]
return partial.container
# Store the partial
me.foundPartials[partial.id] = partial
# Create the task for our partial
partial.task = new Task "renderPartial: #{partial.path}", (complete) ->
me.renderPartial partial, (err, result) ->
partial.err ?= err
partial.result = partial.err?.toString() ? result ? '???'
return complete(partial.err)
# Return the container
return partial.container
# Chain
@
# Render the Document
# Render our partials
renderDocument: (opts,next) ->
# Prepare
{templateData, file} = opts
# Check
partialContainerRegex = /\[partial:([^\]]+)\]/g
partialContainers = if typeof opts.content is 'string' then opts.content.match(partialContainerRegex) else []
return next() if not partialContainers? or partialContainers.length is 0
filePath = file.getFilePath()
# Prepare
me = @
tasks = new TaskGroup("Partials for #{filePath}", concurrency:0).done (err) ->
# Replace containers with results
opts.content = opts.content.replace partialContainerRegex, (match, partialId) ->
# Fetch partial
partial = me.foundPartials[partialId]
# Return result
return partial.result
# Complete
return next(err)
# Wait for found partials to complete rendering
partialContainers.forEach (partialContainer) ->
# Fetch partial
partialId = partialContainer.replace(partialContainerRegex, '$1')
partial = me.foundPartials[partialId]
# Wait for all the partials to complete rendering
tasks.addTask(partial.task) if partial.task
# Run the tasks
tasks.run()
# Chain
@
# Generate After
# Reset the found partials after each generate, otherwise it will get very big
generateAfter: ->
@foundPartials = {}
@partialsCache = {}