Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5,328 changes: 2,159 additions & 3,169 deletions pnpm-lock.yaml

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions src/components/search/IntelligentAutoComplete.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import React, { useState, useEffect, useRef, useCallback } from 'react';
import React, { useState, useEffect, useRef, useCallback, useMemo } from 'react';
import { Search, X, Clock, ChevronRight, Sparkles, User, Tag, Type } from 'lucide-react';
import { getSearchSuggestions, highlightMatch } from '../../utils/searchUtils';

Expand All @@ -17,7 +17,7 @@ export const IntelligentAutoComplete = React.memo<IntelligentAutoCompleteProps>(
const [activeIndex, setActiveIndex] = useState(-1);
const dropdownRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const suggestions = getSearchSuggestions(value);
const suggestions = useMemo(() => getSearchSuggestions(value), [value]);

useEffect(() => {
const handleClickOutside = (event: MouseEvent) => {
Expand Down
73 changes: 61 additions & 12 deletions src/components/shared/ImageUploader.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use client';

import { useState, useRef, ChangeEvent } from 'react';
import { useState, useRef, ChangeEvent, useEffect } from 'react';
import Image from 'next/image';

interface ImageUploaderProps {
Expand All @@ -17,19 +17,68 @@ export default function ImageUploader({
const [previewUrl, setPreviewUrl] = useState<string | null>(initialImageUrl || null);
const fileInputRef = useRef<HTMLInputElement>(null);

const handleFileChange = (event: ChangeEvent<HTMLInputElement>) => {
useEffect(() => {
return () => {
if (previewUrl && previewUrl.startsWith('blob:')) {
URL.revokeObjectURL(previewUrl);
}
};
}, [previewUrl]);

const handleFileChange = async (event: ChangeEvent<HTMLInputElement>) => {
const file = event.target.files?.[0];
if (file) {
// Create local preview
const reader = new FileReader();
reader.onloadend = () => {
setPreviewUrl(reader.result as string);
};
reader.readAsDataURL(file);
if (!file) return;

if (file.type.startsWith('video/')) {
try {
const video = document.createElement('video');
video.src = URL.createObjectURL(file);
video.crossOrigin = 'anonymous';
video.muted = true;

await new Promise<void>((resolve, reject) => {
video.onloadeddata = () => {
// Seek to 1s or midway if shorter
video.currentTime = Math.min(1, video.duration / 2);
};
video.onseeked = () => resolve();
video.onerror = () => reject(new Error('Failed to load video'));
});

// Pass file to parent
const canvas = document.createElement('canvas');
canvas.width = video.videoWidth;
canvas.height = video.videoHeight;
const ctx = canvas.getContext('2d');
if (ctx) {
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
canvas.toBlob(
(blob) => {
if (blob) {
const objectUrl = URL.createObjectURL(blob);
setPreviewUrl(objectUrl);
const optimizedFile = new File([blob], file.name.replace(/\.[^/.]+$/, '.jpg'), {
type: 'image/jpeg',
});
onImageSelect(optimizedFile);
}
},
'image/jpeg',
0.85,
);
}
URL.revokeObjectURL(video.src);
} catch (error) {
console.error('Video optimization failed:', error);
}
} else if (file.type.startsWith('image/')) {
const objectUrl = URL.createObjectURL(file);
setPreviewUrl(objectUrl);
onImageSelect(file);
}

if (fileInputRef.current) {
fileInputRef.current.value = '';
}
};

const handleClick = () => {
Expand All @@ -48,7 +97,7 @@ export default function ImageUploader({
alt="Profile Preview"
fill
sizes="(max-width: 768px) 100vw, 33vw"
unoptimized={previewUrl.startsWith('data:')}
unoptimized={previewUrl.startsWith('data:') || previewUrl.startsWith('blob:')}
className="object-cover"
/>
) : (
Expand Down Expand Up @@ -80,7 +129,7 @@ export default function ImageUploader({
<input
ref={fileInputRef}
type="file"
accept="image/*"
accept="image/*,video/*"
onChange={handleFileChange}
className="hidden"
/>
Expand Down
95 changes: 95 additions & 0 deletions src/components/shared/__tests__/ImageUploader.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
import { render, screen, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { describe, it, expect, vi, beforeEach, afterEach, beforeAll, afterAll } from 'vitest';
import ImageUploader from '../ImageUploader';

describe('ImageUploader', () => {
let originalCreateElement: typeof document.createElement;

beforeAll(() => {
global.URL.createObjectURL = vi.fn(() => 'blob:mock-url');
global.URL.revokeObjectURL = vi.fn();

originalCreateElement = document.createElement.bind(document);
vi.spyOn(document, 'createElement').mockImplementation(
(tagName: string, options?: ElementCreationOptions) => {
if (tagName === 'video') {
const video = originalCreateElement('video');
Object.defineProperty(video, 'duration', { value: 10 });
Object.defineProperty(video, 'videoWidth', { value: 640 });
Object.defineProperty(video, 'videoHeight', { value: 480 });

// Simulate video load and seek events automatically
setTimeout(() => {
if (video.onloadeddata) (video.onloadeddata as Function)();
setTimeout(() => {
if (video.onseeked) (video.onseeked as Function)();
}, 0);
}, 0);
return video;
}

if (tagName === 'canvas') {
const canvas = originalCreateElement('canvas');
canvas.getContext = vi.fn(
() =>
({
drawImage: vi.fn(),
} as any),
);
canvas.toBlob = vi.fn((callback) => {
callback(new Blob(['mock-image-data'], { type: 'image/jpeg' }));
});
return canvas;
}
return originalCreateElement(tagName, options);
},
);
});

afterAll(() => {
vi.restoreAllMocks();
});

afterEach(() => {
vi.clearAllMocks();
});

it('renders correctly with default state', () => {
render(<ImageUploader onImageSelect={vi.fn()} />);
expect(screen.getByText('Upload New Picture')).toBeInTheDocument();
});

it('handles image upload correctly without video extraction', async () => {
const onImageSelect = vi.fn();
const user = userEvent.setup();
render(<ImageUploader onImageSelect={onImageSelect} />);

const file = new File(['hello'], 'hello.png', { type: 'image/png' });
const input = document.querySelector('input[type="file"]') as HTMLInputElement;

await user.upload(input, file);

expect(global.URL.createObjectURL).toHaveBeenCalledWith(file);
expect(onImageSelect).toHaveBeenCalledWith(file);
});

it('extracts frame when video is uploaded', async () => {
const onImageSelect = vi.fn();
const user = userEvent.setup();
render(<ImageUploader onImageSelect={onImageSelect} />);

const file = new File(['video-data'], 'video.mp4', { type: 'video/mp4' });
const input = document.querySelector('input[type="file"]') as HTMLInputElement;

await user.upload(input, file);

await waitFor(() => {
expect(onImageSelect).toHaveBeenCalled();
});

const selectedFile = onImageSelect.mock.calls[0][0];
expect(selectedFile.name).toBe('video.jpg');
expect(selectedFile.type).toBe('image/jpeg');
});
});
Loading