File size: 7,096 Bytes
96dd062 | 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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | ---
import { Picture } from "astro:assets";
import * as path from "node:path";
import type { ImageMetadata } from "astro";
import { coverImageConfig } from "@/config/coverImageConfig";
import type { ImageFormat, ResponsiveImageLayout } from "@/types/config";
import {
getFallbackFormat,
getImageFormats,
getImageQuality,
} from "@/utils/image-utils";
import { url } from "@/utils/url-utils";
interface Props {
id?: string;
src: string;
class?: string;
alt?: string;
position?: string;
basePath?: string;
preview?: boolean;
layout?: ResponsiveImageLayout;
formats?: ImageFormat[];
loading?: "lazy" | "eager";
}
const {
id,
src,
alt,
position = "center",
basePath = "/",
preview = false,
layout = "constrained",
formats = getImageFormats(),
loading = "lazy",
} = Astro.props;
const configQuality = getImageQuality();
const fallbackFormat = getFallbackFormat();
const className = Astro.props.class;
// 判断图片类型
const isLocal = !(
src.startsWith("/") ||
src.startsWith("http") ||
src.startsWith("https") ||
src.startsWith("data:")
);
const isPublic = src.startsWith("/");
// 动态导入本地图片
let img: ImageMetadata | null = null;
if (isLocal) {
const files = import.meta.glob<ImageMetadata>(
"../../**/*.{png,jpg,jpeg,webp,avif}",
{
import: "default",
},
);
const normalizedPath = path
.normalize(path.join("../../", basePath, src))
.replace(/\\/g, "/");
const file = files[normalizedPath];
if (file) {
img = await file();
} else {
console.error(
`[ERROR] Image not found: ${normalizedPath.replace("../../", "src/")}`,
);
}
}
// 加载回退图片
let fallbackImg: ImageMetadata | null = null;
const fallbackPath = coverImageConfig.randomCoverImage.fallback;
if (fallbackPath && !isLocal) {
const files = import.meta.glob<ImageMetadata>(
"../../**/*.{png,jpg,jpeg,webp,avif}",
{
import: "default",
},
);
const normalizedFallbackPath = path
.normalize(path.join("../../", fallbackPath))
.replace(/\\/g, "/");
const file = files[normalizedFallbackPath];
if (file) {
fallbackImg = await file();
}
}
// 图片样式
const imageClass = "w-full h-full object-cover";
const imageStyle = `object-position: ${position};`;
// 响应式配置
const widths = preview ? [320, 480, 640, 960] : [800, 1200, 1600, 2000];
const sizes = preview
? "(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 320px"
: "(max-width: 768px) 100vw, (max-width: 1200px) 90vw, 1200px";
const quality = preview ? Math.round(configQuality * 0.9) : configQuality;
// 是否显示加载动画
const showLoading = coverImageConfig.randomCoverImage.showLoading ?? true;
---
<div
id={id}
class:list={[className, "cover-image-container overflow-hidden relative"]}
data-loading={showLoading ? "true" : "false"}
>
<!-- 加载动画 -->
{showLoading && (
<div class="loading-spinner absolute inset-0 flex items-center justify-center z-10" style="background-color: var(--card-bg);">
<div class="spinner"></div>
</div>
)}
<!-- 错误提示(覆盖在回退图片上) -->
<div class="error-message absolute inset-0 flex items-center justify-center z-20 hidden pointer-events-none">
<span class="text-white text-sm px-3 py-1 rounded bg-black/50">Image API Error</span>
</div>
<!-- 回退图片(错误时显示) -->
{fallbackImg && (
<div class="fallback-image absolute inset-0 hidden">
<Picture
src={fallbackImg}
alt="Fallback cover"
class={imageClass}
style={imageStyle}
width={preview ? 400 : 1200}
height={preview ? 300 : 800}
loading="lazy"
formats={formats}
fallbackFormat={fallbackFormat}
quality={quality}
widths={widths}
sizes={sizes}
layout={layout}
/>
</div>
)}
<!-- 本地图片 -->
{isLocal && img && (
<Picture
src={img}
alt={alt || ""}
class={imageClass}
style={imageStyle}
width={preview ? 400 : 1200}
height={preview ? 300 : 800}
loading={loading}
formats={formats}
fallbackFormat={fallbackFormat}
quality={quality}
widths={widths}
sizes={sizes}
layout={layout}
data-cover-img
/>
)}
<!-- 远程图片 -->
{!isLocal && (
<img
src={isPublic ? url(src) : src}
alt={alt || ""}
class={imageClass}
style={imageStyle}
loading={loading}
decoding="async"
data-cover-img
data-remote="true"
/>
)}
</div>
<style>
.cover-image-container {
min-height: 150px;
}
@media (min-width: 768px) {
.cover-image-container {
min-height: 0;
}
}
/* 加载动画容器 */
.loading-spinner {
transition: opacity 0.3s ease-out;
}
/* 加载完成后隐藏 */
.cover-image-container[data-loading="false"] .loading-spinner {
opacity: 0;
pointer-events: none;
}
/* 错误状态隐藏加载动画 */
.cover-image-container[data-error="true"] .loading-spinner {
display: none;
}
/* 错误状态显示错误信息和回退图片 */
.cover-image-container[data-error="true"] .error-message {
display: flex;
}
.cover-image-container[data-error="true"] .fallback-image {
display: block;
}
/* 错误状态隐藏失败的远程图片 */
.cover-image-container[data-error="true"] img[data-remote="true"] {
display: none;
}
/* 旋转加载动画 */
.spinner {
width: 40px;
height: 40px;
border: 3px solid oklch(0.9 0.05 var(--hue));
border-top-color: oklch(0.6 0.15 var(--hue));
border-radius: 50%;
animation: spin 0.8s linear infinite;
}
@keyframes spin {
to {
transform: rotate(360deg);
}
}
/* 图片样式 */
.cover-image-container img {
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
<script>
function initCoverImages() {
// 处理所有封面图容器,无论是否显示加载动画
const containers = document.querySelectorAll('.cover-image-container');
containers.forEach((container) => {
// 跳过已处理过的容器
if (container.hasAttribute('data-initialized')) return;
container.setAttribute('data-initialized', 'true');
const img = container.querySelector('img[data-cover-img]') as HTMLImageElement | null;
if (!img) return;
const hideLoading = () => {
container.setAttribute('data-loading', 'false');
};
const showError = () => {
container.setAttribute('data-loading', 'false');
container.setAttribute('data-error', 'true');
};
if (img.complete) {
if (img.naturalWidth > 0) {
hideLoading();
} else if (img.dataset.remote === 'true') {
showError();
}
} else {
img.addEventListener('load', hideLoading, { once: true });
img.addEventListener('error', () => {
if (img.dataset.remote === 'true') {
showError();
}
}, { once: true });
}
});
}
// 初始化
initCoverImages();
// 支持 Swup 等页面切换
document.addEventListener('astro:page-load', initCoverImages);
</script>
|