templateManager.ts 23 KB

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