templateManager.ts 15 KB

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