Custom icons uploaded for a custom site link were always stored as non-maskable, so they rendered inset with a rounded border instead of filling the tile. Mark every readIconFile result as maskable so uploads are drawn edge-to-edge like a site's own maskable icon, and update the image-file tests accordingly.
77 lines
2.4 KiB
JavaScript
77 lines
2.4 KiB
JavaScript
// Uploaded icons are kept small so they don't bloat IndexedDB, and only ever
|
|
// rendered through an <img>, so no markup can be executed. They're treated as
|
|
// maskable: a user-chosen icon is assumed to be a full-bleed square tile, so it
|
|
// renders edge-to-edge like a site's own maskable/apple-touch icon.
|
|
export const ICON_MAX_FILE_SIZE = 1024 * 1024;
|
|
|
|
// Match the size the favicon pipeline targets for crisp tiles on hidpi screens.
|
|
export const ICON_TARGET_SIZE = 192;
|
|
|
|
export class IconFileError extends Error {
|
|
constructor(message) {
|
|
super(message);
|
|
this.name = 'IconFileError';
|
|
}
|
|
}
|
|
|
|
function readAsDataUrl(file) {
|
|
return new Promise((resolve, reject) => {
|
|
const reader = new FileReader();
|
|
reader.onload = () => resolve(reader.result);
|
|
reader.onerror = () =>
|
|
reject(reader.error ?? new IconFileError('Unable to read the image'));
|
|
reader.readAsDataURL(file);
|
|
});
|
|
}
|
|
|
|
// Turns an uploaded image file into an icon record ready for storage. Raster
|
|
// images larger than `targetSize` are downscaled; anything that cannot be
|
|
// decoded falls back to the original bytes so an upload never hard-fails.
|
|
export async function readIconFile(
|
|
file,
|
|
{ targetSize = ICON_TARGET_SIZE } = {}
|
|
) {
|
|
if (!file || !file.type?.startsWith('image/')) {
|
|
throw new IconFileError('Please choose an image file');
|
|
}
|
|
|
|
if (file.size > ICON_MAX_FILE_SIZE) {
|
|
throw new IconFileError('That image is too large (max 1 MB)');
|
|
}
|
|
|
|
const dataUrl = await readAsDataUrl(file);
|
|
|
|
// SVGs are already vector and typically tiny; leave them untouched.
|
|
if (file.type === 'image/svg+xml') {
|
|
return { dataUrl, maskable: true };
|
|
}
|
|
|
|
try {
|
|
const bitmap = await createImageBitmap(file);
|
|
const scale = Math.min(
|
|
1,
|
|
targetSize / Math.max(bitmap.width, bitmap.height)
|
|
);
|
|
|
|
if (scale >= 1) {
|
|
bitmap.close?.();
|
|
return { dataUrl, maskable: true };
|
|
}
|
|
|
|
const canvas = document.createElement('canvas');
|
|
canvas.width = Math.max(1, Math.round(bitmap.width * scale));
|
|
canvas.height = Math.max(1, Math.round(bitmap.height * scale));
|
|
|
|
canvas
|
|
.getContext('2d')
|
|
.drawImage(bitmap, 0, 0, canvas.width, canvas.height);
|
|
bitmap.close?.();
|
|
|
|
return { dataUrl: canvas.toDataURL('image/png'), maskable: true };
|
|
} catch {
|
|
// Decoding or canvas can fail (Firefox rejects SVG bitmaps, say); keep the
|
|
// original bytes.
|
|
return { dataUrl, maskable: true };
|
|
}
|
|
}
|