All files / media-loader/src/MediaLoader/image index.ts

100% Statements 9/9
100% Branches 3/3
100% Functions 3/3
100% Lines 9/9

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              1x     1x   3x 3x               3x       1x 1x 1x 1x        
/**
 * Copyright (c) 2024-present, Matti Bar-Zeev.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */
 
import {ReactElement, RefObject, cloneElement, createRef} from 'react';
import {MediaProcessor} from '../types';
 
export class ImageProcessor implements MediaProcessor {
    getProcessedChildren(child: ReactElement): [ReactElement, RefObject<HTMLImageElement>] {
        const imgRef = createRef<HTMLImageElement>();
        const imgElement = cloneElement(child, {
            'data-src': child.props.src,
            src: null,
            style: {visibility: 'hidden'},
            ref: imgRef,
            alt: child.props.alt || '',
        });
 
        return [imgElement, imgRef];
    }
 
    loadMedia(htmlImageElement: HTMLImageElement): void {
        if (htmlImageElement.hasAttribute('data-src')) {
            htmlImageElement.setAttribute('style', 'visibility: "visible"');
            htmlImageElement.setAttribute('src', htmlImageElement.getAttribute('data-src') as string);
            htmlImageElement.removeAttribute('data-src');
        }
    }
}