templateManager.ts 13 KB

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