A lightweight JavaScript game engine
git clone git://soophie.de/game-engine
blob: de595c0ae992b067718cbcb5f9af3f23526abea0 (1797 bytes)[doc][blame][raw]
1
export function html(strings, ...props) {2
let code = '';3
let events = [];4
let children = [];5
for(let i = 0; i < strings.length; i++) {6
code += strings[i];7
if(i < props.length) {8
if(typeof props[i] === 'function') {9
const exp = new RegExp(/on(\w+)=/, 'g');10
const match = exp.exec(strings[i]);11
if(match) {12
const [, type] = match;13
code = code.slice(0, -(type.length + 3));14
code += `data-event-ref="${events.length}"`;15
events.push({ type, handler: props[i] });16
}17
continue;18
}19
if(props[i] instanceof Array) {20
for(const item of props[i]) {21
if(item instanceof HTMLElement) {22
code += `<div data-child-ref="${children.length}"></div>`;23
children.push(item);24
continue;25
}26
code += item;27
}28
continue;29
}30
if(props[i] instanceof HTMLElement) {31
code += `<div data-child-ref="${children.length}"></div>`;32
children.push(props[i]);33
continue;34
}35
code += props[i];36
}37
}38
const template = document.createElement('template');39
template.innerHTML = code;40
const fragment = template.content.cloneNode(true);41
const element = fragment.firstElementChild;42
for(const [id, {type, handler}] of Object.entries(events)) {43
let target;44
if(element.getAttribute('data-event-ref') === id) {45
target = element;46
}47
else {48
target = element.querySelector(`[data-event-ref="${id}"]`);49
}50
target.addEventListener(type, handler);51
target.removeAttribute('data-event-ref');52
}53
for(const [id, child] of Object.entries(children)) {54
element.querySelector(`[data-child-ref="${id}"]`).replaceWith(child);55
}56
return element;57
}59
export function escape(string) {60
return string.replace(/&/g, '&')61
.replace(/</g, '<')62
.replace(/>/g, '>')63
.replace(/"/g, '"')64
.replace(/'/g, ''');