templateManager.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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. export class Template {
  122. public onInit: Observable<Template>;
  123. public onLoaded: Observable<Template>;
  124. public onAppended: Observable<Template>;
  125. public onStateChange: Observable<Template>;
  126. public onEventTriggered: Observable<EventCallback>;
  127. public isLoaded: boolean;
  128. public parent: HTMLElement;
  129. public initPromise: Promise<Template>;
  130. private fragment: DocumentFragment;
  131. constructor(public name: string, private _configuration: ITemplateConfiguration) {
  132. this.onInit = new Observable<Template>();
  133. this.onLoaded = new Observable<Template>();
  134. this.onAppended = new Observable<Template>();
  135. this.onStateChange = new Observable<Template>();
  136. this.onEventTriggered = new Observable<EventCallback>();
  137. this.isLoaded = false;
  138. /*
  139. if (configuration.id) {
  140. this.parent.id = configuration.id;
  141. }
  142. */
  143. this.onInit.notifyObservers(this);
  144. let htmlContentPromise = getTemplateAsHtml(_configuration);
  145. this.initPromise = htmlContentPromise.then(htmlTemplate => {
  146. if (htmlTemplate) {
  147. let compiledTemplate = Handlebars.compile(htmlTemplate);
  148. let config = this._configuration.params || {};
  149. let rawHtml = compiledTemplate(config);
  150. this.fragment = document.createRange().createContextualFragment(rawHtml);
  151. this.isLoaded = true;
  152. this.onLoaded.notifyObservers(this);
  153. }
  154. return this;
  155. });
  156. }
  157. public get configuration(): ITemplateConfiguration {
  158. return this._configuration;
  159. }
  160. public getChildElements(): Array<string> {
  161. let childrenArray: string[] = [];
  162. //Edge and IE don't support frage,ent.children
  163. let children = this.fragment.children;
  164. if (!children) {
  165. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  166. children = <HTMLCollection>this.fragment.querySelectorAll('*');
  167. }
  168. for (let i = 0; i < children.length; ++i) {
  169. childrenArray.push(kebabToCamel(children.item(i).nodeName.toLowerCase()));
  170. }
  171. return childrenArray;
  172. }
  173. public appendTo(parent: HTMLElement) {
  174. if (this.parent) {
  175. console.error('Already appanded to ', this.parent);
  176. } else {
  177. this.parent = parent;
  178. if (this._configuration.id) {
  179. this.parent.id = this._configuration.id;
  180. }
  181. this.parent.appendChild(this.fragment);
  182. // appended only one frame after.
  183. setTimeout(() => {
  184. this.registerEvents();
  185. this.onAppended.notifyObservers(this);
  186. });
  187. }
  188. }
  189. public show(visibilityFunction?: (template: Template) => Promise<Template>): Promise<Template> {
  190. if (visibilityFunction) {
  191. return visibilityFunction(this).then(() => {
  192. this.onStateChange.notifyObservers(this);
  193. return this;
  194. });
  195. } else {
  196. // flex? box? should this be configurable easier than the visibilityFunction?
  197. this.parent.style.display = 'flex';
  198. this.onStateChange.notifyObservers(this);
  199. return Promise.resolve(this);
  200. }
  201. }
  202. public hide(visibilityFunction?: (template: Template) => Promise<Template>): Promise<Template> {
  203. if (visibilityFunction) {
  204. return visibilityFunction(this).then(() => {
  205. this.onStateChange.notifyObservers(this);
  206. return this;
  207. });
  208. } else {
  209. this.parent.style.display = 'none';
  210. this.onStateChange.notifyObservers(this);
  211. return Promise.resolve(this);
  212. }
  213. }
  214. // TODO - Should events be removed as well? when are templates disposed?
  215. private registerEvents() {
  216. if (this._configuration.events) {
  217. for (let eventName in this._configuration.events) {
  218. if (this._configuration.events && this._configuration.events[eventName]) {
  219. let functionToFire = (selector, event) => {
  220. this.onEventTriggered.notifyObservers({ event: event, template: this, selector: selector });
  221. }
  222. // if boolean, set the parent as the event listener
  223. if (typeof this._configuration.events[eventName] === 'boolean') {
  224. this.parent.addEventListener(eventName, functionToFire.bind(this, '#' + this.parent.id), false);
  225. } else if (typeof this._configuration.events[eventName] === 'object') {
  226. let selectorsArray: Array<string> = Object.keys(this._configuration.events[eventName] || {});
  227. // strict null checl is working incorrectly, must override:
  228. let event = this._configuration.events[eventName] || {};
  229. selectorsArray.filter(selector => event[selector]).forEach(selector => {
  230. if (selector.indexOf('#') !== 0) {
  231. selector = '#' + selector;
  232. }
  233. let htmlElement = <HTMLElement>this.parent.querySelector(selector);
  234. htmlElement && htmlElement.addEventListener(eventName, functionToFire.bind(this, selector), false)
  235. });
  236. }
  237. }
  238. }
  239. }
  240. }
  241. }
  242. export function getTemplateAsHtml(templateConfig: ITemplateConfiguration): Promise<string> {
  243. if (!templateConfig) {
  244. return Promise.reject('No templateConfig provided');
  245. } else if (templateConfig.html) {
  246. return Promise.resolve(templateConfig.html);
  247. } else {
  248. let location = getTemplateLocation(templateConfig);
  249. if (isUrl(location)) {
  250. return loadFile(location);
  251. } else {
  252. location = location.replace('#', '');
  253. let element = document.getElementById('#' + location);
  254. if (element) {
  255. return Promise.resolve(element.innerHTML);
  256. } else {
  257. return Promise.reject('Template ID not found');
  258. }
  259. }
  260. }
  261. }
  262. export function getTemplateLocation(templateConfig): string {
  263. if (!templateConfig || typeof templateConfig === 'string') {
  264. return templateConfig;
  265. } else {
  266. return templateConfig.location;
  267. }
  268. }