templateManager.ts 16 KB

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