-
Notifications
You must be signed in to change notification settings - Fork 1
/
mini.von.js
90 lines (78 loc) · 2.85 KB
/
mini.von.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
/**
* @author Timur Kuzhagaliyev <[email protected]>
* @see https://github.com/TimboKZ/Von
* @copyright 2017
* @license MIT
*
* This is a template script for `mini`, a built-in Von template.
*/
const Promise = require('bluebird');
const path = require('path');
const pug = require('pug');
const PUG_TEMPLATE = path.join(__dirname, 'mini.pug');
class MiniTemplate {
/**
* This constructor is called by the parent Von process.
*
* @param {VonOptions} options
* @param {VonSchema} schema
*/
constructor(options, schema) {
this.options = options;
this.schema = schema;
// Default values
this.maxImagesPerRow = 6;
}
/**
* This function will be called by the parent Von process. It can be synchronous or asynchronous, this is up to you.
* If you chose to make it asynchronous, make sure it returns a Promise.
*
* @return {Promise.<string|null>}
*/
compile() {
return Promise.resolve()
.then(() => this.processSchema())
.then(() => this.compileTemplate())
// If you return a string here, it will be written to `options.output` file. If you pass `null,` Von will
// simply ignore the return value and carry on WITHOUT writing anything. In the latter case, Von will assume
// that you have handled writing to file yourself.
.then(compiledTemplate => compiledTemplate);
}
/**
* @return {Promise.<VonSchema>}
*/
processSchema() {
return Promise.resolve()
.then(() => {
for (let group of this.schema.groups) {
// Calculate an optimal amount of images per row
let count = group.images.length;
let maxLeftover = -Infinity;
let imagesPerRow = -1;
for(let currImagesPerRow = this.maxImagesPerRow; currImagesPerRow > Math.floor(this.maxImagesPerRow * 0.75); currImagesPerRow--) {
if (count % currImagesPerRow > maxLeftover) {
maxLeftover = count % imagesPerRow;
imagesPerRow = currImagesPerRow;
}
}
let rows = [];
let totalRows = Math.ceil(count / imagesPerRow);
for (let i = 0; i < totalRows; i++) {
rows.push(group.images.slice(i * imagesPerRow, (i + 1) * imagesPerRow));
}
group.rows = rows;
}
});
}
/**
* @return {Promise.<string>}
*/
compileTemplate() {
return Promise.resolve()
.then(() => {
let fn = pug.compileFile(PUG_TEMPLATE);
return fn({schema: this.schema});
});
}
}
module.exports = MiniTemplate;