templateManager.ts 18 KB

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