Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 | 46x 46x 46x 130x 46x 61x 60x 60x 79x 1x 78x 61x 61x 18x 18x 60x 29x 61x 1x 60x 60x 10x 50x 50x 11x | import { baseUrl } from "./environment";
export const DEFAULT_SONG_IMAGE_URL = `${baseUrl}/defaultSongCover.jpeg`;
const isValidImage = (
image: Spotify.Image | undefined
): image is Pick<Spotify.Image, "url"> => {
return !!(image?.url && image.url.trim() !== "");
};
const calculateDistance = (
image: Spotify.Image,
width: number,
height?: number
) => {
return (
(image?.width ? Math.abs(image.width - width) : 0) +
(height !== undefined && image?.height
? Math.abs(image.height - height)
: 0)
);
};
function findClosestImage(
images: (Spotify.Image | undefined)[],
targetWidth: number,
targetHeight?: number
) {
let closestValidImage: Spotify.Image | undefined;
let closestDistance = Number.MAX_VALUE;
for (const image of images) {
if (
closestValidImage?.url &&
closestValidImage?.width &&
closestValidImage?.width >= targetWidth &&
image?.width &&
image?.width < targetWidth
) {
break;
}
if (isValidImage(image)) {
const distance = calculateDistance(image, targetWidth, targetHeight);
if (distance <= closestDistance && image?.width) {
closestDistance = distance;
closestValidImage = image;
}
}
}
return closestValidImage;
}
export function chooseImage(
images: (Spotify.Image | undefined)[] | undefined,
targetWidth: number,
targetHeight?: number
): Spotify.Image {
if (!images || images.length === 0) {
return { url: DEFAULT_SONG_IMAGE_URL };
}
const closestValidImage = findClosestImage(images, targetWidth, targetHeight);
if (closestValidImage) {
return closestValidImage;
} else {
const imageWithUrl = images.find(isValidImage);
if (imageWithUrl) return imageWithUrl;
}
return { url: DEFAULT_SONG_IMAGE_URL };
}
|