so://phie

game-engine

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

blob: 5e41dfa084177f914685de95cb98241503f9c300 (2278 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 const tag = item.tagName.toLowerCase();

24 code += `<${tag} data-child-ref-${children.length}></${tag}>`;

25 children.push(item);

26 continue;

27 }

28 code += item;

29 }

30 continue;

31 }

32 if(props[i] instanceof HTMLElement) {

33 const tag = props[i].tagName.toLowerCase();

34 code += `<${tag} data-child-ref-${children.length}></${tag}>`;

35 children.push(props[i]);

36 continue;

37 }

38 code += props[i];

39 }

40 }

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

42 template.innerHTML = code;

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

44 const element = fragment.firstElementChild;

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

46 let target;

47 if(element.hasAttribute(`data-event-ref-${id}`)) {

48 target = element;

49 }

50 else {

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

52 }

53 if(target) {

54 target.addEventListener(type, handler);

55 target.removeAttribute(`data-event-ref-${id}`);

56 }

57 else {

58 console.warn(`Unable to bind ${type} event to element with id: ${id}`);

59 }

60 }

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

62 const target = element.querySelector(`[data-child-ref-${id}]`);

63 if(target) {

64 target.replaceWith(child);

65 }

66 else {

67 console.warn(`Unable to reference <${child.tagName.toLowerCase()}> tag with id: ${id}`);

68 }

69 }

70 return element;

71 }

72 catch(error) {

73 console.error(error);

74 }

75}

76

77export function escape(string) {

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

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

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

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

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