so://phie

game-engine

A lightweight JavaScript game engine
git clone git://soophie.de/game-engine

blob: 4046f81ef033914178179b4306af9bae510b9081 (1905 bytes)[doc][blame][raw]

1export function html(strings, ...props) {

2 try {

3 let code = '';

4 let events = [];

5 let children = [];

6 for(let i = 0; i < strings.length; i++) {

7 code += strings[i];

8 if(i < props.length) {

9 if(typeof props[i] === 'function') {

10 const exp = new RegExp(/on(\w+)=/, 'g');

11 const match = exp.exec(strings[i]);

12 if(match) {

13 const [, type] = match;

14 code = code.slice(0, -(type.length + 3));

15 code += `data-event-ref="${events.length}"`;

16 events.push({ type, handler: props[i] });

17 }

18 continue;

19 }

20 if(props[i] instanceof Array) {

21 for(const item of props[i]) {

22 if(item instanceof HTMLElement) {

23 code += `<div data-child-ref="${children.length}"></div>`;

24 children.push(item);

25 continue;

26 }

27 code += item;

28 }

29 continue;

30 }

31 if(props[i] instanceof HTMLElement) {

32 code += `<div data-child-ref="${children.length}"></div>`;

33 children.push(props[i]);

34 continue;

35 }

36 code += props[i];

37 }

38 }

39 const template = document.createElement('template');

40 template.innerHTML = code;

41 const fragment = template.content.cloneNode(true);

42 const element = fragment.firstElementChild;

43 for(const [id, {type, handler}] of Object.entries(events)) {

44 let target;

45 if(element.getAttribute('data-event-ref') === id) {

46 target = element;

47 }

48 else {

49 target = element.querySelector(`[data-event-ref="${id}"]`);

50 }

51 target.addEventListener(type, handler);

52 target.removeAttribute('data-event-ref');

53 }

54 for(const [id, child] of Object.entries(children)) {

55 element.querySelector(`[data-child-ref="${id}"]`).replaceWith(child);

56 }

57 return element;

58 }

59 catch(error) {

60 console.error(error);

61 }

62}

63

64export function escape(string) {

65 return string.replace(/&/g, '&amp;')

66 .replace(/</g, '&lt;')

67 .replace(/>/g, '&gt;')

68 .replace(/"/g, '&quot;')

69 .replace(/'/g, '&apos;');