A lightweight JavaScript game engine
git clone git://soophie.de/game-engine
5
"url": "/js",6
"posts": [7
{8
"id": "js.html",9
"name": "html",10
"syntax": "html`...`",11
"description": "Creates a DOM element from the given template literal.",12
"url": "/js/render.js",13
"code": [14
"const Message = props => {",15
"\treturn html`<h1>${props.text}</h1>`;",16
"};",17
"",18
"const message = Message({ text: 'Hello World!' });",19
"document.body.append(message);"20
]21
},22
{23
"id": "js.escape",24
"name": "escape",25
"syntax": "escape(...)",26
"description": "Returns escape xml from the given string.",27
"url": "/js/render.js",28
"code": [29
"escape(`<h1>Hello World!</h1>`);"30
]31
},32
{33
"id": "js.game",34
"name": "Game",35
"syntax": "Game(width, height, { fps })",
78
.overview {79
padding-left: 20px;80
margin-bottom: 50px;80
display: inline-block;82
li {
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, ''');65
}65
\ No newline at end of file