From b3282708d4c3abcb6bebd07124d47834bd69ea98 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Sat, 16 Dec 2017 19:32:02 +0330 Subject: [PATCH] feat(client): support for presets --- client/js/README.md | 12 ++++++++++-- client/js/package.json | 2 +- client/js/src/index.js | 40 +++++++++++++++++++++++++++------------- 3 files changed, 38 insertions(+), 16 deletions(-) diff --git a/client/js/README.md b/client/js/README.md index ecfd0de..7218c4e 100644 --- a/client/js/README.md +++ b/client/js/README.md @@ -25,8 +25,16 @@ const getImage = img({ baseURL = 'https://cdn.example.com', basePath = 'uploads', opts = [], // Default opts - format = 'webp' + format = 'jpg', + presets: { + chrome400: { + format: 'png', + opts: { s: ['400', '400']} + } + } }) -getImage('posts/ipx.jpg', { w: 200 }) // => https://cdn.example.com/webp/w_200/uploads/posts/ipx.jpg +getImage('posts/ipx.png', { w: 200 }) // => https://cdn.example.com/jpg/w_200/uploads/posts/ipx.png + +getImage.chrome400('posts/ipx.png') // => https://cdn.example.com/webp/s_400_400/uploads/posts/ipx.png ``` diff --git a/client/js/package.json b/client/js/package.json index a0eaaa9..7df38e4 100644 --- a/client/js/package.json +++ b/client/js/package.json @@ -1,6 +1,6 @@ { "name": "ipx-client", - "version": "0.2.2", + "version": "0.3.0", "license": "MIT", "contributors": [ "Pooya Parsa " diff --git a/client/js/src/index.js b/client/js/src/index.js index 7e7c241..43940ea 100644 --- a/client/js/src/index.js +++ b/client/js/src/index.js @@ -1,22 +1,36 @@ +const filterEmpty = arr => arr.filter(o => o && o.length) const normalizeObject = o => Object.keys(o).map(k => [].concat(k, o[k]).join('_')) const normalizeArray = a => a.map(normalize).join('_') -const normalize = o => typeof o === 'string' ? [o] : (Array.isArray(o) ? normalizeArray(o) : normalizeObject(o)) +const normalize = filterEmpty(o => typeof o === 'string' ? [o] : (Array.isArray(o) ? normalizeArray(o) : normalizeObject(o))) export const img = ({ baseURL = '', basePath = '', opts = [], - format = '_' -}) => ( - path, - _opts = [], - _format = format -) => { - const optsStr = [] - .concat(normalize(opts)) - .concat(normalize(_opts)) - .filter(o => o && o.length) - .join(',') + format = '_', + presets = null +}) => { + // Normalize default opts + opts = normalize(opts) - return (baseURL + '/' + format + '/' + optsStr + '/' + basePath + '/' + path).replace(/\/\//g, '/') + // Create fn + const fn = ( + path, + _opts = [], + _format = format + ) => { + const optsStr = [].concat(opts, normalize(_opts)).join(',') + return (baseURL + '/' + format + '/' + optsStr + '/' + basePath + '/' + path).replace(/\/\//g, '/') + } + + // Attach all presets + if (presets) { + Object.keys(presets).forEach(key => { + const preset = presets[key] + const presetOpts = normalize(preset.opts) + fn[key] = (path, _opts, _format) => fn(path, _opts || presetOpts, _format || preset.format) + }) + } + + return fn } -- knotmirror 0.0.1