templateManager.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. import { Observable, IFileRequest, Tools } from 'babylonjs';
  2. import { isUrl, camelToKebab, kebabToCamel } from '../helper';
  3. import * as Handlebars from 'handlebars/dist/handlebars';
  4. import { EventManager } from './eventManager';
  5. import { ITemplateConfiguration } from '../configuration/interfaces';
  6. import { deepmerge } from '../helper/';
  7. /**
  8. * The object sent when an event is triggered
  9. */
  10. export interface EventCallback {
  11. event: Event;
  12. template: Template;
  13. selector: string;
  14. payload?: any;
  15. }
  16. /**
  17. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  18. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  19. */
  20. export class TemplateManager {
  21. /**
  22. * Will be triggered when any template is initialized
  23. */
  24. public onTemplateInit: Observable<Template>;
  25. /**
  26. * Will be triggered when any template is fully loaded
  27. */
  28. public onTemplateLoaded: Observable<Template>;
  29. /**
  30. * Will be triggered when a template state changes
  31. */
  32. public onTemplateStateChange: Observable<Template>;
  33. /**
  34. * Will be triggered when all templates finished loading
  35. */
  36. public onAllLoaded: Observable<TemplateManager>;
  37. /**
  38. * Will be triggered when any event on any template is triggered.
  39. */
  40. public onEventTriggered: Observable<EventCallback>;
  41. /**
  42. * This template manager's event manager. In charge of callback registrations to native event types
  43. */
  44. public eventManager: EventManager;
  45. private templates: { [name: string]: Template };
  46. constructor(public containerElement: HTMLElement) {
  47. this.templates = {};
  48. this.onTemplateInit = new Observable<Template>();
  49. this.onTemplateLoaded = new Observable<Template>();
  50. this.onTemplateStateChange = new Observable<Template>();
  51. this.onAllLoaded = new Observable<TemplateManager>();
  52. this.onEventTriggered = new Observable<EventCallback>();
  53. this.eventManager = new EventManager(this);
  54. }
  55. /**
  56. * Initialize the template(s) for the viewer. Called bay the Viewer class
  57. * @param templates the templates to be used to initialize the main template
  58. */
  59. public initTemplate(templates: { [key: string]: ITemplateConfiguration }) {
  60. let internalInit = (dependencyMap, name: string, parentTemplate?: Template) => {
  61. //init template
  62. let template = this.templates[name];
  63. let childrenTemplates = Object.keys(dependencyMap).map(childName => {
  64. return internalInit(dependencyMap[childName], childName, template);
  65. });
  66. // register the observers
  67. //template.onLoaded.add(() => {
  68. let addToParent = () => {
  69. let containingElement = parentTemplate && parentTemplate.parent.querySelector(camelToKebab(name)) || this.containerElement;
  70. template.appendTo(containingElement);
  71. this._checkLoadedState();
  72. }
  73. if (parentTemplate && !parentTemplate.parent) {
  74. parentTemplate.onAppended.add(() => {
  75. addToParent();
  76. });
  77. } else {
  78. addToParent();
  79. }
  80. //});
  81. return template;
  82. }
  83. //build the html tree
  84. return this._buildHTMLTree(templates).then(htmlTree => {
  85. if (this.templates['main']) {
  86. internalInit(htmlTree, 'main');
  87. } else {
  88. this._checkLoadedState();
  89. }
  90. return;
  91. });
  92. }
  93. /**
  94. *
  95. * This function will create a simple map with child-dependencies of the template html tree.
  96. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  97. * It is expected that the main template will be called main!
  98. *
  99. * @param templates
  100. */
  101. private _buildHTMLTree(templates: { [key: string]: ITemplateConfiguration }): Promise<object> {
  102. let promises: Array<Promise<Template | boolean>> = Object.keys(templates).map(name => {
  103. // if the template was overridden
  104. if (!templates[name]) return Promise.resolve(false);
  105. // else - we have a template, let's do our job!
  106. let template = new Template(name, templates[name]);
  107. template.onLoaded.add(() => {
  108. this.onTemplateLoaded.notifyObservers(template);
  109. });
  110. template.onStateChange.add(() => {
  111. this.onTemplateStateChange.notifyObservers(template);
  112. });
  113. this.onTemplateInit.notifyObservers(template);
  114. // make sure the global onEventTriggered is called as well
  115. template.onEventTriggered.add(eventData => this.onEventTriggered.notifyObservers(eventData));
  116. this.templates[name] = template;
  117. return template.initPromise;
  118. });
  119. return Promise.all(promises).then(() => {
  120. let templateStructure = {};
  121. // now iterate through all templates and check for children:
  122. let buildTree = (parentObject, name) => {
  123. this.templates[name].isInHtmlTree = true;
  124. let childNodes = this.templates[name].getChildElements().filter(n => !!this.templates[n]);
  125. childNodes.forEach(element => {
  126. parentObject[element] = {};
  127. buildTree(parentObject[element], element);
  128. });
  129. }
  130. if (this.templates['main']) {
  131. buildTree(templateStructure, "main");
  132. }
  133. return templateStructure;
  134. });
  135. }
  136. /**
  137. * Get the canvas in the template tree.
  138. * There must be one and only one canvas inthe template.
  139. */
  140. public getCanvas(): HTMLCanvasElement | null {
  141. return this.containerElement.querySelector('canvas');
  142. }
  143. /**
  144. * Get a specific template from the template tree
  145. * @param name the name of the template to load
  146. */
  147. public getTemplate(name: string): Template | undefined {
  148. return this.templates[name];
  149. }
  150. private _checkLoadedState() {
  151. let done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every((key) => {
  152. return (this.templates[key].isLoaded && !!this.templates[key].parent) || !this.templates[key].isInHtmlTree;
  153. });
  154. if (done) {
  155. this.onAllLoaded.notifyObservers(this);
  156. }
  157. }
  158. /**
  159. * Dispose the template manager
  160. */
  161. public dispose() {
  162. // dispose all templates
  163. Object.keys(this.templates).forEach(template => {
  164. this.templates[template].dispose();
  165. });
  166. this.templates = {};
  167. this.eventManager.dispose();
  168. this.onTemplateInit.clear();
  169. this.onAllLoaded.clear();
  170. this.onEventTriggered.clear();
  171. this.onTemplateLoaded.clear();
  172. this.onTemplateStateChange.clear();
  173. }
  174. }
  175. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  176. Handlebars.registerHelper('eachInMap', function (map, block) {
  177. var out = '';
  178. Object.keys(map).map(function (prop) {
  179. let data = map[prop];
  180. if (typeof data === 'object') {
  181. data.id = data.id || prop;
  182. out += block.fn(data);
  183. } else {
  184. out += block.fn({ id: prop, value: data });
  185. }
  186. });
  187. return out;
  188. });
  189. Handlebars.registerHelper('add', function (a, b) {
  190. var out = a + b;
  191. return out;
  192. });
  193. Handlebars.registerHelper('eq', function (a, b) {
  194. var out = (a == b);
  195. return out;
  196. });
  197. Handlebars.registerHelper('or', function (a, b) {
  198. var out = a || b;
  199. return out;
  200. });
  201. Handlebars.registerHelper('not', function (a) {
  202. var out = !a;
  203. return out;
  204. });
  205. Handlebars.registerHelper('count', function (map) {
  206. return map.length;
  207. });
  208. Handlebars.registerHelper('gt', function (a, b) {
  209. var out = a > b;
  210. return out;
  211. });
  212. /**
  213. * This class represents a single template in the viewer's template tree.
  214. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  215. * A template is injected using the template manager in the correct position.
  216. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  217. *
  218. * For further information please refer to the documentation page, https://doc.babylonjs.com
  219. */
  220. export class Template {
  221. /**
  222. * Will be triggered when the template is loaded
  223. */
  224. public onLoaded: Observable<Template>;
  225. /**
  226. * will be triggered when the template is appended to the tree
  227. */
  228. public onAppended: Observable<Template>;
  229. /**
  230. * Will be triggered when the template's state changed (shown, hidden)
  231. */
  232. public onStateChange: Observable<Template>;
  233. /**
  234. * Will be triggered when an event is triggered on ths template.
  235. * The event is a native browser event (like mouse or pointer events)
  236. */
  237. public onEventTriggered: Observable<EventCallback>;
  238. public onParamsUpdated: Observable<Template>;
  239. public onHTMLRendered: Observable<Template>;
  240. /**
  241. * is the template loaded?
  242. */
  243. public isLoaded: boolean;
  244. /**
  245. * This is meant to be used to track the show and hide functions.
  246. * This is NOT (!!) a flag to check if the element is actually visible to the user.
  247. */
  248. public isShown: boolean;
  249. /**
  250. * Is this template a part of the HTML tree (the template manager injected it)
  251. */
  252. public isInHtmlTree: boolean;
  253. /**
  254. * The HTML element containing this template
  255. */
  256. public parent: HTMLElement;
  257. /**
  258. * A promise that is fulfilled when the template finished loading.
  259. */
  260. public initPromise: Promise<Template>;
  261. private _fragment: DocumentFragment | Element;
  262. private _addedFragment: DocumentFragment | Element;
  263. private _htmlTemplate: string;
  264. private _rawHtml: string;
  265. private loadRequests: Array<IFileRequest>;
  266. constructor(public name: string, private _configuration: ITemplateConfiguration) {
  267. this.onLoaded = new Observable<Template>();
  268. this.onAppended = new Observable<Template>();
  269. this.onStateChange = new Observable<Template>();
  270. this.onEventTriggered = new Observable<EventCallback>();
  271. this.onParamsUpdated = new Observable<Template>();
  272. this.onHTMLRendered = new Observable<Template>();
  273. this.loadRequests = [];
  274. this.isLoaded = false;
  275. this.isShown = false;
  276. this.isInHtmlTree = false;
  277. let htmlContentPromise = this._getTemplateAsHtml(_configuration);
  278. this.initPromise = htmlContentPromise.then(htmlTemplate => {
  279. if (htmlTemplate) {
  280. this._htmlTemplate = htmlTemplate;
  281. let compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (this._configuration.params && !!this._configuration.params.noEscape) });
  282. let config = this._configuration.params || {};
  283. this._rawHtml = compiledTemplate(config);
  284. try {
  285. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  286. } catch (e) {
  287. let test = document.createElement(this.name);
  288. test.innerHTML = this._rawHtml;
  289. this._fragment = test;
  290. }
  291. this.isLoaded = true;
  292. this.isShown = true;
  293. this.onLoaded.notifyObservers(this);
  294. }
  295. return this;
  296. });
  297. }
  298. /**
  299. * Some templates have parameters (like background color for example).
  300. * The parameters are provided to Handlebars which in turn generates the template.
  301. * This function will update the template with the new parameters
  302. *
  303. * Note that when updating parameters the events will be registered again (after being cleared).
  304. *
  305. * @param params the new template parameters
  306. */
  307. public updateParams(params: { [key: string]: string | number | boolean | object }, append: boolean = true) {
  308. if (append) {
  309. this._configuration.params = deepmerge(this._configuration.params, params);
  310. } else {
  311. this._configuration.params = params;
  312. }
  313. // update the template
  314. if (this.isLoaded) {
  315. // this.dispose();
  316. }
  317. let compiledTemplate = Handlebars.compile(this._htmlTemplate);
  318. let config = this._configuration.params || {};
  319. this._rawHtml = compiledTemplate(config);
  320. try {
  321. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  322. } catch (e) {
  323. let test = document.createElement(this.name);
  324. test.innerHTML = this._rawHtml;
  325. this._fragment = test;
  326. }
  327. if (this.parent) {
  328. this.appendTo(this.parent, true);
  329. }
  330. }
  331. /**
  332. * Get the template'S configuration
  333. */
  334. public get configuration(): ITemplateConfiguration {
  335. return this._configuration;
  336. }
  337. /**
  338. * A template can be a parent element for other templates or HTML elements.
  339. * This function will deliver all child HTML elements of this template.
  340. */
  341. public getChildElements(): Array<string> {
  342. let childrenArray: string[] = [];
  343. //Edge and IE don't support frage,ent.children
  344. let children: HTMLCollection | NodeListOf<Element> = this._fragment && this._fragment.children;
  345. if (!this._fragment) {
  346. let fragment = this.parent.querySelector(this.name);
  347. if (fragment) {
  348. children = fragment.querySelectorAll('*');
  349. }
  350. }
  351. if (!children) {
  352. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  353. children = this._fragment.querySelectorAll('*');
  354. }
  355. for (let i = 0; i < children.length; ++i) {
  356. childrenArray.push(kebabToCamel(children.item(i).nodeName.toLowerCase()));
  357. }
  358. return childrenArray;
  359. }
  360. /**
  361. * Appending the template to a parent HTML element.
  362. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  363. * @param parent the parent to which the template is added
  364. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  365. */
  366. public appendTo(parent: HTMLElement, forceRemove?: boolean) {
  367. if (this.parent) {
  368. if (forceRemove && this._addedFragment) {
  369. /*let fragement = this.parent.querySelector(this.name)
  370. if (fragement)
  371. this.parent.removeChild(fragement);*/
  372. this.parent.innerHTML = '';
  373. } else {
  374. return;
  375. }
  376. }
  377. this.parent = parent;
  378. if (this._configuration.id) {
  379. this.parent.id = this._configuration.id;
  380. }
  381. if (this._fragment) {
  382. this.parent.appendChild(this._fragment);
  383. this._addedFragment = this._fragment;
  384. } else {
  385. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  386. }
  387. this.onHTMLRendered.notifyObservers(this);
  388. // appended only one frame after.
  389. setTimeout(() => {
  390. this._registerEvents();
  391. this.onAppended.notifyObservers(this);
  392. });
  393. }
  394. private _isShowing: boolean;
  395. private _isHiding: boolean;
  396. /**
  397. * Show the template using the provided visibilityFunction, or natively using display: flex.
  398. * The provided function returns a promise that should be fullfilled when the element is shown.
  399. * Since it is a promise async operations are more than possible.
  400. * See the default viewer for an opacity example.
  401. * @param visibilityFunction The function to execute to show the template.
  402. */
  403. public show(visibilityFunction?: (template: Template) => Promise<Template>): Promise<Template> {
  404. if (this._isHiding) return Promise.resolve(this);
  405. return Promise.resolve().then(() => {
  406. this._isShowing = true;
  407. if (visibilityFunction) {
  408. return visibilityFunction(this);
  409. } else {
  410. // flex? box? should this be configurable easier than the visibilityFunction?
  411. this.parent.style.display = 'flex';
  412. // support old browsers with no flex:
  413. if (this.parent.style.display !== 'flex') {
  414. this.parent.style.display = '';
  415. }
  416. return this;
  417. }
  418. }).then(() => {
  419. this.isShown = true;
  420. this._isShowing = false;
  421. this.onStateChange.notifyObservers(this);
  422. return this;
  423. });
  424. }
  425. /**
  426. * Hide the template using the provided visibilityFunction, or natively using display: none.
  427. * The provided function returns a promise that should be fullfilled when the element is hidden.
  428. * Since it is a promise async operations are more than possible.
  429. * See the default viewer for an opacity example.
  430. * @param visibilityFunction The function to execute to show the template.
  431. */
  432. public hide(visibilityFunction?: (template: Template) => Promise<Template>): Promise<Template> {
  433. if (this._isShowing) return Promise.resolve(this);
  434. return Promise.resolve().then(() => {
  435. this._isHiding = true;
  436. if (visibilityFunction) {
  437. return visibilityFunction(this);
  438. } else {
  439. // flex? box? should this be configurable easier than the visibilityFunction?
  440. this.parent.style.display = 'none';
  441. return this;
  442. }
  443. }).then(() => {
  444. this.isShown = false;
  445. this._isHiding = false;
  446. this.onStateChange.notifyObservers(this);
  447. return this;
  448. });
  449. }
  450. /**
  451. * Dispose this template
  452. */
  453. public dispose() {
  454. this.onAppended.clear();
  455. this.onEventTriggered.clear();
  456. this.onLoaded.clear();
  457. this.onStateChange.clear();
  458. this.isLoaded = false;
  459. // remove from parent
  460. try {
  461. this.parent.removeChild(this._fragment);
  462. } catch (e) {
  463. //noop
  464. }
  465. this.loadRequests.forEach(request => {
  466. request.abort();
  467. });
  468. if (this._registeredEvents) {
  469. this._registeredEvents.forEach(evt => {
  470. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  471. });
  472. }
  473. delete this._fragment;
  474. }
  475. private _getTemplateAsHtml(templateConfig: ITemplateConfiguration): Promise<string> {
  476. if (!templateConfig) {
  477. return Promise.reject('No templateConfig provided');
  478. } else if (templateConfig.html) {
  479. return Promise.resolve(templateConfig.html);
  480. } else {
  481. let location = this._getTemplateLocation(templateConfig);
  482. if (isUrl(location)) {
  483. return new Promise((resolve, reject) => {
  484. let fileRequest = Tools.LoadFile(location, (data: string) => {
  485. resolve(data);
  486. }, undefined, undefined, false, (request, error: any) => {
  487. reject(error);
  488. });
  489. this.loadRequests.push(fileRequest);
  490. });
  491. } else {
  492. location = location.replace('#', '');
  493. let element = document.getElementById(location);
  494. if (element) {
  495. return Promise.resolve(element.innerHTML);
  496. } else {
  497. return Promise.reject('Template ID not found');
  498. }
  499. }
  500. }
  501. }
  502. private _registeredEvents: Array<{ htmlElement: HTMLElement, eventName: string, function: EventListenerOrEventListenerObject }>;
  503. private _registerEvents() {
  504. this._registeredEvents = this._registeredEvents || [];
  505. if (this._registeredEvents.length) {
  506. // first remove the registered events
  507. this._registeredEvents.forEach(evt => {
  508. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  509. });
  510. }
  511. if (this._configuration.events) {
  512. for (let eventName in this._configuration.events) {
  513. if (this._configuration.events && this._configuration.events[eventName]) {
  514. let functionToFire = (selector, event) => {
  515. this.onEventTriggered.notifyObservers({ event: event, template: this, selector: selector });
  516. }
  517. // if boolean, set the parent as the event listener
  518. if (typeof this._configuration.events[eventName] === 'boolean') {
  519. let selector = this.parent.id
  520. if (selector) {
  521. selector = '#' + selector
  522. } else {
  523. selector = this.parent.tagName
  524. }
  525. let binding = functionToFire.bind(this, selector);
  526. this.parent.addEventListener(eventName, functionToFire.bind(this, selector), false);
  527. this._registeredEvents.push({
  528. htmlElement: this.parent,
  529. eventName: eventName,
  530. function: binding
  531. });
  532. } else if (typeof this._configuration.events[eventName] === 'object') {
  533. let selectorsArray: Array<string> = Object.keys(this._configuration.events[eventName] || {});
  534. // strict null checl is working incorrectly, must override:
  535. let event = this._configuration.events[eventName] || {};
  536. selectorsArray.filter(selector => event[selector]).forEach(selector => {
  537. let htmlElement = <HTMLElement>this.parent.querySelector(selector);
  538. if (!htmlElement) {
  539. // backcompat, fallback to id
  540. if (selector && selector.indexOf('#') !== 0) {
  541. selector = '#' + selector;
  542. }
  543. try {
  544. htmlElement = <HTMLElement>this.parent.querySelector(selector);
  545. } catch (e) { }
  546. }
  547. if (htmlElement) {
  548. let binding = functionToFire.bind(this, selector);
  549. htmlElement.addEventListener(eventName, binding, false);
  550. this._registeredEvents.push({
  551. htmlElement: htmlElement,
  552. eventName: eventName,
  553. function: binding
  554. });
  555. }
  556. });
  557. }
  558. }
  559. }
  560. }
  561. }
  562. private _getTemplateLocation(templateConfig): string {
  563. if (!templateConfig || typeof templateConfig === 'string') {
  564. return templateConfig;
  565. } else {
  566. return templateConfig.location;
  567. }
  568. }
  569. }