This repository has been archived by the owner on Mar 15, 2018. It is now read-only.
/
builder.js
344 lines (301 loc) · 13.3 KB
/
builder.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
define('builder',
['log', 'jquery', 'templates', 'models', 'requests', 'settings', 'z', 'nunjucks.compat'],
function(log, $, nunjucks, models, requests, settings, z) {
var console = log('builder');
var SafeString = nunjucks.require('runtime').SafeString;
var counter = 0;
var page = document.getElementById('page');
if (!page) {
// We can't run without a <div id="page">
console.error('Could not start the builder; #page not found!');
return;
}
function render(template, context, env) {
return (env || nunjucks.env).render(template, context || {});
}
var error_template = render(settings.fragment_error_template);
function parse_and_find(snippet, selector) {
var dom = document.implementation.createHTMLDocument('');
dom.body.innerHTML = snippet;
return dom.body.querySelector(selector);
}
function parse_and_replace(snippet, to_replace) {
var dom = document.implementation.createHTMLDocument('');
dom.body.innerHTML = snippet;
var parent = to_replace.parentNode;
while (dom.body.childNodes.length) {
var child = dom.body.childNodes[0];
dom.body.removeChild(child);
parent.insertBefore(child, to_replace);
}
parent.removeChild(to_replace);
}
function fire(el, event_name, data) {
$(el).trigger(event_name, data);
}
function Builder() {
var env = this.env = new nunjucks.Environment([], {autoescape: true});
env.dev = nunjucks.env.dev;
env.cache = nunjucks.templates;
// For retrieving AJAX results from the view.
var result_map = this.results = {};
var result_handlers = {};
var has_cached_elements = false;
var pool = requests.pool();
function make_paginatable(injector, placeholder, target) {
if (!placeholder) {
console.log('No element to paginate');
return;
}
var el = placeholder.querySelector('.loadmore button');
if (!el) {
return;
}
el.addEventListener('click', function() {
el.classList.add('hide');
el.parentNode.classList.remove('pagination-error');
// Call the injector to load the next page's URL into the
// more button's parent. `target` is the selector to extract
// from the newly built HTML to inject into the currently
// visible page.
var url = el.getAttribute('data-url');
injector(url, el.parentNode, target).done(function() {
console.log('Pagination completed');
fire(page, 'loaded_more');
}).fail(function() {
url += (url.indexOf('?') + 1 ? '&' : '?') + '_bust=' + (new Date()).getTime();
parse_and_replace(render(settings.pagination_error_template, {more_url: url}), el.parentNode);
make_paginatable(injector, placeholder, target);
});
}, false);
}
function trigger_fragment_loaded(data) {
fire(page, 'fragment_loaded', data);
}
function trigger_fragment_load_failed(data) {
fire(page, 'fragment_load_failed', data);
}
// This pretends to be the nunjucks extension that does the magic.
this.env.addExtension('defer', {
run: function(context, signature, body, placeholder, empty, except) {
var uid = 'ph_' + counter++;
var out;
var injector = function(url, replace, extract) {
var request;
if ('as' in signature && 'key' in signature) {
request = models(signature.as).get(url, signature.key, pool.get);
} else {
request = pool.get(url, !!signature.nocache);
}
if ('id' in signature) {
result_handlers[signature.id] = request;
request.done(function(data) {
result_map[signature.id] = data;
});
}
function get_result(data, dont_cast) {
// `pluck` pulls the value out of the response.
// Equivalent to `this = this[pluck]`
if ('pluck' in signature) {
data = data[signature.pluck];
}
// `as` passes the data to the models for caching.
if (data && !dont_cast && 'as' in signature) {
console.groupCollapsed('Casting ' + signature.as + 's to model cache...');
models(signature.as).cast(data);
console.groupEnd();
}
var content = '';
if (empty && (!data || Array.isArray(data) && data.length === 0)) {
content = empty();
} else {
context.ctx.this = data;
content = body();
}
if (extract) {
try {
content = parse_and_find(content, extract).innerHTML;
} catch (e) {
console.error('There was an error extracting the result from the rendered response.');
content = error_template;
}
}
return content;
}
if (request.__cached) {
has_cached_elements = true;
var rendered;
// This will run synchronously.
request.done(function(data) {
context.ctx.response = data;
rendered = get_result(data, true);
// Now update the response with the values from the model cache
// For details, see bug 870447
if (data && 'as' in signature) {
var resp = data;
var plucked = 'pluck' in signature;
var uncaster = models(signature.as).uncast;
if (plucked) {
resp = resp[signature.pluck];
}
if (!resp) {
return;
}
if (Array.isArray(resp)) {
for (var i = 0; i < resp.length; i++) {
resp[i] = uncaster(resp[i]);
}
} else if (plucked) {
data[signature.pluck] = uncaster(resp);
}
// We can't do this for requests which have no pluck
// and aren't an array. :(
// Update the model cache in the background (bug 995288).
pool.get(url).done(function(data) {
models(signature.as).cast(data);
});
}
});
if (replace) {
parse_and_replace(rendered, replace);
} else {
out = rendered;
}
if (signature.paginate) {
pool.done(function() {
setTimeout(function() {
make_paginatable(injector, document.getElementById(uid), signature.paginate);
});
});
}
return request;
}
request.done(function(data) {
var el = document.getElementById(uid);
if (!el) {
return;
}
context.ctx.response = data;
var content = get_result(data);
if (replace) {
parse_and_replace(content, replace);
} else {
el.innerHTML = content;
}
if (signature.paginate) {
make_paginatable(injector, el, signature.paginate);
}
trigger_fragment_loaded({context: context, signature: signature});
}).fail(function(xhr, text, code, response) {
if (!replace) {
var el = document.getElementById(uid);
if (!el) {
return;
}
context.ctx.response = response;
context.ctx.error = code;
el.innerHTML = except ? except() : error_template;
}
trigger_fragment_load_failed({context: context, signature: signature});
});
return request;
};
injector(signature.url);
if (!out) {
out = '<div class="loading">' + (placeholder ? placeholder() : '') + '</div>';
}
return new SafeString('<div id="' + uid + '" class="placeholder">' + out + '</div>');
}
});
this.env.addExtension('fetch', {
run: function(context, signature, body) {
var url = signature.url;
var request = pool.get(url);
var uid = 'f_' + counter++;
var out = '';
if (request.__cached) {
has_cached_elements = true;
// This will run synchronously.
request.done(function(data) {
out = data;
});
} else {
var done = function(data) {
if (signature.filters) {
signature.filters.forEach(function(filterName) {
data = env.filters[filterName](data);
});
}
document.getElementById(uid).innerHTML = data;
};
request.done(done).fail(function() {
var fallback = signature.fallback;
if (fallback && fallback !== url) {
request = pool.get(fallback).done(done).fail(function() {
done(error_template);
});
}
});
}
if (!out) {
out = body();
}
return new SafeString('<div id="' + uid + '" class="placeholder fetchblock">' + out + '</div>');
}
});
this.start = function(template, defaults) {
fire(page, 'build_start');
page.innerHTML = render(template, defaults, env);
if (has_cached_elements) {
trigger_fragment_loaded();
}
return this;
};
this.onload = function(id, callback) {
result_handlers[id].done(callback);
return this;
};
pool.promise(this);
this.terminate = pool.abort;
this.finish = function() {
pool.always(function() {
fire(page, 'loaded');
});
pool.finish();
};
// Create a closure that constructs a new context only when it's needed.
var context = (function () {
var context;
return function() {
return context || (context = z.context = {});
};
})();
this.z = function(key, val) {
context()[key] = val;
switch (key) {
case 'title':
if (!val) {
val = settings.title_suffix;
} else if (val !== settings.title_suffix) {
val += ' | ' + settings.title_suffix;
}
document.title = val;
break;
case 'type':
document.body.setAttribute('data-page-type', val);
break;
}
};
}
var last_builder;
return {
getBuilder: function() {
if (last_builder) {
fire(page, 'unloading');
last_builder.terminate();
}
return last_builder = new Builder();
},
getLastBuilder: function() {return last_builder;}
};
});