All files / src/angular directive-lazy-image-simple.ts

0% Statements 0/47
0% Branches 0/11
0% Functions 0/16
0% Lines 0/47

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215                                                                                                                                                                                                                                                                                                                                                                                                                                             
import * as dom from '../dom/dom';
import {DomWatcher} from '../dom/dom-watcher';
import {
  type ElementVisibilityObject,
  elementVisibility,
} from '../dom/element-visibility';
import * as is from '../is/is';
import type {INgDisposable} from './i-ng-disposable';
 
export class LazyImageSimple implements INgDisposable {
  static get $inject() {
    return ['$scope', '$element', '$attrs'];
  }
 
  private el: HTMLElement;
  // The url to set.
  private url: string;
  // Whether this directive has finished setting the background image.
  private imageSet: boolean;
  private setAsBackgroundImage: boolean;
  private watcher: DomWatcher;
  private ev: ElementVisibilityObject;
 
  // The amount of rootMargin offset to apply to lazyimage.
  // 1 would result in a forward load of 1 * window.innerHeight.
  // 0 would mean no forward load.
  // Defaults to 1.
  // Set to higher values if you want to load more images that are below
  // the current fold.
  private forwardLoadScalar: number;
 
  constructor(
    $scope: ng.IScope,
    $element: ng.IAugmentedJQuery,
    $attrs: ng.IAttributes
  ) {
    this.el = $element[0];
    this.url = $attrs.lazyImageSimple;
    this.setAsBackgroundImage = !!$attrs.lazyImageSimpleAsBackground;
    this.forwardLoadScalar = is.defined($attrs.lazyImageSimpleForwardLoadScalar)
      ? +$attrs.lazyImageSimpleForwardLoadScalar
      : 1;
    this.imageSet = false;
 
    this.watcher = new DomWatcher();
    this.watcher.add({
      element: window,
      on: 'smartResize',
      callback: this.paint.bind(this),
    });
 
    this.ev = elementVisibility.inview(
      this.el,
      {
        rootMargin: window.innerHeight * this.forwardLoadScalar + 'px',
      },
      () => {
        this.paint();
      }
    );
 
    this.watcher.add({
      element: this.el,
      on: 'force-lazy-load',
      callback: () => {
        this.startLoad();
      },
    });
 
    $scope.$on('$destroy', () => {
      this.dispose();
    });
  }
 
  /**
   * Attemps to set the image if possible.
   */
  paint() {
    if (this.isPaintedOnScreen() && !this.imageSet && this.ev.state().inview) {
      this.startLoad();
    }
  }
 
  private startLoad() {
    this.imageSet = true;
    this.watcher.dispose();
    this.ev.dispose();
    this.loadImage().then(() => {
      dom.event(document.documentElement, 'lazy-image-simple-loaded', {
        element: this.el,
      });
    });
  }
 
  loadImage(): Promise<void> {
    return new Promise((resolve) => {
      const element = this.el;
 
      // If this is to be a background image.
      if (this.setAsBackgroundImage) {
        this.el.style.backgroundImage = `url(${this.url})`;
        this.el.classList.add('loaded');
        resolve();
        return;
      }
 
      // If this is a new image to be replaced.
      const imageLoader = new Image();
      const onLoad = () => {
        // Add loaded class.
        imageLoader.classList.add('loaded');
        // Swap out the div with the new image.
        element.parentNode &&
          element.parentNode.replaceChild(imageLoader, element);
        resolve();
      };
 
      imageLoader.addEventListener('load', onLoad, {
        once: true,
      });
 
      const onError = () => {
        resolve();
      };
      imageLoader.addEventListener('error', onError, {
        once: true,
      });
 
      const attributes = Array.prototype.slice
        .call(element.attributes)
        .concat();
      // Transfer all attributes on the div to the new image.
      attributes.forEach((attr) => {
        imageLoader.setAttribute(attr.name, attr.value);
      });
 
      imageLoader.src = this.url;
    });
  }
 
  /**
   * Determines whether this element was painted (displayed on the screen).
   * The basis of this is having a css class of display none.  Other methods
   * of hiding the element will return true.
   */
  isPaintedOnScreen() {
    const style = window.getComputedStyle(this.el, null).display;
    return style !== 'none';
  }
 
  dispose() {
    this.ev.dispose();
    this.watcher.dispose();
  }
}
 
/**
 * Allows loading of images only if the element or the child
 * is currently visible on the screen.  The basis of whether it is visible
 * is determined based on if the dislay is NOT set to none.
 *
 * Name your directive as lazyImageSimple.
 *
 *     ngApp.directive('lazyImageSimple', lazyImageSimpleDirective);
 *
 *
 * Now use it.
 * This will load the image:
 * ```
 * <div lazy-image-simple="{{url}}"></div>
 * ```
 *
 * After render will turn into:
 * ```
 * <img src="{{url}}">
 * ```
 *
 *
 * ## As background image
 * This will load the image as a background image:
 * <div lazy-image-simple="{{url}}" lazy-image-simple-as-background="true"></div>
 *
 * After render will turn into:
 * ```
 * <div style="backgroundImage: url({{url}})"></div>
 * ```
 *
 * ## Conditional loading based on element visibility
 * This will load only when on mobile.  The directive runs a test to see if the
 * directive element has display: none as a style.  If so, it will not run.
 * ```
 * .only-mobile
 *   +md
 *     display: none
 *
 * <div lazy-image-simple="{{url}}" style="only-mobile"></div>
 * ```
 *
 *
 * ## Adjust lazyloading timing with forward-load-scalar
 * The directive lazy loads images.   By default, it will load 100vh below
 * the current fold.  You can adjust this value, by passing the lazyImageForwardLoadScalar.
 *
 * <div lazy-image-simple="{{url}}" lazy-image-simple-forward-load-scalar="2"></div>
 *
 * // Zero means no foward load
 * <div lazy-image-simple="{{url}}" lazy-image-simple-forward-load-scalar="0"></div>
 */
export const lazyImageSimpleDirective = function () {
  return {
    restrict: 'A',
    controller: LazyImageSimple,
  };
};