/
thymeleaf-layout-dialect.js
433 lines (377 loc) · 12.8 KB
/
thymeleaf-layout-dialect.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
(function () {
'use strict';
/*
* Copyright 2016, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* A collection of DOM functions that make life a little bit easier.
*
* @author Emanuel Rabina
*/
/**
* Returns the value of a Thymeleaf attribute processor. Checks for both the
* XML and data attribute variants.
*
* @param {Element} element
* @param {String} prefix
* @param {String} name
* @return {String} Value of a matching Thymeleaf attribute, or `null` if no
* attribute with that prefix and name exists.
*/
function getThymeleafAttributeValue(element, prefix, name) {
return element.getAttribute(`${prefix}:${name}`) ||
element.getAttribute(`data-${prefix}-${name}`);
}
/**
* Replaces one element with another.
*
* @param {Element} target Element to replace.
* @param {Element} source Element to replace `target` with.
*/
function replaceElement(target, source) {
let parent = target.parentNode;
parent.insertBefore(source, target);
parent.removeChild(target);
}
/*
* Copyright 2016, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DIALECT_PREFIX$3 = 'layout';
const PROCESSOR_NAME$1 = 'fragment';
/**
* The fragment processor, used to mark areas for replacement in templates.
*
* @author Emanuel Rabina
*/
class FragmentProcessor {
/**
* Replaces the contents of elements with fragments from surrounding
* directives such as the `decorate` or `insert`/`replace` processors.
*
* @param {Object} context
* @param {Element} fragmentEl
*/
process(context, fragmentEl) {
let {fragments} = context;
if (fragments) {
let fragmentName = getThymeleafAttributeValue(fragmentEl, DIALECT_PREFIX$3, PROCESSOR_NAME$1);
let matchingFragment = fragments[fragmentName];
if (matchingFragment) {
replaceElement(fragmentEl, matchingFragment);
}
}
}
}
FragmentProcessor.PROCESSOR_NAME = PROCESSOR_NAME$1;
var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
var dumbQuerySelector = createCommonjsModule(function (module) {
/*
* Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function(root, factory) {
'use strict';
// AMD
if (typeof undefined === 'function' && undefined.amd) {
undefined('dumb-query-selector', [], factory);
}
// CommonJS
else if ('object' === 'object' && module.exports) {
module.exports = factory();
}
// Global
else {
var dumbQuerySelector = factory();
Object.keys(dumbQuerySelector).forEach(function(key) {
root[key] = dumbQuerySelector[key];
});
}
})(commonjsGlobal, function() {
'use strict';
return {
/**
* An element selector and shortcut for `(document/element).querySelector`.
*
* @param {String} query
* @param {Node} [scope] The scope to limit the search to for non-ID queries.
* Defaults to document scope.
* @return {Element} The matching element, or `null` if no match is found.
*/
$: function(query, scope) {
return (scope || document).querySelector(query);
},
/**
* An element list selector, returning an array of elements because
* `NodeList`s are dumb.
*
* @param {String} query
* @param {Node} [scope] The scope to limit the search to for non-ID queries.
* Defaults to document scope.
* @return {Array} The list of matching elements.
*/
$$: function(query, scope) {
return Array.prototype.slice.call((scope || document).querySelectorAll(query));
}
};
});
});
var dumbQuerySelector_2 = dumbQuerySelector.$$;
/*
* Copyright 2017, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DIALECT_PREFIX$2 = 'layout';
/**
* Searches for and returns layout dialect fragements within a given element.
*
* @author Emanuel Rabina
*/
class FragmentFinder {
/**
* Find and return elements that are layout dialect fragments within the given
* element.
*
* @param {Element} element
* @return {Object} A map of fragments, mapped by their name.
*/
findFragments(element) {
let fragmentMap = {};
let fragments = dumbQuerySelector_2('[layout\\:fragment], [data-layout-fragment]', element);
fragments.map(fragment => {
let fragmentName = getThymeleafAttributeValue(fragment, DIALECT_PREFIX$2,
FragmentProcessor.PROCESSOR_NAME);
fragmentMap[fragmentName] = fragment;
});
return fragmentMap;
}
}
/**
* Deep-merges all of the properties of the objects in `sources` with `target`,
* modifying the target object and returning it.
*
* @param {Object} target
* @param {...Object} sources
* @return {Object} The modified target object.
*/
function merge(target = {}, ...sources) {
sources.forEach(source => {
Object.keys(source).forEach(key => {
let targetValue = target[key];
let sourceValue = source[key];
target[key] = targetValue instanceof Object && sourceValue instanceof Object ?
merge(targetValue, sourceValue) :
sourceValue;
});
});
return target;
}
/*
* Copyright 2016, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Checks the status of the response for 200 - 300 which is OK.
*
* @private
* @param {Response} response
* @return {Object} The response object or a new error object.
*/
function checkStatus(response) {
if (response.status >= 200 && response.status < 300) {
return response;
}
else {
let error = new Error(`${response.status} - ${response.statusText}`);
error.response = response;
throw error;
}
}
/**
* Fetches HTML (`text/html`) data from the given URL.
*
* @param {String} url
* @param {Object} [config={}]
* @return {Promise} Promise of the fetched HTML data.
*/
function fetchHtml(url, config = {}) {
return fetch(url, merge({
headers: {
'Accept': 'text/html'
}
}, config))
.then(checkStatus)
.then(response => response.text());
}
/**
* Fetches HTML (`text/html`) data from the given URL, parsed and returned as a
* separate DOM.
*
* @param {String} url
* @param {Object} [config={}]
* @return {Promise} Promise of the fetched HTML data as a DOM.
*/
function fetchHtmlAsDom(url, config = {}) {
return fetchHtml(url, config)
.then(responseText => new DOMParser().parseFromString(responseText, 'text/html'));
}
/*
* Copyright 2013, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DIALECT_PREFIX$1 = 'layout';
const PROCESSOR_NAME = 'decorate';
const FRAGMENT_EXPRESSION = /~\{(.+)\}/;
/**
* Emulates what `DecorateProcessor.groovy` does, but for a prototyping
* environment.
*
* @author Emanuel Rabina
*/
class DecorateProcessor {
/**
* Locates the template to decorate and replaces the current document with it.
*
* @param {Object} context
* @param {Element} htmlEl
* @return {Promise} A promise that is fulfilled once the layout template has
* been applied.
*/
process(context, htmlEl) {
return new Promise(function(resolve, reject) {
// Find the layout template
let layoutTemplateExpression = getThymeleafAttributeValue(htmlEl, DIALECT_PREFIX$1, PROCESSOR_NAME);
if (!layoutTemplateExpression) {
console.warn('No layout:decorate or data-layout-decorate attribute found on the <html> element');
resolve();
}
let layoutTemplateMatch = layoutTemplateExpression.match(FRAGMENT_EXPRESSION);
let layoutTemplateName = layoutTemplateMatch[1];
// Retrieve the layout template, decorating it with the current template
fetchHtmlAsDom(layoutTemplateName)
.then(function(layoutTemplate) {
// Get all the fragments of the current template
context.fragments = new FragmentFinder().findFragments(htmlEl);
// Replace the current template with the layout template. Uses
// document.write since that lets scripts in the new <head> section
// get executed.
// TODO: Using document.write seems to mess with the history on
// Firefox, such that reloading doesn't get this script re-run
document.open('text/html', 'replace');
document.write(layoutTemplate.firstElementChild.outerHTML);
document.close();
document.addEventListener('DOMContentLoaded', resolve);
})
.catch(function(error) {
console.warn(`Unable to retrieve layout at ${error.response.url}`);
resolve();
});
});
}
}
DecorateProcessor.PROCESSOR_NAME = PROCESSOR_NAME;
/*
* Copyright 2013, Emanuel Rabina (http://www.ultraq.net.nz/)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const DIALECT_PREFIX = 'layout';
/**
* Main script for kicking-off the layout dialect.
*
* @author Emanuel Rabina
*/
document.addEventListener('DOMContentLoaded', function() {
let context = {};
new DecorateProcessor().process(context, document.documentElement)
// Forced processing of layout:fragment elements
.then(function() {
let selector = `[${DIALECT_PREFIX}\\:${FragmentProcessor.PROCESSOR_NAME}], ` +
`[data-${DIALECT_PREFIX}-${FragmentProcessor.PROCESSOR_NAME}]`;
let fragmentsToProcess = dumbQuerySelector_2(selector);
fragmentsToProcess.forEach(fragmentToProcess => {
new FragmentProcessor().process(context, fragmentToProcess);
});
});
});
}());