Skip to content

Instantly share code, notes, and snippets.

@phaistonian

phaistonian/getImgSrc.js

Last active Apr 27, 2018
Embed
What would you like to do?
getImgSrc
export default (input, options = {
title: 'image',
size: null,
height: null,
width: null,
crop: {},
cover: false,
}) => {
const data = typeof input === 'string'
? {
path: input,
ts: null,
}
: input;
let path = data ? data.path || data.img || data.url || data.p : null;
if (!path) {
return null;
}
// Missing domain
// TODO: do this better
if (path.indexOf('pstatic') === -1) {
path = `//bbpcdn.pstatic.gr/${path}`;
}
const { crop, title = 'image' } = options;
let width = options.width;
let height = options.height;
// If options.size is assigned, we ignore width and height
if (options.size) {
width = options.size;
height = options.size;
}
if (options.cover) {
const widthFull = data.width || data.w;
const heightFull = data.height || data.h;
if (widthFull && heightFull) {
height = width / (widthFull / heightFull);
}
}
const titleAsSlug = title.toLowerCase().replace(/ +/, '-');
const ts = data.ts;
// Size stuff
const sizes = [];
if (width) {
sizes.push(`X${width}`);
}
if (height) {
sizes.push(`Y${height}`);
}
const tsAppend = ts
? `/${ts}`
: '';
const format = ENV.supports.webp ? 'webp' : 'jpg';
// TODO: we need this on bestprice.gr too
let cropAppend = '';
if (crop && (crop.width || crop.height)) {
crop.width = crop.width || parseInt(width);
crop.height = crop.height || parseInt(height);
cropAppend = `C${crop.width}x${crop.height}`;
}
return `${path}${sizes.length ? `_S${sizes.join('')}` : ''}${cropAppend}${tsAppend}/${titleAsSlug}.${format}`;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment