mirror of
https://github.com/chillpadclub/bedolaga-cabinet.git
synced 2026-07-28 09:33:46 +00:00
feat: multi-media attachments, linkify URLs, shared MessageMediaGrid
- Add media_items array support to ticket messages (types, API clients) - Create shared MessageMediaGrid component with photo grid, fullscreen viewer, keyboard nav, video/document rendering - Replace per-page AdminMessageMedia/MessageMedia with MessageMediaGrid - Add linkifyText util (DOMPurify-sanitized) for auto-linking URLs - Support multi-file upload (up to 10) in AdminTickets and Support pages - Remove unused ticketsApi import from AdminUserDetail
This commit is contained in:
@@ -8,6 +8,12 @@ export interface AdminTicketUser {
|
||||
last_name: string | null;
|
||||
}
|
||||
|
||||
export interface AdminTicketMediaItem {
|
||||
type: 'photo' | 'video' | 'document';
|
||||
file_id: string;
|
||||
caption?: string | null;
|
||||
}
|
||||
|
||||
export interface AdminTicketMessage {
|
||||
id: number;
|
||||
message_text: string;
|
||||
@@ -16,6 +22,7 @@ export interface AdminTicketMessage {
|
||||
media_type: string | null;
|
||||
media_file_id: string | null;
|
||||
media_caption: string | null;
|
||||
media_items?: AdminTicketMediaItem[] | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
@@ -118,7 +125,12 @@ export const adminApi = {
|
||||
replyToTicket: async (
|
||||
ticketId: number,
|
||||
message: string,
|
||||
media?: { media_type?: string; media_file_id?: string; media_caption?: string },
|
||||
media?: {
|
||||
media_type?: string;
|
||||
media_file_id?: string;
|
||||
media_caption?: string;
|
||||
media_items?: AdminTicketMediaItem[];
|
||||
},
|
||||
): Promise<AdminTicketMessage> => {
|
||||
const response = await apiClient.post(`/cabinet/admin/tickets/${ticketId}/reply`, {
|
||||
message,
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
import apiClient from './client';
|
||||
import type { Ticket, TicketDetail, TicketMessage, PaginatedResponse } from '../types';
|
||||
import type {
|
||||
Ticket,
|
||||
TicketDetail,
|
||||
TicketMessage,
|
||||
TicketMediaItem,
|
||||
PaginatedResponse,
|
||||
} from '../types';
|
||||
|
||||
// Media upload response type
|
||||
interface MediaUploadResponse {
|
||||
@@ -14,6 +20,7 @@ interface MediaParams {
|
||||
media_type?: string;
|
||||
media_file_id?: string;
|
||||
media_caption?: string;
|
||||
media_items?: TicketMediaItem[];
|
||||
}
|
||||
|
||||
export const ticketsApi = {
|
||||
|
||||
256
src/components/tickets/MessageMediaGrid.tsx
Normal file
256
src/components/tickets/MessageMediaGrid.tsx
Normal file
@@ -0,0 +1,256 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
import { createPortal } from 'react-dom';
|
||||
import { ticketsApi } from '../../api/tickets';
|
||||
|
||||
export interface MediaItem {
|
||||
type: string;
|
||||
file_id: string;
|
||||
caption?: string | null;
|
||||
}
|
||||
|
||||
interface MessageLike {
|
||||
has_media?: boolean;
|
||||
media_type?: string | null;
|
||||
media_file_id?: string | null;
|
||||
media_caption?: string | null;
|
||||
media_items?: MediaItem[] | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize message media into a unified list.
|
||||
* If media_items is present, use it. Otherwise fall back to legacy single-media fields.
|
||||
*/
|
||||
function getItems(message: MessageLike): MediaItem[] {
|
||||
if (message.media_items && message.media_items.length > 0) {
|
||||
return message.media_items;
|
||||
}
|
||||
if (message.media_file_id && message.media_type) {
|
||||
return [
|
||||
{
|
||||
type: message.media_type,
|
||||
file_id: message.media_file_id,
|
||||
caption: message.media_caption,
|
||||
},
|
||||
];
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
export function MessageMediaGrid({
|
||||
message,
|
||||
translateError = 'Failed to load image',
|
||||
}: {
|
||||
message: MessageLike;
|
||||
translateError?: string;
|
||||
}) {
|
||||
const items = getItems(message);
|
||||
const photoItems = items.filter((i) => i.type === 'photo');
|
||||
const otherItems = items.filter((i) => i.type !== 'photo');
|
||||
|
||||
const [fullscreenIndex, setFullscreenIndex] = useState<number | null>(null);
|
||||
|
||||
const openFullscreen = useCallback((idx: number) => setFullscreenIndex(idx), []);
|
||||
const closeFullscreen = useCallback(() => setFullscreenIndex(null), []);
|
||||
|
||||
// Escape + arrow keys for fullscreen nav
|
||||
useEffect(() => {
|
||||
if (fullscreenIndex === null) return;
|
||||
const onKey = (e: KeyboardEvent) => {
|
||||
if (e.key === 'Escape') setFullscreenIndex(null);
|
||||
else if (e.key === 'ArrowLeft' && fullscreenIndex > 0)
|
||||
setFullscreenIndex(fullscreenIndex - 1);
|
||||
else if (e.key === 'ArrowRight' && fullscreenIndex < photoItems.length - 1)
|
||||
setFullscreenIndex(fullscreenIndex + 1);
|
||||
};
|
||||
window.addEventListener('keydown', onKey);
|
||||
return () => window.removeEventListener('keydown', onKey);
|
||||
}, [fullscreenIndex, photoItems.length]);
|
||||
|
||||
// Lock body scroll while fullscreen overlay is open (mobile mainly).
|
||||
useEffect(() => {
|
||||
if (fullscreenIndex === null) return undefined;
|
||||
const prev = document.body.style.overflow;
|
||||
document.body.style.overflow = 'hidden';
|
||||
return () => {
|
||||
document.body.style.overflow = prev;
|
||||
};
|
||||
}, [fullscreenIndex]);
|
||||
|
||||
// All hooks have been called — safe to early-return now.
|
||||
if (items.length === 0) return null;
|
||||
|
||||
// Grid layout based on photo count
|
||||
let gridClass = '';
|
||||
if (photoItems.length === 1) {
|
||||
gridClass = 'grid-cols-1';
|
||||
} else if (photoItems.length === 2) {
|
||||
gridClass = 'grid-cols-2';
|
||||
} else if (photoItems.length === 3) {
|
||||
gridClass = 'grid-cols-3';
|
||||
} else {
|
||||
gridClass = 'grid-cols-2'; // 4+ → 2x2
|
||||
}
|
||||
|
||||
const visiblePhotos = photoItems.slice(0, 4);
|
||||
const hiddenCount = photoItems.length - visiblePhotos.length;
|
||||
|
||||
return (
|
||||
<div className="mt-3 space-y-2">
|
||||
{photoItems.length > 0 && (
|
||||
<div className={`grid gap-1 ${gridClass}`}>
|
||||
{visiblePhotos.map((item, visIdx) => {
|
||||
// visIdx is always the correct index into photoItems (visible prefix)
|
||||
const originalIdx = visIdx;
|
||||
const isLastVisible = visIdx === visiblePhotos.length - 1 && hiddenCount > 0;
|
||||
return (
|
||||
<button
|
||||
key={`${item.file_id}-${visIdx}`}
|
||||
type="button"
|
||||
className="group relative aspect-square overflow-hidden rounded-lg bg-dark-800"
|
||||
onClick={() => openFullscreen(originalIdx)}
|
||||
>
|
||||
<img
|
||||
src={ticketsApi.getMediaUrl(item.file_id)}
|
||||
alt={item.caption || 'Attached photo'}
|
||||
className="h-full w-full object-cover transition-opacity group-hover:opacity-90"
|
||||
loading="lazy"
|
||||
/>
|
||||
{isLastVisible && (
|
||||
<div className="pointer-events-none absolute inset-0 flex items-center justify-center bg-black/60 text-2xl font-semibold text-white">
|
||||
+{hiddenCount}
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Non-photo media rendered inline */}
|
||||
{otherItems.map((item) => {
|
||||
const mediaUrl = ticketsApi.getMediaUrl(item.file_id);
|
||||
if (item.type === 'video') {
|
||||
return (
|
||||
<div key={item.file_id}>
|
||||
<video
|
||||
src={mediaUrl}
|
||||
controls
|
||||
className="max-h-64 max-w-full rounded-lg"
|
||||
preload="metadata"
|
||||
/>
|
||||
{item.caption && <p className="mt-1 text-xs text-dark-400">{item.caption}</p>}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
return (
|
||||
<a
|
||||
key={item.file_id}
|
||||
href={mediaUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-dark-700 px-3 py-2 text-sm text-dark-200 transition-colors hover:bg-dark-600"
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"
|
||||
/>
|
||||
</svg>
|
||||
{item.caption || `Download ${item.type}`}
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
|
||||
{fullscreenIndex !== null &&
|
||||
photoItems[fullscreenIndex] &&
|
||||
createPortal(
|
||||
<div
|
||||
className="fixed inset-0 z-[9999] bg-black"
|
||||
style={{ touchAction: 'pan-x pan-y pinch-zoom' }}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
className="absolute right-4 top-4 z-10 flex h-12 w-12 items-center justify-center rounded-full bg-white text-black shadow-xl transition-colors hover:bg-gray-200"
|
||||
onClick={closeFullscreen}
|
||||
>
|
||||
<svg
|
||||
className="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{photoItems.length > 1 && (
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
disabled={fullscreenIndex === 0}
|
||||
onClick={() => setFullscreenIndex(fullscreenIndex - 1)}
|
||||
className="absolute left-4 top-1/2 z-10 flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full bg-white/90 text-black shadow-xl transition-colors hover:bg-white disabled:opacity-30"
|
||||
>
|
||||
<svg
|
||||
className="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M15 19l-7-7 7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
disabled={fullscreenIndex >= photoItems.length - 1}
|
||||
onClick={() => setFullscreenIndex(fullscreenIndex + 1)}
|
||||
className="absolute right-4 top-1/2 z-10 flex h-12 w-12 -translate-y-1/2 items-center justify-center rounded-full bg-white/90 text-black shadow-xl transition-colors hover:bg-white disabled:opacity-30"
|
||||
>
|
||||
<svg
|
||||
className="h-5 w-5"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M9 5l7 7-7 7" />
|
||||
</svg>
|
||||
</button>
|
||||
<div className="absolute bottom-6 left-1/2 z-10 -translate-x-1/2 rounded-full bg-black/70 px-3 py-1 text-sm text-white">
|
||||
{fullscreenIndex + 1} / {photoItems.length}
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
<div
|
||||
className="flex h-full w-full items-center justify-center overflow-auto"
|
||||
onClick={closeFullscreen}
|
||||
>
|
||||
<img
|
||||
src={ticketsApi.getMediaUrl(photoItems[fullscreenIndex].file_id)}
|
||||
alt={photoItems[fullscreenIndex].caption || 'Attached photo'}
|
||||
className="max-h-full max-w-full object-contain"
|
||||
style={{ touchAction: 'pinch-zoom' }}
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
/>
|
||||
</div>
|
||||
</div>,
|
||||
document.body,
|
||||
)}
|
||||
|
||||
{/* Fallback: error state */}
|
||||
{photoItems.length === 0 && otherItems.length === 0 && (
|
||||
<div className="text-xs text-dark-400">{translateError}</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,12 +1,16 @@
|
||||
import { useState, useRef, useEffect } from 'react';
|
||||
import logger from '../utils/logger';
|
||||
import { linkifyText } from '../utils/linkify';
|
||||
import { MessageMediaGrid } from '../components/tickets/MessageMediaGrid';
|
||||
import { useNavigate } from 'react-router';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { adminApi, AdminTicket, AdminTicketDetail, AdminTicketMessage } from '../api/admin';
|
||||
import { adminApi, AdminTicket, AdminTicketDetail } from '../api/admin';
|
||||
import { ticketsApi } from '../api/tickets';
|
||||
import { usePlatform } from '../platform/hooks/usePlatform';
|
||||
|
||||
interface MediaAttachment {
|
||||
id: string;
|
||||
file: File;
|
||||
preview: string;
|
||||
uploading: boolean;
|
||||
@@ -34,123 +38,6 @@ const ALLOWED_FILE_TYPES: Record<string, string> = {
|
||||
const ACCEPT_STRING = Object.keys(ALLOWED_FILE_TYPES).join(',');
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024; // 10MB
|
||||
|
||||
function AdminMessageMedia({
|
||||
message,
|
||||
t,
|
||||
}: {
|
||||
message: AdminTicketMessage;
|
||||
t: (key: string) => string;
|
||||
}) {
|
||||
const [imageLoaded, setImageLoaded] = useState(false);
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const [showFullImage, setShowFullImage] = useState(false);
|
||||
|
||||
if (!message.has_media || !message.media_file_id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const mediaUrl = ticketsApi.getMediaUrl(message.media_file_id);
|
||||
|
||||
if (message.media_type === 'photo') {
|
||||
return (
|
||||
<div className="mt-3">
|
||||
{!imageLoaded && !imageError && (
|
||||
<div className="flex h-40 w-full animate-pulse items-center justify-center rounded-lg bg-dark-800">
|
||||
<div className="h-6 w-6 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
|
||||
</div>
|
||||
)}
|
||||
{imageError ? (
|
||||
<div className="flex h-32 w-full items-center justify-center rounded-lg bg-dark-800 text-sm text-dark-400">
|
||||
{t('support.imageLoadFailed')}
|
||||
</div>
|
||||
) : (
|
||||
<img
|
||||
src={mediaUrl}
|
||||
alt={message.media_caption || 'Attached image'}
|
||||
className={`max-h-64 max-w-full cursor-pointer rounded-lg transition-opacity hover:opacity-90 ${
|
||||
imageLoaded ? '' : 'hidden'
|
||||
}`}
|
||||
onLoad={() => setImageLoaded(true)}
|
||||
onError={() => setImageError(true)}
|
||||
onClick={() => setShowFullImage(true)}
|
||||
/>
|
||||
)}
|
||||
{message.media_caption && (
|
||||
<p className="mt-1 text-xs text-dark-400">{message.media_caption}</p>
|
||||
)}
|
||||
{showFullImage && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 p-4"
|
||||
onClick={() => setShowFullImage(false)}
|
||||
>
|
||||
<button
|
||||
className="absolute right-4 top-4 text-white/70 hover:text-white"
|
||||
onClick={() => setShowFullImage(false)}
|
||||
>
|
||||
<svg
|
||||
className="h-6 w-6"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" d="M6 18L18 6M6 6l12 12" />
|
||||
</svg>
|
||||
</button>
|
||||
<img
|
||||
src={mediaUrl}
|
||||
alt={message.media_caption || 'Attached image'}
|
||||
className="max-h-full max-w-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (message.media_type === 'video') {
|
||||
return (
|
||||
<div className="mt-3">
|
||||
<video
|
||||
src={mediaUrl}
|
||||
controls
|
||||
className="max-h-64 max-w-full rounded-lg"
|
||||
preload="metadata"
|
||||
/>
|
||||
{message.media_caption && (
|
||||
<p className="mt-1 text-xs text-dark-400">{message.media_caption}</p>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mt-3">
|
||||
<a
|
||||
href={mediaUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-dark-700 px-3 py-2 text-sm text-dark-200 transition-colors hover:bg-dark-600"
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"
|
||||
/>
|
||||
</svg>
|
||||
{message.media_caption || `Download ${message.media_type}`}
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// BackIcon
|
||||
const BackIcon = () => (
|
||||
<svg
|
||||
@@ -173,21 +60,22 @@ export default function AdminTickets() {
|
||||
const [selectedTicketId, setSelectedTicketId] = useState<number | null>(null);
|
||||
const [statusFilter, setStatusFilter] = useState<string>('');
|
||||
const [replyText, setReplyText] = useState('');
|
||||
const [isReplying, setIsReplying] = useState(false);
|
||||
const [replyError, setReplyError] = useState<string | null>(null);
|
||||
const [page, setPage] = useState(1);
|
||||
const [attachment, setAttachment] = useState<MediaAttachment | null>(null);
|
||||
const [attachments, setAttachments] = useState<MediaAttachment[]>([]);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const previewRef = useRef<string | null>(null);
|
||||
const uploadIdRef = useRef(0);
|
||||
|
||||
// Cancel in-flight uploads and cleanup blob URL on unmount
|
||||
// Track all created blob URLs for cleanup on unmount
|
||||
const blobUrlsRef = useRef<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
const uploadRef = uploadIdRef;
|
||||
const prevRef = previewRef;
|
||||
const urls = blobUrlsRef;
|
||||
return () => {
|
||||
uploadRef.current++;
|
||||
if (prevRef.current) {
|
||||
URL.revokeObjectURL(prevRef.current);
|
||||
}
|
||||
urls.current.forEach((u) => URL.revokeObjectURL(u));
|
||||
};
|
||||
}, []);
|
||||
|
||||
@@ -212,25 +100,6 @@ export default function AdminTickets() {
|
||||
enabled: !!selectedTicketId,
|
||||
});
|
||||
|
||||
const replyMutation = useMutation({
|
||||
mutationFn: ({
|
||||
ticketId,
|
||||
message,
|
||||
media,
|
||||
}: {
|
||||
ticketId: number;
|
||||
message: string;
|
||||
media?: { media_type?: string; media_file_id?: string; media_caption?: string };
|
||||
}) => adminApi.replyToTicket(ticketId, message, media),
|
||||
onSuccess: () => {
|
||||
setReplyText('');
|
||||
clearAttachment();
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-ticket', selectedTicketId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-tickets'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-ticket-stats'] });
|
||||
},
|
||||
});
|
||||
|
||||
const statusMutation = useMutation({
|
||||
mutationFn: ({ ticketId, status }: { ticketId: number; status: string }) =>
|
||||
adminApi.updateTicketStatus(ticketId, status),
|
||||
@@ -241,84 +110,116 @@ export default function AdminTickets() {
|
||||
},
|
||||
});
|
||||
|
||||
const clearAttachment = () => {
|
||||
const clearAttachments = () => {
|
||||
uploadIdRef.current++;
|
||||
if (previewRef.current) {
|
||||
URL.revokeObjectURL(previewRef.current);
|
||||
previewRef.current = null;
|
||||
}
|
||||
setAttachment(null);
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = '';
|
||||
}
|
||||
setAttachments((prev) => {
|
||||
prev.forEach((a) => {
|
||||
if (a.preview) {
|
||||
URL.revokeObjectURL(a.preview);
|
||||
blobUrlsRef.current.delete(a.preview);
|
||||
}
|
||||
});
|
||||
return [];
|
||||
});
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
};
|
||||
|
||||
const removeAttachment = (idx: number) => {
|
||||
setAttachments((prev) => {
|
||||
const removed = prev[idx];
|
||||
if (removed?.preview) URL.revokeObjectURL(removed.preview);
|
||||
return prev.filter((_, i) => i !== idx);
|
||||
});
|
||||
};
|
||||
|
||||
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (!file) return;
|
||||
const files = Array.from(e.target.files || []);
|
||||
if (!files.length) return;
|
||||
if (fileInputRef.current) fileInputRef.current.value = '';
|
||||
|
||||
// Revoke any existing blob URL before processing new file
|
||||
if (previewRef.current) {
|
||||
URL.revokeObjectURL(previewRef.current);
|
||||
previewRef.current = null;
|
||||
}
|
||||
const remaining = 10 - attachments.length;
|
||||
const toAdd = files.slice(0, remaining);
|
||||
|
||||
const mediaType = ALLOWED_FILE_TYPES[file.type];
|
||||
if (!mediaType) {
|
||||
setAttachment({
|
||||
file,
|
||||
preview: '',
|
||||
uploading: false,
|
||||
mediaType: 'document',
|
||||
error: t('admin.tickets.invalidFileType'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
for (const file of toAdd) {
|
||||
const mediaType = ALLOWED_FILE_TYPES[file.type];
|
||||
if (!mediaType) continue;
|
||||
if (file.size > MAX_FILE_SIZE) continue;
|
||||
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
setAttachment({
|
||||
file,
|
||||
preview: '',
|
||||
uploading: false,
|
||||
mediaType,
|
||||
error: t('admin.tickets.fileTooLarge'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const preview = mediaType === 'photo' ? URL.createObjectURL(file) : '';
|
||||
if (preview) blobUrlsRef.current.add(preview);
|
||||
const id =
|
||||
typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
|
||||
? crypto.randomUUID()
|
||||
: `att_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
||||
const entry: MediaAttachment = { id, file, preview, uploading: true, mediaType };
|
||||
const uploadToken = uploadIdRef.current;
|
||||
|
||||
const preview = mediaType === 'photo' ? URL.createObjectURL(file) : '';
|
||||
previewRef.current = preview;
|
||||
setAttachments((prev) => [...prev, entry]);
|
||||
|
||||
const currentUploadId = ++uploadIdRef.current;
|
||||
setAttachment({ file, preview, uploading: true, mediaType });
|
||||
|
||||
try {
|
||||
const result = await ticketsApi.uploadMedia(file, mediaType);
|
||||
if (uploadIdRef.current !== currentUploadId) return; // stale upload
|
||||
setAttachment((prev) =>
|
||||
prev ? { ...prev, uploading: false, fileId: result.file_id } : null,
|
||||
);
|
||||
} catch {
|
||||
if (uploadIdRef.current !== currentUploadId) return; // stale upload
|
||||
setAttachment((prev) =>
|
||||
prev ? { ...prev, uploading: false, error: t('admin.tickets.uploadFailed') } : null,
|
||||
);
|
||||
// Upload in background; ignore the result if user cleared/unmounted in the meantime.
|
||||
(async () => {
|
||||
try {
|
||||
const result = await ticketsApi.uploadMedia(file, mediaType);
|
||||
if (uploadIdRef.current !== uploadToken) return;
|
||||
setAttachments((prev) =>
|
||||
prev.map((a) => (a.id === id ? { ...a, uploading: false, fileId: result.file_id } : a)),
|
||||
);
|
||||
} catch {
|
||||
if (uploadIdRef.current !== uploadToken) return;
|
||||
setAttachments((prev) =>
|
||||
prev.map((a) =>
|
||||
a.id === id ? { ...a, uploading: false, error: t('admin.tickets.uploadFailed') } : a,
|
||||
),
|
||||
);
|
||||
}
|
||||
})();
|
||||
}
|
||||
};
|
||||
|
||||
const handleReply = (e: React.FormEvent) => {
|
||||
const handleReply = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!selectedTicketId || !replyText.trim()) return;
|
||||
if (attachment && (attachment.uploading || attachment.error)) return;
|
||||
if (!selectedTicketId) return;
|
||||
if (attachments.some((a) => a.uploading || a.error)) return;
|
||||
|
||||
const media = attachment?.fileId
|
||||
const readyAttachments = attachments.filter((a) => a.fileId) as Array<{
|
||||
fileId: string;
|
||||
mediaType: string;
|
||||
}>;
|
||||
|
||||
const hasText = replyText.trim().length > 0;
|
||||
const hasMedia = readyAttachments.length > 0;
|
||||
if (!hasText && !hasMedia) return;
|
||||
|
||||
const media = hasMedia
|
||||
? {
|
||||
media_type: attachment.mediaType,
|
||||
media_file_id: attachment.fileId,
|
||||
media_type: readyAttachments[0].mediaType,
|
||||
media_file_id: readyAttachments[0].fileId,
|
||||
media_items: readyAttachments.map((a) => ({
|
||||
type: a.mediaType as 'photo' | 'video' | 'document',
|
||||
file_id: a.fileId,
|
||||
})),
|
||||
}
|
||||
: undefined;
|
||||
|
||||
replyMutation.mutate({ ticketId: selectedTicketId, message: replyText, media });
|
||||
setIsReplying(true);
|
||||
setReplyError(null);
|
||||
try {
|
||||
await adminApi.replyToTicket(selectedTicketId, replyText, media);
|
||||
} catch (err) {
|
||||
logger.error('Ticket reply failed:', err);
|
||||
const msg =
|
||||
err instanceof Error ? err.message : t('admin.tickets.replyFailed', 'Failed to send reply');
|
||||
setReplyError(msg);
|
||||
setIsReplying(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setReplyText('');
|
||||
clearAttachments();
|
||||
setIsReplying(false);
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-ticket', selectedTicketId] });
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-tickets'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['admin-ticket-stats'] });
|
||||
};
|
||||
|
||||
const getStatusBadge = (status: string) => {
|
||||
@@ -470,7 +371,7 @@ export default function AdminTickets() {
|
||||
onClick={() => {
|
||||
setSelectedTicketId(ticket.id);
|
||||
setReplyText('');
|
||||
clearAttachment();
|
||||
clearAttachments();
|
||||
}}
|
||||
className={`w-full rounded-xl border p-4 text-left transition-all ${
|
||||
selectedTicketId === ticket.id
|
||||
@@ -657,9 +558,12 @@ export default function AdminTickets() {
|
||||
</span>
|
||||
</div>
|
||||
{msg.message_text && (
|
||||
<p className="whitespace-pre-wrap text-dark-200">{msg.message_text}</p>
|
||||
<p
|
||||
className="whitespace-pre-wrap text-dark-200 [&_a]:text-accent-400 [&_a]:underline"
|
||||
dangerouslySetInnerHTML={{ __html: linkifyText(msg.message_text) }}
|
||||
/>
|
||||
)}
|
||||
<AdminMessageMedia message={msg} t={t} />
|
||||
<MessageMediaGrid message={msg} translateError={t('support.imageLoadFailed')} />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -675,76 +579,53 @@ export default function AdminTickets() {
|
||||
className="input resize-none"
|
||||
/>
|
||||
|
||||
{/* Attachment preview */}
|
||||
{attachment && (
|
||||
<div className="mt-2 flex items-center gap-3 rounded-lg border border-dark-700/50 bg-dark-800/50 p-2">
|
||||
{attachment.mediaType === 'photo' && attachment.preview ? (
|
||||
<img
|
||||
src={attachment.preview}
|
||||
alt="Preview"
|
||||
className="h-12 w-12 rounded-lg object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-12 w-12 items-center justify-center rounded-lg bg-dark-700">
|
||||
<svg
|
||||
className="h-6 w-6 text-dark-400"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={1.5}
|
||||
{/* Attachments preview */}
|
||||
{attachments.length > 0 && (
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{attachments.map((att, idx) => (
|
||||
<div key={att.id} className="relative">
|
||||
{att.mediaType === 'photo' && att.preview ? (
|
||||
<img
|
||||
src={att.preview}
|
||||
alt="Preview"
|
||||
className="h-16 w-16 rounded-lg object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-lg bg-dark-700 text-xs text-dark-400">
|
||||
{att.file.name.slice(-6)}
|
||||
</div>
|
||||
)}
|
||||
{att.uploading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center rounded-lg bg-black/50">
|
||||
<span className="h-4 w-4 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
|
||||
</div>
|
||||
)}
|
||||
{att.error && (
|
||||
<div className="absolute inset-0 flex items-center justify-center rounded-lg bg-red-500/30">
|
||||
<span className="text-xs text-red-300">!</span>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => removeAttachment(idx)}
|
||||
className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-dark-600 text-dark-300 hover:bg-red-500 hover:text-white"
|
||||
>
|
||||
{attachment.mediaType === 'video' ? (
|
||||
<svg
|
||||
className="h-3 w-3"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={3}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="m15.75 10.5 4.72-4.72a.75.75 0 0 1 1.28.53v11.38a.75.75 0 0 1-1.28.53l-4.72-4.72M4.5 18.75h9a2.25 2.25 0 0 0 2.25-2.25v-9a2.25 2.25 0 0 0-2.25-2.25h-9A2.25 2.25 0 0 0 2.25 7.5v9a2.25 2.25 0 0 0 2.25 2.25Z"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
) : (
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M19.5 14.25v-2.625a3.375 3.375 0 0 0-3.375-3.375h-1.5A1.125 1.125 0 0 1 13.5 7.125v-1.5a3.375 3.375 0 0 0-3.375-3.375H8.25m2.25 0H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 0 0-9-9Z"
|
||||
/>
|
||||
)}
|
||||
</svg>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
<div className="min-w-0 flex-1">
|
||||
<div className="truncate text-sm text-dark-200">{attachment.file.name}</div>
|
||||
{attachment.uploading && (
|
||||
<div className="flex items-center gap-1.5 text-xs text-accent-400">
|
||||
<span className="h-3 w-3 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
|
||||
{t('admin.tickets.uploading')}
|
||||
</div>
|
||||
)}
|
||||
{attachment.error && (
|
||||
<div className="text-xs text-red-400">{attachment.error}</div>
|
||||
)}
|
||||
{attachment.fileId && !attachment.uploading && (
|
||||
<div className="text-xs text-success-400">
|
||||
{t('admin.tickets.uploadComplete')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
onClick={clearAttachment}
|
||||
className="shrink-0 rounded-lg p-1 text-dark-500 transition-colors hover:bg-dark-700 hover:text-dark-200"
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M6 18L18 6M6 6l12 12"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
@@ -752,15 +633,22 @@ export default function AdminTickets() {
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
accept={ACCEPT_STRING}
|
||||
multiple
|
||||
onChange={handleFileSelect}
|
||||
className="hidden"
|
||||
/>
|
||||
|
||||
{replyError && (
|
||||
<div className="mt-2 rounded-lg border border-red-500/30 bg-red-500/10 px-3 py-2 text-sm text-red-300">
|
||||
{replyError}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="mt-3 flex items-center justify-between">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => fileInputRef.current?.click()}
|
||||
disabled={!!attachment?.uploading}
|
||||
disabled={attachments.length >= 10 || attachments.some((a) => a.uploading)}
|
||||
className="flex items-center gap-2 rounded-lg border border-dark-700/50 px-3 py-2 text-sm text-dark-400 transition-colors hover:border-dark-600 hover:text-dark-200 disabled:opacity-50"
|
||||
>
|
||||
<svg
|
||||
@@ -776,19 +664,19 @@ export default function AdminTickets() {
|
||||
d="m18.375 12.739-7.693 7.693a4.5 4.5 0 0 1-6.364-6.364l10.94-10.94A3 3 0 1 1 19.5 7.372L8.552 18.32m.009-.01-.01.01m5.699-9.941-7.81 7.81a1.5 1.5 0 0 0 2.112 2.13"
|
||||
/>
|
||||
</svg>
|
||||
{t('admin.tickets.attachMedia')}
|
||||
{t('admin.tickets.attachMedia')}{' '}
|
||||
{attachments.length > 0 && `(${attachments.length}/10)`}
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={
|
||||
!replyText.trim() ||
|
||||
replyMutation.isPending ||
|
||||
!!attachment?.uploading ||
|
||||
!!attachment?.error
|
||||
(!replyText.trim() && attachments.filter((a) => a.fileId).length === 0) ||
|
||||
isReplying ||
|
||||
attachments.some((a) => a.uploading || a.error)
|
||||
}
|
||||
className="btn-primary"
|
||||
>
|
||||
{replyMutation.isPending ? (
|
||||
{isReplying ? (
|
||||
<span className="flex items-center gap-2">
|
||||
<span className="h-4 w-4 animate-spin rounded-full border-2 border-white/30 border-t-white" />
|
||||
{t('common.loading')}
|
||||
|
||||
@@ -19,10 +19,11 @@ import {
|
||||
import { adminApi, type AdminTicket, type AdminTicketDetail } from '../api/admin';
|
||||
import { promocodesApi, type PromoGroup } from '../api/promocodes';
|
||||
import { promoOffersApi } from '../api/promoOffers';
|
||||
import { ticketsApi } from '../api/tickets';
|
||||
import { AdminBackButton } from '../components/admin';
|
||||
import { createNumberInputHandler, toNumber } from '../utils/inputHelpers';
|
||||
import { usePermissionStore } from '../store/permissions';
|
||||
import { MessageMediaGrid } from '../components/tickets/MessageMediaGrid';
|
||||
import { linkifyText } from '../utils/linkify';
|
||||
|
||||
// ============ Helpers ============
|
||||
|
||||
@@ -3092,32 +3093,13 @@ export default function AdminUserDetail() {
|
||||
{formatDate(msg.created_at)}
|
||||
</span>
|
||||
</div>
|
||||
<p className="whitespace-pre-wrap text-sm text-dark-200">
|
||||
{msg.message_text}
|
||||
</p>
|
||||
{msg.has_media && msg.media_file_id && (
|
||||
<div className="mt-2">
|
||||
{msg.media_type === 'photo' ? (
|
||||
<img
|
||||
src={ticketsApi.getMediaUrl(msg.media_file_id)}
|
||||
alt={msg.media_caption || ''}
|
||||
className="max-h-48 max-w-full rounded-lg"
|
||||
/>
|
||||
) : (
|
||||
<a
|
||||
href={ticketsApi.getMediaUrl(msg.media_file_id)}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-1 rounded-lg bg-dark-700 px-2 py-1 text-xs text-dark-200 hover:bg-dark-600"
|
||||
>
|
||||
{msg.media_caption || msg.media_type}
|
||||
</a>
|
||||
)}
|
||||
{msg.media_caption && msg.media_type === 'photo' && (
|
||||
<p className="mt-1 text-xs text-dark-400">{msg.media_caption}</p>
|
||||
)}
|
||||
</div>
|
||||
{msg.message_text && (
|
||||
<p
|
||||
className="whitespace-pre-wrap text-sm text-dark-200 [&_a]:text-accent-400 [&_a]:underline"
|
||||
dangerouslySetInnerHTML={{ __html: linkifyText(msg.message_text) }}
|
||||
/>
|
||||
)}
|
||||
<MessageMediaGrid message={msg} />
|
||||
</div>
|
||||
))}
|
||||
<div ref={messagesEndRef} />
|
||||
|
||||
@@ -3,15 +3,17 @@ import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { motion } from 'framer-motion';
|
||||
import { ticketsApi } from '../api/tickets';
|
||||
import { MessageMediaGrid } from '../components/tickets/MessageMediaGrid';
|
||||
import { infoApi } from '../api/info';
|
||||
import { useAuthStore } from '../store/auth';
|
||||
import { logger } from '../utils/logger';
|
||||
import { checkRateLimit, getRateLimitResetTime, RATE_LIMIT_KEYS } from '../utils/rateLimit';
|
||||
import type { TicketDetail, TicketMessage } from '../types';
|
||||
import type { TicketDetail } from '../types';
|
||||
import { Card } from '@/components/data-display/Card';
|
||||
import { Button } from '@/components/primitives/Button';
|
||||
import { staggerContainer, staggerItem } from '@/components/motion/transitions';
|
||||
import { usePlatform } from '@/platform';
|
||||
import { linkifyText } from '../utils/linkify';
|
||||
|
||||
const log = logger.createLogger('Support');
|
||||
|
||||
@@ -49,6 +51,7 @@ const CloseIcon = () => (
|
||||
|
||||
// Media attachment state
|
||||
interface MediaAttachment {
|
||||
id: string;
|
||||
file: File;
|
||||
preview: string;
|
||||
uploading: boolean;
|
||||
@@ -56,97 +59,6 @@ interface MediaAttachment {
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// Message media display component
|
||||
function MessageMedia({ message, t }: { message: TicketMessage; t: (key: string) => string }) {
|
||||
const [imageLoaded, setImageLoaded] = useState(false);
|
||||
const [imageError, setImageError] = useState(false);
|
||||
const [showFullImage, setShowFullImage] = useState(false);
|
||||
|
||||
if (!message.has_media || !message.media_file_id) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const mediaUrl = ticketsApi.getMediaUrl(message.media_file_id);
|
||||
|
||||
if (message.media_type === 'photo') {
|
||||
return (
|
||||
<>
|
||||
<div className="relative mt-3">
|
||||
{!imageLoaded && !imageError && (
|
||||
<div className="flex h-48 w-full animate-pulse items-center justify-center rounded-lg bg-dark-700">
|
||||
<div className="h-6 w-6 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
|
||||
</div>
|
||||
)}
|
||||
{imageError ? (
|
||||
<div className="flex h-32 w-full items-center justify-center rounded-lg bg-dark-700 text-sm text-dark-400">
|
||||
{t('support.imageLoadFailed')}
|
||||
</div>
|
||||
) : (
|
||||
<img
|
||||
src={mediaUrl}
|
||||
alt={message.media_caption || 'Attached image'}
|
||||
className={`max-h-64 max-w-full cursor-pointer rounded-lg transition-opacity hover:opacity-90 ${imageLoaded ? '' : 'hidden'}`}
|
||||
onLoad={() => setImageLoaded(true)}
|
||||
onError={() => setImageError(true)}
|
||||
onClick={() => setShowFullImage(true)}
|
||||
/>
|
||||
)}
|
||||
{message.media_caption && (
|
||||
<p className="mt-1 text-xs text-dark-400">{message.media_caption}</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Full image modal */}
|
||||
{showFullImage && (
|
||||
<div
|
||||
className="fixed inset-0 z-50 flex items-center justify-center bg-black/90 p-4"
|
||||
onClick={() => setShowFullImage(false)}
|
||||
>
|
||||
<button
|
||||
className="absolute right-4 top-4 text-white/70 hover:text-white"
|
||||
onClick={() => setShowFullImage(false)}
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
<img
|
||||
src={mediaUrl}
|
||||
alt={message.media_caption || 'Attached image'}
|
||||
className="max-h-full max-w-full object-contain"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// For documents/videos - show download link
|
||||
return (
|
||||
<div className="mt-3">
|
||||
<a
|
||||
href={mediaUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 rounded-lg bg-dark-700 px-3 py-2 text-sm text-dark-200 transition-colors hover:bg-dark-600"
|
||||
>
|
||||
<svg
|
||||
className="h-4 w-4"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
strokeWidth={2}
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
d="M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m.75 12l3 3m0 0l3-3m-3 3v-6m-1.5-9H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"
|
||||
/>
|
||||
</svg>
|
||||
{message.media_caption || `Download ${message.media_type}`}
|
||||
</a>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Support() {
|
||||
log.debug('Component loaded');
|
||||
|
||||
@@ -161,38 +73,35 @@ export default function Support() {
|
||||
const [replyMessage, setReplyMessage] = useState('');
|
||||
const [rateLimitError, setRateLimitError] = useState<string | null>(null);
|
||||
|
||||
// Media attachment states
|
||||
const [createAttachment, setCreateAttachment] = useState<MediaAttachment | null>(null);
|
||||
const [replyAttachment, setReplyAttachment] = useState<MediaAttachment | null>(null);
|
||||
// Media attachment states (multi-upload, up to 10)
|
||||
const [createAttachments, setCreateAttachments] = useState<MediaAttachment[]>([]);
|
||||
const [replyAttachments, setReplyAttachments] = useState<MediaAttachment[]>([]);
|
||||
const createFileInputRef = useRef<HTMLInputElement>(null);
|
||||
const replyFileInputRef = useRef<HTMLInputElement>(null);
|
||||
const createPreviewRef = useRef<string | null>(null);
|
||||
const replyPreviewRef = useRef<string | null>(null);
|
||||
|
||||
// Revoke blob URLs on unmount to prevent memory leaks
|
||||
const blobUrlsRef = useRef<Set<string>>(new Set());
|
||||
|
||||
useEffect(() => {
|
||||
const createRef = createPreviewRef;
|
||||
const replyRef = replyPreviewRef;
|
||||
const urls = blobUrlsRef;
|
||||
return () => {
|
||||
if (createRef.current) URL.revokeObjectURL(createRef.current);
|
||||
if (replyRef.current) URL.revokeObjectURL(replyRef.current);
|
||||
urls.current.forEach((u) => URL.revokeObjectURL(u));
|
||||
};
|
||||
}, []);
|
||||
|
||||
const clearCreateAttachment = () => {
|
||||
if (createPreviewRef.current) {
|
||||
URL.revokeObjectURL(createPreviewRef.current);
|
||||
createPreviewRef.current = null;
|
||||
}
|
||||
clearCreateAttachment();
|
||||
const clearCreateAttachments = () => {
|
||||
createAttachments.forEach((a) => {
|
||||
if (a.preview) URL.revokeObjectURL(a.preview);
|
||||
});
|
||||
setCreateAttachments([]);
|
||||
if (createFileInputRef.current) createFileInputRef.current.value = '';
|
||||
};
|
||||
|
||||
const clearReplyAttachment = () => {
|
||||
if (replyPreviewRef.current) {
|
||||
URL.revokeObjectURL(replyPreviewRef.current);
|
||||
replyPreviewRef.current = null;
|
||||
}
|
||||
clearReplyAttachment();
|
||||
const clearReplyAttachments = () => {
|
||||
replyAttachments.forEach((a) => {
|
||||
if (a.preview) URL.revokeObjectURL(a.preview);
|
||||
});
|
||||
setReplyAttachments([]);
|
||||
if (replyFileInputRef.current) replyFileInputRef.current.value = '';
|
||||
};
|
||||
|
||||
// Get support configuration
|
||||
@@ -213,67 +122,49 @@ export default function Support() {
|
||||
enabled: !!selectedTicket,
|
||||
});
|
||||
|
||||
// Handle file selection
|
||||
// Handle file selection (multi-upload)
|
||||
const handleFileSelect = async (
|
||||
file: File,
|
||||
setAttachment: (a: MediaAttachment | null) => void,
|
||||
setAttachments: React.Dispatch<React.SetStateAction<MediaAttachment[]>>,
|
||||
) => {
|
||||
// Validate file type
|
||||
const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
|
||||
if (!allowedTypes.includes(file.type)) {
|
||||
setAttachment({
|
||||
file,
|
||||
preview: '',
|
||||
uploading: false,
|
||||
error: t('support.invalidFileType'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (!allowedTypes.includes(file.type)) return;
|
||||
if (file.size > 10 * 1024 * 1024) return;
|
||||
|
||||
// Validate file size (10MB)
|
||||
if (file.size > 10 * 1024 * 1024) {
|
||||
setAttachment({
|
||||
file,
|
||||
preview: '',
|
||||
uploading: false,
|
||||
error: t('support.fileTooLarge'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Revoke old blob URL before creating new one
|
||||
const previewRef = setAttachment === setCreateAttachment ? createPreviewRef : replyPreviewRef;
|
||||
if (previewRef.current) URL.revokeObjectURL(previewRef.current);
|
||||
const preview = URL.createObjectURL(file);
|
||||
previewRef.current = preview;
|
||||
setAttachment({ file, preview, uploading: true });
|
||||
blobUrlsRef.current.add(preview);
|
||||
const id =
|
||||
typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'
|
||||
? crypto.randomUUID()
|
||||
: `att_${Date.now()}_${Math.random().toString(36).slice(2)}`;
|
||||
const entry: MediaAttachment = { id, file, preview, uploading: true };
|
||||
setAttachments((prev) => (prev.length >= 10 ? prev : [...prev, entry]));
|
||||
|
||||
try {
|
||||
const result = await ticketsApi.uploadMedia(file, 'photo');
|
||||
setAttachment({
|
||||
file,
|
||||
preview,
|
||||
uploading: false,
|
||||
fileId: result.file_id,
|
||||
});
|
||||
setAttachments((prev) =>
|
||||
prev.map((a) => (a.id === id ? { ...a, uploading: false, fileId: result.file_id } : a)),
|
||||
);
|
||||
} catch {
|
||||
setAttachment({
|
||||
file,
|
||||
preview,
|
||||
uploading: false,
|
||||
error: t('support.uploadFailed'),
|
||||
});
|
||||
setAttachments((prev) =>
|
||||
prev.map((a) =>
|
||||
a.id === id ? { ...a, uploading: false, error: t('support.uploadFailed') } : a,
|
||||
),
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
const createMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const media = createAttachment?.fileId
|
||||
? {
|
||||
media_type: 'photo',
|
||||
media_file_id: createAttachment.fileId,
|
||||
}
|
||||
: undefined;
|
||||
const ready = createAttachments.filter((a) => a.fileId) as Array<{ fileId: string }>;
|
||||
const media =
|
||||
ready.length > 0
|
||||
? {
|
||||
media_type: 'photo',
|
||||
media_file_id: ready[0].fileId,
|
||||
media_items: ready.map((a) => ({ type: 'photo' as const, file_id: a.fileId })),
|
||||
}
|
||||
: undefined;
|
||||
return ticketsApi.createTicket(newTitle, newMessage, media);
|
||||
},
|
||||
onSuccess: (ticket) => {
|
||||
@@ -281,25 +172,28 @@ export default function Support() {
|
||||
setShowCreateForm(false);
|
||||
setNewTitle('');
|
||||
setNewMessage('');
|
||||
clearCreateAttachment();
|
||||
clearCreateAttachments();
|
||||
setSelectedTicket(ticket);
|
||||
},
|
||||
});
|
||||
|
||||
const replyMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
const media = replyAttachment?.fileId
|
||||
? {
|
||||
media_type: 'photo',
|
||||
media_file_id: replyAttachment.fileId,
|
||||
}
|
||||
: undefined;
|
||||
return ticketsApi.addMessage(selectedTicket!.id, replyMessage, media);
|
||||
const ready = replyAttachments.filter((a) => a.fileId) as Array<{ fileId: string }>;
|
||||
const media =
|
||||
ready.length > 0
|
||||
? {
|
||||
media_type: 'photo',
|
||||
media_file_id: ready[0].fileId,
|
||||
media_items: ready.map((a) => ({ type: 'photo' as const, file_id: a.fileId })),
|
||||
}
|
||||
: undefined;
|
||||
await ticketsApi.addMessage(selectedTicket!.id, replyMessage, media);
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ['ticket', selectedTicket?.id] });
|
||||
setReplyMessage('');
|
||||
clearReplyAttachment();
|
||||
clearReplyAttachments();
|
||||
},
|
||||
});
|
||||
|
||||
@@ -427,37 +321,50 @@ export default function Support() {
|
||||
);
|
||||
}
|
||||
|
||||
// Attachment preview component
|
||||
const AttachmentPreview = ({
|
||||
attachment,
|
||||
// Attachments preview component
|
||||
const AttachmentsPreview = ({
|
||||
items,
|
||||
onRemove,
|
||||
}: {
|
||||
attachment: MediaAttachment;
|
||||
onRemove: () => void;
|
||||
}) => (
|
||||
<div className="relative mt-2 inline-block">
|
||||
{attachment.preview && (
|
||||
<img
|
||||
src={attachment.preview}
|
||||
alt="Attachment preview"
|
||||
className="h-20 w-auto rounded-lg border border-dark-700"
|
||||
/>
|
||||
)}
|
||||
{attachment.uploading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center rounded-lg bg-dark-900/70">
|
||||
<div className="h-5 w-5 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
|
||||
</div>
|
||||
)}
|
||||
{attachment.error && <div className="mt-1 text-xs text-red-400">{attachment.error}</div>}
|
||||
<button
|
||||
type="button"
|
||||
onClick={onRemove}
|
||||
className="absolute -right-2 -top-2 flex h-5 w-5 items-center justify-center rounded-full bg-red-500 text-white hover:bg-red-600"
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
);
|
||||
items: MediaAttachment[];
|
||||
onRemove: (idx: number) => void;
|
||||
}) =>
|
||||
items.length === 0 ? null : (
|
||||
<div className="mt-2 flex flex-wrap gap-2">
|
||||
{items.map((att, idx) => (
|
||||
<div key={idx} className="relative">
|
||||
{att.preview ? (
|
||||
<img
|
||||
src={att.preview}
|
||||
alt="Preview"
|
||||
className="h-16 w-16 rounded-lg border border-dark-700 object-cover"
|
||||
/>
|
||||
) : (
|
||||
<div className="flex h-16 w-16 items-center justify-center rounded-lg bg-dark-700 text-xs text-dark-400">
|
||||
{att.file.name.slice(-6)}
|
||||
</div>
|
||||
)}
|
||||
{att.uploading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center rounded-lg bg-black/50">
|
||||
<span className="h-4 w-4 animate-spin rounded-full border-2 border-accent-500 border-t-transparent" />
|
||||
</div>
|
||||
)}
|
||||
{att.error && (
|
||||
<div className="absolute inset-0 flex items-center justify-center rounded-lg bg-red-500/30">
|
||||
<span className="text-xs text-red-300">!</span>
|
||||
</div>
|
||||
)}
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => onRemove(idx)}
|
||||
className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-dark-600 text-dark-300 hover:bg-red-500 hover:text-white"
|
||||
>
|
||||
<CloseIcon />
|
||||
</button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<motion.div
|
||||
@@ -475,7 +382,7 @@ export default function Support() {
|
||||
onClick={() => {
|
||||
setShowCreateForm(true);
|
||||
setSelectedTicket(null);
|
||||
clearCreateAttachment();
|
||||
clearCreateAttachments();
|
||||
}}
|
||||
>
|
||||
<PlusIcon />
|
||||
@@ -540,7 +447,7 @@ export default function Support() {
|
||||
onClick={() => {
|
||||
setSelectedTicket(ticket as unknown as TicketDetail);
|
||||
setShowCreateForm(false);
|
||||
clearReplyAttachment();
|
||||
clearReplyAttachments();
|
||||
}}
|
||||
className={`w-full rounded-bento border p-4 text-left transition-all ${
|
||||
selectedTicket?.id === ticket.id
|
||||
@@ -629,32 +536,40 @@ export default function Support() {
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Image attachment for create */}
|
||||
{/* Image attachments for create */}
|
||||
<div>
|
||||
<input
|
||||
ref={createFileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) handleFileSelect(file, setCreateAttachment);
|
||||
const files = Array.from(e.target.files || []);
|
||||
files.forEach((file) => handleFileSelect(file, setCreateAttachments));
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
{createAttachment ? (
|
||||
<AttachmentPreview
|
||||
attachment={createAttachment}
|
||||
onRemove={() => clearCreateAttachment()}
|
||||
/>
|
||||
) : (
|
||||
<AttachmentsPreview
|
||||
items={createAttachments}
|
||||
onRemove={(idx) =>
|
||||
setCreateAttachments((prev) => {
|
||||
const removed = prev[idx];
|
||||
if (removed?.preview) URL.revokeObjectURL(removed.preview);
|
||||
return prev.filter((_, i) => i !== idx);
|
||||
})
|
||||
}
|
||||
/>
|
||||
{createAttachments.length < 10 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => createFileInputRef.current?.click()}
|
||||
className="flex items-center gap-2 text-sm text-dark-400 transition-colors hover:text-dark-200"
|
||||
disabled={createAttachments.some((a) => a.uploading)}
|
||||
className="mt-2 flex items-center gap-2 text-sm text-dark-400 transition-colors hover:text-dark-200 disabled:opacity-50"
|
||||
>
|
||||
<ImageIcon />
|
||||
{t('support.attachImage')}
|
||||
{t('support.attachImage')}{' '}
|
||||
{createAttachments.length > 0 && `(${createAttachments.length}/10)`}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
@@ -668,7 +583,7 @@ export default function Support() {
|
||||
<div className="flex gap-3">
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={createAttachment?.uploading}
|
||||
disabled={createAttachments.some((a) => a.uploading)}
|
||||
loading={createMutation.isPending}
|
||||
>
|
||||
<SendIcon />
|
||||
@@ -679,7 +594,7 @@ export default function Support() {
|
||||
variant="secondary"
|
||||
onClick={() => {
|
||||
setShowCreateForm(false);
|
||||
clearCreateAttachment();
|
||||
clearCreateAttachments();
|
||||
}}
|
||||
>
|
||||
{t('common.cancel')}
|
||||
@@ -732,9 +647,17 @@ export default function Support() {
|
||||
{new Date(msg.created_at).toLocaleString()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="whitespace-pre-wrap text-dark-200">{msg.message_text}</div>
|
||||
{msg.message_text && (
|
||||
<div
|
||||
className="whitespace-pre-wrap text-dark-200 [&_a]:text-accent-400 [&_a]:underline"
|
||||
dangerouslySetInnerHTML={{ __html: linkifyText(msg.message_text) }}
|
||||
/>
|
||||
)}
|
||||
{/* Display media if present */}
|
||||
<MessageMedia message={msg} t={t} />
|
||||
<MessageMediaGrid
|
||||
message={msg}
|
||||
translateError={t('support.imageLoadFailed')}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
@@ -763,46 +686,56 @@ export default function Support() {
|
||||
placeholder={t('support.replyPlaceholder')}
|
||||
value={replyMessage}
|
||||
onChange={(e) => setReplyMessage(e.target.value)}
|
||||
required
|
||||
minLength={1}
|
||||
maxLength={4000}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Image attachment for reply */}
|
||||
{/* Image attachments for reply */}
|
||||
<div>
|
||||
<input
|
||||
ref={replyFileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||
multiple
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const files = Array.from(e.target.files || []);
|
||||
files.forEach((file) => handleFileSelect(file, setReplyAttachments));
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
<AttachmentsPreview
|
||||
items={replyAttachments}
|
||||
onRemove={(idx) =>
|
||||
setReplyAttachments((prev) => {
|
||||
const removed = prev[idx];
|
||||
if (removed?.preview) URL.revokeObjectURL(removed.preview);
|
||||
return prev.filter((_, i) => i !== idx);
|
||||
})
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<input
|
||||
ref={replyFileInputRef}
|
||||
type="file"
|
||||
accept="image/jpeg,image/png,image/gif,image/webp"
|
||||
className="hidden"
|
||||
onChange={(e) => {
|
||||
const file = e.target.files?.[0];
|
||||
if (file) handleFileSelect(file, setReplyAttachment);
|
||||
e.target.value = '';
|
||||
}}
|
||||
/>
|
||||
{replyAttachment ? (
|
||||
<AttachmentPreview
|
||||
attachment={replyAttachment}
|
||||
onRemove={() => clearReplyAttachment()}
|
||||
/>
|
||||
) : (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => replyFileInputRef.current?.click()}
|
||||
className="flex items-center gap-2 text-sm text-dark-400 transition-colors hover:text-dark-200"
|
||||
>
|
||||
<ImageIcon />
|
||||
{t('support.attachImage')}
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
{replyAttachments.length < 10 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => replyFileInputRef.current?.click()}
|
||||
disabled={replyAttachments.some((a) => a.uploading)}
|
||||
className="flex items-center gap-2 text-sm text-dark-400 transition-colors hover:text-dark-200 disabled:opacity-50"
|
||||
>
|
||||
<ImageIcon />
|
||||
{t('support.attachImage')}{' '}
|
||||
{replyAttachments.length > 0 && `(${replyAttachments.length}/10)`}
|
||||
</button>
|
||||
)}
|
||||
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!replyMessage.trim() || replyAttachment?.uploading}
|
||||
disabled={
|
||||
(!replyMessage.trim() &&
|
||||
replyAttachments.filter((a) => a.fileId).length === 0) ||
|
||||
replyAttachments.some((a) => a.uploading)
|
||||
}
|
||||
loading={replyMutation.isPending}
|
||||
>
|
||||
<SendIcon />
|
||||
|
||||
@@ -473,6 +473,12 @@ export interface ReferralTerms {
|
||||
}
|
||||
|
||||
// Ticket types
|
||||
export interface TicketMediaItem {
|
||||
type: 'photo' | 'video' | 'document';
|
||||
file_id: string;
|
||||
caption?: string | null;
|
||||
}
|
||||
|
||||
export interface TicketMessage {
|
||||
id: number;
|
||||
message_text: string;
|
||||
@@ -481,6 +487,7 @@ export interface TicketMessage {
|
||||
media_type: string | null;
|
||||
media_file_id: string | null;
|
||||
media_caption: string | null;
|
||||
media_items?: TicketMediaItem[] | null;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
|
||||
28
src/utils/linkify.ts
Normal file
28
src/utils/linkify.ts
Normal file
@@ -0,0 +1,28 @@
|
||||
import DOMPurify from 'dompurify';
|
||||
|
||||
/**
|
||||
* Match http(s) URLs but exclude common trailing punctuation that is unlikely
|
||||
* to be part of the URL itself (e.g. the period at the end of a sentence,
|
||||
* or a closing bracket / quote that wraps the URL).
|
||||
*/
|
||||
const URL_REGEX = /(https?:\/\/[^\s<]+[^\s<.,;:!?\])}"'])/g;
|
||||
|
||||
/**
|
||||
* Linkify plain text by wrapping http(s) URLs in <a> tags.
|
||||
* Returns an HTML string sanitized via DOMPurify with a strict allowlist
|
||||
* (only <a> + <br>), safe to render in the UI.
|
||||
*
|
||||
* Trailing punctuation (.,;:!?)]}"') is excluded from the URL match so a
|
||||
* sentence like `Visit https://example.com.` does not capture the period.
|
||||
*/
|
||||
export function linkifyText(text: string | null | undefined): string {
|
||||
if (!text) return '';
|
||||
const replaced = text.replace(
|
||||
URL_REGEX,
|
||||
'<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>',
|
||||
);
|
||||
return DOMPurify.sanitize(replaced, {
|
||||
ALLOWED_TAGS: ['a', 'br'],
|
||||
ALLOWED_ATTR: ['href', 'target', 'rel'],
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user