templateManager.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import { Observable } from 'babylonjs';
  2. import { isUrl, loadFile, camelToKebab, kebabToCamel } from './helper';
  3. export interface ITemplateConfiguration {
  4. location?: string; // #template-id OR http://example.com/loading.html
  5. html?: string; // raw html string
  6. id?: string;
  7. params?: { [key: string]: string | number | boolean | object };
  8. events?: {
  9. // pointer events
  10. pointerdown?: boolean | { [id: string]: boolean; };
  11. pointerup?: boolean | { [id: string]: boolean; };
  12. pointermove?: boolean | { [id: string]: boolean; };
  13. pointerover?: boolean | { [id: string]: boolean; };
  14. pointerout?: boolean | { [id: string]: boolean; };
  15. pointerenter?: boolean | { [id: string]: boolean; };
  16. pointerleave?: boolean | { [id: string]: boolean; };
  17. pointercancel?: boolean | { [id: string]: boolean; };
  18. //click, just in case
  19. click?: boolean | { [id: string]: boolean; };
  20. // drag and drop
  21. dragstart?: boolean | { [id: string]: boolean; };
  22. drop?: boolean | { [id: string]: boolean; };
  23. [key: string]: boolean | { [id: string]: boolean; } | undefined;
  24. }
  25. }
  26. export interface EventCallback {
  27. event: Event;
  28. template: Template;
  29. selector: string;
  30. payload?: any;
  31. }
  32. export class TemplateManager {
  33. public onInit: Observable<Template>;
  34. public onLoaded: Observable<Template>;
  35. public onStateChange: Observable<Template>;
  36. public onAllLoaded: Observable<TemplateManager>;
  37. private templates: { [name: string]: Template };
  38. constructor(public containerElement: HTMLElement) {
  39. this.templates = {};
  40. this.onInit = new Observable<Template>();
  41. this.onLoaded = new Observable<Template>();
  42. this.onStateChange = new Observable<Template>();
  43. this.onAllLoaded = new Observable<TemplateManager>();
  44. }
  45. public initTemplate(templates: { [key: string]: ITemplateConfiguration }) {
  46. let internalInit = (dependencyMap, name: string, parentTemplate?: Template) => {
  47. //init template
  48. let template = this.templates[name];
  49. let childrenTemplates = Object.keys(dependencyMap).map(childName => {
  50. return internalInit(dependencyMap[childName], childName, template);
  51. });
  52. // register the observers
  53. //template.onLoaded.add(() => {
  54. let addToParent = () => {
  55. let containingElement = parentTemplate && parentTemplate.parent.querySelector(camelToKebab(name)) || this.containerElement;
  56. template.appendTo(containingElement);
  57. this.checkLoadedState();
  58. }
  59. if (parentTemplate && !parentTemplate.parent) {
  60. parentTemplate.onAppended.add(() => {
  61. addToParent();
  62. });
  63. } else {
  64. addToParent();
  65. }
  66. //});
  67. return template;
  68. }
  69. //build the html tree
  70. this.buildHTMLTree(templates).then(htmlTree => {
  71. internalInit(htmlTree, 'main');
  72. });
  73. }
  74. /**
  75. *
  76. * This function will create a simple map with child-dependencies of the template html tree.
  77. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  78. * It is expected that the main template will be called main!
  79. *
  80. * @private
  81. * @param {{ [key: string]: ITemplateConfiguration }} templates
  82. * @memberof TemplateManager
  83. */
  84. private buildHTMLTree(templates: { [key: string]: ITemplateConfiguration }): Promise<object> {
  85. let promises = Object.keys(templates).map(name => {
  86. let template = new Template(name, templates[name]);
  87. this.templates[name] = template;
  88. return template.initPromise;
  89. });
  90. return Promise.all(promises).then(() => {
  91. let templateStructure = {};
  92. // now iterate through all templates and check for children:
  93. let buildTree = (parentObject, name) => {
  94. let childNodes = this.templates[name].getChildElements().filter(n => !!this.templates[n]);
  95. childNodes.forEach(element => {
  96. parentObject[element] = {};
  97. buildTree(parentObject[element], element);
  98. });
  99. }
  100. buildTree(templateStructure, "main");
  101. return templateStructure;
  102. });
  103. }
  104. // assumiung only ONE(!) canvas
  105. public getCanvas(): HTMLCanvasElement | null {
  106. return this.containerElement.querySelector('canvas');
  107. }
  108. public getTemplate(name: string): Template | undefined {
  109. return this.templates[name];
  110. }
  111. private checkLoadedState() {
  112. let done = Object.keys(this.templates).every((key) => {
  113. return this.templates[key].isLoaded && !!this.templates[key].parent;
  114. });
  115. if (done) {
  116. this.onAllLoaded.notifyObservers(this);
  117. }
  118. }
  119. }
  120. import * as Handlebars from 'handlebars/dist/handlebars.min.js';
  121. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  122. Handlebars.registerHelper('eachInMap', function (map, block) {
  123. var out = '';
  124. Object.keys(map).map(function (prop) {
  125. let data = map[prop];
  126. if (typeof data === 'object') {
  127. data.id = prop;
  128. out += block.fn(data);
  129. } else {
  130. out += block.fn({ id: prop, value: data });
  131. }
  132. });
  133. return out;
  134. });
  135. export class Template {
  136. public onInit: Observable<Template>;
  137. public onLoaded: Observable<Template>;
  138. public onAppended: Observable<Template>;
  139. public onStateChange: Observable<Template>;
  140. public onEventTriggered: Observable<EventCallback>;
  141. public isLoaded: boolean;
  142. public parent: HTMLElement;
  143. public initPromise: Promise<Template>;
  144. private fragment: DocumentFragment;
  145. constructor(public name: string, private _configuration: ITemplateConfiguration) {
  146. this.onInit = new Observable<Template>();
  147. this.onLoaded = new Observable<Template>();
  148. this.onAppended = new Observable<Template>();
  149. this.onStateChange = new Observable<Template>();
  150. this.onEventTriggered = new Observable<EventCallback>();
  151. this.isLoaded = false;
  152. /*
  153. if (configuration.id) {
  154. this.parent.id = configuration.id;
  155. }
  156. */
  157. this.onInit.notifyObservers(this);
  158. let htmlContentPromise = getTemplateAsHtml(_configuration);
  159. this.initPromise = htmlContentPromise.then(htmlTemplate => {
  160. if (htmlTemplate) {
  161. let compiledTemplate = Handlebars.compile(htmlTemplate);
  162. let config = this._configuration.params || {};
  163. let rawHtml = compiledTemplate(config);
  164. this.fragment = document.createRange().createContextualFragment(rawHtml);
  165. this.isLoaded = true;
  166. this.onLoaded.notifyObservers(this);
  167. }
  168. return this;
  169. });
  170. }
  171. public get configuration(): ITemplateConfiguration {
  172. return this._configuration;
  173. }
  174. public getChildElements(): Array<string> {
  175. let childrenArray: string[] = [];
  176. //Edge and IE don't support frage,ent.children
  177. let children = this.fragment.children;
  178. if (!children) {
  179. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  180. children = <HTMLCollection>this.fragment.querySelectorAll('*');
  181. }
  182. for (let i = 0; i < children.length; ++i) {
  183. childrenArray.push(kebabToCamel(children.item(i).nodeName.toLowerCase()));
  184. }
  185. return childrenArray;
  186. }
  187. public appendTo(parent: HTMLElement) {
  188. if (this.parent) {
  189. console.error('Already appanded to ', this.parent);
  190. } else {
  191. this.parent = parent;
  192. if (this._configuration.id) {
  193. this.parent.id = this._configuration.id;
  194. }
  195. this.parent.appendChild(this.fragment);
  196. // appended only one frame after.
  197. setTimeout(() => {
  198. this.registerEvents();
  199. this.onAppended.notifyObservers(this);
  200. });
  201. }
  202. }
  203. public show(visibilityFunction?: (template: Template) => Promise<Template>): Promise<Template> {
  204. if (visibilityFunction) {
  205. return visibilityFunction(this).then(() => {
  206. this.onStateChange.notifyObservers(this);
  207. return this;
  208. });
  209. } else {
  210. // flex? box? should this be configurable easier than the visibilityFunction?
  211. this.parent.style.display = 'flex';
  212. this.onStateChange.notifyObservers(this);
  213. return Promise.resolve(this);
  214. }
  215. }
  216. public hide(visibilityFunction?: (template: Template) => Promise<Template>): Promise<Template> {
  217. if (visibilityFunction) {
  218. return visibilityFunction(this).then(() => {
  219. this.onStateChange.notifyObservers(this);
  220. return this;
  221. });
  222. } else {
  223. this.parent.style.display = 'none';
  224. this.onStateChange.notifyObservers(this);
  225. return Promise.resolve(this);
  226. }
  227. }
  228. // TODO - Should events be removed as well? when are templates disposed?
  229. private registerEvents() {
  230. if (this._configuration.events) {
  231. for (let eventName in this._configuration.events) {
  232. if (this._configuration.events && this._configuration.events[eventName]) {
  233. let functionToFire = (selector, event) => {
  234. this.onEventTriggered.notifyObservers({ event: event, template: this, selector: selector });
  235. }
  236. // if boolean, set the parent as the event listener
  237. if (typeof this._configuration.events[eventName] === 'boolean') {
  238. this.parent.addEventListener(eventName, functionToFire.bind(this, '#' + this.parent.id), false);
  239. } else if (typeof this._configuration.events[eventName] === 'object') {
  240. let selectorsArray: Array<string> = Object.keys(this._configuration.events[eventName] || {});
  241. // strict null checl is working incorrectly, must override:
  242. let event = this._configuration.events[eventName] || {};
  243. selectorsArray.filter(selector => event[selector]).forEach(selector => {
  244. if (selector.indexOf('#') !== 0) {
  245. selector = '#' + selector;
  246. }
  247. let htmlElement = <HTMLElement>this.parent.querySelector(selector);
  248. htmlElement && htmlElement.addEventListener(eventName, functionToFire.bind(this, selector), false)
  249. });
  250. }
  251. }
  252. }
  253. }
  254. }
  255. }
  256. export function getTemplateAsHtml(templateConfig: ITemplateConfiguration): Promise<string> {
  257. if (!templateConfig) {
  258. return Promise.reject('No templateConfig provided');
  259. } else if (templateConfig.html) {
  260. return Promise.resolve(templateConfig.html);
  261. } else {
  262. let location = getTemplateLocation(templateConfig);
  263. if (isUrl(location)) {
  264. return loadFile(location);
  265. } else {
  266. location = location.replace('#', '');
  267. let element = document.getElementById(location);
  268. if (element) {
  269. return Promise.resolve(element.innerHTML);
  270. } else {
  271. return Promise.reject('Template ID not found');
  272. }
  273. }
  274. }
  275. }
  276. export function getTemplateLocation(templateConfig): string {
  277. if (!templateConfig || typeof templateConfig === 'string') {
  278. return templateConfig;
  279. } else {
  280. return templateConfig.location;
  281. }
  282. }