feat: 媒体流图片自适应显示(单图/2图/Telegram式相册)
- 单图气泡按真实比例显示:横图限高260px、过高裁上下;竖图完整铺满宽度不裁、无黑边 - 2张同类相册:都竖图左右并排、都横图上下堆叠,按比例不裁 - 3+张相册:Telegram式马赛克拼贴(竖主图占左+其余堆右 / 横主图占顶+其余排底) - 图片比例优先用后端width/height,缺失时从加载后的naturalWidth/Height读取 - 新增 constants/media.ts 统一尺寸规范;albumLayout 纯算法附单测 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
47
src/components/messageStream/hooks/useImageRatios.ts
Normal file
47
src/components/messageStream/hooks/useImageRatios.ts
Normal file
@@ -0,0 +1,47 @@
|
||||
import { useEffect, useState } from "react";
|
||||
import type { Attachment } from "../../../types/post";
|
||||
|
||||
/**
|
||||
* Resolves each attachment's aspect ratio (width / height). Seeds from
|
||||
* backend-provided width/height when present (no flash), then refines by
|
||||
* loading the image and reading its intrinsic size — so it works even when the
|
||||
* backend omits dimensions. Entries are `undefined` until known.
|
||||
*/
|
||||
export function useImageRatios(
|
||||
attachments: Attachment[],
|
||||
sources: (string | undefined)[],
|
||||
): (number | undefined)[] {
|
||||
const seed = attachments.map((a) =>
|
||||
a.width && a.height ? a.width / a.height : undefined,
|
||||
);
|
||||
const [ratios, setRatios] = useState<(number | undefined)[]>(seed);
|
||||
|
||||
const key = sources.join("|");
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
setRatios(
|
||||
attachments.map((a) =>
|
||||
a.width && a.height ? a.width / a.height : undefined,
|
||||
),
|
||||
);
|
||||
sources.forEach((src, i) => {
|
||||
if (!src) return;
|
||||
const img = new Image();
|
||||
img.onload = () => {
|
||||
if (cancelled || !img.naturalWidth || !img.naturalHeight) return;
|
||||
setRatios((prev) => {
|
||||
const next = prev.slice();
|
||||
next[i] = img.naturalWidth / img.naturalHeight;
|
||||
return next;
|
||||
});
|
||||
};
|
||||
img.src = src;
|
||||
});
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [key]);
|
||||
|
||||
return ratios;
|
||||
}
|
||||
Reference in New Issue
Block a user