Files
co-lite/solvway-admin-portal/app/components/messages/ImageAttachments.tsx
T
ngqileandClaude Opus 5.5 5ee51d1913 chore: copy kept Tastefully modules and portals into Co-Lite
Backend modules from tastefully 8bd93d15: core-libs, core-session,
api-gateway, mobile-api, services-auth, services-system,
services-counter, services-member, services-log, services-email.
solvway-admin-portal from babyboo f64d096ea, solvway-customer-portal
from tastefully 8bd93d15. Copied as tracked files only.

Literal secrets replaced with environment placeholders:
- services-email: SMTP_PASSWORD, MAILGUN_API_KEY, SENDGRID_API_KEY,
  MAILJET_API_KEY, MAILJET_SECRET_KEY (optional, empty default)
- services-system: JUMIO_TOKEN, JUMIO_SECRET (optional)
- services-auth: USER_AUTH_API_SECRET (required); commented JWT secret removed
- core-libs: JWT_TOKEN default removed (required), XXL_JOB_TOKEN default
  removed, ipgeolocation key read from IPGEOLOCATION_API_KEY
- services-system EkycAppConfig: commented Jumio credentials removed

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EFUzfj5akPxyikzGc2iAHM
2026-11-26 15:55:45 +08:00

117 lines
4.6 KiB
TypeScript

"use client";
import { useRef, useState } from "react";
import { ImagePlus, X } from "lucide-react";
import { Button } from "@/app/components/ui/button";
import { useT } from "@/app/lib/i18n/MessagesProvider";
import { MAX_IMAGES, messageErrorText, uploadAdminMessageImage, validateImage } from "@/app/lib/services/adminMessages";
import { shrinkImage } from "@/app/lib/images/shrinkImage";
// Step 1 of the TWO-STEP image flow: each picked file uploads immediately and yields a private-bucket
// `ref`; mobile-api commits the refs when the message is sent. Abandoned uploads are reaped (intended).
export interface Attachment {
id: number;
name: string;
ref?: string;
error?: string;
}
export function useAttachments() {
const t = useT();
const [items, setItems] = useState<Attachment[]>([]);
const seq = useRef(0);
const add = async (files: File[]) => {
// Rejected types are listed with their error but never take one of the MAX_IMAGES slots; size is checked
// only after shrinkImage re-encodes the photo (see below).
const room = Math.max(0, MAX_IMAGES - items.filter((x) => !x.error).length);
const ok = files.filter((f) => validateImage(f) !== "type").slice(0, room);
const bad = files.filter((f) => validateImage(f) === "type");
const fresh = [...ok, ...bad].map((file) => {
const att: Attachment = {
id: ++seq.current,
name: file.name,
error: validateImage(file) === "type" ? t("MsgImageType") : undefined,
};
return { file, att };
});
setItems((cur) => [...cur, ...fresh.map((f) => f.att)]);
await Promise.all(
fresh
.filter((f) => !f.att.error)
.map(async ({ file, att }) => {
try {
const small = await shrinkImage(file); // <=2000px JPEG within ~900 KB; small PNGs and undecodable files unchanged
if (validateImage(small) === "size") {
setItems((cur) => cur.map((x) => (x.id === att.id ? { ...x, error: t("MsgImageSize") } : x)));
return;
}
const { ref } = await uploadAdminMessageImage(small);
setItems((cur) => cur.map((x) => (x.id === att.id ? { ...x, ref } : x)));
} catch (e) {
const error = messageErrorText(e, t, "MsgImageUploadFailed");
setItems((cur) => cur.map((x) => (x.id === att.id ? { ...x, error } : x)));
}
}),
);
};
return {
items,
add,
remove: (id: number) => setItems((cur) => cur.filter((x) => x.id !== id)),
reset: () => setItems([]),
/** After a send: drop only the images that went out, so anything added meanwhile survives. */
removeSent: (refs: string[]) => setItems((cur) => cur.filter((x) => !x.ref || !refs.includes(x.ref))),
refs: items.flatMap((x) => (x.ref ? [x.ref] : [])),
busy: items.some((x) => !x.ref && !x.error),
};
}
export type Attachments = ReturnType<typeof useAttachments>;
export function ImageAttachments({ attachments, disabled = false }: { attachments: Attachments; disabled?: boolean }) {
const t = useT();
const input = useRef<HTMLInputElement>(null);
const { items } = attachments;
return (
<div className="space-y-2">
<input
ref={input}
type="file"
accept="image/jpeg,image/png"
multiple
className="sr-only"
aria-label={t("MsgAttachImagesInput")}
tabIndex={-1}
onChange={(e) => {
const files = Array.from(e.target.files ?? []);
e.target.value = "";
void attachments.add(files);
}}
/>
<Button type="button" variant="outline" size="sm" disabled={disabled || items.filter((x) => !x.error).length >= MAX_IMAGES} onClick={() => input.current?.click()}>
<ImagePlus aria-hidden="true" className="size-4" />
{t("MsgAttachImages", { max: MAX_IMAGES })}
</Button>
{items.length > 0 && (
<ul className="flex flex-wrap gap-2">
{items.map((x) => (
<li key={x.id} className="flex items-center gap-2 rounded-md border px-2 py-1 text-xs">
<span>{x.name}</span>
{x.error ? (
<span role="alert" className="text-destructive">{x.error}</span>
) : !x.ref ? (
<span className="text-muted-foreground">{t("MsgImageUploading")}</span>
) : null}
<button type="button" aria-label={t("MsgRemoveImage", { name: x.name })} disabled={disabled} onClick={() => attachments.remove(x.id)}>
<X aria-hidden="true" className="size-3" />
</button>
</li>
))}
</ul>
)}
</div>
);
}