| 1 |
import { sleep } from '@shared/lib/utils'; |
| 2 |
|
| 3 |
const MAX_RETRIES = 2; |
| 4 |
const RETRY_DELAY = 1000; // 1 second in milliseconds |
| 5 |
|
| 6 |
export const fetchFontFaceFile = async (url) => { |
| 7 |
for (let attempt = 0; attempt <= MAX_RETRIES; attempt++) { |
| 8 |
try { |
| 9 |
// Add delay if this is not the first attempt |
| 10 |
if (attempt > 0) await sleep(RETRY_DELAY); |
| 11 |
|
| 12 |
const response = await fetch(url); |
| 13 |
|
| 14 |
if (!response.ok) { |
| 15 |
throw new Error('Failed to fetch font file.'); |
| 16 |
} |
| 17 |
|
| 18 |
const blob = await response.blob(); |
| 19 |
const filename = url.split('/').pop(); |
| 20 |
|
| 21 |
return new File([blob], filename, { |
| 22 |
type: blob.type, |
| 23 |
}); |
| 24 |
} catch (_) { |
| 25 |
if (attempt <= MAX_RETRIES) continue; |
| 26 |
|
| 27 |
console.error( |
| 28 |
`Failed to fetch font file after ${MAX_RETRIES + 1} attempts.`, |
| 29 |
); |
| 30 |
|
| 31 |
return; |
| 32 |
} |
| 33 |
} |
| 34 |
}; |
| 35 |
|
| 36 |
export function makeFontFamilyFormData({ name, slug, fontFamily }) { |
| 37 |
const formData = new FormData(); |
| 38 |
const fontFamilySettings = { name, slug, fontFamily }; |
| 39 |
formData.append('font_family_settings', JSON.stringify(fontFamilySettings)); |
| 40 |
|
| 41 |
return formData; |
| 42 |
} |
| 43 |
|
| 44 |
export function makeFontFaceFormData({ |
| 45 |
fontFamilySlug, |
| 46 |
fontFamily, |
| 47 |
fontStyle, |
| 48 |
fontWeight, |
| 49 |
fontDisplay, |
| 50 |
unicodeRange, |
| 51 |
src = [], |
| 52 |
file = [], |
| 53 |
}) { |
| 54 |
const formData = new FormData(); |
| 55 |
const fontFaceSettings = { |
| 56 |
fontFamily, |
| 57 |
fontStyle, |
| 58 |
fontWeight, |
| 59 |
fontDisplay, |
| 60 |
unicodeRange: |
| 61 |
unicodeRange === undefined || unicodeRange === null ? '' : unicodeRange, |
| 62 |
src: Array.isArray(src) ? src : [src], |
| 63 |
}; |
| 64 |
const files = Array.isArray(file) ? file : [file]; |
| 65 |
|
| 66 |
// Add each font file to the form data. |
| 67 |
files.forEach((file) => { |
| 68 |
const fileId = `${fontFamilySlug}-${fontWeight}-${fontStyle}`; |
| 69 |
formData.append(fileId, file, file.name); |
| 70 |
|
| 71 |
// Use the file ids as src for WP to match and upload the files. |
| 72 |
if (!src?.length) { |
| 73 |
fontFaceSettings.src.push(fileId); |
| 74 |
} else { |
| 75 |
fontFaceSettings.src = [fileId]; |
| 76 |
} |
| 77 |
}); |
| 78 |
|
| 79 |
formData.append('font_face_settings', JSON.stringify(fontFaceSettings)); |
| 80 |
|
| 81 |
return formData; |
| 82 |
} |
| 83 |
|