live-photos.js

  1. var LivePhoto = require('./live-photo');
  2. var styles = require('./styles.scss');
  3. var supportsLivePhotos = true;
  4. var stylesInUse = 0;
  5. var useStyles = true;
  6. /**
  7. * Initializes the Live Photos on a page specified by the `data-live-photo` attribute or supplied
  8. *
  9. * @memberof LivePhotos
  10. * @static
  11. * @alias initialize
  12. *
  13. * @param {Object|Array|string} [elements] - elements or selectors to create Live Photos from
  14. * @param {Object} [options] - options passed to each live photo
  15. *
  16. * @return {Array<LivePhoto>} Array of {@link LivePhoto} instances
  17. */
  18. function initializeLivePhotos(elements, options) {
  19. if (!supportsLivePhotos) {
  20. return;
  21. }
  22. if (useStyles) {
  23. addStyles();
  24. }
  25. if (typeof elements === 'object' && elements.toString() === '[object Object]') {
  26. options = elements;
  27. elements = options.elements;
  28. delete options.elements;
  29. }
  30. elements || (elements = 'img[data-live-photo]');
  31. if (typeof elements === 'string') {
  32. elements = document.querySelectorAll(elements);
  33. }
  34. if (elements instanceof HTMLElement) {
  35. elements = [elements];
  36. }
  37. var livePhotos = [];
  38. Array.prototype.forEach.call(elements, function(el) {
  39. if (typeof el === 'string') {
  40. el = document.querySelector(el);
  41. }
  42. if (el) {
  43. var livePhoto = new LivePhoto(el, options);
  44. livePhotos.push(livePhoto);
  45. }
  46. });
  47. return livePhotos;
  48. }
  49. /**
  50. * Appends the styles to the page
  51. *
  52. * @memberof LivePhotos
  53. * @static
  54. */
  55. function addStyles() {
  56. styles.use();
  57. stylesInUse++;
  58. }
  59. /**
  60. * Prevents styles from being appended to the page
  61. *
  62. * @memberof LivePhotos
  63. * @static
  64. */
  65. function noStyles() {
  66. useStyles = false;
  67. }
  68. /**
  69. * Removes appended styles
  70. *
  71. * @memberof LivePhotos
  72. * @static
  73. */
  74. function cleanup() {
  75. while (stylesInUse > 0) {
  76. styles.unuse();
  77. stylesInUse--;
  78. }
  79. }
  80. /**
  81. * By default, this module acts as a function that creates LivePhotos, but using the
  82. * {@linkplain LivePhotos.initialize static method} is preferable.
  83. *
  84. * @namespace LivePhotos
  85. * @see {@link LivePhotos.initialize}
  86. */
  87. function LivePhotos(elements, options) {
  88. return initializeLivePhotos(elements, options);
  89. }
  90. LivePhotos.initialize = initializeLivePhotos;
  91. LivePhotos.addStyles = addStyles;
  92. LivePhotos.noStyles = noStyles;
  93. LivePhotos.cleanup = cleanup;
  94. /**
  95. * Passthrough for the {@link LivePhoto} class
  96. *
  97. * @memberof LivePhotos
  98. * @see {@link LivePhoto}
  99. */
  100. LivePhotos.LivePhoto = LivePhoto;
  101. module.exports = LivePhotos;