util.ts 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. /**
  2. * Extend object a with the properties of object b.
  3. * If there's a conflict, object b takes precedence.
  4. *
  5. * @param {object} a
  6. * @param {object} b
  7. */
  8. export const extend = (a: Record<string, any>, b: Record<string, any>) => {
  9. for (let i in b) {
  10. a[i] = b[i];
  11. }
  12. return a;
  13. };
  14. /**
  15. * querySelectorAll but returns an Array.
  16. */
  17. export const queryAll = (el: Element | Document, selector: string): Element[] => {
  18. return Array.from(el.querySelectorAll(selector));
  19. };
  20. /**
  21. * classList.toggle() with cross browser support
  22. */
  23. export const toggleClass = (el: Element, className: string, value: boolean) => {
  24. if (value) {
  25. el.classList.add(className);
  26. } else {
  27. el.classList.remove(className);
  28. }
  29. };
  30. type DeserializedValue = string | number | boolean | null;
  31. /**
  32. * Utility for deserializing a value.
  33. *
  34. * @param {*} value
  35. * @return {*}
  36. */
  37. export const deserialize = (value: string): DeserializedValue => {
  38. if (typeof value === 'string') {
  39. if (value === 'null') return null;
  40. else if (value === 'true') return true;
  41. else if (value === 'false') return false;
  42. else if (value.match(/^-?[\d\.]+$/)) return parseFloat(value);
  43. }
  44. return value;
  45. };
  46. /**
  47. * Measures the distance in pixels between point a
  48. * and point b.
  49. *
  50. * @param {object} a point with x/y properties
  51. * @param {object} b point with x/y properties
  52. *
  53. * @return {number}
  54. */
  55. export const distanceBetween = (
  56. a: { x: number; y: number },
  57. b: { x: number; y: number }
  58. ): number => {
  59. let dx = a.x - b.x,
  60. dy = a.y - b.y;
  61. return Math.sqrt(dx * dx + dy * dy);
  62. };
  63. /**
  64. * Applies a CSS transform to the target element.
  65. *
  66. * @param {HTMLElement} element
  67. * @param {string} transform
  68. */
  69. export const transformElement = (element: HTMLElement, transform: string) => {
  70. element.style.transform = transform;
  71. };
  72. /**
  73. * Element.matches with IE support.
  74. *
  75. * @param {HTMLElement} target The element to match
  76. * @param {String} selector The CSS selector to match
  77. * the element against
  78. *
  79. * @return {Boolean}
  80. */
  81. export const matches = (target: any, selector: string): boolean => {
  82. let matchesMethod = target.matches || target.matchesSelector || target.msMatchesSelector;
  83. return !!(matchesMethod && matchesMethod.call(target, selector));
  84. };
  85. /**
  86. * Find the closest parent that matches the given
  87. * selector.
  88. *
  89. * @param {HTMLElement} target The child element
  90. * @param {String} selector The CSS selector to match
  91. * the parents against
  92. *
  93. * @return {HTMLElement} The matched parent or null
  94. * if no matching parent was found
  95. */
  96. export const closest = (target: Element | null, selector: string): Element | null => {
  97. // Native Element.closest
  98. if (target && typeof target.closest === 'function') {
  99. return target.closest(selector);
  100. }
  101. // Polyfill
  102. while (target) {
  103. if (matches(target, selector)) {
  104. return target;
  105. }
  106. // Keep searching
  107. target = target.parentElement;
  108. }
  109. return null;
  110. };
  111. /**
  112. * Handling the fullscreen functionality via the fullscreen API
  113. *
  114. * @see http://fullscreen.spec.whatwg.org/
  115. * @see https://developer.mozilla.org/en-US/docs/DOM/Using_fullscreen_mode
  116. */
  117. export const enterFullscreen = (element?: Element) => {
  118. element = element || document.documentElement;
  119. // Check which implementation is available
  120. let requestMethod =
  121. (element as any).requestFullscreen ||
  122. (element as any).webkitRequestFullscreen ||
  123. (element as any).webkitRequestFullScreen ||
  124. (element as any).mozRequestFullScreen ||
  125. (element as any).msRequestFullscreen;
  126. if (requestMethod) {
  127. requestMethod.apply(element);
  128. }
  129. };
  130. /**
  131. * Creates an HTML element and returns a reference to it.
  132. * If the element already exists the existing instance will
  133. * be returned.
  134. *
  135. * @param {HTMLElement} container
  136. * @param {string} tagname
  137. * @param {string} classname
  138. * @param {string} innerHTML
  139. *
  140. * @return {HTMLElement}
  141. */
  142. export const createSingletonNode = (
  143. container: Element,
  144. tagname: string,
  145. classname: string,
  146. innerHTML: string = ''
  147. ): Element => {
  148. // Find all nodes matching the description
  149. let nodes = container.querySelectorAll('.' + classname);
  150. // Check all matches to find one which is a direct child of
  151. // the specified container
  152. for (let i = 0; i < nodes.length; i++) {
  153. let testNode = nodes[i];
  154. if (testNode.parentNode === container) {
  155. return testNode;
  156. }
  157. }
  158. // If no node was found, create it now
  159. let node = document.createElement(tagname);
  160. node.className = classname;
  161. node.innerHTML = innerHTML;
  162. container.appendChild(node);
  163. return node;
  164. };
  165. /**
  166. * Injects the given CSS styles into the DOM.
  167. *
  168. * @param {string} value
  169. */
  170. export const createStyleSheet = (value: string): HTMLStyleElement => {
  171. let tag = document.createElement('style');
  172. if (value && value.length > 0) {
  173. tag.appendChild(document.createTextNode(value));
  174. }
  175. document.head.appendChild(tag);
  176. return tag;
  177. };
  178. /**
  179. * Returns a key:value hash of all query params.
  180. */
  181. export const getQueryHash = (): Record<string, DeserializedValue> => {
  182. let query: Record<string, DeserializedValue> = {};
  183. location.search.replace(/[A-Z0-9]+?=([\w\.%-]*)/gi, (a: string) => {
  184. const key = a.split('=').shift();
  185. const value = a.split('=').pop();
  186. if (key && value !== undefined) {
  187. query[key] = value;
  188. }
  189. return a;
  190. });
  191. // Basic deserialization
  192. for (let i in query) {
  193. let value = query[i];
  194. query[i] = deserialize(unescape(value as string));
  195. }
  196. // Do not accept new dependencies via query config to avoid
  197. // the potential of malicious script injection
  198. if (typeof query['dependencies'] !== 'undefined') delete query['dependencies'];
  199. return query;
  200. };
  201. /**
  202. * Returns the remaining height within the parent of the
  203. * target element.
  204. *
  205. * remaining height = [ configured parent height ] - [ current parent height ]
  206. *
  207. * @param {HTMLElement} element
  208. * @param {number} [height]
  209. */
  210. export const getRemainingHeight = (element: HTMLElement | null, height: number = 0): number => {
  211. if (element) {
  212. let newHeight: number,
  213. oldHeight = element.style.height;
  214. // Change the .stretch element height to 0 in order find the height of all
  215. // the other elements
  216. element.style.height = '0px';
  217. // In Overview mode, the parent (.slide) height is set of 700px.
  218. // Restore it temporarily to its natural height.
  219. if (element.parentElement) {
  220. element.parentElement.style.height = 'auto';
  221. }
  222. newHeight = height - (element.parentElement?.offsetHeight || 0);
  223. // Restore the old height, just in case
  224. element.style.height = oldHeight + 'px';
  225. // Clear the parent (.slide) height. .removeProperty works in IE9+
  226. if (element.parentElement) {
  227. element.parentElement.style.removeProperty('height');
  228. }
  229. return newHeight;
  230. }
  231. return height;
  232. };
  233. const fileExtensionToMimeMap: Record<string, string> = {
  234. mp4: 'video/mp4',
  235. m4a: 'video/mp4',
  236. ogv: 'video/ogg',
  237. mpeg: 'video/mpeg',
  238. webm: 'video/webm',
  239. };
  240. /**
  241. * Guess the MIME type for common file formats.
  242. */
  243. export const getMimeTypeFromFile = (filename: string = ''): string | undefined => {
  244. const extension = filename.split('.').pop();
  245. return extension ? fileExtensionToMimeMap[extension] : undefined;
  246. };
  247. /**
  248. * Encodes a string for RFC3986-compliant URL format.
  249. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/encodeURI#encoding_for_rfc3986
  250. *
  251. * @param {string} url
  252. */
  253. export const encodeRFC3986URI = (url: string = ''): string => {
  254. return encodeURI(url)
  255. .replace(/%5B/g, '[')
  256. .replace(/%5D/g, ']')
  257. .replace(/[!'()*]/g, (c) => `%${c.charCodeAt(0).toString(16).toUpperCase()}`);
  258. };