templateManager.ts 24 KB

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