Frontend revision 2. Expanded template functionality and convenience

This commit is contained in:
Gnarwhal 2021-01-29 19:52:25 -05:00
parent e5a84268cc
commit 723cd41487
Signed by: Gnarwhal
GPG key ID: 0989A73D8C421174
6 changed files with 142 additions and 89 deletions

View file

@ -1,25 +1,25 @@
const expandTemplates = async () => {
template.register("navbar", [
template.apply("navbar").values([
{ section: "left" },
{ section: "right" }
]);
template.register("navbar-section-left", [
template.apply("navbar-section-left").values([
{ item: "games", title: "Games" },
{ item: "achievements", title: "Achievements" }
]);
template.register("navbar-section-right", [
template.apply("navbar-section-right").values([
{ item: "profile", title: "Profile" }
]);
template.register("content-body", [
template.apply("content-body").values([
{ page: "games", title: "Games" },
{ page: "achievements", title: "Achievements" },
{ page: "profile", title: "Profile" }
]);
template.register("fetch-games-page", "games_page" );
template.register("fetch-achievements-page", "achievements_page");
template.register("fetch-profile-page", "profile_page" );
template.registerFetch("achievements-page-list", "Achievements", "https://localhost:4730/achievements", { method: 'GET', mode: 'cors' });
template.apply("extern-games-page" ).values("games_page" );
template.apply("extern-achievements-page").values("achievements_page");
template.apply("extern-profile-page" ).values("profile_page" );
template.apply("achievements-page-list" ).fetch("achievements", "https://localhost:4730/achievements");
await template.expand();
};

View file

@ -3,35 +3,57 @@ var template = template || {};
template.type = {};
template.type._entryMap = new Map();
template.type.register = (type, callback) => {
const asyncCallback = async function() {
await callback.apply(null, Array.from(arguments));
}
if (typeof type !== 'string') {
console.error(`'type' must be a string, recieved: `, type);
} else {
if (type === "") {
console.error(`'type' may not be empty`);
} else if (template.type._entryMap.get(type) === undefined) {
template.type._entryMap.set(type, asyncCallback);
const TYPE_REGEX = /^(\w+)\s*(<\s*\?(?:\s*,\s*\?)*\s*>)?\s*$/;
const result = type.match(TYPE_REGEX);
if (result === null) {
console.error(`'${type}' is not a valid type id`);
} else {
console.error(`${type} is already a registered template!`);
if (result[2] === undefined) {
result[2] = 0;
} else {
result[2] = result[2].split(/\s*,\s*/).length;
}
const completeType = result[1] + ':' + result[2];
if (template.type._entryMap.get(completeType) === undefined) {
template.type._entryMap.set(completeType, async function() {
await callback.apply(null, Array.from(arguments));
});
} else {
console.error(`${type} is already a registered template!`);
}
}
}
};
// Courtesy of https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions#escaping
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|\[\]\\]/g, '\\$&'); // $& means the whole matched string
}
/* Intrinsic Templates */
// Basic - Simple search and replace
template.type.register('basic', (template, map) => {
let html = template.element.innerHTML;
for (const key in map) {
html = html.replace(new RegExp(`(?:(?<!(?<!\\\\)\\\\)\\\${${key}})`, 'gm'), map[key]);
template.type.register('Basic', (element, map) => {
let html = element.innerHTML;
function applyObject(object, path) {
for (const key in object) {
const regexKey = escapeRegExp(path + key);
html = html.replace(new RegExp(`(?:(?<!\\\\)\\\${${regexKey}})`, 'gm'), object[key]);
if (typeof object[key] === 'object') {
applyObject(object[key], path + key + '.');
}
}
}
template.element.outerHTML = html.trim();
applyObject(map, '');
html = html.replace('\\&', '&');
element.outerHTML = html.trim();
});
// Fetch - Retrieve template from webserver
template.type.register('fetch', (template, name) => {
// Extern - Retrieve template from webserver
template.type.register('Extern', (element, name) => {
return fetch(`templates/${name}.html.template`, {
method: 'GET',
mode: 'no-cors',
@ -39,70 +61,98 @@ template.type.register('fetch', (template, name) => {
'Content-Type': 'text/plain'
}
}).then(response => response.text().then((data) => {
template.element.outerHTML = data;
element.outerHTML = data;
})).catch(error => {
console.error(`failed to retrieve template '${name}': `, error);
});
});
// List - Iterate over list and emit copy of child for each iteration
template.type.register('list', (template, arrayMap) => {
let cumulative = "";
for (const map of arrayMap) {
let html = template.element.innerHTML;
for (const key in map) {
html = html.replace(new RegExp(`(?:(?<!(?<!\\\\)\\\\)\\\${${template.id}\\[${key}\\]})`, 'gm'), map[key]);
template.type.register('List<?>', async (element, subtype, arrayMap) => {
let cumulative = '';
const temp = document.createElement('template');
for (const obj of arrayMap) {
temp.innerHTML = `<template></template>`;
const child = temp.content.children[0];
child.innerHTML = element.innerHTML;
const callback = template.type._entryMap.get(subtype.type);
if (callback === undefined) {
cumulative = '';
console.error(`'${subtype.type}' is not a registered template type`);
} else {
await callback.apply(null, [ child, obj ]);
}
cumulative = cumulative + html.trim();
cumulative = cumulative + temp.innerHTML.trim();
}
template.element.outerHTML = cumulative;
element.outerHTML = cumulative;
});
template._entryMap = new Map();
template.register = function(pattern/*, arguments */) {
template.apply = function(pattern, promise) {
if (typeof pattern !== 'string') {
console.error('pattern must be a string, received: ', pattern);
} else {
const arrayArguments = Array.from(arguments);
arrayArguments.splice(0, 1);
template._entryMap.set(RegExp("^" + pattern + "$"), async () => arrayArguments);
return new template.apply.applicators(pattern);
}
};
template.registerFetch = function(pattern, path, url, fetchOptions) {
if (typeof pattern !== 'string') {
console.error('pattern must be a string, received: ', pattern);
} else {
template.apply.applicators = class {
constructor(pattern) {
this._pattern = pattern;
}
_apply(asyncArgs) {
template._entryMap.set(RegExp('^' + this._pattern + '$'), asyncArgs);
}
values(...args) {
this._apply(async () => Array.from(args));
}
promise(promise) {
let args = null;
template._entryMap.set(RegExp("^" + pattern + "$"), async () => {
if (args !== null) {
return Promise.resolve(args);
} else {
return fetch(url, fetchOptions)
.then(response => response.json())
.then(data => {
args = data;
path = path.split('\\.');
for (const id of path) {
args = args[id];
}
return args = [ args ];
});
}
});
promise = promise.then(data => args = [ data ]);
this._apply(async () => args || promise);
}
fetch(dataProcessor, url, options) {
if (typeof dataProcessor === 'string') {
const path = dataProcessor;
dataProcessor = data => {
for (const id of path.split(/\./)) {
data = data[id];
if (data === undefined) {
throw `invalid path '${path}'`;
}
}
return data;
};
};
this.promise(
fetch(url, options || { method: 'GET', mode: 'cors' })
.then(response => response.json())
.then(data => dataProcessor(data))
);
}
};
(() => {
const parseType = (type) => {
let result = type.match(/^\s*(\w+)\s*(?:<(.*)>)?\s*$/);
let id = result[1];
result = result[2] ? result[2].split(/\s*,\s*/).map(parseType) : [];
return { type: id + ':' + result.length, params: result };
};
const findTemplates = (element) =>
Array
.from(element.querySelectorAll("template"))
.from(element.querySelectorAll('template'))
.filter(child => Boolean(child.dataset.template))
.map(child => {
const data = child.dataset.template.split(/\s*:\s*/);
return {
id: data[0],
type: data.length > 1 ? data[1] : 'basic',
typeCapture: parseType(data[1] || 'Begin'),
element: child
};
});
@ -112,15 +162,18 @@ template.registerFetch = function(pattern, path, url, fetchOptions) {
let promises = [];
let parents = new Set();
for (const child of children) {
for (const [pattern, argCallbacks] of template._entryMap) {
await argCallbacks().then(args => {
for (const [pattern, argsCallback] of template._entryMap) {
await argsCallback().then(args => {
if (pattern.test(child.id)) {
const callback = template.type._entryMap.get(child.type);
const callback = template.type._entryMap.get(child.typeCapture.type);
if (typeof callback !== 'function') {
console.error(`'${child.type}' is not a registered template type`);
console.error(`'${child.typeCapture.type}' is not a registered template type`);
} else {
let params = Array.from(args)
params.splice(0, 0, child);
for (const subtype of child.typeCapture.params) {
params.unshift(subtype);
}
params.unshift(child.element);
let parent = child.element.parentElement;
if (!parents.has(parent)) {
parents.add(parent);
@ -139,7 +192,7 @@ template.registerFetch = function(pattern, path, url, fetchOptions) {
promises.push(expand(parent));
}
await Promise.all(promises);
}
};
template.expand = async () => expand(document.children[0]);
})();
})();