|
| 1 | +--- |
| 2 | +import type { ImageLoaderProps } from './imageloader' |
| 3 | +
|
| 4 | +import Image from '../Image/Image.astro' |
| 5 | +import Skeleton from '../Skeleton/Skeleton.astro' |
| 6 | +
|
| 7 | +import { classNames } from '../../utils/classNames' |
| 8 | +
|
| 9 | +import styles from './imageloader.module.scss' |
| 10 | +
|
| 11 | +interface Props extends ImageLoaderProps {} |
| 12 | +
|
| 13 | +const { |
| 14 | + fallback, |
| 15 | + animate, |
| 16 | + type, |
| 17 | + width, |
| 18 | + height, |
| 19 | + color, |
| 20 | + waveColor, |
| 21 | + className, |
| 22 | + ...rest |
| 23 | +} = Astro.props |
| 24 | +
|
| 25 | +const styleVariables = classNames([ |
| 26 | + `width: ${width}px;`, |
| 27 | + `height: ${height}px;` |
| 28 | +]) |
| 29 | +--- |
| 30 | + |
| 31 | +<div data-id="w-image-loader" class={styles.loader} style={styleVariables}> |
| 32 | + <Skeleton |
| 33 | + animate={animate} |
| 34 | + type={type} |
| 35 | + width={Number(width)} |
| 36 | + height={Number(height)} |
| 37 | + color={color} |
| 38 | + waveColor={waveColor} |
| 39 | + className={className} |
| 40 | + /> |
| 41 | + <Image |
| 42 | + width={width} |
| 43 | + height={height} |
| 44 | + className={className} |
| 45 | + data-fallback={fallback} |
| 46 | + {...rest} |
| 47 | + /> |
| 48 | +</div> |
| 49 | + |
| 50 | +<script> |
| 51 | + import { get, on } from '../../utils/DOMUtils' |
| 52 | + |
| 53 | + const addEventListeners = () => { |
| 54 | + const images = get<HTMLImageElement>('[data-id="w-image-loader"] img', true) |
| 55 | + |
| 56 | + if (!images || !(images instanceof NodeList)) { |
| 57 | + return |
| 58 | + } |
| 59 | + |
| 60 | + images.forEach(img => { |
| 61 | + const container = img.parentElement as HTMLDivElement |
| 62 | + const skeleton = container.firstElementChild as HTMLDivElement |
| 63 | + |
| 64 | + const handleError = () => { |
| 65 | + img.src = img.dataset.fallback || img.src |
| 66 | + skeleton?.remove() |
| 67 | + } |
| 68 | + |
| 69 | + if (img.complete) { |
| 70 | + img.naturalWidth === 0 ? handleError() : skeleton?.remove() |
| 71 | + |
| 72 | + return |
| 73 | + } |
| 74 | + |
| 75 | + img.addEventListener('load', () => skeleton?.remove(), { once: true }) |
| 76 | + img.addEventListener('error', () => handleError(), { once: true }) |
| 77 | + }) |
| 78 | + } |
| 79 | + |
| 80 | + on(document, 'astro:after-swap', addEventListeners) |
| 81 | + addEventListeners() |
| 82 | +</script> |
0 commit comments