templateManager.ts 17 KB

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