inogen/app/admin/components/RecordImage.tsx
2026-10-18 18:12:59 +03:30

65 lines
1.6 KiB
TypeScript

import { Image as ImageIcon } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { api, apiOrigin } from "../lib/api";
import type { FirstImageItem } from "../types";
export function useFirstImages(entityType: string, entityIds: string[] | undefined) {
const key = useMemo(
() => [...new Set(entityIds ?? [])].sort().join(","),
[entityIds?.join(",")],
);
const [images, setImages] = useState<Record<string, string>>({});
useEffect(() => {
let active = true;
if (!key) {
setImages({});
return;
}
api<FirstImageItem[]>(
`/api/v1/files/first-images?entityType=${encodeURIComponent(entityType)}&entityIds=${encodeURIComponent(key)}`,
)
.then((items) => {
if (active)
setImages(Object.fromEntries(items.map((x) => [x.entityId, x.attachmentId])));
})
.catch(() => {
if (active) setImages({});
});
return () => {
active = false;
};
}, [entityType, key]);
return images;
}
export function RecordAvatar({
attachmentId,
label,
}: {
attachmentId?: string;
label: string;
}) {
const [failed, setFailed] = useState(false);
useEffect(() => setFailed(false), [attachmentId]);
if (!attachmentId || failed)
return (
<span className="record-avatar record-avatar-empty" title="تصویری ثبت نشده است">
<ImageIcon size={18} />
</span>
);
return (
<img
className="record-avatar"
src={`${apiOrigin}/api/v1/files/${attachmentId}/preview`}
alt={label}
loading="lazy"
onError={() => setFailed(true)}
/>
);
}