Skip to content

Instantly share code, notes, and snippets.

@phaistonian
Last active April 27, 2018 08:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phaistonian/13ebc6962b7dc6d8da003dfab036b084 to your computer and use it in GitHub Desktop.
Save phaistonian/13ebc6962b7dc6d8da003dfab036b084 to your computer and use it in GitHub Desktop.
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