mappers.ts 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. import { Tools } from 'babylonjs';
  2. import { ViewerConfiguration } from './configuration';
  3. import { kebabToCamel } from '../helper';
  4. /**
  5. * This is the mapper's interface. Implement this function to create your own mapper and register it at the mapper manager
  6. */
  7. export interface IMapper {
  8. map(rawSource: any): ViewerConfiguration;
  9. }
  10. /**
  11. * This is a simple HTML mapper.
  12. * This mapper parses a single HTML element and returns the configuration from its attributes.
  13. * it parses numbers and boolean values to the corresponding variable types.
  14. * The following HTML element:
  15. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  16. *
  17. * {
  18. * test: 1, //a number!
  19. * randomFlag: boolean, //camelCase and boolean
  20. * a: {
  21. * string: {
  22. * object: "test" //dot-separated object levels
  23. * }
  24. * }
  25. * }
  26. */
  27. class HTMLMapper implements IMapper {
  28. /**
  29. * Map a specific element and get configuration from it
  30. * @param element the HTML element to analyze.
  31. */
  32. map(element: HTMLElement): ViewerConfiguration {
  33. let config = {};
  34. for (let attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  35. let attr = element.attributes.item(attrIdx);
  36. if (!attr) {
  37. continue;
  38. }
  39. // map "object.property" to the right configuration place.
  40. let split = attr.nodeName.split('.');
  41. split.reduce((currentConfig, key, idx) => {
  42. //convert html-style to json-style
  43. let camelKey = kebabToCamel(key);
  44. if (idx === split.length - 1) {
  45. let val: any = attr!.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  46. if (val === "true") {
  47. val = true;
  48. } else if (val === "false") {
  49. val = false;
  50. } else {
  51. var isnum = !isNaN(parseFloat(val)) && isFinite(val);///^\d+$/.test(val);
  52. if (isnum) {
  53. let number = parseFloat(val);
  54. if (!isNaN(number)) {
  55. val = number;
  56. }
  57. }
  58. }
  59. currentConfig[camelKey] = val;
  60. } else {
  61. currentConfig[camelKey] = currentConfig[camelKey] || {};
  62. }
  63. return currentConfig[camelKey];
  64. }, config);
  65. }
  66. return config;
  67. }
  68. }
  69. /**
  70. * A simple string-to-JSON mapper.
  71. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  72. */
  73. class JSONMapper implements IMapper {
  74. map(rawSource: string) {
  75. return JSON.parse(rawSource);
  76. }
  77. }
  78. /**
  79. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  80. * DOM elements and attributes.
  81. */
  82. class DOMMapper implements IMapper {
  83. /**
  84. * The mapping function that will convert HTML data to a viewer configuration object
  85. * @param baseElement the baseElement from which to start traversing
  86. * @returns a ViewerCOnfiguration object from the provided HTML Element
  87. */
  88. map(baseElement: HTMLElement): ViewerConfiguration {
  89. let htmlMapper = new HTMLMapper();
  90. let config = htmlMapper.map(baseElement);
  91. let traverseChildren = function (element: HTMLElement, partConfig) {
  92. let children = element.children;
  93. if (children.length) {
  94. for (let i = 0; i < children.length; ++i) {
  95. let item = <HTMLElement>children.item(i);
  96. // use the HTML Mapper to read configuration from a single element
  97. let configMapped = htmlMapper.map(item);
  98. let key = kebabToCamel(item.nodeName.toLowerCase());
  99. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array')!.nodeValue === 'true') {
  100. partConfig[key] = [];
  101. } else {
  102. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array')!.nodeValue === 'true') {
  103. partConfig.push(configMapped)
  104. } else if (partConfig[key]) {
  105. //exists already! probably an array
  106. element.setAttribute('array', 'true');
  107. let oldItem = partConfig[key];
  108. partConfig = [oldItem, configMapped]
  109. } else {
  110. partConfig[key] = configMapped;
  111. }
  112. }
  113. traverseChildren(item, partConfig[key] || configMapped);
  114. }
  115. }
  116. return partConfig;
  117. }
  118. traverseChildren(baseElement, config);
  119. return config;
  120. }
  121. }
  122. /**
  123. * The MapperManager manages the different implemented mappers.
  124. * It allows the user to register new mappers as well and use them to parse their own configuration data
  125. */
  126. export class MapperManager {
  127. private _mappers: { [key: string]: IMapper };
  128. /**
  129. * The default mapper is the JSON mapper.
  130. */
  131. public static DefaultMapper = 'json';
  132. constructor() {
  133. this._mappers = {
  134. "html": new HTMLMapper(),
  135. "json": new JSONMapper(),
  136. "dom": new DOMMapper()
  137. }
  138. }
  139. /**
  140. * Get a specific configuration mapper.
  141. *
  142. * @param type the name of the mapper to load
  143. */
  144. public getMapper(type: string) {
  145. if (!this._mappers[type]) {
  146. Tools.Error("No mapper defined for " + type);
  147. }
  148. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  149. }
  150. /**
  151. * Use this functio to register your own configuration mapper.
  152. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  153. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  154. * @param mapper The implemented mapper
  155. */
  156. public registerMapper(type: string, mapper: IMapper) {
  157. this._mappers[type] = mapper;
  158. }
  159. /**
  160. * Dispose the mapper manager and all of its mappers.
  161. */
  162. public dispose() {
  163. this._mappers = {};
  164. }
  165. }
  166. /**
  167. * mapperManager is a singleton of the type MapperManager.
  168. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  169. * or indirectly with using BabylonViewer.disposeAll()
  170. */
  171. export let mapperManager = new MapperManager();