All files / src/components image.ts

82.05% Statements 32/39
68.75% Branches 22/32
75% Functions 6/8
81.57% Lines 31/38

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                                                                                        1x     1x     1x     1x     1x     1x             1x 25x   1x 25x   1x     25x             1x                     25x 25x       17x   17x   17x 17x   17x               17x 11x         11x         17x                                   17x   17x         17x         17x                               17x       18x                             18x                            
import {LitElement, html, nothing} from 'lit';
import {property} from 'lit/decorators.js';
import {ifDefined} from 'lit/directives/if-defined.js';
import * as dom from '../dom/dom';
import {DomWatcher} from '../dom/dom-watcher';
import {elementVisibility} from '../dom/element-visibility';
import * as func from '../func/func';
 
/**
 *
 * # DeguImage Component.
 *
 *
 * Usage:
 *
 * ```ts
 * import { DeguImage} from '@blinkk/degu/lib/components/image';
 *
 * window.customElements.define('degu-image', DeguImage);
 * ```
 *
 * ```html
 * <degu-image src="xxx" alt=""></degu-image>
 * ```
 *
 * ```css
 *   degu-image {
 *      display: inline-block;
 *      line-height: 0;
 *       width: 100%;
 *   }
 *
 *   degu-image img {
 *     max-width: 100%;
 *     height: auto;
 *   }
 * ```
 *
 * ## Google Image Service Images - automatically autowidthed
 * DeguImage will automatically look at your image source and if it is google
 * image service like, apply autowidth where it fetches the right size image
 * based on your image render width.
 */
export class DeguImage extends LitElement {
  @property({type: String, attribute: 'src'})
  src: string;
 
  @property({type: String, attribute: 'alt'})
  private alt: string;
 
  @property({type: String, attribute: 'loading'})
  private loading: string;
 
  @property({type: String, attribute: 'width'})
  private aspectRatioWidth: number;
 
  @property({type: String, attribute: 'height'})
  private aspectRatioHeight: number;
 
  @property({type: String, attribute: 'google-params'})
  private googleParams: string;
 
  /**
   * When enabled prevents eager loading of images when they are already
   * visible on the screen.
   */
  @property({type: Boolean, attribute: 'disable-eager'})
  private disableEager = false;
 
  @property({type: Number, attribute: 'max-dpr'})
  private maxDpr: number = window.devicePixelRatio;
 
  @property({type: String, attribute: 'fetch-priority'})
  private fetchPriority: string;
 
  @property() autoRenderWidth = 0;
 
  /**
   * Specify a scalar to force increase the size of the google image.
   * Note that an alternative to this is to pass a width parameter via
   * googleParams.
   */
  @property({type: String, attribute: 'google-image-scalar'})
  private googleImageScalar: number;
 
  /**
   * Whether this is a google service like image.
   */
  private isGoogleImage: boolean;
 
  private watcher: DomWatcher;
 
  constructor() {
    super();
    this.loading = 'lazy';
  }
 
  connectedCallback() {
    super.connectedCallback();
 
    this.watcher = new DomWatcher();
 
    this.googleParams = this.googleParams ? '-' + this.googleParams : '';
    this.disableEager = this.getAttribute('disable-eager') === 'true';
 
    this.isGoogleImage =
      this.src &&
      !this.src.includes('.svg') &&
      this.src.startsWith('https://lh3.googleusercontent.com') &&
      // Skip cases where a google image service parameter has already been
      // appended.
      !this.src.includes('=');
 
    if (this.isGoogleImage) {
      this.watcher.add({
        element: this as HTMLElement,
        on: 'resize',
        callback: func.debounce(this.onResize.bind(this), 100),
      });
      this.onResize();
    }
 
    // One time element visibility check to see if this image is already
    // on the screen in which case we don't use lazy image loading.
    elementVisibility.inview(
      this,
      {threshold: 0},
      (element, changes, dispose) => {
        if (changes.isIntersecting) {
          const isPainted = !dom.isDisplayNoneWithAncestors(this);
          if (isPainted && !this.disableEager) {
            this.loading = 'eager';
          }
        }
        dispose();
      }
    );
  }
 
  private onResize() {
    // Calculate the width to the nearest 50 pixel.
    // Example: 420 --> 450, 451 --> 500
    const image = this.querySelector('img');
    const width =
      Math.ceil(
        Math.max(this.offsetWidth, image ? image.offsetWidth : 0) / 50
      ) * 50;
 
    const height =
      Math.ceil(
        Math.max(this.offsetHeight, image ? image.offsetHeight : 0) / 50
      ) * 50;
 
    // Calculate the autowidth render size and take the historical maximum.
    this.autoRenderWidth = Math.max(
      this.autoRenderWidth,
      Math.ceil(
        Math.max(width, height) *
          (this.googleImageScalar || 1) *
          Math.min(window.devicePixelRatio, this.maxDpr)
      )
    );
  }
 
  disconnectedCallback() {
    super.disconnectedCallback();
    this.watcher && this.watcher.dispose();
  }
 
  createRenderRoot() {
    return this;
  }
 
  private renderImage(src: string) {
    return html`
      <img 
        loading="${this.loading}"
        fetchPriority=${ifDefined(this.fetchPriority ? this.fetchPriority : null)}
        width=${ifDefined(this.aspectRatioWidth ? this.aspectRatioWidth : null)}
        height=${ifDefined(
          this.aspectRatioHeight ? this.aspectRatioHeight : null
        )}
        src="${src}"
        alt="${this.alt}"
      />
    `;
  }
 
  render() {
    return html`
      ${
        this.isGoogleImage
          ? this.autoRenderWidth === 0
            ? nothing
            : this.renderImage(
                this.src +
                  `=rw-e365-w${this.autoRenderWidth}${this.googleParams}`
              )
          : this.renderImage(this.src)
      }
    `;
  }
}