utils.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import { type ClassValue, clsx } from 'clsx';
  2. export function cn(...inputs: ClassValue[]) {
  3. return clsx(inputs);
  4. }
  5. export function formatFileSize(bytes: number): string {
  6. if (bytes === 0) return '0 Bytes';
  7. const k = 1024;
  8. const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
  9. const i = Math.floor(Math.log(bytes) / Math.log(k));
  10. return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i];
  11. }
  12. export function downloadImage(url: string, filename: string = 'generated-image.png') {
  13. const link = document.createElement('a');
  14. link.href = url;
  15. link.download = filename;
  16. document.body.appendChild(link);
  17. link.click();
  18. document.body.removeChild(link);
  19. }
  20. // Download image with authentication support
  21. export async function downloadAuthenticatedImage(
  22. imageUrl: string,
  23. filename: string = 'generated-image.png',
  24. authToken?: string,
  25. unixUser?: string
  26. ): Promise<void> {
  27. try {
  28. const headers: Record<string, string> = {};
  29. // Add authentication headers if provided
  30. if (unixUser) {
  31. headers['X-Unix-User'] = unixUser;
  32. } else if (authToken) {
  33. headers['Authorization'] = `Bearer ${authToken}`;
  34. }
  35. const response = await fetch(imageUrl, { headers });
  36. if (!response.ok) {
  37. throw new Error(`Failed to download image: ${response.statusText}`);
  38. }
  39. const blob = await response.blob();
  40. const url = window.URL.createObjectURL(blob);
  41. downloadImage(url, filename);
  42. // Clean up the object URL
  43. window.URL.revokeObjectURL(url);
  44. } catch (error) {
  45. console.error('Error downloading authenticated image:', error);
  46. throw error;
  47. }
  48. }
  49. export function fileToBase64(file: File): Promise<string> {
  50. return new Promise((resolve, reject) => {
  51. const reader = new FileReader();
  52. reader.readAsDataURL(file);
  53. reader.onload = () => resolve(reader.result as string);
  54. reader.onerror = error => reject(error);
  55. });
  56. }