From 7a440769cb3fd7b880719a88a2e47a3c77ab6d98 Mon Sep 17 00:00:00 2001 From: Amir Tocker Date: Mon, 28 Jan 2019 12:40:13 +0200 Subject: [PATCH] Fix imports; refactor code --- karma.cloudinary-core.js | 5 +- karma.cloudinary-jquery-file-upload.js | 5 +- karma.cloudinary-jquery.js | 5 +- src/cloudinary.js | 42 +++----------- src/cloudinaryjquery.js | 14 +---- src/expression.js | 2 +- src/jquery-file-upload.js | 1 + src/layer/fetchlayer.js | 3 +- src/layer/textlayer.js | 26 ++++----- src/parameters.js | 5 +- src/tags/htmltag.js | 2 + src/tags/imagetag.js | 6 +- src/tags/picturetag.js | 3 +- src/tags/videotag.js | 15 ++--- src/transformation.js | 26 ++++----- src/util/baseutil.js | 78 +++++++------------------- src/util/firstNotNull.js | 16 ++++++ src/util/lodash.js | 2 - src/util/srcsetUtils.js | 1 - webpack.config.js | 4 +- 20 files changed, 103 insertions(+), 158 deletions(-) create mode 100644 src/util/firstNotNull.js diff --git a/karma.cloudinary-core.js b/karma.cloudinary-core.js index 89c05776..173b2b81 100644 --- a/karma.cloudinary-core.js +++ b/karma.cloudinary-core.js @@ -1,5 +1,8 @@ // Karma configuration // Generated on Tue Jul 28 2015 09:31:57 GMT+0300 (IDT) +let isProd = mode === 'production'; +let mode = isProd ? 'production' : 'development'; +console.log(`mode is ${mode}`); module.exports = function(config) { return config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) @@ -11,7 +14,7 @@ module.exports = function(config) { // list of files / patterns to load in the browser files: [ 'node_modules/lodash/lodash.js', - 'dist/cloudinary-core.min.js', + 'dist/cloudinary-core' + (isProd ? '.min': '') + '.js', 'test/spec/spec-helper.js', 'test/spec/cloudinary-spec.js', 'test/spec/transformation-spec.js', diff --git a/karma.cloudinary-jquery-file-upload.js b/karma.cloudinary-jquery-file-upload.js index 169028d4..8a23416f 100644 --- a/karma.cloudinary-jquery-file-upload.js +++ b/karma.cloudinary-jquery-file-upload.js @@ -1,5 +1,8 @@ // Karma configuration // Generated on Tue Jul 28 2015 09:31:57 GMT+0300 (IDT) +let isProd = mode === 'production'; +let mode = isProd ? 'production' : 'development'; +console.log(`mode is ${mode}`); module.exports = function(config) { return config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) @@ -15,7 +18,7 @@ module.exports = function(config) { 'node_modules/blueimp-file-upload/js/jquery.fileupload-process.js', 'node_modules/blueimp-file-upload/js/jquery.iframe-transport.js', 'node_modules/blueimp-file-upload/js/jquery.fileupload-image.js', - 'dist/cloudinary-jquery-file-upload.min.js', + 'dist/cloudinary-jquery-file-upload' + (isProd ? '.min': '') + '.js', 'test/spec/spec-helper.js', 'test/spec/cloudinary-spec.js', 'test/spec/cloudinary-jquery-upload-spec.js', diff --git a/karma.cloudinary-jquery.js b/karma.cloudinary-jquery.js index fc2d3bfc..b675e478 100644 --- a/karma.cloudinary-jquery.js +++ b/karma.cloudinary-jquery.js @@ -1,5 +1,8 @@ // Karma configuration // Generated on Tue Jul 28 2015 09:31:57 GMT+0300 (IDT) +let isProd = mode === 'production'; +let mode = isProd ? 'production' : 'development'; +console.log(`mode is ${mode}`); module.exports = function(config) { return config.set({ // base path that will be used to resolve all patterns (eg. files, exclude) @@ -10,7 +13,7 @@ module.exports = function(config) { // list of files / patterns to load in the browser files: [ 'node_modules/jquery/dist/jquery.js', - 'dist/cloudinary-jquery.min.js', + 'dist/cloudinary-jquery' + (isProd ? '.min': '') + '.js', 'test/spec/spec-helper.js', 'test/spec/cloudinary-spec.js', 'test/spec/transformation-spec.js', diff --git a/src/cloudinary.js b/src/cloudinary.js index 7912d16a..7abf257c 100644 --- a/src/cloudinary.js +++ b/src/cloudinary.js @@ -1,18 +1,12 @@ -var Cloudinary, applyBreakpoints, closestAbove, defaultBreakpoints, findContainerWidth, maxWidth, updateDpr; - -import url from './url'; +var applyBreakpoints, closestAbove, defaultBreakpoints, findContainerWidth, maxWidth, updateDpr; import Configuration from './configuration'; - -import Transformation from './transformation'; - import HtmlTag from './tags/htmltag'; - import ImageTag from './tags/imagetag'; - import PictureTag from './tags/picturetag'; import SourceTag from './tags/sourcetag'; - +import Transformation from './transformation'; +import url from './url'; import VideoTag from './tags/videotag'; import { @@ -23,7 +17,6 @@ import { isArray, isEmpty, isFunction, - isPlainObject, isString, merge, removeAttribute, @@ -33,16 +26,7 @@ import { } from './util'; import { - VERSION, - CF_SHARED_CDN, - OLD_AKAMAI_SHARED_CDN, - AKAMAI_SHARED_CDN, - SHARED_CDN, - DEFAULT_POSTER_OPTIONS, - DEFAULT_VIDEO_SOURCE_TYPES, - SEO_TYPES, - DEFAULT_IMAGE_PARAMS, - DEFAULT_VIDEO_PARAMS + DEFAULT_POSTER_OPTIONS } from './constants'; defaultBreakpoints = function(width, steps = 100) { @@ -94,7 +78,7 @@ maxWidth = function(requiredWidth, tag) { return imageWidth; }; -Cloudinary = class Cloudinary { +var Cloudinary = class Cloudinary { /** * Main Cloudinary class * @class Cloudinary @@ -439,24 +423,12 @@ Cloudinary = class Cloudinary { * @ignore */ calc_breakpoint(element, width, steps) { - var breakpoints, point; - breakpoints = getData(element, 'breakpoints') || getData(element, 'stoppoints') || this.config('breakpoints') || this.config('stoppoints') || defaultBreakpoints; + let breakpoints = getData(element, 'breakpoints') || getData(element, 'stoppoints') || this.config('breakpoints') || this.config('stoppoints') || defaultBreakpoints; if (isFunction(breakpoints)) { return breakpoints(width, steps); } else { if (isString(breakpoints)) { - breakpoints = ((function() { - var j, len, ref, results; - ref = breakpoints.split(','); - results = []; - for (j = 0, len = ref.length; j < len; j++) { - point = ref[j]; - results.push(parseInt(point)); - } - return results; - })()).sort(function(a, b) { - return a - b; - }); + breakpoints = breakpoints.split(',').map(point=>parseInt(point)).sort((a, b) => a - b); } return closestAbove(breakpoints, width); } diff --git a/src/cloudinaryjquery.js b/src/cloudinaryjquery.js index 438a1052..e39b82b8 100644 --- a/src/cloudinaryjquery.js +++ b/src/cloudinaryjquery.js @@ -5,16 +5,8 @@ var webp; import Cloudinary from './cloudinary'; - -function firstNotNull(...args) { - while(args && args.length > 0) { - let next = args.shift(); - if( next != null){ - return next; - } - } - return null; -} +import Transformation from './transformation' +import firstNotNull from './util/firstNotNull' const CloudinaryJQuery = class CloudinaryJQuery extends Cloudinary { /** @@ -85,7 +77,7 @@ const CloudinaryJQuery = class CloudinaryJQuery extends Cloudinary { } } -} +}; /** * The following methods are provided through the jQuery class diff --git a/src/expression.js b/src/expression.js index 834991e2..9a96859e 100644 --- a/src/expression.js +++ b/src/expression.js @@ -270,7 +270,7 @@ const Expression = class Expression { return new this("pageY"); } -} +}; /** * @internal diff --git a/src/jquery-file-upload.js b/src/jquery-file-upload.js index 77ed6d7b..ddbb4870 100644 --- a/src/jquery-file-upload.js +++ b/src/jquery-file-upload.js @@ -3,6 +3,7 @@ * Depends on 'jquery', 'util', 'cloudinaryjquery', 'jquery.ui.widget', 'jquery.iframe-transport','jquery.fileupload' */ import CloudinaryJQuery from './cloudinaryjquery'; +import * as Util from './util'; /** * Delete a resource using the upload token diff --git a/src/layer/fetchlayer.js b/src/layer/fetchlayer.js index a79b8550..e82f0807 100644 --- a/src/layer/fetchlayer.js +++ b/src/layer/fetchlayer.js @@ -1,6 +1,7 @@ import Layer from './layer'; import { + base64EncodeURL, isString } from '../util'; @@ -30,7 +31,7 @@ const FetchLayer = class FetchLayer extends Layer { * @return {String} */ toString() { - return `fetch:${cloudinary.Util.base64EncodeURL(this.options.url)}`; + return `fetch:${base64EncodeURL(this.options.url)}`; } }; diff --git a/src/layer/textlayer.js b/src/layer/textlayer.js index edbc0de1..81e894a9 100644 --- a/src/layer/textlayer.js +++ b/src/layer/textlayer.js @@ -20,7 +20,7 @@ var TextLayer = class TextLayer extends Layer { if (options != null) { keys.forEach((key) => { var ref; - return this.options[key] = (ref = options[key]) != null ? ref : options[Util.snakeCase(key)]; + return this.options[key] = (ref = options[key]) != null ? ref : options[snakeCase(key)]; }); } this.options.resourceType = "text"; @@ -100,25 +100,25 @@ var TextLayer = class TextLayer extends Layer { publicId = this.getFullPublicId(); } if (this.options.text != null) { - hasPublicId = !Util.isEmpty(publicId); - hasStyle = !Util.isEmpty(style); + hasPublicId = !isEmpty(publicId); + hasStyle = !isEmpty(style); if (hasPublicId && hasStyle || !hasPublicId && !hasStyle) { throw "Must supply either style parameters or a public_id when providing text parameter in a text overlay/underlay, but not both!"; } re = /\$\([a-zA-Z]\w*\)/g; start = 0; // textSource = text.replace(new RegExp("[,/]", 'g'), (c)-> "%#{c.charCodeAt(0).toString(16).toUpperCase()}") - textSource = Util.smartEscape(this.options.text, /[,\/]/g); + textSource = smartEscape(this.options.text, /[,\/]/g); text = ""; while (res = re.exec(textSource)) { - text += Util.smartEscape(textSource.slice(start, res.index)); + text += smartEscape(textSource.slice(start, res.index)); text += res[0]; start = res.index + res[0].length; } - text += Util.smartEscape(textSource.slice(start)); + text += smartEscape(textSource.slice(start)); } components = [this.options.resourceType, style, publicId, text]; - return Util.compact(components).join(":"); + return compact(components).join(":"); } textStyleIdentifier() { @@ -137,22 +137,22 @@ var TextLayer = class TextLayer extends Layer { if (this.options.stroke !== "none") { components.push(this.options.stroke); } - if (!(Util.isEmpty(this.options.letterSpacing) && !Util.isNumberLike(this.options.letterSpacing))) { + if (!(isEmpty(this.options.letterSpacing) && !isNumberLike(this.options.letterSpacing))) { components.push("letter_spacing_" + this.options.letterSpacing); } - if (!(Util.isEmpty(this.options.lineSpacing) && !Util.isNumberLike(this.options.lineSpacing))) { + if (!(isEmpty(this.options.lineSpacing) && !isNumberLike(this.options.lineSpacing))) { components.push("line_spacing_" + this.options.lineSpacing); } - if (!Util.isEmpty(Util.compact(components))) { - if (Util.isEmpty(this.options.fontFamily)) { + if (!isEmpty(compact(components))) { + if (isEmpty(this.options.fontFamily)) { throw `Must supply fontFamily. ${components}`; } - if (Util.isEmpty(this.options.fontSize) && !Util.isNumberLike(this.options.fontSize)) { + if (isEmpty(this.options.fontSize) && !isNumberLike(this.options.fontSize)) { throw "Must supply fontSize."; } } components.unshift(this.options.fontFamily, this.options.fontSize); - components = Util.compact(components).join("_"); + components = compact(components).join("_"); return components; } diff --git a/src/parameters.js b/src/parameters.js index 9e208b07..14bfbcc0 100644 --- a/src/parameters.js +++ b/src/parameters.js @@ -3,6 +3,7 @@ import Transformation from "./transformation"; import { allStrings, + identity, isArray, isEmpty, isFunction, @@ -33,7 +34,7 @@ var Param = class Param { * @param {function} [process=Util.identity ] - Manipulate origValue when value is called * @ignore */ - constructor(name, shortName, process = Util.identity) { + constructor(name, shortName, process = identity) { /** * The name of the parameter in snake_case * @member {string} Param#name @@ -266,7 +267,7 @@ var RangeParam = class RangeParam extends Param { }; var RawParam = class RawParam extends Param { - constructor(name, shortName, process = Util.identity) { + constructor(name, shortName, process = identity) { super(name, shortName, process); } diff --git a/src/tags/htmltag.js b/src/tags/htmltag.js index 22628a90..01615a2e 100644 --- a/src/tags/htmltag.js +++ b/src/tags/htmltag.js @@ -11,6 +11,8 @@ import { merge } from '../util'; +import Transformation from '../transformation'; + var HtmlTag = class HtmlTag { /** * Represents an HTML (DOM) tag diff --git a/src/tags/imagetag.js b/src/tags/imagetag.js index fb6c015a..72bb35e4 100644 --- a/src/tags/imagetag.js +++ b/src/tags/imagetag.js @@ -38,11 +38,11 @@ var ImageTag = class ImageTag extends HtmlTag { if (isString(srcsetParam)) { responsiveAttributes.srcset = srcsetParam } else { - responsiveAttributes = generateImageResponsiveAttributes(this.publicId, {}, srcsetParam, options); + responsiveAttributes = generateImageResponsiveAttributes(this.publicId, attributes, srcsetParam, options); } if(!isEmpty(responsiveAttributes)) { - delete localOptions.width; - delete localOptions.height; + delete options.width; + delete options.height; } merge(attr, responsiveAttributes); diff --git a/src/tags/picturetag.js b/src/tags/picturetag.js index 8b9e427c..6fffac6f 100644 --- a/src/tags/picturetag.js +++ b/src/tags/picturetag.js @@ -1,6 +1,6 @@ import HtmlTag from './htmltag'; +import ImageTag from './imagetag'; import Transformation from '../transformation'; -import url from '../url'; import SourceTag from './sourcetag'; import {extractUrlParams} from "../util"; @@ -22,7 +22,6 @@ const PictureTag = class PictureTag extends HtmlTag { options.media = {min_width, max_width}; options.transformation = sourceTransformation; return new SourceTag(this.publicId, options).toHtml(); - // return ``; }).join('') + new ImageTag(this.publicId, this.getOptions()).toHtml(); } diff --git a/src/tags/videotag.js b/src/tags/videotag.js index 0a413ac8..befc6acc 100644 --- a/src/tags/videotag.js +++ b/src/tags/videotag.js @@ -89,28 +89,25 @@ const VideoTag = class VideoTag extends HtmlTag { } content() { - var cld, fallback, innerTags, mimeType, sourceTransformation, sourceTypes, src, srcType, transformation, videoType; + var fallback, innerTags, type, sourceTransformation, sourceTypes, src, srcType, transformation, videoType; sourceTypes = this.transformation().getValue('source_types'); sourceTransformation = this.transformation().getValue('source_transformation'); fallback = this.transformation().getValue('fallback_content'); if (isArray(sourceTypes)) { - cld = new Cloudinary(this.getOptions()); + let options = this.getOptions(); innerTags = (function () { var i, len, results; results = []; for (i = 0, len = sourceTypes.length; i < len; i++) { srcType = sourceTypes[i]; transformation = sourceTransformation[srcType] || {}; - src = cld.url(`${this.publicId}`, defaults({}, transformation, { + src = url(`${this.publicId}`, defaults({}, transformation, { resource_type: 'video', format: srcType - })); + }, options)); videoType = srcType === 'ogv' ? 'ogg' : srcType; - mimeType = 'video/' + videoType; - results.push(``); + type = 'video/' + videoType; + results.push(``); } return results; }).call(this); diff --git a/src/transformation.js b/src/transformation.js index 1f5cd77a..4dfa8741 100644 --- a/src/transformation.js +++ b/src/transformation.js @@ -1,25 +1,21 @@ -import { - assign, - camelCase, - contains, - functions, - snakeCase -} from './util'; - import Expression from './expression'; - +import Condition from './condition'; import Configuration from './configuration'; import { + assign, + camelCase, + cloneDeep, + compact, + contains, + difference, identity, isArray, isEmpty, isFunction, isPlainObject, isString, - cloneDeep, - compact, - difference + snakeCase } from './util'; import { @@ -222,7 +218,7 @@ var TransformationBase = class TransformationBase { * @return {Object} the transformation options as plain object */ this.toPlainObject = function () { - var hash, key, list, tr; + var hash, key, list; hash = {}; for (key in trans) { hash[key] = trans[key].value(); @@ -348,7 +344,7 @@ var TransformationBase = class TransformationBase { * @return {string} Returns the transformation as a string */ serialize() { - var ifParam, j, len, paramList, ref, ref1, ref2, ref3, ref4, resultArray, t, tr, transformationList, + var ifParam, j, len, paramList, ref, ref1, ref2, ref3, ref4, resultArray, t, transformationList, transformationString, transformations, value, variables, vars; resultArray = this.chained.map(tr => tr.serialize()); paramList = this.keys(); @@ -413,7 +409,7 @@ var TransformationBase = class TransformationBase { * @return PlainObject */ toHtmlAttributes() { - var attrName, height, j, key, len, options, ref, ref1, ref2, ref3, value, width; + var attrName, height, key, options, ref2, ref3, value, width; options = {}; for (key in this.otherOptions) { value = this.otherOptions[key]; diff --git a/src/util/baseutil.js b/src/util/baseutil.js index ef3e3a6a..c2fb681d 100644 --- a/src/util/baseutil.js +++ b/src/util/baseutil.js @@ -3,6 +3,7 @@ */ import {isString} from "../util"; import {isEmpty} from "../util"; +import {identity} from "../util"; /** * Return true if all items in list are strings @@ -10,14 +11,7 @@ import {isEmpty} from "../util"; * @param {Array} list - an array of items */ export var allStrings = function(list) { - var item, j, len; - for (j = 0, len = list.length; j < len; j++) { - item = list[j]; - if (!isString(item)) { - return false; - } - } - return true; + return list.length && list.every(isString); }; /** @@ -28,16 +22,7 @@ export var allStrings = function(list) { * @return {Array} a new array made of the original array's items except for `item` */ export var without = function(array, item) { - var i, length, newArray; - newArray = []; - i = -1; - length = array.length; - while (++i < length) { - if (array[i] !== item) { - newArray.push(array[i]); - } - } - return newArray; + return array.filter(v=>v!==item); }; /** @@ -80,7 +65,7 @@ export var smartEscape = function(string, unsafe = /([^a-zA-Z0-9_.\-\/:]+)/g) { */ export var defaults = function(destination, ...sources) { return sources.reduce(function(dest, source) { - var key, value; + let key, value; for (key in source) { value = source[key]; if (dest[key] === void 0) { @@ -160,51 +145,30 @@ export var reWords = (function() { /** * Convert string to camelCase * @function Util.camelCase -* @param {string} string - the string to convert +* @param {string} source - the string to convert * @return {string} in camelCase format */ export var camelCase = function(source) { - var i, word, words; - words = source.match(reWords); - words = (function() { - var j, len, results; - results = []; - for (i = j = 0, len = words.length; j < len; i = ++j) { - word = words[i]; - word = word.toLocaleLowerCase(); - if (i) { - results.push(word.charAt(0).toLocaleUpperCase() + word.slice(1)); - } else { - results.push(word); - } - } - return results; - })(); + var words = source.match(reWords); + words = words.map(word=> word.charAt(0).toLocaleUpperCase() + word.slice(1).toLocaleLowerCase()); + words[0] = words[0].toLocaleLowerCase(); + return words.join(''); }; /** * Convert string to snake_case * @function Util.snakeCase - * @param {string} string - the string to convert + * @param {string} source - the string to convert * @return {string} in snake_case format */ export var snakeCase = function(source) { - var i, word, words; - words = source.match(reWords); - words = (function() { - var j, len, results; - results = []; - for (i = j = 0, len = words.length; j < len; i = ++j) { - word = words[i]; - results.push(word.toLocaleLowerCase()); - } - return results; - })(); + var words = source.match(reWords); + words = words.map(word=> word.toLocaleLowerCase()); return words.join('_'); }; -export var convertKeys = function(source, converter = Util.identity) { +export var convertKeys = function(source, converter = identity) { var key, result, value; result = {}; for (key in source) { @@ -224,7 +188,7 @@ export var convertKeys = function(source, converter = Util.identity) { * @return {Object} a new object */ export var withCamelCaseKeys = function(source) { - return convertKeys(source, Util.camelCase); + return convertKeys(source, camelCase); }; /** @@ -234,7 +198,7 @@ export var withCamelCaseKeys = function(source) { * @return {Object} a new object */ export var withSnakeCaseKeys = function(source) { - return convertKeys(source, Util.snakeCase); + return convertKeys(source, snakeCase); }; // Browser @@ -255,15 +219,13 @@ export var base64Encode = typeof btoa !== 'undefined' && isFunction(btoa) ? btoa * @param {string} url - the url to encode. the value is URIdecoded and then re-encoded before converting to base64 representation * @return {string} the base64 representation of the URL */ -export var base64EncodeURL = function(input) { - var ignore; +export var base64EncodeURL = function(url) { try { - input = decodeURI(input); - } catch (error) { - ignore = error; + url = decodeURI(url); + } finally { + url = encodeURI(url); } - input = encodeURI(input); - return base64Encode(input); + return base64Encode(url); }; /** diff --git a/src/util/firstNotNull.js b/src/util/firstNotNull.js new file mode 100644 index 00000000..1aa77781 --- /dev/null +++ b/src/util/firstNotNull.js @@ -0,0 +1,16 @@ +/** + * Return the first argument whose value is not null + * @param args + * @returns {*} + */ +let firstNotNull = function firstNotNull(...args) { + while(args && args.length > 0) { + let next = args.shift(); + if( next != null){ + return next; + } + } + return null; +}; + +export default firstNotNull; diff --git a/src/util/lodash.js b/src/util/lodash.js index d76ecde7..2db50d17 100644 --- a/src/util/lodash.js +++ b/src/util/lodash.js @@ -81,7 +81,6 @@ export * from './baseutil'; * @function Util.getData */ export var getData = function (element, name) { - var ref; switch (false) { case !(element == null): return void 0; @@ -107,7 +106,6 @@ export var getData = function (element, name) { * */ export var setData = function (element, name, value) { - var ref; switch (false) { case !(element == null): return void 0; diff --git a/src/util/srcsetUtils.js b/src/util/srcsetUtils.js index 9f3e836c..31ab4d7a 100644 --- a/src/util/srcsetUtils.js +++ b/src/util/srcsetUtils.js @@ -1,4 +1,3 @@ -import ensurePresenceOf from './ensurePresenceOf'; import * as utils from '../util'; const isEmpty = utils.isEmpty; import generateBreakpoints from './generateBreakpoints'; diff --git a/webpack.config.js b/webpack.config.js index 2e17a351..bb5ed076 100644 --- a/webpack.config.js +++ b/webpack.config.js @@ -2,7 +2,7 @@ var path = require('path'); var TerserPlugin = require('terser-webpack-plugin'); var webpack = require('webpack'); var fs = require('fs'); -var package = require('./package.json'); +var pkg = require('./package.json'); // Create a list of Class names to preserve when minifying var namespace = fs.readFileSync('./src/namespace/cloudinary-jquery-file-upload.js').toString(); var reserved = namespace.match(/(?<=as )(\w+)/g); @@ -96,7 +96,7 @@ module.exports = function (env, argv) { new webpack.BannerPlugin({ banner: `/** * cloudinary-[name].js - * Cloudinary's JavaScript library - Version ${package.version} + * Cloudinary's JavaScript library - Version ${pkg.version} * Copyright Cloudinary * see https://github.com/cloudinary/cloudinary_js *