-
Notifications
You must be signed in to change notification settings - Fork 1
/
dadi-dustjs-helpers.js
627 lines (538 loc) · 17.7 KB
/
dadi-dustjs-helpers.js
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
var ___dadiDustJsHelpers = (function (dust, options) { // eslint-disable-line
if (typeof exports !== 'undefined') {
var JSON5 = require('json5')
var marked = require('marked')
var moment = require('moment')
var pluralist = require('pluralist')
var _ = require('underscore')
var s = require('underscore.string')
var htmlStrip = require('striptags')
}
dust.webExtensions = options || {}
/*
* Returns the supplied 'data' parameter truncated using the supplied 'length' parameter
* Usage: {@Truncate data="{body}" length="250" ellipsis="true"/}
*/
dust.helpers.Truncate = function (chunk, context, bodies, params) {
var data = context.resolve(params.data)
var length = context.resolve(params.length)
var ellipsis = context.resolve(params.ellipsis)
var str
if (ellipsis === 'true' && data.length > length) {
str = data.substr(0, length)
if (data) {
str = str.replace(/[\W]*$/, '…')
}
} else {
str = data.substr(0, length)
}
return chunk.write(str)
}
/*
* Returns the supplied 'data' parameter trimmed of whitespace on both left and right sides
* Usage: {@Trim data="{body}"/}
*/
dust.helpers.Trim = function (chunk, context, bodies, params) {
var data = context.resolve(params.data)
return chunk.write(data.trim())
}
/*
* Returns the supplied 'data' parameter formatted using the supplied 'format' parameter
* Pass a unix epoch time (expects milliseconds) in the 'unix' parameter. For seconds use 'unix_sec'
* Usage: {@formatDate data="{body}" [unix="{lastModifiedAt}"] format="YYYY-MM-DDTh:mm:ss+01:00"/}
*/
dust.helpers.formatDate = function (chunk, context, bodies, params) {
var format = context.resolve(params.format)
var parseFormat = context.resolve(params.parseFormat)
if (params.unix_sec) {
var unixSec = context.resolve(params.unix_sec)
return chunk.write(moment.unix(unixSec).format(format))
} else if (params.unix) {
var unix = context.resolve(params.unix)
return chunk.write(moment.unix(unix / 1000).format(format))
} else {
var data = context.resolve(params.data)
return chunk.write(moment(data, parseFormat || format).format(format))
}
}
/*
* Returns the supplied 'data' parameter formatted using the supplied parameters
* See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
* Params:
* localeString: e.g. 'en-GB'
* style
* currency
* minimumFractionDigits
*
* options: An object containing properties to determine how the formatting should be applied.
* Unless above params exist, the default is: {style: 'decimal', minimumFractionDigits: 0}
* Usage:
* {@formatNumber data="12345" localeString="en-GB" /} => 12,345
* {@formatNumber data="12345" localeString="en-GB" style="currency" currency="GBP" minimumFractionDigits="0"/} => £12,345
*/
dust.helpers.formatNumber = function (chunk, context, bodies, params) {
var data = context.resolve(params.data)
var localeString = context.resolve(params.localeString)
var style = context.resolve(params.style)
var currency = context.resolve(params.currency)
var fractionDigits = context.resolve(params.minimumFractionDigits)
var options = {style: 'decimal', minimumFractionDigits: 0}
if (style) options.style = style
if (currency) options.currency = currency
if (fractionDigits) options.minimumFractionDigits = fractionDigits
try {
if (data && localeString) {
var result = parseFloat((data).toFixed(2)).toLocaleString(localeString, options)
result = result.replace(/\.([\d])$/, '.$10')
return chunk.write(result)
} else {
return chunk.write(data)
}
} catch (err) {
console.log(err)
if (err.stack) console.log(err.stack)
return chunk.write(data)
}
}
/*
* Returns the markdown content formatted as HTML
*/
dust.helpers.markdown = function (chunk, context, bodies, params) {
var renderer = new marked.Renderer()
renderer.link = function (href, title, text) {
var attrArray = href.split('|')
var attrs = {}
var first = attrArray.shift()
if (first) href = first
for (var i = 0; i < attrArray.length; i++) {
var attr = attrArray[i]
var attrName = ''
var attrValue = ''
var pos = attr.indexOf('=')
if (pos > 0) {
attrName = attr.substr(0, pos)
attrValue = attr.substr(pos + 1)
}
attrs[attrName] = attrValue
}
var attrString = ''
Object.keys(attrs).forEach(function (key) {
attrString = attrString + key + '="' + attrs[key] + '" '
})
if (title && title.length > 0) {
title = ' title="' + title + '"'
} else {
title = ''
}
return '<a href="' + href + '" ' + attrString + title + '>' + text + '</a>'
}
if (bodies.block) {
return chunk.capture(bodies.block, context, function (string, chunk) {
chunk.end(marked(string, { renderer: renderer }))
})
}
return chunk
}
/*
* Returns the markdown content formatted as HTML, but without <p> wrappers
*/
dust.helpers.soberMarkdown = function (chunk, context, bodies, params) {
if (bodies.block) {
return chunk.capture(bodies.block, context, function (string, chunk) {
var md = marked(string)
// Replace </p><p> with <br>
var str = md.replace(/<\/p><p[^>]*>/igm, '<br>')
// Remove wrapping <p></p> tags
str = str.replace(/<p[^>]*>(.*?)<\/p>/igm, '$1')
chunk.end(str)
})
}
return chunk
}
/*
* Returns the supplied 'str' parameter with any instanses of {...} resolved to {vartoreplace}
* Usage: {@forceRender str="{body}" value="{vartoreplace}" /}
*/
dust.helpers.forceRender = function (chunk, context, bodies, params) {
var str = context.resolve(params.str)
var value = context.resolve(params.value)
str = str.replace(/{.*?}/gmi, value)
return chunk.write(str)
}
/*
* iter iterates over `items`, much like using `{#items}{/items}`,
* but with the possiblity to loop over a subset, and in any direction
* Usage:
* ```
* {@iter items=arrayOfItems from=0 to=12}
* run for each item, with the item as context
* {/iter}
* ```
*/
dust.helpers.iter = function (chunk, context, bodies, params) {
params.items = params.items || []
params.from = params.from || 0
params.to = params.to === 0 ? 0 : params.to || params.items.length
var direction
if (params.from < params.to) {
direction = 1
} else {
direction = -1
// to reach the beginning of the array we need to go to -1
params.to--
}
var metaContext = {
$idx: params.from,
$len: params.items.length
}
context = context.push(metaContext)
while (metaContext.$idx !== params.to) {
if (params.items[metaContext.$idx]) {
chunk = chunk.render(bodies.block, context.push(params.items[metaContext.$idx]))
}
metaContext.$idx += direction
}
// pop metaContext
context.pop()
return chunk
}
/*
* Strips HTML from passed content
* Uses: https://github.com/zaro/node-htmlstrip-native
*/
dust.helpers.htmlstrip = function (chunk, context, bodies, params) {
return chunk.capture(bodies.block, context, function (data, chunk) {
data = htmlStrip(data).trim()
chunk.write(data)
chunk.end()
})
}
/*
* Default values for partials
*/
dust.helpers.defaultParam = function (chunk, context, bodies, params) {
var key = params.key
var value = params.value
if (typeof context.get(key) === 'undefined' || context.get(key) === null) {
var obj = {}
obj[key] = value
var ctx = dust.makeBase(obj)
var global = context.global || {}
context.global = _.extend(global, ctx.global)
}
}
/*
* Numbers with commas
*/
dust.helpers.numberCommas = function (chunk, context, bodies, params) {
return chunk.capture(bodies.block, context, function (data, chunk) {
data = data.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')
chunk.write(data)
chunk.end()
})
}
dust.helpers.plural = function (chunk, context, bodies, params) {
var options = {
val: params.val,
auto: params.auto,
one: params.one,
many: params.many
}
if (typeof options.val !== 'undefined') {
var multiple = Boolean(Number(options.val) - 1)
if (typeof options.auto !== 'undefined') {
return chunk.write(multiple ? pluralist.plural(options.auto).anglicised_plural : pluralist.singular(options.auto).singular_suffix)
} else if (options.one && options.many) {
var str = multiple ? options.many : options.one
return chunk.write(str)
}
} else if (options.auto) {
return chunk.write(options.auto)
} else {
return chunk.write('')
}
}
/*
* Encode html to json valid
*/
dust.helpers.htmlEncode = function (chunk, context, bodies, params) {
return chunk.capture(bodies.block, context, function (data, chunk) {
data = JSON.stringify(data.toString())
chunk.write(data)
chunk.end()
})
}
/*
* Use the Underscore.JS Slugify method to generate a URL friendly string
* Usage:
* ```
* {@slugify}{title}{/slugify}
* ```
*/
dust.helpers.slugify = function (chunk, context, bodies, params) {
return chunk.capture(bodies.block, context, function (data, chunk) {
data = s.slugify(data)
chunk.write(data)
chunk.end()
})
}
/**
* Performs a global search and replace within a string.
* In the following example, we replace all periods in the
* message string with dashes.
*
* {@replace str="{message}" search="." replace="-" /}
*
* str - the input string within which the search and replace will be performed
* search - the character or sequence to search
* replace - the character or sequence used to replace
*/
dust.helpers.replace = function (chunk, context, bodies, params) {
var str = context.resolve(params.str)
var search = context.resolve(params.search)
var replace = context.resolve(params.replace)
var result = str.replace(new RegExp(escapeRegExp(search), 'g'), replace)
return chunk.write(result)
}
/**
* Processes the given string to escape special meta characters used within
* Regular Expressions. This is used by the replace helper.
*/
function escapeRegExp (string) {
return string.replace(/([.*+?^=!:${}()|[\]/\\])/g, '\\$1')
}
/**
* Generate URLs based on routes by sending in page names & parameters
* Usage:
* ```
* {@url page="pagename" param="val" otherparam=variableval/}
* ```
*/
dust.helpers.url = (function () {
return function (chunk, context, bodies, params) {
if (!dust.webExtensions.components) {
throw new Error('The @url helper needs the loaded components from DADI Web.')
}
// Ensure a page name is input
if (typeof params.page === 'undefined') {
throw new Error('The @url helper needs a page to work. Please send it in as a string (double quote marks if not referencing a variable).')
}
// Get the page
var component = _.find(dust.webExtensions.components, function (component) {
return component.page.key === params.page
})
if (!component) {
throw new Error('The @url helper could not find a page with the key "' + params.page + '".')
}
// Get the route
return component.page.toPath(_.omit(params, 'page'))
}
}())
/*
* Paginate pages
* Usage:
* Send in current page, total pages, and a pattern for the path to generate.
* In the path pattern, use the dust variable `n` where you want the page number inserted.
* ```
* {@paginate page=currentPageNumber totalPages=totalPageCount path="/page/{n}"}
* <a href="{path}">{n}</a>
* {:current}
* <a href="{path}">Current page {n}</a>
* {:prev}
* <a href="{path}">Prev</a>
* {:next}
* <a href="{path}">Next</a>
* {/paginate}
* ```
*/
dust.helpers.paginate = function (chunk, context, bodies, params) {
var err
if (!('page' in params && 'totalPages' in params && 'path' in params)) {
err = new Error('Insufficient information provided to @paginate helper')
}
var current = parseInt(params.page, 10)
var totalPages = parseInt(params.totalPages, 10)
if (!(isFinite(current) && isFinite(totalPages))) {
err = new Error('Parameters provided to @paginate helper are not integers')
}
// var path = params.path
var paginateContext = {
n: current,
path: ''
}
if (err) {
console.log(err)
return chunk
}
context = context.push(paginateContext)
function printStep (body, n) {
paginateContext.n = n
paginateContext.path = context.resolve(params.path)
if (n === 1) {
// this is to make the path just the base path, without the number
paginateContext.path = (paginateContext.path || '').replace(/1\/?$/, '')
}
chunk.render(body, context)
}
var printGap = bodies.gap ? printStep.bind(null, bodies.gap) : function () {}
function printStepOrGap (step) {
if (step === '.') {
printGap()
} else {
printStep(bodies.block, step)
}
}
function getStepSize (distance) {
if (distance > 550) {
return 500
} else if (distance > 110) {
return 100
} else if (distance > 53) {
return distance - 25
} else if (distance > 23) {
return distance - 10
} else if (distance >= 10) {
return distance - 5
} else if (distance >= 5) {
return distance - 2
} else {
return 1
}
}
function makeSteps (start, end, tightness) {
// start & end are non-inclusive
var now
var final
var stepSize
var steps = []
if (tightness === 'increase') {
now = start
final = end
while (now < final) {
if (now !== start) {
steps.push(now)
}
stepSize = getStepSize(final - now)
if (stepSize > 1) {
steps.push('.')
}
now += stepSize
}
} else { // decrease
now = end
final = start
while (now > final) {
if (now !== end) {
steps.push(now)
}
stepSize = getStepSize(now - final)
if (stepSize > 1) {
steps.push('.')
}
now -= stepSize
}
steps.reverse()
}
return steps
}
// Only one page
if (!totalPages || totalPages === 1) {
if (bodies.else) {
return chunk.render(bodies.else, context)
}
return chunk
}
if (current > 1) {
// Prev
if (bodies.prev) {
printStep(bodies.prev, current - 1)
}
// First step
printStep(bodies.block, 1)
// Pre current
_.each(makeSteps(1, current, 'increase'), printStepOrGap)
}
// Current
printStep(bodies.current, current)
if (current < totalPages) {
// Post current
_.each(makeSteps(current, totalPages, 'decrease'), printStepOrGap)
// Last step
printStep(bodies.block, totalPages)
// Next
if (bodies.next) {
printStep(bodies.next, current + 1)
}
}
return chunk
}
/*
* Get the first item matching the sent in params. Replaces iteration+eq combos.
* Usage:
* For arrays of objects each object has its property at key checked for a match with the provided value, much like underscore's `findWhere`
* ```
* {@findWhere list=aList key="id" value=id}
* {.}
* {/findWhere}
* ```
* You can also supply the `list` with `props`, which is a (loosely parsed by json5)
* JSON object in a string. This makes it possible to combine multiple filters.
* ```
* {@findWhere list=aList props="{attr: "{strvalue}", other: {numericalId}}"}
* {.}
* {/findWhere}
* ```
* Whatever you send in you will at most ever get one item back.
*/
dust.helpers.findWhere = function (chunk, context, bodies, params) {
var list = params.list
var key = params.key
var value = params.value
var props
var found
if ('list' in params && 'key' in params && 'value' in params) {
found = _.find(list, function (obj) {
return (obj[key] === value)
})
} else if ('list' in params && 'props' in params) {
try {
props = JSON5.parse(context.resolve(params.props))
} catch (err) {
throw new Error('The @findWhere dust helper received invalid json for props')
}
found = _.findWhere(list, props)
} else {
throw new Error('The @findWhere dust helper is missing a parameter')
}
if (found) {
return chunk.render(bodies.block, context.push(found))
} else if ('else' in bodies) {
return chunk.render(bodies.else, context)
}
return chunk
}
/*
* Render references to #hashtags in a block as links.
* Can be prefixed or suffixed with other url elements
* Usage:
* ```
* {@hashtagToLink [prefix="/url/"] [suffix="/url/"]}{body}{/hashtagToLink}
* ```
*/
dust.helpers.hashtagToLink = function (chunk, context, bodies, params) {
var prefix = params.prefix ? context.resolve(params.prefix) : ''
var suffix = params.suffix ? context.resolve(params.suffix) : ''
return chunk.capture(bodies.block, context, function (data, chunk) {
data = data.replace(/#([\w/]*)/gmi, '<a href="' + prefix + '$1' + suffix + '">#$1</a>')
chunk.write(data)
chunk.end()
})
}
})
if (typeof exports !== 'undefined') {
module.exports = function (dust, options) {
___dadiDustJsHelpers(dust, options)
}
} else {
___dadiDustJsHelpers(dust) // eslint-disable-line
}