diff --git a/package-lock.json b/package-lock.json index d73285bc94..8b3dad9900 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8667,6 +8667,12 @@ "integrity": "sha1-gV7R9uvGWSb4ZbMQwHE7yzMVzks=", "dev": true }, + "prettier": { + "version": "1.10.1", + "resolved": "https://registry.npmjs.org/prettier/-/prettier-1.10.1.tgz", + "integrity": "sha512-lPTx4BsvN5v9w/JXBRNlvTXCJBKrr7VW4NOl1rdX00x+YuOLqNYAOGk2x7v+4PI4hx/SyW1Z3AEg9MeB87yYcQ==", + "dev": true + }, "pretty-error": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/pretty-error/-/pretty-error-2.1.1.tgz", diff --git a/package.json b/package.json index d3ea74c4b9..afffbb0494 100644 --- a/package.json +++ b/package.json @@ -25,7 +25,6 @@ "babel-core": "^6.24.1", "babel-loader": "^7.0.0", "babel-plugin-transform-object-rest-spread": "^6.26.0", - "promise-polyfill": "^6.0.2", "babel-preset-env": "^1.6.1", "chai": "^4.1.2", "cross-env": "^5.0.5", @@ -37,6 +36,8 @@ "jsdom": "^11.2.0", "mocha": "^3.1.2", "node-sass": "^4.5.3", + "prettier": "1.10.1", + "promise-polyfill": "^6.0.2", "sinon": "^3.2.1", "string-replace-loader": "^1.3.0", "webpack": "^3.5.5", @@ -81,6 +82,7 @@ "build:css": "node-sass src/styles/scss/main.scss dist/css/grapes.min.css --output-style compressed", "v:patch": "npm version --no-git-tag-version patch", "start": "npm run build:css -- -w & webpack-dev-server --open --progress --colors", + "format": "prettier --single-quote --write './{src,test}/**/*.js'", "test": "cross-env NODE_PATH=./src mocha --compilers js:babel-core/register --require test/helper.js --timeout 10000 --recursive test/main.js", "test:dev": "npm test -- -R min -w" } diff --git a/src/asset_manager/index.js b/src/asset_manager/index.js index d38602e1ee..a39a8769e4 100644 --- a/src/asset_manager/index.js +++ b/src/asset_manager/index.js @@ -47,7 +47,6 @@ module.exports = () => { let assets, am, fu; return { - /** * Name of the module * @type {String} @@ -75,8 +74,7 @@ module.exports = () => { c = config || {}; for (let name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } const ppfx = c.pStylePrefix; @@ -92,19 +90,19 @@ module.exports = () => { // Collection visible in asset manager collection: new Assets([]), globalCollection: assets, - config: c, + config: c }; fu = new FileUpload(obj); obj.fu = fu; am = new AssetsView(obj); // Setup the sync between the global and public collections - assets.listenTo(assets, 'add', (model) => { + assets.listenTo(assets, 'add', model => { this.getAllVisible().add(model); em && em.trigger('asset:add', model); }); - assets.listenTo(assets, 'remove', (model) => { + assets.listenTo(assets, 'remove', model => { this.getAllVisible().remove(model); em && em.trigger('asset:remove', model); }); @@ -136,7 +134,6 @@ module.exports = () => { * }]); */ add(asset, opts = {}) { - // Put the model at the beginning if (typeof opts.at == 'undefined') { opts.at = 0; @@ -153,7 +150,7 @@ module.exports = () => { * var asset = assetManager.get('http://img.jpg'); */ get(src) { - return assets.where({src})[0]; + return assets.where({ src })[0]; }, /** @@ -196,8 +193,7 @@ module.exports = () => { var obj = {}; var assets = JSON.stringify(this.getAll().toJSON()); obj[this.storageKey] = assets; - if(!noStore && c.stm) - c.stm.store(obj); + if (!noStore && c.stm) c.stm.store(obj); return obj; }, @@ -219,7 +215,7 @@ module.exports = () => { if (typeof assets == 'string') { try { assets = JSON.parse(data[name]); - } catch(err) {} + } catch (err) {} } if (assets && assets.length) { @@ -357,7 +353,6 @@ module.exports = () => { */ onDblClick(func) { c.onDblClick = func; - }, - + } }; }; diff --git a/src/asset_manager/model/Asset.js b/src/asset_manager/model/Asset.js index 8eaa01ec51..2a3a623d47 100644 --- a/src/asset_manager/model/Asset.js +++ b/src/asset_manager/model/Asset.js @@ -1,10 +1,9 @@ module.exports = require('backbone').Model.extend({ - idAttribute: 'src', defaults: { - type: '', - src: '', + type: '', + src: '' }, /** @@ -13,7 +12,9 @@ module.exports = require('backbone').Model.extend({ * @private * */ getFilename() { - return this.get('src').split('/').pop(); + return this.get('src') + .split('/') + .pop(); }, /** @@ -22,7 +23,8 @@ module.exports = require('backbone').Model.extend({ * @private * */ getExtension() { - return this.getFilename().split('.').pop(); - }, - + return this.getFilename() + .split('.') + .pop(); + } }); diff --git a/src/asset_manager/model/AssetImage.js b/src/asset_manager/model/AssetImage.js index f43bd092d1..137112e8ef 100644 --- a/src/asset_manager/model/AssetImage.js +++ b/src/asset_manager/model/AssetImage.js @@ -1,12 +1,11 @@ const Asset = require('./Asset'); module.exports = Asset.extend({ - - defaults: { ...Asset.prototype.defaults, + defaults: { + ...Asset.prototype.defaults, type: 'image', unitDim: 'px', height: 0, - width: 0, - }, - + width: 0 + } }); diff --git a/src/asset_manager/model/Assets.js b/src/asset_manager/model/Assets.js index e6343b255f..204aa5c2f1 100644 --- a/src/asset_manager/model/Assets.js +++ b/src/asset_manager/model/Assets.js @@ -1,18 +1,22 @@ import TypeableCollection from 'domain_abstract/model/TypeableCollection'; -module.exports = require('backbone').Collection.extend(TypeableCollection).extend({ - types: [{ - id: 'image', - model: require('./AssetImage'), - view: require('./../view/AssetImageView'), - isType(value) { - if (typeof value == 'string') { - return { - type: 'image', - src: value, +module.exports = require('backbone') + .Collection.extend(TypeableCollection) + .extend({ + types: [ + { + id: 'image', + model: require('./AssetImage'), + view: require('./../view/AssetImageView'), + isType(value) { + if (typeof value == 'string') { + return { + type: 'image', + src: value + }; } + return value; } - return value; } - }] -}); + ] + }); diff --git a/src/asset_manager/view/AssetImageView.js b/src/asset_manager/view/AssetImageView.js index 5adb5974c2..9e1708ed11 100644 --- a/src/asset_manager/view/AssetImageView.js +++ b/src/asset_manager/view/AssetImageView.js @@ -1,9 +1,8 @@ module.exports = require('./AssetView').extend({ - events: { 'click [data-toggle=asset-remove]': 'onRemove', click: 'onClick', - dblclick: 'onDblClick', + dblclick: 'onDblClick' }, getPreview() { @@ -32,7 +31,7 @@ module.exports = require('./AssetView').extend({ init(o) { const pfx = this.pfx; - this.className += ` ${pfx}asset-image`; + this.className += ` ${pfx}asset-image`; }, /** diff --git a/src/asset_manager/view/AssetView.js b/src/asset_manager/view/AssetView.js index 3d82353b16..3297ee8e54 100644 --- a/src/asset_manager/view/AssetView.js +++ b/src/asset_manager/view/AssetView.js @@ -1,5 +1,4 @@ module.exports = Backbone.View.extend({ - initialize(o = {}) { this.options = o; this.collection = o.collection; @@ -55,5 +54,5 @@ module.exports = Backbone.View.extend({ el.innerHTML = this.template(this, this.model); el.className = this.className; return this; - }, + } }); diff --git a/src/asset_manager/view/AssetsView.js b/src/asset_manager/view/AssetsView.js index d125dc1b59..038130f22c 100644 --- a/src/asset_manager/view/AssetsView.js +++ b/src/asset_manager/view/AssetsView.js @@ -3,9 +3,8 @@ var AssetImageView = require('./AssetImageView'); var FileUploader = require('./FileUploader'); module.exports = Backbone.View.extend({ - events: { - submit: 'handleSubmit', + submit: 'handleSubmit' }, template(view) { @@ -66,7 +65,7 @@ module.exports = Backbone.View.extend({ if (handleAdd) { handleAdd(url); } else { - this.options.globalCollection.add(url, {at: 0}); + this.options.globalCollection.add(url, { at: 0 }); } }, @@ -86,7 +85,7 @@ module.exports = Backbone.View.extend({ * @private */ getAddInput() { - if(!this.inputUrl || !this.inputUrl.value) + if (!this.inputUrl || !this.inputUrl.value) this.inputUrl = this.el.querySelector(`.${this.pfx}add-asset input`); return this.inputUrl; }, @@ -127,11 +126,11 @@ module.exports = Backbone.View.extend({ const rendered = new model.typeView({ model, collection, - config, + config }).render().el; if (fragment) { - fragment.appendChild( rendered ); + fragment.appendChild(rendered); } else { const assetsEl = this.getAssetsEl(); if (assetsEl) { @@ -172,7 +171,7 @@ module.exports = Backbone.View.extend({ const assets = this.$el.find(`.${this.pfx}assets`); assets.empty(); this.toggleNoAssets(this.collection.length); - this.collection.each((model) => this.addAsset(model, fragment)); + this.collection.each(model => this.addAsset(model, fragment)); assets.append(fragment); }, diff --git a/src/asset_manager/view/FileUploader.js b/src/asset_manager/view/FileUploader.js index c3c02feab9..54291dca19 100644 --- a/src/asset_manager/view/FileUploader.js +++ b/src/asset_manager/view/FileUploader.js @@ -1,8 +1,8 @@ import fetch from 'utils/fetch'; -module.exports = Backbone.View.extend({ - - template: _.template(` +module.exports = Backbone.View.extend( + { + template: _.template(`
<%= title %>
multiple/> @@ -10,307 +10,318 @@ module.exports = Backbone.View.extend({
`), - events: {}, - - initialize(opts = {}) { - this.options = opts; - const c = opts.config || {}; - this.config = c; - this.pfx = c.stylePrefix || ''; - this.ppfx = c.pStylePrefix || ''; - this.target = this.options.globalCollection || {}; - this.uploadId = this.pfx + 'uploadFile'; - this.disabled = c.disableUpload !== undefined ? c.disableUpload : !c.upload && !c.embedAsBase64; - this.events['change #' + this.uploadId] = 'uploadFile'; - let uploadFile = c.uploadFile; - - if (uploadFile) { - this.uploadFile = uploadFile.bind(this); - } else if (c.embedAsBase64) { - this.uploadFile = this.constructor.embedAsBase64; - } - - this.delegateEvents(); - }, - - /** - * Triggered before the upload is started - * @private - */ - onUploadStart() { - const em = this.config.em; - em && em.trigger('asset:upload:start'); - }, - - /** - * Triggered after the upload is ended - * @param {Object|string} res End result - * @private - */ - onUploadEnd(res) { - const em = this.config.em; - em && em.trigger('asset:upload:end', res); - }, - - /** - * Triggered on upload error - * @param {Object} err Error - * @private - */ - onUploadError(err) { - const em = this.config.em; - console.error(err); - this.onUploadEnd(err); - em && em.trigger('asset:upload:error', err); - }, - - /** - * Triggered on upload response - * @param {string} text Response text - * @private - */ - onUploadResponse(text) { - const em = this.config.em; - const config = this.config; - const target = this.target; - const json = typeof text === 'string' ? JSON.parse(text) : text; - em && em.trigger('asset:upload:response', json); - - if (config.autoAdd && target) { - target.add(json.data, {at: 0}); - } - - this.onUploadEnd(text); - }, + events: {}, + + initialize(opts = {}) { + this.options = opts; + const c = opts.config || {}; + this.config = c; + this.pfx = c.stylePrefix || ''; + this.ppfx = c.pStylePrefix || ''; + this.target = this.options.globalCollection || {}; + this.uploadId = this.pfx + 'uploadFile'; + this.disabled = + c.disableUpload !== undefined + ? c.disableUpload + : !c.upload && !c.embedAsBase64; + this.events['change #' + this.uploadId] = 'uploadFile'; + let uploadFile = c.uploadFile; + + if (uploadFile) { + this.uploadFile = uploadFile.bind(this); + } else if (c.embedAsBase64) { + this.uploadFile = this.constructor.embedAsBase64; + } - /** - * Upload files - * @param {Object} e Event - * @return {Promise} - * @private - * */ - uploadFile(e) { - const files = e.dataTransfer ? e.dataTransfer.files : e.target.files; - const body = new FormData(); - const config = this.config; - const params = config.params; - - for (let i = 0; i < files.length; i++) { - body.append(`${config.uploadName}[]`, files[i]); - } + this.delegateEvents(); + }, + + /** + * Triggered before the upload is started + * @private + */ + onUploadStart() { + const em = this.config.em; + em && em.trigger('asset:upload:start'); + }, + + /** + * Triggered after the upload is ended + * @param {Object|string} res End result + * @private + */ + onUploadEnd(res) { + const em = this.config.em; + em && em.trigger('asset:upload:end', res); + }, + + /** + * Triggered on upload error + * @param {Object} err Error + * @private + */ + onUploadError(err) { + const em = this.config.em; + console.error(err); + this.onUploadEnd(err); + em && em.trigger('asset:upload:error', err); + }, + + /** + * Triggered on upload response + * @param {string} text Response text + * @private + */ + onUploadResponse(text) { + const em = this.config.em; + const config = this.config; + const target = this.target; + const json = typeof text === 'string' ? JSON.parse(text) : text; + em && em.trigger('asset:upload:response', json); + + if (config.autoAdd && target) { + target.add(json.data, { at: 0 }); + } - for (let param in params) { - body.append(param, params[param]); - } + this.onUploadEnd(text); + }, + + /** + * Upload files + * @param {Object} e Event + * @return {Promise} + * @private + * */ + uploadFile(e) { + const files = e.dataTransfer ? e.dataTransfer.files : e.target.files; + const body = new FormData(); + const config = this.config; + const params = config.params; + + for (let i = 0; i < files.length; i++) { + body.append(`${config.uploadName}[]`, files[i]); + } - var target = this.target; - const url = config.upload; - const headers = config.headers; - const reqHead = 'X-Requested-With'; + for (let param in params) { + body.append(param, params[param]); + } - if (typeof headers[reqHead] == 'undefined') { - headers[reqHead] = 'XMLHttpRequest'; - } + var target = this.target; + const url = config.upload; + const headers = config.headers; + const reqHead = 'X-Requested-With'; - if (url) { - this.onUploadStart(); - return fetch(url, { - method: 'post', - credentials: 'include', - headers, - body, - }).then(res => (res.status/200|0) == 1 ? - res.text() : res.text().then((text) => - Promise.reject(text) - )) - .then((text) => this.onUploadResponse(text)) - .catch(err => this.onUploadError(err)); - } - }, - - /** - * Make input file droppable - * @private - * */ - initDrop() { - var that = this; - if(!this.uploadForm){ - this.uploadForm = this.$el.find('form').get(0); - if( 'draggable' in this.uploadForm ){ - var uploadFile = this.uploadFile; - this.uploadForm.ondragover = function(){ - this.className = that.pfx + 'hover'; - return false; - }; - this.uploadForm.ondragleave = function(){ - this.className = ''; - return false; - }; - this.uploadForm.ondrop = function(e){ - this.className = ''; - e.preventDefault(); - that.uploadFile(e); - return; - }; + if (typeof headers[reqHead] == 'undefined') { + headers[reqHead] = 'XMLHttpRequest'; } - } - }, - initDropzone(ev) { - let addedCls = 0; - const c = this.config; - const em = ev.model; - const edEl = ev.el; - const editor = em.get('Editor'); - const container = em.get('Config').el; - const frameEl = em.get('Canvas').getBody(); - const ppfx = this.ppfx; - const updatedCls = `${ppfx}dropzone-active`; - const dropzoneCls = `${ppfx}dropzone`; - const cleanEditorElCls = () => { - edEl.className = edEl.className.replace(updatedCls, '').trim(); - addedCls = 0; - } - const onDragOver = () => { - if (!addedCls) { - edEl.className += ` ${updatedCls}`; - addedCls = 1; + if (url) { + this.onUploadStart(); + return fetch(url, { + method: 'post', + credentials: 'include', + headers, + body + }) + .then( + res => + ((res.status / 200) | 0) == 1 + ? res.text() + : res.text().then(text => Promise.reject(text)) + ) + .then(text => this.onUploadResponse(text)) + .catch(err => this.onUploadError(err)); } - return false; - }; - const onDragLeave = () => { - cleanEditorElCls(); - return false; - }; - const onDrop = (e) => { + }, + + /** + * Make input file droppable + * @private + * */ + initDrop() { + var that = this; + if (!this.uploadForm) { + this.uploadForm = this.$el.find('form').get(0); + if ('draggable' in this.uploadForm) { + var uploadFile = this.uploadFile; + this.uploadForm.ondragover = function() { + this.className = that.pfx + 'hover'; + return false; + }; + this.uploadForm.ondragleave = function() { + this.className = ''; + return false; + }; + this.uploadForm.ondrop = function(e) { + this.className = ''; + e.preventDefault(); + that.uploadFile(e); + return; + }; + } + } + }, + + initDropzone(ev) { + let addedCls = 0; + const c = this.config; + const em = ev.model; + const edEl = ev.el; + const editor = em.get('Editor'); + const container = em.get('Config').el; + const frameEl = em.get('Canvas').getBody(); + const ppfx = this.ppfx; + const updatedCls = `${ppfx}dropzone-active`; + const dropzoneCls = `${ppfx}dropzone`; + const cleanEditorElCls = () => { + edEl.className = edEl.className.replace(updatedCls, '').trim(); + addedCls = 0; + }; + const onDragOver = () => { + if (!addedCls) { + edEl.className += ` ${updatedCls}`; + addedCls = 1; + } + return false; + }; + const onDragLeave = () => { + cleanEditorElCls(); + return false; + }; + const onDrop = e => { + cleanEditorElCls(); + e.preventDefault(); + e.stopPropagation(); + this.uploadFile(e); + + if (c.openAssetsOnDrop && editor) { + const target = editor.getSelected(); + editor.runCommand('open-assets', { + target, + onSelect() { + editor.Modal.close(); + editor.AssetManager.setTarget(null); + } + }); + } + + return false; + }; + + ev.$el.append(`
${c.dropzoneContent}
`); cleanEditorElCls(); - e.preventDefault(); - e.stopPropagation(); - this.uploadFile(e); - - if (c.openAssetsOnDrop && editor) { - const target = editor.getSelected(); - editor.runCommand('open-assets', { - target, - onSelect() { - editor.Modal.close(); - editor.AssetManager.setTarget(null); - } + + if ('draggable' in edEl) { + [edEl, frameEl].forEach(item => { + item.ondragover = onDragOver; + item.ondragleave = onDragLeave; + item.ondrop = onDrop; }); } - - return false; - }; - - ev.$el.append(`
${c.dropzoneContent}
`); - cleanEditorElCls(); - - if ('draggable' in edEl) { - [edEl, frameEl].forEach((item) => { - item.ondragover = onDragOver; - item.ondragleave = onDragLeave; - item.ondrop = onDrop; - }); + }, + + render() { + this.$el.html( + this.template({ + title: this.config.uploadText, + uploadId: this.uploadId, + disabled: this.disabled, + pfx: this.pfx + }) + ); + this.initDrop(); + this.$el.attr('class', this.pfx + 'file-uploader'); + return this; } }, + { + embedAsBase64: function(e) { + // List files dropped + const files = e.dataTransfer ? e.dataTransfer.files : e.target.files; + const response = { data: [] }; + + // Unlikely, widely supported now + if (!FileReader) { + this.onUploadError( + new Error('Unsupported platform, FileReader is not defined') + ); + return; + } - render() { - this.$el.html( this.template({ - title: this.config.uploadText, - uploadId: this.uploadId, - disabled: this.disabled, - pfx: this.pfx - }) ); - this.initDrop(); - this.$el.attr('class', this.pfx + 'file-uploader'); - return this; - }, - -}, { - embedAsBase64: function (e) { - // List files dropped - const files = e.dataTransfer ? e.dataTransfer.files : e.target.files; - const response = { data: [] }; - - // Unlikely, widely supported now - if (!FileReader) { - this.onUploadError(new Error('Unsupported platform, FileReader is not defined')); - return; - } - - const promises = []; - const mimeTypeMatcher = /^(.+)\/(.+)$/; - - for (const file of files) { - // For each file a reader (to read the base64 URL) - // and a promise (to track and merge results and errors) - const promise = new Promise((resolve, reject) => { - const reader = new FileReader(); - reader.addEventListener('load', (event) => { - let type; - const name = file.name; - - // Try to find the MIME type of the file. - const match = mimeTypeMatcher.exec(file.type); - if (match) { - type = match[1]; // The first part in the MIME, "image" in image/png - } else { - type = file.type; - } - - // If it's an image, try to find its size - if (type === 'image') { - const data = { - src: reader.result, - name, - type, - height: 0, - width: 0 - }; - - const image = new Image(); - image.addEventListener('error', (error) => { - reject(error); - }); - image.addEventListener('load', () => { - data.height = image.height; - data.width = image.width; - resolve(data); - }); - image.src = data.src; - - } else if (type) { - // Not an image, but has a type - resolve({ - src: reader.result, - name, - type - }); - } else { - // No type found, resolve with the URL only - resolve(reader.result); - } - }); - reader.addEventListener('error', (error) => { - reject(error); - }); - reader.addEventListener('abort', (error) => { - reject('Aborted'); + const promises = []; + const mimeTypeMatcher = /^(.+)\/(.+)$/; + + for (const file of files) { + // For each file a reader (to read the base64 URL) + // and a promise (to track and merge results and errors) + const promise = new Promise((resolve, reject) => { + const reader = new FileReader(); + reader.addEventListener('load', event => { + let type; + const name = file.name; + + // Try to find the MIME type of the file. + const match = mimeTypeMatcher.exec(file.type); + if (match) { + type = match[1]; // The first part in the MIME, "image" in image/png + } else { + type = file.type; + } + + // If it's an image, try to find its size + if (type === 'image') { + const data = { + src: reader.result, + name, + type, + height: 0, + width: 0 + }; + + const image = new Image(); + image.addEventListener('error', error => { + reject(error); + }); + image.addEventListener('load', () => { + data.height = image.height; + data.width = image.width; + resolve(data); + }); + image.src = data.src; + } else if (type) { + // Not an image, but has a type + resolve({ + src: reader.result, + name, + type + }); + } else { + // No type found, resolve with the URL only + resolve(reader.result); + } + }); + reader.addEventListener('error', error => { + reject(error); + }); + reader.addEventListener('abort', error => { + reject('Aborted'); + }); + + reader.readAsDataURL(file); }); - reader.readAsDataURL(file); - }); + promises.push(promise); + } - promises.push(promise); + Promise.all(promises).then( + data => { + response.data = data; + this.onUploadResponse(response); + }, + error => { + this.onUploadError(error); + } + ); } - - Promise - .all(promises) - .then((data) => { - response.data = data; - this.onUploadResponse(response); - }, (error) => { - this.onUploadError(error); - }); } -}); +); diff --git a/src/block_manager/config/config.js b/src/block_manager/config/config.js index 3d8331e1ec..9a66db0023 100644 --- a/src/block_manager/config/config.js +++ b/src/block_manager/config/config.js @@ -1,7 +1,5 @@ module.exports = { - blocks: [], - appendTo: '', - + appendTo: '' }; diff --git a/src/block_manager/index.js b/src/block_manager/index.js index c7edca7b80..ea7e844f55 100644 --- a/src/block_manager/index.js +++ b/src/block_manager/index.js @@ -30,201 +30,201 @@ */ module.exports = () => { var c = {}, - defaults = require('./config/config'), - Blocks = require('./model/Blocks'), - BlockCategories = require('./model/Categories'), - BlocksView = require('./view/BlocksView'); + defaults = require('./config/config'), + Blocks = require('./model/Blocks'), + BlockCategories = require('./model/Categories'), + BlocksView = require('./view/BlocksView'); var blocks, blocksVisible, blocksView; var categories = []; return { - - /** - * Name of the module - * @type {String} - * @private - */ - name: 'BlockManager', - - /** - * Initialize module. Automatically called with a new instance of the editor - * @param {Object} config Configurations - * @return {this} - * @private - */ - init(config) { - c = config || {}; - const em = c.em; - - for (let name in defaults) { - if (!(name in c)) { - c[name] = defaults[name]; - } - } - - // Global blocks collection - blocks = new Blocks([]); - blocksVisible = new Blocks([]); - categories = new BlockCategories(), - blocksView = new BlocksView({ - // Visible collection - collection: blocksVisible, - categories, - }, c); - - // Setup the sync between the global and public collections - blocks.listenTo(blocks, 'add', model => { - blocksVisible.add(model); - em && em.trigger('block:add', model); - }); - - blocks.listenTo(blocks, 'remove', model => { - blocksVisible.remove(model); - em && em.trigger('block:remove', model); - }); - - blocks.listenTo(blocks, 'reset', coll => { - blocksVisible.reset(coll.models); - }); - - return this; - }, - - /** - * Get configuration object - * @return {Object} - */ - getConfig() { - return c; - }, - - /** - * Load default blocks if the collection is empty - */ - onLoad() { - const blocks = this.getAll(); - !blocks.length && blocks.reset(c.blocks); - }, - - /** - * Add new block to the collection. - * @param {string} id Block id - * @param {Object} opts Options - * @param {string} opts.label Name of the block - * @param {string} opts.content HTML content - * @param {string|Object} opts.category Group the block inside a catgegory. - * You should pass objects with id property, eg: - * {id: 'some-uid', label: 'My category'} - * The string will be converted in: - * 'someid' => {id: 'someid', label: 'someid'} - * @param {Object} [opts.attributes={}] Block attributes - * @return {Block} Added block - * @example - * blockManager.add('h1-block', { - * label: 'Heading', - * content: '

Put your title here

', - * category: 'Basic', - * attributes: { - * title: 'Insert h1 block' - * } - * }); - */ - add(id, opts) { - var obj = opts || {}; - obj.id = id; - return blocks.add(obj); - }, - - /** - * Return the block by id - * @param {string} id Block id - * @example - * const block = blockManager.get('h1-block'); - * console.log(JSON.stringify(block)); - * // {label: 'Heading', content: '

Put your ...', ...} - */ - get(id) { - return blocks.get(id); - }, - - /** - * Return all blocks - * @return {Collection} - * @example - * const blocks = blockManager.getAll(); - * console.log(JSON.stringify(blocks)); - * // [{label: 'Heading', content: '

Put your ...'}, ...] - */ - getAll() { - return blocks; - }, - - /** - * Return the visible collection, which containes blocks actually rendered - * @return {Collection} - */ - getAllVisible() { - return blocksVisible; - }, - - /** - * Remove a block by id - * @param {string} id Block id - * @return {Block} Removed block - */ - remove(id) { - return blocks.remove(id); - }, - - /** - * Get all available categories. - * It's possible to add categories only within blocks via 'add()' method - * @return {Array|Collection} - */ - getCategories() { - return categories; - }, - - /** - * Return the Blocks container element - * @return {HTMLElement} - */ - getContainer() { - return blocksView.el; - }, - - /** - * Render blocks - * @param {Array} blocks Blocks to render, without the argument will render - * all global blocks - * @example - * // Render all blocks (inside the global collection) - * blockManager.render(); - * - * // Render new set of blocks - * const blocks = blockManager.getAll(); - * blockManager.render(blocks.filter( - * block => block.get('category') == 'sections' - * )); - * // Or a new set from an array - * blockManager.render([ - * {label: 'Label text', content: '
Content
'} - * ]); - * - * // Back to blocks from the global collection - * blockManager.render(); - */ - render(blocks) { - const toRender = blocks || this.getAll().models; - - if (!blocksView.rendered) { - blocksView.render(); - blocksView.rendered = 1; + /** + * Name of the module + * @type {String} + * @private + */ + name: 'BlockManager', + + /** + * Initialize module. Automatically called with a new instance of the editor + * @param {Object} config Configurations + * @return {this} + * @private + */ + init(config) { + c = config || {}; + const em = c.em; + + for (let name in defaults) { + if (!(name in c)) { + c[name] = defaults[name]; } - - blocksView.collection.reset(toRender); - }, - + } + + // Global blocks collection + blocks = new Blocks([]); + blocksVisible = new Blocks([]); + (categories = new BlockCategories()), + (blocksView = new BlocksView( + { + // Visible collection + collection: blocksVisible, + categories + }, + c + )); + + // Setup the sync between the global and public collections + blocks.listenTo(blocks, 'add', model => { + blocksVisible.add(model); + em && em.trigger('block:add', model); + }); + + blocks.listenTo(blocks, 'remove', model => { + blocksVisible.remove(model); + em && em.trigger('block:remove', model); + }); + + blocks.listenTo(blocks, 'reset', coll => { + blocksVisible.reset(coll.models); + }); + + return this; + }, + + /** + * Get configuration object + * @return {Object} + */ + getConfig() { + return c; + }, + + /** + * Load default blocks if the collection is empty + */ + onLoad() { + const blocks = this.getAll(); + !blocks.length && blocks.reset(c.blocks); + }, + + /** + * Add new block to the collection. + * @param {string} id Block id + * @param {Object} opts Options + * @param {string} opts.label Name of the block + * @param {string} opts.content HTML content + * @param {string|Object} opts.category Group the block inside a catgegory. + * You should pass objects with id property, eg: + * {id: 'some-uid', label: 'My category'} + * The string will be converted in: + * 'someid' => {id: 'someid', label: 'someid'} + * @param {Object} [opts.attributes={}] Block attributes + * @return {Block} Added block + * @example + * blockManager.add('h1-block', { + * label: 'Heading', + * content: '

Put your title here

', + * category: 'Basic', + * attributes: { + * title: 'Insert h1 block' + * } + * }); + */ + add(id, opts) { + var obj = opts || {}; + obj.id = id; + return blocks.add(obj); + }, + + /** + * Return the block by id + * @param {string} id Block id + * @example + * const block = blockManager.get('h1-block'); + * console.log(JSON.stringify(block)); + * // {label: 'Heading', content: '

Put your ...', ...} + */ + get(id) { + return blocks.get(id); + }, + + /** + * Return all blocks + * @return {Collection} + * @example + * const blocks = blockManager.getAll(); + * console.log(JSON.stringify(blocks)); + * // [{label: 'Heading', content: '

Put your ...'}, ...] + */ + getAll() { + return blocks; + }, + + /** + * Return the visible collection, which containes blocks actually rendered + * @return {Collection} + */ + getAllVisible() { + return blocksVisible; + }, + + /** + * Remove a block by id + * @param {string} id Block id + * @return {Block} Removed block + */ + remove(id) { + return blocks.remove(id); + }, + + /** + * Get all available categories. + * It's possible to add categories only within blocks via 'add()' method + * @return {Array|Collection} + */ + getCategories() { + return categories; + }, + + /** + * Return the Blocks container element + * @return {HTMLElement} + */ + getContainer() { + return blocksView.el; + }, + + /** + * Render blocks + * @param {Array} blocks Blocks to render, without the argument will render + * all global blocks + * @example + * // Render all blocks (inside the global collection) + * blockManager.render(); + * + * // Render new set of blocks + * const blocks = blockManager.getAll(); + * blockManager.render(blocks.filter( + * block => block.get('category') == 'sections' + * )); + * // Or a new set from an array + * blockManager.render([ + * {label: 'Label text', content: '
Content
'} + * ]); + * + * // Back to blocks from the global collection + * blockManager.render(); + */ + render(blocks) { + const toRender = blocks || this.getAll().models; + + if (!blocksView.rendered) { + blocksView.render(); + blocksView.rendered = 1; + } + + blocksView.collection.reset(toRender); + } }; - }; diff --git a/src/block_manager/model/Block.js b/src/block_manager/model/Block.js index 3e8b7d7ede..356091ea1e 100644 --- a/src/block_manager/model/Block.js +++ b/src/block_manager/model/Block.js @@ -2,12 +2,11 @@ var Backbone = require('backbone'); var Category = require('./Category'); module.exports = Backbone.Model.extend({ - defaults: { label: '', content: '', category: '', - attributes: {}, + attributes: {} }, initialize(opts = {}) { @@ -17,10 +16,9 @@ module.exports = Backbone.Model.extend({ if (typeof category == 'string') { var catObj = new Category({ id: category, - label: category, + label: category }); } } - }, - + } }); diff --git a/src/block_manager/model/Blocks.js b/src/block_manager/model/Blocks.js index 0522254e6c..30b9a039ab 100644 --- a/src/block_manager/model/Blocks.js +++ b/src/block_manager/model/Blocks.js @@ -2,5 +2,5 @@ var Backbone = require('backbone'); var Block = require('./Block'); module.exports = Backbone.Collection.extend({ - model: Block, + model: Block }); diff --git a/src/block_manager/model/Categories.js b/src/block_manager/model/Categories.js index cc0352ec17..849324aee9 100644 --- a/src/block_manager/model/Categories.js +++ b/src/block_manager/model/Categories.js @@ -1,5 +1,5 @@ var Backbone = require('backbone'); module.exports = Backbone.Collection.extend({ - model: require('./Category'), + model: require('./Category') }); diff --git a/src/block_manager/model/Category.js b/src/block_manager/model/Category.js index e969636e01..379151c572 100644 --- a/src/block_manager/model/Category.js +++ b/src/block_manager/model/Category.js @@ -1,12 +1,10 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - defaults: { id: '', label: '', open: true, - attributes: {}, - }, - + attributes: {} + } }); diff --git a/src/block_manager/view/BlockView.js b/src/block_manager/view/BlockView.js index b7891b0fca..950d370aca 100644 --- a/src/block_manager/view/BlockView.js +++ b/src/block_manager/view/BlockView.js @@ -1,7 +1,6 @@ -import {on, off} from 'utils/mixins'; +import { on, off } from 'utils/mixins'; module.exports = Backbone.View.extend({ - events: { mousedown: 'startDrag' }, @@ -23,7 +22,7 @@ module.exports = Backbone.View.extend({ return; } - if(!this.config.getSorter) { + if (!this.config.getSorter) { return; } @@ -56,8 +55,9 @@ module.exports = Backbone.View.extend({ const pfx = this.ppfx; const className = `${pfx}block`; el.className += ` ${className} ${pfx}one-bg ${pfx}four-color-h`; - el.innerHTML = `
${this.model.get('label')}
`; + el.innerHTML = `
${this.model.get( + 'label' + )}
`; return this; - }, - + } }); diff --git a/src/block_manager/view/BlocksView.js b/src/block_manager/view/BlocksView.js index e14663450e..c389650a36 100644 --- a/src/block_manager/view/BlocksView.js +++ b/src/block_manager/view/BlocksView.js @@ -3,7 +3,6 @@ var BlockView = require('./BlockView'); var CategoryView = require('./CategoryView'); module.exports = Backbone.View.extend({ - initialize(opts, config) { _.bindAll(this, 'getSorter', 'onDrag', 'onDrop'); this.config = config || {}; @@ -21,7 +20,7 @@ module.exports = Backbone.View.extend({ this.tac = 'test-tac'; this.grabbingCls = this.ppfx + 'grabbing'; - if(this.em){ + if (this.em) { this.config.getSorter = this.getSorter; this.canvas = this.em.get('Canvas'); } @@ -32,9 +31,8 @@ module.exports = Backbone.View.extend({ * @private */ getSorter() { - if(!this.em) - return; - if(!this.sorter){ + if (!this.em) return; + if (!this.sorter) { var utils = this.em.get('Utils'); var canvas = this.canvas; this.sorter = new utils.Sorter({ @@ -51,7 +49,7 @@ module.exports = Backbone.View.extend({ wmargin: 1, nested: 1, em: this.em, - canvasRelative: 1, + canvasRelative: 1 }); } return this.sorter; @@ -79,7 +77,7 @@ module.exports = Backbone.View.extend({ em.runDefault(); if (model && model.get) { - if(model.get('activeOnRender')) { + if (model.get('activeOnRender')) { model.trigger('active'); model.set('activeOnRender', 0); } @@ -105,10 +103,13 @@ module.exports = Backbone.View.extend({ * */ add(model, fragment) { var frag = fragment || null; - var view = new BlockView({ - model, - attributes: model.get('attributes'), - }, this.config); + var view = new BlockView( + { + model, + attributes: model.get('attributes') + }, + this.config + ); var rendered = view.render().el; var category = model.get('category'); @@ -128,9 +129,12 @@ module.exports = Backbone.View.extend({ model.set('category', catModel); if (!catView && categories) { - catView = new CategoryView({ - model: catModel - }, this.config).render(); + catView = new CategoryView( + { + model: catModel + }, + this.config + ).render(); this.renderedCategories[catId] = catView; categories.appendChild(catView.el); } @@ -139,10 +143,8 @@ module.exports = Backbone.View.extend({ return; } - if(frag) - frag.appendChild(rendered); - else - this.append(rendered); + if (frag) frag.appendChild(rendered); + else this.append(rendered); }, getCategoriesEl() { @@ -155,7 +157,9 @@ module.exports = Backbone.View.extend({ getBlocksEl() { if (!this.blocksEl) { - this.blocksEl = this.el.querySelector(`.${this.noCatClass} .${this.blockContClass}`); + this.blocksEl = this.el.querySelector( + `.${this.noCatClass} .${this.blockContClass}` + ); } return this.blocksEl; @@ -180,8 +184,7 @@ module.exports = Backbone.View.extend({ this.collection.each(model => this.add(model, frag)); this.append(frag); - this.$el.addClass(this.blockContClass + 's') + this.$el.addClass(this.blockContClass + 's'); return this; - }, - + } }); diff --git a/src/block_manager/view/CategoryView.js b/src/block_manager/view/CategoryView.js index fa6c811f0c..31372bf716 100644 --- a/src/block_manager/view/CategoryView.js +++ b/src/block_manager/view/CategoryView.js @@ -1,7 +1,6 @@ var Backbone = require('backbone'); module.exports = Backbone.View.extend({ - template: _.template(`
@@ -21,16 +20,14 @@ module.exports = Backbone.View.extend({ this.iconClass = `${pfx}caret-icon`; this.activeClass = `${pfx}open`; this.className = `${pfx}block-category`; - this.events[`click .${pfx}title`] = 'toggle'; + this.events[`click .${pfx}title`] = 'toggle'; this.listenTo(this.model, 'change:open', this.updateVisibility); this.delegateEvents(); }, updateVisibility() { - if(this.model.get('open')) - this.open(); - else - this.close(); + if (this.model.get('open')) this.open(); + else this.close(); }, open() { @@ -73,10 +70,10 @@ module.exports = Backbone.View.extend({ render() { this.el.innerHTML = this.template({ pfx: this.pfx, - label: this.model.get('label'), + label: this.model.get('label') }); this.el.className = this.className; this.updateVisibility(); return this; - }, + } }); diff --git a/src/canvas/config/config.js b/src/canvas/config/config.js index 084ac18daa..e69831d7ab 100644 --- a/src/canvas/config/config.js +++ b/src/canvas/config/config.js @@ -1,5 +1,4 @@ module.exports = { - stylePrefix: 'cv-', // Coming soon @@ -31,6 +30,5 @@ module.exports = { * return ComponentModel.getName(); * } */ - customBadgeLabel: '', - + customBadgeLabel: '' }; diff --git a/src/canvas/index.js b/src/canvas/index.js index 0f3f80dede..8e3398cf43 100644 --- a/src/canvas/index.js +++ b/src/canvas/index.js @@ -1,15 +1,14 @@ -import {on, off} from 'utils/mixins' +import { on, off } from 'utils/mixins'; module.exports = () => { var c = {}, - defaults = require('./config/config'), - Canvas = require('./model/Canvas'), - CanvasView = require('./view/CanvasView'); + defaults = require('./config/config'), + Canvas = require('./model/Canvas'), + CanvasView = require('./view/CanvasView'); var canvas; var frameRect; return { - /** * Used inside RTE * @private @@ -32,23 +31,20 @@ module.exports = () => { init(config) { c = config || {}; for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } var ppfx = c.pStylePrefix; - if(ppfx) - c.stylePrefix = ppfx + c.stylePrefix; + if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; canvas = new Canvas(config); - CanvasView = new CanvasView({ + CanvasView = new CanvasView({ model: canvas, - config: c, + config: c }); var cm = c.em.get('DomComponents'); - if(cm) - this.setWrapper(cm); + if (cm) this.setWrapper(cm); this.startAutoscroll = this.startAutoscroll.bind(this); this.stopAutoscroll = this.stopAutoscroll.bind(this); @@ -200,11 +196,11 @@ module.exports = () => { }, /** - * Get the offset of the element - * @param {HTMLElement} el - * @return {Object} - * @private - */ + * Get the offset of the element + * @param {HTMLElement} el + * @return {Object} + * @private + */ offset(el) { return CanvasView.offset(el); }, @@ -257,11 +253,11 @@ module.exports = () => { var elTop = pos.top - targetHeight; var elLeft = pos.left; elLeft += toRight ? pos.width : 0; - elLeft = toRight ? (elLeft - targetWidth) : elLeft; + elLeft = toRight ? elLeft - targetWidth : elLeft; var leftPos = elLeft < canvasPos.left ? canvasPos.left : elLeft; var topPos = elTop < canvasPos.top ? canvasPos.top : elTop; - topPos = topPos > (pos.top + pos.height) ? (pos.top + pos.height) : topPos; + topPos = topPos > pos.top + pos.height ? pos.top + pos.height : topPos; var result = { top: topPos, @@ -273,11 +269,11 @@ module.exports = () => { targetWidth: target.offsetWidth, targetHeight: target.offsetHeight, canvasTop: canvasPos.top, - canvasLeft: canvasPos.left, + canvasLeft: canvasPos.left }; // In this way I can catch data and also change the position strategy - if(eventToTrigger && c.em) { + if (eventToTrigger && c.em) { c.em.trigger(eventToTrigger, result); } @@ -311,7 +307,7 @@ module.exports = () => { return { y: e.clientY + addTop - yOffset, - x: e.clientX + addLeft - xOffset, + x: e.clientX + addLeft - xOffset }; }, @@ -331,7 +327,7 @@ module.exports = () => { return { y: e.clientY + addTop + yOffset, - x: e.clientX + addLeft + xOffset, + x: e.clientX + addLeft + xOffset }; }, @@ -371,11 +367,11 @@ module.exports = () => { let limitBottom = frameRect.height - limitTop; if (clientY < limitTop) { - nextTop -= (limitTop - clientY); + nextTop -= limitTop - clientY; } if (clientY > limitBottom) { - nextTop += (clientY - limitBottom); + nextTop += clientY - limitBottom; } //console.log(`actualTop: ${actualTop} clientY: ${clientY} nextTop: ${nextTop} frameHeigh: ${frameRect.height}`); @@ -404,6 +400,6 @@ module.exports = () => { */ getFrameWrapperEl() { return CanvasView.frame.getWrapper(); - }, + } }; }; diff --git a/src/canvas/model/Canvas.js b/src/canvas/model/Canvas.js index 6f4968364d..ce168885fc 100644 --- a/src/canvas/model/Canvas.js +++ b/src/canvas/model/Canvas.js @@ -2,16 +2,14 @@ var Backbone = require('backbone'); var Frame = require('./Frame'); module.exports = Backbone.Model.extend({ - - defaults :{ + defaults: { frame: '', wrapper: '', - rulers: false, + rulers: false }, initialize(config) { var conf = this.conf || {}; this.set('frame', new Frame(conf.frame)); - }, - + } }); diff --git a/src/canvas/model/Frame.js b/src/canvas/model/Frame.js index aa66331cdb..9c859ac0df 100644 --- a/src/canvas/model/Frame.js +++ b/src/canvas/model/Frame.js @@ -1,12 +1,10 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - - defaults :{ + defaults: { wrapper: '', width: '', height: '', - attributes: {}, - }, - + attributes: {} + } }); diff --git a/src/canvas/view/CanvasView.js b/src/canvas/view/CanvasView.js index b07320317d..a42b89d4db 100644 --- a/src/canvas/view/CanvasView.js +++ b/src/canvas/view/CanvasView.js @@ -2,14 +2,13 @@ const FrameView = require('./FrameView'); const $ = Backbone.$; module.exports = Backbone.View.extend({ - initialize(o) { _.bindAll(this, 'renderBody', 'onFrameScroll', 'clearOff'); - window.onscroll = this.clearOff + window.onscroll = this.clearOff; this.config = o.config || {}; this.em = this.config.em || {}; - this.ppfx = this.config.pStylePrefix || ''; - this.className = this.config.stylePrefix + 'canvas'; + this.ppfx = this.config.pStylePrefix || ''; + this.className = this.config.stylePrefix + 'canvas'; this.listenTo(this.em, 'change:canvasOffset', this.clearOff); this.frame = new FrameView({ model: this.model.get('frame'), @@ -17,7 +16,6 @@ module.exports = Backbone.View.extend({ }); }, - /** * Checks if the element is visible in the canvas's viewport * @param {HTMLElement} el @@ -28,8 +26,12 @@ module.exports = Backbone.View.extend({ const frameRect = this.getFrameOffset(1); const rTop = rect.top; const rLeft = rect.left; - return rTop >= 0 && rLeft >= 0 && - rTop <= frameRect.height && rLeft <= frameRect.width; + return ( + rTop >= 0 && + rLeft >= 0 && + rTop <= frameRect.height && + rLeft <= frameRect.width + ); }, /** @@ -49,26 +51,26 @@ module.exports = Backbone.View.extend({ * @private */ renderScripts() { - var frame = this.frame; - var that = this; - - frame.el.onload = () => { - var scripts = that.config.scripts.slice(0), // clone - counter = 0; - - function appendScript(scripts) { - if (scripts.length > 0) { - var script = document.createElement('script'); - script.type = 'text/javascript'; - script.src = scripts.shift(); - script.onerror = script.onload = appendScript.bind(null, scripts); - frame.el.contentDocument.head.appendChild(script); - } else { - that.renderBody(); - } + var frame = this.frame; + var that = this; + + frame.el.onload = () => { + var scripts = that.config.scripts.slice(0), // clone + counter = 0; + + function appendScript(scripts) { + if (scripts.length > 0) { + var script = document.createElement('script'); + script.type = 'text/javascript'; + script.src = scripts.shift(); + script.onerror = script.onload = appendScript.bind(null, scripts); + frame.el.contentDocument.head.appendChild(script); + } else { + that.renderBody(); } - appendScript(scripts); - }; + } + appendScript(scripts); + }; }, /** @@ -78,7 +80,7 @@ module.exports = Backbone.View.extend({ renderBody() { var wrap = this.model.get('frame').get('wrapper'); var em = this.config.em; - if(wrap) { + if (wrap) { var ppfx = this.ppfx; //var body = this.frame.$el.contents().find('body'); var body = $(this.frame.el.contentWindow.document.body); @@ -88,7 +90,7 @@ module.exports = Backbone.View.extend({ var protCss = conf.protectedCss; var externalStyles = ''; - confCanvas.styles.forEach((style) => { + confCanvas.styles.forEach(style => { externalStyles += ``; }); @@ -203,7 +205,7 @@ module.exports = Backbone.View.extend({ // the keyCode/which will be always `0`. Even if it's an old/deprecated // property keymaster (and many others) still use it... using `defineProperty` // hack seems the only way - const createCustomEvent = (e) => { + const createCustomEvent = e => { var oEvent = new KeyboardEvent(e.type, e); oEvent.keyCodeVal = e.keyCode; ['keyCode', 'which'].forEach(prop => { @@ -214,7 +216,7 @@ module.exports = Backbone.View.extend({ }); }); return oEvent; - } + }; fdoc.addEventListener('keydown', e => { doc.dispatchEvent(createCustomEvent(e)); }); @@ -236,7 +238,7 @@ module.exports = Backbone.View.extend({ top: rect.top + docBody.scrollTop, left: rect.left + docBody.scrollLeft, width: rect.width, - height: rect.height, + height: rect.height }; }, @@ -255,8 +257,7 @@ module.exports = Backbone.View.extend({ * @private */ getFrameOffset(force = 0) { - if(!this.frmOff || force) - this.frmOff = this.offset(this.frame.el); + if (!this.frmOff || force) this.frmOff = this.offset(this.frame.el); return this.frmOff; }, @@ -266,8 +267,7 @@ module.exports = Backbone.View.extend({ * @private */ getCanvasOffset() { - if(!this.cvsOff) - this.cvsOff = this.offset(this.el); + if (!this.cvsOff) this.cvsOff = this.offset(this.el); return this.cvsOff; }, @@ -316,7 +316,7 @@ module.exports = Backbone.View.extend({ * @private */ updateScript(view) { - if(!view.scriptContainer) { + if (!view.scriptContainer) { view.scriptContainer = $('
'); this.getJsContainer().append(view.scriptContainer.get(0)); } @@ -350,11 +350,10 @@ module.exports = Backbone.View.extend({ return this.jsContainer; }, - render() { - this.wrapper = this.model.get('wrapper'); + this.wrapper = this.model.get('wrapper'); - if(this.wrapper && typeof this.wrapper.render == 'function'){ + if (this.wrapper && typeof this.wrapper.render == 'function') { this.model.get('frame').set('wrapper', this.wrapper); this.$el.append(this.frame.render().el); var frame = this.frame; @@ -392,6 +391,5 @@ module.exports = Backbone.View.extend({ this.toolsEl = toolsEl; this.el.className = this.className; return this; - }, - + } }); diff --git a/src/canvas/view/FrameView.js b/src/canvas/view/FrameView.js index fd19711752..554a240f18 100644 --- a/src/canvas/view/FrameView.js +++ b/src/canvas/view/FrameView.js @@ -1,9 +1,9 @@ -import { bindAll } from 'underscore' +import { bindAll } from 'underscore'; -const motionsEv = 'transitionend oTransitionEnd transitionend webkitTransitionEnd'; +const motionsEv = + 'transitionend oTransitionEnd transitionend webkitTransitionEnd'; module.exports = require('backbone').View.extend({ - tagName: 'iframe', attributes: { @@ -58,8 +58,7 @@ module.exports = require('backbone').View.extend({ }, render() { - this.$el.attr({class: this.ppfx + 'frame'}); + this.$el.attr({ class: this.ppfx + 'frame' }); return this; - }, - + } }); diff --git a/src/code_manager/config/config.js b/src/code_manager/config/config.js index 215b6c02ef..c6b41a11d1 100644 --- a/src/code_manager/config/config.js +++ b/src/code_manager/config/config.js @@ -2,5 +2,5 @@ module.exports = { // Style prefix stylePrefix: 'cm-', - inlineCss: false, + inlineCss: false }; diff --git a/src/code_manager/index.js b/src/code_manager/index.js index 32beeada44..05ed2c7640 100644 --- a/src/code_manager/index.js +++ b/src/code_manager/index.js @@ -18,23 +18,21 @@ * @module CodeManager */ module.exports = () => { - var c = {}, - defaults = require('./config/config'), - gHtml = require('./model/HtmlGenerator'), - gCss = require('./model/CssGenerator'), - gJson = require('./model/JsonGenerator'), - gJs = require('./model/JsGenerator'), - eCM = require('./model/CodeMirrorEditor'), - editorView = require('./view/EditorView'); + defaults = require('./config/config'), + gHtml = require('./model/HtmlGenerator'), + gCss = require('./model/CssGenerator'), + gJson = require('./model/JsonGenerator'), + gJs = require('./model/JsGenerator'), + eCM = require('./model/CodeMirrorEditor'), + editorView = require('./view/EditorView'); var generators = {}, - defGenerators = {}, - viewers = {}, - defViewers = {}; + defGenerators = {}, + viewers = {}, + defViewers = {}; return { - getConfig() { return c; }, @@ -57,16 +55,14 @@ module.exports = () => { init(config) { c = config || {}; for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } var ppfx = c.pStylePrefix; - if(ppfx) - c.stylePrefix = ppfx + c.stylePrefix; + if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; defGenerators.html = new gHtml(); - defGenerators.css = new gCss(); + defGenerators.css = new gCss(); defGenerators.json = new gJson(); defGenerators.js = new gJs(); defViewers.CodeMirror = new eCM(); @@ -183,7 +179,7 @@ module.exports = () => { * */ getCode(model, genId, opt = {}) { opt.em = c.em; - var generator = this.getGenerator(genId); + var generator = this.getGenerator(genId); return generator ? generator.build(model, opt) : ''; }, @@ -193,8 +189,7 @@ module.exports = () => { * @private * */ loadDefaultGenerators() { - for (var id in defGenerators) - this.addGenerator(id, defGenerators[id]); + for (var id in defGenerators) this.addGenerator(id, defGenerators[id]); return this; }, @@ -205,12 +200,9 @@ module.exports = () => { * @private * */ loadDefaultViewers() { - for (var id in defViewers) - this.addViewer(id, defViewers[id]); + for (var id in defViewers) this.addViewer(id, defViewers[id]); return this; - }, - + } }; - }; diff --git a/src/code_manager/model/CodeMirrorEditor.js b/src/code_manager/model/CodeMirrorEditor.js index eb52076120..045f65f2bb 100644 --- a/src/code_manager/model/CodeMirrorEditor.js +++ b/src/code_manager/model/CodeMirrorEditor.js @@ -5,23 +5,22 @@ var cssMode = require('codemirror/mode/css/css'); var formatting = require('codemirror-formatting'); module.exports = Backbone.Model.extend({ - defaults: { - input : '', - label : '', - codeName : '', - theme : '', - readOnly : true, - lineNumbers : true, + input: '', + label: '', + codeName: '', + theme: '', + readOnly: true, + lineNumbers: true }, /** @inheritdoc */ init(el) { - this.editor = CodeMirror.fromTextArea(el, { + this.editor = CodeMirror.fromTextArea(el, { dragDrop: false, lineWrapping: true, mode: this.get('codeName'), - ...this.attributes, + ...this.attributes }); return this; @@ -29,14 +28,15 @@ module.exports = Backbone.Model.extend({ /** @inheritdoc */ setContent(v) { - if(!this.editor) - return; + if (!this.editor) return; this.editor.setValue(v); - if(this.editor.autoFormatRange){ + if (this.editor.autoFormatRange) { CodeMirror.commands.selectAll(this.editor); - this.editor.autoFormatRange(this.editor.getCursor(true), this.editor.getCursor(false) ); + this.editor.autoFormatRange( + this.editor.getCursor(true), + this.editor.getCursor(false) + ); CodeMirror.commands.goDocStart(this.editor); } - }, - + } }); diff --git a/src/code_manager/model/CssGenerator.js b/src/code_manager/model/CssGenerator.js index 1c0ddf6a89..37872a91e7 100644 --- a/src/code_manager/model/CssGenerator.js +++ b/src/code_manager/model/CssGenerator.js @@ -1,5 +1,4 @@ module.exports = require('backbone').Model.extend({ - initialize() { this.compCls = []; this.ids = []; @@ -30,11 +29,10 @@ module.exports = require('backbone').Model.extend({ } const components = model.components(); - components.each(model => code += this.buildFromModel(model, opts)); + components.each(model => (code += this.buildFromModel(model, opts))); return code; }, - build(model, opts = {}) { const cssc = opts.cssc; this.em = opts.em || ''; @@ -67,13 +65,12 @@ module.exports = require('backbone').Model.extend({ for (let media in mediaRules) { let rulesStr = ''; const mRules = mediaRules[media]; - mRules.forEach(rule => rulesStr += this.buildFromRule(rule)); + mRules.forEach(rule => (rulesStr += this.buildFromRule(rule))); if (rulesStr) { code += `@media ${media}{${rulesStr}}`; } } - } return code; @@ -87,7 +84,7 @@ module.exports = require('backbone').Model.extend({ buildFromRule(rule) { let result = ''; const selectorStr = rule.selectorsToString(); - const selectorStrNoAdd = rule.selectorsToString({skipAdd: 1}); + const selectorStrNoAdd = rule.selectorsToString({ skipAdd: 1 }); let found; // This will not render a rule if there is no its component @@ -107,6 +104,5 @@ module.exports = require('backbone').Model.extend({ } return result; - }, - + } }); diff --git a/src/code_manager/model/HtmlGenerator.js b/src/code_manager/model/HtmlGenerator.js index d7087cbfaa..84559412e6 100644 --- a/src/code_manager/model/HtmlGenerator.js +++ b/src/code_manager/model/HtmlGenerator.js @@ -1,13 +1,13 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - build(model, opts = {}) { const models = model.get('components'); if (opts.exportWrapper) { - return opts.wrappesIsBody ? - `${this.buildModels(models)}` : model.toHTML(); + return opts.wrappesIsBody + ? `${this.buildModels(models)}` + : model.toHTML(); } return this.buildModels(models); @@ -20,5 +20,4 @@ module.exports = Backbone.Model.extend({ }); return code; } - }); diff --git a/src/code_manager/model/JsGenerator.js b/src/code_manager/model/JsGenerator.js index ac8a0d530f..4c1116e7ae 100644 --- a/src/code_manager/model/JsGenerator.js +++ b/src/code_manager/model/JsGenerator.js @@ -1,31 +1,30 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - mapModel(model) { var code = ''; - var script = model.get('script'); - var type = model.get('type'); - var comps = model.get('components'); + var script = model.get('script'); + var type = model.get('type'); + var comps = model.get('components'); var id = model.getId(); if (script) { // If the component has scripts we need to expose his ID var attr = model.get('attributes'); - attr = _.extend({}, attr, {id}); + attr = _.extend({}, attr, { id }); model.set('attributes', attr); var scrStr = model.getScriptString(); // If the script was updated, I'll put its code in a separate container if (model.get('scriptUpdated')) { - this.mapJs[type+'-'+id] = {ids: [id], code: scrStr}; + this.mapJs[type + '-' + id] = { ids: [id], code: scrStr }; } else { var mapType = this.mapJs[type]; - if(mapType) { + if (mapType) { mapType.ids.push(id); } else { - this.mapJs[type] = {ids: [id], code: scrStr}; + this.mapJs[type] = { ids: [id], code: scrStr }; } } } @@ -43,7 +42,7 @@ module.exports = Backbone.Model.extend({ var code = ''; - for(var type in this.mapJs) { + for (var type in this.mapJs) { var mapType = this.mapJs[type]; var ids = '#' + mapType.ids.join(', #'); code += ` @@ -53,8 +52,6 @@ module.exports = Backbone.Model.extend({ }`; } - return code; - }, - + } }); diff --git a/src/code_manager/model/JsonGenerator.js b/src/code_manager/model/JsonGenerator.js index 4085a3192b..48dc5f737e 100644 --- a/src/code_manager/model/JsonGenerator.js +++ b/src/code_manager/model/JsonGenerator.js @@ -1,26 +1,29 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - /** @inheritdoc */ build(model) { - var json = model.toJSON(); + var json = model.toJSON(); this.beforeEach(json); - _.each(json,function(v, attr){ - var obj = json[attr]; - if(obj instanceof Backbone.Model){ - json[attr] = this.build(obj); - }else if(obj instanceof Backbone.Collection){ - var coll = obj; - json[attr] = []; - if(coll.length){ - coll.each(function (el, index) { - json[attr][index] = this.build(el); - }, this); + _.each( + json, + function(v, attr) { + var obj = json[attr]; + if (obj instanceof Backbone.Model) { + json[attr] = this.build(obj); + } else if (obj instanceof Backbone.Collection) { + var coll = obj; + json[attr] = []; + if (coll.length) { + coll.each(function(el, index) { + json[attr][index] = this.build(el); + }, this); + } } - } - }, this); + }, + this + ); return json; }, @@ -32,5 +35,4 @@ module.exports = Backbone.Model.extend({ beforeEach(obj) { delete obj.status; } - }); diff --git a/src/code_manager/view/EditorView.js b/src/code_manager/view/EditorView.js index 679b8b564a..e68fc2afa9 100644 --- a/src/code_manager/view/EditorView.js +++ b/src/code_manager/view/EditorView.js @@ -1,7 +1,6 @@ var Backbone = require('backbone'); module.exports = Backbone.View.extend({ - template: _.template(`
<%= label %>
@@ -16,10 +15,9 @@ module.exports = Backbone.View.extend({ render() { var obj = this.model.toJSON(); obj.pfx = this.pfx; - this.$el.html( this.template(obj) ); + this.$el.html(this.template(obj)); this.$el.attr('class', this.pfx + 'editor-c'); - this.$el.find('#'+this.pfx+'code').append(this.model.get('input')); + this.$el.find('#' + this.pfx + 'code').append(this.model.get('input')); return this; - }, - + } }); diff --git a/src/commands/config/config.js b/src/commands/config/config.js index 23351446ab..618ca5665e 100644 --- a/src/commands/config/config.js +++ b/src/commands/config/config.js @@ -1,5 +1,4 @@ module.exports = { - ESCAPE_KEY: 27, stylePrefix: 'com-', @@ -19,5 +18,5 @@ module.exports = { minComponentH: 50, // Minimum width (in px) of component on creation - minComponentW: 50, + minComponentW: 50 }; diff --git a/src/commands/index.js b/src/commands/index.js index d8cda886ac..b65d5d1cba 100644 --- a/src/commands/index.js +++ b/src/commands/index.js @@ -43,10 +43,10 @@ import { isFunction } from 'underscore'; module.exports = () => { let em; var c = {}, - commands = {}, - defaultCommands = {}, - defaults = require('./config/config'), - AbsCommands = require('./view/CommandAbstract'); + commands = {}, + defaultCommands = {}, + defaults = require('./config/config'), + AbsCommands = require('./view/CommandAbstract'); // Need it here as it would be used below var add = function(id, obj) { @@ -60,7 +60,6 @@ module.exports = () => { }; return { - /** * Name of the module * @type {String} @@ -76,19 +75,16 @@ module.exports = () => { init(config) { c = config || {}; for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } em = c.em; var ppfx = c.pStylePrefix; - if(ppfx) - c.stylePrefix = ppfx + c.stylePrefix; + if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; // Load commands passed via configuration - for( var k in c.defaults) { + for (var k in c.defaults) { var obj = c.defaults[k]; - if(obj.id) - this.add(obj.id, obj); + if (obj.id) this.add(obj.id, obj); } const ViewCode = require('./view/ExportTemplate'); @@ -117,31 +113,31 @@ module.exports = () => { run(ed) { var sel = ed.getSelected(); - if(!sel || !sel.get('removable')) { + if (!sel || !sel.get('removable')) { console.warn('The element is not removable'); return; } ed.select(null); sel.destroy(); - }, + } }; defaultCommands['tlb-clone'] = { run(ed) { var sel = ed.getSelected(); - if(!sel || !sel.get('copyable')) { + if (!sel || !sel.get('copyable')) { console.warn('The element is not clonable'); return; } var collection = sel.collection; var index = collection.indexOf(sel); - const added = collection.add(sel.clone(), {at: index + 1}); + const added = collection.add(sel.clone(), { at: index + 1 }); sel.emitUpdate(); ed.trigger('component:clone', added); - }, + } }; defaultCommands['tlb-move'] = { @@ -149,7 +145,7 @@ module.exports = () => { var sel = ed.getSelected(); var dragger; - if(!sel || !sel.get('draggable')) { + if (!sel || !sel.get('draggable')) { console.warn('The element is not draggable'); return; } @@ -165,7 +161,7 @@ module.exports = () => { const onEnd = (e, opts) => { em.runDefault(); em.set('selectedComponent', sel); - sel.emitUpdate() + sel.emitUpdate(); dragger && dragger.blur(); }; @@ -196,9 +192,8 @@ module.exports = () => { cmdMove.initSorterFromModel(sel); } - sel.set('status', 'selected'); - }, + } }; // Core commands @@ -228,10 +223,9 @@ module.exports = () => { } }; - if(c.em) - c.model = c.em.get('Canvas'); + if (c.em) c.model = c.em.get('Canvas'); - this.loadDefaultCommands() + this.loadDefaultCommands(); return this; }, @@ -267,9 +261,9 @@ module.exports = () => { get(id) { var el = commands[id]; - if(typeof el == 'function'){ + if (typeof el == 'function') { el = new el(c); - commands[id] = el; + commands[id] = el; } return el; @@ -291,11 +285,10 @@ module.exports = () => { * */ loadDefaultCommands() { for (var id in defaultCommands) { - this.add(id, defaultCommands[id]); + this.add(id, defaultCommands[id]); } return this; - }, + } }; - }; diff --git a/src/commands/model/Command.js b/src/commands/model/Command.js index 801af11b95..a6fcb3639c 100644 --- a/src/commands/model/Command.js +++ b/src/commands/model/Command.js @@ -1,9 +1,7 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - - defaults :{ - id: '', + defaults: { + id: '' } - }); diff --git a/src/commands/model/Commands.js b/src/commands/model/Commands.js index 1313b3e5fb..a2036bf9ba 100644 --- a/src/commands/model/Commands.js +++ b/src/commands/model/Commands.js @@ -2,7 +2,5 @@ var Backbone = require('backbone'); var Command = require('./Command'); module.exports = Backbone.Collection.extend({ - - model: Command, - + model: Command }); diff --git a/src/commands/view/CommandAbstract.js b/src/commands/view/CommandAbstract.js index 8c615b8e81..b49a4cd4b3 100644 --- a/src/commands/view/CommandAbstract.js +++ b/src/commands/view/CommandAbstract.js @@ -1,28 +1,26 @@ -const $ = Backbone.$ +const $ = Backbone.$; module.exports = Backbone.View.extend({ - /** * Initialize method that can't be removed * @param {Object} o Options * @private * */ initialize(o) { - this.config = o || {}; - this.editorModel = this.em = this.config.em || {}; - this.pfx = this.config.stylePrefix; - this.ppfx = this.config.pStylePrefix; - this.hoverClass = this.pfx + 'hover'; - this.badgeClass = this.pfx + 'badge'; - this.plhClass = this.pfx + 'placeholder'; - this.freezClass = this.ppfx + 'freezed'; + this.config = o || {}; + this.editorModel = this.em = this.config.em || {}; + this.pfx = this.config.stylePrefix; + this.ppfx = this.config.pStylePrefix; + this.hoverClass = this.pfx + 'hover'; + this.badgeClass = this.pfx + 'badge'; + this.plhClass = this.pfx + 'placeholder'; + this.freezClass = this.ppfx + 'freezed'; this.canvas = this.em.get && this.em.get('Canvas'); - if(this.em.get) - this.setElement(this.getCanvas()); + if (this.em.get) this.setElement(this.getCanvas()); - if(this.canvas){ + if (this.canvas) { this.$canvas = this.$el; this.$wrapper = $(this.getCanvasWrapper()); this.frameEl = this.canvas.getFrameEl(); @@ -106,6 +104,5 @@ module.exports = Backbone.View.extend({ * @param {Object} sender Button sender * @private * */ - stop(em, sender) {}, - + stop(em, sender) {} }); diff --git a/src/commands/view/CreateComponent.js b/src/commands/view/CreateComponent.js index bb6e6d5fbe..99438a2a5f 100644 --- a/src/commands/view/CreateComponent.js +++ b/src/commands/view/CreateComponent.js @@ -2,9 +2,8 @@ const SelectPosition = require('./SelectPosition'); const $ = Backbone.$; module.exports = _.extend({}, SelectPosition, { - init(opt) { - _.bindAll(this,'startDraw','draw','endDraw','rollback'); + _.bindAll(this, 'startDraw', 'draw', 'endDraw', 'rollback'); this.config = opt || {}; this.hType = this.config.newFixedH ? 'height' : 'min-height'; this.allowDraw = 1; @@ -16,9 +15,8 @@ module.exports = _.extend({}, SelectPosition, { * */ enable(...args) { SelectPosition.enable.apply(this, args); - this.$wr.css('cursor','crosshair'); - if(this.allowDraw) - this.$wr.on('mousedown', this.startDraw); + this.$wr.css('cursor', 'crosshair'); + if (this.allowDraw) this.$wr.on('mousedown', this.startDraw); this.ghost = this.canvas.getGhostEl(); }, @@ -33,11 +31,11 @@ module.exports = _.extend({}, SelectPosition, { this.ghost.style.display = 'block'; this.frameOff = this.getOffsetDim(); this.startPos = { - top : e.pageY + this.frameOff.top, + top: e.pageY + this.frameOff.top, left: e.pageX + this.frameOff.left }; this.isDragged = false; - this.tempComponent = {style: {}}; + this.tempComponent = { style: {} }; this.beforeDraw(this.tempComponent); this.updateSize(this.startPos.top, this.startPos.left, 0, 0); this.toggleEvents(1); @@ -75,11 +73,16 @@ module.exports = _.extend({}, SelectPosition, { this.toggleEvents(); var model = {}; // Only if the mouse was moved - if(this.isDragged){ + if (this.isDragged) { this.updateComponentSize(e); this.setRequirements(this.tempComponent); var lp = this.sorter.lastPos; - model = this.create(this.sorter.target, this.tempComponent, lp.index, lp.method); + model = this.create( + this.sorter.target, + this.tempComponent, + lp.index, + lp.method + ); this.sorter.prevTarget = null; } this.ghost.style.display = 'none'; @@ -103,10 +106,8 @@ module.exports = _.extend({}, SelectPosition, { var trgCollection = $trg.data('collection'); var droppable = trgModel ? trgModel.get('droppable') : 1; opt.at = index; - if(trgCollection && droppable) - return trgCollection.add(component, opt); - else - console.warn("Invalid target position"); + if (trgCollection && droppable) return trgCollection.add(component, opt); + else console.warn('Invalid target position'); }, /** @@ -116,29 +117,29 @@ module.exports = _.extend({}, SelectPosition, { * @private * */ setRequirements(component) { - var c = this.config; + var c = this.config; var compStl = component.style; // Check min width - if(compStl.width.replace(/\D/g,'') < c.minComponentW) - compStl.width = c.minComponentW +'px'; + if (compStl.width.replace(/\D/g, '') < c.minComponentW) + compStl.width = c.minComponentW + 'px'; // Check min height - if(compStl[this.hType].replace(/\D/g,'') < c.minComponentH) - compStl[this.hType] = c.minComponentH +'px'; + if (compStl[this.hType].replace(/\D/g, '') < c.minComponentH) + compStl[this.hType] = c.minComponentH + 'px'; // Set overflow in case of fixed height - if(c.newFixedH) - compStl.overflow = 'auto'; - if(!this.absoluteMode){ + if (c.newFixedH) compStl.overflow = 'auto'; + if (!this.absoluteMode) { delete compStl.left; delete compStl.top; - }else - compStl.position = 'absolute'; + } else compStl.position = 'absolute'; var lp = this.sorter.lastPos; - if(this.nearFloat(lp.index, lp.method, this.sorter.lastDims)) + if (this.nearFloat(lp.index, lp.method, this.sorter.lastDims)) compStl.float = 'left'; - if(this.config.firstCentered && - this.getCanvasWrapper() == this.sorter.target){ + if ( + this.config.firstCentered && + this.getCanvasWrapper() == this.sorter.target + ) { compStl.margin = '0 auto'; } @@ -152,12 +153,12 @@ module.exports = _.extend({}, SelectPosition, { * */ updateComponentSize(e) { var y = e.pageY + this.frameOff.top; - var x = e.pageX + this.frameOff.left; + var x = e.pageX + this.frameOff.left; var start = this.startPos; var top = start.top; var left = start.left; var height = y - top; - var width = x - left; + var width = x - left; if (x < left) { left = x; width = start.left - x; @@ -180,7 +181,7 @@ module.exports = _.extend({}, SelectPosition, { ghStl.top = compStl.top = top + u; ghStl.left = compStl.left = left + u; ghStl.width = compStl.width = width + u; - ghStl[this.hType] = compStl[this.hType] = height + u; + ghStl[this.hType] = compStl[this.hType] = height + u; }, /** @@ -191,7 +192,7 @@ module.exports = _.extend({}, SelectPosition, { * */ rollback(e, force) { var key = e.which || e.keyCode; - if(key == this.config.ESCAPE_KEY || force){ + if (key == this.config.ESCAPE_KEY || force) { this.isDragged = false; this.endDraw(); } @@ -204,7 +205,7 @@ module.exports = _.extend({}, SelectPosition, { * @private * */ beforeDraw(component) { - component.editable = false;//set this component editable + component.editable = false; //set this component editable }, /** @@ -214,17 +215,16 @@ module.exports = _.extend({}, SelectPosition, { * */ afterDraw(model) {}, - run(editor, sender, opts) { this.editor = editor; - this.sender = sender; + this.sender = sender; this.$wr = this.$wrapper; this.enable(); }, stop() { this.stopSelectPosition(); - this.$wrapper.css('cursor',''); + this.$wrapper.css('cursor', ''); this.$wrapper.unbind(); } }); diff --git a/src/commands/view/DeleteComponent.js b/src/commands/view/DeleteComponent.js index dcdd304b3d..a023bbc621 100644 --- a/src/commands/view/DeleteComponent.js +++ b/src/commands/view/DeleteComponent.js @@ -1,17 +1,17 @@ const SelectComponent = require('./SelectComponent'); const $ = Backbone.$; -module.exports = _.extend({},SelectComponent,{ - +module.exports = _.extend({}, SelectComponent, { init(o) { _.bindAll(this, 'startDelete', 'stopDelete', 'onDelete'); - this.hoverClass = this.pfx + 'hover-delete'; - this.badgeClass = this.pfx + 'badge-red'; + this.hoverClass = this.pfx + 'hover-delete'; + this.badgeClass = this.pfx + 'badge-red'; }, enable() { var that = this; - this.$el.find('*') + this.$el + .find('*') .mouseover(this.startDelete) .mouseout(this.stopDelete) .click(this.onDelete); @@ -23,15 +23,14 @@ module.exports = _.extend({},SelectComponent,{ * @private */ startDelete(e) { - e.stopPropagation(); - var $this = $(e.target); - - // Show badge if possible - if($this.data('model').get('removable')){ - $this.addClass(this.hoverClass); - this.attachBadge($this.get(0)); - } + e.stopPropagation(); + var $this = $(e.target); + // Show badge if possible + if ($this.data('model').get('removable')) { + $this.addClass(this.hoverClass); + this.attachBadge($this.get(0)); + } }, /** @@ -40,13 +39,12 @@ module.exports = _.extend({},SelectComponent,{ * @private */ stopDelete(e) { - e.stopPropagation(); - var $this = $(e.target); - $this.removeClass(this.hoverClass); + e.stopPropagation(); + var $this = $(e.target); + $this.removeClass(this.hoverClass); - // Hide badge if possible - if(this.badge) - this.badge.css({ left: -1000, top:-1000 }); + // Hide badge if possible + if (this.badge) this.badge.css({ left: -1000, top: -1000 }); }, /** @@ -59,8 +57,7 @@ module.exports = _.extend({},SelectComponent,{ var $this = $(e.target); // Do nothing in case can't remove - if(!$this.data('model').get('removable')) - return; + if (!$this.data('model').get('removable')) return; $this.data('model').destroy(); this.removeBadge(); @@ -73,7 +70,6 @@ module.exports = _.extend({},SelectComponent,{ * @private * */ updateBadgeLabel(model) { - this.badge.html( 'Remove ' + model.getName() ); - }, - + this.badge.html('Remove ' + model.getName()); + } }); diff --git a/src/commands/view/Drag.js b/src/commands/view/Drag.js index 567d56754c..9906593dc1 100644 --- a/src/commands/view/Drag.js +++ b/src/commands/view/Drag.js @@ -1,5 +1,4 @@ module.exports = { - run(editor, sender, opts) { var el = (opts && opts.el) || ''; var canvas = editor.Canvas; @@ -11,7 +10,7 @@ module.exports = { options.posFetcher = canvasView.getElementPos.bind(canvasView); // Create the resizer for the canvas if not yet created - if(!dragger) { + if (!dragger) { dragger = editor.Utils.Dragger.init(options); this.dragger = dragger; } @@ -27,8 +26,6 @@ module.exports = { }, stop() { - if(this.canvasResizer) - this.canvasResizer.blur(); - }, - + if (this.canvasResizer) this.canvasResizer.blur(); + } }; diff --git a/src/commands/view/ExportTemplate.js b/src/commands/view/ExportTemplate.js index 0d651f457a..a5fda7243f 100644 --- a/src/commands/view/ExportTemplate.js +++ b/src/commands/view/ExportTemplate.js @@ -1,7 +1,6 @@ const $ = Backbone.$; module.exports = { - run(editor, sender, opts = {}) { sender && sender.set && sender.set('active', 0); const config = editor.getConfig(); @@ -9,7 +8,6 @@ module.exports = { const pfx = config.stylePrefix; this.cm = editor.CodeManager || null; - if (!this.$editors) { const oHtmlEd = this.buildEditor('htmlmixed', 'hopscotch', 'HTML'); const oCsslEd = this.buildEditor('css', 'hopscotch', 'CSS'); @@ -40,7 +38,7 @@ module.exports = { label, codeName, theme, - input, + input }); const $el = new this.cm.EditorView({ @@ -51,5 +49,5 @@ module.exports = { el.init(input); return { el, $el }; - }, + } }; diff --git a/src/commands/view/Fullscreen.js b/src/commands/view/Fullscreen.js index 9a2baf0549..7b650b8e4a 100644 --- a/src/commands/view/Fullscreen.js +++ b/src/commands/view/Fullscreen.js @@ -5,10 +5,13 @@ module.exports = { */ isEnabled() { var d = document; - if(d.fullscreenElement || d.webkitFullscreenElement || d.mozFullScreenElement) + if ( + d.fullscreenElement || + d.webkitFullscreenElement || + d.mozFullScreenElement + ) return 1; - else - return 0; + else return 0; }, /** @@ -18,18 +21,15 @@ module.exports = { */ enable(el) { var pfx = ''; - if (el.requestFullscreen) - el.requestFullscreen(); + if (el.requestFullscreen) el.requestFullscreen(); else if (el.webkitRequestFullscreen) { pfx = 'webkit'; el.webkitRequestFullscreen(); - }else if (el.mozRequestFullScreen) { + } else if (el.mozRequestFullScreen) { pfx = 'moz'; el.mozRequestFullScreen(); - }else if (el.msRequestFullscreen) - el.msRequestFullscreen(); - else - console.warn('Fullscreen not supported'); + } else if (el.msRequestFullscreen) el.msRequestFullscreen(); + else console.warn('Fullscreen not supported'); return pfx; }, @@ -38,14 +38,10 @@ module.exports = { */ disable() { var d = document; - if (d.exitFullscreen) - d.exitFullscreen(); - else if (d.webkitExitFullscreen) - d.webkitExitFullscreen(); - else if (d.mozCancelFullScreen) - d.mozCancelFullScreen(); - else if (d.msExitFullscreen) - d.msExitFullscreen(); + if (d.exitFullscreen) d.exitFullscreen(); + else if (d.webkitExitFullscreen) d.webkitExitFullscreen(); + else if (d.mozCancelFullScreen) d.mozCancelFullScreen(); + else if (d.msExitFullscreen) d.msExitFullscreen(); }, /** @@ -53,11 +49,11 @@ module.exports = { * it's enabled * @param {strinf} pfx Browser prefix * @param {Event} e - */ + */ fsChanged(pfx, e) { var d = document; var ev = (pfx || '') + 'fullscreenchange'; - if(!this.isEnabled()){ + if (!this.isEnabled()) { this.stop(null, this.sender); document.removeEventListener(ev, this.fsChanged); } @@ -68,16 +64,12 @@ module.exports = { var pfx = this.enable(editor.getContainer()); this.fsChanged = this.fsChanged.bind(this, pfx); document.addEventListener(pfx + 'fullscreenchange', this.fsChanged); - if(editor) - editor.trigger('change:canvasOffset'); + if (editor) editor.trigger('change:canvasOffset'); }, stop(editor, sender) { - if(sender && sender.set) - sender.set('active', false); + if (sender && sender.set) sender.set('active', false); this.disable(); - if(editor) - editor.trigger('change:canvasOffset'); + if (editor) editor.trigger('change:canvasOffset'); } - }; diff --git a/src/commands/view/ImageComponent.js b/src/commands/view/ImageComponent.js index b1f064f6aa..f150195d5a 100644 --- a/src/commands/view/ImageComponent.js +++ b/src/commands/view/ImageComponent.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var InsertCustom = require('./InsertCustom'); module.exports = _.extend({}, InsertCustom, { - /** * Trigger before insert * @param {Object} object @@ -14,8 +13,10 @@ module.exports = _.extend({}, InsertCustom, { object.style = {}; object.attributes = {}; object.attributes.onmousedown = 'return false'; - if (this.config.firstCentered && - this.getCanvasWrapper() == this.sorter.target ) { + if ( + this.config.firstCentered && + this.getCanvasWrapper() == this.sorter.target + ) { object.style.margin = '0 auto'; } }, @@ -27,9 +28,6 @@ module.exports = _.extend({}, InsertCustom, { * */ afterInsert(model) { model.trigger('dblclick'); - if(this.sender) - this.sender.set('active', false); - }, - - + if (this.sender) this.sender.set('active', false); + } }); diff --git a/src/commands/view/InsertCustom.js b/src/commands/view/InsertCustom.js index 02bd7fa06d..9a3d61ef9e 100644 --- a/src/commands/view/InsertCustom.js +++ b/src/commands/view/InsertCustom.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var CreateComponent = require('./CreateComponent'); module.exports = _.extend({}, CreateComponent, { - init(...args) { CreateComponent.init.apply(this, args); _.bindAll(this, 'insertComponent'); @@ -37,15 +36,15 @@ module.exports = _.extend({}, CreateComponent, { this.beforeInsert(object); var index = this.sorter.lastPos.index; // By default, collections do not trigger add event, so silent is used - var model = this.create(this.sorter.target, object, index, null, {silent: false}); + var model = this.create(this.sorter.target, object, index, null, { + silent: false + }); - if(this.opt.terminateAfterInsert && this.sender) + if (this.opt.terminateAfterInsert && this.sender) this.sender.set('active', false); - else - this.enable(); + else this.enable(); - if(!model) - return; + if (!model) return; this.afterInsert(model, this); }, @@ -72,5 +71,5 @@ module.exports = _.extend({}, CreateComponent, { * */ buildContent() { return this.opt.content || {}; - }, + } }); diff --git a/src/commands/view/MoveComponent.js b/src/commands/view/MoveComponent.js index 18872627b2..219072acbf 100644 --- a/src/commands/view/MoveComponent.js +++ b/src/commands/view/MoveComponent.js @@ -1,18 +1,17 @@ -import {on, off} from 'utils/mixins' +import { on, off } from 'utils/mixins'; const SelectComponent = require('./SelectComponent'); const SelectPosition = require('./SelectPosition'); const $ = Backbone.$; module.exports = _.extend({}, SelectPosition, SelectComponent, { - init(o) { SelectComponent.init.apply(this, arguments); - _.bindAll(this, 'initSorter','rollback', 'onEndMove'); + _.bindAll(this, 'initSorter', 'rollback', 'onEndMove'); this.opt = o; - this.hoverClass = this.ppfx + 'highlighter-warning'; - this.badgeClass = this.ppfx + 'badge-warning'; - this.noSelClass = this.ppfx + 'no-select'; + this.hoverClass = this.ppfx + 'highlighter-warning'; + this.badgeClass = this.ppfx + 'badge-warning'; + this.noSelClass = this.ppfx + 'no-select'; }, enable(...args) { @@ -20,7 +19,7 @@ module.exports = _.extend({}, SelectPosition, SelectComponent, { this.getBadgeEl().addClass(this.badgeClass); this.getHighlighterEl().addClass(this.hoverClass); var wp = this.$wrapper; - wp.css('cursor','move'); + wp.css('cursor', 'move'); wp.on('mousedown', this.initSorter); // Avoid strange moving behavior @@ -41,8 +40,7 @@ module.exports = _.extend({}, SelectPosition, SelectComponent, { initSorter(e) { var el = $(e.target).data('model'); var drag = el.get('draggable'); - if(!drag) - return; + if (!drag) return; // Avoid badge showing on move this.cacheEl = null; @@ -61,8 +59,7 @@ module.exports = _.extend({}, SelectPosition, SelectComponent, { */ initSorterFromModel(model) { var drag = model.get('draggable'); - if(!drag) - return; + if (!drag) return; // Avoid badge showing on move this.cacheEl = null; var el = model.view.el; @@ -111,7 +108,7 @@ module.exports = _.extend({}, SelectPosition, SelectComponent, { * */ rollback(e, force) { var key = e.which || e.keyCode; - if(key == this.opt.ESCAPE_KEY || force){ + if (key == this.opt.ESCAPE_KEY || force) { this.sorter.moved = false; this.sorter.endMove(); } @@ -124,8 +121,7 @@ module.exports = _.extend({}, SelectPosition, SelectComponent, { * @private */ getBadgeEl() { - if(!this.$badge) - this.$badge = $(this.getBadge()); + if (!this.$badge) this.$badge = $(this.getBadge()); return this.$badge; }, @@ -135,8 +131,7 @@ module.exports = _.extend({}, SelectPosition, SelectComponent, { * @private */ getHighlighterEl() { - if(!this.$hl) - this.$hl = $(this.canvas.getHighlighter()); + if (!this.$hl) this.$hl = $(this.canvas.getHighlighter()); return this.$hl; }, @@ -145,6 +140,9 @@ module.exports = _.extend({}, SelectPosition, SelectComponent, { this.getBadgeEl().removeClass(this.badgeClass); this.getHighlighterEl().removeClass(this.hoverClass); var wp = this.$wrapper; - wp.css('cursor', '').unbind().removeClass(this.noSelClass); + wp + .css('cursor', '') + .unbind() + .removeClass(this.noSelClass); } }); diff --git a/src/commands/view/OpenAssets.js b/src/commands/view/OpenAssets.js index 4f9984e11e..179c089762 100644 --- a/src/commands/view/OpenAssets.js +++ b/src/commands/view/OpenAssets.js @@ -1,5 +1,4 @@ module.exports = { - run(editor, sender, opts = {}) { const modal = editor.Modal; const am = editor.AssetManager; @@ -12,15 +11,12 @@ module.exports = { am.onSelect(opts.onSelect); if (!this.rendered) { - am.render(am.getAll().filter( - asset => asset.get('type') == 'image' - )); + am.render(am.getAll().filter(asset => asset.get('type') == 'image')); this.rendered = 1; } modal.setTitle(title); modal.setContent(am.getContainer()); modal.open(); - }, - + } }; diff --git a/src/commands/view/OpenBlocks.js b/src/commands/view/OpenBlocks.js index 8abb5d871c..a4ae5f7216 100644 --- a/src/commands/view/OpenBlocks.js +++ b/src/commands/view/OpenBlocks.js @@ -1,5 +1,4 @@ module.exports = { - run(editor, sender) { const bm = editor.BlockManager; const pn = editor.Panels; @@ -8,7 +7,7 @@ module.exports = { bm.render(); const id = 'views-container'; const blocks = document.createElement('div'); - const panels = pn.getPanel(id) || pn.addPanel({id}); + const panels = pn.getPanel(id) || pn.addPanel({ id }); blocks.appendChild(bm.getContainer()); panels.set('appendContent', blocks).trigger('change:appendContent'); this.blocks = blocks; diff --git a/src/commands/view/OpenLayers.js b/src/commands/view/OpenLayers.js index e51185b5b8..a47d2c55e9 100644 --- a/src/commands/view/OpenLayers.js +++ b/src/commands/view/OpenLayers.js @@ -2,7 +2,6 @@ const Layers = require('navigator'); const $ = Backbone.$; module.exports = { - run(em, sender) { if (!this.toAppend) { var collection = em.DomComponents.getComponent().get('components'); @@ -13,14 +12,13 @@ module.exports = { config.layers.stylePrefix = config.stylePrefix + lyStylePfx; config.layers.pStylePrefix = config.stylePrefix; - config.layers.em = em.editor; + config.layers.em = em.editor; config.layers.opened = em.editor.get('opened'); // Check if panel exists otherwise crate it - if(!panels.getPanel('views-container')) - this.panel = panels.addPanel({id: 'views-container'}); - else - this.panel = panels.getPanel('views-container'); + if (!panels.getPanel('views-container')) + this.panel = panels.addPanel({ id: 'views-container' }); + else this.panel = panels.getPanel('views-container'); const toAppend = $(`
`); this.panel.set('appendContent', toAppend).trigger('change:appendContent'); diff --git a/src/commands/view/OpenStyleManager.js b/src/commands/view/OpenStyleManager.js index aada8ef551..87869a786d 100644 --- a/src/commands/view/OpenStyleManager.js +++ b/src/commands/view/OpenStyleManager.js @@ -3,12 +3,11 @@ const Backbone = require('backbone'); const $ = Backbone.$; module.exports = { - run(em, sender) { - this.sender = sender; + this.sender = sender; if (!this.$cn) { - var config = em.getConfig(), - panels = em.Panels; + var config = em.getConfig(), + panels = em.Panels; // Main container this.$cn = $('
'); // Secondary container @@ -17,34 +16,36 @@ module.exports = { // Device Manager var dvm = em.DeviceManager; - if(dvm && config.showDevices){ - var devicePanel = panels.addPanel({ id: 'devices-c'}); - devicePanel.set('appendContent', dvm.render()).trigger('change:appendContent'); + if (dvm && config.showDevices) { + var devicePanel = panels.addPanel({ id: 'devices-c' }); + devicePanel + .set('appendContent', dvm.render()) + .trigger('change:appendContent'); } // Class Manager container var clm = em.SelectorManager; - if(clm) - this.$cn2.append(clm.render([])); + if (clm) this.$cn2.append(clm.render([])); this.$cn2.append(em.StyleManager.render()); var smConfig = em.StyleManager.getConfig(); const pfx = smConfig.stylePrefix; // Create header - this.$header = $(`
${smConfig.textNoElement}
`); + this.$header = $( + `
${smConfig.textNoElement}
` + ); this.$cn.append(this.$header); // Create panel if not exists - if(!panels.getPanel('views-container')) - this.panel = panels.addPanel({ id: 'views-container'}); - else - this.panel = panels.getPanel('views-container'); + if (!panels.getPanel('views-container')) + this.panel = panels.addPanel({ id: 'views-container' }); + else this.panel = panels.getPanel('views-container'); // Add all containers to the panel this.panel.set('appendContent', this.$cn).trigger('change:appendContent'); this.target = em.editor; - this.listenTo( this.target ,'change:selectedComponent', this.toggleSm); + this.listenTo(this.target, 'change:selectedComponent', this.toggleSm); } this.toggleSm(); }, @@ -54,25 +55,23 @@ module.exports = { * @private */ toggleSm() { - const sender = this.sender; - if (sender && sender.get && !sender.get('active')) return; + const sender = this.sender; + if (sender && sender.get && !sender.get('active')) return; - if (this.target.get('selectedComponent')) { - this.$cn2.show(); - this.$header.hide(); - } else { - this.$cn2.hide(); - this.$header.show(); - } + if (this.target.get('selectedComponent')) { + this.$cn2.show(); + this.$header.hide(); + } else { + this.$cn2.hide(); + this.$header.show(); + } }, stop() { // Hide secondary container if exists - if(this.$cn2) - this.$cn2.hide(); + if (this.$cn2) this.$cn2.hide(); // Hide header container if exists - if(this.$header) - this.$header.hide(); + if (this.$header) this.$header.hide(); } }; diff --git a/src/commands/view/OpenTraitManager.js b/src/commands/view/OpenTraitManager.js index 3c9a92ab95..fe72334c33 100644 --- a/src/commands/view/OpenTraitManager.js +++ b/src/commands/view/OpenTraitManager.js @@ -1,24 +1,28 @@ const $ = Backbone.$; module.exports = { - run(editor, sender) { var config = editor.Config; var pfx = config.stylePrefix; var tm = editor.TraitManager; var panelC; - if(!this.obj){ + if (!this.obj) { var tmView = tm.getTraitsViewer(); var confTm = tm.getConfig(); this.obj = $('
') - .append('
' + confTm.labelContainer + '
') - .get(0); + .append( + '
' + + confTm.labelContainer + + '
' + ) + .get(0); this.obj.appendChild(tmView.render().el); var panels = editor.Panels; - if(!panels.getPanel('views-container')) - panelC = panels.addPanel({id: 'views-container'}); - else - panelC = panels.getPanel('views-container'); + if (!panels.getPanel('views-container')) + panelC = panels.addPanel({ id: 'views-container' }); + else panelC = panels.getPanel('views-container'); panelC.set('appendContent', this.obj).trigger('change:appendContent'); } @@ -26,7 +30,6 @@ module.exports = { }, stop() { - if(this.obj) - this.obj.style.display = 'none'; + if (this.obj) this.obj.style.display = 'none'; } }; diff --git a/src/commands/view/Preview.js b/src/commands/view/Preview.js index 008283a646..4a878dc22e 100644 --- a/src/commands/view/Preview.js +++ b/src/commands/view/Preview.js @@ -1,21 +1,20 @@ module.exports = { - getPanels(editor) { - if(!this.panels) - this.panels = editor.Panels.getPanelsEl(); + if (!this.panels) this.panels = editor.Panels.getPanelsEl(); return this.panels; }, tglPointers(editor, v) { - var elP = editor.Canvas.getBody().querySelectorAll('.' + this.ppfx + 'no-pointer'); + var elP = editor.Canvas.getBody().querySelectorAll( + '.' + this.ppfx + 'no-pointer' + ); _.each(elP, item => { item.style.pointerEvents = v ? '' : 'all'; }); }, run(editor, sender) { - if(sender && sender.set) - sender.set('active', false); + if (sender && sender.set) sender.set('active', false); editor.stopCommand('sw-visibility'); editor.getModel().stopDefault(); var that = this; @@ -23,7 +22,7 @@ module.exports = { var canvas = editor.Canvas.getElement(); var editorEl = editor.getEl(); var pfx = editor.Config.stylePrefix; - if(!this.helper) { + if (!this.helper) { this.helper = document.createElement('span'); this.helper.className = pfx + 'off-prv fa fa-eye-slash'; editorEl.appendChild(this.helper); @@ -57,7 +56,7 @@ module.exports = { panels.style.display = 'block'; var canvas = editor.Canvas.getElement(); canvas.setAttribute('style', ''); - if(this.helper) { + if (this.helper) { this.helper.style.display = 'none'; } editor.trigger('change:canvasOffset'); diff --git a/src/commands/view/Resize.js b/src/commands/view/Resize.js index 99b49784a5..a35becd639 100644 --- a/src/commands/view/Resize.js +++ b/src/commands/view/Resize.js @@ -1,5 +1,4 @@ module.exports = { - run(editor, sender, opts) { var opt = opts || {}; var el = opt.el || ''; @@ -14,7 +13,7 @@ module.exports = { options.mousePosFetcher = canvas.getMouseRelativePos; // Create the resizer for the canvas if not yet created - if(!canvasResizer || opt.forceNew) { + if (!canvasResizer || opt.forceNew) { this.canvasResizer = editor.Utils.Resizer.init(options); canvasResizer = this.canvasResizer; } @@ -27,6 +26,5 @@ module.exports = { stop() { const resizer = this.canvasResizer; resizer && resizer.blur(); - }, - + } }; diff --git a/src/commands/view/SelectComponent.js b/src/commands/view/SelectComponent.js index 996ca374a5..79dcdd4ca2 100644 --- a/src/commands/view/SelectComponent.js +++ b/src/commands/view/SelectComponent.js @@ -1,5 +1,5 @@ import { bindAll } from 'underscore'; -import { on, off, getUnitFromValue} from 'utils/mixins'; +import { on, off, getUnitFromValue } from 'utils/mixins'; const ToolbarView = require('dom_components/view/ToolbarView'); const Toolbar = require('dom_components/model/Toolbar'); @@ -8,15 +8,13 @@ const $ = require('backbone').$; let showOffsets; module.exports = { - init(o) { bindAll(this, 'onHover', 'onOut', 'onClick', 'onKeyPress', 'onFrameScroll'); }, - enable() { this.frameOff = this.canvasOff = this.adjScroll = null; - var config = this.config.em.get('Config'); + var config = this.config.em.get('Config'); this.startSelectComponent(); var em = this.config.em; showOffsets = 1; @@ -30,7 +28,7 @@ module.exports = { * @private * */ startSelectComponent() { - this.toggleSelectComponent(1); + this.toggleSelectComponent(1); }, /** @@ -38,7 +36,7 @@ module.exports = { * @private * */ stopSelectComponent() { - this.toggleSelectComponent(); + this.toggleSelectComponent(); }, /** @@ -48,7 +46,7 @@ module.exports = { toggleSelectComponent(enable) { const em = this.em; const method = enable ? 'on' : 'off'; - const methods = {on, off}; + const methods = { on, off }; const body = this.getCanvasBody(); const win = this.getContentWindow(); methods[method](body, 'mouseover', this.onHover); @@ -69,13 +67,11 @@ module.exports = { var focused = this.frameEl.contentDocument.activeElement.tagName !== 'BODY'; // On CANC (46) or Backspace (8) - if(key == 8 || key == 46) { - if(!focused) - e.preventDefault(); - if(comp && !focused) { - if(!comp.get('removable')) - return; - comp.set('status',''); + if (key == 8 || key == 46) { + if (!focused) e.preventDefault(); + if (comp && !focused) { + if (!comp.get('removable')) return; + comp.set('status', ''); comp.destroy(); this.hideBadge(); this.clean(); @@ -135,14 +131,13 @@ module.exports = { var $el = $(el); var model = $el.data('model'); - if ( (model && model.get('status') == 'selected') || - !showOffsets){ + if ((model && model.get('status') == 'selected') || !showOffsets) { return; } this.editor.runCommand('show-offset', { el, - elPos: pos, + elPos: pos }); }, @@ -164,7 +159,7 @@ module.exports = { this.editor.runCommand('show-offset', { el, elPos: pos, - state: 'Fixed', + state: 'Fixed' }); }, @@ -174,8 +169,7 @@ module.exports = { * @param {Object} pos */ hideFixedElementOffset(el, pos) { - if(this.editor) - this.editor.stopCommand('show-offset', {state: 'Fixed'}); + if (this.editor) this.editor.stopCommand('show-offset', { state: 'Fixed' }); }, /** @@ -199,7 +193,7 @@ module.exports = { if (model.get('selectable')) { editor.select(model); } else { - let parent = model.parent(); + let parent = model.parent(); while (parent && !parent.get('selectable')) parent = parent.parent(); parent && editor.select(parent); } @@ -218,9 +212,8 @@ module.exports = { var config = canvas.getConfig(); var customeLabel = config.customBadgeLabel; this.cacheEl = el; - var model = $el.data("model"); - if(!model || !model.get('badgable')) - return; + var model = $el.data('model'); + if (!model || !model.get('badgable')) return; var badge = this.getBadge(); var badgeLabel = model.getIcon() + model.getName(); badgeLabel = customeLabel ? customeLabel(model) : badgeLabel; @@ -231,7 +224,8 @@ module.exports = { var canvasPos = canvas.getCanvasView().getPosition(); var badgeH = badge ? badge.offsetHeight : 0; var badgeW = badge ? badge.offsetWidth : 0; - var top = pos.top - badgeH < canvasPos.top ? canvasPos.top : pos.top - badgeH; + var top = + pos.top - badgeH < canvasPos.top ? canvasPos.top : pos.top - badgeH; var left = pos.left + badgeW < canvasPos.left ? canvasPos.left : pos.left; bStyle.top = top + u; bStyle.left = left + u; @@ -247,7 +241,11 @@ module.exports = { var $el = $(el); var model = $el.data('model'); - if(!model || !model.get("hoverable") || model.get('status') == 'selected') { + if ( + !model || + !model.get('hoverable') || + model.get('status') == 'selected' + ) { return; } @@ -302,15 +300,17 @@ module.exports = { var toggleBodyClass = (method, e, opts) => { const docs = opts.docs; - docs && docs.forEach(doc => { - const body = doc.body; - const cls = body.className || ''; - body.className = (method == 'add' ? - `${cls} ${resizeClass}` : cls.replace(resizeClass, '')).trim(); - }); + docs && + docs.forEach(doc => { + const body = doc.body; + const cls = body.className || ''; + body.className = (method == 'add' + ? `${cls} ${resizeClass}` + : cls.replace(resizeClass, '') + ).trim(); + }); }; - if (editor && resizable) { options = { // Here the resizer is updated with the current element height and width @@ -322,7 +322,8 @@ module.exports = { const computedStyle = getComputedStyle(el); const modelStyle = modelToStyle.getStyle(); const currentWidth = modelStyle[keyWidth] || computedStyle[keyWidth]; - const currentHeight = modelStyle[keyHeight] || computedStyle[keyHeight]; + const currentHeight = + modelStyle[keyHeight] || computedStyle[keyHeight]; resizer.startDim.w = parseFloat(currentWidth); resizer.startDim.h = parseFloat(currentHeight); showOffsets = 0; @@ -349,7 +350,7 @@ module.exports = { return; } - const { store, selectedHandler, config} = options; + const { store, selectedHandler, config } = options; const { keyHeight, keyWidth } = config; const onlyHeight = ['tc', 'bc'].indexOf(selectedHandler) >= 0; const onlyWidth = ['cl', 'cr'].indexOf(selectedHandler) >= 0; @@ -363,9 +364,12 @@ module.exports = { style[keyHeight] = rect.h + config.unitHeight; } - modelToStyle.setStyle(style, {avoidStore: 1}); + modelToStyle.setStyle(style, { avoidStore: 1 }); const updateEvent = `update:component:style`; - em && em.trigger(`${updateEvent}:${keyHeight} ${updateEvent}:${keyWidth}`); + em && + em.trigger( + `${updateEvent}:${keyHeight} ${updateEvent}:${keyWidth}` + ); if (store) { modelToStyle.trigger('change:style', modelToStyle, style, {}); @@ -377,7 +381,7 @@ module.exports = { options = { ...options, ...resizable }; } - editor.runCommand('resize', {el, options}); + editor.runCommand('resize', { el, options }); // On undo/redo the resizer rect is not updating, need somehow to call // this.updateRect on undo/redo action @@ -409,7 +413,7 @@ module.exports = { if (showToolbar && toolbar && toolbar.length) { toolbarStyle.opacity = ''; toolbarStyle.display = ''; - if(!this.toolbar) { + if (!this.toolbar) { toolbarEl.innerHTML = ''; this.toolbar = new Toolbar(toolbar); var toolbarView = new ToolbarView({ @@ -440,7 +444,7 @@ module.exports = { toolbarStyle.display = 'block'; var pos = this.canvas.getTargetToElementDim(toolbarEl, el, { elPos, - event: 'toolbarPosUpdate', + event: 'toolbarPosUpdate' }); var leftPos = pos.left + pos.elementWidth - pos.targetWidth; toolbarStyle.top = pos.top + unit; @@ -461,8 +465,7 @@ module.exports = { * @private * */ clean() { - if(this.selEl) - this.selEl.removeClass(this.hoverClass); + if (this.selEl) this.selEl.removeClass(this.hoverClass); }, /** @@ -529,10 +532,11 @@ module.exports = { * @private */ cleanPrevious(model) { - model && model.set({ - status: '', - state: '', - }); + model && + model.set({ + status: '', + state: '' + }); }, /** diff --git a/src/commands/view/SelectParent.js b/src/commands/view/SelectParent.js index a40c3ee8fc..ad6a742498 100644 --- a/src/commands/view/SelectParent.js +++ b/src/commands/view/SelectParent.js @@ -1,15 +1,13 @@ module.exports = { - run(editor) { const sel = editor.getSelected(); let comp = sel && sel.parent(); // Recurse through the parent() chain until a selectable parent is found - while (comp && !comp.get("selectable")) { + while (comp && !comp.get('selectable')) { comp = comp.parent(); } comp && editor.select(comp); } - }; diff --git a/src/commands/view/SelectPosition.js b/src/commands/view/SelectPosition.js index 1c103fb1db..fc3241524a 100644 --- a/src/commands/view/SelectPosition.js +++ b/src/commands/view/SelectPosition.js @@ -1,7 +1,6 @@ const $ = Backbone.$; module.exports = { - /** * Start select position event * @param {HTMLElement} trg @@ -10,7 +9,7 @@ module.exports = { startSelectPosition(trg, doc) { this.isPointed = false; var utils = this.editorModel.get('Utils'); - if(utils && !this.sorter) + if (utils && !this.sorter) this.sorter = new utils.Sorter({ container: this.getCanvasBody(), placer: this.canvas.getPlacerEl(), @@ -22,7 +21,7 @@ module.exports = { wmargin: 1, nested: 1, em: this.editorModel, - canvasRelative: 1, + canvasRelative: 1 }); this.sorter.startSort(trg); }, @@ -46,17 +45,27 @@ module.exports = { * */ stopSelectPosition() { this.posTargetCollection = null; - this.posIndex = this.posMethod=='after' && this.cDim.length!==0 ? this.posIndex + 1 : this.posIndex; //Normalize - if(this.sorter){ + this.posIndex = + this.posMethod == 'after' && this.cDim.length !== 0 + ? this.posIndex + 1 + : this.posIndex; //Normalize + if (this.sorter) { this.sorter.moved = 0; this.sorter.endMove(); } - if(this.cDim){ - this.posIsLastEl = this.cDim.length!==0 && this.posMethod=='after' && this.posIndex==this.cDim.length; - this.posTargetEl = (this.cDim.length===0 ? $(this.outsideElem) : - (!this.posIsLastEl && this.cDim[this.posIndex] ? $(this.cDim[this.posIndex][5]).parent() : $(this.outsideElem) )); - this.posTargetModel = this.posTargetEl.data("model"); - this.posTargetCollection = this.posTargetEl.data("model-comp"); + if (this.cDim) { + this.posIsLastEl = + this.cDim.length !== 0 && + this.posMethod == 'after' && + this.posIndex == this.cDim.length; + this.posTargetEl = + this.cDim.length === 0 + ? $(this.outsideElem) + : !this.posIsLastEl && this.cDim[this.posIndex] + ? $(this.cDim[this.posIndex][5]).parent() + : $(this.outsideElem); + this.posTargetModel = this.posTargetEl.data('model'); + this.posTargetCollection = this.posTargetEl.data('model-comp'); } }, @@ -80,23 +89,24 @@ module.exports = { var i = index || 0; var m = method || 'before'; var len = dims.length; - var isLast = len !== 0 && m == 'after' && i == len; - if(len !== 0 && ( - (!isLast && !dims[i][4]) || - (dims[i-1] && !dims[i-1][4]) || - (isLast && !dims[i-1][4]) ) ) + var isLast = len !== 0 && m == 'after' && i == len; + if ( + len !== 0 && + ((!isLast && !dims[i][4]) || + (dims[i - 1] && !dims[i - 1][4]) || + (isLast && !dims[i - 1][4])) + ) return 1; return 0; }, - run() { this.enable(); }, stop() { this.stopSelectPosition(); - this.$wrapper.css('cursor',''); + this.$wrapper.css('cursor', ''); this.$wrapper.unbind(); } }; diff --git a/src/commands/view/ShowOffset.js b/src/commands/view/ShowOffset.js index d1f5b98499..b407092c8d 100644 --- a/src/commands/view/ShowOffset.js +++ b/src/commands/view/ShowOffset.js @@ -1,7 +1,6 @@ const $ = Backbone.$; module.exports = { - getOffsetMethod(state) { var method = state || ''; return 'get' + method + 'OffsetViewerEl'; @@ -12,8 +11,10 @@ module.exports = { var state = opt.state || ''; var config = editor.getConfig(); - if (!config.showOffsets || - (!config.showOffsetsSelected && state == 'Fixed') ) { + if ( + !config.showOffsets || + (!config.showOffsetsSelected && state == 'Fixed') + ) { return; } @@ -36,7 +37,7 @@ module.exports = { var padL = this['padL' + state]; var padR = this['padR' + state]; - if(!this[stateVar]) { + if (!this[stateVar]) { var stateLow = state.toLowerCase(); var marginName = stateLow + 'margin-v'; var paddingName = stateLow + 'padding-v'; @@ -125,7 +126,7 @@ module.exports = { pbStyle.top = pos.top + pos.height - padBot + unit; pbStyle.left = posLeft + unit; - var padSideH = (pos.height - padBot - padTop) + unit; + var padSideH = pos.height - padBot - padTop + unit; var padSideT = pos.top + padTop + unit; plStyle.height = padSideH; plStyle.width = style.paddingLeft; @@ -146,6 +147,5 @@ module.exports = { var canvas = editor.Canvas; var offsetViewer = canvas[method](); offsetViewer.style.display = 'none'; - }, - + } }; diff --git a/src/commands/view/SwitchVisibility.js b/src/commands/view/SwitchVisibility.js index f2a067f123..82a7e771ab 100644 --- a/src/commands/view/SwitchVisibility.js +++ b/src/commands/view/SwitchVisibility.js @@ -1,11 +1,9 @@ module.exports = { - run(ed) { ed.Canvas.getBody().className = this.ppfx + 'dashed'; }, stop(ed) { - ed.Canvas.getBody().className = ""; + ed.Canvas.getBody().className = ''; } - }; diff --git a/src/commands/view/TextComponent.js b/src/commands/view/TextComponent.js index f24022aa52..aafc9589aa 100644 --- a/src/commands/view/TextComponent.js +++ b/src/commands/view/TextComponent.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var CreateComponent = require('./CreateComponent'); module.exports = _.extend({}, CreateComponent, { - /** * This event is triggered at the beginning of a draw operation * @param {Object} component Object component before creation @@ -10,8 +9,7 @@ module.exports = _.extend({}, CreateComponent, { * */ beforeDraw(component) { component.type = 'text'; - if(!component.style) - component.style = {}; + if (!component.style) component.style = {}; component.style.padding = '10px'; }, @@ -21,11 +19,8 @@ module.exports = _.extend({}, CreateComponent, { * @private * */ afterDraw(model) { - if(!model || !model.set) - return; + if (!model || !model.set) return; model.trigger('focus'); - if(this.sender) - this.sender.set('active', false); - }, - + if (this.sender) this.sender.set('active', false); + } }); diff --git a/src/css_composer/config/config.js b/src/css_composer/config/config.js index 421594aacd..0ae4f356fa 100644 --- a/src/css_composer/config/config.js +++ b/src/css_composer/config/config.js @@ -1,12 +1,10 @@ module.exports = { - // Style prefix stylePrefix: 'css-', // Custom CSS string to render on top - 'staticRules': '', + staticRules: '', // Default CSS style - rules: [], - + rules: [] }; diff --git a/src/css_composer/index.js b/src/css_composer/index.js index 2e4e1d9f0c..d56683cc7d 100644 --- a/src/css_composer/index.js +++ b/src/css_composer/index.js @@ -19,375 +19,352 @@ module.exports = () => { let em; var c = {}, - defaults = require('./config/config'), - CssRule = require('./model/CssRule'), - CssRules = require('./model/CssRules'), - CssRulesView = require('./view/CssRulesView'); + defaults = require('./config/config'), + CssRule = require('./model/CssRule'), + CssRules = require('./model/CssRules'), + CssRulesView = require('./view/CssRulesView'); const Selectors = require('selector_manager/model/Selectors'); const Selector = require('selector_manager/model/Selector'); var rules, rulesView; return { - - Selectors, - - /** - * Name of the module - * @type {String} - * @private - */ - name: 'CssComposer', - - /** - * Mandatory for the storage manager - * @type {String} - * @private - */ - storageKey() { - var keys = []; - var smc = (c.stm && c.stm.getConfig()) || {}; - if(smc.storeCss) - keys.push('css'); - if(smc.storeStyles) - keys.push('styles'); - return keys; - }, - - /** - * Initializes module. Automatically called with a new instance of the editor - * @param {Object} config Configurations - * @private - */ - init(config) { - c = config || {}; - for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; - } - - var ppfx = c.pStylePrefix; - if(ppfx) - c.stylePrefix = ppfx + c.stylePrefix; - - var elStyle = (c.em && c.em.config.style) || ''; - c.rules = elStyle || c.rules; - - c.sm = c.em; - em = c.em; - rules = new CssRules([], c); - rulesView = new CssRulesView({ - collection: rules, - config: c, - }); - return this; - }, - - /** - * On load callback - * @private - */ - onLoad() { - rules.add(c.rules); - }, - - - /** - * Do stuff after load - * @param {Editor} em - * @private - */ - postLoad(em) { - const ev = 'add remove'; - const rules = this.getAll(); - em.stopListening(rules, ev, this.handleChange); - em.listenTo(rules, ev, this.handleChange); - rules.each(rule => this.handleChange(rule)); - }, - - - /** - * Handle rule changes - * @private - */ - handleChange(model) { - const ev = 'change:style'; - const um = em.get('UndoManager'); - um && um.add(model); - const handleUpdates = em.handleUpdates.bind(em); - em.stopListening(model, ev, handleUpdates); - em.listenTo(model, ev, handleUpdates); - }, - - - /** - * Load data from the passed object, if the object is empty will try to fetch them - * autonomously from the storage manager. - * The fetched data will be added to the collection - * @param {Object} data Object of data to load - * @return {Object} Loaded rules - */ - load(data) { - var d = data || ''; - - if (!d && c.stm) { - d = c.em.getCacheLoad(); - } - - var obj = d.styles || ''; - - if(d.styles) { - try { - obj = JSON.parse(d.styles); - } catch (err) {} - } else if (d.css) { - obj = c.em.get('Parser').parseCss(d.css); + Selectors, + + /** + * Name of the module + * @type {String} + * @private + */ + name: 'CssComposer', + + /** + * Mandatory for the storage manager + * @type {String} + * @private + */ + storageKey() { + var keys = []; + var smc = (c.stm && c.stm.getConfig()) || {}; + if (smc.storeCss) keys.push('css'); + if (smc.storeStyles) keys.push('styles'); + return keys; + }, + + /** + * Initializes module. Automatically called with a new instance of the editor + * @param {Object} config Configurations + * @private + */ + init(config) { + c = config || {}; + for (var name in defaults) { + if (!(name in c)) c[name] = defaults[name]; + } + + var ppfx = c.pStylePrefix; + if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; + + var elStyle = (c.em && c.em.config.style) || ''; + c.rules = elStyle || c.rules; + + c.sm = c.em; + em = c.em; + rules = new CssRules([], c); + rulesView = new CssRulesView({ + collection: rules, + config: c + }); + return this; + }, + + /** + * On load callback + * @private + */ + onLoad() { + rules.add(c.rules); + }, + + /** + * Do stuff after load + * @param {Editor} em + * @private + */ + postLoad(em) { + const ev = 'add remove'; + const rules = this.getAll(); + em.stopListening(rules, ev, this.handleChange); + em.listenTo(rules, ev, this.handleChange); + rules.each(rule => this.handleChange(rule)); + }, + + /** + * Handle rule changes + * @private + */ + handleChange(model) { + const ev = 'change:style'; + const um = em.get('UndoManager'); + um && um.add(model); + const handleUpdates = em.handleUpdates.bind(em); + em.stopListening(model, ev, handleUpdates); + em.listenTo(model, ev, handleUpdates); + }, + + /** + * Load data from the passed object, if the object is empty will try to fetch them + * autonomously from the storage manager. + * The fetched data will be added to the collection + * @param {Object} data Object of data to load + * @return {Object} Loaded rules + */ + load(data) { + var d = data || ''; + + if (!d && c.stm) { + d = c.em.getCacheLoad(); + } + + var obj = d.styles || ''; + + if (d.styles) { + try { + obj = JSON.parse(d.styles); + } catch (err) {} + } else if (d.css) { + obj = c.em.get('Parser').parseCss(d.css); + } + + if (obj) { + rules.reset(obj); + } + + return obj; + }, + + /** + * Store data to the selected storage + * @param {Boolean} noStore If true, won't store + * @return {Object} Data to store + */ + store(noStore) { + if (!c.stm) return; + var obj = {}; + var keys = this.storageKey(); + if (keys.indexOf('css') >= 0) obj.css = c.em.getCss(); + if (keys.indexOf('styles') >= 0) obj.styles = JSON.stringify(rules); + if (!noStore) c.stm.store(obj); + return obj; + }, + + /** + * Add new rule to the collection, if not yet exists with the same selectors + * @param {Array} selectors Array of selectors + * @param {String} state Css rule state + * @param {String} width For which device this style is oriented + * @param {Object} opts Other options for the rule + * @return {Model} + * @example + * var sm = editor.SelectorManager; + * var sel1 = sm.add('myClass1'); + * var sel2 = sm.add('myClass2'); + * var rule = cssComposer.add([sel1, sel2], 'hover'); + * rule.set('style', { + * width: '100px', + * color: '#fff', + * }); + * */ + add(selectors, state, width, opts) { + var s = state || ''; + var w = width || ''; + var opt = opts || {}; + var rule = this.get(selectors, s, w, opt); + if (rule) return rule; + else { + opt.state = s; + opt.mediaText = w; + opt.selectors = ''; + rule = new CssRule(opt, c); + rule.get('selectors').add(selectors); + rules.add(rule); + return rule; + } + }, + + /** + * Get the rule + * @param {Array} selectors Array of selectors + * @param {String} state Css rule state + * @param {String} width For which device this style is oriented + * @param {Object} ruleProps Other rule props + * @return {Model|null} + * @example + * var sm = editor.SelectorManager; + * var sel1 = sm.add('myClass1'); + * var sel2 = sm.add('myClass2'); + * var rule = cssComposer.get([sel1, sel2], 'hover'); + * // Update the style + * rule.set('style', { + * width: '300px', + * color: '#000', + * }); + * */ + get(selectors, state, width, ruleProps) { + var rule = null; + rules.each(m => { + if (rule) return; + if (m.compare(selectors, state, width, ruleProps)) rule = m; + }); + return rule; + }, + + /** + * Get the collection of rules + * @return {Collection} + * */ + getAll() { + return rules; + }, + + /** + * Remove all rules + * @return {this} + */ + clear() { + this.getAll().reset(); + return this; + }, + + /** + * Add a raw collection of rule objects + * This method overrides styles, in case, of already defined rule + * @param {Array} data Array of rule objects, eg . [{selectors: ['class1'], style: {....}}, ..] + * @param {Object} opts Options + * @return {Array} + * @private + */ + addCollection(data, opts = {}) { + var result = []; + var d = data instanceof Array ? data : [data]; + + for (var i = 0, l = d.length; i < l; i++) { + var rule = d[i] || {}; + if (!rule.selectors) continue; + var sm = c.em && c.em.get('SelectorManager'); + if (!sm) console.warn('Selector Manager not found'); + var sl = rule.selectors; + var sels = sl instanceof Array ? sl : [sl]; + var newSels = []; + + for (var j = 0, le = sels.length; j < le; j++) { + var selec = sm.add(sels[j]); + newSels.push(selec); } - if (obj) { - rules.reset(obj); - } + var modelExists = this.get(newSels, rule.state, rule.mediaText, rule); + var model = this.add(newSels, rule.state, rule.mediaText, rule); + var updateStyle = !modelExists || !opts.avoidUpdateStyle; + const style = rule.style || {}; - return obj; - }, - - /** - * Store data to the selected storage - * @param {Boolean} noStore If true, won't store - * @return {Object} Data to store - */ - store(noStore) { - if(!c.stm) - return; - var obj = {}; - var keys = this.storageKey(); - if(keys.indexOf('css') >= 0) - obj.css = c.em.getCss(); - if(keys.indexOf('styles') >= 0) - obj.styles = JSON.stringify(rules); - if(!noStore) - c.stm.store(obj); - return obj; - }, - - /** - * Add new rule to the collection, if not yet exists with the same selectors - * @param {Array} selectors Array of selectors - * @param {String} state Css rule state - * @param {String} width For which device this style is oriented - * @param {Object} opts Other options for the rule - * @return {Model} - * @example - * var sm = editor.SelectorManager; - * var sel1 = sm.add('myClass1'); - * var sel2 = sm.add('myClass2'); - * var rule = cssComposer.add([sel1, sel2], 'hover'); - * rule.set('style', { - * width: '100px', - * color: '#fff', - * }); - * */ - add(selectors, state, width, opts) { - var s = state || ''; - var w = width || ''; - var opt = opts || {}; - var rule = this.get(selectors, s, w, opt); - if(rule) - return rule; - else { - opt.state = s; - opt.mediaText = w; - opt.selectors = ''; - rule = new CssRule(opt, c); - rule.get('selectors').add(selectors); - rules.add(rule); - return rule; - } - }, - - /** - * Get the rule - * @param {Array} selectors Array of selectors - * @param {String} state Css rule state - * @param {String} width For which device this style is oriented - * @param {Object} ruleProps Other rule props - * @return {Model|null} - * @example - * var sm = editor.SelectorManager; - * var sel1 = sm.add('myClass1'); - * var sel2 = sm.add('myClass2'); - * var rule = cssComposer.get([sel1, sel2], 'hover'); - * // Update the style - * rule.set('style', { - * width: '300px', - * color: '#000', - * }); - * */ - get(selectors, state, width, ruleProps) { - var rule = null; - rules.each(m => { - if(rule) - return; - if(m.compare(selectors, state, width, ruleProps)) - rule = m; - }); - return rule; - }, - - /** - * Get the collection of rules - * @return {Collection} - * */ - getAll() { - return rules; - }, - - - /** - * Remove all rules - * @return {this} - */ - clear() { - this.getAll().reset(); - return this; - }, - - - /** - * Add a raw collection of rule objects - * This method overrides styles, in case, of already defined rule - * @param {Array} data Array of rule objects, eg . [{selectors: ['class1'], style: {....}}, ..] - * @param {Object} opts Options - * @return {Array} - * @private - */ - addCollection(data, opts = {}) { - var result = []; - var d = data instanceof Array ? data : [data]; - - for (var i = 0, l = d.length; i < l; i++) { - var rule = d[i] || {}; - if(!rule.selectors) - continue; - var sm = c.em && c.em.get('SelectorManager'); - if(!sm) - console.warn('Selector Manager not found'); - var sl = rule.selectors; - var sels = sl instanceof Array ? sl : [sl]; - var newSels = []; - - for (var j = 0, le = sels.length; j < le; j++) { - var selec = sm.add(sels[j]); - newSels.push(selec); - } - - var modelExists = this.get(newSels, rule.state, rule.mediaText, rule); - var model = this.add(newSels, rule.state, rule.mediaText, rule); - var updateStyle = !modelExists || !opts.avoidUpdateStyle; - const style = rule.style || {}; - - if (updateStyle) { - let styleUpdate = opts.extend ? { ...model.get('style'), ...style } : style; - model.set('style', styleUpdate); - } - - result.push(model); + if (updateStyle) { + let styleUpdate = opts.extend + ? { ...model.get('style'), ...style } + : style; + model.set('style', styleUpdate); } - return result; - }, - - - /** - * Add/update the CSS rule with id selector - * @param {string} name Id selector name, eg. 'my-id' - * @param {Object} style Style properties and values - * @param {Object} [opts={}] Custom options, like `state` and `mediaText` - * @return {CssRule} The new/updated rule - * @example - * const rule = cc.setIdRule('myid', { color: 'red' }); - * const ruleHover = cc.setIdRule('myid', { color: 'blue' }, { state: 'hover' }); - * // This will add current CSS: - * // #myid { color: red } - * // #myid:hover { color: blue } - */ - setIdRule(name, style = {}, opts = {}) { - const state = opts.state || ''; - const media = opts.mediaText || em.getCurrentMedia(); - const sm = em.get('SelectorManager'); - const selector = sm.add({ name, type: Selector.TYPE_ID }); - const rule = this.add(selector, state, media); - rule.setStyle(style, opts); - return rule; - }, - - - /** - * Get the CSS rule by id selector - * @param {string} name Id selector name, eg. 'my-id' - * @param {Object} [opts={}] Custom options, like `state` and `mediaText` - * @return {CssRule} - * @example - * const rule = cc.getIdRule('myid'); - * const ruleHover = cc.setIdRule('myid', { state: 'hover' }); - */ - getIdRule(name, opts = {}) { - const state = opts.state || ''; - const media = opts.mediaText || em.getCurrentMedia(); - const selector = em.get('SelectorManager').get(name, Selector.TYPE_ID); - return selector && this.get(selector, state, media); - }, - - - /** - * Add/update the CSS rule with class selector - * @param {string} name Class selector name, eg. 'my-class' - * @param {Object} style Style properties and values - * @param {Object} [opts={}] Custom options, like `state` and `mediaText` - * @return {CssRule} The new/updated rule - * @example - * const rule = cc.setClassRule('myclass', { color: 'red' }); - * const ruleHover = cc.setClassRule('myclass', { color: 'blue' }, { state: 'hover' }); - * // This will add current CSS: - * // .myclass { color: red } - * // .myclass:hover { color: blue } - */ - setClassRule(name, style = {}, opts = {}) { - const state = opts.state || ''; - const media = opts.mediaText || em.getCurrentMedia(); - const sm = em.get('SelectorManager'); - const selector = sm.add({ name, type: Selector.TYPE_CLASS }); - const rule = this.add(selector, state, media); - rule.setStyle(style, opts); - return rule; - }, - - - /** - * Get the CSS rule by class selector - * @param {string} name Class selector name, eg. 'my-class' - * @param {Object} [opts={}] Custom options, like `state` and `mediaText` - * @return {CssRule} - * @example - * const rule = cc.getClassRule('myclass'); - * const ruleHover = cc.getClassRule('myclass', { state: 'hover' }); - */ - getClassRule(name, opts = {}) { - const state = opts.state || ''; - const media = opts.mediaText || em.getCurrentMedia(); - const selector = em.get('SelectorManager').get(name, Selector.TYPE_CLASS); - return selector && this.get(selector, state, media); - }, - - - /** - * Render the block of CSS rules - * @return {HTMLElement} - * @private - */ - render() { - return rulesView.render().el; - }, - - }; + result.push(model); + } + + return result; + }, + + /** + * Add/update the CSS rule with id selector + * @param {string} name Id selector name, eg. 'my-id' + * @param {Object} style Style properties and values + * @param {Object} [opts={}] Custom options, like `state` and `mediaText` + * @return {CssRule} The new/updated rule + * @example + * const rule = cc.setIdRule('myid', { color: 'red' }); + * const ruleHover = cc.setIdRule('myid', { color: 'blue' }, { state: 'hover' }); + * // This will add current CSS: + * // #myid { color: red } + * // #myid:hover { color: blue } + */ + setIdRule(name, style = {}, opts = {}) { + const state = opts.state || ''; + const media = opts.mediaText || em.getCurrentMedia(); + const sm = em.get('SelectorManager'); + const selector = sm.add({ name, type: Selector.TYPE_ID }); + const rule = this.add(selector, state, media); + rule.setStyle(style, opts); + return rule; + }, + + /** + * Get the CSS rule by id selector + * @param {string} name Id selector name, eg. 'my-id' + * @param {Object} [opts={}] Custom options, like `state` and `mediaText` + * @return {CssRule} + * @example + * const rule = cc.getIdRule('myid'); + * const ruleHover = cc.setIdRule('myid', { state: 'hover' }); + */ + getIdRule(name, opts = {}) { + const state = opts.state || ''; + const media = opts.mediaText || em.getCurrentMedia(); + const selector = em.get('SelectorManager').get(name, Selector.TYPE_ID); + return selector && this.get(selector, state, media); + }, + + /** + * Add/update the CSS rule with class selector + * @param {string} name Class selector name, eg. 'my-class' + * @param {Object} style Style properties and values + * @param {Object} [opts={}] Custom options, like `state` and `mediaText` + * @return {CssRule} The new/updated rule + * @example + * const rule = cc.setClassRule('myclass', { color: 'red' }); + * const ruleHover = cc.setClassRule('myclass', { color: 'blue' }, { state: 'hover' }); + * // This will add current CSS: + * // .myclass { color: red } + * // .myclass:hover { color: blue } + */ + setClassRule(name, style = {}, opts = {}) { + const state = opts.state || ''; + const media = opts.mediaText || em.getCurrentMedia(); + const sm = em.get('SelectorManager'); + const selector = sm.add({ name, type: Selector.TYPE_CLASS }); + const rule = this.add(selector, state, media); + rule.setStyle(style, opts); + return rule; + }, + + /** + * Get the CSS rule by class selector + * @param {string} name Class selector name, eg. 'my-class' + * @param {Object} [opts={}] Custom options, like `state` and `mediaText` + * @return {CssRule} + * @example + * const rule = cc.getClassRule('myclass'); + * const ruleHover = cc.getClassRule('myclass', { state: 'hover' }); + */ + getClassRule(name, opts = {}) { + const state = opts.state || ''; + const media = opts.mediaText || em.getCurrentMedia(); + const selector = em.get('SelectorManager').get(name, Selector.TYPE_CLASS); + return selector && this.get(selector, state, media); + }, + + /** + * Render the block of CSS rules + * @return {HTMLElement} + * @private + */ + render() { + return rulesView.render().el; + } + }; }; diff --git a/src/css_composer/model/CssRule.js b/src/css_composer/model/CssRule.js index bfadfbf434..1ea86c623e 100644 --- a/src/css_composer/model/CssRule.js +++ b/src/css_composer/model/CssRule.js @@ -4,8 +4,7 @@ var Backbone = require('backbone'); var Selectors = require('selector_manager/model/Selectors'); module.exports = Backbone.Model.extend(Styleable).extend({ - - defaults: { + defaults: { // Css selectors selectors: {}, @@ -27,9 +26,8 @@ module.exports = Backbone.Model.extend(Styleable).extend({ // If true, sets '!important' on all properties // You can use an array to specify properties to set important // Used in view - important: 0, - }, - + important: 0 + }, initialize(c, opt = {}) { this.config = c || {}; @@ -40,7 +38,7 @@ module.exports = Backbone.Model.extend(Styleable).extend({ if (em) { const sm = em.get('SelectorManager'); const slct = []; - selectors.forEach((selector) => { + selectors.forEach(selector => { slct.push(sm.add(selector)); }); selectors = slct; @@ -49,7 +47,6 @@ module.exports = Backbone.Model.extend(Styleable).extend({ this.set('selectors', new Selectors(selectors)); }, - /** * Return selectors fo the rule as a string * @return {string} @@ -65,7 +62,6 @@ module.exports = Backbone.Model.extend(Styleable).extend({ return result.join(', '); }, - /** * Returns CSS string of the rule * @param {Object} [opts={}] Options @@ -88,7 +84,6 @@ module.exports = Backbone.Model.extend(Styleable).extend({ return result; }, - /** * Compare the actual model with parameters * @param {Object} selectors Collection of selectors @@ -99,42 +94,35 @@ module.exports = Backbone.Model.extend(Styleable).extend({ * @private */ compare(selectors, state, width, ruleProps) { - var otherRule = ruleProps || {}; - var st = state || ''; - var wd = width || ''; - var selectorsAdd = otherRule.selectorsAdd || ''; - var cId = 'cid'; - //var a1 = _.pluck(selectors.models || selectors, cId); - //var a2 = _.pluck(this.get('selectors').models, cId); - if(!(selectors instanceof Array) && !selectors.models) - selectors = [selectors]; - var a1 = _.map((selectors.models || selectors), model => model.get('name')); - var a2 = _.map(this.get('selectors').models, model => model.get('name')); - var f = false; - - if(a1.length !== a2.length) - return f; - - for (var i = 0; i < a1.length; i++) { - var re = 0; - for (var j = 0; j < a2.length; j++) { - if (a1[i] === a2[j]) - re = 1; - } - if(re === 0) - return f; + var otherRule = ruleProps || {}; + var st = state || ''; + var wd = width || ''; + var selectorsAdd = otherRule.selectorsAdd || ''; + var cId = 'cid'; + //var a1 = _.pluck(selectors.models || selectors, cId); + //var a2 = _.pluck(this.get('selectors').models, cId); + if (!(selectors instanceof Array) && !selectors.models) + selectors = [selectors]; + var a1 = _.map(selectors.models || selectors, model => model.get('name')); + var a2 = _.map(this.get('selectors').models, model => model.get('name')); + var f = false; + + if (a1.length !== a2.length) return f; + + for (var i = 0; i < a1.length; i++) { + var re = 0; + for (var j = 0; j < a2.length; j++) { + if (a1[i] === a2[j]) re = 1; } + if (re === 0) return f; + } - if(this.get('state') !== st) - return f; - - if(this.get('mediaText') !== wd) - return f; + if (this.get('state') !== st) return f; - if(this.get('selectorsAdd') !== selectorsAdd) - return f; + if (this.get('mediaText') !== wd) return f; - return true; - }, + if (this.get('selectorsAdd') !== selectorsAdd) return f; + return true; + } }); diff --git a/src/css_composer/model/CssRules.js b/src/css_composer/model/CssRules.js index 19c23ced33..158761d945 100644 --- a/src/css_composer/model/CssRules.js +++ b/src/css_composer/model/CssRules.js @@ -2,27 +2,23 @@ var Backbone = require('backbone'); var CssRule = require('./CssRule'); module.exports = Backbone.Collection.extend({ - initialize(models, opt) { // Inject editor - if(opt && opt.sm) - this.editor = opt.sm; + if (opt && opt.sm) this.editor = opt.sm; // Not used this.model = (attrs, options) => { var model; - if(!options.sm && opt && opt.sm) - options.sm = opt.sm; + if (!options.sm && opt && opt.sm) options.sm = opt.sm; - switch(1){ + switch (1) { default: model = new CssRule(attrs, options); } - return model; + return model; }; - }, add(models, opt = {}) { @@ -31,6 +27,5 @@ module.exports = Backbone.Collection.extend({ } opt.em = this.editor; return Backbone.Collection.prototype.add.apply(this, [models, opt]); - }, - + } }); diff --git a/src/css_composer/view/CssRuleView.js b/src/css_composer/view/CssRuleView.js index 9bc9baf3d8..4a7f29bf21 100644 --- a/src/css_composer/view/CssRuleView.js +++ b/src/css_composer/view/CssRuleView.js @@ -10,12 +10,10 @@ module.exports = require('backbone').View.extend({ this.listenTo(model.get('selectors'), 'change', this.render); }, - render() { const model = this.model; const important = model.get('important'); - this.el.innerHTML = this.model.toCSS({important}); + this.el.innerHTML = this.model.toCSS({ important }); return this; - }, - + } }); diff --git a/src/css_composer/view/CssRulesView.js b/src/css_composer/view/CssRulesView.js index 94ed5905bb..0c2e132f73 100644 --- a/src/css_composer/view/CssRulesView.js +++ b/src/css_composer/view/CssRulesView.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var CssRuleView = require('./CssRuleView'); module.exports = Backbone.View.extend({ - initialize(o) { const config = o.config || {}; this.config = config; @@ -10,8 +9,8 @@ module.exports = Backbone.View.extend({ this.pfx = config.stylePrefix || ''; this.className = this.pfx + 'rules'; const coll = this.collection; - this.listenTo(coll, 'add', this.addTo ); - this.listenTo(coll, 'reset', this.render ); + this.listenTo(coll, 'add', this.addTo); + this.listenTo(coll, 'reset', this.render); }, /** @@ -31,19 +30,17 @@ module.exports = Backbone.View.extend({ * @private * */ addToCollection(model, fragmentEl) { - var fragment = fragmentEl || null; - var viewObject = CssRuleView; + var fragment = fragmentEl || null; + var viewObject = CssRuleView; var view = new viewObject({ - model, - config: this.config, + model, + config: this.config }); - var rendered = view.render().el; + var rendered = view.render().el; - if(fragment) - fragment.appendChild( rendered ); - else - this.$el.append(rendered); + if (fragment) fragment.appendChild(rendered); + else this.$el.append(rendered); return rendered; }, diff --git a/src/device_manager/config/config.js b/src/device_manager/config/config.js index e412a20508..b22a66721a 100644 --- a/src/device_manager/config/config.js +++ b/src/device_manager/config/config.js @@ -1,7 +1,5 @@ module.exports = { - devices: [], - deviceLabel: 'Device', - + deviceLabel: 'Device' }; diff --git a/src/device_manager/index.js b/src/device_manager/index.js index 3a8f5451f3..46190c2fa0 100644 --- a/src/device_manager/index.js +++ b/src/device_manager/index.js @@ -9,104 +9,100 @@ */ module.exports = () => { var c = {}, - defaults = require('./config/config'), - Devices = require('./model/Devices'), - DevicesView = require('./view/DevicesView'); + defaults = require('./config/config'), + Devices = require('./model/Devices'), + DevicesView = require('./view/DevicesView'); var devices, view; return { + /** + * Name of the module + * @type {String} + * @private + */ + name: 'DeviceManager', - /** - * Name of the module - * @type {String} - * @private - */ - name: 'DeviceManager', + /** + * Initialize module. Automatically called with a new instance of the editor + * @param {Object} config Configurations + * @param {Array} [config.devices=[]] Default devices + * @example + * ... + * { + * devices: [ + * {name: 'Desktop', width: ''} + * {name: 'Tablet', width: '991px'} + * ], + * } + * ... + * @return {this} + * @private + */ + init(config) { + c = config || {}; + for (var name in defaults) { + if (!(name in c)) c[name] = defaults[name]; + } - /** - * Initialize module. Automatically called with a new instance of the editor - * @param {Object} config Configurations - * @param {Array} [config.devices=[]] Default devices - * @example - * ... - * { - * devices: [ - * {name: 'Desktop', width: ''} - * {name: 'Tablet', width: '991px'} - * ], - * } - * ... - * @return {this} - * @private - */ - init(config) { - c = config || {}; - for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; - } + devices = new Devices(c.devices); + view = new DevicesView({ + collection: devices, + config: c + }); + return this; + }, - devices = new Devices(c.devices); - view = new DevicesView({ - collection: devices, - config: c - }); - return this; - }, + /** + * Add new device to the collection. URLs are supposed to be unique + * @param {string} name Device name + * @param {string} width Width of the device + * @param {Object} opts Custom options + * @return {Device} Added device + * @example + * deviceManager.add('Tablet', '900px'); + * deviceManager.add('Tablet2', '900px', { + * height: '300px', + * widthMedia: '810px', // the width that will be used for the CSS media + * }); + */ + add(name, width, opts) { + var obj = opts || {}; + obj.name = name; + obj.width = width; + return devices.add(obj); + }, - /** - * Add new device to the collection. URLs are supposed to be unique - * @param {string} name Device name - * @param {string} width Width of the device - * @param {Object} opts Custom options - * @return {Device} Added device - * @example - * deviceManager.add('Tablet', '900px'); - * deviceManager.add('Tablet2', '900px', { - * height: '300px', - * widthMedia: '810px', // the width that will be used for the CSS media - * }); - */ - add(name, width, opts) { - var obj = opts || {}; - obj.name = name; - obj.width = width; - return devices.add(obj); - }, + /** + * Return device by name + * @param {string} name Name of the device + * @example + * var device = deviceManager.get('Tablet'); + * console.log(JSON.stringify(device)); + * // {name: 'Tablet', width: '900px'} + */ + get(name) { + return devices.get(name); + }, - /** - * Return device by name - * @param {string} name Name of the device - * @example - * var device = deviceManager.get('Tablet'); - * console.log(JSON.stringify(device)); - * // {name: 'Tablet', width: '900px'} - */ - get(name) { - return devices.get(name); - }, - - /** - * Return all devices - * @return {Collection} - * @example - * var devices = deviceManager.getAll(); - * console.log(JSON.stringify(devices)); - * // [{name: 'Desktop', width: ''}, ...] - */ - getAll() { - return devices; - }, - - /** - * Render devices - * @return {string} HTML string - * @private - */ - render() { - return view.render().el; - }, + /** + * Return all devices + * @return {Collection} + * @example + * var devices = deviceManager.getAll(); + * console.log(JSON.stringify(devices)); + * // [{name: 'Desktop', width: ''}, ...] + */ + getAll() { + return devices; + }, + /** + * Render devices + * @return {string} HTML string + * @private + */ + render() { + return view.render().el; + } }; - }; diff --git a/src/device_manager/model/Device.js b/src/device_manager/model/Device.js index 07e6d5a882..123906f03e 100644 --- a/src/device_manager/model/Device.js +++ b/src/device_manager/model/Device.js @@ -1,10 +1,9 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - idAttribute: 'name', - defaults :{ + defaults: { name: '', // Width to set for the editor iframe @@ -15,7 +14,7 @@ module.exports = Backbone.Model.extend({ // The width which will be used in media queries, // If empty the width will be used - widthMedia: null, + widthMedia: null }, initialize() { @@ -23,5 +22,4 @@ module.exports = Backbone.Model.extend({ this.set('widthMedia', this.get('width')); } } - }); diff --git a/src/device_manager/model/Devices.js b/src/device_manager/model/Devices.js index 4ffcba36ae..c6ced6ffba 100644 --- a/src/device_manager/model/Devices.js +++ b/src/device_manager/model/Devices.js @@ -2,5 +2,5 @@ var Backbone = require('backbone'); var Device = require('./Device'); module.exports = Backbone.Collection.extend({ - model: Device, + model: Device }); diff --git a/src/device_manager/view/DevicesView.js b/src/device_manager/view/DevicesView.js index a699568bc8..9da83e16bb 100644 --- a/src/device_manager/view/DevicesView.js +++ b/src/device_manager/view/DevicesView.js @@ -1,7 +1,6 @@ var Backbone = require('backbone'); module.exports = Backbone.View.extend({ - template: _.template(`
<%= deviceLabel %>
@@ -15,7 +14,7 @@ module.exports = Backbone.View.extend({ `), events: { - 'change': 'updateDevice' + change: 'updateDevice' }, initialize(o) { @@ -40,7 +39,7 @@ module.exports = Backbone.View.extend({ */ updateDevice() { var em = this.em; - if(em){ + if (em) { var devEl = this.devicesEl; var val = devEl ? devEl.val() : ''; em.set('device', val); @@ -54,7 +53,7 @@ module.exports = Backbone.View.extend({ updateSelect() { var em = this.em; var devEl = this.devicesEl; - if(em && em.getDeviceModel && devEl){ + if (em && em.getDeviceModel && devEl) { var device = em.getDeviceModel(); var name = device ? device.get('name') : ''; devEl.val(name); @@ -70,21 +69,22 @@ module.exports = Backbone.View.extend({ var result = ''; this.collection.each(device => { var name = device.get('name'); - result += ''; + result += ''; }); return result; }, render() { var pfx = this.ppfx; - this.$el.html(this.template({ - ppfx: pfx, - deviceLabel: this.config.deviceLabel - })); + this.$el.html( + this.template({ + ppfx: pfx, + deviceLabel: this.config.deviceLabel + }) + ); this.devicesEl = this.$el.find('.' + pfx + 'devices'); this.devicesEl.append(this.getOptions()); this.el.className = pfx + 'devices-c'; return this; - }, - + } }); diff --git a/src/dom_components/config/config.js b/src/dom_components/config/config.js index 5098e51d2f..7b92d98b17 100644 --- a/src/dom_components/config/config.js +++ b/src/dom_components/config/config.js @@ -12,9 +12,15 @@ module.exports = { draggable: false, components: [], traits: [], - stylable: ['background','background-color','background-image', - 'background-repeat','background-attachment','background-position', - 'background-size'], + stylable: [ + 'background', + 'background-color', + 'background-image', + 'background-repeat', + 'background-attachment', + 'background-position', + 'background-size' + ] }, // Could be used for default components @@ -32,7 +38,22 @@ module.exports = { storeWrapper: 0, // List of void elements - voidElements: ['area', 'base', 'br', 'col', 'embed', 'hr', 'img', - 'input', 'keygen', 'link', 'menuitem', 'meta', 'param', 'source', - 'track', 'wbr'], + voidElements: [ + 'area', + 'base', + 'br', + 'col', + 'embed', + 'hr', + 'img', + 'input', + 'keygen', + 'link', + 'menuitem', + 'meta', + 'param', + 'source', + 'track', + 'wbr' + ] }; diff --git a/src/dom_components/index.js b/src/dom_components/index.js index eddbe820a9..d8e5a56681 100644 --- a/src/dom_components/index.js +++ b/src/dom_components/index.js @@ -46,82 +46,81 @@ module.exports = () => { { id: 'cell', model: require('./model/ComponentTableCell'), - view: require('./view/ComponentTableCellView'), + view: require('./view/ComponentTableCellView') }, { id: 'row', model: require('./model/ComponentTableRow'), - view: require('./view/ComponentTableRowView'), + view: require('./view/ComponentTableRowView') }, { id: 'table', model: require('./model/ComponentTable'), - view: require('./view/ComponentTableView'), + view: require('./view/ComponentTableView') }, { id: 'thead', model: require('./model/ComponentTableHead'), - view: require('./view/ComponentTableHeadView'), + view: require('./view/ComponentTableHeadView') }, { id: 'tbody', model: require('./model/ComponentTableBody'), - view: require('./view/ComponentTableBodyView'), + view: require('./view/ComponentTableBodyView') }, { id: 'tfoot', model: require('./model/ComponentTableFoot'), - view: require('./view/ComponentTableFootView'), + view: require('./view/ComponentTableFootView') }, { id: 'map', model: require('./model/ComponentMap'), - view: require('./view/ComponentMapView'), + view: require('./view/ComponentMapView') }, { id: 'link', model: require('./model/ComponentLink'), - view: require('./view/ComponentLinkView'), + view: require('./view/ComponentLinkView') }, { id: 'video', model: require('./model/ComponentVideo'), - view: require('./view/ComponentVideoView'), + view: require('./view/ComponentVideoView') }, { id: 'image', model: require('./model/ComponentImage'), - view: require('./view/ComponentImageView'), + view: require('./view/ComponentImageView') }, { id: 'script', model: require('./model/ComponentScript'), - view: require('./view/ComponentScriptView'), + view: require('./view/ComponentScriptView') }, { id: 'svg', model: require('./model/ComponentSvg'), - view: require('./view/ComponentSvgView'), + view: require('./view/ComponentSvgView') }, { id: 'textnode', model: require('./model/ComponentTextNode'), - view: require('./view/ComponentTextNodeView'), + view: require('./view/ComponentTextNodeView') }, { id: 'text', model: require('./model/ComponentText'), - view: require('./view/ComponentTextView'), + view: require('./view/ComponentTextView') }, { id: 'default', model: Component, - view: ComponentView, - }, + view: ComponentView + } ]; return { - Component, Components, @@ -143,7 +142,7 @@ module.exports = () => { * @private */ getConfig() { - return c; + return c; }, /** @@ -154,10 +153,8 @@ module.exports = () => { storageKey() { var keys = []; var smc = (c.stm && c.stm.getConfig()) || {}; - if(smc.storeHtml) - keys.push('html'); - if(smc.storeComponents) - keys.push('components'); + if (smc.storeHtml) keys.push('html'); + if (smc.storeComponents) keys.push('components'); return keys; }, @@ -176,13 +173,11 @@ module.exports = () => { } for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } var ppfx = c.pStylePrefix; - if(ppfx) - c.stylePrefix = ppfx + c.stylePrefix; + if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; // Load dependencies if (em) { @@ -199,7 +194,11 @@ module.exports = () => { wrapper.wrapper = 1; // Components might be a wrapper - if (components && components.constructor === Object && components.wrapper) { + if ( + components && + components.constructor === Object && + components.wrapper + ) { wrapper = { ...components }; components = components.components || []; wrapper.components = []; @@ -214,14 +213,14 @@ module.exports = () => { component = new Component(wrapper, { sm: em, config: c, - componentTypes, + componentTypes }); - component.set({ attributes: {id: 'wrapper'}}); + component.set({ attributes: { id: 'wrapper' } }); componentView = new ComponentView({ model: component, config: c, - componentTypes, + componentTypes }); return this; }, @@ -243,7 +242,6 @@ module.exports = () => { this.handleChanges(this.getWrapper(), null, { avoidStore: 1 }); }, - /** * Handle component changes * @private @@ -258,10 +256,11 @@ module.exports = () => { um && comps && um.add(comps); const evn = 'change:style change:content change:attributes change:src'; - [ [model, evn, handleUpdates], + [ + [model, evn, handleUpdates], [comps, 'add', handleChanges], [comps, 'remove', handleRemoves], - [model.get('classes'), 'add remove', handleUpdates], + [model.get('classes'), 'add remove', handleUpdates] ].forEach(els => { em.stopListening(els[0], els[1], els[2]); em.listenTo(els[0], els[1], els[2]); @@ -271,7 +270,6 @@ module.exports = () => { comps.each(model => this.handleChanges(model, value, opts)); }, - /** * Triggered when some component is removed * @private @@ -280,7 +278,6 @@ module.exports = () => { !opts.avoidStore && em.handleUpdates(model, value, opts); }, - /** * Load components from the passed object, if the object is empty will try to fetch them * autonomously from the selected storage @@ -311,8 +308,11 @@ module.exports = () => { // If the result is an object I consider it the wrapper if (isObj) { - this.getWrapper().set(result) - .initComponents().initClasses().loadTraits(); + this.getWrapper() + .set(result) + .initComponents() + .initClasses() + .loadTraits(); } else { this.getComponents().add(result); } @@ -327,7 +327,7 @@ module.exports = () => { * @return {Object} Data to store */ store(noStore) { - if(!c.stm) { + if (!c.stm) { return; } @@ -339,8 +339,9 @@ module.exports = () => { } if (keys.indexOf('components') >= 0) { - const toStore = c.storeWrapper ? - this.getWrapper() : this.getComponents(); + const toStore = c.storeWrapper + ? this.getWrapper() + : this.getComponents(); obj.components = JSON.stringify(toStore); } @@ -454,8 +455,7 @@ module.exports = () => { */ clear() { var c = this.getComponents(); - for(var i = 0, len = c.length; i < len; i++) - c.pop(); + for (var i = 0, len = c.length; i < len; i++) c.pop(); return this; }, @@ -477,7 +477,7 @@ module.exports = () => { */ addType(type, methods) { var compType = this.getType(type); - if(compType) { + if (compType) { compType.model = methods.model; compType.view = methods.view; } else { @@ -496,7 +496,7 @@ module.exports = () => { for (var it = 0; it < df.length; it++) { var dfId = df[it].id; - if(dfId == type) { + if (dfId == type) { return df[it]; } } @@ -516,12 +516,11 @@ module.exports = () => { if (previousModel) { previousModel.set({ status: '', - state: '', + state: '' }); } - model && model.set('status','selected'); + model && model.set('status', 'selected'); } - }; }; diff --git a/src/dom_components/model/Component.js b/src/dom_components/model/Component.js index cd9b1b1c13..3486c9965c 100644 --- a/src/dom_components/model/Component.js +++ b/src/dom_components/model/Component.js @@ -1,4 +1,12 @@ -import { isUndefined, isArray, isEmpty, has, clone, isString, keys } from 'underscore'; +import { + isUndefined, + isArray, + isEmpty, + has, + clone, + isString, + keys +} from 'underscore'; import { shallowDiff } from 'utils/mixins'; import Styleable from 'domain_abstract/model/Styleable'; @@ -10,774 +18,745 @@ const Traits = require('trait_manager/model/Traits'); const componentList = {}; let componentIndex = 0; -const escapeRegExp = (str) => { +const escapeRegExp = str => { return str.replace(/[|\\{}()[\]^$+*?.]/g, '\\$&'); -} +}; -const Component = Backbone.Model.extend(Styleable).extend({ +const Component = Backbone.Model.extend(Styleable).extend( + { + defaults: { + // HTML tag of the component + tagName: 'div', - defaults: { - // HTML tag of the component - tagName: 'div', + // Component type, eg. 'text', 'image', 'video', etc. + type: '', - // Component type, eg. 'text', 'image', 'video', etc. - type: '', + // Name of the component. Will be used, for example, in layers and badges + name: '', - // Name of the component. Will be used, for example, in layers and badges - name: '', + // True if the component is removable from the canvas + removable: true, - // True if the component is removable from the canvas - removable: true, + // Indicates if it's possible to drag the component inside others + // Tip: Indicate an array of selectors where it could be dropped inside + draggable: true, - // Indicates if it's possible to drag the component inside others - // Tip: Indicate an array of selectors where it could be dropped inside - draggable: true, + // Indicates if it's possible to drop other components inside + // Tip: Indicate an array of selectors which could be dropped inside + droppable: true, - // Indicates if it's possible to drop other components inside - // Tip: Indicate an array of selectors which could be dropped inside - droppable: true, + // Set false if don't want to see the badge (with the name) over the component + badgable: true, - // Set false if don't want to see the badge (with the name) over the component - badgable: true, - - // True if it's possible to style it - // Tip: - // Indicate an array of CSS properties which is possible to style, eg. ['color', 'width'] - // All other properties will be hidden from the style manager - stylable: true, - - // Indicate an array of style properties to show up which has been marked as `toRequire` - 'stylable-require': '', - - // Indicate an array of style properties which should be hidden from the style manager - unstylable: '', - - // Highlightable with 'dotted' style if true - highlightable: true, - - // True if it's possible to clone the component - copyable: true, - - // Indicates if it's possible to resize the component (at the moment implemented only on Image Components) - // It's also possible to pass an object as options for the Resizer - resizable: false, - - // Allow to edit the content of the component (used on Text components) - editable: false, - - // Hide the component inside Layers - layerable: true, - - // Allow component to be selected when clicked - selectable: true, - - // Shows a highlight outline when hovering on the element if true - hoverable: true, - - // This property is used by the HTML exporter as void elements do not - // have closing tag, eg.
,
, etc. - void: false, - - // Indicates if the component is in some CSS state like ':hover', ':active', etc. - state: '', - - // State, eg. 'selected' - status: '', - - // Content of the component (not escaped) which will be appended before children rendering - content: '', - - // Component icon, this string will be inserted before the name, eg. '' - icon: '', - - // Component related style - style: '', - - // Key-value object of the component's attributes - attributes: '', - - // Array of classes - classes: '', - - // Component's javascript - script: '', - - // Traits - traits: ['id', 'title'], - - // Indicates an array of properties which will be inhereted by - // all NEW appended children - // - // If you create a model likes this - // removable: false, - // draggable: false, - // propagate: ['removable', 'draggable'] - // When you append some new component inside, the new added model - // will get the exact same properties indicated in `propagate` array - // (as the `propagate` property itself) - // - propagate: '', - - /** - * Set an array of items to show up inside the toolbar (eg. move, clone, delete) - * when the component is selected - * toolbar: [{ - * attributes: {class: 'fa fa-arrows'}, - * command: 'tlb-move', - * },{ - * attributes: {class: 'fa fa-clone'}, - * command: 'tlb-clone', - * }] - */ - toolbar: null, - }, - - - initialize(props = {}, opt = {}) { - const em = opt.sm || opt.em || ''; - - // Propagate properties from parent if indicated - const parent = this.parent(); - const parentAttr = parent && parent.attributes; - - if (parentAttr && parentAttr.propagate) { - let newAttr = {}; - const toPropagate = parentAttr.propagate; - toPropagate.forEach(prop => newAttr[prop] = parent.get(prop)); - newAttr.propagate = toPropagate; - newAttr = {...newAttr, ...props}; - this.set(newAttr); - } - - const propagate = this.get('propagate'); - propagate && this.set('propagate', isArray(propagate) ? propagate : [propagate]); + // True if it's possible to style it + // Tip: + // Indicate an array of CSS properties which is possible to style, eg. ['color', 'width'] + // All other properties will be hidden from the style manager + stylable: true, + + // Indicate an array of style properties to show up which has been marked as `toRequire` + 'stylable-require': '', + + // Indicate an array of style properties which should be hidden from the style manager + unstylable: '', + + // Highlightable with 'dotted' style if true + highlightable: true, + + // True if it's possible to clone the component + copyable: true, + + // Indicates if it's possible to resize the component (at the moment implemented only on Image Components) + // It's also possible to pass an object as options for the Resizer + resizable: false, + + // Allow to edit the content of the component (used on Text components) + editable: false, + + // Hide the component inside Layers + layerable: true, + + // Allow component to be selected when clicked + selectable: true, + + // Shows a highlight outline when hovering on the element if true + hoverable: true, + + // This property is used by the HTML exporter as void elements do not + // have closing tag, eg.
,
, etc. + void: false, + + // Indicates if the component is in some CSS state like ':hover', ':active', etc. + state: '', + + // State, eg. 'selected' + status: '', + + // Content of the component (not escaped) which will be appended before children rendering + content: '', + + // Component icon, this string will be inserted before the name, eg. '' + icon: '', + + // Component related style + style: '', + + // Key-value object of the component's attributes + attributes: '', + + // Array of classes + classes: '', + + // Component's javascript + script: '', + + // Traits + traits: ['id', 'title'], + + // Indicates an array of properties which will be inhereted by + // all NEW appended children + // + // If you create a model likes this + // removable: false, + // draggable: false, + // propagate: ['removable', 'draggable'] + // When you append some new component inside, the new added model + // will get the exact same properties indicated in `propagate` array + // (as the `propagate` property itself) + // + propagate: '', + + /** + * Set an array of items to show up inside the toolbar (eg. move, clone, delete) + * when the component is selected + * toolbar: [{ + * attributes: {class: 'fa fa-arrows'}, + * command: 'tlb-move', + * },{ + * attributes: {class: 'fa fa-clone'}, + * command: 'tlb-clone', + * }] + */ + toolbar: null + }, + + initialize(props = {}, opt = {}) { + const em = opt.sm || opt.em || ''; + + // Propagate properties from parent if indicated + const parent = this.parent(); + const parentAttr = parent && parent.attributes; + + if (parentAttr && parentAttr.propagate) { + let newAttr = {}; + const toPropagate = parentAttr.propagate; + toPropagate.forEach(prop => (newAttr[prop] = parent.get(prop))); + newAttr.propagate = toPropagate; + newAttr = { ...newAttr, ...props }; + this.set(newAttr); + } + const propagate = this.get('propagate'); + propagate && + this.set('propagate', isArray(propagate) ? propagate : [propagate]); - // Check void elements - if(opt && opt.config && - opt.config.voidElements.indexOf(this.get('tagName')) >= 0) { + // Check void elements + if ( + opt && + opt.config && + opt.config.voidElements.indexOf(this.get('tagName')) >= 0 + ) { this.set('void', true); - } - - opt.em = em; - this.opt = opt; - this.sm = em; - this.em = em; - this.config = opt.config || {}; - this.ccid = Component.createId(this); - this.set('attributes', this.get('attributes') || {}); - this.listenTo(this, 'change:script', this.scriptUpdated); - this.listenTo(this, 'change:traits', this.traitsUpdated); - this.listenTo(this, 'change:tagName', this.tagUpdated); - this.listenTo(this, 'change:attributes', this.attrUpdated); - this.initClasses(); - this.loadTraits(); - this.initComponents(); - this.initToolbar(); - this.set('status', ''); - this.listenTo(this.get('classes'), 'add remove change', - () => this.emitUpdate('classes')); - this.init(); - }, - - /** - * Check component's type - * @param {string} type Component type - * @return {Boolean} - * @example - * model.is('image') - * // -> false - */ - is(type) { - return !!(this.get('type') == type); - }, - - - /** - * Find inner models by query string - * ATTENTION: this method works only with alredy rendered component - * @param {string} query Query string - * @return {Array} Array of models - * @example - * model.find('div > .class'); - * // -> [Component, Component, ...] - */ - find(query) { - const result = []; - - this.view.$el.find(query).each((el, i, $els) => { - const $el = $els.eq(i); - const model = $el.data('model'); - model && result.push(model); - }); - - return result; - }, - - - /** - * Once the tag is updated I have to remove the node and replace it - */ - tagUpdated() { - const coll = this.collection; - const at = coll.indexOf(this); - coll.remove(this); - coll.add(this, { at }); - }, - - - /** - * Emit changes for each updated attribute - */ - attrUpdated() { - const attrPrev = { ...this.previous('attributes') }; - const attrCurrent = { ...this.get('attributes') }; - const diff = shallowDiff(attrPrev, attrCurrent); - keys(diff).forEach(pr => this.trigger(`change:attributes:${pr}`)); - }, - - - /** - * Update attributes of the model - * @param {Object} attrs Key value attributes - * @example - * model.setAttributes({id: 'test', 'data-key': 'value'}); - */ - setAttributes(attrs) { - attrs = { ...attrs }; - - // Handle classes - const classes = attrs.class; - classes && this.setClass(classes); - delete attrs.class; - - // Handle style - const style = attrs.style; - style && this.setStyle(style); - delete attrs.style; - - this.set('attributes', attrs); - }, - - - getStyle() { - const em = this.em; - - if (em && em.getConfig('avoidInlineStyle')) { - const state = this.get('state'); - const cc = em.get('CssComposer'); - const rule = cc.getIdRule(this.getId(), { state }); - this.rule = rule; - - if (rule) { - return rule.getStyle(); } - } - - return Styleable.getStyle.call(this); - }, - - - setStyle(prop = {}, opts = {}) { - const em = this.em; - - if (em && em.getConfig('avoidInlineStyle')) { - prop = isString(prop) ? this.parseStyle(prop) : prop; - const state = this.get('state'); - const cc = em.get('CssComposer'); - const propOrig = this.getStyle(); - this.rule = cc.setIdRule(this.getId(), prop, { ...opts, state }); - const diff = shallowDiff(propOrig, prop); - keys(diff).forEach(pr => this.trigger(`change:style:${pr}`)); - } else { - prop = Styleable.setStyle.apply(this, arguments); - } - - return prop; - }, - - - /** - * Return attributes - * @return {Object} - */ - getAttributes() { - const classes = []; - const attributes = { ...this.get('attributes') }; - - // Add classes - this.get('classes').each(cls => classes.push(cls.get('name'))); - classes.length && (attributes.class = classes.join(' ')); - - // If style is not empty I need an ID attached to the component - if (!isEmpty(this.getStyle()) && !has(attributes, 'id')) { - attributes.id = this.getId(); - } - - return attributes; - }, + opt.em = em; + this.opt = opt; + this.sm = em; + this.em = em; + this.config = opt.config || {}; + this.ccid = Component.createId(this); + this.set('attributes', this.get('attributes') || {}); + this.listenTo(this, 'change:script', this.scriptUpdated); + this.listenTo(this, 'change:traits', this.traitsUpdated); + this.listenTo(this, 'change:tagName', this.tagUpdated); + this.listenTo(this, 'change:attributes', this.attrUpdated); + this.initClasses(); + this.loadTraits(); + this.initComponents(); + this.initToolbar(); + this.set('status', ''); + this.listenTo(this.get('classes'), 'add remove change', () => + this.emitUpdate('classes') + ); + this.init(); + }, - /** - * Add classes - * @param {Array|string} classes Array or string of classes - * @return {Array} Array of added selectors - * @example - * model.addClass('class1'); - * model.addClass('class1 class2'); - * model.addClass(['class1', 'class2']); - * // -> [SelectorObject, ...] - */ - addClass(classes) { - const added = this.em.get('SelectorManager').addClass(classes); - return this.get('classes').add(added); - }, + /** + * Check component's type + * @param {string} type Component type + * @return {Boolean} + * @example + * model.is('image') + * // -> false + */ + is(type) { + return !!(this.get('type') == type); + }, + /** + * Find inner models by query string + * ATTENTION: this method works only with alredy rendered component + * @param {string} query Query string + * @return {Array} Array of models + * @example + * model.find('div > .class'); + * // -> [Component, Component, ...] + */ + find(query) { + const result = []; + + this.view.$el.find(query).each((el, i, $els) => { + const $el = $els.eq(i); + const model = $el.data('model'); + model && result.push(model); + }); + + return result; + }, - /** - * Set classes (resets current collection) - * @param {Array|string} classes Array or string of classes - * @return {Array} Array of added selectors - * @example - * model.setClass('class1'); - * model.setClass('class1 class2'); - * model.setClass(['class1', 'class2']); - * // -> [SelectorObject, ...] - */ - setClass(classes) { - this.get('classes').reset(); - return this.addClass(classes); - }, + /** + * Once the tag is updated I have to remove the node and replace it + */ + tagUpdated() { + const coll = this.collection; + const at = coll.indexOf(this); + coll.remove(this); + coll.add(this, { at }); + }, + /** + * Emit changes for each updated attribute + */ + attrUpdated() { + const attrPrev = { ...this.previous('attributes') }; + const attrCurrent = { ...this.get('attributes') }; + const diff = shallowDiff(attrPrev, attrCurrent); + keys(diff).forEach(pr => this.trigger(`change:attributes:${pr}`)); + }, - /** - * Remove classes - * @param {Array|string} classes Array or string of classes - * @return {Array} Array of removed selectors - * @example - * model.removeClass('class1'); - * model.removeClass('class1 class2'); - * model.removeClass(['class1', 'class2']); - * // -> [SelectorObject, ...] - */ - removeClass(classes) { - const removed = []; - classes = isArray(classes) ? classes : [classes]; - const selectors = this.get('classes'); - const type = Selector.TYPE_CLASS; - - classes.forEach(classe => { - const classes = classe.split(' '); - classes.forEach(name => { - const selector = selectors.where({ name, type })[0]; - selector && removed.push(selectors.remove(selector)); - }) - }); - - return removed; - }, + /** + * Update attributes of the model + * @param {Object} attrs Key value attributes + * @example + * model.setAttributes({id: 'test', 'data-key': 'value'}); + */ + setAttributes(attrs) { + attrs = { ...attrs }; + + // Handle classes + const classes = attrs.class; + classes && this.setClass(classes); + delete attrs.class; + + // Handle style + const style = attrs.style; + style && this.setStyle(style); + delete attrs.style; + + this.set('attributes', attrs); + }, + + getStyle() { + const em = this.em; + + if (em && em.getConfig('avoidInlineStyle')) { + const state = this.get('state'); + const cc = em.get('CssComposer'); + const rule = cc.getIdRule(this.getId(), { state }); + this.rule = rule; + + if (rule) { + return rule.getStyle(); + } + } + return Styleable.getStyle.call(this); + }, + + setStyle(prop = {}, opts = {}) { + const em = this.em; + + if (em && em.getConfig('avoidInlineStyle')) { + prop = isString(prop) ? this.parseStyle(prop) : prop; + const state = this.get('state'); + const cc = em.get('CssComposer'); + const propOrig = this.getStyle(); + this.rule = cc.setIdRule(this.getId(), prop, { ...opts, state }); + const diff = shallowDiff(propOrig, prop); + keys(diff).forEach(pr => this.trigger(`change:style:${pr}`)); + } else { + prop = Styleable.setStyle.apply(this, arguments); + } - initClasses() { - const classes = this.normalizeClasses(this.get('classes') || []); - this.set('classes', new Selectors(classes)); - return this; - }, + return prop; + }, + /** + * Return attributes + * @return {Object} + */ + getAttributes() { + const classes = []; + const attributes = { ...this.get('attributes') }; + + // Add classes + this.get('classes').each(cls => classes.push(cls.get('name'))); + classes.length && (attributes.class = classes.join(' ')); + + // If style is not empty I need an ID attached to the component + if (!isEmpty(this.getStyle()) && !has(attributes, 'id')) { + attributes.id = this.getId(); + } - initComponents() { - // Have to add components after the init, otherwise the parent - // is not visible - const comps = new Components(null, this.opt); - comps.parent = this; - comps.reset(this.get('components')); - this.set('components', comps); - return this; - }, + return attributes; + }, + /** + * Add classes + * @param {Array|string} classes Array or string of classes + * @return {Array} Array of added selectors + * @example + * model.addClass('class1'); + * model.addClass('class1 class2'); + * model.addClass(['class1', 'class2']); + * // -> [SelectorObject, ...] + */ + addClass(classes) { + const added = this.em.get('SelectorManager').addClass(classes); + return this.get('classes').add(added); + }, - /** - * Initialize callback - */ - init() {}, - - - /** - * Add new component children - * @param {Component|string} components Component to add - * @param {Object} [opts={}] Options, same as in `model.add()`(from backbone) - * @return {Array} Array of appended components - * @example - * someModel.get('components').lenght // -> 0 - * const videoComponent = someModel.append('
')[0]; - * // This will add 2 components (`video` and `div`) to your `someModel` - * someModel.get('components').lenght // -> 2 - * // You can pass components directly - * otherModel.append(otherModel2); - * otherModel.append([otherModel3, otherModel4]); - */ - append(components, opts = {}) { - const result = this.components().add(components, opts); - return isArray(result) ? result : [result]; - }, + /** + * Set classes (resets current collection) + * @param {Array|string} classes Array or string of classes + * @return {Array} Array of added selectors + * @example + * model.setClass('class1'); + * model.setClass('class1 class2'); + * model.setClass(['class1', 'class2']); + * // -> [SelectorObject, ...] + */ + setClass(classes) { + this.get('classes').reset(); + return this.addClass(classes); + }, + /** + * Remove classes + * @param {Array|string} classes Array or string of classes + * @return {Array} Array of removed selectors + * @example + * model.removeClass('class1'); + * model.removeClass('class1 class2'); + * model.removeClass(['class1', 'class2']); + * // -> [SelectorObject, ...] + */ + removeClass(classes) { + const removed = []; + classes = isArray(classes) ? classes : [classes]; + const selectors = this.get('classes'); + const type = Selector.TYPE_CLASS; + + classes.forEach(classe => { + const classes = classe.split(' '); + classes.forEach(name => { + const selector = selectors.where({ name, type })[0]; + selector && removed.push(selectors.remove(selector)); + }); + }); + + return removed; + }, + + initClasses() { + const classes = this.normalizeClasses(this.get('classes') || []); + this.set('classes', new Selectors(classes)); + return this; + }, + + initComponents() { + // Have to add components after the init, otherwise the parent + // is not visible + const comps = new Components(null, this.opt); + comps.parent = this; + comps.reset(this.get('components')); + this.set('components', comps); + return this; + }, - /** - * Set new collection if `components` are provided, otherwise the - * current collection is returned - * @param {Component|string} [components] Components to set - * @return {Collection|undefined} - * @example - * // Get current collection - * const collection = model.components(); - * // Set new collection - * model.components('
'); - */ - components(components) { - const coll = this.get('components'); - - if (isUndefined(components)) { - return coll; - } else { - coll.reset(); - components && this.append(components); - } - }, + /** + * Initialize callback + */ + init() {}, + /** + * Add new component children + * @param {Component|string} components Component to add + * @param {Object} [opts={}] Options, same as in `model.add()`(from backbone) + * @return {Array} Array of appended components + * @example + * someModel.get('components').lenght // -> 0 + * const videoComponent = someModel.append('
')[0]; + * // This will add 2 components (`video` and `div`) to your `someModel` + * someModel.get('components').lenght // -> 2 + * // You can pass components directly + * otherModel.append(otherModel2); + * otherModel.append([otherModel3, otherModel4]); + */ + append(components, opts = {}) { + const result = this.components().add(components, opts); + return isArray(result) ? result : [result]; + }, - /** - * Get parent model - * @return {Component} - */ - parent() { - const coll = this.collection; - return coll && coll.parent; - }, + /** + * Set new collection if `components` are provided, otherwise the + * current collection is returned + * @param {Component|string} [components] Components to set + * @return {Collection|undefined} + * @example + * // Get current collection + * const collection = model.components(); + * // Set new collection + * model.components('
'); + */ + components(components) { + const coll = this.get('components'); + + if (isUndefined(components)) { + return coll; + } else { + coll.reset(); + components && this.append(components); + } + }, + /** + * Get parent model + * @return {Component} + */ + parent() { + const coll = this.collection; + return coll && coll.parent; + }, - /** - * Script updated - */ - scriptUpdated() { - this.set('scriptUpdated', 1); - }, + /** + * Script updated + */ + scriptUpdated() { + this.set('scriptUpdated', 1); + }, + /** + * Once traits are updated I have to populates model's attributes + */ + traitsUpdated() { + let found = 0; + const attrs = { ...this.get('attributes') }; + const traits = this.get('traits'); + + if (!(traits instanceof Traits)) { + this.loadTraits(); + return; + } - /** - * Once traits are updated I have to populates model's attributes - */ - traitsUpdated() { - let found = 0; - const attrs = { ...this.get('attributes') }; - const traits = this.get('traits'); + traits.each(trait => { + found = 1; + if (!trait.get('changeProp')) { + const value = trait.getInitValue(); + if (value) { + attrs[trait.get('name')] = value; + } + } + }); - if (!(traits instanceof Traits)) { - this.loadTraits(); - return; - } + found && this.set('attributes', attrs); + }, - traits.each((trait) => { - found = 1; - if (!trait.get('changeProp')) { - const value = trait.getInitValue(); - if (value) { - attrs[trait.get('name')] = value; + /** + * Init toolbar + */ + initToolbar() { + var model = this; + if (!model.get('toolbar')) { + var tb = []; + if (model.collection) { + tb.push({ + attributes: { class: 'fa fa-arrow-up' }, + command: 'select-parent' + }); + } + if (model.get('draggable')) { + tb.push({ + attributes: { class: 'fa fa-arrows' }, + command: 'tlb-move' + }); + } + if (model.get('copyable')) { + tb.push({ + attributes: { class: 'fa fa-clone' }, + command: 'tlb-clone' + }); } + if (model.get('removable')) { + tb.push({ + attributes: { class: 'fa fa-trash-o' }, + command: 'tlb-delete' + }); + } + model.set('toolbar', tb); } - }); - - found && this.set('attributes', attrs); - }, + }, - - /** - * Init toolbar - */ - initToolbar() { - var model = this; - if(!model.get('toolbar')) { - var tb = []; - if(model.collection) { - tb.push({ - attributes: {class: 'fa fa-arrow-up'}, - command: 'select-parent', - }); - } - if(model.get('draggable')) { - tb.push({ - attributes: {class: 'fa fa-arrows'}, - command: 'tlb-move', - }); - } - if(model.get('copyable')) { - tb.push({ - attributes: {class: 'fa fa-clone'}, - command: 'tlb-clone', - }); - } - if(model.get('removable')) { - tb.push({ - attributes: {class: 'fa fa-trash-o'}, - command: 'tlb-delete', - }); + /** + * Load traits + * @param {Array} traits + * @private + */ + loadTraits(traits, opts = {}) { + var trt = new Traits([], this.opt); + trt.setTarget(this); + traits = traits || this.get('traits'); + + if (traits.length) { + trt.add(traits); } - model.set('toolbar', tb); - } - }, - - - /** - * Load traits - * @param {Array} traits - * @private - */ - loadTraits(traits, opts = {}) { - var trt = new Traits([], this.opt); - trt.setTarget(this); - traits = traits || this.get('traits'); - - if (traits.length) { - trt.add(traits); - } - - this.set('traits', trt, opts); - return this; - }, - - - /** - * Normalize input classes from array to array of objects - * @param {Array} arr - * @return {Array} - * @private - */ - normalizeClasses(arr) { - var res = []; - if(!this.sm.get) - return; + this.set('traits', trt, opts); + return this; + }, - var clm = this.sm.get('SelectorManager'); - if(!clm) - return; - - arr.forEach(val => { - var name = ''; + /** + * Normalize input classes from array to array of objects + * @param {Array} arr + * @return {Array} + * @private + */ + normalizeClasses(arr) { + var res = []; - if(typeof val === 'string') - name = val; - else - name = val.name; + if (!this.sm.get) return; - var model = clm.add(name); - res.push(model); - }); - return res; - }, + var clm = this.sm.get('SelectorManager'); + if (!clm) return; + arr.forEach(val => { + var name = ''; - /** - * Override original clone method - * @private - */ - clone(reset) { - const em = this.em; - const style = this.getStyle(); - const attr = { ...this.attributes }; - attr.attributes = { ...attr.attributes }; - delete attr.attributes.id; - attr.components = []; - attr.classes = []; - attr.traits = []; - - this.get('components').each((md, i) => { - attr.components[i] = md.clone(1); - }); - this.get('traits').each((md, i) => { - attr.traits[i] = md.clone(); - }); - this.get('classes').each((md, i) => { - attr.classes[i] = md.get('name'); - }); - - attr.status = ''; - attr.view = ''; - - if(reset){ - this.opt.collection = null; - } + if (typeof val === 'string') name = val; + else name = val.name; - if (em && em.getConfig('avoidInlineStyle') && !isEmpty(style)) { - attr.style = style; - } - - return new this.constructor(attr, this.opt); - }, + var model = clm.add(name); + res.push(model); + }); + return res; + }, + /** + * Override original clone method + * @private + */ + clone(reset) { + const em = this.em; + const style = this.getStyle(); + const attr = { ...this.attributes }; + attr.attributes = { ...attr.attributes }; + delete attr.attributes.id; + attr.components = []; + attr.classes = []; + attr.traits = []; + + this.get('components').each((md, i) => { + attr.components[i] = md.clone(1); + }); + this.get('traits').each((md, i) => { + attr.traits[i] = md.clone(); + }); + this.get('classes').each((md, i) => { + attr.classes[i] = md.get('name'); + }); + + attr.status = ''; + attr.view = ''; + + if (reset) { + this.opt.collection = null; + } - /** - * Get the name of the component - * @return {string} - * */ - getName() { - let customName = this.get('name') || this.get('custom-name'); - let tag = this.get('tagName'); - tag = tag == 'div' ? 'box' : tag; - let name = this.get('type') || tag; - name = name.charAt(0).toUpperCase() + name.slice(1); - return customName || name; - }, + if (em && em.getConfig('avoidInlineStyle') && !isEmpty(style)) { + attr.style = style; + } + return new this.constructor(attr, this.opt); + }, - /** - * Get the icon string - * @return {string} - */ - getIcon() { - let icon = this.get('icon'); - return icon ? icon + ' ' : ''; - }, + /** + * Get the name of the component + * @return {string} + * */ + getName() { + let customName = this.get('name') || this.get('custom-name'); + let tag = this.get('tagName'); + tag = tag == 'div' ? 'box' : tag; + let name = this.get('type') || tag; + name = name.charAt(0).toUpperCase() + name.slice(1); + return customName || name; + }, + /** + * Get the icon string + * @return {string} + */ + getIcon() { + let icon = this.get('icon'); + return icon ? icon + ' ' : ''; + }, - /** - * Return HTML string of the component - * @param {Object} opts Options - * @return {string} HTML string - * @private - */ - toHTML(opts) { - const model = this; - const attrs = []; - const classes = []; - const tag = model.get('tagName'); - const sTag = model.get('void'); - const attributes = this.getAttrToHTML(); - - for (let attr in attributes) { - const value = attributes[attr]; - - if (!isUndefined(value)) { + /** + * Return HTML string of the component + * @param {Object} opts Options + * @return {string} HTML string + * @private + */ + toHTML(opts) { + const model = this; + const attrs = []; + const classes = []; + const tag = model.get('tagName'); + const sTag = model.get('void'); + const attributes = this.getAttrToHTML(); + + for (let attr in attributes) { + const value = attributes[attr]; + + if (!isUndefined(value)) { attrs.push(`${attr}="${value}"`); + } } - } - let attrString = attrs.length ? ` ${attrs.join(' ')}` : ''; - let code = `<${tag}${attrString}${sTag ? '/' : ''}>${model.get('content')}`; - model.get('components').each(comp => code += comp.toHTML()); - !sTag && (code += ``); - - return code; - }, + let attrString = attrs.length ? ` ${attrs.join(' ')}` : ''; + let code = `<${tag}${attrString}${sTag ? '/' : ''}>${model.get( + 'content' + )}`; + model.get('components').each(comp => (code += comp.toHTML())); + !sTag && (code += ``); + return code; + }, - /** - * Returns object of attributes for HTML - * @return {Object} - * @private - */ - getAttrToHTML() { - var attr = this.getAttributes(); - delete attr.style; - return attr; - }, - + /** + * Returns object of attributes for HTML + * @return {Object} + * @private + */ + getAttrToHTML() { + var attr = this.getAttributes(); + delete attr.style; + return attr; + }, - /** - * Return a shallow copy of the model's attributes for JSON - * stringification. - * @return {Object} - * @private - */ - toJSON(...args) { - const obj = Backbone.Model.prototype.toJSON.apply(this, args); - const scriptStr = this.getScriptString(); - obj.attributes = this.getAttributes(); - delete obj.attributes.class; - delete obj.toolbar; - scriptStr && (obj.script = scriptStr); - - return obj; - }, + /** + * Return a shallow copy of the model's attributes for JSON + * stringification. + * @return {Object} + * @private + */ + toJSON(...args) { + const obj = Backbone.Model.prototype.toJSON.apply(this, args); + const scriptStr = this.getScriptString(); + obj.attributes = this.getAttributes(); + delete obj.attributes.class; + delete obj.toolbar; + scriptStr && (obj.script = scriptStr); + + return obj; + }, + /** + * Return model id + * @return {string} + */ + getId() { + let attrs = this.get('attributes') || {}; + return attrs.id || this.ccid || this.cid; + }, - /** - * Return model id - * @return {string} - */ - getId() { - let attrs = this.get('attributes') || {}; - return attrs.id || this.ccid || this.cid; - }, + /** + * Return script in string format, cleans 'function() {..' from scripts + * if it's a function + * @param {string|Function} script + * @return {string} + * @private + */ + getScriptString(script) { + var scr = script || this.get('script'); + + if (!scr) { + return scr; + } + // Need to convert script functions to strings + if (typeof scr == 'function') { + var scrStr = scr.toString().trim(); + scrStr = scrStr + .replace(/^function[\s\w]*\(\)\s?\{/, '') + .replace(/\}$/, ''); + scr = scrStr.trim(); + } - /** - * Return script in string format, cleans 'function() {..' from scripts - * if it's a function - * @param {string|Function} script - * @return {string} - * @private - */ - getScriptString(script) { - var scr = script || this.get('script'); + var config = this.sm.config || {}; + var tagVarStart = escapeRegExp(config.tagVarStart || '{[ '); + var tagVarEnd = escapeRegExp(config.tagVarEnd || ' ]}'); + var reg = new RegExp(`${tagVarStart}([\\w\\d-]*)${tagVarEnd}`, 'g'); + scr = scr.replace(reg, (match, v) => { + // If at least one match is found I have to track this change for a + // better optimization inside JS generator + this.scriptUpdated(); + return this.attributes[v] || ''; + }); - if (!scr) { return scr; - } + }, - // Need to convert script functions to strings - if (typeof scr == 'function') { - var scrStr = scr.toString().trim(); - scrStr = scrStr.replace(/^function[\s\w]*\(\)\s?\{/, '').replace(/\}$/, ''); - scr = scrStr.trim(); + emitUpdate(property) { + const em = this.em; + const event = 'component:update' + (property ? `:${property}` : ''); + em && em.trigger(event, this.model); } - - var config = this.sm.config || {}; - var tagVarStart = escapeRegExp(config.tagVarStart || '{[ '); - var tagVarEnd = escapeRegExp(config.tagVarEnd || ' ]}'); - var reg = new RegExp(`${tagVarStart}([\\w\\d-]*)${tagVarEnd}`, 'g'); - scr = scr.replace(reg, (match, v) => { - // If at least one match is found I have to track this change for a - // better optimization inside JS generator - this.scriptUpdated(); - return this.attributes[v] || ''; - }); - - return scr; }, - - - emitUpdate(property) { - const em = this.em; - const event = 'component:update' + (property ? `:${property}` : ''); - em && em.trigger(event, this.model); - }, - -},{ - - /** - * Detect if the passed element is a valid component. - * In case the element is valid an object abstracted - * from the element will be returned - * @param {HTMLElement} - * @return {Object} - * @private - */ - isComponent(el) { - return {tagName: el.tagName ? el.tagName.toLowerCase() : ''}; - }, - - - createId(model) { - componentIndex++; - const nextId = 'i' + componentIndex; - componentList[nextId] = model; - return nextId; - }, - - - getList() { - return componentList; + { + /** + * Detect if the passed element is a valid component. + * In case the element is valid an object abstracted + * from the element will be returned + * @param {HTMLElement} + * @return {Object} + * @private + */ + isComponent(el) { + return { tagName: el.tagName ? el.tagName.toLowerCase() : '' }; + }, + + createId(model) { + componentIndex++; + const nextId = 'i' + componentIndex; + componentList[nextId] = model; + return nextId; + }, + + getList() { + return componentList; + } } -}); +); module.exports = Component; diff --git a/src/dom_components/model/ComponentImage.js b/src/dom_components/model/ComponentImage.js index 2c6d28db1f..1a1a047c95 100644 --- a/src/dom_components/model/ComponentImage.js +++ b/src/dom_components/model/ComponentImage.js @@ -1,103 +1,100 @@ var Component = require('./Component'); -module.exports = Component.extend({ +module.exports = Component.extend( + { + defaults: { + ...Component.prototype.defaults, + type: 'image', + tagName: 'img', + src: '', + void: 1, + droppable: 0, + editable: 1, + highlightable: 0, + resizable: 1, + traits: ['alt'] + }, - defaults: { ...Component.prototype.defaults, - type: 'image', - tagName: 'img', - src: '', - void: 1, - droppable: 0, - editable: 1, - highlightable: 0, - resizable: 1, - traits: ['alt'] - }, - - initialize(o, opt) { - Component.prototype.initialize.apply(this, arguments); - var attr = this.get('attributes'); - if(attr.src) - this.set('src', attr.src); - }, + initialize(o, opt) { + Component.prototype.initialize.apply(this, arguments); + var attr = this.get('attributes'); + if (attr.src) this.set('src', attr.src); + }, - initToolbar(...args) { - Component.prototype.initToolbar.apply(this, args); + initToolbar(...args) { + Component.prototype.initToolbar.apply(this, args); - if (this.sm && this.sm.get) { - var cmd = this.sm.get('Commands'); - var cmdName = 'image-editor'; + if (this.sm && this.sm.get) { + var cmd = this.sm.get('Commands'); + var cmdName = 'image-editor'; - // Add Image Editor button only if the default command exists - if (cmd.has(cmdName)) { - var tb = this.get('toolbar'); - tb.push({ - attributes: {class: 'fa fa-pencil'}, - command: cmdName, - }); - this.set('toolbar', tb); + // Add Image Editor button only if the default command exists + if (cmd.has(cmdName)) { + var tb = this.get('toolbar'); + tb.push({ + attributes: { class: 'fa fa-pencil' }, + command: cmdName + }); + this.set('toolbar', tb); + } } - } - }, + }, - /** - * Returns object of attributes for HTML - * @return {Object} - * @private - */ - getAttrToHTML(...args) { - var attr = Component.prototype.getAttrToHTML.apply(this, args); - delete attr.onmousedown; - var src = this.get('src'); - if(src) - attr.src = src; - return attr; - }, + /** + * Returns object of attributes for HTML + * @return {Object} + * @private + */ + getAttrToHTML(...args) { + var attr = Component.prototype.getAttrToHTML.apply(this, args); + delete attr.onmousedown; + var src = this.get('src'); + if (src) attr.src = src; + return attr; + }, - /** - * Parse uri - * @param {string} uri - * @return {object} - * @private - */ - parseUri(uri) { - var el = document.createElement('a'); - el.href = uri; - var query = {}; - var qrs = el.search.substring(1).split('&'); - for (var i = 0; i < qrs.length; i++) { - var pair = qrs[i].split('='); - var name = decodeURIComponent(pair[0]); - if(name) - query[name] = decodeURIComponent(pair[1]); + /** + * Parse uri + * @param {string} uri + * @return {object} + * @private + */ + parseUri(uri) { + var el = document.createElement('a'); + el.href = uri; + var query = {}; + var qrs = el.search.substring(1).split('&'); + for (var i = 0; i < qrs.length; i++) { + var pair = qrs[i].split('='); + var name = decodeURIComponent(pair[0]); + if (name) query[name] = decodeURIComponent(pair[1]); + } + return { + hostname: el.hostname, + pathname: el.pathname, + protocol: el.protocol, + search: el.search, + hash: el.hash, + port: el.port, + query + }; } - return { - hostname: el.hostname, - pathname: el.pathname, - protocol: el.protocol, - search: el.search, - hash: el.hash, - port: el.port, - query, - }; }, - -},{ - - /** - * Detect if the passed element is a valid component. - * In case the element is valid an object abstracted - * from the element will be returned - * @param {HTMLElement} - * @return {Object} - * @private - */ - isComponent(el) { - var result = ''; - if(el.tagName == 'IMG'){ - result = {type: 'image'}; + { + /** + * Detect if the passed element is a valid component. + * In case the element is valid an object abstracted + * from the element will be returned + * @param {HTMLElement} + * @return {Object} + * @private + */ + isComponent(el) { + var result = ''; + if (el.tagName == 'IMG') { + result = { type: 'image' }; + } + return result; } - return result; - }, - -}); + } +); diff --git a/src/dom_components/model/ComponentLink.js b/src/dom_components/model/ComponentLink.js index 39f91d7ef8..87140575d7 100644 --- a/src/dom_components/model/ComponentLink.js +++ b/src/dom_components/model/ComponentLink.js @@ -1,53 +1,53 @@ const Component = require('./ComponentText'); -module.exports = Component.extend({ - - defaults: { ...Component.prototype.defaults, +module.exports = Component.extend( + { + defaults: { + ...Component.prototype.defaults, type: 'link', tagName: 'a', - traits: ['title', 'href', 'target'], - }, - - /** - * Returns object of attributes for HTML - * @return {Object} - * @private - */ - getAttrToHTML(...args) { - const attr = Component.prototype.getAttrToHTML.apply(this, args); - delete attr.onmousedown; - return attr; + traits: ['title', 'href', 'target'] + }, + + /** + * Returns object of attributes for HTML + * @return {Object} + * @private + */ + getAttrToHTML(...args) { + const attr = Component.prototype.getAttrToHTML.apply(this, args); + delete attr.onmousedown; + return attr; + } }, - -}, { - - isComponent(el) { - let result; - let avoidEdit; - - if (el.tagName == 'A') { - result = { - type: 'link', - editable: 0, - }; - - // The link is editable only if, at least, one of its - // children is a text node (not empty one) - const children = el.childNodes; - const len = children.length; - if (!len) delete result.editable; - - for (let i = 0; i < len; i++) { - const child = children[i]; - - if (child.nodeType == 3 && child.textContent.trim() != '') { - delete result.editable; - break; + { + isComponent(el) { + let result; + let avoidEdit; + + if (el.tagName == 'A') { + result = { + type: 'link', + editable: 0 + }; + + // The link is editable only if, at least, one of its + // children is a text node (not empty one) + const children = el.childNodes; + const len = children.length; + if (!len) delete result.editable; + + for (let i = 0; i < len; i++) { + const child = children[i]; + + if (child.nodeType == 3 && child.textContent.trim() != '') { + delete result.editable; + break; + } } } - } - return result; - }, - -}); + return result; + } + } +); diff --git a/src/dom_components/model/ComponentMap.js b/src/dom_components/model/ComponentMap.js index 0de3780bf7..704ab6d207 100644 --- a/src/dom_components/model/ComponentMap.js +++ b/src/dom_components/model/ComponentMap.js @@ -1,9 +1,9 @@ var Component = require('./ComponentImage'); var OComponent = require('./Component'); -module.exports = Component.extend({ - - defaults: _.extend({}, Component.prototype.defaults, { +module.exports = Component.extend( + { + defaults: _.extend({}, Component.prototype.defaults, { type: 'map', void: 0, mapUrl: 'https://maps.google.com/maps', @@ -11,97 +11,97 @@ module.exports = Component.extend({ mapType: 'q', address: '', zoom: '1', - attributes: {frameborder: 0}, + attributes: { frameborder: 0 }, toolbar: OComponent.prototype.defaults.toolbar, - traits: [{ - label: 'Address', - name: 'address', - placeholder: 'eg. London, UK', - changeProp: 1, - },{ - type: 'select', - label: 'Map type', - name: 'mapType', - changeProp: 1, - options: [ - {value: 'q', name: 'Roadmap'}, - {value: 'w', name: 'Satellite'} - ] - },{ - label: 'Zoom', - name: 'zoom', - type: 'range', - min: '1', - max: '20', - changeProp: 1, - }], - }), - - - initialize(o, opt) { - if(this.get('src')) - this.parseFromSrc(); - else - this.updateSrc(); - Component.prototype.initialize.apply(this, arguments); - this.listenTo(this, 'change:address change:zoom change:mapType', this.updateSrc); - }, - - updateSrc() { - this.set('src', this.getMapUrl()); - }, + traits: [ + { + label: 'Address', + name: 'address', + placeholder: 'eg. London, UK', + changeProp: 1 + }, + { + type: 'select', + label: 'Map type', + name: 'mapType', + changeProp: 1, + options: [ + { value: 'q', name: 'Roadmap' }, + { value: 'w', name: 'Satellite' } + ] + }, + { + label: 'Zoom', + name: 'zoom', + type: 'range', + min: '1', + max: '20', + changeProp: 1 + } + ] + }), - /** - * Returns url of the map - * @return {string} - * @private - */ - getMapUrl() { - var md = this; - var addr = md.get('address'); - var zoom = md.get('zoom'); - var type = md.get('mapType'); - var size = ''; - addr = addr ? '&q=' + addr : ''; - zoom = zoom ? '&z=' + zoom : ''; - type = type ? '&t=' + type : ''; - var result = md.get('mapUrl')+'?' + addr + zoom + type; - result += '&output=embed'; - return result; - }, + initialize(o, opt) { + if (this.get('src')) this.parseFromSrc(); + else this.updateSrc(); + Component.prototype.initialize.apply(this, arguments); + this.listenTo( + this, + 'change:address change:zoom change:mapType', + this.updateSrc + ); + }, - /** - * Set attributes by src string - * @private - */ - parseFromSrc() { - var uri = this.parseUri(this.get('src')); - var qr = uri.query; - if(qr.q) - this.set('address', qr.q); - if(qr.z) - this.set('zoom', qr.z); - if(qr.t) - this.set('mapType', qr.t); - }, + updateSrc() { + this.set('src', this.getMapUrl()); + }, -},{ + /** + * Returns url of the map + * @return {string} + * @private + */ + getMapUrl() { + var md = this; + var addr = md.get('address'); + var zoom = md.get('zoom'); + var type = md.get('mapType'); + var size = ''; + addr = addr ? '&q=' + addr : ''; + zoom = zoom ? '&z=' + zoom : ''; + type = type ? '&t=' + type : ''; + var result = md.get('mapUrl') + '?' + addr + zoom + type; + result += '&output=embed'; + return result; + }, - /** - * Detect if the passed element is a valid component. - * In case the element is valid an object abstracted - * from the element will be returned - * @param {HTMLElement} - * @return {Object} - * @private - */ - isComponent(el) { - var result = ''; - if(el.tagName == 'IFRAME' && - /maps\.google\.com/.test(el.src) ){ - result = {type: 'map', src: el.src}; + /** + * Set attributes by src string + * @private + */ + parseFromSrc() { + var uri = this.parseUri(this.get('src')); + var qr = uri.query; + if (qr.q) this.set('address', qr.q); + if (qr.z) this.set('zoom', qr.z); + if (qr.t) this.set('mapType', qr.t); } - return result; }, - -}); + { + /** + * Detect if the passed element is a valid component. + * In case the element is valid an object abstracted + * from the element will be returned + * @param {HTMLElement} + * @return {Object} + * @private + */ + isComponent(el) { + var result = ''; + if (el.tagName == 'IFRAME' && /maps\.google\.com/.test(el.src)) { + result = { type: 'map', src: el.src }; + } + return result; + } + } +); diff --git a/src/dom_components/model/ComponentScript.js b/src/dom_components/model/ComponentScript.js index a18eae12d7..b3b1bde4cb 100644 --- a/src/dom_components/model/ComponentScript.js +++ b/src/dom_components/model/ComponentScript.js @@ -1,27 +1,26 @@ var Component = require('./Component'); -module.exports = Component.extend({ - - defaults: _.extend({}, Component.prototype.defaults, { - type: 'script', - droppable: false, - draggable: false, - layerable: false, - }), - -}, { +module.exports = Component.extend( + { + defaults: _.extend({}, Component.prototype.defaults, { + type: 'script', + droppable: false, + draggable: false, + layerable: false + }) + }, + { + isComponent(el) { + if (el.tagName == 'SCRIPT') { + var result = { type: 'script' }; - isComponent(el) { - if (el.tagName == 'SCRIPT') { - var result = {type: 'script'}; + if (el.src) { + result.src = el.src; + result.onload = el.onload; + } - if (el.src) { - result.src = el.src; - result.onload = el.onload; + return result; } - - return result; } - }, - -}); + } +); diff --git a/src/dom_components/model/ComponentSvg.js b/src/dom_components/model/ComponentSvg.js index cab7f6c368..db5b2c058d 100644 --- a/src/dom_components/model/ComponentSvg.js +++ b/src/dom_components/model/ComponentSvg.js @@ -1,33 +1,33 @@ var Component = require('./Component'); -module.exports = Component.extend({ +module.exports = Component.extend( + { + defaults: { + ...Component.prototype.defaults, + highlightable: 0 + }, - defaults: { ...Component.prototype.defaults, - highlightable: 0, - }, - - getName() { - let name = this.get('tagName'); - let customName = this.get('custom-name'); - name = name.charAt(0).toUpperCase() + name.slice(1); - return customName || name; - }, - -}, { - - isComponent(el) { - if (SVGElement && el instanceof SVGElement) { - // Some SVG elements require uppercase letters (eg. ) - const tagName = el.tagName; - // Make the root resizable - const resizable = tagName == 'svg' ? true : false; - - return { - tagName, - type: 'svg', - resizable - }; + getName() { + let name = this.get('tagName'); + let customName = this.get('custom-name'); + name = name.charAt(0).toUpperCase() + name.slice(1); + return customName || name; } }, + { + isComponent(el) { + if (SVGElement && el instanceof SVGElement) { + // Some SVG elements require uppercase letters (eg. ) + const tagName = el.tagName; + // Make the root resizable + const resizable = tagName == 'svg' ? true : false; -}); + return { + tagName, + type: 'svg', + resizable + }; + } + } + } +); diff --git a/src/dom_components/model/ComponentTable.js b/src/dom_components/model/ComponentTable.js index 6f784425d3..b500342228 100644 --- a/src/dom_components/model/ComponentTable.js +++ b/src/dom_components/model/ComponentTable.js @@ -1,29 +1,29 @@ const Component = require('./Component'); -module.exports = Component.extend({ - - defaults: { ...Component.prototype.defaults, +module.exports = Component.extend( + { + defaults: { + ...Component.prototype.defaults, type: 'table', tagName: 'table', - droppable: ['tbody', 'thead', 'tfoot'], - }, + droppable: ['tbody', 'thead', 'tfoot'] + }, - initialize(o, opt) { - Component.prototype.initialize.apply(this, arguments); - const components = this.get('components'); - !components.length && components.add({ type: 'tbody' }); + initialize(o, opt) { + Component.prototype.initialize.apply(this, arguments); + const components = this.get('components'); + !components.length && components.add({ type: 'tbody' }); + } }, + { + isComponent(el) { + let result = ''; -}, { - - isComponent(el) { - let result = ''; + if (el.tagName == 'TABLE') { + result = { type: 'table' }; + } - if (el.tagName == 'TABLE') { - result = { type: 'table' }; + return result; } - - return result; - }, - -}); + } +); diff --git a/src/dom_components/model/ComponentTableBody.js b/src/dom_components/model/ComponentTableBody.js index 943bdb33eb..75754ede3d 100644 --- a/src/dom_components/model/ComponentTableBody.js +++ b/src/dom_components/model/ComponentTableBody.js @@ -1,58 +1,58 @@ const Component = require('./Component'); -module.exports = Component.extend({ - - defaults: { ...Component.prototype.defaults, - type: 'tbody', - tagName: 'tbody', - draggable: ['table'], - droppable: ['tr'], - columns: 1, - rows: 1, - }, - - initialize(o, opt) { - Component.prototype.initialize.apply(this, arguments); - const components = this.get('components'); - let columns = this.get('columns'); - let rows = this.get('rows'); - - // Init components if empty - if (!components.length) { - const rowsToAdd = []; - - while (rows--) { - const columnsToAdd = []; - let clm = columns; - - while (clm--) { - columnsToAdd.push({ - type: 'cell', - classes: ['cell'] +module.exports = Component.extend( + { + defaults: { + ...Component.prototype.defaults, + type: 'tbody', + tagName: 'tbody', + draggable: ['table'], + droppable: ['tr'], + columns: 1, + rows: 1 + }, + + initialize(o, opt) { + Component.prototype.initialize.apply(this, arguments); + const components = this.get('components'); + let columns = this.get('columns'); + let rows = this.get('rows'); + + // Init components if empty + if (!components.length) { + const rowsToAdd = []; + + while (rows--) { + const columnsToAdd = []; + let clm = columns; + + while (clm--) { + columnsToAdd.push({ + type: 'cell', + classes: ['cell'] + }); + } + + rowsToAdd.push({ + type: 'row', + classes: ['row'], + components: columnsToAdd }); } - rowsToAdd.push({ - type: 'row', - classes: ['row'], - components: columnsToAdd - }); + components.add(rowsToAdd); } - - components.add(rowsToAdd); } }, + { + isComponent(el) { + let result = ''; -},{ - - isComponent(el) { - let result = ''; + if (el.tagName == 'TBODY') { + result = { type: 'tbody' }; + } - if (el.tagName == 'TBODY') { - result = { type: 'tbody' }; + return result; } - - return result; - }, - -}); + } +); diff --git a/src/dom_components/model/ComponentTableCell.js b/src/dom_components/model/ComponentTableCell.js index 852cd4353d..28dace9c47 100644 --- a/src/dom_components/model/ComponentTableCell.js +++ b/src/dom_components/model/ComponentTableCell.js @@ -1,26 +1,27 @@ const Component = require('./Component'); -module.exports = Component.extend({ - - defaults: { ...Component.prototype.defaults, +module.exports = Component.extend( + { + defaults: { + ...Component.prototype.defaults, type: 'cell', tagName: 'td', - draggable: ['tr'], + draggable: ['tr'] + } }, + { + isComponent(el) { + let result = ''; + const tag = el.tagName; -}, { - isComponent(el) { - let result = ''; - const tag = el.tagName; + if (tag == 'TD' || tag == 'TH') { + result = { + type: 'cell', + tagName: tag.toLowerCase() + }; + } - if (tag == 'TD' || tag == 'TH') { - result = { - type: 'cell', - tagName: tag.toLowerCase() - }; + return result; } - - return result; - }, - -}); + } +); diff --git a/src/dom_components/model/ComponentTableFoot.js b/src/dom_components/model/ComponentTableFoot.js index c6723e8993..67ba53b162 100644 --- a/src/dom_components/model/ComponentTableFoot.js +++ b/src/dom_components/model/ComponentTableFoot.js @@ -1,21 +1,22 @@ const ComponentTableBody = require('./ComponentTableBody'); -module.exports = ComponentTableBody.extend({ - - defaults: { ...ComponentTableBody.prototype.defaults, - type: 'tfoot', - tagName: 'tfoot', +module.exports = ComponentTableBody.extend( + { + defaults: { + ...ComponentTableBody.prototype.defaults, + type: 'tfoot', + tagName: 'tfoot' + } }, + { + isComponent(el) { + let result = ''; -},{ - isComponent(el) { - let result = ''; + if (el.tagName == 'TFOOT') { + result = { type: 'tfoot' }; + } - if (el.tagName == 'TFOOT') { - result = { type: 'tfoot' }; + return result; } - - return result; - }, - -}); + } +); diff --git a/src/dom_components/model/ComponentTableHead.js b/src/dom_components/model/ComponentTableHead.js index b7c383dc67..a645957453 100644 --- a/src/dom_components/model/ComponentTableHead.js +++ b/src/dom_components/model/ComponentTableHead.js @@ -1,21 +1,22 @@ const ComponentTableBody = require('./ComponentTableBody'); -module.exports = ComponentTableBody.extend({ - - defaults: { ...ComponentTableBody.prototype.defaults, - type: 'thead', - tagName: 'thead' +module.exports = ComponentTableBody.extend( + { + defaults: { + ...ComponentTableBody.prototype.defaults, + type: 'thead', + tagName: 'thead' + } }, + { + isComponent(el) { + let result = ''; -}, { - isComponent(el) { - let result = ''; + if (el.tagName == 'THEAD') { + result = { type: 'thead' }; + } - if (el.tagName == 'THEAD') { - result = { type: 'thead' }; + return result; } - - return result; - }, - -}); + } +); diff --git a/src/dom_components/model/ComponentTableRow.js b/src/dom_components/model/ComponentTableRow.js index 9558872f33..0981a044a0 100644 --- a/src/dom_components/model/ComponentTableRow.js +++ b/src/dom_components/model/ComponentTableRow.js @@ -1,33 +1,34 @@ const Component = require('./Component'); -module.exports = Component.extend({ - - defaults: { ...Component.prototype.defaults, +module.exports = Component.extend( + { + defaults: { + ...Component.prototype.defaults, type: 'row', tagName: 'tr', draggable: ['thead', 'tbody', 'tfoot'], droppable: ['th', 'td'] - }, - - initialize(o, opt) { - Component.prototype.initialize.apply(this, arguments); - - // Clean the row from non cell components - const cells = []; - const components = this.get('components'); - components.each(model => model.is('cell') && cells.push(model)); - components.reset(cells); - } + }, -}, { - isComponent(el) { - let result = ''; + initialize(o, opt) { + Component.prototype.initialize.apply(this, arguments); - if (el.tagName == 'TR') { - result = { type: 'row' }; + // Clean the row from non cell components + const cells = []; + const components = this.get('components'); + components.each(model => model.is('cell') && cells.push(model)); + components.reset(cells); } - - return result; }, + { + isComponent(el) { + let result = ''; + + if (el.tagName == 'TR') { + result = { type: 'row' }; + } -}); + return result; + } + } +); diff --git a/src/dom_components/model/ComponentText.js b/src/dom_components/model/ComponentText.js index 58867f0fd6..d914440846 100644 --- a/src/dom_components/model/ComponentText.js +++ b/src/dom_components/model/ComponentText.js @@ -1,11 +1,10 @@ const Component = require('./Component'); module.exports = Component.extend({ - - defaults: { ...Component.prototype.defaults, + defaults: { + ...Component.prototype.defaults, type: 'text', droppable: false, - editable: true, - }, - + editable: true + } }); diff --git a/src/dom_components/model/ComponentTextNode.js b/src/dom_components/model/ComponentTextNode.js index 1cc5d4c8b1..3328c33657 100644 --- a/src/dom_components/model/ComponentTextNode.js +++ b/src/dom_components/model/ComponentTextNode.js @@ -1,27 +1,26 @@ var Component = require('./Component'); -module.exports = Component.extend({ +module.exports = Component.extend( + { + defaults: _.extend({}, Component.prototype.defaults, { + droppable: false, + editable: true + }), - defaults: _.extend({}, Component.prototype.defaults, { - droppable: false, - editable: true, - }), - - toHTML() { - return this.get('content'); - }, - -}, { - - isComponent(el) { - var result = ''; - if(el.nodeType === 3){ - result = { - type: 'textnode', - content: el.textContent - }; + toHTML() { + return this.get('content'); } - return result; }, - -}); + { + isComponent(el) { + var result = ''; + if (el.nodeType === 3) { + result = { + type: 'textnode', + content: el.textContent + }; + } + return result; + } + } +); diff --git a/src/dom_components/model/ComponentVideo.js b/src/dom_components/model/ComponentVideo.js index 1c90500609..f7ef96f412 100644 --- a/src/dom_components/model/ComponentVideo.js +++ b/src/dom_components/model/ComponentVideo.js @@ -3,9 +3,10 @@ const OComponent = require('./Component'); const yt = 'yt'; const vi = 'vi'; -module.exports = Component.extend({ - - defaults: { ...Component.prototype.defaults, +module.exports = Component.extend( + { + defaults: { + ...Component.prototype.defaults, type: 'video', tagName: 'video', videoId: '', @@ -19,302 +20,295 @@ module.exports = Component.extend({ controls: 1, color: '', sources: [], - attributes:{allowfullscreen:'allowfullscreen'}, - toolbar: OComponent.prototype.defaults.toolbar, - }, - - initialize(o, opt) { - var traits = []; - var prov = this.get('provider'); - switch (prov) { - case yt: - traits = this.getYoutubeTraits(); - break; - case vi: - traits = this.getVimeoTraits(); - break; - default: - traits = this.getSourceTraits(); - } - if(this.get('src')) - this.parseFromSrc(); - this.set('traits', traits); - Component.prototype.initialize.apply(this, arguments); - this.listenTo(this, 'change:provider', this.updateTraits); - this.listenTo(this, 'change:videoId', this.updateSrc); - }, + attributes: { allowfullscreen: 'allowfullscreen' }, + toolbar: OComponent.prototype.defaults.toolbar + }, + initialize(o, opt) { + var traits = []; + var prov = this.get('provider'); + switch (prov) { + case yt: + traits = this.getYoutubeTraits(); + break; + case vi: + traits = this.getVimeoTraits(); + break; + default: + traits = this.getSourceTraits(); + } + if (this.get('src')) this.parseFromSrc(); + this.set('traits', traits); + Component.prototype.initialize.apply(this, arguments); + this.listenTo(this, 'change:provider', this.updateTraits); + this.listenTo(this, 'change:videoId', this.updateSrc); + }, - initToolbar(...args) { - OComponent.prototype.initToolbar.apply(this, args); - }, - - /** - * Set attributes by src string - */ - parseFromSrc() { - var prov = this.get('provider'); - var uri = this.parseUri(this.get('src')); - var qr = uri.query; - switch (prov) { - case yt: case vi: - var videoId = uri.pathname.split('/').pop(); - this.set('videoId', videoId); - if(qr.autoplay) - this.set('autoplay', 1); - if(qr.loop) - this.set('loop', 1); - if(parseInt(qr.controls) === 0) - this.set('controls', 0); - if(qr.color) - this.set('color', qr.color); - break; - default: - } - }, + initToolbar(...args) { + OComponent.prototype.initToolbar.apply(this, args); + }, - /** - * Update src on change of video ID - * @private - */ - updateSrc() { - var prov = this.get('provider'); - switch (prov) { - case yt: - this.set('src',this.getYoutubeSrc()); - break; - case vi: - this.set('src',this.getVimeoSrc()); - break; - } - }, + /** + * Set attributes by src string + */ + parseFromSrc() { + var prov = this.get('provider'); + var uri = this.parseUri(this.get('src')); + var qr = uri.query; + switch (prov) { + case yt: + case vi: + var videoId = uri.pathname.split('/').pop(); + this.set('videoId', videoId); + if (qr.autoplay) this.set('autoplay', 1); + if (qr.loop) this.set('loop', 1); + if (parseInt(qr.controls) === 0) this.set('controls', 0); + if (qr.color) this.set('color', qr.color); + break; + default: + } + }, - /** - * Returns object of attributes for HTML - * @return {Object} - * @private - */ - getAttrToHTML(...args) { - var attr = Component.prototype.getAttrToHTML.apply(this, args); - var prov = this.get('provider'); - switch (prov) { - case yt: case vi: - break; - default: - if(this.get('loop')) - attr.loop = 'loop'; - if(this.get('autoplay')) - attr.autoplay = 'autoplay'; - if(this.get('controls')) - attr.controls = 'controls'; - } - return attr; - }, + /** + * Update src on change of video ID + * @private + */ + updateSrc() { + var prov = this.get('provider'); + switch (prov) { + case yt: + this.set('src', this.getYoutubeSrc()); + break; + case vi: + this.set('src', this.getVimeoSrc()); + break; + } + }, - /** - * Update traits by provider - * @private - */ - updateTraits() { - var prov = this.get('provider'); - var traits = this.getSourceTraits(); - switch (prov) { - case yt: - this.set('tagName', 'iframe'); - traits = this.getYoutubeTraits(); - break; - case vi: - this.set('tagName', 'iframe'); - traits = this.getVimeoTraits(); - break; - default: - this.set('tagName', 'video'); - } - this.loadTraits(traits); - this.sm.trigger('change:selectedComponent'); - }, + /** + * Returns object of attributes for HTML + * @return {Object} + * @private + */ + getAttrToHTML(...args) { + var attr = Component.prototype.getAttrToHTML.apply(this, args); + var prov = this.get('provider'); + switch (prov) { + case yt: + case vi: + break; + default: + if (this.get('loop')) attr.loop = 'loop'; + if (this.get('autoplay')) attr.autoplay = 'autoplay'; + if (this.get('controls')) attr.controls = 'controls'; + } + return attr; + }, - // Listen provider change and switch traits, in TraitView listen traits change + /** + * Update traits by provider + * @private + */ + updateTraits() { + var prov = this.get('provider'); + var traits = this.getSourceTraits(); + switch (prov) { + case yt: + this.set('tagName', 'iframe'); + traits = this.getYoutubeTraits(); + break; + case vi: + this.set('tagName', 'iframe'); + traits = this.getVimeoTraits(); + break; + default: + this.set('tagName', 'video'); + } + this.loadTraits(traits); + this.sm.trigger('change:selectedComponent'); + }, - /** - * Return the provider trait - * @return {Object} - * @private - */ - getProviderTrait() { - return { - type: 'select', - label: 'Provider', - name: 'provider', - changeProp: 1, - value: this.get('provider'), - options: [ - {value: 'so', name: 'HTML5 Source'}, - {value: yt, name: 'Youtube'}, - {value: vi, name: 'Vimeo'} - ] - }; - }, + // Listen provider change and switch traits, in TraitView listen traits change - /** - * Return traits for the source provider - * @return {Array} - * @private - */ - getSourceTraits() { - return [ - this.getProviderTrait(), { - label: 'Source', - name: 'src', - placeholder: 'eg. ./media/video.mp4', - changeProp: 1, - }, - this.getAutoplayTrait(), - this.getLoopTrait(), - this.getControlsTrait()]; - }, - /** - * Return traits for the source provider - * @return {Array} - * @private - */ - getYoutubeTraits() { - return [ - this.getProviderTrait(), { - label: 'Video ID', - name: 'videoId', - placeholder: 'eg. jNQXAC9IVRw', + /** + * Return the provider trait + * @return {Object} + * @private + */ + getProviderTrait() { + return { + type: 'select', + label: 'Provider', + name: 'provider', changeProp: 1, - }, - this.getAutoplayTrait(), - this.getLoopTrait(), - this.getControlsTrait() - ]; - }, + value: this.get('provider'), + options: [ + { value: 'so', name: 'HTML5 Source' }, + { value: yt, name: 'Youtube' }, + { value: vi, name: 'Vimeo' } + ] + }; + }, - /** - * Return traits for the source provider - * @return {Array} - * @private - */ - getVimeoTraits() { - return [ - this.getProviderTrait(), { - label: 'Video ID', - name: 'videoId', - placeholder: 'eg. 123456789', - changeProp: 1, - },{ - label: 'Color', - name: 'color', - placeholder: 'eg. FF0000', - changeProp: 1, - }, - this.getAutoplayTrait(), - this.getLoopTrait(), - this.getControlsTrait()]; - }, + /** + * Return traits for the source provider + * @return {Array} + * @private + */ + getSourceTraits() { + return [ + this.getProviderTrait(), + { + label: 'Source', + name: 'src', + placeholder: 'eg. ./media/video.mp4', + changeProp: 1 + }, + this.getAutoplayTrait(), + this.getLoopTrait(), + this.getControlsTrait() + ]; + }, + /** + * Return traits for the source provider + * @return {Array} + * @private + */ + getYoutubeTraits() { + return [ + this.getProviderTrait(), + { + label: 'Video ID', + name: 'videoId', + placeholder: 'eg. jNQXAC9IVRw', + changeProp: 1 + }, + this.getAutoplayTrait(), + this.getLoopTrait(), + this.getControlsTrait() + ]; + }, - /** - * Return object trait - * @return {Object} - * @private - */ - getAutoplayTrait() { - return { - type: 'checkbox', - label: 'Autoplay', - name: 'autoplay', - changeProp: 1, - }; - }, + /** + * Return traits for the source provider + * @return {Array} + * @private + */ + getVimeoTraits() { + return [ + this.getProviderTrait(), + { + label: 'Video ID', + name: 'videoId', + placeholder: 'eg. 123456789', + changeProp: 1 + }, + { + label: 'Color', + name: 'color', + placeholder: 'eg. FF0000', + changeProp: 1 + }, + this.getAutoplayTrait(), + this.getLoopTrait(), + this.getControlsTrait() + ]; + }, - /** - * Return object trait - * @return {Object} - * @private - */ - getLoopTrait() { - return { - type: 'checkbox', - label: 'Loop', - name: 'loop', - changeProp: 1, - }; - }, + /** + * Return object trait + * @return {Object} + * @private + */ + getAutoplayTrait() { + return { + type: 'checkbox', + label: 'Autoplay', + name: 'autoplay', + changeProp: 1 + }; + }, - /** - * Return object trait - * @return {Object} - * @private - */ - getControlsTrait() { - return { - type: 'checkbox', - label: 'Controls', - name: 'controls', - changeProp: 1, - }; - }, + /** + * Return object trait + * @return {Object} + * @private + */ + getLoopTrait() { + return { + type: 'checkbox', + label: 'Loop', + name: 'loop', + changeProp: 1 + }; + }, + /** + * Return object trait + * @return {Object} + * @private + */ + getControlsTrait() { + return { + type: 'checkbox', + label: 'Controls', + name: 'controls', + changeProp: 1 + }; + }, - /** - * Returns url to youtube video - * @return {string} - * @private - */ - getYoutubeSrc() { - var url = this.get('ytUrl'); - url += this.get('videoId') + '?'; - url += this.get('autoplay') ? '&autoplay=1' : ''; - url += !this.get('controls') ? '&controls=0' : ''; - url += this.get('loop') ? '&loop=1' : ''; - return url; - }, + /** + * Returns url to youtube video + * @return {string} + * @private + */ + getYoutubeSrc() { + var url = this.get('ytUrl'); + url += this.get('videoId') + '?'; + url += this.get('autoplay') ? '&autoplay=1' : ''; + url += !this.get('controls') ? '&controls=0' : ''; + url += this.get('loop') ? '&loop=1' : ''; + return url; + }, - /** - * Returns url to vimeo video - * @return {string} - * @private - */ - getVimeoSrc() { - var url = this.get('viUrl'); - url += this.get('videoId') + '?'; - url += this.get('autoplay') ? '&autoplay=1' : ''; - url += this.get('loop') ? '&loop=1' : ''; - url += !this.get('controls') ? '&title=0&portrait=0&badge=0' : ''; - url += this.get('color') ? '&color=' + this.get('color') : ''; - return url; + /** + * Returns url to vimeo video + * @return {string} + * @private + */ + getVimeoSrc() { + var url = this.get('viUrl'); + url += this.get('videoId') + '?'; + url += this.get('autoplay') ? '&autoplay=1' : ''; + url += this.get('loop') ? '&loop=1' : ''; + url += !this.get('controls') ? '&title=0&portrait=0&badge=0' : ''; + url += this.get('color') ? '&color=' + this.get('color') : ''; + return url; + } }, - -},{ - - /** - * Detect if the passed element is a valid component. - * In case the element is valid an object abstracted - * from the element will be returned - * @param {HTMLElement} - * @return {Object} - * @private - */ - isComponent(el) { - var result = ''; - var isYtProv = /youtube\.com\/embed/.test(el.src); - var isViProv = /player\.vimeo\.com\/video/.test(el.src); - var isExtProv = isYtProv || isViProv; - if(el.tagName == 'VIDEO' || - (el.tagName == 'IFRAME' && isExtProv) ){ - result = {type: 'video'}; - if(el.src) - result.src = el.src; - if(isExtProv){ - if(isYtProv) - result.provider = yt; - else if(isViProv) - result.provider = vi; + { + /** + * Detect if the passed element is a valid component. + * In case the element is valid an object abstracted + * from the element will be returned + * @param {HTMLElement} + * @return {Object} + * @private + */ + isComponent(el) { + var result = ''; + var isYtProv = /youtube\.com\/embed/.test(el.src); + var isViProv = /player\.vimeo\.com\/video/.test(el.src); + var isExtProv = isYtProv || isViProv; + if (el.tagName == 'VIDEO' || (el.tagName == 'IFRAME' && isExtProv)) { + result = { type: 'video' }; + if (el.src) result.src = el.src; + if (isExtProv) { + if (isYtProv) result.provider = yt; + else if (isViProv) result.provider = vi; + } } + return result; } - return result; - }, - -}); + } +); diff --git a/src/dom_components/model/Components.js b/src/dom_components/model/Components.js index 71a511370e..e3df908a0b 100644 --- a/src/dom_components/model/Components.js +++ b/src/dom_components/model/Components.js @@ -3,50 +3,43 @@ import { isEmpty } from 'underscore'; const Backbone = require('backbone'); module.exports = Backbone.Collection.extend({ - initialize(models, opt) { - this.on('add', this.onAdd); this.config = opt && opt.config ? opt.config : null; // Inject editor - if(opt && (opt.sm || opt.em)) - this.editor = opt.sm || opt.em; + if (opt && (opt.sm || opt.em)) this.editor = opt.sm || opt.em; - this.model = (attrs, options) => { + this.model = (attrs, options) => { var model; - if(!options.sm && opt && opt.sm) - options.sm = opt.sm; + if (!options.sm && opt && opt.sm) options.sm = opt.sm; - if(!options.em && opt && opt.em) - options.em = opt.em; + if (!options.em && opt && opt.em) options.em = opt.em; - if(opt && opt.config) - options.config = opt.config; + if (opt && opt.config) options.config = opt.config; - if(opt && opt.componentTypes) - options.componentTypes = opt.componentTypes; + if (opt && opt.componentTypes) + options.componentTypes = opt.componentTypes; var df = opt.componentTypes; for (var it = 0; it < df.length; it++) { var dfId = df[it].id; - if(dfId == attrs.type) { + if (dfId == attrs.type) { model = df[it].model; break; } } - if(!model) { + if (!model) { // get the last one model = df[df.length - 1].model; } return new model(attrs, options); }; - }, add(models, opt = {}) { @@ -57,7 +50,7 @@ module.exports = Backbone.Collection.extend({ var cssc = this.editor.get('CssComposer'); if (parsed.css && cssc) { - var {avoidUpdateStyle} = opt; + var { avoidUpdateStyle } = opt; var added = cssc.addCollection(parsed.css, { extend: 1, avoidUpdateStyle @@ -73,15 +66,19 @@ module.exports = Backbone.Collection.extend({ const style = model.get('style'); const avoidInline = em && em.getConfig('avoidInlineStyle'); - if (!isEmpty(style) && !avoidInline && - em && em.get && em.get('Config').forceClass) { - var cssC = this.editor.get('CssComposer'); - var newClass = this.editor.get('SelectorManager').add(model.cid); - model.set({style:{}}); - model.get('classes').add(newClass); - var rule = cssC.add(newClass); - rule.set('style', style); + if ( + !isEmpty(style) && + !avoidInline && + em && + em.get && + em.get('Config').forceClass + ) { + var cssC = this.editor.get('CssComposer'); + var newClass = this.editor.get('SelectorManager').add(model.cid); + model.set({ style: {} }); + model.get('classes').add(newClass); + var rule = cssC.add(newClass); + rule.set('style', style); } - }, - + } }); diff --git a/src/dom_components/model/Toolbar.js b/src/dom_components/model/Toolbar.js index 499b70025a..94367142fa 100644 --- a/src/dom_components/model/Toolbar.js +++ b/src/dom_components/model/Toolbar.js @@ -1,4 +1,4 @@ var Backbone = require('backbone'); var ToolbarButton = require('./ToolbarButton'); -module.exports = Backbone.Collection.extend({model: ToolbarButton}); +module.exports = Backbone.Collection.extend({ model: ToolbarButton }); diff --git a/src/dom_components/model/ToolbarButton.js b/src/dom_components/model/ToolbarButton.js index 5caa202856..b4145ed057 100644 --- a/src/dom_components/model/ToolbarButton.js +++ b/src/dom_components/model/ToolbarButton.js @@ -1,10 +1,8 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - defaults: { - command: '', - attributes: {}, - }, - + command: '', + attributes: {} + } }); diff --git a/src/dom_components/view/ComponentImageView.js b/src/dom_components/view/ComponentImageView.js index d4f3f17079..753d2e72c1 100644 --- a/src/dom_components/view/ComponentImageView.js +++ b/src/dom_components/view/ComponentImageView.js @@ -2,12 +2,11 @@ var Backbone = require('backbone'); var ComponentView = require('./ComponentView'); module.exports = ComponentView.extend({ - tagName: 'img', events: { - 'dblclick': 'openModal', - 'click': 'initResize', + dblclick: 'openModal', + click: 'initResize' }, initialize(o) { @@ -21,19 +20,17 @@ module.exports = ComponentView.extend({ config.am && (this.am = config.am); }, - /** * Update src attribute * @private * */ updateSrc() { - const src = this.model.get("src"); + const src = this.model.get('src'); const el = this.$el; el.attr('src', src); el[src ? 'removeClass' : 'addClass'](this.classEmpty); }, - /** * Open dialog for image changing * @param {Object} e Event @@ -43,7 +40,7 @@ module.exports = ComponentView.extend({ var em = this.opts.config.em; var editor = em ? em.get('Editor') : ''; - if(editor && this.model.get('editable')) { + if (editor && this.model.get('editable')) { editor.runCommand('open-assets', { target: this.model, onSelect() { @@ -54,17 +51,16 @@ module.exports = ComponentView.extend({ } }, - render() { this.updateAttributes(); this.updateClasses(); var actCls = this.$el.attr('class') || ''; - if(!this.model.get('src')) + if (!this.model.get('src')) this.$el.attr('class', (actCls + ' ' + this.classEmpty).trim()); // Avoid strange behaviours while try to drag this.$el.attr('onmousedown', 'return false'); return this; - }, + } }); diff --git a/src/dom_components/view/ComponentLinkView.js b/src/dom_components/view/ComponentLinkView.js index aabf8f3dba..3c6dbcaec8 100644 --- a/src/dom_components/view/ComponentLinkView.js +++ b/src/dom_components/view/ComponentLinkView.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var ComponentView = require('./ComponentTextView'); module.exports = ComponentView.extend({ - render(...args) { ComponentView.prototype.render.apply(this, args); @@ -11,6 +10,5 @@ module.exports = ComponentView.extend({ this.el.addEventListener('click', this.prevDef, true); return this; - }, - + } }); diff --git a/src/dom_components/view/ComponentMapView.js b/src/dom_components/view/ComponentMapView.js index 54b5e76e5e..92f6d7c123 100644 --- a/src/dom_components/view/ComponentMapView.js +++ b/src/dom_components/view/ComponentMapView.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var ComponentView = require('./ComponentImageView'); module.exports = ComponentView.extend({ - tagName: 'div', events: {}, @@ -21,8 +20,8 @@ module.exports = ComponentView.extend({ }, getIframe() { - if(!this.iframe){ - var ifrm = document.createElement("iframe"); + if (!this.iframe) { + var ifrm = document.createElement('iframe'); ifrm.src = this.model.get('src'); ifrm.frameBorder = 0; ifrm.style.height = '100%'; @@ -38,6 +37,5 @@ module.exports = ComponentView.extend({ this.updateClasses(); this.el.appendChild(this.getIframe()); return this; - }, - + } }); diff --git a/src/dom_components/view/ComponentScriptView.js b/src/dom_components/view/ComponentScriptView.js index 9e2d7debda..5a546a1596 100644 --- a/src/dom_components/view/ComponentScriptView.js +++ b/src/dom_components/view/ComponentScriptView.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var ComponentView = require('./ComponentImageView'); module.exports = ComponentView.extend({ - tagName: 'script', events: {}, @@ -15,20 +14,35 @@ module.exports = ComponentView.extend({ var content = ''; // If it's an external script - if(src) { + if (src) { var onload = model.get('onload'); var svar = 'script' + scriptCount; var svarNext = 'script' + (scriptCount + 1); - content = "var "+svar+" = document.createElement('script');\n" + - svar+".onload = function(){\n" + - (onload ? onload + "();\n" : '') + - "typeof "+svarNext+"Start == 'function' && "+svarNext+"Start();\n" + - "};\n" + - svar+".src = '" + src + "';\n"+ - "function "+svar+"Start() { document.body.appendChild("+svar+"); };\n" + - (!scriptCount ? svar+"Start();" : ''); - if(em){ - em.set('scriptCount', scriptCount + 1); + content = + 'var ' + + svar + + " = document.createElement('script');\n" + + svar + + '.onload = function(){\n' + + (onload ? onload + '();\n' : '') + + 'typeof ' + + svarNext + + "Start == 'function' && " + + svarNext + + 'Start();\n' + + '};\n' + + svar + + ".src = '" + + src + + "';\n" + + 'function ' + + svar + + 'Start() { document.body.appendChild(' + + svar + + '); };\n' + + (!scriptCount ? svar + 'Start();' : ''); + if (em) { + em.set('scriptCount', scriptCount + 1); } } else { content = model.get('content'); @@ -36,6 +50,5 @@ module.exports = ComponentView.extend({ this.el.innerHTML = content; return this; - }, - + } }); diff --git a/src/dom_components/view/ComponentSvgView.js b/src/dom_components/view/ComponentSvgView.js index 91a40a8af1..4e54232ed4 100644 --- a/src/dom_components/view/ComponentSvgView.js +++ b/src/dom_components/view/ComponentSvgView.js @@ -1,9 +1,7 @@ const ComponentView = require('./ComponentView'); module.exports = ComponentView.extend({ - _createElement: function(tagName) { return document.createElementNS('http://www.w3.org/2000/svg', tagName); } - }); diff --git a/src/dom_components/view/ComponentTableView.js b/src/dom_components/view/ComponentTableView.js index 55e290a246..56e4aa7336 100644 --- a/src/dom_components/view/ComponentTableView.js +++ b/src/dom_components/view/ComponentTableView.js @@ -2,5 +2,5 @@ var Backbone = require('backbone'); var ComponentView = require('./ComponentView'); module.exports = ComponentView.extend({ - events: {}, + events: {} }); diff --git a/src/dom_components/view/ComponentTextView.js b/src/dom_components/view/ComponentTextView.js index 2471e56452..c9d34644c4 100644 --- a/src/dom_components/view/ComponentTextView.js +++ b/src/dom_components/view/ComponentTextView.js @@ -1,11 +1,10 @@ -import {on, off} from 'utils/mixins' +import { on, off } from 'utils/mixins'; const ComponentView = require('./ComponentView'); module.exports = ComponentView.extend({ - events: { - 'dblclick': 'enableEditing', + dblclick: 'enableEditing' }, initialize(o) { @@ -76,10 +75,10 @@ module.exports = ComponentView.extend({ removable: 0, draggable: 0, copyable: 0, - toolbar: '', - }) + toolbar: '' + }); model.get('components').each(model => clean(model)); - } + }; // Avoid re-render on reset with silent option model.trigger('change:content', model); @@ -108,7 +107,7 @@ module.exports = ComponentView.extend({ */ toggleEvents(enable) { var method = enable ? 'on' : 'off'; - const mixins = {on, off}; + const mixins = { on, off }; // The ownerDocument is from the frame var elDocs = [this.el.ownerDocument, document]; @@ -118,6 +117,5 @@ module.exports = ComponentView.extend({ // Avoid closing edit mode on component click this.$el.off('mousedown', this.disablePropagation); this.$el[method]('mousedown', this.disablePropagation); - }, - + } }); diff --git a/src/dom_components/view/ComponentVideoView.js b/src/dom_components/view/ComponentVideoView.js index 9de803aa49..775c99441d 100644 --- a/src/dom_components/view/ComponentVideoView.js +++ b/src/dom_components/view/ComponentVideoView.js @@ -3,7 +3,6 @@ var ComponentView = require('./ComponentImageView'); var OComponentView = require('./ComponentView'); module.exports = ComponentView.extend({ - tagName: 'div', events: {}, @@ -11,7 +10,11 @@ module.exports = ComponentView.extend({ initialize(o) { OComponentView.prototype.initialize.apply(this, arguments); this.listenTo(this.model, 'change:src', this.updateSrc); - this.listenTo(this.model, 'change:loop change:autoplay change:controls change:color', this.updateVideo); + this.listenTo( + this.model, + 'change:loop change:autoplay change:controls change:color', + this.updateVideo + ); this.listenTo(this.model, 'change:provider', this.updateProvider); }, @@ -52,7 +55,8 @@ module.exports = ComponentView.extend({ var videoEl = this.videoEl; var md = this.model; switch (prov) { - case 'yt': case 'vi': + case 'yt': + case 'vi': this.model.trigger('change:videoId'); break; default: @@ -115,6 +119,5 @@ module.exports = ComponentView.extend({ var prov = this.model.get('provider'); this.el.appendChild(this.renderByProvider(prov)); return this; - }, - + } }); diff --git a/src/dom_components/view/ComponentView.js b/src/dom_components/view/ComponentView.js index 550bf0ac6a..3c6162e746 100644 --- a/src/dom_components/view/ComponentView.js +++ b/src/dom_components/view/ComponentView.js @@ -3,7 +3,6 @@ import { isArray } from 'underscore'; const ComponentsView = require('./ComponentsView'); module.exports = Backbone.View.extend({ - className() { return this.getClasses(); }, @@ -64,7 +63,6 @@ module.exports = Backbone.View.extend({ } }, - /** * Import, if possible, classes inside main container * @private @@ -72,14 +70,13 @@ module.exports = Backbone.View.extend({ importClasses() { var clm = this.config.em.get('SelectorManager'); - if(clm){ + if (clm) { this.model.get('classes').each(m => { - clm.add(m.get('name')); + clm.add(m.get('name')); }); } }, - /** * Fires on state update. If the state is not empty will add a helper class * @param {Event} e @@ -89,14 +86,13 @@ module.exports = Backbone.View.extend({ var cl = 'hc-state'; var state = this.model.get('state'); - if(state){ + if (state) { this.$el.addClass(cl); - }else{ + } else { this.$el.removeClass(cl); } }, - /** * Update item on status change * @param {Event} e @@ -114,17 +110,19 @@ module.exports = Backbone.View.extend({ var cls = ''; switch (status) { - case 'selected': - cls = `${actualCls} ${selectedCls}`; - break; - case 'selected-parent': - cls = `${actualCls} ${selectedParentCls}`; - break; - case 'freezed': - cls = `${actualCls} ${freezedCls}`; - break; - default: - this.$el.removeClass(`${selectedCls} ${selectedParentCls} ${freezedCls}`); + case 'selected': + cls = `${actualCls} ${selectedCls}`; + break; + case 'selected-parent': + cls = `${actualCls} ${selectedParentCls}`; + break; + case 'freezed': + cls = `${actualCls} ${freezedCls}`; + break; + default: + this.$el.removeClass( + `${selectedCls} ${selectedParentCls} ${freezedCls}` + ); } cls = cls.trim(); @@ -134,7 +132,6 @@ module.exports = Backbone.View.extend({ } }, - /** * Update highlight attribute * @private @@ -144,7 +141,6 @@ module.exports = Backbone.View.extend({ this.setAttribute('data-highlightable', hl ? 1 : ''); }, - /** * Update style attribute * @private @@ -161,13 +157,15 @@ module.exports = Backbone.View.extend({ } }, - /** * Update classe attribute * @private * */ updateClasses() { - const str = this.model.get('classes').pluck('name').join(' '); + const str = this.model + .get('classes') + .pluck('name') + .join(' '); this.setAttribute('class', str); // Regenerate status class @@ -192,8 +190,8 @@ module.exports = Backbone.View.extend({ * @private * */ getClasses() { - var attr = this.model.get("attributes"), - classes = attr['class'] || []; + var attr = this.model.get('attributes'), + classes = attr['class'] || []; classes = isArray(classes) ? classes : [classes]; if (classes.length) { @@ -209,7 +207,7 @@ module.exports = Backbone.View.extend({ * */ updateAttributes() { const model = this.model; - const attrs = {} + const attrs = {}; const attr = model.get('attributes'); const src = model.get('src'); @@ -250,7 +248,7 @@ module.exports = Backbone.View.extend({ } var em = this.em; - if(em) { + if (em) { var canvas = em.get('Canvas'); canvas.getCanvasView().updateScript(this); } @@ -301,14 +299,14 @@ module.exports = Backbone.View.extend({ const view = new ComponentsView({ collection: this.model.get('components'), config: this.config, - componentTypes: this.opts.componentTypes, + componentTypes: this.opts.componentTypes }); view.render(container); this.childrenView = view; const childNodes = Array.prototype.slice.call(view.el.childNodes); - for (var i = 0, len = childNodes.length ; i < len; i++) { + for (var i = 0, len = childNodes.length; i < len; i++) { container.appendChild(childNodes.shift()); } @@ -341,6 +339,5 @@ module.exports = Backbone.View.extend({ this.renderChildren(); this.updateScript(); return this; - }, - + } }); diff --git a/src/dom_components/view/ComponentsView.js b/src/dom_components/view/ComponentsView.js index 7408104fb3..647952c03f 100644 --- a/src/dom_components/view/ComponentsView.js +++ b/src/dom_components/view/ComponentsView.js @@ -1,7 +1,6 @@ -import { isUndefined } from 'underscore' +import { isUndefined } from 'underscore'; module.exports = Backbone.View.extend({ - initialize(o) { this.opts = o || {}; this.config = o.config || {}; @@ -38,10 +37,9 @@ module.exports = Backbone.View.extend({ * @private * */ addToCollection(model, fragmentEl, index) { - if(!this.compView) - this.compView = require('./ComponentView'); - var fragment = fragmentEl || null, - viewObject = this.compView; + if (!this.compView) this.compView = require('./ComponentView'); + var fragment = fragmentEl || null, + viewObject = this.compView; var dt = this.opts.componentTypes; @@ -49,7 +47,7 @@ module.exports = Backbone.View.extend({ for (var it = 0; it < dt.length; it++) { var dtId = dt[it].id; - if(dtId == type) { + if (dtId == type) { viewObject = dt[it].view; break; } @@ -59,16 +57,16 @@ module.exports = Backbone.View.extend({ var view = new viewObject({ model, config: this.config, - componentTypes: dt, + componentTypes: dt }); - var rendered = view.render().el; - if(view.model.get('type') == 'textnode') - rendered = document.createTextNode(view.model.get('content')); + var rendered = view.render().el; + if (view.model.get('type') == 'textnode') + rendered = document.createTextNode(view.model.get('content')); if (fragment) { fragment.appendChild(rendered); } else { - const parent = this.parentEl; + const parent = this.parentEl; const children = parent.childNodes; if (!isUndefined(index)) { @@ -102,11 +100,10 @@ module.exports = Backbone.View.extend({ render(parent) { const el = this.el; const frag = document.createDocumentFragment(); - this.parentEl = parent || this.el; + this.parentEl = parent || this.el; this.collection.each(model => this.addToCollection(model, frag)); el.innerHTML = ''; el.appendChild(frag); return this; } - }); diff --git a/src/dom_components/view/ToolbarButtonView.js b/src/dom_components/view/ToolbarButtonView.js index af9fc41b83..13d87930ce 100644 --- a/src/dom_components/view/ToolbarButtonView.js +++ b/src/dom_components/view/ToolbarButtonView.js @@ -2,7 +2,7 @@ var Backbone = require('backbone'); module.exports = Backbone.View.extend({ events: { - 'mousedown': 'handleClick', + mousedown: 'handleClick' }, attributes() { @@ -11,12 +11,12 @@ module.exports = Backbone.View.extend({ initialize(opts) { this.editor = opts.config.editor; - }, + }, handleClick(event) { event.preventDefault(); event.stopPropagation(); - const opts = {event}; + const opts = { event }; const command = this.model.get('command'); const editor = this.editor; @@ -33,6 +33,5 @@ module.exports = Backbone.View.extend({ var config = this.editor.getConfig(); this.el.className += ' ' + config.stylePrefix + 'toolbar-item'; return this; - }, - + } }); diff --git a/src/dom_components/view/ToolbarView.js b/src/dom_components/view/ToolbarView.js index b76cb49318..a984020d59 100644 --- a/src/dom_components/view/ToolbarView.js +++ b/src/dom_components/view/ToolbarView.js @@ -3,12 +3,10 @@ var DomainViews = require('domain_abstract/view/DomainViews'); var ToolbarButtonView = require('./ToolbarButtonView'); module.exports = DomainViews.extend({ - itemView: ToolbarButtonView, initialize(opts) { - this.config = {editor: opts.editor || ''}; + this.config = { editor: opts.editor || '' }; this.listenTo(this.collection, 'reset', this.render); - }, - + } }); diff --git a/src/domain_abstract/model/Styleable.js b/src/domain_abstract/model/Styleable.js index a0d379a8bc..217b656424 100644 --- a/src/domain_abstract/model/Styleable.js +++ b/src/domain_abstract/model/Styleable.js @@ -4,7 +4,6 @@ import ParserHtml from 'parser/model/ParserHtml'; const parseStyle = ParserHtml().parseStyle; export default { - parseStyle, /** @@ -14,10 +13,9 @@ export default { * @return {Object} */ extendStyle(prop) { - return { ...this.getStyle(), ...prop}; + return { ...this.getStyle(), ...prop }; }, - /** * Get style object * @return {Object} @@ -26,7 +24,6 @@ export default { return { ...this.get('style') }; }, - /** * Set new style object * @param {Object|string} prop @@ -47,7 +44,6 @@ export default { return propNew; }, - /** * Add style property * @param {Object|string} prop @@ -69,7 +65,6 @@ export default { this.setStyle(prop, opts); }, - /** * Remove style property * @param {string} prop @@ -80,7 +75,6 @@ export default { this.setStyle(style); }, - /** * Returns string of style properties * @param {Object} [opts={}] Options @@ -98,5 +92,5 @@ export default { } return result.join(''); - }, -} + } +}; diff --git a/src/domain_abstract/model/TypeableCollection.js b/src/domain_abstract/model/TypeableCollection.js index 41394998c9..6a207d9931 100644 --- a/src/domain_abstract/model/TypeableCollection.js +++ b/src/domain_abstract/model/TypeableCollection.js @@ -40,13 +40,15 @@ export default { for (let i = 0; i < types.length; i++) { const type = types[i]; let typeFound = type.isType(value); - typeFound = typeof typeFound == 'boolean' && typeFound ? - {type: type.id} : typeFound; + typeFound = + typeof typeFound == 'boolean' && typeFound + ? { type: type.id } + : typeFound; if (typeFound) { return { type, - attributes: typeFound, + attributes: typeFound }; } } @@ -54,8 +56,8 @@ export default { // If, for any reason, the type is not found it'll return the base one return { type: this.getBaseType(), - attributes: value, - } + attributes: value + }; }, /** @@ -109,7 +111,7 @@ export default { const baseType = this.getBaseType(); const ModelInst = type ? type.model : baseType.model; const ViewInst = type ? type.view : baseType.view; - let {model, view, isType} = definition; + let { model, view, isType } = definition; model = model instanceof Model ? model : ModelInst.extend(model || {}); view = view instanceof View ? view : ViewInst.extend(view || {}); @@ -121,12 +123,14 @@ export default { definition.id = id; definition.model = model; definition.view = view; - definition.isType = isType || function(value) { - if (value && value.type == id) { - return true; - } - }; + definition.isType = + isType || + function(value) { + if (value && value.type == id) { + return true; + } + }; this.getTypes().unshift(definition); } } -} +}; diff --git a/src/domain_abstract/ui/Input.js b/src/domain_abstract/ui/Input.js index 4bb9ad3fc1..4677f3881c 100644 --- a/src/domain_abstract/ui/Input.js +++ b/src/domain_abstract/ui/Input.js @@ -1,17 +1,14 @@ const $ = Backbone.$; module.exports = Backbone.View.extend({ - events: { - 'change': 'handleChange', + change: 'handleChange' }, - template() { return ``; }, - inputClass() { return `${this.ppfx}field`; }, @@ -20,7 +17,6 @@ module.exports = Backbone.View.extend({ return `${this.ppfx}input-holder`; }, - initialize(opts = {}) { const ppfx = opts.ppfx || ''; this.opts = opts; @@ -29,7 +25,6 @@ module.exports = Backbone.View.extend({ this.listenTo(this.model, 'change:value', this.handleModelChange); }, - /** * Fired when the element of the property is updated */ @@ -37,7 +32,6 @@ module.exports = Backbone.View.extend({ this.model.trigger('el:change'); }, - /** * Set value to the input element * @param {string} value @@ -49,7 +43,6 @@ module.exports = Backbone.View.extend({ input && (input.value = val); }, - /** * Updates the view when the model is changed * */ @@ -57,7 +50,6 @@ module.exports = Backbone.View.extend({ this.setValue(value, opts); }, - /** * Handled when the view is changed */ @@ -67,7 +59,6 @@ module.exports = Backbone.View.extend({ this.elementUpdated(); }, - /** * Get the input element * @return {HTMLElement} @@ -81,7 +72,6 @@ module.exports = Backbone.View.extend({ return this.inputEl.get(0); }, - render() { const el = this.$el; el.addClass(this.inputClass()); @@ -89,5 +79,4 @@ module.exports = Backbone.View.extend({ el.find(`.${this.holderClass()}`).append(this.getInputEl()); return this; } - }); diff --git a/src/domain_abstract/ui/InputColor.js b/src/domain_abstract/ui/InputColor.js index b9284a893a..c53674881a 100644 --- a/src/domain_abstract/ui/InputColor.js +++ b/src/domain_abstract/ui/InputColor.js @@ -3,7 +3,6 @@ const Input = require('./Input'); const $ = Backbone.$; module.exports = Input.extend({ - template() { const ppfx = this.ppfx; return ` @@ -59,11 +58,14 @@ module.exports = Input.extend({ var colorEl = $(`
`); var cpStyle = colorEl.get(0).style; var elToAppend = this.em && this.em.config ? this.em.config.el : ''; - var colorPickerConfig = this.em && this.em.getConfig && this.em.getConfig("colorPicker") || {}; + var colorPickerConfig = + (this.em && this.em.getConfig && this.em.getConfig('colorPicker')) || + {}; const getColor = color => { - let cl = color.getAlpha() == 1 ? color.toHexString() : color.toRgbString(); + let cl = + color.getAlpha() == 1 ? color.toHexString() : color.toRgbString(); return cl.replace(/ /g, ''); - } + }; let changed = 0; let previousColor; @@ -73,7 +75,7 @@ module.exports = Input.extend({ appendTo: elToAppend || 'body', maxSelectionSize: 8, showPalette: true, - showAlpha: true, + showAlpha: true, chooseText: 'Ok', cancelText: '⨯', palette: [], @@ -98,14 +100,14 @@ module.exports = Input.extend({ previousColor = getColor(color); }, hide(color) { - if (!changed && previousColor) { - if (self.noneColor) { - previousColor = ''; - } - cpStyle.backgroundColor = previousColor; - colorEl.spectrum('set', previousColor); - model.setValueFromInput(previousColor, 0); - } + if (!changed && previousColor) { + if (self.noneColor) { + previousColor = ''; + } + cpStyle.backgroundColor = previousColor; + colorEl.spectrum('set', previousColor); + model.setValueFromInput(previousColor, 0); + } } }); @@ -120,5 +122,4 @@ module.exports = Input.extend({ this.getColorEl(); return this; } - }); diff --git a/src/domain_abstract/ui/InputNumber.js b/src/domain_abstract/ui/InputNumber.js index 0bc10a17a1..c350720bb7 100644 --- a/src/domain_abstract/ui/InputNumber.js +++ b/src/domain_abstract/ui/InputNumber.js @@ -1,20 +1,18 @@ import { bindAll } from 'underscore'; -import {on, off} from 'utils/mixins'; +import { on, off } from 'utils/mixins'; const Input = require('./Input'); const Backbone = require('backbone'); const $ = Backbone.$; module.exports = Input.extend({ - events: { 'change input': 'handleChange', 'change select': 'handleUnitChange', 'click [data-arrow-up]': 'upArrowClick', 'click [data-arrow-down]': 'downArrowClick', - 'mousedown [data-arrows]': 'downIncrement', + 'mousedown [data-arrows]': 'downIncrement' }, - template() { const ppfx = this.ppfx; return ` @@ -32,7 +30,6 @@ module.exports = Input.extend({ return this.opts.contClass || `${ppfx}field ${ppfx}field-integer`; }, - initialize(opts = {}) { Input.prototype.initialize.apply(this, arguments); bindAll(this, 'moveIncrement', 'upIncrement'); @@ -40,7 +37,6 @@ module.exports = Input.extend({ this.listenTo(this.model, 'change:unit', this.handleModelChange); }, - /** * Set value to the model * @param {string} value @@ -48,11 +44,11 @@ module.exports = Input.extend({ */ setValue(value, opts) { var opt = opts || {}; - var valid = this.validateInputValue(value, {deepCheck: 1}); - var validObj = {value: valid.value}; + var valid = this.validateInputValue(value, { deepCheck: 1 }); + var validObj = { value: valid.value }; // If found some unit value - if(valid.unit || valid.force) { + if (valid.unit || valid.force) { validObj.unit = valid.unit; } @@ -60,12 +56,11 @@ module.exports = Input.extend({ // Generally I get silent when I need to reflect data to view without // reupdating the target - if(opt.silent) { + if (opt.silent) { this.handleModelChange(); } }, - /** * Handled when the view is changed */ @@ -75,7 +70,6 @@ module.exports = Input.extend({ this.elementUpdated(); }, - /** * Handled when the view is changed */ @@ -86,7 +80,6 @@ module.exports = Input.extend({ this.elementUpdated(); }, - /** * Fired when the element of the property is updated */ @@ -94,7 +87,6 @@ module.exports = Input.extend({ this.model.trigger('el:change'); }, - /** * Updates the view when the model is changed * */ @@ -105,7 +97,6 @@ module.exports = Input.extend({ unitEl && (unitEl.value = model.get('unit') || ''); }, - /** * Get the unit element * @return {HTMLElement} @@ -124,7 +115,9 @@ module.exports = Input.extend({ }); const temp = document.createElement('div'); - temp.innerHTML = ``; + temp.innerHTML = ``; this.unitEl = temp.firstChild; } } @@ -132,35 +125,32 @@ module.exports = Input.extend({ return this.unitEl; }, - /** * Invoked when the up arrow is clicked * */ upArrowClick() { const model = this.model; const step = model.get('step'); - let value = parseInt(model.get('value'), 10); + let value = parseInt(model.get('value'), 10); value = this.normalizeValue(value + step); var valid = this.validateInputValue(value); model.set('value', valid.value); this.elementUpdated(); }, - /** * Invoked when the down arrow is clicked * */ downArrowClick() { const model = this.model; const step = model.get('step'); - const value = parseInt(model.get('value'), 10); + const value = parseInt(model.get('value'), 10); const val = this.normalizeValue(value - step); var valid = this.validateInputValue(val); model.set('value', valid.value); this.elementUpdated(); }, - /** * Change easily integer input value with click&drag method * @param Event @@ -172,12 +162,11 @@ module.exports = Input.extend({ this.moved = 0; var value = this.model.get('value'); value = this.normalizeValue(value); - this.current = {y: e.pageY, val: value}; + this.current = { y: e.pageY, val: value }; on(this.doc, 'mousemove', this.moveIncrement); on(this.doc, 'mouseup', this.upIncrement); }, - /** While the increment is clicked, moving the mouse will update input value * @param Object * @@ -190,11 +179,10 @@ module.exports = Input.extend({ const data = this.current; var pos = this.normalizeValue(data.val + (data.y - ev.pageY) * step); this.prValue = this.validateInputValue(pos).value; - model.set('value', this.prValue, {avoidStore: 1}); + model.set('value', this.prValue, { avoidStore: 1 }); return false; }, - /** * Stop moveIncrement method * */ @@ -204,15 +192,13 @@ module.exports = Input.extend({ off(this.doc, 'mouseup', this.upIncrement); off(this.doc, 'mousemove', this.moveIncrement); - if(this.prValue && this.moved) { + if (this.prValue && this.moved) { var value = this.prValue - step; - model.set('value', value, {avoidStore: 1}) - .set('value', value + step); + model.set('value', value, { avoidStore: 1 }).set('value', value + step); this.elementUpdated(); } }, - normalizeValue(value, defValue = 0) { const model = this.model; const step = model.get('step'); @@ -232,7 +218,6 @@ module.exports = Input.extend({ return stepDecimals ? parseFloat(value.toFixed(stepDecimals)) : value; }, - /** * Validate input value * @param {String} value Raw value @@ -249,7 +234,7 @@ module.exports = Input.extend({ var max = model.get('max'); var min = model.get('min'); - if(opt.deepCheck) { + if (opt.deepCheck) { var fixed = model.get('fixedValues') || []; if (val) { @@ -266,17 +251,14 @@ module.exports = Input.extend({ val = !isNaN(val) ? val : model.get('defaults'); var uN = valCopy.replace(val, ''); // Check if exists as unit - if(_.indexOf(units, uN) >= 0) - unit = uN; + if (_.indexOf(units, uN) >= 0) unit = uN; } } } - if(typeof max !== 'undefined' && max !== '') - val = val > max ? max : val; + if (typeof max !== 'undefined' && max !== '') val = val > max ? max : val; - if(typeof min !== 'undefined' && min !== '') - val = val < min ? min : val; + if (typeof min !== 'undefined' && min !== '') val = val < min ? min : val; return { force, @@ -285,12 +267,14 @@ module.exports = Input.extend({ }; }, - render() { Input.prototype.render.call(this); const unit = this.getUnitEl(); - unit && this.$el.find(`.${this.ppfx}field-units`).get(0).appendChild(unit); + unit && + this.$el + .find(`.${this.ppfx}field-units`) + .get(0) + .appendChild(unit); return this; } - }); diff --git a/src/domain_abstract/view/DomainViews.js b/src/domain_abstract/view/DomainViews.js index 6b1d2e708f..ac16b1d7cd 100644 --- a/src/domain_abstract/view/DomainViews.js +++ b/src/domain_abstract/view/DomainViews.js @@ -1,7 +1,6 @@ var Backbone = require('backbone'); module.exports = Backbone.View.extend({ - // Default view itemView: '', @@ -14,7 +13,6 @@ module.exports = Backbone.View.extend({ this.config = config || {}; }, - /** * Add new model to the collection * @param {Model} model @@ -34,34 +32,32 @@ module.exports = Backbone.View.extend({ var frag = fragment || null; var itemView = this.itemView; var typeField = model.get(this.itemType); - if(this.itemsView && this.itemsView[typeField]){ + if (this.itemsView && this.itemsView[typeField]) { itemView = this.itemsView[typeField]; } - var view = new itemView({ - model, - config: this.config - }, this.config); + var view = new itemView( + { + model, + config: this.config + }, + this.config + ); var rendered = view.render().el; - if(frag) - frag.appendChild(rendered); - else - this.$el.append(rendered); + if (frag) frag.appendChild(rendered); + else this.$el.append(rendered); }, - - render() { var frag = document.createDocumentFragment(); this.$el.empty(); - if(this.collection.length) - this.collection.each(function(model){ + if (this.collection.length) + this.collection.each(function(model) { this.add(model, frag); }, this); this.$el.append(frag); return this; - }, - + } }); diff --git a/src/editor/config/config.js b/src/editor/config/config.js index 5e604949c1..2c44d3da47 100644 --- a/src/editor/config/config.js +++ b/src/editor/config/config.js @@ -115,65 +115,106 @@ module.exports = { //Configurations for Device Manager deviceManager: { - devices: [{ + devices: [ + { name: 'Desktop', - width: '', - },{ + width: '' + }, + { name: 'Tablet', width: '768px', - widthMedia: '992px', - },{ + widthMedia: '992px' + }, + { name: 'Mobile landscape', width: '568px', - widthMedia: '768px', - },{ + widthMedia: '768px' + }, + { name: 'Mobile portrait', width: '320px', - widthMedia: '480px', - }], + widthMedia: '480px' + } + ] }, //Configurations for Style Manager styleManager: { - - sectors: [{ + sectors: [ + { name: 'General', open: false, - buildProps: ['float', 'display', 'position', 'top', 'right', 'left', 'bottom'], - },{ + buildProps: [ + 'float', + 'display', + 'position', + 'top', + 'right', + 'left', + 'bottom' + ] + }, + { name: 'Dimension', open: false, - buildProps: ['width', 'height', 'max-width', 'min-height', 'margin', 'padding'], - },{ + buildProps: [ + 'width', + 'height', + 'max-width', + 'min-height', + 'margin', + 'padding' + ] + }, + { name: 'Typography', open: false, - buildProps: ['font-family', 'font-size', 'font-weight', 'letter-spacing', 'color', 'line-height', 'text-align', 'text-shadow'], - properties: [{ + buildProps: [ + 'font-family', + 'font-size', + 'font-weight', + 'letter-spacing', + 'color', + 'line-height', + 'text-align', + 'text-shadow' + ], + properties: [ + { property: 'text-align', - list : [ - {value: 'left', className: 'fa fa-align-left'}, - {value: 'center', className: 'fa fa-align-center' }, - {value: 'right', className: 'fa fa-align-right'}, - {value: 'justify', className: 'fa fa-align-justify'} - ], - }] - },{ + list: [ + { value: 'left', className: 'fa fa-align-left' }, + { value: 'center', className: 'fa fa-align-center' }, + { value: 'right', className: 'fa fa-align-right' }, + { value: 'justify', className: 'fa fa-align-justify' } + ] + } + ] + }, + { name: 'Decorations', open: false, - buildProps: ['border-radius-c', 'background-color', 'border-radius', 'border', 'box-shadow', 'background'], - },{ + buildProps: [ + 'border-radius-c', + 'background-color', + 'border-radius', + 'border', + 'box-shadow', + 'background' + ] + }, + { name: 'Extra', open: false, - buildProps: ['transition', 'perspective', 'transform'], - }], - + buildProps: ['transition', 'perspective', 'transform'] + } + ] }, //Configurations for Block Manager blockManager: {}, - // Texts - textViewCode: 'Code', + textViewCode: 'Code' }; diff --git a/src/editor/index.js b/src/editor/index.js index f8419d863a..dcb86cccf6 100644 --- a/src/editor/index.js +++ b/src/editor/index.js @@ -86,24 +86,22 @@ import $ from 'cash-dom'; module.exports = config => { var c = config || {}, - defaults = require('./config/config'), - EditorModel = require('./model/Editor'), - EditorView = require('./view/EditorView'); + defaults = require('./config/config'), + EditorModel = require('./model/Editor'), + EditorView = require('./view/EditorView'); for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } c.pStylePrefix = c.stylePrefix; var em = new EditorModel(c); var editorView = new EditorView({ - model: em, - config: c, + model: em, + config: c }); return { - $, /** @@ -418,7 +416,7 @@ module.exports = config => { var result; var command = em.get('Commands').get(id); - if(command){ + if (command) { result = command.run(this, this, options); this.trigger('run:' + id); } @@ -437,7 +435,7 @@ module.exports = config => { var result; var command = em.get('Commands').get(id); - if(command){ + if (command) { result = command.stop(this, this, options); this.trigger('stop:' + id); } @@ -581,8 +579,6 @@ module.exports = config => { editorView.render(); return editorView.el; - }, - + } }; - }; diff --git a/src/editor/model/Editor.js b/src/editor/model/Editor.js index 6cb880b9d1..337652fe19 100644 --- a/src/editor/model/Editor.js +++ b/src/editor/model/Editor.js @@ -33,7 +33,6 @@ require('utils/extender')({ const $ = Backbone.$; module.exports = Backbone.Model.extend({ - defaults: { clipboard: null, designerMode: false, @@ -44,7 +43,7 @@ module.exports = Backbone.Model.extend({ modules: [], toLoad: [], opened: {}, - device: '', + device: '' }, initialize(c = {}) { @@ -52,8 +51,7 @@ module.exports = Backbone.Model.extend({ this.set('Config', c); this.set('modules', []); - if(c.el && c.fromElement) - this.config.components = c.el.innerHTML; + if (c.el && c.fromElement) this.config.components = c.el.innerHTML; // Load modules deps.forEach(name => this.loadModule(name)); @@ -61,7 +59,6 @@ module.exports = Backbone.Model.extend({ this.on('change:changesCount', this.updateChanges, this); }, - /** * Get configurations * @param {string} [prop] Property name @@ -73,7 +70,6 @@ module.exports = Backbone.Model.extend({ return isUndefined(prop) ? config : config[prop]; }, - /** * Should be called after all modules and plugins are loaded * @param {Function} clb @@ -102,7 +98,6 @@ module.exports = Backbone.Model.extend({ } }, - /** * Set the alert before unload in case it's requested * and there are unsaved changes @@ -123,7 +118,6 @@ module.exports = Backbone.Model.extend({ } }, - /** * Load generic module * @param {String} moduleName Module name @@ -167,12 +161,10 @@ module.exports = Backbone.Model.extend({ this.set('Editor', editor); }, - getEditor() { return this.get('Editor'); }, - /** * This method handles updates on the editor and tries to store them * if requested and if the changesCount is exceeded @@ -190,12 +182,11 @@ module.exports = Backbone.Model.extend({ timedInterval && clearInterval(timedInterval); timedInterval = setTimeout(() => { if (!opt.avoidStore) { - this.set('changesCount', this.get('changesCount') + 1, opt) + this.set('changesCount', this.get('changesCount') + 1, opt); } }, 0); }, - /** * Callback on component selection * @param {Object} Model @@ -207,12 +198,11 @@ module.exports = Backbone.Model.extend({ if (!this.get('selectedComponent')) { this.trigger('deselect-comp'); } else { - this.trigger('select-comp',[model,val,options]); + this.trigger('select-comp', [model, val, options]); this.trigger('component:selected', arguments); } }, - /** * Returns model of the selected component * @return {Component|null} @@ -235,7 +225,7 @@ module.exports = Backbone.Model.extend({ model = $(el).data('model'); } - if (model && !model.get("selectable")) { + if (model && !model.get('selectable')) { return; } @@ -261,10 +251,9 @@ module.exports = Backbone.Model.extend({ var cmp = this.get('DomComponents'); var cm = this.get('CodeManager'); - if(!cmp || !cm) - return; + if (!cmp || !cm) return; - var wrp = cmp.getComponents(); + var wrp = cmp.getComponents(); return cm.getCode(wrp, 'json'); }, @@ -276,8 +265,7 @@ module.exports = Backbone.Model.extend({ */ setStyle(style) { var rules = this.get('CssComposer').getAll(); - for(var i = 0, len = rules.length; i < len; i++) - rules.pop(); + for (var i = 0, len = rules.length; i < len; i++) rules.pop(); rules.add(style); return this; }, @@ -301,9 +289,10 @@ module.exports = Backbone.Model.extend({ const exportWrapper = config.exportWrapper; const wrappesIsBody = config.wrappesIsBody; const js = config.jsInHtml ? this.getJs() : ''; - var wrp = this.get('DomComponents').getComponent(); + var wrp = this.get('DomComponents').getComponent(); var html = this.get('CodeManager').getCode(wrp, 'html', { - exportWrapper, wrappesIsBody + exportWrapper, + wrappesIsBody }); html += js ? `` : ''; return html; @@ -323,9 +312,13 @@ module.exports = Backbone.Model.extend({ const wrp = this.get('DomComponents').getComponent(); const protCss = !avoidProt ? config.protectedCss : ''; - return protCss + this.get('CodeManager').getCode(wrp, 'css', { - cssc, wrappesIsBody - }); + return ( + protCss + + this.get('CodeManager').getCode(wrp, 'css', { + cssc, + wrappesIsBody + }) + ); }, /** @@ -335,7 +328,9 @@ module.exports = Backbone.Model.extend({ */ getJs() { var wrp = this.get('DomComponents').getWrapper(); - return this.get('CodeManager').getCode(wrp, 'js').trim(); + return this.get('CodeManager') + .getCode(wrp, 'js') + .trim(); }, /** @@ -347,14 +342,12 @@ module.exports = Backbone.Model.extend({ store(clb) { var sm = this.get('StorageManager'); var store = {}; - if(!sm) - return; + if (!sm) return; // Fetch what to store this.get('storables').forEach(m => { var obj = m.store(1); - for(var el in obj) - store[el] = obj[el]; + for (var el in obj) store[el] = obj[el]; }); sm.store(store, () => { @@ -372,7 +365,7 @@ module.exports = Backbone.Model.extend({ * @private */ load(clb = null) { - this.getCacheLoad(1, (res) => { + this.getCacheLoad(1, res => { this.get('storables').forEach(module => module.load(res)); clb && clb(res); }); @@ -387,13 +380,11 @@ module.exports = Backbone.Model.extend({ */ getCacheLoad(force, clb) { var f = force ? 1 : 0; - if(this.cacheLoad && !f) - return this.cacheLoad; + if (this.cacheLoad && !f) return this.cacheLoad; var sm = this.get('StorageManager'); var load = []; - if(!sm) - return {}; + if (!sm) return {}; this.get('storables').forEach(m => { var key = m.storageKey; @@ -428,8 +419,7 @@ module.exports = Backbone.Model.extend({ */ runDefault(opts = {}) { var command = this.get('Commands').get(this.config.defaultCommand); - if(!command || this.defaultRunning) - return; + if (!command || this.defaultRunning) return; command.stop(this, this, opts); command.run(this, this, opts); this.defaultRunning = 1; @@ -442,8 +432,7 @@ module.exports = Backbone.Model.extend({ */ stopDefault(opts = {}) { var command = this.get('Commands').get(this.config.defaultCommand); - if(!command) - return; + if (!command) return; command.stop(this, this, opts); this.defaultRunning = 0; }, @@ -467,7 +456,6 @@ module.exports = Backbone.Model.extend({ w.getSelection().removeAllRanges(); }, - /** * Get the current media text * @return {string} @@ -481,7 +469,6 @@ module.exports = Backbone.Model.extend({ return device && width && !preview ? `(${condition}: ${width})` : ''; }, - /** * Set/get data from the HTMLElement * @param {HTMLElement} el @@ -503,5 +490,4 @@ module.exports = Backbone.Model.extend({ el[varName][name] = value; } } - }); diff --git a/src/editor/view/EditorView.js b/src/editor/view/EditorView.js index ae2745c740..00a0611692 100644 --- a/src/editor/view/EditorView.js +++ b/src/editor/view/EditorView.js @@ -1,7 +1,6 @@ const $ = Backbone.$; module.exports = Backbone.View.extend({ - initialize() { const model = this.model; model.view = this; @@ -23,16 +22,17 @@ module.exports = Backbone.View.extend({ const pfx = conf.stylePrefix; el.empty(); - if (conf.width) - contEl.css('width', conf.width); + if (conf.width) contEl.css('width', conf.width); - if (conf.height) - contEl.css('height', conf.height); + if (conf.height) contEl.css('height', conf.height); el.append(model.get('Canvas').render()); el.append(this.pn.render()); el.attr('class', `${pfx}editor ${pfx}one-bg ${pfx}two-color`); - contEl.addClass(`${pfx}editor-cont`).empty().append(el); + contEl + .addClass(`${pfx}editor-cont`) + .empty() + .append(el); return this; } diff --git a/src/grapesjs/index.js b/src/grapesjs/index.js index 1a24b3235e..36202199b7 100644 --- a/src/grapesjs/index.js +++ b/src/grapesjs/index.js @@ -12,7 +12,6 @@ module.exports = (() => { const editors = []; return { - $, editors, @@ -47,7 +46,8 @@ module.exports = (() => { } defaults(config, defaultConfig); - config.el = els instanceof window.HTMLElement ? els : document.querySelector(els); + config.el = + els instanceof window.HTMLElement ? els : document.querySelector(els); const editor = new Editor(config).init(); // Load plugins @@ -70,8 +70,6 @@ module.exports = (() => { editors.push(editor); return editor; - }, - + } }; - })(); diff --git a/src/keymaps/index.js b/src/keymaps/index.js index f29ce68669..3d7b74b3ca 100644 --- a/src/keymaps/index.js +++ b/src/keymaps/index.js @@ -19,31 +19,28 @@ module.exports = () => { defaults: { 'core:undo': { keys: '⌘+z, ctrl+z', - handler: 'core:undo', + handler: 'core:undo' }, 'core:redo': { keys: '⌘+shift+z, ctrl+shift+z', - handler: 'core:redo', + handler: 'core:redo' }, 'core:copy': { keys: '⌘+c, ctrl+c', - handler: 'core:copy', + handler: 'core:copy' }, 'core:paste': { keys: '⌘+v, ctrl+v', - handler: 'core:paste', + handler: 'core:paste' } } }; return { - keymaster, - name: 'Keymaps', - /** * Get module configurations * @return {Object} Configuration object @@ -52,7 +49,6 @@ module.exports = () => { return config; }, - /** * Initialize module * @param {Object} config Configurations @@ -65,7 +61,6 @@ module.exports = () => { return this; }, - onLoad() { const defKeys = config.defaults; @@ -75,7 +70,6 @@ module.exports = () => { } }, - /** * Add new keymap * @param {string} id Keymap id @@ -116,7 +110,6 @@ module.exports = () => { return keymap; }, - /** * Get the keymap by id * @param {string} id Keymap id @@ -129,7 +122,6 @@ module.exports = () => { return keymaps[id]; }, - /** * Get all keymaps * @return {Object} @@ -141,7 +133,6 @@ module.exports = () => { return keymaps; }, - /** * Remove the keymap by id * @param {string} id Keymap id @@ -160,8 +151,6 @@ module.exports = () => { em && em.trigger('keymap:remove', keymap); return keymap; } - }, - - + } }; }; diff --git a/src/modal_dialog/config/config.js b/src/modal_dialog/config/config.js index 0bf040bae4..d333148196 100644 --- a/src/modal_dialog/config/config.js +++ b/src/modal_dialog/config/config.js @@ -1,11 +1,9 @@ module.exports = { - stylePrefix: 'mdl-', title: '', content: '', - backdrop: true, - -};; + backdrop: true +}; diff --git a/src/modal_dialog/index.js b/src/modal_dialog/index.js index e5f0e512fb..9bbf4c4b05 100644 --- a/src/modal_dialog/index.js +++ b/src/modal_dialog/index.js @@ -16,14 +16,13 @@ */ module.exports = () => { var c = {}, - defaults = require('./config/config'), - ModalM = require('./model/Modal'), - ModalView = require('./view/ModalView'); + defaults = require('./config/config'), + ModalM = require('./model/Modal'), + ModalView = require('./view/ModalView'); var model, modal; return { - - /** + /** * Name of the module * @type {String} * @private @@ -38,18 +37,16 @@ module.exports = () => { init(config) { c = config || {}; for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } var ppfx = c.pStylePrefix; - if(ppfx) - c.stylePrefix = ppfx + c.stylePrefix; + if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; model = new ModalM(c); modal = new ModalView({ model, - config: c, + config: c }); return this; diff --git a/src/modal_dialog/model/Modal.js b/src/modal_dialog/model/Modal.js index c50e9ed301..01d759ac68 100644 --- a/src/modal_dialog/model/Modal.js +++ b/src/modal_dialog/model/Modal.js @@ -4,6 +4,6 @@ module.exports = Backbone.Model.extend({ defaults: { title: '', content: '', - open: false, + open: false } }); diff --git a/src/modal_dialog/view/ModalView.js b/src/modal_dialog/view/ModalView.js index 70651c90c8..bbc81dcd67 100644 --- a/src/modal_dialog/view/ModalView.js +++ b/src/modal_dialog/view/ModalView.js @@ -1,6 +1,5 @@ module.exports = require('backbone').View.extend({ - - template({pfx, ppfx, content, title}) { + template({ pfx, ppfx, content, title }) { return `
${title}
@@ -28,7 +27,7 @@ module.exports = require('backbone').View.extend({ this.listenTo(model, 'change:open', this.updateOpen); this.listenTo(model, 'change:title', this.updateTitle); this.listenTo(model, 'change:content', this.updateContent); - this.events[`click .${pfx}btn-close`] = 'hide'; + this.events[`click .${pfx}btn-close`] = 'hide'; bkd && (this.events[`click .${pfx}backlayer`] = 'hide'); this.delegateEvents(); }, @@ -39,8 +38,8 @@ module.exports = require('backbone').View.extend({ * @private */ getCollector() { - if(!this.$collector) - this.$collector = this.$el.find('.'+this.pfx+'collector'); + if (!this.$collector) + this.$collector = this.$el.find('.' + this.pfx + 'collector'); return this.$collector; }, @@ -65,8 +64,7 @@ module.exports = require('backbone').View.extend({ * @private */ getTitle() { - if(!this.$title) - this.$title = this.$el.find('.'+this.pfx+'title'); + if (!this.$title) this.$title = this.$el.find('.' + this.pfx + 'title'); return this.$title.get(0); }, @@ -89,8 +87,7 @@ module.exports = require('backbone').View.extend({ * */ updateTitle() { var title = this.getTitle(); - if(title) - title.innerHTML = this.model.get('title'); + if (title) title.innerHTML = this.model.get('title'); }, /** @@ -113,7 +110,7 @@ module.exports = require('backbone').View.extend({ * Show modal * @private * */ - show() { + show() { this.model.set('open', 1); }, @@ -128,6 +125,5 @@ module.exports = require('backbone').View.extend({ el.attr('class', `${pfx}container`); this.updateOpen(); return this; - }, - + } }); diff --git a/src/navigator/config/config.js b/src/navigator/config/config.js index 1ca049f51b..aaca2c84fa 100644 --- a/src/navigator/config/config.js +++ b/src/navigator/config/config.js @@ -11,5 +11,5 @@ module.exports = { hideTextnode: 1, // Indicates if the wrapper is visible in layers - showWrapper: 1, + showWrapper: 1 }; diff --git a/src/navigator/index.js b/src/navigator/index.js index 93267562ba..437aefd970 100644 --- a/src/navigator/index.js +++ b/src/navigator/index.js @@ -12,8 +12,7 @@ module.exports = () => { // Set default options for (var name in defaults) { - if (!(name in config)) - config[name] = defaults[name]; + if (!(name in config)) config[name] = defaults[name]; } let View = ItemsView; @@ -23,14 +22,14 @@ module.exports = () => { level, config, opened - } + }; // Show wrapper if requested if (config.showWrapper && collection.parent) { View = ItemView; options.model = collection.parent; } else { - options.collection = collection + options.collection = collection; } itemsView = new View(options); @@ -67,6 +66,6 @@ module.exports = () => { render() { return itemsView.render().$el; - }, - } + } + }; }; diff --git a/src/navigator/view/ItemView.js b/src/navigator/view/ItemView.js index b641879f03..2bace9326a 100644 --- a/src/navigator/view/ItemView.js +++ b/src/navigator/view/ItemView.js @@ -3,17 +3,15 @@ const ComponentView = require('dom_components/view/ComponentView'); let ItemsView; module.exports = require('backbone').View.extend({ - events: { 'mousedown [data-toggle-move]': 'startSort', 'click [data-toggle-visible]': 'toggleVisibility', 'click [data-toggle-select]': 'handleSelect', 'click [data-toggle-open]': 'toggleOpening', 'dblclick input': 'handleEdit', - 'focusout input': 'handleEditEnd', + 'focusout input': 'handleEditEnd' }, - template(model) { const pfx = this.pfx; const ppfx = this.ppfx; @@ -22,20 +20,29 @@ module.exports = require('backbone').View.extend({ const addClass = !count ? `${pfx}no-chld` : ''; const level = this.level + 1; return ` - ${ hidable ? - `` - : ''} + ${ + hidable + ? `` + : '' + }
-
+
- + ${model.getIcon()} - +
-
${ count ? count : '' }
+
${count ? count : ''}
@@ -43,7 +50,6 @@ module.exports = require('backbone').View.extend({ `; }, - initialize(o = {}) { this.opt = o; this.level = o.level; @@ -71,8 +77,7 @@ module.exports = require('backbone').View.extend({ this.$el.data('collection', components); }, - - getVisibilityEl () { + getVisibilityEl() { if (!this.eyeEl) { this.eyeEl = this.$el.children(`#${this.pfx}btn-eye`); } @@ -80,7 +85,6 @@ module.exports = require('backbone').View.extend({ return this.eyeEl; }, - updateVisibility() { const pfx = this.pfx; const model = this.model; @@ -92,7 +96,6 @@ module.exports = require('backbone').View.extend({ this.getVisibilityEl()[method](hideIcon); }, - /** * Toggle visibility * @param Event @@ -114,7 +117,6 @@ module.exports = require('backbone').View.extend({ model.setStyle(style); }, - /** * Handle the edit of the component name */ @@ -125,7 +127,6 @@ module.exports = require('backbone').View.extend({ inputName.focus(); }, - /** * Handle with the end of editing of the component name */ @@ -141,7 +142,7 @@ module.exports = require('backbone').View.extend({ * @return {HTMLElement} */ getInputName() { - if(!this.inputName) { + if (!this.inputName) { this.inputName = this.el.querySelector('.' + this.inputNameCls); } return this.inputName; @@ -162,7 +163,7 @@ module.exports = require('backbone').View.extend({ this.getCaret().addClass(chvDown); opened[model.cid] = model; } else { - this.$el.removeClass("open"); + this.$el.removeClass('open'); this.getCaret().removeClass(chvDown); delete opened[model.cid]; } @@ -177,10 +178,9 @@ module.exports = require('backbone').View.extend({ toggleOpening(e) { e.stopPropagation(); - if(!this.model.get('components').length) - return; + if (!this.model.get('components').length) return; - this.model.set('open', !this.model.get('open') ); + this.model.set('open', !this.model.get('open')); }, /** @@ -188,7 +188,7 @@ module.exports = require('backbone').View.extend({ */ handleSelect(e) { e.stopPropagation(); - this.em && this.em.setSelected(this.model, {fromLayers: 1}); + this.em && this.em.setSelected(this.model, { fromLayers: 1 }); }, /** @@ -212,7 +212,7 @@ module.exports = require('backbone').View.extend({ * */ freeze() { this.$el.addClass(this.pfx + 'opac50'); - this.model.set('open',0); + this.model.set('open', 0); }, /** @@ -231,7 +231,6 @@ module.exports = require('backbone').View.extend({ ComponentView.prototype.updateStatus.apply(this, arguments); }, - /** * Check if component is visible * @@ -240,8 +239,7 @@ module.exports = require('backbone').View.extend({ isVisible() { var css = this.model.get('style'), pr = css.display; - if(pr && pr == 'none' ) - return; + if (pr && pr == 'none') return; return 1; }, @@ -258,7 +256,7 @@ module.exports = require('backbone').View.extend({ const title = this.$el.children(`.${pfx}title-c`).children(`.${pfx}title`); //tC = `> .${pfx}title-c > .${pfx}title`; if (!this.$counter) { - this.$counter = this.$el.children(`#${pfx}counter`); + this.$counter = this.$el.children(`#${pfx}counter`); } if (c) { @@ -279,11 +277,10 @@ module.exports = require('backbone').View.extend({ */ countChildren(model) { var count = 0; - model.get('components').each(function(m){ + model.get('components').each(function(m) { var isCountable = this.opt.isCountable; var hide = this.config.hideTextnode; - if(isCountable && !isCountable(m, hide)) - return; + if (isCountable && !isCountable(m, hide)) return; count++; }, this); return count; @@ -320,8 +317,8 @@ module.exports = require('backbone').View.extend({ }).render().$el; el.find(`.${pfx}children`).append(children); - if(!model.get('draggable') || !this.config.sortable) { - el.children(`#${pfx}move`).remove(); + if (!model.get('draggable') || !this.config.sortable) { + el.children(`#${pfx}move`).remove(); } !vis && (this.className += ` ${pfx}hide`); @@ -330,6 +327,5 @@ module.exports = require('backbone').View.extend({ this.updateStatus(); this.updateVisibility(); return this; - }, - + } }); diff --git a/src/navigator/view/ItemsView.js b/src/navigator/view/ItemsView.js index 9713384420..b14b54a66d 100644 --- a/src/navigator/view/ItemsView.js +++ b/src/navigator/view/ItemsView.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var ItemView = require('./ItemView'); module.exports = Backbone.View.extend({ - initialize(o = {}) { this.opt = o; const config = o.config || {}; @@ -48,7 +47,7 @@ module.exports = Backbone.View.extend({ * @return Object * */ addTo(model) { - var i = this.collection.indexOf(model); + var i = this.collection.indexOf(model); this.addToCollection(model, null, i); }, @@ -62,10 +61,10 @@ module.exports = Backbone.View.extend({ * */ addToCollection(model, fragmentEl, index) { const level = this.level; - var fragment = fragmentEl || null; - var viewObject = ItemView; + var fragment = fragmentEl || null; + var viewObject = ItemView; - if(!this.isCountable(model, this.config.hideTextnode)) { + if (!this.isCountable(model, this.config.hideTextnode)) { return; } @@ -75,28 +74,30 @@ module.exports = Backbone.View.extend({ config: this.config, sorter: this.sorter, isCountable: this.isCountable, - opened: this.opt.opened, + opened: this.opt.opened }); - var rendered = view.render().el; + var rendered = view.render().el; - if(fragment){ + if (fragment) { fragment.appendChild(rendered); - }else{ - if(typeof index != 'undefined'){ - var method = 'before'; + } else { + if (typeof index != 'undefined') { + var method = 'before'; // If the added model is the last of collection // need to change the logic of append - if(this.$el.children().length == index){ + if (this.$el.children().length == index) { index--; - method = 'after'; + method = 'after'; } // In case the added is new in the collection index will be -1 - if(index < 0){ + if (index < 0) { this.$el.append(rendered); - }else - this.$el.children().eq(index)[method](rendered); - }else - this.$el.append(rendered); + } else + this.$el + .children() + .eq(index) + [method](rendered); + } else this.$el.append(rendered); } return rendered; @@ -111,8 +112,10 @@ module.exports = Backbone.View.extend({ isCountable(model, hide) { var type = model.get('type'); var tag = model.get('tagName'); - if( ((type == 'textnode' || tag == 'br') && hide) || - !model.get('layerable')) { + if ( + ((type == 'textnode' || tag == 'br') && hide) || + !model.get('layerable') + ) { return false; } return true; diff --git a/src/panels/config/config.js b/src/panels/config/config.js index 4acf56d968..75246a3497 100644 --- a/src/panels/config/config.js +++ b/src/panels/config/config.js @@ -1,6 +1,6 @@ var crc = 'create-comp'; var mvc = 'move-comp'; -var swv = 'sw-visibility'; +var swv = 'sw-visibility'; var expt = 'export-template'; var osm = 'open-sm'; var otm = 'open-tm'; @@ -13,65 +13,79 @@ module.exports = { stylePrefix: 'pn-', // Default panels fa-sliders for features - defaults: [{ - id: 'commands', - buttons: [{}], - },{ - id: 'options', - buttons: [{ - active: true, - id: swv, - className: 'fa fa-square-o', - command: swv, - context: swv, - attributes: { title: 'View components' }, - },{ - id: prv, - className: 'fa fa-eye', - command: prv, - context: prv, - attributes: { title: 'Preview' }, - },{ - id: ful, - className: 'fa fa-arrows-alt', - command: ful, - context: ful, - attributes: { title: 'Fullscreen' }, - },{ - id: expt, - className: 'fa fa-code', - command: expt, - attributes: { title: 'View code' }, - }], - },{ - id: 'views', - buttons : [{ - id: osm, - className: 'fa fa-paint-brush', - command: osm, - active: true, - attributes: { title: 'Open Style Manager' }, - },{ - id: otm, - className: 'fa fa-cog', - command: otm, - attributes: { title: 'Settings' }, - },{ - id: ola, - className: 'fa fa-bars', - command: ola, - attributes : { title: 'Open Layer Manager' }, - },{ - id: obl, - className: 'fa fa-th-large', - command: obl, - attributes : { title: 'Open Blocks' }, - }], - }], + defaults: [ + { + id: 'commands', + buttons: [{}] + }, + { + id: 'options', + buttons: [ + { + active: true, + id: swv, + className: 'fa fa-square-o', + command: swv, + context: swv, + attributes: { title: 'View components' } + }, + { + id: prv, + className: 'fa fa-eye', + command: prv, + context: prv, + attributes: { title: 'Preview' } + }, + { + id: ful, + className: 'fa fa-arrows-alt', + command: ful, + context: ful, + attributes: { title: 'Fullscreen' } + }, + { + id: expt, + className: 'fa fa-code', + command: expt, + attributes: { title: 'View code' } + } + ] + }, + { + id: 'views', + buttons: [ + { + id: osm, + className: 'fa fa-paint-brush', + command: osm, + active: true, + attributes: { title: 'Open Style Manager' } + }, + { + id: otm, + className: 'fa fa-cog', + command: otm, + attributes: { title: 'Settings' } + }, + { + id: ola, + className: 'fa fa-bars', + command: ola, + attributes: { title: 'Open Layer Manager' } + }, + { + id: obl, + className: 'fa fa-th-large', + command: obl, + attributes: { title: 'Open Blocks' } + } + ] + } + ], // Editor model - em : null, + em: null, // Delay before show children buttons (in milliseconds) - delayBtnsShow : 300, + delayBtnsShow: 300 }; diff --git a/src/panels/index.js b/src/panels/index.js index 0ec6920a1a..1cd05439b4 100644 --- a/src/panels/index.js +++ b/src/panels/index.js @@ -47,15 +47,14 @@ */ module.exports = () => { var c = {}, - defaults = require('./config/config'), - Panel = require('./model/Panel'), - Panels = require('./model/Panels'), - PanelView = require('./view/PanelView'), - PanelsView = require('./view/PanelsView'); + defaults = require('./config/config'), + Panel = require('./model/Panel'), + Panels = require('./model/Panels'), + PanelView = require('./view/PanelView'), + PanelsView = require('./view/PanelsView'); var panels, PanelsViewObj; return { - /** * Name of the module * @type {String} @@ -70,18 +69,16 @@ module.exports = () => { init(config) { c = config || {}; for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } var ppfx = c.pStylePrefix; - if(ppfx) - c.stylePrefix = ppfx + c.stylePrefix; + if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; panels = new Panels(c.defaults); PanelsViewObj = new PanelsView({ - collection : panels, - config : c, + collection: panels, + config: c }); return this; }, @@ -116,7 +113,7 @@ module.exports = () => { addPanel(panel) { return panels.add(panel); }, - + /** * Remove a panel from the collection * @param {Object|Panel|String} panel Object with right properties or an instance of Panel or Painel id @@ -127,9 +124,9 @@ module.exports = () => { * visible : true, * buttons : [...], * }); - * + * * const newPanel = panelManager.removePanel('myNewPanel'); - * + * */ removePanel(panel) { return panels.remove(panel); @@ -143,7 +140,7 @@ module.exports = () => { * var myPanel = panelManager.getPanel('myNewPanel'); */ getPanel(id) { - var res = panels.where({id}); + var res = panels.where({ id }); return res.length ? res[0] : null; }, @@ -178,15 +175,15 @@ module.exports = () => { * } */ addButton(panelId, button) { - var pn = this.getPanel(panelId); + var pn = this.getPanel(panelId); return pn ? pn.get('buttons').add(button) : null; }, - + /** * Remove button from the panel * @param {string} panelId Panel's ID * @param {Object|Button|String} button Button object or instance of Button or button id - * @return {Button|null} Removed button. + * @return {Button|null} Removed button. * @example * const removedButton = panelManager.removeButton('myNewPanel',{ * id: 'myNewButton', @@ -195,13 +192,13 @@ module.exports = () => { * attributes: { title: 'Some title'}, * active: false, * }); - * + * * // It's also possible to use the button id * const removedButton = panelManager.removeButton('myNewPanel','myNewButton'); - * + * */ removeButton(panelId, button) { - var pn = this.getPanel(panelId); + var pn = this.getPanel(panelId); return pn && pn.get('buttons').remove(button); }, @@ -214,9 +211,9 @@ module.exports = () => { * var button = panelManager.getButton('myPanel','myButton'); */ getButton(panelId, id) { - var pn = this.getPanel(panelId); - if(pn){ - var res = pn.get('buttons').where({id}); + var pn = this.getPanel(panelId); + if (pn) { + var res = pn.get('buttons').where({ id }); return res.length ? res[0] : null; } return null; @@ -236,27 +233,24 @@ module.exports = () => { */ active() { this.getPanels().each(p => { - p.get('buttons').each(btn => { - if(btn.get('active')) - btn.trigger('updateActive'); - }); + p.get('buttons').each(btn => { + if (btn.get('active')) btn.trigger('updateActive'); }); + }); }, - + /** * Disable buttons flagged as disabled * @private */ disableButtons() { this.getPanels().each(p => { - p.get('buttons').each(btn => { - if(btn.get('disable')) - btn.trigger('change:disable'); - }); + p.get('buttons').each(btn => { + if (btn.get('disable')) btn.trigger('change:disable'); }); + }); }, - Panel, - + Panel }; }; diff --git a/src/panels/model/Button.js b/src/panels/model/Button.js index 559fcd55d6..5218e477ec 100644 --- a/src/panels/model/Button.js +++ b/src/panels/model/Button.js @@ -1,8 +1,7 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - - defaults :{ + defaults: { id: '', className: '', command: '', @@ -14,14 +13,13 @@ module.exports = Backbone.Model.extend({ dragDrop: false, runDefaultCommand: true, stopDefaultCommand: false, - disable: false, + disable: false }, initialize(options) { - if(this.get('buttons').length){ - var Buttons = require('./Buttons'); - this.set('buttons', new Buttons(this.get('buttons')) ); + if (this.get('buttons').length) { + var Buttons = require('./Buttons'); + this.set('buttons', new Buttons(this.get('buttons'))); } - }, - + } }); diff --git a/src/panels/model/Buttons.js b/src/panels/model/Buttons.js index 74901156ba..9d343e0b9f 100644 --- a/src/panels/model/Buttons.js +++ b/src/panels/model/Buttons.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var Button = require('./Button'); module.exports = Backbone.Collection.extend({ - model: Button, /** @@ -14,10 +13,10 @@ module.exports = Backbone.Collection.extend({ * */ deactivateAllExceptOne(except, r) { this.forEach((model, index) => { - if(model !== except){ + if (model !== except) { model.set('active', false); - if(r && model.get('buttons').length) - model.get('buttons').deactivateAllExceptOne(except,r); + if (r && model.get('buttons').length) + model.get('buttons').deactivateAllExceptOne(except, r); } }); }, @@ -31,14 +30,14 @@ module.exports = Backbone.Collection.extend({ deactivateAll(ctx) { var context = ctx || ''; this.forEach((model, index) => { - if( model.get('context') == context ){ + if (model.get('context') == context) { model.set('active', false); - if(model.get('buttons').length) + if (model.get('buttons').length) model.get('buttons').deactivateAll(context); } }); }, - + /** * Disables all buttons * @param {String} ctx Context string @@ -48,9 +47,9 @@ module.exports = Backbone.Collection.extend({ disableAllButtons(ctx) { var context = ctx || ''; this.forEach((model, index) => { - if( model.get('context') == context ){ + if (model.get('context') == context) { model.set('disable', true); - if(model.get('buttons').length) + if (model.get('buttons').length) model.get('buttons').disableAllButtons(context); } }); @@ -65,12 +64,11 @@ module.exports = Backbone.Collection.extend({ * */ disableAllButtonsExceptOne(except, r) { this.forEach((model, index) => { - if(model !== except){ + if (model !== except) { model.set('disable', true); - if(r && model.get('buttons').length) - model.get('buttons').disableAllButtonsExceptOne(except,r); + if (r && model.get('buttons').length) + model.get('buttons').disableAllButtonsExceptOne(except, r); } }); - }, - + } }); diff --git a/src/panels/model/Panel.js b/src/panels/model/Panel.js index 1ac83c765e..9554b1a05c 100644 --- a/src/panels/model/Panel.js +++ b/src/panels/model/Panel.js @@ -2,18 +2,16 @@ var Backbone = require('backbone'); var Buttons = require('./Buttons'); module.exports = Backbone.Model.extend({ - defaults: { id: '', content: '', visible: true, - buttons: [], + buttons: [] }, initialize(options) { this.btn = this.get('buttons') || []; this.buttons = new Buttons(this.btn); this.set('buttons', this.buttons); - }, - + } }); diff --git a/src/panels/model/Panels.js b/src/panels/model/Panels.js index 01e040ca56..5f7db27bf7 100644 --- a/src/panels/model/Panels.js +++ b/src/panels/model/Panels.js @@ -2,5 +2,5 @@ var Backbone = require('backbone'); var Panel = require('./Panel'); module.exports = Backbone.Collection.extend({ - model: Panel, + model: Panel }); diff --git a/src/panels/view/ButtonView.js b/src/panels/view/ButtonView.js index 8219d89686..e420016b0f 100644 --- a/src/panels/view/ButtonView.js +++ b/src/panels/view/ButtonView.js @@ -2,11 +2,20 @@ import { isString, isObject, isFunction } from 'underscore'; const $ = Backbone.$; module.exports = Backbone.View.extend({ - tagName: 'span', initialize(o) { - _.bindAll(this, 'startTimer', 'stopTimer', 'showButtons', 'hideButtons','closeOnKeyPress','onDrop', 'initSorter', 'stopDrag'); + _.bindAll( + this, + 'startTimer', + 'stopTimer', + 'showButtons', + 'hideButtons', + 'closeOnKeyPress', + 'onDrop', + 'initSorter', + 'stopDrag' + ); var cls = this.model.get('className'); this.config = o.config || {}; this.em = this.config.em || {}; @@ -27,26 +36,24 @@ module.exports = Backbone.View.extend({ this.listenTo(this.model, 'change:className', this.updateClassName); this.listenTo(this.model, 'change:disable', this.updateDisable); - if(this.model.get('buttons').length){ + if (this.model.get('buttons').length) { this.$el.on('mousedown', this.startTimer); - this.$el.append($('
',{class: pfx + 'arrow-rd'})); + this.$el.append($('
', { class: pfx + 'arrow-rd' })); } - if(this.em && this.em.get) - this.commands = this.em.get('Commands'); + if (this.em && this.em.get) this.commands = this.em.get('Commands'); this.events = {}; - if(this.model.get('dragDrop')){ + if (this.model.get('dragDrop')) { this.events.mousedown = 'initDrag'; this.em.on('loaded', this.initSorter); - }else - this.events.click = 'clicked'; + } else this.events.click = 'clicked'; this.delegateEvents(); }, initSorter() { - if(this.em.Canvas){ + if (this.em.Canvas) { var canvas = this.em.Canvas; this.canvasEl = canvas.getBody(); this.sorter = new this.em.Utils.Sorter({ @@ -60,7 +67,7 @@ module.exports = Backbone.View.extend({ document: canvas.getFrameEl().contentDocument, direction: 'a', wmargin: 1, - nested: 1, + nested: 1 }); var offDim = canvas.getOffset(); this.sorter.offTop = offDim.top; @@ -119,7 +126,7 @@ module.exports = Backbone.View.extend({ * @return void * */ updateAttributes() { - this.$el.attr(this.model.get("attributes")); + this.$el.attr(this.model.get('attributes')); }, /** @@ -128,13 +135,10 @@ module.exports = Backbone.View.extend({ * @return void * */ updateBtnsVis() { - if(!this.$buttons) - return; + if (!this.$buttons) return; - if(this.model.get('bntsVis')) - this.$buttons.addClass(this.btnsVisCls); - else - this.$buttons.removeClass(this.btnsVisCls); + if (this.model.get('bntsVis')) this.$buttons.addClass(this.btnsVisCls); + else this.$buttons.removeClass(this.btnsVisCls); }, /** @@ -153,9 +157,8 @@ module.exports = Backbone.View.extend({ * @return void * */ stopTimer() { - $(document).off('mouseup', this.stopTimer); - if(this.timeout) - clearTimeout(this.timeout); + $(document).off('mouseup', this.stopTimer); + if (this.timeout) clearTimeout(this.timeout); }, /** @@ -166,8 +169,8 @@ module.exports = Backbone.View.extend({ showButtons() { clearTimeout(this.timeout); this.model.set('bntsVis', true); - $(document).on('mousedown', this.hideButtons); - $(document).on('keypress', this.closeOnKeyPress); + $(document).on('mousedown', this.hideButtons); + $(document).on('keypress', this.closeOnKeyPress); }, /** @@ -176,10 +179,12 @@ module.exports = Backbone.View.extend({ * @return void * */ hideButtons(e) { - if(e){ $(e.target).trigger('click'); } + if (e) { + $(e.target).trigger('click'); + } this.model.set('bntsVis', false); - $(document).off('mousedown', this.hideButtons); - $(document).off('keypress', this.closeOnKeyPress); + $(document).off('mousedown', this.hideButtons); + $(document).off('keypress', this.closeOnKeyPress); }, /** @@ -190,8 +195,7 @@ module.exports = Backbone.View.extend({ * */ closeOnKeyPress(e) { var key = e.which || e.keyCode; - if(key == 27) - this.hideButtons(); + if (key == 27) this.hideButtons(); }, /** @@ -208,7 +212,7 @@ module.exports = Backbone.View.extend({ var commandName = model.get('command'); if (this.commands && isString(commandName)) { - command = this.commands.get(commandName) || {}; + command = this.commands.get(commandName) || {}; } else if (isFunction(commandName)) { command = { run: commandName }; } else if (commandName !== null && isObject(commandName)) { @@ -218,7 +222,8 @@ module.exports = Backbone.View.extend({ if (model.get('active')) { model.collection.deactivateAll(context); model.set('active', true, { silent: true }).trigger('checkActive'); - parent && parent.set('active', true, { silent: true }).trigger('checkActive'); + parent && + parent.set('active', true, { silent: true }).trigger('checkActive'); if (command.run) { command.run(editor, model, model.get('options')); @@ -230,7 +235,8 @@ module.exports = Backbone.View.extend({ } else { this.$el.removeClass(this.activeCls); model.collection.deactivateAll(context); - parent && parent.set('active', false, { silent: true }).trigger('checkActive'); + parent && + parent.set('active', false, { silent: true }).trigger('checkActive'); if (command.stop) { command.stop(editor, model, model.get('options')); @@ -240,12 +246,11 @@ module.exports = Backbone.View.extend({ }, updateDisable() { - if(this.model.get('disable')) { + if (this.model.get('disable')) { this.$el.addClass(this.disableCls); } else { this.$el.removeClass(this.disableCls); } - }, /** @@ -254,10 +259,8 @@ module.exports = Backbone.View.extend({ * @return void * */ checkActive() { - if(this.model.get('active')) - this.$el.addClass(this.activeCls); - else - this.$el.removeClass(this.activeCls); + if (this.model.get('active')) this.$el.addClass(this.activeCls); + else this.$el.removeClass(this.activeCls); }, /** @@ -267,19 +270,15 @@ module.exports = Backbone.View.extend({ * @return void * */ clicked(e) { - if(this.model.get('bntsVis') ) - return; + if (this.model.get('bntsVis')) return; - if(this.model.get('disable') ) - return; + if (this.model.get('disable')) return; this.toogleActive(); }, toogleActive() { - - if(this.parentM) - this.swapParent(); + if (this.parentM) this.swapParent(); var active = this.model.get('active'); this.model.set('active', !active); @@ -287,12 +286,10 @@ module.exports = Backbone.View.extend({ // If the stop is requested var command = this.em.get('Commands').get('select-comp'); - if(active){ - if(this.model.get('runDefaultCommand')) - this.em.runDefault(); - }else{ - if(this.model.get('stopDefaultCommand')) - this.em.stopDefault(); + if (active) { + if (this.model.get('runDefaultCommand')) this.em.runDefault(); + } else { + if (this.model.get('stopDefaultCommand')) this.em.stopDefault(); } }, @@ -303,10 +300,10 @@ module.exports = Backbone.View.extend({ * */ swapParent() { this.parentM.collection.deactivateAll(this.model.get('context')); - this.parentM.set('attributes', this.model.get('attributes')); - this.parentM.set('options', this.model.get('options')); - this.parentM.set('command', this.model.get('command')); - this.parentM.set('className', this.model.get('className')); + this.parentM.set('attributes', this.model.get('attributes')); + this.parentM.set('options', this.model.get('options')); + this.parentM.set('command', this.model.get('command')); + this.parentM.set('className', this.model.get('className')); this.parentM.set('active', true, { silent: true }).trigger('checkActive'); }, @@ -314,19 +311,18 @@ module.exports = Backbone.View.extend({ this.updateAttributes(); this.$el.attr('class', this.className); - if(this.model.get('buttons').length){ - var btnsView = require('./ButtonsView'); //Avoid Circular Dependencies + if (this.model.get('buttons').length) { + var btnsView = require('./ButtonsView'); //Avoid Circular Dependencies var view = new btnsView({ - collection : this.model.get('buttons'), - config : this.config, - parentM : this.model + collection: this.model.get('buttons'), + config: this.config, + parentM: this.model }); - this.$buttons = view.render().$el; - this.$buttons.append($('
',{class: this.pfx + 'arrow-l'})); - this.$el.append(this.$buttons); //childNodes avoids wrapping 'div' + this.$buttons = view.render().$el; + this.$buttons.append($('
', { class: this.pfx + 'arrow-l' })); + this.$el.append(this.$buttons); //childNodes avoids wrapping 'div' } return this; - }, - + } }); diff --git a/src/panels/view/ButtonsView.js b/src/panels/view/ButtonsView.js index 8f48aca1ca..6ca613fe64 100644 --- a/src/panels/view/ButtonsView.js +++ b/src/panels/view/ButtonsView.js @@ -2,14 +2,13 @@ var Backbone = require('backbone'); var ButtonView = require('./ButtonView'); module.exports = Backbone.View.extend({ - initialize(o) { this.opt = o || {}; this.config = this.opt.config || {}; this.pfx = this.config.stylePrefix || ''; this.parentM = this.opt.parentM || null; - this.listenTo(this.collection, 'add', this.addTo ); - this.listenTo(this.collection, 'reset', this.render ); + this.listenTo(this.collection, 'add', this.addTo); + this.listenTo(this.collection, 'reset', this.render); this.className = this.pfx + 'buttons'; }, @@ -31,19 +30,19 @@ module.exports = Backbone.View.extend({ * @return Object Object created * */ addToCollection(model, fragmentEl) { - var fragment = fragmentEl || null; - var viewObject = ButtonView; + var fragment = fragmentEl || null; + var viewObject = ButtonView; - var view = new viewObject({ + var view = new viewObject({ model, - config : this.config, - parentM : this.parentM + config: this.config, + parentM: this.parentM }); - var rendered = view.render().el; + var rendered = view.render().el; - if(fragment){ + if (fragment) { fragment.appendChild(rendered); - }else{ + } else { this.$el.append(rendered); } @@ -54,7 +53,7 @@ module.exports = Backbone.View.extend({ var fragment = document.createDocumentFragment(); this.$el.empty(); - this.collection.each(function(model){ + this.collection.each(function(model) { this.addToCollection(model, fragment); }, this); diff --git a/src/panels/view/PanelView.js b/src/panels/view/PanelView.js index dd6f689fa9..c321154bef 100644 --- a/src/panels/view/PanelView.js +++ b/src/panels/view/PanelView.js @@ -2,7 +2,6 @@ var Backbone = require('backbone'); var ButtonsView = require('./ButtonsView'); module.exports = Backbone.View.extend({ - initialize(o) { const config = o.config || {}; this.config = config; @@ -37,7 +36,10 @@ module.exports = Backbone.View.extend({ if (editor && resizable) { var resz = resizable === true ? [1, 1, 1, 1] : resizable; var resLen = resz.length; - var tc, cr, bc, cl = 0; + var tc, + cr, + bc, + cl = 0; // Choose which sides of the panel are resizable if (resLen == 2) { @@ -63,10 +65,11 @@ module.exports = Backbone.View.extend({ br: 0, appendTo: this.el, prefix: editor.getConfig().stylePrefix, - posFetcher: (el) => { + posFetcher: el => { var rect = el.getBoundingClientRect(); return { - left: 0, top: 0, + left: 0, + top: 0, width: rect.width, height: rect.height }; @@ -84,15 +87,14 @@ module.exports = Backbone.View.extend({ this.id && el.attr('id', this.id); if (this.buttons.length) { - var buttons = new ButtonsView({ + var buttons = new ButtonsView({ collection: this.buttons, - config: this.config, + config: this.config }); el.append(buttons.render().el); } el.append(this.model.get('content')); return this; - }, - + } }); diff --git a/src/panels/view/PanelsView.js b/src/panels/view/PanelsView.js index 34ac7682ae..3ed5cf0453 100644 --- a/src/panels/view/PanelsView.js +++ b/src/panels/view/PanelsView.js @@ -2,13 +2,12 @@ var Backbone = require('backbone'); var PanelView = require('./PanelView'); module.exports = Backbone.View.extend({ - initialize(o) { this.opt = o || {}; this.config = this.opt.config || {}; this.pfx = this.config.stylePrefix || ''; - this.listenTo(this.collection, 'add', this.addTo ); - this.listenTo(this.collection, 'reset', this.render ); + this.listenTo(this.collection, 'add', this.addTo); + this.listenTo(this.collection, 'reset', this.render); this.className = this.pfx + 'panels'; }, @@ -36,7 +35,7 @@ module.exports = Backbone.View.extend({ var fragment = fragmentEl || null; var view = new PanelView({ model, - config: this.config, + config: this.config }); var rendered = view.render().el; var appendTo = model.get('appendTo'); @@ -60,7 +59,7 @@ module.exports = Backbone.View.extend({ var fragment = document.createDocumentFragment(); this.$el.empty(); - this.collection.each(function(model){ + this.collection.each(function(model) { this.addToCollection(model, fragment); }, this); diff --git a/src/parser/config/config.js b/src/parser/config/config.js index 0302532ac6..31922f6dbe 100644 --- a/src/parser/config/config.js +++ b/src/parser/config/config.js @@ -1,5 +1,3 @@ module.exports = { - - textTags: ['br', 'b', 'i', 'u', 'a', 'ul', 'ol'], - + textTags: ['br', 'b', 'i', 'u', 'a', 'ul', 'ol'] }; diff --git a/src/parser/index.js b/src/parser/index.js index e0b9ededdf..c9d6bb0216 100644 --- a/src/parser/index.js +++ b/src/parser/index.js @@ -1,12 +1,11 @@ module.exports = () => { var c = {}, - defaults = require('./config/config'), - parserCss = require('./model/ParserCss'), - parserHtml = require('./model/ParserHtml'); + defaults = require('./config/config'), + parserCss = require('./model/ParserCss'), + parserHtml = require('./model/ParserHtml'); var pHtml, pCss; return { - compTypes: '', /** @@ -34,8 +33,7 @@ module.exports = () => { init(config) { c = config || {}; for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } pHtml = new parserHtml(c); pCss = new parserCss(c); @@ -54,7 +52,6 @@ module.exports = () => { parseCss(str) { return pCss.parse(str); - }, - + } }; }; diff --git a/src/parser/model/ParserCss.js b/src/parser/model/ParserCss.js index 9ddf2ad5b5..7746a49eb2 100644 --- a/src/parser/model/ParserCss.js +++ b/src/parser/model/ParserCss.js @@ -22,7 +22,7 @@ module.exports = config => ({ var sel = sels[i].trim(); // Will accept only concatenated classes and last // class might be with state (eg. :hover), nothing else. - if (/^(\.{1}[\w\-]+)+(:{1,2}[\w\-()]+)?$/ig.test(sel)) { + if (/^(\.{1}[\w\-]+)+(:{1,2}[\w\-()]+)?$/gi.test(sel)) { var cls = sel.split('.').filter(Boolean); result.push(cls); } else { @@ -31,7 +31,7 @@ module.exports = config => ({ } return { result, - add, + add }; }, @@ -50,11 +50,11 @@ module.exports = config => ({ var selsAdd = []; // It's a CSSMediaRule - if(node.cssRules) { + if (node.cssRules) { var subRules = this.parseNode(node); var mediaText = node.media.mediaText; - for( var s = 0, lens = subRules.length; s < lens; s++) { + for (var s = 0, lens = subRules.length; s < lens; s++) { var subRule = subRules[s]; subRule.mediaText = mediaText ? mediaText.trim() : ''; } @@ -62,8 +62,7 @@ module.exports = config => ({ result = result.concat(subRules); } - if(!sels) - continue; + if (!sels) continue; var selsParsed = this.parseSelector(sels); sels = selsParsed.result; @@ -77,7 +76,7 @@ module.exports = config => ({ const propName = stl[j]; const propValue = stl.getPropertyValue(propName); const important = stl.getPropertyPriority(propName); - style[propName] = `${propValue}${important ? ` !${important}` : ''}` + style[propName] = `${propValue}${important ? ` !${important}` : ''}`; } var lastRule = ''; @@ -88,7 +87,7 @@ module.exports = config => ({ //Isolate state from selector var stateArr = selArr[selArr.length - 1].split(/:(.+)/); - if(stateArr[1]){ + if (stateArr[1]) { selArr[selArr.length - 1] = stateArr[0]; model.state = stateArr[1]; stateArr.splice(stateArr.length - 1, 1); @@ -110,11 +109,10 @@ module.exports = config => ({ result.push({ selectors: [], selectorsAdd: selsAddStr, - style, + style }); } } - } return result; @@ -140,8 +138,7 @@ module.exports = config => ({ document.head.removeChild(el); var result = this.parseNode(sheet); - if(result.length == 1) - result = result[0]; + if (result.length == 1) result = result[0]; return result; } diff --git a/src/parser/model/ParserHtml.js b/src/parser/model/ParserHtml.js index da858228ac..021c5dbf9a 100644 --- a/src/parser/model/ParserHtml.js +++ b/src/parser/model/ParserHtml.js @@ -1,11 +1,9 @@ module.exports = config => { - var TEXT_NODE = 'span'; var c = config; var modelAttrStart = 'data-gjs-'; return { - compTypes: '', /** @@ -22,10 +20,12 @@ module.exports = config => { var decls = str.split(';'); for (var i = 0, len = decls.length; i < len; i++) { var decl = decls[i].trim(); - if(!decl) - continue; + if (!decl) continue; var prop = decl.split(':'); - result[prop[0].trim()] = prop.slice(1).join(':').trim(); + result[prop[0].trim()] = prop + .slice(1) + .join(':') + .trim(); } return result; }, @@ -45,8 +45,7 @@ module.exports = config => { for (var i = 0, len = cls.length; i < len; i++) { var cl = cls[i].trim(); var reg = new RegExp('^' + c.pStylePrefix); - if(!cl || reg.test(cl)) - continue; + if (!cl || reg.test(cl)) continue; result.push(cl); } return result; @@ -117,8 +116,11 @@ module.exports = config => { // I can get false positive here (eg. a selector '[data-attr]') // so put it under try/catch and let fail silently try { - nodeValue = (firstChar == '{' && lastChar == '}') || - (firstChar == '[' && lastChar == ']') ? JSON.parse(nodeValue) : nodeValue; + nodeValue = + (firstChar == '{' && lastChar == '}') || + (firstChar == '[' && lastChar == ']') + ? JSON.parse(nodeValue) + : nodeValue; } catch (e) {} model[modelAttr] = nodeValue; @@ -167,8 +169,10 @@ module.exports = config => { const comp = comps[ci]; const cType = comp.type; - if (['text', 'textnode'].indexOf(cType) < 0 && - c.textTags.indexOf(comp.tagName) < 0 ) { + if ( + ['text', 'textnode'].indexOf(cType) < 0 && + c.textTags.indexOf(comp.tagName) < 0 + ) { allTxt = 0; break; } @@ -202,44 +206,38 @@ module.exports = config => { */ parse(str, parserCss) { var config = (c.em && c.em.get('Config')) || {}; - var res = { html: '', css: ''}; + var res = { html: '', css: '' }; var el = document.createElement('div'); el.innerHTML = str; var scripts = el.querySelectorAll('script'); var i = scripts.length; // Remove all scripts - if(!config.allowScripts){ - while (i--) - scripts[i].parentNode.removeChild(scripts[i]); + if (!config.allowScripts) { + while (i--) scripts[i].parentNode.removeChild(scripts[i]); } // Detach style tags and parse them - if(parserCss){ + if (parserCss) { var styleStr = ''; var styles = el.querySelectorAll('style'); var j = styles.length; - while (j--){ + while (j--) { styleStr = styles[j].innerHTML + styleStr; styles[j].parentNode.removeChild(styles[j]); } - if(styleStr) - res.css = parserCss.parse(styleStr); + if (styleStr) res.css = parserCss.parse(styleStr); } var result = this.parseNode(el); - if(result.length == 1) - result = result[0]; + if (result.length == 1) result = result[0]; res.html = result; return res; - - }, - + } }; - }; diff --git a/src/plugin_manager/index.js b/src/plugin_manager/index.js index 9aafde0724..225e9cf895 100644 --- a/src/plugin_manager/index.js +++ b/src/plugin_manager/index.js @@ -1,18 +1,15 @@ module.exports = config => { - var c = config || {}, - defaults = require('./config/config'); + defaults = require('./config/config'); // Set default options for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } var plugins = {}; return { - /** * Add new plugin. Plugins could not be overwritten * @param {string} id Plugin ID @@ -55,6 +52,5 @@ module.exports = config => { getAll() { return plugins; } - }; }; diff --git a/src/rich_text_editor/config/config.js b/src/rich_text_editor/config/config.js index f27a589f08..22b0e73516 100644 --- a/src/rich_text_editor/config/config.js +++ b/src/rich_text_editor/config/config.js @@ -1,11 +1,10 @@ module.exports = { - - stylePrefix : 'rte-', + stylePrefix: 'rte-', // If true, moves the toolbar below the element when the top canvas // edge is reached adjustToolbar: 1, // Default RTE actions - actions: ['bold', 'italic', 'underline', 'strikethrough', 'link'], + actions: ['bold', 'italic', 'underline', 'strikethrough', 'link'] }; diff --git a/src/rich_text_editor/index.js b/src/rich_text_editor/index.js index 2e9c5e453b..d2bec1c8ac 100644 --- a/src/rich_text_editor/index.js +++ b/src/rich_text_editor/index.js @@ -14,7 +14,7 @@ * @module RichTextEditor */ import RichTextEditor from './model/RichTextEditor'; -import {on, off} from 'utils/mixins' +import { on, off } from 'utils/mixins'; module.exports = () => { let config = {}; @@ -30,7 +30,6 @@ module.exports = () => { }; return { - customRte: null, /** @@ -71,7 +70,6 @@ module.exports = () => { return this; }, - /** * Post render callback * @param {View} ev @@ -84,7 +82,6 @@ module.exports = () => { canvas.getToolsEl().appendChild(toolbar); }, - /** * Init the built-in RTE * @param {HTMLElement} el @@ -99,14 +96,14 @@ module.exports = () => { const classes = { actionbar: `${pfx}actionbar`, button: `${pfx}action`, - active: `${pfx}active`, + active: `${pfx}active` }; const rte = new RichTextEditor({ el, classes, actions, actionbar, - actionbarContainer, + actionbarContainer }); globalRte && globalRte.setEl(el); @@ -158,7 +155,7 @@ module.exports = () => { */ add(name, action = {}) { action.name = name; - globalRte.addAction(action, {sync: 1}); + globalRte.addAction(action, { sync: 1 }); }, /** @@ -225,7 +222,7 @@ module.exports = () => { const un = 'px'; const canvas = config.em.get('Canvas'); const pos = canvas.getTargetToElementDim(toolbar, lastEl, { - event: 'rteToolbarPosUpdate', + event: 'rteToolbarPosUpdate' }); if (config.adjustToolbar) { @@ -285,6 +282,6 @@ module.exports = () => { hideToolbar(); em && em.trigger('rte:disable', view, rte); - }, + } }; }; diff --git a/src/rich_text_editor/model/RichTextEditor.js b/src/rich_text_editor/model/RichTextEditor.js index 11631fcc50..40cdad27f0 100644 --- a/src/rich_text_editor/model/RichTextEditor.js +++ b/src/rich_text_editor/model/RichTextEditor.js @@ -1,7 +1,7 @@ // The initial version of this RTE was borrowed from https://github.com/jaredreich/pell // and adapted to the GrapesJS's need -import {on, off} from 'utils/mixins' +import { on, off } from 'utils/mixins'; const RTE_KEY = '_rte'; @@ -9,40 +9,40 @@ const defActions = { bold: { name: 'bold', icon: 'B', - attributes: {title: 'Bold'}, - result: (rte) => rte.exec('bold') + attributes: { title: 'Bold' }, + result: rte => rte.exec('bold') }, italic: { name: 'italic', icon: 'I', - attributes: {title: 'Italic'}, - result: (rte) => rte.exec('italic') + attributes: { title: 'Italic' }, + result: rte => rte.exec('italic') }, underline: { name: 'underline', icon: 'U', - attributes: {title: 'Underline'}, - result: (rte) => rte.exec('underline') + attributes: { title: 'Underline' }, + result: rte => rte.exec('underline') }, strikethrough: { name: 'strikethrough', icon: 'S', - attributes: {title: 'Strike-through'}, - result: (rte) => rte.exec('strikeThrough') + attributes: { title: 'Strike-through' }, + result: rte => rte.exec('strikeThrough') }, link: { icon: ``, name: 'link', attributes: { style: 'font-size:1.4rem;padding:0 4px 2px;', - title: 'Link', + title: 'Link' }, - result: (rte) => rte.insertHTML(`${rte.selection()}`) + result: rte => + rte.insertHTML(`${rte.selection()}`) } -} +}; export default class RichTextEditor { - constructor(settings = {}) { const el = settings.el; @@ -56,21 +56,25 @@ export default class RichTextEditor { const settAct = settings.actions || []; settAct.forEach((action, i) => { - if (typeof action === 'string') { - action = defActions[action]; - } else if (defActions[action.name]) { - action = {...defActions[action.name], ...action}; - } - settAct[i] = action; + if (typeof action === 'string') { + action = defActions[action]; + } else if (defActions[action.name]) { + action = { ...defActions[action.name], ...action }; + } + settAct[i] = action; }); - const actions = settAct.length ? settAct : - Object.keys(defActions).map(action => defActions[action]) - - settings.classes = { ...{ - actionbar: 'actionbar', - button: 'action', - active: 'active', - }, ...settings.classes}; + const actions = settAct.length + ? settAct + : Object.keys(defActions).map(action => defActions[action]); + + settings.classes = { + ...{ + actionbar: 'actionbar', + button: 'action', + active: 'active' + }, + ...settings.classes + }; const classes = settings.classes; let actionbar = settings.actionbar; @@ -85,7 +89,7 @@ export default class RichTextEditor { actionbar.className = classes.actionbar; actionbarCont.appendChild(actionbar); this.actionbar = actionbar; - actions.forEach(action => this.addAction(action)) + actions.forEach(action => this.addAction(action)); } settings.styleWithCSS && this.exec('styleWithCSS'); @@ -114,7 +118,7 @@ export default class RichTextEditor { } update && update(this, action); - }) + }); } enable() { @@ -124,7 +128,7 @@ export default class RichTextEditor { this.actionbarEl().style.display = ''; this.el.contentEditable = true; - on(this.el, 'mouseup keyup', this.updateActiveActions) + on(this.el, 'mouseup keyup', this.updateActiveActions); this.syncActions(); this.updateActiveActions(); this.el.focus(); @@ -150,7 +154,7 @@ export default class RichTextEditor { action.result(this, action); this.updateActiveActions(); }; - }) + }); } /** @@ -197,7 +201,7 @@ export default class RichTextEditor { * @return {Selection} */ selection() { - return this.doc.getSelection() + return this.doc.getSelection(); } /** @@ -235,7 +239,7 @@ export default class RichTextEditor { Array.prototype.slice.call(node.childNodes).forEach(nd => { range.insertNode(nd); lastNode = nd; - }) + }); sel.removeAllRanges(); sel.addRange(range); diff --git a/src/selector_manager/config/config.js b/src/selector_manager/config/config.js index 4da150b4a7..8bad099382 100644 --- a/src/selector_manager/config/config.js +++ b/src/selector_manager/config/config.js @@ -1,5 +1,4 @@ module.exports = { - // Style prefix stylePrefix: 'clm-', @@ -16,8 +15,8 @@ module.exports = { // States states: [ - { name: 'hover', label: 'Hover' }, - { name: 'active', label: 'Click' }, - { name: 'nth-of-type(2n)', label: 'Even/Odd' } - ], + { name: 'hover', label: 'Hover' }, + { name: 'active', label: 'Click' }, + { name: 'nth-of-type(2n)', label: 'Even/Odd' } + ] }; diff --git a/src/selector_manager/index.js b/src/selector_manager/index.js index 96d45b0dfa..7b3cf34840 100644 --- a/src/selector_manager/index.js +++ b/src/selector_manager/index.js @@ -49,18 +49,17 @@ * } */ -import { isString } from 'underscore' +import { isString } from 'underscore'; module.exports = config => { var c = config || {}, - defaults = require('./config/config'), - Selector = require('./model/Selector'), - Selectors = require('./model/Selectors'), - ClassTagsView = require('./view/ClassTagsView'); + defaults = require('./config/config'), + Selector = require('./model/Selector'), + Selectors = require('./model/Selectors'), + ClassTagsView = require('./view/ClassTagsView'); var selectors, selectorTags; return { - Selector, Selectors, @@ -82,8 +81,7 @@ module.exports = config => { c = conf || {}; for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } const em = c.em; @@ -94,14 +92,13 @@ module.exports = config => { } selectorTags = new ClassTagsView({ - collection: new Selectors([], {em,config: c}), - config: c, + collection: new Selectors([], { em, config: c }), + config: c }); // Global selectors container selectors = new Selectors(c.selectors); - selectors.on('add', (model) => - em.trigger('selector:add', model)); + selectors.on('add', model => em.trigger('selector:add', model)); return this; }, @@ -133,7 +130,9 @@ module.exports = config => { } const cname = opts.name; - const selector = cname ? this.get(cname, opts.type) : selectors.where(opts)[0]; + const selector = cname + ? this.get(cname, opts.type) + : selectors.where(opts)[0]; if (!selector) { return selectors.add(opts); @@ -159,11 +158,10 @@ module.exports = config => { classes = classes.trim().split(' '); } - classes.forEach(name => added.push(selectors.add({name}))) + classes.forEach(name => added.push(selectors.add({ name }))); return added; }, - /** * Get the selector by its name * @param {String} name Selector name @@ -173,7 +171,7 @@ module.exports = config => { * var selector = selectorManager.get('selectorName'); * */ get(name, type = Selector.TYPE_CLASS) { - return selectors.where({name, type})[0]; + return selectors.where({ name, type })[0]; }, /** @@ -191,15 +189,13 @@ module.exports = config => { * @private */ render(selectors) { - if(selectors){ + if (selectors) { var view = new ClassTagsView({ collection: new Selectors(selectors), - config: c, + config: c }); return view.render().el; - }else - return selectorTags.render().el; - }, - + } else return selectorTags.render().el; + } }; }; diff --git a/src/selector_manager/model/Selector.js b/src/selector_manager/model/Selector.js index 4f8c921bc3..bfdd509e08 100644 --- a/src/selector_manager/model/Selector.js +++ b/src/selector_manager/model/Selector.js @@ -3,77 +3,78 @@ var Backbone = require('backbone'); const TYPE_CLASS = 1; const TYPE_ID = 2; -const Selector = Backbone.Model.extend({ - - idAttribute: 'name', - - defaults: { - name: '', - - label: '', - - // Type of the selector - type: TYPE_CLASS, - - // If not active it's not selectable by the style manager (uncheckboxed) - active: true, - - // Can't be seen by the style manager, therefore even by the user - // Will be rendered only in export code - private: false, - - // If true, can't be removed from the attacched element - protected: false, - }, - - initialize() { - const name = this.get('name'); - const label = this.get('label'); - - if (!name) { - this.set('name', label); - } else if (!label) { - this.set('label', name); +const Selector = Backbone.Model.extend( + { + idAttribute: 'name', + + defaults: { + name: '', + + label: '', + + // Type of the selector + type: TYPE_CLASS, + + // If not active it's not selectable by the style manager (uncheckboxed) + active: true, + + // Can't be seen by the style manager, therefore even by the user + // Will be rendered only in export code + private: false, + + // If true, can't be removed from the attacched element + protected: false + }, + + initialize() { + const name = this.get('name'); + const label = this.get('label'); + + if (!name) { + this.set('name', label); + } else if (!label) { + this.set('label', name); + } + + this.set('name', Selector.escapeName(this.get('name'))); + }, + + /** + * Get full selector name + * @return {string} + */ + getFullName() { + let init = ''; + + switch (this.get('type')) { + case TYPE_CLASS: + init = '.'; + break; + case TYPE_ID: + init = '#'; + break; + } + + return init + this.get('name'); } - - this.set('name', Selector.escapeName(this.get('name'))); }, - - /** - * Get full selector name - * @return {string} - */ - getFullName() { - let init = ''; - - switch (this.get('type')) { - case TYPE_CLASS: - init = '.'; - break; - case TYPE_ID: - init = '#'; - break; + { + // All type selectors: https://developer.mozilla.org/it/docs/Web/CSS/CSS_Selectors + // Here I define only what I need + TYPE_CLASS, + + TYPE_ID, + + /** + * Escape string + * @param {string} name + * @return {string} + * @private + */ + escapeName(name) { + return `${name}`.trim().replace(/([^a-z0-9\w-]+)/gi, '-'); } - - return init + this.get('name'); } - -}, { - // All type selectors: https://developer.mozilla.org/it/docs/Web/CSS/CSS_Selectors - // Here I define only what I need - TYPE_CLASS, - - TYPE_ID, - - /** - * Escape string - * @param {string} name - * @return {string} - * @private - */ - escapeName(name) { - return `${name}`.trim().replace(/([^a-z0-9\w-]+)/gi, '-'); - }, -}); +); module.exports = Selector; diff --git a/src/selector_manager/model/Selectors.js b/src/selector_manager/model/Selectors.js index 119e6f574c..a3a800b7a4 100644 --- a/src/selector_manager/model/Selectors.js +++ b/src/selector_manager/model/Selectors.js @@ -5,8 +5,10 @@ module.exports = require('backbone').Collection.extend({ model: Selector, getStyleable() { - return filter(this.models, item => - item.get('active') && !item.get('private')); + return filter( + this.models, + item => item.get('active') && !item.get('private') + ); }, getValid() { diff --git a/src/selector_manager/view/ClassTagView.js b/src/selector_manager/view/ClassTagView.js index 96bd42ef6c..119c936dec 100644 --- a/src/selector_manager/view/ClassTagView.js +++ b/src/selector_manager/view/ClassTagView.js @@ -2,7 +2,6 @@ const Selector = require('./../model/Selector'); const inputProp = 'contentEditable'; module.exports = require('backbone').View.extend({ - template() { const pfx = this.pfx; const ppfx = this.ppfx; @@ -16,15 +15,13 @@ module.exports = require('backbone').View.extend({ `; }, - events: { 'click [data-tag-remove]': 'removeTag', 'click [data-tag-status]': 'changeStatus', 'dblclick [data-tag-name]': 'startEditTag', - 'focusout [data-tag-name]': 'endEditTag', + 'focusout [data-tag-name]': 'endEditTag' }, - initialize(o) { this.config = o.config || {}; this.coll = o.coll || null; @@ -34,7 +31,6 @@ module.exports = require('backbone').View.extend({ this.listenTo(this.model, 'change:active', this.updateStatus); }, - /** * Returns the element which containes the anme of the tag * @return {HTMLElement} @@ -47,7 +43,6 @@ module.exports = require('backbone').View.extend({ return this.inputEl; }, - /** * Start editing tag * @private @@ -58,7 +53,6 @@ module.exports = require('backbone').View.extend({ inputEl.focus(); }, - /** * End editing tag. If the class typed already exists the * old one will be restored otherwise will be changed @@ -82,7 +76,6 @@ module.exports = require('backbone').View.extend({ } }, - /** * Update status of the tag * @private @@ -91,7 +84,6 @@ module.exports = require('backbone').View.extend({ this.model.set('active', !this.model.get('active')); }, - /** * Remove tag from the selected component * @param {Object} e @@ -108,7 +100,6 @@ module.exports = require('backbone').View.extend({ setTimeout(() => this.remove(), 0); }, - /** * Update status of the checkbox * @private @@ -117,19 +108,17 @@ module.exports = require('backbone').View.extend({ var chkOn = 'fa-check-square-o'; var chkOff = 'fa-square-o'; - if(!this.$chk) - this.$chk = this.$el.find('#' + this.pfx + 'checkbox'); + if (!this.$chk) this.$chk = this.$el.find('#' + this.pfx + 'checkbox'); - if(this.model.get('active')){ + if (this.model.get('active')) { this.$chk.removeClass(chkOff).addClass(chkOn); this.$el.removeClass('opac50'); - }else{ + } else { this.$chk.removeClass(chkOn).addClass(chkOff); this.$el.addClass('opac50'); } }, - render() { const pfx = this.pfx; const ppfx = this.ppfx; @@ -137,6 +126,5 @@ module.exports = require('backbone').View.extend({ this.$el.attr('class', `${pfx}tag ${ppfx}three-bg`); this.updateStatus(); return this; - }, - + } }); diff --git a/src/selector_manager/view/ClassTagsView.js b/src/selector_manager/view/ClassTagsView.js index 5eeeadefbe..a00019e7fc 100644 --- a/src/selector_manager/view/ClassTagsView.js +++ b/src/selector_manager/view/ClassTagsView.js @@ -51,7 +51,11 @@ module.exports = Backbone.View.extend({ this.target = this.config.em; this.em = this.target; - this.listenTo(this.target ,'change:selectedComponent',this.componentChanged); + this.listenTo( + this.target, + 'change:selectedComponent', + this.componentChanged + ); this.listenTo(this.target, 'component:update:classes', this.updateSelector); this.listenTo(this.collection, 'add', this.addNew); @@ -77,8 +81,13 @@ module.exports = Backbone.View.extend({ */ getStateOptions() { var strInput = ''; - for(var i = 0; i < this.states.length; i++){ - strInput += ''; + for (var i = 0; i < this.states.length; i++) { + strInput += + ''; } return strInput; }, @@ -118,10 +127,8 @@ module.exports = Backbone.View.extend({ * @private */ onInputKeyUp(e) { - if (e.keyCode === 13) - this.addNewTag(this.$input.val()); - else if(e.keyCode === 27) - this.endNewTag(); + if (e.keyCode === 13) this.addNewTag(this.$input.val()); + else if (e.keyCode === 27) this.endNewTag(); }, /** @@ -152,14 +159,12 @@ module.exports = Backbone.View.extend({ const em = this.em; const avoidInline = em && em.getConfig('avoidInlineStyle'); - if(this.collection.length || avoidInline) - this.getStatesC().css('display','block'); - else - this.getStatesC().css('display','none'); + if (this.collection.length || avoidInline) + this.getStatesC().css('display', 'block'); + else this.getStatesC().css('display', 'none'); this.updateSelector(); }, - /** * Udpate selector helper * @return {this} @@ -182,14 +187,13 @@ module.exports = Backbone.View.extend({ el && (el.innerHTML = result); }, - /** * Triggered when the select with states is changed * @param {Object} e * @private */ stateChanged(e) { - if(this.compTarget){ + if (this.compTarget) { this.compTarget.set('state', this.$states.val()); this.updateSelector(); } @@ -210,7 +214,7 @@ module.exports = Backbone.View.extend({ if (target) { const sm = target.get('SelectorManager'); - var model = sm.add({label}); + var model = sm.add({ label }); if (component) { var compCls = component.get('classes'); @@ -232,19 +236,17 @@ module.exports = Backbone.View.extend({ * @private * */ addToClasses(model, fragmentEl) { - var fragment = fragmentEl || null; + var fragment = fragmentEl || null; var view = new ClassTagView({ - model, - config: this.config, - coll: this.collection, + model, + config: this.config, + coll: this.collection }); - var rendered = view.render().el; + var rendered = view.render().el; - if(fragment) - fragment.appendChild(rendered); - else - this.getClasses().append(rendered); + if (fragment) fragment.appendChild(rendered); + else this.getClasses().append(rendered); return rendered; }, @@ -257,12 +259,14 @@ module.exports = Backbone.View.extend({ renderClasses() { var fragment = document.createDocumentFragment(); - this.collection.each(function(model){ + this.collection.each(function(model) { this.addToClasses(model, fragment); - },this); + }, this); - if(this.getClasses()) - this.getClasses().empty().append(fragment); + if (this.getClasses()) + this.getClasses() + .empty() + .append(fragment); return this; }, @@ -273,7 +277,7 @@ module.exports = Backbone.View.extend({ * @private */ getClasses() { - if(!this.$classes) + if (!this.$classes) this.$classes = this.$el.find('#' + this.pfx + 'tags-c'); return this.$classes; }, @@ -284,8 +288,7 @@ module.exports = Backbone.View.extend({ * @private */ getStates() { - if(!this.$states) - this.$states = this.$el.find('#' + this.stateInputId); + if (!this.$states) this.$states = this.$el.find('#' + this.stateInputId); return this.$states; }, @@ -295,20 +298,21 @@ module.exports = Backbone.View.extend({ * @private */ getStatesC() { - if(!this.$statesC) - this.$statesC = this.$el.find('#' + this.stateInputC); + if (!this.$statesC) this.$statesC = this.$el.find('#' + this.stateInputC); return this.$statesC; }, render() { const config = this.config; - this.$el.html(this.template({ - selectedLabel: config.selectedLabel, - statesLabel: config.statesLabel, - label: config.label, - pfx: this.pfx, - ppfx: this.ppfx, - })); + this.$el.html( + this.template({ + selectedLabel: config.selectedLabel, + statesLabel: config.statesLabel, + label: config.label, + pfx: this.pfx, + ppfx: this.ppfx + }) + ); this.$input = this.$el.find('input#' + this.newInputId); this.$addBtn = this.$el.find('#' + this.addBtnId); this.$classes = this.$el.find('#' + this.pfx + 'tags-c'); @@ -318,6 +322,5 @@ module.exports = Backbone.View.extend({ this.renderClasses(); this.$el.attr('class', this.className); return this; - }, - + } }); diff --git a/src/storage_manager/config/config.js b/src/storage_manager/config/config.js index 77f074a2c6..f77f889d03 100644 --- a/src/storage_manager/config/config.js +++ b/src/storage_manager/config/config.js @@ -54,5 +54,4 @@ module.exports = { // true: application/json; charset=utf-8' // false: 'x-www-form-urlencoded' contentTypeJson: false - }; diff --git a/src/storage_manager/index.js b/src/storage_manager/index.js index 20b0e0f28c..ff8d8082e9 100644 --- a/src/storage_manager/index.js +++ b/src/storage_manager/index.js @@ -7,15 +7,14 @@ */ module.exports = () => { var c = {}, - defaults = require('./config/config'), - LocalStorage = require('./model/LocalStorage'), - RemoteStorage = require('./model/RemoteStorage'); + defaults = require('./config/config'), + LocalStorage = require('./model/LocalStorage'), + RemoteStorage = require('./model/RemoteStorage'); var storages = {}; var defaultStorages = {}; return { - /** * Name of the module * @type {String} @@ -45,11 +44,10 @@ module.exports = () => { c = config || {}; for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } - defaultStorages.remote = new RemoteStorage(c); + defaultStorages.remote = new RemoteStorage(c); defaultStorages.local = new LocalStorage(c); c.currentStorage = c.type; this.loadDefaultProviders().setCurrent(c.type); @@ -88,7 +86,7 @@ module.exports = () => { * @return {this} * */ setStepsBeforeSave(v) { - c.stepsBeforeSave = v; + c.stepsBeforeSave = v; return this; }, @@ -168,8 +166,7 @@ module.exports = () => { var st = this.get(this.getCurrent()); var dataF = {}; - for(var key in data) - dataF[c.id + key] = data[key]; + for (var key in data) dataF[c.id + key] = data[key]; return st ? st.store(dataF, clb) : null; }, @@ -191,22 +188,22 @@ module.exports = () => { var keysF = []; var result = {}; - if(typeof keys === 'string') - keys = [keys]; + if (typeof keys === 'string') keys = [keys]; for (var i = 0, len = keys.length; i < len; i++) keysF.push(c.id + keys[i]); - st && st.load(keysF, res => { - // Restore keys name - var reg = new RegExp('^' + c.id + ''); - for (var itemKey in res) { - var itemKeyR = itemKey.replace(reg, ''); - result[itemKeyR] = res[itemKey]; - } - - clb && clb(result); - }); + st && + st.load(keysF, res => { + // Restore keys name + var reg = new RegExp('^' + c.id + ''); + for (var itemKey in res) { + var itemKeyR = itemKey.replace(reg, ''); + result[itemKeyR] = res[itemKey]; + } + + clb && clb(result); + }); }, /** @@ -215,8 +212,7 @@ module.exports = () => { * @private * */ loadDefaultProviders() { - for (var id in defaultStorages) - this.add(id, defaultStorages[id]); + for (var id in defaultStorages) this.add(id, defaultStorages[id]); return this; }, @@ -227,8 +223,6 @@ module.exports = () => { * */ getConfig() { return c; - }, - + } }; - }; diff --git a/src/storage_manager/model/LocalStorage.js b/src/storage_manager/model/LocalStorage.js index ec8c688750..1e0421dea3 100644 --- a/src/storage_manager/model/LocalStorage.js +++ b/src/storage_manager/model/LocalStorage.js @@ -1,19 +1,17 @@ var Backbone = require('backbone'); module.exports = Backbone.Model.extend({ - defaults: { - checkLocal: true, + checkLocal: true }, /** - * @private - */ + * @private + */ store(data, clb) { this.checkStorageEnvironment(); - for(var key in data) - localStorage.setItem(key, data[key]); + for (var key in data) localStorage.setItem(key, data[key]); if (typeof clb == 'function') { clb(); @@ -27,10 +25,9 @@ module.exports = Backbone.Model.extend({ this.checkStorageEnvironment(); var result = {}; - for (var i = 0, len = keys.length; i < len; i++){ + for (var i = 0, len = keys.length; i < len; i++) { var value = localStorage.getItem(keys[i]); - if(value) - result[keys[i]] = value; + if (value) result[keys[i]] = value; } if (typeof clb == 'function') { @@ -55,8 +52,7 @@ module.exports = Backbone.Model.extend({ * @private * */ checkStorageEnvironment() { - if(this.get('checkLocal') && !localStorage) + if (this.get('checkLocal') && !localStorage) console.warn("Your browser doesn't support localStorage"); - }, - + } }); diff --git a/src/storage_manager/model/RemoteStorage.js b/src/storage_manager/model/RemoteStorage.js index df043b096f..bb577803db 100644 --- a/src/storage_manager/model/RemoteStorage.js +++ b/src/storage_manager/model/RemoteStorage.js @@ -2,7 +2,6 @@ import fetch from 'utils/fetch'; import { isUndefined } from 'underscore'; module.exports = require('backbone').Model.extend({ - fetch, defaults: { @@ -56,7 +55,7 @@ module.exports = require('backbone').Model.extend({ const em = this.get('em'); const complete = this.get('onComplete'); const typeJson = this.get('contentTypeJson'); - const res = typeJson && typeof text === 'string' ? JSON.parse(text): text; + const res = typeJson && typeof text === 'string' ? JSON.parse(text) : text; complete && complete(res); clb && clb(res); em && em.trigger('storage:response', res); @@ -70,11 +69,11 @@ module.exports = require('backbone').Model.extend({ body[key] = data[key]; } - this.request(this.get('urlStore'), {body}, clb); + this.request(this.get('urlStore'), { body }, clb); }, load(keys, clb) { - this.request(this.get('urlLoad'), {method: 'get'}, clb); + this.request(this.get('urlLoad'), { method: 'get' }, clb); }, /** @@ -121,7 +120,7 @@ module.exports = require('backbone').Model.extend({ fetchOptions = { method: opts.method || 'post', credentials: 'include', - headers, + headers }; // Body should only be included on POST method @@ -131,11 +130,13 @@ module.exports = require('backbone').Model.extend({ this.onStart(); this.fetch(url, fetchOptions) - .then(res => (res.status/200|0) == 1 - ? res.text() - : res.text().then((text) => Promise.reject(text))) - .then((text) => this.onResponse(text, clb)) + .then( + res => + ((res.status / 200) | 0) == 1 + ? res.text() + : res.text().then(text => Promise.reject(text)) + ) + .then(text => this.onResponse(text, clb)) .catch(err => this.onError(err)); - }, - + } }); diff --git a/src/style_manager/config/config.js b/src/style_manager/config/config.js index b38722724c..bbda994afb 100644 --- a/src/style_manager/config/config.js +++ b/src/style_manager/config/config.js @@ -24,5 +24,5 @@ module.exports = { clearProperties: 0, // Properties not to take in account for computed styles - avoidComputed: ['width', 'height'], + avoidComputed: ['width', 'height'] }; diff --git a/src/style_manager/index.js b/src/style_manager/index.js index 135bd6c88e..d6615c3af2 100644 --- a/src/style_manager/index.js +++ b/src/style_manager/index.js @@ -40,15 +40,14 @@ */ module.exports = () => { var c = {}, - defaults = require('./config/config'), - Sectors = require('./model/Sectors'), - Properties = require('./model/Properties'), - SectorsView = require('./view/SectorsView'); + defaults = require('./config/config'), + Sectors = require('./model/Sectors'), + Properties = require('./model/Properties'), + SectorsView = require('./view/SectorsView'); let properties; var sectors, SectView; return { - /** * Name of the module * @type {String} @@ -56,7 +55,6 @@ module.exports = () => { */ name: 'StyleManager', - /** * Get configuration object * @return {Object} @@ -66,7 +64,6 @@ module.exports = () => { return c; }, - /** * Initialize module. Automatically called with a new instance of the editor * @param {Object} config Configurations @@ -74,25 +71,22 @@ module.exports = () => { init(config) { c = config || {}; for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; + if (!(name in c)) c[name] = defaults[name]; } var ppfx = c.pStylePrefix; - if(ppfx) - c.stylePrefix = ppfx + c.stylePrefix; + if (ppfx) c.stylePrefix = ppfx + c.stylePrefix; properties = new Properties(); sectors = new Sectors(c.sectors, c); - SectView = new SectorsView({ + SectView = new SectorsView({ collection: sectors, target: c.em, - config: c, + config: c }); return this; }, - /** * Add new sector to the collection. If the sector with the same id already exists, * that one will be returned @@ -111,14 +105,13 @@ module.exports = () => { * */ addSector(id, sector) { var result = this.getSector(id); - if(!result){ + if (!result) { sector.id = id; result = sectors.add(sector); } return result; }, - /** * Get sector by id * @param {string} id Sector id @@ -127,11 +120,10 @@ module.exports = () => { * var sector = styleManager.getSector('mySector'); * */ getSector(id) { - var res = sectors.where({id}); + var res = sectors.where({ id }); return res.length ? res[0] : null; }, - /** * Remove a sector by id * @param {string} id Sector id @@ -143,7 +135,6 @@ module.exports = () => { return this.getSectors().remove(this.getSector(id)); }, - /** * Get all sectors * @return {Sectors} Collection of sectors @@ -152,7 +143,6 @@ module.exports = () => { return sectors; }, - /** * Add property to the sector identified by id * @param {string} sectorId Sector id @@ -192,13 +182,11 @@ module.exports = () => { var prop = null; var sector = this.getSector(sectorId); - if(sector) - prop = sector.get('properties').add(property); + if (sector) prop = sector.get('properties').add(property); return prop; }, - /** * Get property by its CSS name and sector id * @param {string} sectorId Sector id @@ -211,15 +199,14 @@ module.exports = () => { var prop = null; var sector = this.getSector(sectorId); - if(sector){ - prop = sector.get('properties').where({property: name}); + if (sector) { + prop = sector.get('properties').where({ property: name }); prop = prop.length == 1 ? prop[0] : prop; } return prop; }, - /** * Remove a property from the sector * @param {string} sectorId Sector id @@ -233,7 +220,6 @@ module.exports = () => { return props && props.remove(this.getProperty(sectorId, name)); }, - /** * Get properties of the sector * @param {string} sectorId Sector id @@ -245,13 +231,11 @@ module.exports = () => { var props = null; var sector = this.getSector(sectorId); - if(sector) - props = sector.get('properties'); + if (sector) props = sector.get('properties'); return props; }, - /** * Get what to style inside Style Manager. If you select the component * without classes the entity is the Component itself and all changes will @@ -286,7 +270,6 @@ module.exports = () => { return model; }, - /** * Add new property type * @param {string} id Type ID @@ -308,7 +291,6 @@ module.exports = () => { properties.addType(id, definition); }, - /** * Get type * @param {string} id Type ID @@ -318,7 +300,6 @@ module.exports = () => { return properties.getType(id); }, - /** * Get all types * @return {Array} @@ -327,7 +308,6 @@ module.exports = () => { return properties.getTypes(); }, - /** * Create new property from type * @param {string} id Type ID @@ -343,7 +323,7 @@ module.exports = () => { * propView.model.on('change:value', ...); * someContainer.appendChild(propView.el); */ - createType(id, {model = {}, view = {}} = {}) { + createType(id, { model = {}, view = {} } = {}) { const type = this.getType(id); if (type) { @@ -355,14 +335,12 @@ module.exports = () => { } }, - /** * Render sectors and properties * @return {HTMLElement} * */ render() { return SectView.render().el; - }, - + } }; }; diff --git a/src/style_manager/model/Layer.js b/src/style_manager/model/Layer.js index a704c72674..2a99e9fff5 100644 --- a/src/style_manager/model/Layer.js +++ b/src/style_manager/model/Layer.js @@ -1,24 +1,25 @@ module.exports = Backbone.Model.extend({ - defaults: { index: '', value: '', values: {}, active: false, preview: false, - properties: [], + properties: [] }, initialize() { const Properties = require('./Properties'); const properties = this.get('properties'); var value = this.get('value'); - this.set('properties', properties instanceof Properties ? - properties : new Properties(properties)); + this.set( + 'properties', + properties instanceof Properties ? properties : new Properties(properties) + ); // If there is no value I'll try to get it from values // I need value setted to make preview working - if(!value){ + if (!value) { var val = ''; var values = this.get('values'); @@ -45,5 +46,4 @@ module.exports = Backbone.Model.extend({ this.get('properties').each(prop => result.push(prop.getFullValue())); return result.join(' '); } - }); diff --git a/src/style_manager/model/Layers.js b/src/style_manager/model/Layers.js index c1fc0b9bd0..3411d683cc 100644 --- a/src/style_manager/model/Layers.js +++ b/src/style_manager/model/Layers.js @@ -1,7 +1,6 @@ const Layer = require('./Layer'); module.exports = Backbone.Collection.extend({ - model: Layer, initialize() { @@ -11,8 +10,7 @@ module.exports = Backbone.Collection.extend({ }, onAdd(model, c, opts) { - if(!opts.noIncrement) - model.set('index', this.idx++); + if (!opts.noIncrement) model.set('index', this.idx++); }, onReset() { @@ -38,7 +36,7 @@ module.exports = Backbone.Collection.extend({ }); const layerValues = value ? value.split(', ') : []; layerValues.forEach(layerValue => { - layers.push({properties: this.properties.parseValue(layerValue)}); + layers.push({ properties: this.properties.parseValue(layerValue) }); }); return layers; }, @@ -85,15 +83,14 @@ module.exports = Backbone.Collection.extend({ const propertyName = propModel.get('property'); if (layerProprs.indexOf(propertyName) < 0) { - layer.properties.push({ ...propModel.attributes }) + layer.properties.push({ ...propModel.attributes }); } - }) + }); }); return layers; }, - active(index) { this.each(layer => layer.set('active', 0)); const layer = this.at(index); @@ -114,5 +111,4 @@ module.exports = Backbone.Collection.extend({ }); return result.join(', '); } - }); diff --git a/src/style_manager/model/Properties.js b/src/style_manager/model/Properties.js index c2d4471ae6..33253ad81f 100644 --- a/src/style_manager/model/Properties.js +++ b/src/style_manager/model/Properties.js @@ -1,120 +1,132 @@ import TypeableCollection from 'domain_abstract/model/TypeableCollection'; const Property = require('./Property'); -module.exports = require('backbone').Collection.extend(TypeableCollection).extend({ - types: [ - { - id: 'stack', - model: require('./PropertyStack'), - view: require('./../view/PropertyStackView'), - isType(value) { - if (value && value.type == 'stack') { - return value; +module.exports = require('backbone') + .Collection.extend(TypeableCollection) + .extend({ + types: [ + { + id: 'stack', + model: require('./PropertyStack'), + view: require('./../view/PropertyStackView'), + isType(value) { + if (value && value.type == 'stack') { + return value; + } } - } - },{ - id: 'composite', - model: require('./PropertyComposite'), - view: require('./../view/PropertyCompositeView'), - isType(value) { - if (value && value.type == 'composite') { - return value; + }, + { + id: 'composite', + model: require('./PropertyComposite'), + view: require('./../view/PropertyCompositeView'), + isType(value) { + if (value && value.type == 'composite') { + return value; + } } - } - },{ - id: 'file', - model: Property, - view: require('./../view/PropertyFileView'), - isType(value) { - if (value && value.type == 'file') { - return value; + }, + { + id: 'file', + model: Property, + view: require('./../view/PropertyFileView'), + isType(value) { + if (value && value.type == 'file') { + return value; + } } - } - },{ - id: 'color', - model: Property, - view: require('./../view/PropertyColorView'), - isType(value) { - if (value && value.type == 'color') { - return value; + }, + { + id: 'color', + model: Property, + view: require('./../view/PropertyColorView'), + isType(value) { + if (value && value.type == 'color') { + return value; + } } - } - },{ - id: 'select', - model: require('./PropertyRadio'), - view: require('./../view/PropertySelectView'), - isType(value) { - if (value && value.type == 'select') { - return value; + }, + { + id: 'select', + model: require('./PropertyRadio'), + view: require('./../view/PropertySelectView'), + isType(value) { + if (value && value.type == 'select') { + return value; + } } - } - },{ - id: 'radio', - model: require('./PropertyRadio'), - view: require('./../view/PropertyRadioView'), - isType(value) { - if (value && value.type == 'radio') { - return value; + }, + { + id: 'radio', + model: require('./PropertyRadio'), + view: require('./../view/PropertyRadioView'), + isType(value) { + if (value && value.type == 'radio') { + return value; + } } - } - },{ - id: 'slider', - model: require('./PropertySlider'), - view: require('./../view/PropertySliderView'), - isType(value) { - if (value && value.type == 'slider') { - return value; + }, + { + id: 'slider', + model: require('./PropertySlider'), + view: require('./../view/PropertySliderView'), + isType(value) { + if (value && value.type == 'slider') { + return value; + } } - } - },{ - id: 'integer', - model: require('./PropertyInteger'), - view: require('./../view/PropertyIntegerView'), - isType(value) { - if (value && value.type == 'integer') { + }, + { + id: 'integer', + model: require('./PropertyInteger'), + view: require('./../view/PropertyIntegerView'), + isType(value) { + if (value && value.type == 'integer') { + return value; + } + } + }, + { + id: 'base', + model: Property, + view: require('./../view/PropertyView'), + isType(value) { + value.type = 'base'; return value; } } - },{ - id: 'base', - model: Property, - view: require('./../view/PropertyView'), - isType(value) { - value.type = 'base'; - return value; - } - } - ], + ], - deepClone() { - const collection = this.clone(); - collection.reset(collection.map(model => { - const cloned = model.clone(); - cloned.typeView = model.typeView; - return cloned; - })); - return collection; - }, + deepClone() { + const collection = this.clone(); + collection.reset( + collection.map(model => { + const cloned = model.clone(); + cloned.typeView = model.typeView; + return cloned; + }) + ); + return collection; + }, - /** - * Parse a value and return an array splitted by properties - * @param {string} value - * @return {Array} - * @return - */ - parseValue(value) { - const properties = []; - const values = value.split(' '); - values.forEach((value, i) => { - const property = this.at(i); - properties.push({ ...property.attributes, ...{ value } }); - }); - return properties; - }, + /** + * Parse a value and return an array splitted by properties + * @param {string} value + * @return {Array} + * @return + */ + parseValue(value) { + const properties = []; + const values = value.split(' '); + values.forEach((value, i) => { + const property = this.at(i); + properties.push({ ...property.attributes, ...{ value } }); + }); + return properties; + }, - getFullValue() { - let result = ''; - this.each(model => result += `${model.getFullValue()} `); - return result.trim(); - } -}); + getFullValue() { + let result = ''; + this.each(model => (result += `${model.getFullValue()} `)); + return result.trim(); + } + }); diff --git a/src/style_manager/model/Property.js b/src/style_manager/model/Property.js index c6f4d48f3d..cf0d757cff 100644 --- a/src/style_manager/model/Property.js +++ b/src/style_manager/model/Property.js @@ -1,5 +1,4 @@ module.exports = require('backbone').Model.extend({ - defaults: { name: '', property: '', @@ -18,24 +17,25 @@ module.exports = require('backbone').Model.extend({ // Use case: // you can add all SVG CSS properties with toRequire as true // and then require them on SVG Components - toRequire: 0, + toRequire: 0 }, - initialize(opt) { var o = opt || {}; var name = this.get('name'); var prop = this.get('property'); if (!name) { - this.set('name', prop.charAt(0).toUpperCase() + prop.slice(1).replace(/-/g,' ')); + this.set( + 'name', + prop.charAt(0).toUpperCase() + prop.slice(1).replace(/-/g, ' ') + ); } const init = this.init && this.init.bind(this); init && init(); }, - /** * Update value * @param {any} value @@ -44,7 +44,7 @@ module.exports = require('backbone').Model.extend({ */ setValue(value, complete = 1, opts = {}) { const parsed = this.parseValue(value); - this.set(parsed, { ...opts, avoidStore: 1}); + this.set(parsed, { ...opts, avoidStore: 1 }); // It's important to set an empty value, otherwise the // UndoManager won't see the change @@ -54,7 +54,6 @@ module.exports = require('backbone').Model.extend({ } }, - /** * Like `setValue` but, in addition, prevents the update of the input element * as the changes should come from the input itself. @@ -64,10 +63,9 @@ module.exports = require('backbone').Model.extend({ * @param {Object} [opts={}] Options */ setValueFromInput(value, complete, opts = {}) { - this.setValue(value, complete, {...opts, fromInput: 1}); + this.setValue(value, complete, { ...opts, fromInput: 1 }); }, - /** * Parse a raw value, generally fetched from the target, for this property * @param {string} value Raw value string @@ -100,7 +98,6 @@ module.exports = require('backbone').Model.extend({ return result; }, - /** * Get the default value * @return {string} @@ -110,7 +107,6 @@ module.exports = require('backbone').Model.extend({ return this.get('defaults'); }, - /** * Get a complete value of the property. * This probably will replace the getValue when all @@ -128,6 +124,5 @@ module.exports = require('backbone').Model.extend({ } return value; - }, - + } }); diff --git a/src/style_manager/model/PropertyComposite.js b/src/style_manager/model/PropertyComposite.js index 069ecfb791..8234217c53 100644 --- a/src/style_manager/model/PropertyComposite.js +++ b/src/style_manager/model/PropertyComposite.js @@ -1,8 +1,8 @@ const Property = require('./Property'); module.exports = Property.extend({ - - defaults: { ...Property.prototype.defaults, + defaults: { + ...Property.prototype.defaults, // 'background' is a good example where to make a difference // between detached and not // @@ -18,18 +18,16 @@ module.exports = Property.extend({ properties: [], // Separator between properties - separator: ' ', + separator: ' ' }, - init() { const properties = this.get('properties') || []; const Properties = require('./Properties'); this.set('properties', new Properties(properties)); - this.listenTo(this, 'change:value', this.updateValues) + this.listenTo(this, 'change:value', this.updateValues); }, - /** * Update property values */ @@ -40,13 +38,13 @@ module.exports = Property.extend({ // Try to get value from a shorthand: // 11px -> 11px 11px 11px 11xp // 11px 22px -> 11px 22px 11px 22xp - const value = values[i] || values[(i % len) + (len != 1 && len % 2 ? 1 : 0)]; + const value = + values[i] || values[i % len + (len != 1 && len % 2 ? 1 : 0)]; // There some issue with UndoManager //property.setValue(value, 0, {fromParent: 1}); }); }, - /** * Returns default value * @param {Boolean} defaultProps Force to get defaults from properties @@ -61,17 +59,15 @@ module.exports = Property.extend({ value = ''; const properties = this.get('properties'); - properties.each((prop, index) => value += `${prop.getDefaultValue()} `); + properties.each((prop, index) => (value += `${prop.getDefaultValue()} `)); return value.trim(); }, - getFullValue() { if (this.get('detached')) { return ''; } return this.get('properties').getFullValue(); - }, - + } }); diff --git a/src/style_manager/model/PropertyFactory.js b/src/style_manager/model/PropertyFactory.js index 3851d91343..231b908e17 100644 --- a/src/style_manager/model/PropertyFactory.js +++ b/src/style_manager/model/PropertyFactory.js @@ -10,8 +10,7 @@ module.exports = () => ({ var objs = []; var dftFixedValues = ['initial', 'inherit']; - if(typeof props === 'string') - props = [props]; + if (typeof props === 'string') props = [props]; for (var i = 0, len = props.length; i < len; i++) { var obj = {}; @@ -19,73 +18,135 @@ module.exports = () => ({ obj.property = prop; // Property - switch(prop){ + switch (prop) { case 'border-radius-c': obj.property = 'border-radius'; break; } // Fixed values - switch(prop) { - case 'margin-top': case 'margin-right': case 'margin-bottom': case 'margin-left': - case 'padding-top': case 'padding-right': case 'padding-bottom': case 'padding-left': - case 'width': case 'max-width': case 'min-width': - case 'height': case 'max-height': case 'min-height': + switch (prop) { + case 'margin-top': + case 'margin-right': + case 'margin-bottom': + case 'margin-left': + case 'padding-top': + case 'padding-right': + case 'padding-bottom': + case 'padding-left': + case 'width': + case 'max-width': + case 'min-width': + case 'height': + case 'max-height': + case 'min-height': obj.fixedValues = ['initial', 'inherit', 'auto']; break; case 'font-size': - obj.fixedValues = ['medium', 'xx-small', 'x-small', 'small', 'large', - 'x-large', 'xx-large', 'smaller', 'larger', 'length', 'initial', 'inherit']; + obj.fixedValues = [ + 'medium', + 'xx-small', + 'x-small', + 'small', + 'large', + 'x-large', + 'xx-large', + 'smaller', + 'larger', + 'length', + 'initial', + 'inherit' + ]; break; - case 'letter-spacing': case 'line-height': + case 'letter-spacing': + case 'line-height': obj.fixedValues = ['normal', 'initial', 'inherit']; break; } // Type - switch(prop){ - case 'float': case 'position': + switch (prop) { + case 'float': + case 'position': case 'text-align': obj.type = 'radio'; break; - case 'display': case 'font-family': + case 'display': + case 'font-family': case 'font-weight': case 'border-style': case 'box-shadow-type': - case 'background-repeat': case 'background-position': case 'background-attachment': case 'background-size': - case 'transition-property': case 'transition-timing-function': + case 'background-repeat': + case 'background-position': + case 'background-attachment': + case 'background-size': + case 'transition-property': + case 'transition-timing-function': case 'cursor': case 'overflow': obj.type = 'select'; break; - case 'top': case 'right': case 'bottom': case 'left': - case 'margin-top': case 'margin-right': case 'margin-bottom': case 'margin-left': - case 'padding-top': case 'padding-right': case 'padding-bottom': case 'padding-left': - case 'min-height': case 'min-width': case 'max-height': case 'max-width': - case 'width': case 'height': - case 'font-size': case 'letter-spacing': case 'line-height': - case 'text-shadow-h': case 'text-shadow-v': case 'text-shadow-blur': + case 'top': + case 'right': + case 'bottom': + case 'left': + case 'margin-top': + case 'margin-right': + case 'margin-bottom': + case 'margin-left': + case 'padding-top': + case 'padding-right': + case 'padding-bottom': + case 'padding-left': + case 'min-height': + case 'min-width': + case 'max-height': + case 'max-width': + case 'width': + case 'height': + case 'font-size': + case 'letter-spacing': + case 'line-height': + case 'text-shadow-h': + case 'text-shadow-v': + case 'text-shadow-blur': case 'border-radius-c': - case 'border-top-left-radius': case 'border-top-right-radius': case 'border-bottom-left-radius':case 'border-bottom-right-radius': + case 'border-top-left-radius': + case 'border-top-right-radius': + case 'border-bottom-left-radius': + case 'border-bottom-right-radius': case 'border-width': - case 'box-shadow-h': case 'box-shadow-v': case 'box-shadow-blur': case 'box-shadow-spread': + case 'box-shadow-h': + case 'box-shadow-v': + case 'box-shadow-blur': + case 'box-shadow-spread': case 'transition-duration': case 'perspective': - case 'transform-rotate-x': case 'transform-rotate-y': case 'transform-rotate-z': - case 'transform-scale-x': case 'transform-scale-y': case 'transform-scale-z': + case 'transform-rotate-x': + case 'transform-rotate-y': + case 'transform-rotate-z': + case 'transform-scale-x': + case 'transform-scale-y': + case 'transform-scale-z': obj.type = 'integer'; break; - case 'margin': case 'padding': + case 'margin': + case 'padding': case 'border-radius': case 'border': case 'transform': obj.type = 'composite'; break; - case 'color': case 'text-shadow-color': - case 'background-color': case 'border-color': case 'box-shadow-color': + case 'color': + case 'text-shadow-color': + case 'background-color': + case 'border-color': + case 'box-shadow-color': obj.type = 'color'; break; - case 'text-shadow': case 'box-shadow': case 'background': + case 'text-shadow': + case 'box-shadow': + case 'background': case 'transition': obj.type = 'stack'; break; @@ -95,9 +156,11 @@ module.exports = () => ({ } // Defaults - switch(prop) { - case 'float': case 'background-color': - case 'background-image': case 'text-shadow': + switch (prop) { + case 'float': + case 'background-color': + case 'background-image': + case 'text-shadow': obj.defaults = 'none'; break; case 'display': @@ -106,25 +169,49 @@ module.exports = () => ({ case 'position': obj.defaults = 'static'; break; - case 'top': case 'right': case 'bottom': case 'left': - case 'margin-top': case 'margin-right': case 'margin-bottom': case 'margin-left': - case 'padding-top': case 'padding-right': case 'padding-bottom': case 'padding-left': - case 'text-shadow-h': case 'text-shadow-v': case 'text-shadow-blur': + case 'top': + case 'right': + case 'bottom': + case 'left': + case 'margin-top': + case 'margin-right': + case 'margin-bottom': + case 'margin-left': + case 'padding-top': + case 'padding-right': + case 'padding-bottom': + case 'padding-left': + case 'text-shadow-h': + case 'text-shadow-v': + case 'text-shadow-blur': case 'border-radius-c': - case 'border-top-left-radius': case 'border-top-right-radius': case 'border-bottom-left-radius':case 'border-bottom-right-radius': - case 'box-shadow-h': case 'box-shadow-v': case 'box-shadow-spread': + case 'border-top-left-radius': + case 'border-top-right-radius': + case 'border-bottom-left-radius': + case 'border-bottom-right-radius': + case 'box-shadow-h': + case 'box-shadow-v': + case 'box-shadow-spread': case 'perspective': - case 'transform-rotate-x': case 'transform-rotate-y': case 'transform-rotate-z': + case 'transform-rotate-x': + case 'transform-rotate-y': + case 'transform-rotate-z': obj.defaults = 0; break; - case 'transform-scale-x': case 'transform-scale-y': case 'transform-scale-z': + case 'transform-scale-x': + case 'transform-scale-y': + case 'transform-scale-z': obj.defaults = 1; break; case 'box-shadow-blur': obj.defaults = '5px'; break; - case 'min-height': case 'min-width': case 'max-height': case 'max-width': - case 'width': case 'height': + case 'min-height': + case 'min-width': + case 'max-height': + case 'max-width': + case 'width': + case 'height': case 'background-size': case 'cursor': obj.defaults = 'auto'; @@ -132,17 +219,21 @@ module.exports = () => ({ case 'font-family': obj.defaults = 'Arial, Helvetica, sans-serif'; break; - case 'font-size': case 'border-width': + case 'font-size': + case 'border-width': obj.defaults = 'medium'; break; case 'font-weight': obj.defaults = '400'; break; - case 'letter-spacing': case 'line-height': + case 'letter-spacing': + case 'line-height': obj.defaults = 'normal'; break; - case 'color': case 'text-shadow-color': - case 'border-color': case 'box-shadow-color': + case 'color': + case 'text-shadow-color': + case 'border-color': + case 'box-shadow-color': obj.defaults = 'black'; break; case 'text-align': @@ -178,45 +269,79 @@ module.exports = () => ({ } // Units - switch(prop){ - case 'top': case 'right': case 'bottom': case 'left': - case 'margin-top': case 'margin-right': case 'margin-bottom': case 'margin-left': - case 'padding-top': case 'padding-right': case 'padding-bottom': case 'padding-left': - case 'min-height': case 'min-width': case 'max-height': case 'max-width': - case 'width': case 'height': - case 'text-shadow-h': case 'text-shadow-v': case 'text-shadow-blur': + switch (prop) { + case 'top': + case 'right': + case 'bottom': + case 'left': + case 'margin-top': + case 'margin-right': + case 'margin-bottom': + case 'margin-left': + case 'padding-top': + case 'padding-right': + case 'padding-bottom': + case 'padding-left': + case 'min-height': + case 'min-width': + case 'max-height': + case 'max-width': + case 'width': + case 'height': + case 'text-shadow-h': + case 'text-shadow-v': + case 'text-shadow-blur': case 'border-radius-c': - case 'border-top-left-radius': case 'border-top-right-radius': case 'border-bottom-left-radius':case 'border-bottom-right-radius': - case 'box-shadow-h': case 'box-shadow-v': - obj.units = ['px','%']; + case 'border-top-left-radius': + case 'border-top-right-radius': + case 'border-bottom-left-radius': + case 'border-bottom-right-radius': + case 'box-shadow-h': + case 'box-shadow-v': + obj.units = ['px', '%']; break; - case 'font-size': case 'letter-spacing': case 'line-height': - obj.units = ['px','em', 'rem', '%']; + case 'font-size': + case 'letter-spacing': + case 'line-height': + obj.units = ['px', 'em', 'rem', '%']; break; case 'border-width': - obj.units = ['px','em']; + obj.units = ['px', 'em']; break; - case 'box-shadow-blur': case 'box-shadow-spread': + case 'box-shadow-blur': + case 'box-shadow-spread': case 'perspective': obj.units = ['px']; break; case 'transition-duration': obj.units = ['s']; break; - case 'transform-rotate-x': case 'transform-rotate-y': case 'transform-rotate-z': + case 'transform-rotate-x': + case 'transform-rotate-y': + case 'transform-rotate-z': obj.units = ['deg']; break; } // Min/Max - switch(prop) { - case 'padding-top': case 'padding-right': case 'padding-bottom': case 'padding-left': - case 'min-height': case 'min-width': case 'max-height': case 'max-width': - case 'width': case 'height': + switch (prop) { + case 'padding-top': + case 'padding-right': + case 'padding-bottom': + case 'padding-left': + case 'min-height': + case 'min-width': + case 'max-height': + case 'max-width': + case 'width': + case 'height': case 'font-size': case 'text-shadow-blur': case 'border-radius-c': - case 'border-top-left-radius': case 'border-top-right-radius': case 'border-bottom-left-radius':case 'border-bottom-right-radius': + case 'border-top-left-radius': + case 'border-top-right-radius': + case 'border-bottom-left-radius': + case 'border-bottom-right-radius': case 'border-width': case 'box-shadow-blur': case 'transition-duration': @@ -226,21 +351,23 @@ module.exports = () => ({ } // Preview - switch(prop){ - case 'text-shadow': case 'box-shadow': case 'background': + switch (prop) { + case 'text-shadow': + case 'box-shadow': + case 'background': obj.preview = true; break; } // Detached - switch(prop){ + switch (prop) { case 'background': obj.detached = true; break; } // Functions - switch(prop){ + switch (prop) { case 'transform-rotate-x': obj.functionName = 'rotateX'; break; @@ -265,28 +392,24 @@ module.exports = () => ({ } // Options - switch(prop){ + switch (prop) { case 'float': - obj.list = [ - {value: 'none'}, - {value: 'left'}, - {value: 'right'}, - ]; + obj.list = [{ value: 'none' }, { value: 'left' }, { value: 'right' }]; break; case 'display': obj.list = [ - {value: 'block'}, - {value: 'inline'}, - {value: 'inline-block'}, - {value: 'none'}, - ]; + { value: 'block' }, + { value: 'inline' }, + { value: 'inline-block' }, + { value: 'none' } + ]; break; case 'position': obj.list = [ - {value: 'static'}, - {value: 'relative'}, - {value: 'absolute'}, - {value: 'fixed'}, + { value: 'static' }, + { value: 'relative' }, + { value: 'absolute' }, + { value: 'fixed' } ]; break; case 'font-family': @@ -307,7 +430,7 @@ module.exports = () => ({ 'Verdana, Geneva' + ss ]; obj.list = []; - for(var j = 0, l = fonts.length; j < l; j++){ + for (var j = 0, l = fonts.length; j < l; j++) { var font = {}; font.value = fonts[j]; font.name = fonts[j].split(',')[0]; @@ -316,154 +439,198 @@ module.exports = () => ({ break; case 'font-weight': obj.list = [ - { value : '100', name : 'Thin', }, - { value : '200', name : 'Extra-Light', }, - { value : '300', name : 'Light', }, - { value : '400', name : 'Normal', }, - { value : '500', name : 'Medium',}, - { value : '600', name : 'Semi-Bold',}, - { value : '700', name : 'Bold', }, - { value : '800', name : 'Extra-Bold',}, - { value : '900', name : 'Ultra-Bold', } + { value: '100', name: 'Thin' }, + { value: '200', name: 'Extra-Light' }, + { value: '300', name: 'Light' }, + { value: '400', name: 'Normal' }, + { value: '500', name: 'Medium' }, + { value: '600', name: 'Semi-Bold' }, + { value: '700', name: 'Bold' }, + { value: '800', name: 'Extra-Bold' }, + { value: '900', name: 'Ultra-Bold' } ]; break; case 'text-align': obj.list = [ - { value : 'left'}, - { value : 'center'}, - { value : 'right'}, - { value : 'justify'} - ]; + { value: 'left' }, + { value: 'center' }, + { value: 'right' }, + { value: 'justify' } + ]; break; case 'border-style': obj.list = [ - { value : 'none'}, - { value : 'solid'}, - { value : 'dotted'}, - { value : 'dashed'}, - { value : 'double'}, - { value : 'groove'}, - { value : 'ridge'}, - { value : 'inset'}, - { value : 'outset'} - ]; + { value: 'none' }, + { value: 'solid' }, + { value: 'dotted' }, + { value: 'dashed' }, + { value: 'double' }, + { value: 'groove' }, + { value: 'ridge' }, + { value: 'inset' }, + { value: 'outset' } + ]; break; case 'box-shadow-type': obj.list = [ - {value : '', name: 'Outside'}, - {value : 'inset', name: 'Inside'} - ]; + { value: '', name: 'Outside' }, + { value: 'inset', name: 'Inside' } + ]; break; case 'background-repeat': obj.list = [ - { value : 'repeat'}, - { value : 'repeat-x'}, - { value : 'repeat-y'}, - { value : 'no-repeat'} - ]; + { value: 'repeat' }, + { value: 'repeat-x' }, + { value: 'repeat-y' }, + { value: 'no-repeat' } + ]; break; case 'background-position': obj.list = [ - { value : 'left top',}, - { value : 'left center',}, - { value : 'left bottom',}, - { value : 'right top',}, - { value : 'right center'}, - { value : 'right bottom'}, - { value : 'center top'}, - { value : 'center center'}, - { value : 'center bottom'} - ]; + { value: 'left top' }, + { value: 'left center' }, + { value: 'left bottom' }, + { value: 'right top' }, + { value: 'right center' }, + { value: 'right bottom' }, + { value: 'center top' }, + { value: 'center center' }, + { value: 'center bottom' } + ]; break; case 'background-attachment': obj.list = [ - { value : 'scroll'}, - { value : 'fixed'}, - { value : 'local'} - ]; + { value: 'scroll' }, + { value: 'fixed' }, + { value: 'local' } + ]; break; case 'background-size': obj.list = [ - { value : 'auto'}, - { value : 'cover'}, - { value : 'contain'} - ]; + { value: 'auto' }, + { value: 'cover' }, + { value: 'contain' } + ]; break; case 'transition-property': obj.list = [ - { value: 'all'}, - { value: 'width'}, - { value : 'height'}, - { value : 'background-color'}, - { value : 'transform'}, - { value : 'box-shadow'}, - { value : 'opacity'} - ]; + { value: 'all' }, + { value: 'width' }, + { value: 'height' }, + { value: 'background-color' }, + { value: 'transform' }, + { value: 'box-shadow' }, + { value: 'opacity' } + ]; break; case 'transition-timing-function': obj.list = [ - { value : 'linear'}, - { value : 'ease'}, - { value : 'ease-in'}, - { value : 'ease-out'}, - { value : 'ease-in-out'} - ]; + { value: 'linear' }, + { value: 'ease' }, + { value: 'ease-in' }, + { value: 'ease-out' }, + { value: 'ease-in-out' } + ]; break; case 'cursor': obj.list = [ - { value : 'auto'}, - { value : 'pointer'}, - { value : 'copy'}, - { value : 'crosshair'}, - { value : 'grab'}, - { value : 'grabbing'}, - { value : 'help'}, - { value : 'move'}, - { value : 'text'} - ]; + { value: 'auto' }, + { value: 'pointer' }, + { value: 'copy' }, + { value: 'crosshair' }, + { value: 'grab' }, + { value: 'grabbing' }, + { value: 'help' }, + { value: 'move' }, + { value: 'text' } + ]; break; case 'overflow': obj.list = [ - { value : 'visible'}, - { value : 'hidden'}, - { value : 'scroll'}, - { value : 'auto'} + { value: 'visible' }, + { value: 'hidden' }, + { value: 'scroll' }, + { value: 'auto' } ]; break; } // Properties - switch(prop){ + switch (prop) { case 'margin': - obj.properties = this.build(['margin-top', 'margin-right', 'margin-bottom', 'margin-left']); + obj.properties = this.build([ + 'margin-top', + 'margin-right', + 'margin-bottom', + 'margin-left' + ]); break; case 'padding': - obj.properties = this.build(['padding-top', 'padding-right', 'padding-bottom', 'padding-left']); + obj.properties = this.build([ + 'padding-top', + 'padding-right', + 'padding-bottom', + 'padding-left' + ]); break; case 'text-shadow': - obj.properties = this.build(['text-shadow-h', 'text-shadow-v', 'text-shadow-blur', 'text-shadow-color']); + obj.properties = this.build([ + 'text-shadow-h', + 'text-shadow-v', + 'text-shadow-blur', + 'text-shadow-color' + ]); break; case 'border': - obj.properties = this.build(['border-width', 'border-style', 'border-color']); + obj.properties = this.build([ + 'border-width', + 'border-style', + 'border-color' + ]); break; case 'border-radius': - obj.properties = this.build(['border-top-left-radius', 'border-top-right-radius', - 'border-bottom-left-radius', 'border-bottom-right-radius']); + obj.properties = this.build([ + 'border-top-left-radius', + 'border-top-right-radius', + 'border-bottom-left-radius', + 'border-bottom-right-radius' + ]); break; case 'box-shadow': - obj.properties = this.build(['box-shadow-h', 'box-shadow-v', 'box-shadow-blur','box-shadow-spread', - 'box-shadow-color', 'box-shadow-type']); + obj.properties = this.build([ + 'box-shadow-h', + 'box-shadow-v', + 'box-shadow-blur', + 'box-shadow-spread', + 'box-shadow-color', + 'box-shadow-type' + ]); break; case 'background': - obj.properties = this.build(['background-image', 'background-repeat', 'background-position','background-attachment', - 'background-size']); + obj.properties = this.build([ + 'background-image', + 'background-repeat', + 'background-position', + 'background-attachment', + 'background-size' + ]); break; case 'transition': - obj.properties = this.build(['transition-property', 'transition-duration', 'transition-timing-function']); + obj.properties = this.build([ + 'transition-property', + 'transition-duration', + 'transition-timing-function' + ]); break; case 'transform': - obj.properties = this.build(['transform-rotate-x', 'transform-rotate-y', 'transform-rotate-z', - 'transform-scale-x', 'transform-scale-y', 'transform-scale-z']); + obj.properties = this.build([ + 'transform-rotate-x', + 'transform-rotate-y', + 'transform-rotate-z', + 'transform-scale-x', + 'transform-scale-y', + 'transform-scale-z' + ]); break; } diff --git a/src/style_manager/model/PropertyInteger.js b/src/style_manager/model/PropertyInteger.js index 27dc4ddb1e..5aea5c69b7 100644 --- a/src/style_manager/model/PropertyInteger.js +++ b/src/style_manager/model/PropertyInteger.js @@ -2,8 +2,8 @@ const Property = require('./Property'); const InputNumber = require('domain_abstract/ui/InputNumber'); module.exports = Property.extend({ - - defaults: { ...Property.prototype.defaults, + defaults: { + ...Property.prototype.defaults, // Array of units, eg. ['px', '%'] units: [], @@ -17,10 +17,9 @@ module.exports = Property.extend({ min: '', // Maximum value - max: '', + max: '' }, - init() { const unit = this.get('unit'); const units = this.get('units'); @@ -31,19 +30,18 @@ module.exports = Property.extend({ } }, - parseValue(val) { const parsed = Property.prototype.parseValue.apply(this, arguments); - const { value, unit } = this.input.validateInputValue(parsed.value, {deepCheck: 1}); + const { value, unit } = this.input.validateInputValue(parsed.value, { + deepCheck: 1 + }); parsed.value = value; parsed.unit = unit; return parsed; }, - getFullValue() { let value = this.get('value') + this.get('unit'); return Property.prototype.getFullValue.apply(this, [value]); - }, - + } }); diff --git a/src/style_manager/model/PropertyRadio.js b/src/style_manager/model/PropertyRadio.js index 7c46315532..959711154d 100644 --- a/src/style_manager/model/PropertyRadio.js +++ b/src/style_manager/model/PropertyRadio.js @@ -1,10 +1,9 @@ const Property = require('./Property'); module.exports = Property.extend({ - - defaults: { ...Property.prototype.defaults, + defaults: { + ...Property.prototype.defaults, // Array of options, eg. [{name: 'Label ', value: '100'}] - options: [], - }, - + options: [] + } }); diff --git a/src/style_manager/model/PropertySlider.js b/src/style_manager/model/PropertySlider.js index 51285c13a9..403141b6ce 100644 --- a/src/style_manager/model/PropertySlider.js +++ b/src/style_manager/model/PropertySlider.js @@ -1,9 +1,8 @@ const Property = require('./PropertyInteger'); module.exports = Property.extend({ - - defaults: { ...Property.prototype.defaults, - showInput: 1, - }, - + defaults: { + ...Property.prototype.defaults, + showInput: 1 + } }); diff --git a/src/style_manager/model/PropertyStack.js b/src/style_manager/model/PropertyStack.js index 86a4c7df80..b0ec21479a 100644 --- a/src/style_manager/model/PropertyStack.js +++ b/src/style_manager/model/PropertyStack.js @@ -2,13 +2,13 @@ const Property = require('./PropertyComposite'); const Layers = require('./Layers'); module.exports = Property.extend({ - - defaults: { ...Property.prototype.defaults, + defaults: { + ...Property.prototype.defaults, // Array of layers (which contain properties) layers: [], // Layer preview - preview: 0, + preview: 0 }, init() { @@ -21,6 +21,5 @@ module.exports = Property.extend({ getFullValue() { return this.get('detached') ? '' : this.get('layers').getFullValue(); - }, - + } }); diff --git a/src/style_manager/model/Sector.js b/src/style_manager/model/Sector.js index 19b6d19504..b61487b132 100644 --- a/src/style_manager/model/Sector.js +++ b/src/style_manager/model/Sector.js @@ -5,14 +5,13 @@ const Properties = require('./Properties'); const PropertyFactory = require('./PropertyFactory'); module.exports = Backbone.Model.extend({ - defaults: { id: '', name: '', open: true, buildProps: '', extendBuilded: 1, - properties : [], + properties: [] }, initialize(opts) { @@ -21,10 +20,8 @@ module.exports = Backbone.Model.extend({ var builded = this.buildProperties(o.buildProps); !this.get('id') && this.set('id', this.get('name')); - if(!builded) - props = this.get('properties'); - else - props = this.extendProperties(builded); + if (!builded) props = this.get('properties'); + else props = this.extendProperties(builded); var propsModel = new Properties(props); propsModel.sector = this; @@ -51,12 +48,15 @@ module.exports = Backbone.Model.extend({ for (var j = 0; j < pLen; j++) { var prop = props[j]; - if (mProp.property == prop.property || - mProp.id == prop.property) { + if (mProp.property == prop.property || mProp.id == prop.property) { // Check for nested properties var mPProps = mProp.properties; if (mPProps && mPProps.length) { - mProp.properties = this.extendProperties(prop.properties, mPProps, 1); + mProp.properties = this.extendProperties( + prop.properties, + mPProps, + 1 + ); } props[j] = ext ? extend(prop, mProp) : mProp; isolated[j] = props[j]; @@ -65,7 +65,7 @@ module.exports = Backbone.Model.extend({ } } - if(!found){ + if (!found) { props.push(mProp); isolated.push(mProp); } @@ -84,15 +84,12 @@ module.exports = Backbone.Model.extend({ var r; var buildP = props || []; - if(!buildP.length) - return; + if (!buildP.length) return; - if(!this.propFactory) - this.propFactory = new PropertyFactory(); + if (!this.propFactory) this.propFactory = new PropertyFactory(); r = this.propFactory.build(buildP); return r; - }, - + } }); diff --git a/src/style_manager/model/Sectors.js b/src/style_manager/model/Sectors.js index f52fdc3cbe..65439242b3 100644 --- a/src/style_manager/model/Sectors.js +++ b/src/style_manager/model/Sectors.js @@ -1,5 +1,5 @@ const Sector = require('./Sector'); module.exports = require('backbone').Collection.extend({ - model: Sector + model: Sector }); diff --git a/src/style_manager/view/LayerView.js b/src/style_manager/view/LayerView.js index 8c780bf790..50810ca5f6 100644 --- a/src/style_manager/view/LayerView.js +++ b/src/style_manager/view/LayerView.js @@ -1,5 +1,4 @@ module.exports = Backbone.View.extend({ - events: { click: 'active', 'click [data-close-layer]': 'remove', @@ -23,7 +22,7 @@ module.exports = Backbone.View.extend({
- ` + `; }, initialize(o = {}) { @@ -44,7 +43,7 @@ module.exports = Backbone.View.extend({ // For the sorter model.view = this; - model.set({droppable: 0, draggable: 1}); + model.set({ droppable: 0, draggable: 1 }); this.$el.data('model', model); }, @@ -53,14 +52,11 @@ module.exports = Backbone.View.extend({ * @param {Event} e * */ initSorter(e) { - if(this.sorter) - this.sorter.startSort(this.el); + if (this.sorter) this.sorter.startSort(this.el); }, - remove(e) { - if(e && e.stopPropagation) - e.stopPropagation(); + if (e && e.stopPropagation) e.stopPropagation(); const model = this.model; const collection = model.collection; @@ -73,7 +69,7 @@ module.exports = Backbone.View.extend({ } if (stackModel && stackModel.set) { - stackModel.set({stackIndex: null}, {silent: true}); + stackModel.set({ stackIndex: null }, { silent: true }); stackModel.trigger('updateValue'); } }, @@ -93,7 +89,7 @@ module.exports = Backbone.View.extend({ if (value) { if (prop.get('type') == 'integer') { let valueInt = parseInt(value, 10); - let unit = value.replace(valueInt,''); + let unit = value.replace(valueInt, ''); valueInt = !isNaN(valueInt) ? valueInt : 0; valueInt = valueInt > lim ? lim : valueInt; valueInt = valueInt < -lim ? -lim : valueInt; @@ -112,7 +108,9 @@ module.exports = Backbone.View.extend({ const customPreview = this.customPreview; const previewEl = this.getPreviewEl(); const value = this.model.getFullValue(); - const preview = customPreview ? customPreview(value) : this.onPreview(value); + const preview = customPreview + ? customPreview(value) + : this.onPreview(value); if (preview && stackModel && previewEl) { previewEl.style[stackModel.get('property')] = preview; @@ -159,7 +157,7 @@ module.exports = Backbone.View.extend({ target: propsConfig.target, customValue: propsConfig.customValue, propTarget: propsConfig.propTarget, - onChange: propsConfig.onChange, + onChange: propsConfig.onChange }).render().el; el.innerHTML = this.template(model); el.className = className; @@ -167,6 +165,5 @@ module.exports = Backbone.View.extend({ this.updateVisibility(); this.updatePreview(); return this; - }, - + } }); diff --git a/src/style_manager/view/LayersView.js b/src/style_manager/view/LayersView.js index 8289645a5c..94fd1727f8 100644 --- a/src/style_manager/view/LayersView.js +++ b/src/style_manager/view/LayersView.js @@ -2,10 +2,9 @@ var Backbone = require('backbone'); var LayerView = require('./LayerView'); module.exports = Backbone.View.extend({ - initialize(o) { this.config = o.config || {}; - this.stackModel = o.stackModel; + this.stackModel = o.stackModel; this.preview = o.preview; this.pfx = this.config.stylePrefix || ''; this.ppfx = this.config.pStylePrefix || ''; @@ -15,19 +14,21 @@ module.exports = Backbone.View.extend({ let collection = this.collection; this.className = `${pfx}layers ${ppfx}field`; this.listenTo(collection, 'add', this.addTo); - this.listenTo(collection, 'deselectAll', this.deselectAll ); + this.listenTo(collection, 'deselectAll', this.deselectAll); this.listenTo(collection, 'reset', this.render); var em = this.config.em || ''; var utils = em ? em.get('Utils') : ''; - this.sorter = utils ? new utils.Sorter({ - container: this.el, - ignoreViewChildren: 1, - containerSel: `.${pfx}layers`, - itemSel: `.${pfx}layer`, - pfx: this.config.pStylePrefix, - }) : ''; + this.sorter = utils + ? new utils.Sorter({ + container: this.el, + ignoreViewChildren: 1, + containerSel: `.${pfx}layers`, + itemSel: `.${pfx}layer`, + pfx: this.config.pStylePrefix + }) + : ''; // For the Sorter collection.view = this; @@ -42,7 +43,7 @@ module.exports = Backbone.View.extend({ * @return Object * */ addTo(model) { - var i = this.collection.indexOf(model); + var i = this.collection.indexOf(model); this.addToCollection(model, null, i); }, @@ -61,37 +62,39 @@ module.exports = Backbone.View.extend({ const sorter = this.sorter; const propsConfig = this.propsConfig; - if(typeof this.preview !== 'undefined'){ + if (typeof this.preview !== 'undefined') { model.set('preview', this.preview); } var view = new LayerView({ - model, - config, - sorter, - stackModel, - propsConfig + model, + config, + sorter, + stackModel, + propsConfig }); var rendered = view.render().el; if (fragment) { fragment.appendChild(rendered); } else { - if(typeof index != 'undefined'){ - var method = 'before'; + if (typeof index != 'undefined') { + var method = 'before'; // If the added model is the last of collection // need to change the logic of append - if(this.$el.children().length == index){ + if (this.$el.children().length == index) { index--; method = 'after'; } // In case the added is new in the collection index will be -1 - if(index < 0){ + if (index < 0) { this.$el.append(rendered); - }else - this.$el.children().eq(index)[method](rendered); - }else - this.$el.append(rendered); + } else + this.$el + .children() + .eq(index) + [method](rendered); + } else this.$el.append(rendered); } return rendered; @@ -103,22 +106,21 @@ module.exports = Backbone.View.extend({ * @return void * */ deselectAll() { - this.$el.find('.'+ this.pfx +'layer').removeClass(this.pfx + 'active'); + this.$el.find('.' + this.pfx + 'layer').removeClass(this.pfx + 'active'); }, render() { var fragment = document.createDocumentFragment(); this.$el.empty(); - this.collection.each(function(model){ + this.collection.each(function(model) { this.addToCollection(model, fragment); - },this); + }, this); this.$el.append(fragment); this.$el.attr('class', this.className); - if(this.sorter) - this.sorter.plh = null; + if (this.sorter) this.sorter.plh = null; return this; } diff --git a/src/style_manager/view/PropertiesView.js b/src/style_manager/view/PropertiesView.js index 1cbbd1417b..07e2fb2dd5 100644 --- a/src/style_manager/view/PropertiesView.js +++ b/src/style_manager/view/PropertiesView.js @@ -8,7 +8,6 @@ const PropertyCompositeView = require('./PropertyCompositeView'); const PropertyStackView = require('./PropertyStackView'); module.exports = Backbone.View.extend({ - initialize(o) { this.config = o.config || {}; this.pfx = this.config.stylePrefix || ''; @@ -22,12 +21,10 @@ module.exports = Backbone.View.extend({ this.listenTo(coll, 'reset', this.render); }, - addTo(model) { this.add(model); }, - add(model, frag) { var view = new model.typeView({ model, @@ -37,7 +34,7 @@ module.exports = Backbone.View.extend({ propTarget: this.propTarget, onChange: this.onChange, onInputRender: this.onInputRender, - config: this.config, + config: this.config }); if (model.get('type') != 'composite') { @@ -54,7 +51,6 @@ module.exports = Backbone.View.extend({ } }, - render() { const fragment = document.createDocumentFragment(); this.collection.each(model => this.add(model, fragment)); diff --git a/src/style_manager/view/PropertyColorView.js b/src/style_manager/view/PropertyColorView.js index 6e8a870a5a..48c8518e00 100644 --- a/src/style_manager/view/PropertyColorView.js +++ b/src/style_manager/view/PropertyColorView.js @@ -1,7 +1,6 @@ const InputColor = require('domain_abstract/ui/InputColor'); module.exports = require('./PropertyIntegerView').extend({ - setValue(value, opts = {}) { opts = { ...opts, silent: 1 }; this.inputInst.setValue(value, opts); @@ -22,6 +21,5 @@ module.exports = require('./PropertyIntegerView').extend({ this.input = this.$input.get(0); this.inputInst = input; } - }, - + } }); diff --git a/src/style_manager/view/PropertyCompositeView.js b/src/style_manager/view/PropertyCompositeView.js index 618a1e9df7..7d8fa6e085 100644 --- a/src/style_manager/view/PropertyCompositeView.js +++ b/src/style_manager/view/PropertyCompositeView.js @@ -2,7 +2,6 @@ const PropertyView = require('./PropertyView'); const $ = Backbone.$; module.exports = PropertyView.extend({ - templateInput() { const pfx = this.pfx; return ` @@ -41,7 +40,7 @@ module.exports = PropertyView.extend({ if (!this.$props) { //Not yet supported nested composite this.props.each(function(prop, index) { - if(prop && prop.get('type') == 'composite') { + if (prop && prop.get('type') == 'composite') { this.props.remove(prop); console.warn('Nested composite types not yet allowed.'); } @@ -78,7 +77,7 @@ module.exports = PropertyView.extend({ // I need to extract from that string the corresponding one to that property. customValue(property, mIndex) { return that.valueOnIndex(mIndex, property); - }, + } }; // If detached let follow its standard flow @@ -97,7 +96,7 @@ module.exports = PropertyView.extend({ * */ valueOnIndex(index, view) { let value; - const targetValue = this.getTargetValue({ignoreDefault: 1}); + const targetValue = this.getTargetValue({ ignoreDefault: 1 }); // If the target value of the composite is not empty I'll fetch // the corresponding value from the requested index, otherwise try @@ -106,7 +105,8 @@ module.exports = PropertyView.extend({ const values = targetValue.split(' '); value = values[index]; } else { - value = view && view.getTargetValue({ignoreCustomValue: 1, ignoreDefault: 1}); + value = + view && view.getTargetValue({ ignoreCustomValue: 1, ignoreDefault: 1 }); } if (view) { @@ -114,6 +114,5 @@ module.exports = PropertyView.extend({ } return value; - }, - + } }); diff --git a/src/style_manager/view/PropertyFileView.js b/src/style_manager/view/PropertyFileView.js index 4d5a9c87ff..8114adb85f 100644 --- a/src/style_manager/view/PropertyFileView.js +++ b/src/style_manager/view/PropertyFileView.js @@ -2,7 +2,6 @@ const PropertyView = require('./PropertyView'); const $ = Backbone.$; module.exports = PropertyView.extend({ - templateInput() { const pfx = this.pfx; const ppfx = this.ppfx; @@ -29,8 +28,8 @@ module.exports = PropertyView.extend({ const em = this.em; this.modal = em.get('Modal'); this.am = em.get('AssetManager'); - this.events['click #'+this.pfx+'close'] = 'removeFile'; - this.events['click #'+this.pfx+'images'] = 'openAssetManager'; + this.events['click #' + this.pfx + 'close'] = 'removeFile'; + this.events['click #' + this.pfx + 'images'] = 'openAssetManager'; this.delegateEvents(); }, @@ -92,7 +91,7 @@ module.exports = PropertyView.extend({ /** @inheritdoc */ cleanValue() { this.setPreviewView(0); - this.model.set({value: ''},{silent: true}); + this.model.set({ value: '' }, { silent: true }); }, /** @@ -113,11 +112,11 @@ module.exports = PropertyView.extend({ * @return void * */ openAssetManager(e) { - var that = this; + var that = this; var em = this.em; var editor = em ? em.get('Editor') : ''; - if(editor) { + if (editor) { this.modal.setTitle('Select image'); this.modal.setContent(this.am.getContainer()); this.am.setTarget(null); @@ -129,5 +128,5 @@ module.exports = PropertyView.extend({ } }); } - }, + } }); diff --git a/src/style_manager/view/PropertyIntegerView.js b/src/style_manager/view/PropertyIntegerView.js index 4a8c301155..91609c4589 100644 --- a/src/style_manager/view/PropertyIntegerView.js +++ b/src/style_manager/view/PropertyIntegerView.js @@ -2,7 +2,6 @@ const InputNumber = require('domain_abstract/ui/InputNumber'); const $ = Backbone.$; module.exports = require('./PropertyView').extend({ - templateInput() { return ''; }, @@ -14,7 +13,7 @@ module.exports = require('./PropertyView').extend({ }, setValue(value) { - this.inputInst.setValue(value, {silent: 1}); + this.inputInst.setValue(value, { silent: 1 }); }, onRender() { @@ -32,6 +31,5 @@ module.exports = require('./PropertyView').extend({ this.input = this.$input.get(0); this.inputInst = input; } - }, - + } }); diff --git a/src/style_manager/view/PropertyRadioView.js b/src/style_manager/view/PropertyRadioView.js index 4ed37e7c65..cf99fc789b 100644 --- a/src/style_manager/view/PropertyRadioView.js +++ b/src/style_manager/view/PropertyRadioView.js @@ -1,5 +1,4 @@ module.exports = require('./PropertyView').extend({ - templateInput() { const pfx = this.pfx; const ppfx = this.ppfx; @@ -18,18 +17,22 @@ module.exports = require('./PropertyView').extend({ const options = model.get('list') || model.get('options') || []; if (!this.input) { - if(options && options.length) { + if (options && options.length) { let inputStr = ''; options.forEach(el => { - let cl = el.className ? `${el.className} ${pfx}icon ${itemCls}` : ''; + let cl = el.className ? `${el.className} ${pfx}icon ${itemCls}` : ''; let id = `${prop}-${el.value}`; let labelTxt = el.name || el.value; let titleAttr = el.title ? `title="${el.title}"` : ''; inputStr += `
- - + +
`; }); @@ -63,6 +66,5 @@ module.exports = require('./PropertyView').extend({ const inputChk = this.getCheckedEl(); inputChk && (inputChk.checked = false); } - }, - + } }); diff --git a/src/style_manager/view/PropertySelectView.js b/src/style_manager/view/PropertySelectView.js index 61ff92d96e..f235e081bd 100644 --- a/src/style_manager/view/PropertySelectView.js +++ b/src/style_manager/view/PropertySelectView.js @@ -1,7 +1,6 @@ const $ = Backbone.$; module.exports = require('./PropertyView').extend({ - templateInput() { const pfx = this.pfx; const ppfx = this.ppfx; @@ -16,7 +15,7 @@ module.exports = require('./PropertyView').extend({ }, onRender() { - var pfx = this.pfx; + var pfx = this.pfx; const model = this.model; const options = model.get('list') || model.get('options') || []; @@ -25,9 +24,9 @@ module.exports = require('./PropertyView').extend({ options.forEach(option => { let name = option.name || option.value; - let style = option.style ? option.style.replace(/"/g,'"') : ''; + let style = option.style ? option.style.replace(/"/g, '"') : ''; let styleAttr = style ? `style="${style}"` : ''; - let value = option.value.replace(/"/g,'"'); + let value = option.value.replace(/"/g, '"'); optionsStr += ``; }); @@ -35,6 +34,5 @@ module.exports = require('./PropertyView').extend({ inputH.innerHTML = ``; this.input = inputH.firstChild; } - }, - + } }); diff --git a/src/style_manager/view/PropertySliderView.js b/src/style_manager/view/PropertySliderView.js index 4de4bac50e..f6e1b362da 100644 --- a/src/style_manager/view/PropertySliderView.js +++ b/src/style_manager/view/PropertySliderView.js @@ -1,13 +1,11 @@ const Property = require('./PropertyIntegerView'); module.exports = Property.extend({ - events: { 'change [type=range]': 'inputValueChanged', - 'input [type=range]': 'inputValueChangedSoft', + 'input [type=range]': 'inputValueChangedSoft' }, - templateInput(model) { const ppfx = this.ppfx; return ` @@ -20,7 +18,6 @@ module.exports = Property.extend({ `; }, - getSliderEl() { if (!this.slider) { this.slider = this.el.querySelector('input[type=range]'); @@ -29,30 +26,26 @@ module.exports = Property.extend({ return this.slider; }, - inputValueChanged() { const model = this.model; const step = model.get('step'); this.getInputEl().value = this.getSliderEl().value; const value = this.getInputValue() - step; - model.set('value', value, {avoidStore: 1}).set('value', value + step); + model.set('value', value, { avoidStore: 1 }).set('value', value + step); this.elementUpdated(); }, - inputValueChangedSoft() { this.getInputEl().value = this.getSliderEl().value; - this.model.set('value', this.getInputValue(), {avoidStore: 1}); + this.model.set('value', this.getInputValue(), { avoidStore: 1 }); this.elementUpdated(); }, - setValue(value) { this.getSliderEl().value = value; - this.inputInst.setValue(value, {silent: 1}); + this.inputInst.setValue(value, { silent: 1 }); }, - onRender() { Property.prototype.onRender.apply(this, arguments); diff --git a/src/style_manager/view/PropertyStackView.js b/src/style_manager/view/PropertyStackView.js index 5a20e06629..b97780f12d 100644 --- a/src/style_manager/view/PropertyStackView.js +++ b/src/style_manager/view/PropertyStackView.js @@ -2,7 +2,6 @@ const PropertyCompositeView = require('./PropertyCompositeView'); const LayersView = require('./LayersView'); module.exports = PropertyCompositeView.extend({ - templateInput() { const pfx = this.pfx; const ppfx = this.ppfx; @@ -65,7 +64,7 @@ module.exports = PropertyCompositeView.extend({ const layers = this.getLayers(); const properties = model.get('properties').deepClone(); properties.each(property => property.set('value', '')); - const layer = layers.add({properties}); + const layer = layers.add({ properties }); // In detached mode inputValueChanged will add new 'layer value' // to all subprops @@ -75,7 +74,6 @@ module.exports = PropertyCompositeView.extend({ model.set('stackIndex', layers.indexOf(layer)); }, - inputValueChanged() { const model = this.model; this.elementUpdated(); @@ -85,7 +83,7 @@ module.exports = PropertyCompositeView.extend({ if (!model.get('detached')) { model.set('value', this.getLayerValues()); } else { - model.get('properties').each(prop => prop.trigger('change:value')) + model.get('properties').each(prop => prop.trigger('change:value')); } }, @@ -126,7 +124,7 @@ module.exports = PropertyCompositeView.extend({ layers.reset(); layers.add(layersObj); - model.set({stackIndex: null}, {silent: true}); + model.set({ stackIndex: null }, { silent: true }); }, onRender() { @@ -149,14 +147,14 @@ module.exports = PropertyCompositeView.extend({ } else { model.set('value', model.getFullValue(), opt); } - }, + } }; const layers = new LayersView({ collection: this.getLayers(), stackModel: model, preview: model.get('preview'), config: this.config, - propsConfig, + propsConfig }).render().el; // Will use it to propogate changes @@ -167,11 +165,10 @@ module.exports = PropertyCompositeView.extend({ config: this.config, onChange: propsConfig.onChange, propTarget: propsConfig.propTarget, - customValue: propsConfig.customValue, + customValue: propsConfig.customValue }).render(); //model.get('properties') fieldEl.appendChild(layers); - }, - + } }); diff --git a/src/style_manager/view/PropertyView.js b/src/style_manager/view/PropertyView.js index 5f01672a8d..bc601ea158 100644 --- a/src/style_manager/view/PropertyView.js +++ b/src/style_manager/view/PropertyView.js @@ -4,7 +4,6 @@ import { camelCase } from 'utils/mixins'; const clearProp = 'data-clear-style'; module.exports = Backbone.View.extend({ - template(model) { const pfx = this.pfx; return ` @@ -38,8 +37,8 @@ module.exports = Backbone.View.extend({ }, events: { - 'change': 'inputValueChanged', - [`click [${clearProp}]`]: 'clear', + change: 'inputValueChanged', + [`click [${clearProp}]`]: 'clear' }, initialize(o = {}) { @@ -52,8 +51,8 @@ module.exports = Backbone.View.extend({ this.target = o.target || {}; this.propTarget = o.propTarget || {}; this.onChange = o.onChange; - this.onInputRender = o.onInputRender || {}; - this.customValue = o.customValue || {}; + this.onInputRender = o.onInputRender || {}; + this.customValue = o.customValue || {}; const model = this.model; this.property = model.get('property'); this.input = null; @@ -160,7 +159,6 @@ module.exports = Backbone.View.extend({ this.elementUpdated(); }, - /** * Fired when the element of the property is updated */ @@ -168,14 +166,12 @@ module.exports = Backbone.View.extend({ this.setStatus('updated'); }, - setStatus(value) { this.model.set('status', value); const parent = this.model.parent; parent && parent.set('status', value); }, - /** * Fired when the target is changed * */ @@ -189,7 +185,7 @@ module.exports = Backbone.View.extend({ const model = this.model; let value = ''; let status = ''; - let targetValue = this.getTargetValue({ignoreDefault: 1}); + let targetValue = this.getTargetValue({ ignoreDefault: 1 }); let defaultValue = model.getDefaultValue(); let computedValue = this.getComputedValue(); @@ -199,8 +195,11 @@ module.exports = Backbone.View.extend({ if (config.highlightChanged) { status = 'updated'; } - } else if (computedValue && config.showComputed && - computedValue != defaultValue) { + } else if ( + computedValue && + config.showComputed && + computedValue != defaultValue + ) { value = computedValue; if (config.highlightComputed) { @@ -432,7 +431,6 @@ module.exports = Backbone.View.extend({ this.setValue(this.model.parseValue(value)); }, - /** * Update the element input. * Usually the value is a result of `model.getFullValue()` @@ -445,7 +443,6 @@ module.exports = Backbone.View.extend({ input && (input.value = val); }, - getInputEl() { if (!this.input) { this.input = this.el.querySelector('input'); @@ -455,8 +452,7 @@ module.exports = Backbone.View.extend({ }, updateVisibility() { - this.el.style.display = this.model.get('visible') ? - 'block' : 'none'; + this.el.style.display = this.model.get('visible') ? 'block' : 'none'; }, show() { @@ -484,7 +480,6 @@ module.exports = Backbone.View.extend({ const onRender = this.onRender && this.onRender.bind(this); onRender && onRender(); - this.setValue(model.get('value'), {targetUpdate: 1}); - }, - + this.setValue(model.get('value'), { targetUpdate: 1 }); + } }); diff --git a/src/style_manager/view/SectorView.js b/src/style_manager/view/SectorView.js index 336866a0ef..807083f194 100644 --- a/src/style_manager/view/SectorView.js +++ b/src/style_manager/view/SectorView.js @@ -2,14 +2,13 @@ var Backbone = require('backbone'); var PropertiesView = require('./PropertiesView'); module.exports = Backbone.View.extend({ - template: _.template(`
<%= label %>
`), - events:{ + events: { 'click [data-sector-title]': 'toggle' }, @@ -43,17 +42,15 @@ module.exports = Backbone.View.extend({ * Update visibility */ updateOpen() { - if(this.model.get('open')) - this.show(); - else - this.hide(); + if (this.model.get('open')) this.show(); + else this.hide(); }, /** * Show the content of the sector * */ show() { - this.$el.addClass(this.pfx + "open"); + this.$el.addClass(this.pfx + 'open'); this.getPropertiesEl().style.display = ''; this.$caret.removeClass(this.caretR).addClass(this.caretD); }, @@ -62,7 +59,7 @@ module.exports = Backbone.View.extend({ * Hide the content of the sector * */ hide() { - this.$el.removeClass(this.pfx + "open"); + this.$el.removeClass(this.pfx + 'open'); this.getPropertiesEl().style.display = 'none'; this.$caret.removeClass(this.caretD).addClass(this.caretR); }, @@ -80,11 +77,13 @@ module.exports = Backbone.View.extend({ }, render() { - this.$el.html(this.template({ - pfx: this.pfx, - label: this.model.get('name'), - })); - this.$caret = this.$el.find('#' + this.pfx + 'caret'); + this.$el.html( + this.template({ + pfx: this.pfx, + label: this.model.get('name') + }) + ); + this.$caret = this.$el.find('#' + this.pfx + 'caret'); this.renderProperties(); this.$el.attr('class', this.pfx + 'sector no-select'); this.updateOpen(); @@ -94,14 +93,14 @@ module.exports = Backbone.View.extend({ renderProperties() { var objs = this.model.get('properties'); - if(objs){ + if (objs) { var view = new PropertiesView({ collection: objs, target: this.target, propTarget: this.propTarget, - config: this.config, + config: this.config }); this.$el.append(view.render().el); } - }, + } }); diff --git a/src/style_manager/view/SectorsView.js b/src/style_manager/view/SectorsView.js index 339c9bde65..ce8c4c8d84 100644 --- a/src/style_manager/view/SectorsView.js +++ b/src/style_manager/view/SectorsView.js @@ -3,7 +3,6 @@ import { extend } from 'underscore'; const SectorView = require('./SectorView'); module.exports = Backbone.View.extend({ - initialize(o) { this.config = o.config || {}; this.pfx = this.config.stylePrefix || ''; @@ -19,11 +18,11 @@ module.exports = Backbone.View.extend({ body.removeChild(dummy); this.propTarget = target; const coll = this.collection; - const events = 'change:selectedComponent component:update:classes change:device'; + const events = + 'change:selectedComponent component:update:classes change:device'; this.listenTo(coll, 'add', this.addTo); this.listenTo(coll, 'reset', this.render); this.listenTo(this.target, events, this.targetUpdated); - }, /** @@ -63,7 +62,10 @@ module.exports = Backbone.View.extend({ pt.helper = null; if (view) { - pt.computed = window.getComputedStyle(view.el, state ? `:${state}` : null); + pt.computed = window.getComputedStyle( + view.el, + state ? `:${state}` : null + ); } const appendStateRule = (style = {}) => { @@ -137,7 +139,6 @@ module.exports = Backbone.View.extend({ pt.trigger('update'); }, - /** * Add new object to collection * @param {Object} model Model @@ -149,18 +150,23 @@ module.exports = Backbone.View.extend({ var fragment = fragmentEl || null; var view = new SectorView({ model, - id: this.pfx + model.get('name').replace(' ','_').toLowerCase(), + id: + this.pfx + + model + .get('name') + .replace(' ', '_') + .toLowerCase(), name: model.get('name'), properties: model.get('properties'), target: this.target, propTarget: this.propTarget, - config: this.config, + config: this.config }); var rendered = view.render().el; - if(fragment){ + if (fragment) { fragment.appendChild(rendered); - }else{ + } else { this.$el.append(rendered); } @@ -171,7 +177,7 @@ module.exports = Backbone.View.extend({ var fragment = document.createDocumentFragment(); this.$el.empty(); - this.collection.each(function(model){ + this.collection.each(function(model) { this.addToCollection(model, fragment); }, this); diff --git a/src/trait_manager/config/config.js b/src/trait_manager/config/config.js index 0d45e5e9bb..65cfd48e59 100644 --- a/src/trait_manager/config/config.js +++ b/src/trait_manager/config/config.js @@ -1,5 +1,4 @@ module.exports = { - stylePrefix: 'trt-', labelContainer: 'Component settings', @@ -15,5 +14,4 @@ module.exports = { { value: '', name: 'This window' }, { value: '_blank', name: 'New window' } ] - }; diff --git a/src/trait_manager/index.js b/src/trait_manager/index.js index 3f3350ff86..6dbc65f3fb 100644 --- a/src/trait_manager/index.js +++ b/src/trait_manager/index.js @@ -7,14 +7,13 @@ module.exports = () => { let TraitsViewer; return { - TraitsView, /** * Name of the module * @type {String} * @private - */ + */ name: 'TraitManager', /** @@ -38,7 +37,7 @@ module.exports = () => { TraitsViewer = new TraitsView({ collection: [], editor: c.em, - config: c, + config: c }); return this; }, @@ -69,7 +68,6 @@ module.exports = () => { */ getType(name) { return TraitsViewer.itemsView[name]; - }, - + } }; }; diff --git a/src/trait_manager/model/Trait.js b/src/trait_manager/model/Trait.js index 7b1c6501fc..fc8fe54f42 100644 --- a/src/trait_manager/model/Trait.js +++ b/src/trait_manager/model/Trait.js @@ -1,7 +1,6 @@ import { isUndefined } from 'underscore'; module.exports = require('backbone').Model.extend({ - defaults: { type: 'text', // text, number, range, select label: '', @@ -15,10 +14,9 @@ module.exports = require('backbone').Model.extend({ default: '', placeholder: '', changeProp: 0, - options: [], + options: [] }, - initialize() { const target = this.get('target'); const name = this.get('name'); @@ -27,18 +25,18 @@ module.exports = require('backbone').Model.extend({ if (target) { this.target = target; this.unset('target'); - const targetEvent = changeProp ? `change:${name}` : `change:attributes:${name}`; + const targetEvent = changeProp + ? `change:${name}` + : `change:attributes:${name}`; this.listenTo(target, targetEvent, this.targetUpdated); } }, - targetUpdated() { const value = this.getTargetValue(); !isUndefined(value) && this.set({ value }, { fromTarget: 1 }); }, - getTargetValue() { const name = this.get('name'); const target = this.target; @@ -46,7 +44,6 @@ module.exports = require('backbone').Model.extend({ if (target) return prop ? target.get(name) : target.getAttributes()[name]; }, - setTargetValue(value) { const target = this.target; const name = this.get('name'); @@ -61,7 +58,6 @@ module.exports = require('backbone').Model.extend({ } }, - /** * Get the initial value of the trait * @return {string} @@ -78,5 +74,4 @@ module.exports = require('backbone').Model.extend({ return value || this.get('value') || this.get('default'); } - }); diff --git a/src/trait_manager/model/TraitFactory.js b/src/trait_manager/model/TraitFactory.js index 1c3355d7a1..5f47b7ab8d 100644 --- a/src/trait_manager/model/TraitFactory.js +++ b/src/trait_manager/model/TraitFactory.js @@ -7,8 +7,7 @@ module.exports = (config = {}) => ({ build(props) { var objs = []; - if(typeof props === 'string') - props = [props]; + if (typeof props === 'string') props = [props]; for (var i = 0; i < props.length; i++) { var obj = {}; @@ -24,7 +23,9 @@ module.exports = (config = {}) => ({ // Define placeholder switch (prop) { - case 'title': case 'alt': case 'id': + case 'title': + case 'alt': + case 'id': obj.placeholder = config.labelPlhText; break; case 'href': @@ -32,7 +33,6 @@ module.exports = (config = {}) => ({ break; } - // Define options switch (prop) { case 'target': diff --git a/src/trait_manager/model/Traits.js b/src/trait_manager/model/Traits.js index bf9d9ba038..55a57aa64c 100644 --- a/src/trait_manager/model/Traits.js +++ b/src/trait_manager/model/Traits.js @@ -4,7 +4,6 @@ const Trait = require('./Trait'); const TraitFactory = require('./TraitFactory'); module.exports = Backbone.Collection.extend({ - model: Trait, initialize(coll, options = {}) { @@ -25,7 +24,7 @@ module.exports = Backbone.Collection.extend({ const tf = TraitFactory(tmOpts); if (isString(models)) { - models = [models]; + models = [models]; } for (var i = 0, len = models.length; i < len; i++) { diff --git a/src/trait_manager/view/TraitCheckboxView.js b/src/trait_manager/view/TraitCheckboxView.js index c36bf1d23e..79a3bbe0f9 100644 --- a/src/trait_manager/view/TraitCheckboxView.js +++ b/src/trait_manager/view/TraitCheckboxView.js @@ -1,11 +1,17 @@ var TraitView = require('./TraitView'); module.exports = TraitView.extend({ - initialize(o) { TraitView.prototype.initialize.apply(this, arguments); var iconCls = this.ppfx + 'chk-icon'; - this.tmpl = '
'; + this.tmpl = + '
'; }, /** @@ -23,14 +29,13 @@ module.exports = TraitView.extend({ */ getInputEl(...args) { var first; - if(!this.$input) - first = 1; + if (!this.$input) first = 1; var el = TraitView.prototype.getInputEl.apply(this, args); - if(first){ + if (first) { var md = this.model; var name = md.get('name'); var target = this.target; - if(md.get('changeProp')){ + if (md.get('changeProp')) { el.checked = target.get(name); } else { var attrs = target.get('attributes'); @@ -38,6 +43,5 @@ module.exports = TraitView.extend({ } } return el; - }, - + } }); diff --git a/src/trait_manager/view/TraitColorView.js b/src/trait_manager/view/TraitColorView.js index 621ae3dcd1..d6682bcd17 100644 --- a/src/trait_manager/view/TraitColorView.js +++ b/src/trait_manager/view/TraitColorView.js @@ -29,10 +29,9 @@ module.exports = TraitView.extend({ * @private * */ renderField() { - if(!this.$input){ + if (!this.$input) { this.getInputEl(); this.$el.append(this.input.el); } - }, - + } }); diff --git a/src/trait_manager/view/TraitNumberView.js b/src/trait_manager/view/TraitNumberView.js index 3c66519f84..083872af54 100644 --- a/src/trait_manager/view/TraitNumberView.js +++ b/src/trait_manager/view/TraitNumberView.js @@ -2,12 +2,11 @@ var TraitView = require('./TraitView'); var InputNumber = require('domain_abstract/ui/InputNumber'); module.exports = TraitView.extend({ - getValueForTarget() { var model = this.model; var value = model.get('value'); var unit = model.get('unit'); - return value ? (value + unit) : ''; + return value ? value + unit : ''; }, /** @@ -37,11 +36,10 @@ module.exports = TraitView.extend({ * @private * */ renderField() { - if(!this.$input){ + if (!this.$input) { this.$el.append(this.tmpl); this.getInputEl(); this.$el.find('.' + this.inputhClass).prepend(this.input.el); } - }, - + } }); diff --git a/src/trait_manager/view/TraitSelectView.js b/src/trait_manager/view/TraitSelectView.js index 494f8238c9..ca51ecdecc 100644 --- a/src/trait_manager/view/TraitSelectView.js +++ b/src/trait_manager/view/TraitSelectView.js @@ -2,12 +2,20 @@ const TraitView = require('./TraitView'); const $ = Backbone.$; module.exports = TraitView.extend({ - initialize(o) { TraitView.prototype.initialize.apply(this, arguments); var ppfx = this.ppfx; - this.tmpl = '
'+ - '
'; + this.tmpl = + '
' + + '
'; }, /** @@ -16,7 +24,7 @@ module.exports = TraitView.extend({ * @private */ getInputEl() { - if(!this.$input) { + if (!this.$input) { var md = this.model; var opts = md.get('options') || []; var input = '`); if (value) { @@ -142,7 +147,7 @@ module.exports = Backbone.View.extend({ * @private * */ renderField() { - if(!this.$input){ + if (!this.$input) { this.$el.append(this.tmpl); const el = this.getInputEl(); // I use prepand expecially for checkbox traits @@ -156,6 +161,5 @@ module.exports = Backbone.View.extend({ this.renderField(); this.el.className = this.className; return this; - }, - + } }); diff --git a/src/trait_manager/view/TraitsView.js b/src/trait_manager/view/TraitsView.js index 1142b92322..c11a1a7bad 100644 --- a/src/trait_manager/view/TraitsView.js +++ b/src/trait_manager/view/TraitsView.js @@ -6,15 +6,14 @@ var TraitNumberView = require('./TraitNumberView'); var TraitColorView = require('./TraitColorView'); module.exports = DomainViews.extend({ - itemView: TraitView, itemsView: { - 'text': TraitView, - 'number': TraitNumberView, - 'select': TraitSelectView, - 'checkbox': TraitCheckboxView, - 'color': TraitColorView, + text: TraitView, + number: TraitNumberView, + select: TraitSelectView, + checkbox: TraitCheckboxView, + color: TraitColorView }, initialize(o) { @@ -33,10 +32,9 @@ module.exports = DomainViews.extend({ updatedCollection() { this.el.className = this.className; var comp = this.em.get('selectedComponent'); - if(comp){ + if (comp) { this.collection = comp.get('traits'); this.render(); } - }, - + } }); diff --git a/src/undo_manager/index.js b/src/undo_manager/index.js index 786fd4af64..ae38cb9194 100644 --- a/src/undo_manager/index.js +++ b/src/undo_manager/index.js @@ -17,10 +17,8 @@ module.exports = () => { const configDef = {}; return { - name: 'UndoManager', - /** * Initialize module * @param {Object} config Configurations @@ -60,13 +58,14 @@ module.exports = () => { const events = ['style', 'attributes', 'content', 'src']; events.forEach(ev => um.addUndoType(`change:${ev}`, customUndoType)); - um.on('undo redo', () => em.trigger('change:selectedComponent change:canvasOffset')); + um.on('undo redo', () => + em.trigger('change:selectedComponent change:canvasOffset') + ); ['undo', 'redo'].forEach(ev => um.on(ev, () => em.trigger(ev))); return this; }, - /** * Get module configurations * @return {Object} Configuration object @@ -78,7 +77,6 @@ module.exports = () => { return config; }, - /** * Add an entity (Model/Collection) to track * Note: New Components and CSSRules will be added automatically @@ -92,7 +90,6 @@ module.exports = () => { return this; }, - /** * Remove and stop tracking the entity (Model/Collection) * @param {Model|Collection} entity Entity to remove @@ -105,7 +102,6 @@ module.exports = () => { return this; }, - /** * Remove all entities * @return {this} @@ -117,7 +113,6 @@ module.exports = () => { return this; }, - /** * Start/resume tracking changes * @return {this} @@ -129,7 +124,6 @@ module.exports = () => { return this; }, - /** * Stop tracking changes * @return {this} @@ -141,7 +135,6 @@ module.exports = () => { return this; }, - /** * Undo last change * @return {this} @@ -153,7 +146,6 @@ module.exports = () => { return this; }, - /** * Undo all changes * @return {this} @@ -165,7 +157,6 @@ module.exports = () => { return this; }, - /** * Redo last change * @return {this} @@ -177,7 +168,6 @@ module.exports = () => { return this; }, - /** * Redo all changes * @return {this} @@ -189,7 +179,6 @@ module.exports = () => { return this; }, - /** * Checks if exists an available undo * @return {Boolean} @@ -200,7 +189,6 @@ module.exports = () => { return um.isAvailable('undo'); }, - /** * Checks if exists an available redo * @return {Boolean} @@ -211,7 +199,6 @@ module.exports = () => { return um.isAvailable('redo'); }, - /** * Get stack of changes * @return {Collection} @@ -234,7 +221,6 @@ module.exports = () => { return this; }, - getInstance() { return um; } diff --git a/src/utils/ColorPicker.js b/src/utils/ColorPicker.js index 2018513c73..d3eacce10d 100644 --- a/src/utils/ColorPicker.js +++ b/src/utils/ColorPicker.js @@ -5,2317 +5,2530 @@ // Author: Brian Grinstead // License: MIT -(function (factory) { - factory(Backbone.$) +(function(factory) { + factory(Backbone.$); })(function($, undefined) { - "use strict"; - - var defaultOpts = { - - // Callbacks - beforeShow: noop, - move: noop, - change: noop, - show: noop, - hide: noop, - - // Options - color: false, - flat: false, - showInput: false, - allowEmpty: false, - showButtons: true, - clickoutFiresChange: true, - showInitial: false, - showPalette: false, - showPaletteOnly: false, - hideAfterPaletteSelect: false, - togglePaletteOnly: false, - showSelectionPalette: true, - localStorageKey: false, - appendTo: "body", - maxSelectionSize: 7, - cancelText: "cancel", - chooseText: "choose", - togglePaletteMoreText: "more", - togglePaletteLessText: "less", - clearText: "Clear Color Selection", - noColorSelectedText: "No Color Selected", - preferredFormat: false, - className: "", // Deprecated - use containerClassName and replacerClassName instead. - containerClassName: "", - replacerClassName: "", - showAlpha: false, - theme: "sp-light", - palette: [["#ffffff", "#000000", "#ff0000", "#ff8000", "#ffff00", "#008000", "#0000ff", "#4b0082", "#9400d3"]], - selectionPalette: [], - disabled: false, - offset: null + 'use strict'; + + var defaultOpts = { + // Callbacks + beforeShow: noop, + move: noop, + change: noop, + show: noop, + hide: noop, + + // Options + color: false, + flat: false, + showInput: false, + allowEmpty: false, + showButtons: true, + clickoutFiresChange: true, + showInitial: false, + showPalette: false, + showPaletteOnly: false, + hideAfterPaletteSelect: false, + togglePaletteOnly: false, + showSelectionPalette: true, + localStorageKey: false, + appendTo: 'body', + maxSelectionSize: 7, + cancelText: 'cancel', + chooseText: 'choose', + togglePaletteMoreText: 'more', + togglePaletteLessText: 'less', + clearText: 'Clear Color Selection', + noColorSelectedText: 'No Color Selected', + preferredFormat: false, + className: '', // Deprecated - use containerClassName and replacerClassName instead. + containerClassName: '', + replacerClassName: '', + showAlpha: false, + theme: 'sp-light', + palette: [ + [ + '#ffffff', + '#000000', + '#ff0000', + '#ff8000', + '#ffff00', + '#008000', + '#0000ff', + '#4b0082', + '#9400d3' + ] + ], + selectionPalette: [], + disabled: false, + offset: null }, spectrums = [], - IE = !!/msie/i.exec( window.navigator.userAgent ), + IE = !!/msie/i.exec(window.navigator.userAgent), rgbaSupport = (function() { - function contains( str, substr ) { - return !!~('' + str).indexOf(substr); - } - - var elem = document.createElement('div'); - var style = elem.style; - style.cssText = 'background-color:rgba(0,0,0,.5)'; - return contains(style.backgroundColor, 'rgba') || contains(style.backgroundColor, 'hsla'); + function contains(str, substr) { + return !!~('' + str).indexOf(substr); + } + + var elem = document.createElement('div'); + var style = elem.style; + style.cssText = 'background-color:rgba(0,0,0,.5)'; + return ( + contains(style.backgroundColor, 'rgba') || + contains(style.backgroundColor, 'hsla') + ); })(), replaceInput = [ - "
", - "
", - "
", - "
" + "
", + "
", + "
", + '
' ].join(''), - markup = (function () { - - // IE does not support gradients with multiple stops, so we need to simulate - // that for the rainbow slider with 8 divs that each have a single gradient - var gradientFix = ""; - if (IE) { - for (var i = 1; i <= 6; i++) { - gradientFix += "
"; - } - } - - return [ - "
", - "
", - "
", - "
", - "", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - "
", - gradientFix, - "
", - "
", - "
", - "
", - "
", - "", - "
", - "
", - "
", - "", - "", - "
", - "
", - "
" - ].join(""); + markup = (function() { + // IE does not support gradients with multiple stops, so we need to simulate + // that for the rainbow slider with 8 divs that each have a single gradient + var gradientFix = ''; + if (IE) { + for (var i = 1; i <= 6; i++) { + gradientFix += "
"; + } + } + + return [ + "
", + "
", + "
", + "
", + "", + '
', + '
', + "
", + "
", + "
", + "
", + "
", + "
", + "
", + "
", + '
', + '
', + '
', + "
", + '
', + "
", + "
", + gradientFix, + '
', + '
', + "
", + '
', + "
", + "", + '
', + "
", + "
", + "", + "", + '
', + '
', + '
' + ].join(''); })(); - function paletteTemplate (p, color, className, opts) { - var html = []; - for (var i = 0; i < p.length; i++) { - var current = p[i]; - if(current) { - var tiny = tinycolor(current); - var c = tiny.toHsl().l < 0.5 ? "sp-thumb-el sp-thumb-dark" : "sp-thumb-el sp-thumb-light"; - c += (tinycolor.equals(color, current)) ? " sp-thumb-active" : ""; - var formattedString = tiny.toString(opts.preferredFormat || "rgb"); - var swatchStyle = rgbaSupport ? ("background-color:" + tiny.toRgbString()) : "filter:" + tiny.toFilter(); - html.push(''); - } else { - var cls = 'sp-clear-display'; - html.push($('
') - .append($('') - .attr('title', opts.noColorSelectedText) - ) - .html() - ); - } - } - return "
" + html.join('') + "
"; + function paletteTemplate(p, color, className, opts) { + var html = []; + for (var i = 0; i < p.length; i++) { + var current = p[i]; + if (current) { + var tiny = tinycolor(current); + var c = + tiny.toHsl().l < 0.5 + ? 'sp-thumb-el sp-thumb-dark' + : 'sp-thumb-el sp-thumb-light'; + c += tinycolor.equals(color, current) ? ' sp-thumb-active' : ''; + var formattedString = tiny.toString(opts.preferredFormat || 'rgb'); + var swatchStyle = rgbaSupport + ? 'background-color:' + tiny.toRgbString() + : 'filter:' + tiny.toFilter(); + html.push( + '' + ); + } else { + var cls = 'sp-clear-display'; + html.push( + $('
') + .append( + $( + '' + ).attr('title', opts.noColorSelectedText) + ) + .html() + ); + } } - - function hideAll() { - for (var i = 0; i < spectrums.length; i++) { - if (spectrums[i]) { - spectrums[i].hide(); - } - } + return "
" + html.join('') + '
'; + } + + function hideAll() { + for (var i = 0; i < spectrums.length; i++) { + if (spectrums[i]) { + spectrums[i].hide(); + } + } + } + + function instanceOptions(o, callbackContext) { + var opts = $.extend({}, defaultOpts, o); + opts.callbacks = { + move: bind(opts.move, callbackContext), + change: bind(opts.change, callbackContext), + show: bind(opts.show, callbackContext), + hide: bind(opts.hide, callbackContext), + beforeShow: bind(opts.beforeShow, callbackContext) + }; + return opts; + } + + function spectrum(element, o) { + var opts = instanceOptions(o, element), + flat = opts.flat, + showSelectionPalette = opts.showSelectionPalette, + localStorageKey = opts.localStorageKey, + theme = opts.theme, + callbacks = opts.callbacks, + resize = throttle(reflow, 10), + visible = false, + isDragging = false, + dragWidth = 0, + dragHeight = 0, + dragHelperHeight = 0, + slideHeight = 0, + slideWidth = 0, + alphaWidth = 0, + alphaSlideHelperWidth = 0, + slideHelperHeight = 0, + currentHue = 0, + currentSaturation = 0, + currentValue = 0, + currentAlpha = 1, + palette = [], + paletteArray = [], + paletteLookup = {}, + selectionPalette = opts.selectionPalette.slice(0), + maxSelectionSize = opts.maxSelectionSize, + draggingClass = 'sp-dragging', + shiftMovementDirection = null; + + var doc = element.ownerDocument, + body = doc.body, + boundElement = $(element), + disabled = false, + container = $(markup, doc).addClass(theme), + pickerContainer = container.find('.sp-picker-container'), + dragger = container.find('.sp-color'), + dragHelper = container.find('.sp-dragger'), + slider = container.find('.sp-hue'), + slideHelper = container.find('.sp-slider'), + alphaSliderInner = container.find('.sp-alpha-inner'), + alphaSlider = container.find('.sp-alpha'), + alphaSlideHelper = container.find('.sp-alpha-handle'), + textInput = container.find('.sp-input'), + paletteContainer = container.find('.sp-palette'), + initialColorContainer = container.find('.sp-initial'), + cancelButton = container.find('.sp-cancel'), + clearButton = container.find('.sp-clear'), + chooseButton = container.find('.sp-choose'), + toggleButton = container.find('.sp-palette-toggle'), + isInput = boundElement.is('input'), + isInputTypeColor = + isInput && + boundElement.attr('type') === 'color' && + inputTypeColorSupport(), + shouldReplace = isInput && !flat, + replacer = shouldReplace + ? $(replaceInput) + .addClass(theme) + .addClass(opts.className) + .addClass(opts.replacerClassName) + : $([]), + offsetElement = shouldReplace ? replacer : boundElement, + previewElement = replacer.find('.sp-preview-inner'), + initialColor = opts.color || (isInput && boundElement.val()), + colorOnShow = false, + currentPreferredFormat = opts.preferredFormat, + clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange, + isEmpty = !initialColor, + allowEmpty = opts.allowEmpty && !isInputTypeColor; + + function applyOptions() { + if (opts.showPaletteOnly) { + opts.showPalette = true; + } + + toggleButton.text( + opts.showPaletteOnly + ? opts.togglePaletteMoreText + : opts.togglePaletteLessText + ); + + if (opts.palette) { + palette = opts.palette.slice(0); + paletteArray = $.isArray(palette[0]) ? palette : [palette]; + paletteLookup = {}; + for (var i = 0; i < paletteArray.length; i++) { + for (var j = 0; j < paletteArray[i].length; j++) { + var rgb = tinycolor(paletteArray[i][j]).toRgbString(); + paletteLookup[rgb] = true; + } + } + } + + container.toggleClass('sp-flat', flat); + container.toggleClass('sp-input-disabled', !opts.showInput); + container.toggleClass('sp-alpha-enabled', opts.showAlpha); + container.toggleClass('sp-clear-enabled', allowEmpty); + container.toggleClass('sp-buttons-disabled', !opts.showButtons); + container.toggleClass( + 'sp-palette-buttons-disabled', + !opts.togglePaletteOnly + ); + container.toggleClass('sp-palette-disabled', !opts.showPalette); + container.toggleClass('sp-palette-only', opts.showPaletteOnly); + container.toggleClass('sp-initial-disabled', !opts.showInitial); + container.addClass(opts.className).addClass(opts.containerClassName); + + reflow(); } - function instanceOptions(o, callbackContext) { - var opts = $.extend({}, defaultOpts, o); - opts.callbacks = { - 'move': bind(opts.move, callbackContext), - 'change': bind(opts.change, callbackContext), - 'show': bind(opts.show, callbackContext), - 'hide': bind(opts.hide, callbackContext), - 'beforeShow': bind(opts.beforeShow, callbackContext) - }; - return opts; - } - - function spectrum(element, o) { - - var opts = instanceOptions(o, element), - flat = opts.flat, - showSelectionPalette = opts.showSelectionPalette, - localStorageKey = opts.localStorageKey, - theme = opts.theme, - callbacks = opts.callbacks, - resize = throttle(reflow, 10), - visible = false, - isDragging = false, - dragWidth = 0, - dragHeight = 0, - dragHelperHeight = 0, - slideHeight = 0, - slideWidth = 0, - alphaWidth = 0, - alphaSlideHelperWidth = 0, - slideHelperHeight = 0, - currentHue = 0, - currentSaturation = 0, - currentValue = 0, - currentAlpha = 1, - palette = [], - paletteArray = [], - paletteLookup = {}, - selectionPalette = opts.selectionPalette.slice(0), - maxSelectionSize = opts.maxSelectionSize, - draggingClass = "sp-dragging", - shiftMovementDirection = null; - - var doc = element.ownerDocument, - body = doc.body, - boundElement = $(element), - disabled = false, - container = $(markup, doc).addClass(theme), - pickerContainer = container.find(".sp-picker-container"), - dragger = container.find(".sp-color"), - dragHelper = container.find(".sp-dragger"), - slider = container.find(".sp-hue"), - slideHelper = container.find(".sp-slider"), - alphaSliderInner = container.find(".sp-alpha-inner"), - alphaSlider = container.find(".sp-alpha"), - alphaSlideHelper = container.find(".sp-alpha-handle"), - textInput = container.find(".sp-input"), - paletteContainer = container.find(".sp-palette"), - initialColorContainer = container.find(".sp-initial"), - cancelButton = container.find(".sp-cancel"), - clearButton = container.find(".sp-clear"), - chooseButton = container.find(".sp-choose"), - toggleButton = container.find(".sp-palette-toggle"), - isInput = boundElement.is("input"), - isInputTypeColor = isInput && boundElement.attr("type") === "color" && inputTypeColorSupport(), - shouldReplace = isInput && !flat, - replacer = (shouldReplace) ? $(replaceInput).addClass(theme).addClass(opts.className).addClass(opts.replacerClassName) : $([]), - offsetElement = (shouldReplace) ? replacer : boundElement, - previewElement = replacer.find(".sp-preview-inner"), - initialColor = opts.color || (isInput && boundElement.val()), - colorOnShow = false, - currentPreferredFormat = opts.preferredFormat, - clickoutFiresChange = !opts.showButtons || opts.clickoutFiresChange, - isEmpty = !initialColor, - allowEmpty = opts.allowEmpty && !isInputTypeColor; - - function applyOptions() { - - if (opts.showPaletteOnly) { - opts.showPalette = true; - } - - toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText); - - if (opts.palette) { - palette = opts.palette.slice(0); - paletteArray = $.isArray(palette[0]) ? palette : [palette]; - paletteLookup = {}; - for (var i = 0; i < paletteArray.length; i++) { - for (var j = 0; j < paletteArray[i].length; j++) { - var rgb = tinycolor(paletteArray[i][j]).toRgbString(); - paletteLookup[rgb] = true; - } - } - } - - container.toggleClass("sp-flat", flat); - container.toggleClass("sp-input-disabled", !opts.showInput); - container.toggleClass("sp-alpha-enabled", opts.showAlpha); - container.toggleClass("sp-clear-enabled", allowEmpty); - container.toggleClass("sp-buttons-disabled", !opts.showButtons); - container.toggleClass("sp-palette-buttons-disabled", !opts.togglePaletteOnly); - container.toggleClass("sp-palette-disabled", !opts.showPalette); - container.toggleClass("sp-palette-only", opts.showPaletteOnly); - container.toggleClass("sp-initial-disabled", !opts.showInitial); - container.addClass(opts.className).addClass(opts.containerClassName); - - reflow(); - } - - function initialize() { - - if (IE) { - container.find("*:not(input)").attr("unselectable", "on"); - } - - applyOptions(); - - if (shouldReplace) { - boundElement.after(replacer).hide(); - } - - if (!allowEmpty) { - clearButton.hide(); - } - - if (flat) { - boundElement.after(container).hide(); - } - else { - - var appendTo = opts.appendTo === "parent" ? boundElement.parent() : $(opts.appendTo); - if (appendTo.length !== 1) { - appendTo = $("body"); - } - - appendTo.append(container); - } - - updateSelectionPaletteFromStorage(); - - offsetElement.bind("click.spectrum touchstart.spectrum", function (e) { - - if (!disabled) { - toggle(); - } - - e.stopPropagation(); - - if (!$(e.target).is("input")) { - e.preventDefault(); - } - }); - - if(boundElement.is(":disabled") || (opts.disabled === true)) { - disable(); - } - - // Prevent clicks from bubbling up to document. This would cause it to be hidden. - container.click(stopPropagation); + function initialize() { + if (IE) { + container.find('*:not(input)').attr('unselectable', 'on'); + } - // Handle user typed input - textInput.change(setFromTextInput); - textInput.bind("paste", function () { - setTimeout(setFromTextInput, 1); - }); - textInput.keydown(function (e) { if (e.keyCode == 13) { setFromTextInput(); } }); - - cancelButton.text(opts.cancelText); - cancelButton.bind("click.spectrum", function (e) { - e.stopPropagation(); - e.preventDefault(); - revert(); - hide(); - }); + applyOptions(); - clearButton.attr("title", opts.clearText); - clearButton.bind("click.spectrum", function (e) { - e.stopPropagation(); - e.preventDefault(); - isEmpty = true; - move(); - - if(flat) { - //for the flat style, this is a change event - updateOriginalInput(true); - } - }); + if (shouldReplace) { + boundElement.after(replacer).hide(); + } - chooseButton.text(opts.chooseText); - chooseButton.bind("click.spectrum", function (e) { - e.stopPropagation(); - e.preventDefault(); + if (!allowEmpty) { + clearButton.hide(); + } - if (IE && textInput.is(":focus")) { - textInput.trigger('change'); - } + if (flat) { + boundElement.after(container).hide(); + } else { + var appendTo = + opts.appendTo === 'parent' ? boundElement.parent() : $(opts.appendTo); + if (appendTo.length !== 1) { + appendTo = $('body'); + } - if (isValid()) { - updateOriginalInput(true); - hide(); - } - }); + appendTo.append(container); + } - toggleButton.text(opts.showPaletteOnly ? opts.togglePaletteMoreText : opts.togglePaletteLessText); - toggleButton.bind("click.spectrum", function (e) { - e.stopPropagation(); - e.preventDefault(); - - opts.showPaletteOnly = !opts.showPaletteOnly; - - // To make sure the Picker area is drawn on the right, next to the - // Palette area (and not below the palette), first move the Palette - // to the left to make space for the picker, plus 5px extra. - // The 'applyOptions' function puts the whole container back into place - // and takes care of the button-text and the sp-palette-only CSS class. - if (!opts.showPaletteOnly && !flat) { - container.css('left', '-=' + (pickerContainer.outerWidth(true) + 5)); - } - applyOptions(); - }); + updateSelectionPaletteFromStorage(); - draggable(alphaSlider, function (dragX, dragY, e) { - currentAlpha = (dragX / alphaWidth); - isEmpty = false; - if (e.shiftKey) { - currentAlpha = Math.round(currentAlpha * 10) / 10; - } - - move(); - }, dragStart, dragStop); - - draggable(slider, function (dragX, dragY) { - currentHue = parseFloat(dragY / slideHeight); - isEmpty = false; - if (!opts.showAlpha) { - currentAlpha = 1; - } - move(); - }, dragStart, dragStop); - - draggable(dragger, function (dragX, dragY, e) { - - // shift+drag should snap the movement to either the x or y axis. - if (!e.shiftKey) { - shiftMovementDirection = null; - } - else if (!shiftMovementDirection) { - var oldDragX = currentSaturation * dragWidth; - var oldDragY = dragHeight - (currentValue * dragHeight); - var furtherFromX = Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY); - - shiftMovementDirection = furtherFromX ? "x" : "y"; - } - - var setSaturation = !shiftMovementDirection || shiftMovementDirection === "x"; - var setValue = !shiftMovementDirection || shiftMovementDirection === "y"; - - if (setSaturation) { - currentSaturation = parseFloat(dragX / dragWidth); - } - if (setValue) { - currentValue = parseFloat((dragHeight - dragY) / dragHeight); - } - - isEmpty = false; - if (!opts.showAlpha) { - currentAlpha = 1; - } - - move(); - - }, dragStart, dragStop); - - if (!!initialColor) { - set(initialColor); - - // In case color was black - update the preview UI and set the format - // since the set function will not run (default color is black). - updateUI(); - currentPreferredFormat = opts.preferredFormat || tinycolor(initialColor).format; - - addColorToSelectionPalette(initialColor); - } - else { - updateUI(); - } - - if (flat) { - show(); - } - - function paletteElementClick(e) { - if (e.data && e.data.ignore) { - set($(e.target).closest(".sp-thumb-el").data("color")); - move(); - } - else { - set($(e.target).closest(".sp-thumb-el").data("color")); - move(); - updateOriginalInput(true); - if (opts.hideAfterPaletteSelect) { - hide(); - } - } - - return false; - } - - var paletteEvent = IE ? "mousedown.spectrum" : "click.spectrum touchstart.spectrum"; - paletteContainer.delegate(".sp-thumb-el", paletteEvent, paletteElementClick); - initialColorContainer.delegate(".sp-thumb-el:nth-child(1)", paletteEvent, { ignore: true }, paletteElementClick); + offsetElement.bind('click.spectrum touchstart.spectrum', function(e) { + if (!disabled) { + toggle(); } - function updateSelectionPaletteFromStorage() { - - if (localStorageKey && window.localStorage) { - - // Migrate old palettes over to new format. May want to remove this eventually. - try { - var oldPalette = window.localStorage[localStorageKey].split(",#"); - if (oldPalette.length > 1) { - delete window.localStorage[localStorageKey]; - $.each(oldPalette, function(i, c) { - addColorToSelectionPalette(c); - }); - } - } - catch(e) { } - - try { - selectionPalette = window.localStorage[localStorageKey].split(";"); - } - catch (e) { } - } - } + e.stopPropagation(); - function addColorToSelectionPalette(color) { - if (showSelectionPalette) { - var rgb = tinycolor(color).toRgbString(); - if (!paletteLookup[rgb] && $.inArray(rgb, selectionPalette) === -1) { - selectionPalette.push(rgb); - while(selectionPalette.length > maxSelectionSize) { - selectionPalette.shift(); - } - } - - if (localStorageKey && window.localStorage) { - try { - window.localStorage[localStorageKey] = selectionPalette.join(";"); - } - catch(e) { } - } - } + if (!$(e.target).is('input')) { + e.preventDefault(); } + }); - function getUniqueSelectionPalette() { - var unique = []; - if (opts.showPalette) { - for (var i = 0; i < selectionPalette.length; i++) { - var rgb = tinycolor(selectionPalette[i]).toRgbString(); + if (boundElement.is(':disabled') || opts.disabled === true) { + disable(); + } - if (!paletteLookup[rgb]) { - unique.push(selectionPalette[i]); - } - } - } + // Prevent clicks from bubbling up to document. This would cause it to be hidden. + container.click(stopPropagation); - return unique.reverse().slice(0, opts.maxSelectionSize); + // Handle user typed input + textInput.change(setFromTextInput); + textInput.bind('paste', function() { + setTimeout(setFromTextInput, 1); + }); + textInput.keydown(function(e) { + if (e.keyCode == 13) { + setFromTextInput(); } + }); - function drawPalette() { - - var currentColor = get(); - - var html = $.map(paletteArray, function (palette, i) { - return paletteTemplate(palette, currentColor, "sp-palette-row sp-palette-row-" + i, opts); - }); - - updateSelectionPaletteFromStorage(); - - if (selectionPalette) { - html.push(paletteTemplate(getUniqueSelectionPalette(), currentColor, "sp-palette-row sp-palette-row-selection", opts)); - } + cancelButton.text(opts.cancelText); + cancelButton.bind('click.spectrum', function(e) { + e.stopPropagation(); + e.preventDefault(); + revert(); + hide(); + }); - paletteContainer.html(html.join("")); - } + clearButton.attr('title', opts.clearText); + clearButton.bind('click.spectrum', function(e) { + e.stopPropagation(); + e.preventDefault(); + isEmpty = true; + move(); - function drawInitial() { - if (opts.showInitial) { - var initial = colorOnShow; - var current = get(); - initialColorContainer.html(paletteTemplate([initial, current], current, "sp-palette-row-initial", opts)); - } + if (flat) { + //for the flat style, this is a change event + updateOriginalInput(true); } + }); - function dragStart() { - if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) { - reflow(); - } - isDragging = true; - container.addClass(draggingClass); - shiftMovementDirection = null; - boundElement.trigger('dragstart.spectrum', [ get() ]); - } + chooseButton.text(opts.chooseText); + chooseButton.bind('click.spectrum', function(e) { + e.stopPropagation(); + e.preventDefault(); - function dragStop() { - isDragging = false; - container.removeClass(draggingClass); - boundElement.trigger('dragstop.spectrum', [ get() ]); + if (IE && textInput.is(':focus')) { + textInput.trigger('change'); } - function setFromTextInput() { - - var value = textInput.val(); - - if ((value === null || value === "") && allowEmpty) { - set(null); - updateOriginalInput(true); - } - else { - var tiny = tinycolor(value); - if (tiny.isValid()) { - set(tiny); - updateOriginalInput(true); - } - else { - textInput.addClass("sp-validation-error"); - } - } + if (isValid()) { + updateOriginalInput(true); + hide(); } + }); - function toggle() { - if (visible) { - hide(); - } - else { - show(); - } + toggleButton.text( + opts.showPaletteOnly + ? opts.togglePaletteMoreText + : opts.togglePaletteLessText + ); + toggleButton.bind('click.spectrum', function(e) { + e.stopPropagation(); + e.preventDefault(); + + opts.showPaletteOnly = !opts.showPaletteOnly; + + // To make sure the Picker area is drawn on the right, next to the + // Palette area (and not below the palette), first move the Palette + // to the left to make space for the picker, plus 5px extra. + // The 'applyOptions' function puts the whole container back into place + // and takes care of the button-text and the sp-palette-only CSS class. + if (!opts.showPaletteOnly && !flat) { + container.css('left', '-=' + (pickerContainer.outerWidth(true) + 5)); + } + applyOptions(); + }); + + draggable( + alphaSlider, + function(dragX, dragY, e) { + currentAlpha = dragX / alphaWidth; + isEmpty = false; + if (e.shiftKey) { + currentAlpha = Math.round(currentAlpha * 10) / 10; + } + + move(); + }, + dragStart, + dragStop + ); + + draggable( + slider, + function(dragX, dragY) { + currentHue = parseFloat(dragY / slideHeight); + isEmpty = false; + if (!opts.showAlpha) { + currentAlpha = 1; + } + move(); + }, + dragStart, + dragStop + ); + + draggable( + dragger, + function(dragX, dragY, e) { + // shift+drag should snap the movement to either the x or y axis. + if (!e.shiftKey) { + shiftMovementDirection = null; + } else if (!shiftMovementDirection) { + var oldDragX = currentSaturation * dragWidth; + var oldDragY = dragHeight - currentValue * dragHeight; + var furtherFromX = + Math.abs(dragX - oldDragX) > Math.abs(dragY - oldDragY); + + shiftMovementDirection = furtherFromX ? 'x' : 'y'; + } + + var setSaturation = + !shiftMovementDirection || shiftMovementDirection === 'x'; + var setValue = + !shiftMovementDirection || shiftMovementDirection === 'y'; + + if (setSaturation) { + currentSaturation = parseFloat(dragX / dragWidth); + } + if (setValue) { + currentValue = parseFloat((dragHeight - dragY) / dragHeight); + } + + isEmpty = false; + if (!opts.showAlpha) { + currentAlpha = 1; + } + + move(); + }, + dragStart, + dragStop + ); + + if (!!initialColor) { + set(initialColor); + + // In case color was black - update the preview UI and set the format + // since the set function will not run (default color is black). + updateUI(); + currentPreferredFormat = + opts.preferredFormat || tinycolor(initialColor).format; + + addColorToSelectionPalette(initialColor); + } else { + updateUI(); + } + + if (flat) { + show(); + } + + function paletteElementClick(e) { + if (e.data && e.data.ignore) { + set( + $(e.target) + .closest('.sp-thumb-el') + .data('color') + ); + move(); + } else { + set( + $(e.target) + .closest('.sp-thumb-el') + .data('color') + ); + move(); + updateOriginalInput(true); + if (opts.hideAfterPaletteSelect) { + hide(); + } } - function show() { - var event = $.Event('beforeShow.spectrum'); - - if (visible) { - reflow(); - return; - } - - boundElement.trigger(event, [ get() ]); - - if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) { - return; - } - - hideAll(); - visible = true; - - var $doc = $(doc); - $doc.bind("keydown.spectrum", onkeydown); - $doc.bind("click.spectrum", clickout); - $(window).bind("resize.spectrum", resize); - replacer.addClass("sp-active"); - container.removeClass("sp-hidden"); - - reflow(); - updateUI(); + return false; + } + + var paletteEvent = IE + ? 'mousedown.spectrum' + : 'click.spectrum touchstart.spectrum'; + paletteContainer.delegate( + '.sp-thumb-el', + paletteEvent, + paletteElementClick + ); + initialColorContainer.delegate( + '.sp-thumb-el:nth-child(1)', + paletteEvent, + { ignore: true }, + paletteElementClick + ); + } - colorOnShow = get(); + function updateSelectionPaletteFromStorage() { + if (localStorageKey && window.localStorage) { + // Migrate old palettes over to new format. May want to remove this eventually. + try { + var oldPalette = window.localStorage[localStorageKey].split(',#'); + if (oldPalette.length > 1) { + delete window.localStorage[localStorageKey]; + $.each(oldPalette, function(i, c) { + addColorToSelectionPalette(c); + }); + } + } catch (e) {} - drawInitial(); - callbacks.show(colorOnShow); - boundElement.trigger('show.spectrum', [ colorOnShow ]); - } + try { + selectionPalette = window.localStorage[localStorageKey].split(';'); + } catch (e) {} + } + } - function onkeydown(e) { - // Close on ESC - if (e.keyCode === 27) { - hide(); - } + function addColorToSelectionPalette(color) { + if (showSelectionPalette) { + var rgb = tinycolor(color).toRgbString(); + if (!paletteLookup[rgb] && $.inArray(rgb, selectionPalette) === -1) { + selectionPalette.push(rgb); + while (selectionPalette.length > maxSelectionSize) { + selectionPalette.shift(); + } } - function clickout(e) { - // Return on right click. - if (e.button == 2) { return; } - - // If a drag event was happening during the mouseup, don't hide - // on click. - if (isDragging) { return; } - - if (clickoutFiresChange) { - updateOriginalInput(true); - } - else { - revert(); - } - hide(); + if (localStorageKey && window.localStorage) { + try { + window.localStorage[localStorageKey] = selectionPalette.join(';'); + } catch (e) {} } + } + } - function hide() { - // Return if hiding is unnecessary - if (!visible || flat) { return; } - visible = false; - - $(doc).unbind("keydown.spectrum", onkeydown); - $(doc).unbind("click.spectrum", clickout); - $(window).unbind("resize.spectrum", resize); - - replacer.removeClass("sp-active"); - container.addClass("sp-hidden"); + function getUniqueSelectionPalette() { + var unique = []; + if (opts.showPalette) { + for (var i = 0; i < selectionPalette.length; i++) { + var rgb = tinycolor(selectionPalette[i]).toRgbString(); - callbacks.hide(get()); - boundElement.trigger('hide.spectrum', [ get() ]); + if (!paletteLookup[rgb]) { + unique.push(selectionPalette[i]); + } } + } - function revert() { - set(colorOnShow, true); - } + return unique.reverse().slice(0, opts.maxSelectionSize); + } - function set(color, ignoreFormatChange) { - if (tinycolor.equals(color, get())) { - // Update UI just in case a validation error needs - // to be cleared. - updateUI(); - return; - } - - var newColor, newHsv; - if (!color && allowEmpty) { - isEmpty = true; - } else { - isEmpty = false; - newColor = tinycolor(color); - newHsv = newColor.toHsv(); - - currentHue = (newHsv.h % 360) / 360; - currentSaturation = newHsv.s; - currentValue = newHsv.v; - currentAlpha = newHsv.a; - } - updateUI(); - - if (newColor && newColor.isValid() && !ignoreFormatChange) { - currentPreferredFormat = opts.preferredFormat || newColor.getFormat(); - } - } + function drawPalette() { + var currentColor = get(); - function get(opts) { - opts = opts || { }; + var html = $.map(paletteArray, function(palette, i) { + return paletteTemplate( + palette, + currentColor, + 'sp-palette-row sp-palette-row-' + i, + opts + ); + }); + + updateSelectionPaletteFromStorage(); + + if (selectionPalette) { + html.push( + paletteTemplate( + getUniqueSelectionPalette(), + currentColor, + 'sp-palette-row sp-palette-row-selection', + opts + ) + ); + } - if (allowEmpty && isEmpty) { - return null; - } + paletteContainer.html(html.join('')); + } - return tinycolor.fromRatio({ - h: currentHue, - s: currentSaturation, - v: currentValue, - a: Math.round(currentAlpha * 100) / 100 - }, { format: opts.format || currentPreferredFormat }); - } + function drawInitial() { + if (opts.showInitial) { + var initial = colorOnShow; + var current = get(); + initialColorContainer.html( + paletteTemplate( + [initial, current], + current, + 'sp-palette-row-initial', + opts + ) + ); + } + } - function isValid() { - return !textInput.hasClass("sp-validation-error"); - } + function dragStart() { + if (dragHeight <= 0 || dragWidth <= 0 || slideHeight <= 0) { + reflow(); + } + isDragging = true; + container.addClass(draggingClass); + shiftMovementDirection = null; + boundElement.trigger('dragstart.spectrum', [get()]); + } - function move() { - updateUI(); + function dragStop() { + isDragging = false; + container.removeClass(draggingClass); + boundElement.trigger('dragstop.spectrum', [get()]); + } - callbacks.move(get()); - boundElement.trigger('move.spectrum', [ get() ]); + function setFromTextInput() { + var value = textInput.val(); + + if ((value === null || value === '') && allowEmpty) { + set(null); + updateOriginalInput(true); + } else { + var tiny = tinycolor(value); + if (tiny.isValid()) { + set(tiny); + updateOriginalInput(true); + } else { + textInput.addClass('sp-validation-error'); } + } + } - function updateUI() { - - textInput.removeClass("sp-validation-error"); - - updateHelperLocations(); - - // Update dragger background color (gradients take care of saturation and value). - var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 }); - dragger.css("background-color", flatColor.toHexString()); - - // Get a format that alpha will be included in (hex and names ignore alpha) - var format = currentPreferredFormat; - if (currentAlpha < 1 && !(currentAlpha === 0 && format === "name")) { - if (format === "hex" || format === "hex3" || format === "hex6" || format === "name") { - format = "rgb"; - } - } - - var realColor = get({ format: format }), - displayColor = ''; - - //reset background info for preview element - previewElement.removeClass("sp-clear-display"); - previewElement.css('background-color', 'transparent'); - - if (!realColor && allowEmpty) { - // Update the replaced elements background with icon indicating no color selection - previewElement.addClass("sp-clear-display"); - } - else { - var realHex = realColor.toHexString(), - realRgb = realColor.toRgbString(); - - // Update the replaced elements background color (with actual selected color) - if (rgbaSupport || realColor.alpha === 1) { - previewElement.css("background-color", realRgb); - } - else { - previewElement.css("background-color", "transparent"); - previewElement.css("filter", realColor.toFilter()); - } - - if (opts.showAlpha) { - var rgb = realColor.toRgb(); - rgb.a = 0; - var realAlpha = tinycolor(rgb).toRgbString(); - var gradient = "linear-gradient(left, " + realAlpha + ", " + realHex + ")"; - - if (IE) { - alphaSliderInner.css("filter", tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex)); - } - else { - alphaSliderInner.css("background", "-webkit-" + gradient); - alphaSliderInner.css("background", "-moz-" + gradient); - alphaSliderInner.css("background", "-ms-" + gradient); - // Use current syntax gradient on unprefixed property. - alphaSliderInner.css("background", - "linear-gradient(to right, " + realAlpha + ", " + realHex + ")"); - } - } - - displayColor = realColor.toString(format); - } - - // Update the text entry input as it changes happen - if (opts.showInput) { - textInput.val(displayColor); - } - - if (opts.showPalette) { - drawPalette(); - } - - drawInitial(); - } + function toggle() { + if (visible) { + hide(); + } else { + show(); + } + } - function updateHelperLocations() { - var s = currentSaturation; - var v = currentValue; - - if(allowEmpty && isEmpty) { - //if selected color is empty, hide the helpers - alphaSlideHelper.hide(); - slideHelper.hide(); - dragHelper.hide(); - } - else { - //make sure helpers are visible - alphaSlideHelper.show(); - slideHelper.show(); - dragHelper.show(); - - // Where to show the little circle in that displays your current selected color - var dragX = s * dragWidth; - var dragY = dragHeight - (v * dragHeight); - dragX = Math.max( - -dragHelperHeight, - Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight) - ); - dragY = Math.max( - -dragHelperHeight, - Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight) - ); - dragHelper.css({ - "top": dragY + "px", - "left": dragX + "px" - }); - - var alphaX = currentAlpha * alphaWidth; - alphaSlideHelper.css({ - "left": (alphaX - (alphaSlideHelperWidth / 2)) + "px" - }); - - // Where to show the bar that displays your current selected hue - var slideY = (currentHue) * slideHeight; - slideHelper.css({ - "top": (slideY - slideHelperHeight) + "px" - }); - } - } + function show() { + var event = $.Event('beforeShow.spectrum'); - function updateOriginalInput(fireCallback) { - var color = get(), - displayColor = '', - hasChanged = !tinycolor.equals(color, colorOnShow); - - if (color) { - displayColor = color.toString(currentPreferredFormat); - // Update the selection palette with the current color - addColorToSelectionPalette(color); - } - - if (isInput) { - boundElement.val(displayColor); - } - - if (fireCallback && hasChanged) { - callbacks.change(color); - boundElement.trigger('change', [ color ]); - } - } + if (visible) { + reflow(); + return; + } - function reflow() { - if (!visible) { - return; // Calculations would be useless and wouldn't be reliable anyways - } - dragWidth = dragger.width(); - dragHeight = dragger.height(); - dragHelperHeight = dragHelper.height(); - slideWidth = slider.width(); - slideHeight = slider.height(); - slideHelperHeight = slideHelper.height(); - alphaWidth = alphaSlider.width(); - alphaSlideHelperWidth = alphaSlideHelper.width(); - - if (!flat) { - container.css("position", "absolute"); - if (opts.offset) { - container.offset(opts.offset); - } else { - container.offset(getOffset(container, offsetElement)); - } - } - - updateHelperLocations(); - - if (opts.showPalette) { - drawPalette(); - } - - boundElement.trigger('reflow.spectrum'); - } + boundElement.trigger(event, [get()]); - function destroy() { - boundElement.show(); - offsetElement.unbind("click.spectrum touchstart.spectrum"); - container.remove(); - replacer.remove(); - spectrums[spect.id] = null; - } + if (callbacks.beforeShow(get()) === false || event.isDefaultPrevented()) { + return; + } - function option(optionName, optionValue) { - if (optionName === undefined) { - return $.extend({}, opts); - } - if (optionValue === undefined) { - return opts[optionName]; - } + hideAll(); + visible = true; - opts[optionName] = optionValue; + var $doc = $(doc); + $doc.bind('keydown.spectrum', onkeydown); + $doc.bind('click.spectrum', clickout); + $(window).bind('resize.spectrum', resize); + replacer.addClass('sp-active'); + container.removeClass('sp-hidden'); - if (optionName === "preferredFormat") { - currentPreferredFormat = opts.preferredFormat; - } - applyOptions(); - } + reflow(); + updateUI(); - function enable() { - disabled = false; - boundElement.attr("disabled", false); - offsetElement.removeClass("sp-disabled"); - } + colorOnShow = get(); - function disable() { - hide(); - disabled = true; - boundElement.attr("disabled", true); - offsetElement.addClass("sp-disabled"); - } + drawInitial(); + callbacks.show(colorOnShow); + boundElement.trigger('show.spectrum', [colorOnShow]); + } - function setOffset(coord) { - opts.offset = coord; - reflow(); - } + function onkeydown(e) { + // Close on ESC + if (e.keyCode === 27) { + hide(); + } + } - initialize(); - - var spect = { - show: show, - hide: hide, - toggle: toggle, - reflow: reflow, - option: option, - enable: enable, - disable: disable, - offset: setOffset, - set: function (c) { - set(c); - updateOriginalInput(); - }, - get: get, - destroy: destroy, - container: container - }; - - spect.id = spectrums.push(spect) - 1; - - return spect; - } - - /** - * checkOffset - get the offset below/above and left/right element depending on screen position - * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js - */ - function getOffset(picker, input) { - var extraY = 0; - var dpWidth = picker.outerWidth(); - var dpHeight = picker.outerHeight(); - var inputHeight = input.outerHeight(); - var doc = picker[0].ownerDocument; - var docElem = doc.documentElement; - var cW = docElem.clientWidth; - var cH = docElem.clientHeight; - var scL = $(doc).scrollLeft(); - var scT = $(doc).scrollTop(); - var viewWidth = cW + scL; - var viewHeight = cH + scT; - var offset = input.offset(); - - offset.top += inputHeight; - - offset.left -= - Math.min(offset.left, (offset.left + dpWidth > viewWidth && viewWidth > dpWidth) ? - Math.abs(offset.left + dpWidth - viewWidth) : 0); - - offset.top -= - Math.min(offset.top, ((offset.top + dpHeight > viewHeight && viewHeight > dpHeight) ? - Math.abs(dpHeight + inputHeight - extraY) : extraY)); - - return offset; - } - - /** - * noop - do nothing - */ - function noop() { - - } - - /** - * stopPropagation - makes the code only doing this a little easier to read in line - */ - function stopPropagation(e) { - e.stopPropagation(); + function clickout(e) { + // Return on right click. + if (e.button == 2) { + return; + } + + // If a drag event was happening during the mouseup, don't hide + // on click. + if (isDragging) { + return; + } + + if (clickoutFiresChange) { + updateOriginalInput(true); + } else { + revert(); + } + hide(); } - /** - * Create a function bound to a given object - * Thanks to underscore.js - */ - function bind(func, obj) { - var slice = Array.prototype.slice; - var args = slice.call(arguments, 2); - return function () { - return func.apply(obj, args.concat(slice.call(arguments))); - }; - } - - /** - * Lightweight drag helper. Handles containment within the element, so that - * when dragging, the x is within [0,element.width] and y is within [0,element.height] - */ - function draggable(element, onmove, onstart, onstop) { - onmove = onmove || function () { }; - onstart = onstart || function () { }; - onstop = onstop || function () { }; - var doc = document; - var dragging = false; - var offset = {}; - var maxHeight = 0; - var maxWidth = 0; - var hasTouch = ('ontouchstart' in window); - - var duringDragEvents = {}; - duringDragEvents["selectstart"] = prevent; - duringDragEvents["dragstart"] = prevent; - duringDragEvents["touchmove mousemove"] = move; - duringDragEvents["touchend mouseup"] = stop; - - function prevent(e) { - if (e.stopPropagation) { - e.stopPropagation(); - } - if (e.preventDefault) { - e.preventDefault(); - } - e.returnValue = false; - } + function hide() { + // Return if hiding is unnecessary + if (!visible || flat) { + return; + } + visible = false; - function move(e) { - if (dragging) { - // Mouseup happened outside of window - if (IE && doc.documentMode < 9 && !e.button) { - return stop(); - } + $(doc).unbind('keydown.spectrum', onkeydown); + $(doc).unbind('click.spectrum', clickout); + $(window).unbind('resize.spectrum', resize); - var t0 = e.originalEvent && e.originalEvent.touches && e.originalEvent.touches[0]; - var pageX = t0 && t0.pageX || e.pageX; - var pageY = t0 && t0.pageY || e.pageY; + replacer.removeClass('sp-active'); + container.addClass('sp-hidden'); - var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth)); - var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight)); + callbacks.hide(get()); + boundElement.trigger('hide.spectrum', [get()]); + } - if (hasTouch) { - // Stop scrolling in iOS - prevent(e); - } + function revert() { + set(colorOnShow, true); + } - onmove.apply(element, [dragX, dragY, e]); - } - } + function set(color, ignoreFormatChange) { + if (tinycolor.equals(color, get())) { + // Update UI just in case a validation error needs + // to be cleared. + updateUI(); + return; + } + + var newColor, newHsv; + if (!color && allowEmpty) { + isEmpty = true; + } else { + isEmpty = false; + newColor = tinycolor(color); + newHsv = newColor.toHsv(); + + currentHue = (newHsv.h % 360) / 360; + currentSaturation = newHsv.s; + currentValue = newHsv.v; + currentAlpha = newHsv.a; + } + updateUI(); + + if (newColor && newColor.isValid() && !ignoreFormatChange) { + currentPreferredFormat = opts.preferredFormat || newColor.getFormat(); + } + } - function start(e) { - var rightclick = (e.which) ? (e.which == 3) : (e.button == 2); + function get(opts) { + opts = opts || {}; - if (!rightclick && !dragging) { - if (onstart.apply(element, arguments) !== false) { - dragging = true; - maxHeight = $(element).height(); - maxWidth = $(element).width(); - offset = $(element).offset(); + if (allowEmpty && isEmpty) { + return null; + } - $(doc).bind(duringDragEvents); - $(doc.body).addClass("sp-dragging"); + return tinycolor.fromRatio( + { + h: currentHue, + s: currentSaturation, + v: currentValue, + a: Math.round(currentAlpha * 100) / 100 + }, + { format: opts.format || currentPreferredFormat } + ); + } - move(e); + function isValid() { + return !textInput.hasClass('sp-validation-error'); + } - prevent(e); - } - } - } + function move() { + updateUI(); - function stop() { - if (dragging) { - $(doc).unbind(duringDragEvents); - $(doc.body).removeClass("sp-dragging"); - - // Wait a tick before notifying observers to allow the click event - // to fire in Chrome. - setTimeout(function() { - onstop.apply(element, arguments); - }, 0); - } - dragging = false; - } + callbacks.move(get()); + boundElement.trigger('move.spectrum', [get()]); + } - $(element).bind("touchstart mousedown", start); - } - - function throttle(func, wait, debounce) { - var timeout; - return function () { - var context = this, args = arguments; - var throttler = function () { - timeout = null; - func.apply(context, args); - }; - if (debounce) clearTimeout(timeout); - if (debounce || !timeout) timeout = setTimeout(throttler, wait); - }; - } - - function inputTypeColorSupport() { - return $.fn.spectrum.inputTypeColorSupport(); - } - - /** - * Define a jQuery plugin - */ - var dataID = "spectrum.id"; - $.fn.spectrum = function (opts, extra) { - - if (typeof opts == "string") { - - var returnValue = this; - var args = Array.prototype.slice.call( arguments, 1 ); - - this.each(function () { - var spect = spectrums[$(this).data(dataID)]; - if (spect) { - var method = spect[opts]; - if (!method) { - throw new Error( "Spectrum: no such method: '" + opts + "'" ); - } - - if (opts == "get") { - returnValue = spect.get(); - } - else if (opts == "container") { - returnValue = spect.container; - } - else if (opts == "option") { - returnValue = spect.option.apply(spect, args); - } - else if (opts == "destroy") { - spect.destroy(); - $(this).removeData(dataID); - } - else { - method.apply(spect, args); - } - } - }); + function updateUI() { + textInput.removeClass('sp-validation-error'); + + updateHelperLocations(); + + // Update dragger background color (gradients take care of saturation and value). + var flatColor = tinycolor.fromRatio({ h: currentHue, s: 1, v: 1 }); + dragger.css('background-color', flatColor.toHexString()); + + // Get a format that alpha will be included in (hex and names ignore alpha) + var format = currentPreferredFormat; + if (currentAlpha < 1 && !(currentAlpha === 0 && format === 'name')) { + if ( + format === 'hex' || + format === 'hex3' || + format === 'hex6' || + format === 'name' + ) { + format = 'rgb'; + } + } + + var realColor = get({ format: format }), + displayColor = ''; + + //reset background info for preview element + previewElement.removeClass('sp-clear-display'); + previewElement.css('background-color', 'transparent'); + + if (!realColor && allowEmpty) { + // Update the replaced elements background with icon indicating no color selection + previewElement.addClass('sp-clear-display'); + } else { + var realHex = realColor.toHexString(), + realRgb = realColor.toRgbString(); + + // Update the replaced elements background color (with actual selected color) + if (rgbaSupport || realColor.alpha === 1) { + previewElement.css('background-color', realRgb); + } else { + previewElement.css('background-color', 'transparent'); + previewElement.css('filter', realColor.toFilter()); + } + + if (opts.showAlpha) { + var rgb = realColor.toRgb(); + rgb.a = 0; + var realAlpha = tinycolor(rgb).toRgbString(); + var gradient = + 'linear-gradient(left, ' + realAlpha + ', ' + realHex + ')'; + + if (IE) { + alphaSliderInner.css( + 'filter', + tinycolor(realAlpha).toFilter({ gradientType: 1 }, realHex) + ); + } else { + alphaSliderInner.css('background', '-webkit-' + gradient); + alphaSliderInner.css('background', '-moz-' + gradient); + alphaSliderInner.css('background', '-ms-' + gradient); + // Use current syntax gradient on unprefixed property. + alphaSliderInner.css( + 'background', + 'linear-gradient(to right, ' + realAlpha + ', ' + realHex + ')' + ); + } + } + + displayColor = realColor.toString(format); + } + + // Update the text entry input as it changes happen + if (opts.showInput) { + textInput.val(displayColor); + } + + if (opts.showPalette) { + drawPalette(); + } + + drawInitial(); + } - return returnValue; - } + function updateHelperLocations() { + var s = currentSaturation; + var v = currentValue; + + if (allowEmpty && isEmpty) { + //if selected color is empty, hide the helpers + alphaSlideHelper.hide(); + slideHelper.hide(); + dragHelper.hide(); + } else { + //make sure helpers are visible + alphaSlideHelper.show(); + slideHelper.show(); + dragHelper.show(); + + // Where to show the little circle in that displays your current selected color + var dragX = s * dragWidth; + var dragY = dragHeight - v * dragHeight; + dragX = Math.max( + -dragHelperHeight, + Math.min(dragWidth - dragHelperHeight, dragX - dragHelperHeight) + ); + dragY = Math.max( + -dragHelperHeight, + Math.min(dragHeight - dragHelperHeight, dragY - dragHelperHeight) + ); + dragHelper.css({ + top: dragY + 'px', + left: dragX + 'px' + }); - // Initializing a new instance of spectrum - return this.spectrum("destroy").each(function () { - var options = $.extend({}, opts, $(this).data()); - var spect = spectrum(this, options); - $(this).data(dataID, spect.id); + var alphaX = currentAlpha * alphaWidth; + alphaSlideHelper.css({ + left: alphaX - alphaSlideHelperWidth / 2 + 'px' }); - }; - $.fn.spectrum.load = true; - $.fn.spectrum.loadOpts = {}; - $.fn.spectrum.draggable = draggable; - $.fn.spectrum.defaults = defaultOpts; - $.fn.spectrum.inputTypeColorSupport = function inputTypeColorSupport() { - if (typeof inputTypeColorSupport._cachedResult === "undefined") { - var colorInput = $("")[0]; // if color element is supported, value will default to not null - inputTypeColorSupport._cachedResult = colorInput.type === "color" && colorInput.value !== ""; - } - return inputTypeColorSupport._cachedResult; - }; + // Where to show the bar that displays your current selected hue + var slideY = currentHue * slideHeight; + slideHelper.css({ + top: slideY - slideHelperHeight + 'px' + }); + } + } - $.spectrum = { }; - $.spectrum.localization = { }; - $.spectrum.palettes = { }; + function updateOriginalInput(fireCallback) { + var color = get(), + displayColor = '', + hasChanged = !tinycolor.equals(color, colorOnShow); + + if (color) { + displayColor = color.toString(currentPreferredFormat); + // Update the selection palette with the current color + addColorToSelectionPalette(color); + } + + if (isInput) { + boundElement.val(displayColor); + } + + if (fireCallback && hasChanged) { + callbacks.change(color); + boundElement.trigger('change', [color]); + } + } - $.fn.spectrum.processNativeColorInputs = function () { - var colorInputs = $("input[type=color]"); - if (colorInputs.length && !inputTypeColorSupport()) { - colorInputs.spectrum({ - preferredFormat: "hex6" - }); + function reflow() { + if (!visible) { + return; // Calculations would be useless and wouldn't be reliable anyways + } + dragWidth = dragger.width(); + dragHeight = dragger.height(); + dragHelperHeight = dragHelper.height(); + slideWidth = slider.width(); + slideHeight = slider.height(); + slideHelperHeight = slideHelper.height(); + alphaWidth = alphaSlider.width(); + alphaSlideHelperWidth = alphaSlideHelper.width(); + + if (!flat) { + container.css('position', 'absolute'); + if (opts.offset) { + container.offset(opts.offset); + } else { + container.offset(getOffset(container, offsetElement)); } - }; - - // TinyColor v1.1.2 - // https://github.com/bgrins/TinyColor - // Brian Grinstead, MIT License + } - //(function() { + updateHelperLocations(); - var trimLeft = /^[\s,#]+/, - trimRight = /\s+$/, - tinyCounter = 0, - math = Math, - mathRound = math.round, - mathMin = math.min, - mathMax = math.max, - mathRandom = math.random; + if (opts.showPalette) { + drawPalette(); + } - var tinycolor = function(color, opts) { + boundElement.trigger('reflow.spectrum'); + } - color = (color) ? color : ''; - opts = opts || { }; + function destroy() { + boundElement.show(); + offsetElement.unbind('click.spectrum touchstart.spectrum'); + container.remove(); + replacer.remove(); + spectrums[spect.id] = null; + } - // If input is already a tinycolor, return itself - if (color instanceof tinycolor) { - return color; - } - // If we are called as a function, call using new instead - if (!(this instanceof tinycolor)) { - return new tinycolor(color, opts); - } + function option(optionName, optionValue) { + if (optionName === undefined) { + return $.extend({}, opts); + } + if (optionValue === undefined) { + return opts[optionName]; + } - var rgb = inputToRGB(color); - this._originalInput = color, - this._r = rgb.r, - this._g = rgb.g, - this._b = rgb.b, - this._a = rgb.a, - this._roundA = mathRound(100*this._a) / 100, - this._format = opts.format || rgb.format; - this._gradientType = opts.gradientType; - - // Don't let the range of [0,255] come back in [0,1]. - // Potentially lose a little bit of precision here, but will fix issues where - // .5 gets interpreted as half of the total, instead of half of 1 - // If it was supposed to be 128, this was already taken care of by `inputToRgb` - if (this._r < 1) { this._r = mathRound(this._r); } - if (this._g < 1) { this._g = mathRound(this._g); } - if (this._b < 1) { this._b = mathRound(this._b); } - - this._ok = rgb.ok; - this._tc_id = tinyCounter++; - }; + opts[optionName] = optionValue; - tinycolor.prototype = { - isDark: function() { - return this.getBrightness() < 128; - }, - isLight: function() { - return !this.isDark(); - }, - isValid: function() { - return this._ok; - }, - getOriginalInput: function() { - return this._originalInput; - }, - getFormat: function() { - return this._format; - }, - getAlpha: function() { - return this._a; - }, - getBrightness: function() { - var rgb = this.toRgb(); - return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; - }, - setAlpha: function(value) { - this._a = boundAlpha(value); - this._roundA = mathRound(100*this._a) / 100; - return this; - }, - toHsv: function() { - var hsv = rgbToHsv(this._r, this._g, this._b); - return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; - }, - toHsvString: function() { - var hsv = rgbToHsv(this._r, this._g, this._b); - var h = mathRound(hsv.h * 360), s = mathRound(hsv.s * 100), v = mathRound(hsv.v * 100); - return (this._a == 1) ? - "hsv(" + h + ", " + s + "%, " + v + "%)" : - "hsva(" + h + ", " + s + "%, " + v + "%, "+ this._roundA + ")"; - }, - toHsl: function() { - var hsl = rgbToHsl(this._r, this._g, this._b); - return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; - }, - toHslString: function() { - var hsl = rgbToHsl(this._r, this._g, this._b); - var h = mathRound(hsl.h * 360), s = mathRound(hsl.s * 100), l = mathRound(hsl.l * 100); - return (this._a == 1) ? - "hsl(" + h + ", " + s + "%, " + l + "%)" : - "hsla(" + h + ", " + s + "%, " + l + "%, "+ this._roundA + ")"; - }, - toHex: function(allow3Char) { - return rgbToHex(this._r, this._g, this._b, allow3Char); - }, - toHexString: function(allow3Char) { - return '#' + this.toHex(allow3Char); - }, - toHex8: function() { - return rgbaToHex(this._r, this._g, this._b, this._a); - }, - toHex8String: function() { - return '#' + this.toHex8(); - }, - toRgb: function() { - return { r: mathRound(this._r), g: mathRound(this._g), b: mathRound(this._b), a: this._a }; - }, - toRgbString: function() { - return (this._a == 1) ? - "rgb(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ")" : - "rgba(" + mathRound(this._r) + ", " + mathRound(this._g) + ", " + mathRound(this._b) + ", " + this._roundA + ")"; - }, - toPercentageRgb: function() { - return { r: mathRound(bound01(this._r, 255) * 100) + "%", g: mathRound(bound01(this._g, 255) * 100) + "%", b: mathRound(bound01(this._b, 255) * 100) + "%", a: this._a }; - }, - toPercentageRgbString: function() { - return (this._a == 1) ? - "rgb(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%)" : - "rgba(" + mathRound(bound01(this._r, 255) * 100) + "%, " + mathRound(bound01(this._g, 255) * 100) + "%, " + mathRound(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; - }, - toName: function() { - if (this._a === 0) { - return "transparent"; - } - - if (this._a < 1) { - return false; - } + if (optionName === 'preferredFormat') { + currentPreferredFormat = opts.preferredFormat; + } + applyOptions(); + } - return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; - }, - toFilter: function(secondColor) { - var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a); - var secondHex8String = hex8String; - var gradientType = this._gradientType ? "GradientType = 1, " : ""; + function enable() { + disabled = false; + boundElement.attr('disabled', false); + offsetElement.removeClass('sp-disabled'); + } - if (secondColor) { - var s = tinycolor(secondColor); - secondHex8String = s.toHex8String(); - } + function disable() { + hide(); + disabled = true; + boundElement.attr('disabled', true); + offsetElement.addClass('sp-disabled'); + } - return "progid:DXImageTransform.Microsoft.gradient("+gradientType+"startColorstr="+hex8String+",endColorstr="+secondHex8String+")"; - }, - toString: function(format) { - var formatSet = !!format; - format = format || this._format; - - var formattedString = false; - var hasAlpha = this._a < 1 && this._a >= 0; - var needsAlphaFormat = !formatSet && hasAlpha && (format === "hex" || format === "hex6" || format === "hex3" || format === "name"); - - if (needsAlphaFormat) { - // Special case for "transparent", all other non-alpha formats - // will return rgba when there is transparency. - if (format === "name" && this._a === 0) { - return this.toName(); - } - return this.toRgbString(); - } - if (format === "rgb") { - formattedString = this.toRgbString(); - } - if (format === "prgb") { - formattedString = this.toPercentageRgbString(); - } - if (format === "hex" || format === "hex6") { - formattedString = this.toHexString(); - } - if (format === "hex3") { - formattedString = this.toHexString(true); - } - if (format === "hex8") { - formattedString = this.toHex8String(); - } - if (format === "name") { - formattedString = this.toName(); - } - if (format === "hsl") { - formattedString = this.toHslString(); - } - if (format === "hsv") { - formattedString = this.toHsvString(); - } - - return formattedString || this.toHexString(); - }, + function setOffset(coord) { + opts.offset = coord; + reflow(); + } - _applyModification: function(fn, args) { - var color = fn.apply(null, [this].concat([].slice.call(args))); - this._r = color._r; - this._g = color._g; - this._b = color._b; - this.setAlpha(color._a); - return this; - }, - lighten: function() { - return this._applyModification(lighten, arguments); - }, - brighten: function() { - return this._applyModification(brighten, arguments); - }, - darken: function() { - return this._applyModification(darken, arguments); - }, - desaturate: function() { - return this._applyModification(desaturate, arguments); - }, - saturate: function() { - return this._applyModification(saturate, arguments); - }, - greyscale: function() { - return this._applyModification(greyscale, arguments); - }, - spin: function() { - return this._applyModification(spin, arguments); - }, + initialize(); + + var spect = { + show: show, + hide: hide, + toggle: toggle, + reflow: reflow, + option: option, + enable: enable, + disable: disable, + offset: setOffset, + set: function(c) { + set(c); + updateOriginalInput(); + }, + get: get, + destroy: destroy, + container: container + }; - _applyCombination: function(fn, args) { - return fn.apply(null, [this].concat([].slice.call(args))); - }, - analogous: function() { - return this._applyCombination(analogous, arguments); - }, - complement: function() { - return this._applyCombination(complement, arguments); - }, - monochromatic: function() { - return this._applyCombination(monochromatic, arguments); - }, - splitcomplement: function() { - return this._applyCombination(splitcomplement, arguments); - }, - triad: function() { - return this._applyCombination(triad, arguments); - }, - tetrad: function() { - return this._applyCombination(tetrad, arguments); - } + spect.id = spectrums.push(spect) - 1; + + return spect; + } + + /** + * checkOffset - get the offset below/above and left/right element depending on screen position + * Thanks https://github.com/jquery/jquery-ui/blob/master/ui/jquery.ui.datepicker.js + */ + function getOffset(picker, input) { + var extraY = 0; + var dpWidth = picker.outerWidth(); + var dpHeight = picker.outerHeight(); + var inputHeight = input.outerHeight(); + var doc = picker[0].ownerDocument; + var docElem = doc.documentElement; + var cW = docElem.clientWidth; + var cH = docElem.clientHeight; + var scL = $(doc).scrollLeft(); + var scT = $(doc).scrollTop(); + var viewWidth = cW + scL; + var viewHeight = cH + scT; + var offset = input.offset(); + + offset.top += inputHeight; + + offset.left -= Math.min( + offset.left, + offset.left + dpWidth > viewWidth && viewWidth > dpWidth + ? Math.abs(offset.left + dpWidth - viewWidth) + : 0 + ); + + offset.top -= Math.min( + offset.top, + offset.top + dpHeight > viewHeight && viewHeight > dpHeight + ? Math.abs(dpHeight + inputHeight - extraY) + : extraY + ); + + return offset; + } + + /** + * noop - do nothing + */ + function noop() {} + + /** + * stopPropagation - makes the code only doing this a little easier to read in line + */ + function stopPropagation(e) { + e.stopPropagation(); + } + + /** + * Create a function bound to a given object + * Thanks to underscore.js + */ + function bind(func, obj) { + var slice = Array.prototype.slice; + var args = slice.call(arguments, 2); + return function() { + return func.apply(obj, args.concat(slice.call(arguments))); }; + } + + /** + * Lightweight drag helper. Handles containment within the element, so that + * when dragging, the x is within [0,element.width] and y is within [0,element.height] + */ + function draggable(element, onmove, onstart, onstop) { + onmove = onmove || function() {}; + onstart = onstart || function() {}; + onstop = onstop || function() {}; + var doc = document; + var dragging = false; + var offset = {}; + var maxHeight = 0; + var maxWidth = 0; + var hasTouch = 'ontouchstart' in window; + + var duringDragEvents = {}; + duringDragEvents['selectstart'] = prevent; + duringDragEvents['dragstart'] = prevent; + duringDragEvents['touchmove mousemove'] = move; + duringDragEvents['touchend mouseup'] = stop; + + function prevent(e) { + if (e.stopPropagation) { + e.stopPropagation(); + } + if (e.preventDefault) { + e.preventDefault(); + } + e.returnValue = false; + } - // If input is an object, force 1 into "1.0" to handle ratios properly - // String input requires "1.0" as input, so 1 will be treated as 1 - tinycolor.fromRatio = function(color, opts) { - if (typeof color == "object") { - var newColor = {}; - for (var i in color) { - if (color.hasOwnProperty(i)) { - if (i === "a") { - newColor[i] = color[i]; - } - else { - newColor[i] = convertToPercentage(color[i]); - } - } - } - color = newColor; + function move(e) { + if (dragging) { + // Mouseup happened outside of window + if (IE && doc.documentMode < 9 && !e.button) { + return stop(); } - return tinycolor(color, opts); - }; + var t0 = + e.originalEvent && + e.originalEvent.touches && + e.originalEvent.touches[0]; + var pageX = (t0 && t0.pageX) || e.pageX; + var pageY = (t0 && t0.pageY) || e.pageY; - // Given a string or object, convert that input to RGB - // Possible string inputs: - // - // "red" - // "#f00" or "f00" - // "#ff0000" or "ff0000" - // "#ff000000" or "ff000000" - // "rgb 255 0 0" or "rgb (255, 0, 0)" - // "rgb 1.0 0 0" or "rgb (1, 0, 0)" - // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" - // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" - // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" - // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" - // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" - // - function inputToRGB(color) { - - var rgb = { r: 0, g: 0, b: 0 }; - var a = 1; - var ok = false; - var format = false; - - if (typeof color == "string") { - color = stringInputToObject(color); - } + var dragX = Math.max(0, Math.min(pageX - offset.left, maxWidth)); + var dragY = Math.max(0, Math.min(pageY - offset.top, maxHeight)); - if (typeof color == "object") { - if (color.hasOwnProperty("r") && color.hasOwnProperty("g") && color.hasOwnProperty("b")) { - rgb = rgbToRgb(color.r, color.g, color.b); - ok = true; - format = String(color.r).substr(-1) === "%" ? "prgb" : "rgb"; - } - else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("v")) { - color.s = convertToPercentage(color.s); - color.v = convertToPercentage(color.v); - rgb = hsvToRgb(color.h, color.s, color.v); - ok = true; - format = "hsv"; - } - else if (color.hasOwnProperty("h") && color.hasOwnProperty("s") && color.hasOwnProperty("l")) { - color.s = convertToPercentage(color.s); - color.l = convertToPercentage(color.l); - rgb = hslToRgb(color.h, color.s, color.l); - ok = true; - format = "hsl"; - } - - if (color.hasOwnProperty("a")) { - a = color.a; - } + if (hasTouch) { + // Stop scrolling in iOS + prevent(e); } - a = boundAlpha(a); - - return { - ok: ok, - format: color.format || format, - r: mathMin(255, mathMax(rgb.r, 0)), - g: mathMin(255, mathMax(rgb.g, 0)), - b: mathMin(255, mathMax(rgb.b, 0)), - a: a - }; + onmove.apply(element, [dragX, dragY, e]); + } } + function start(e) { + var rightclick = e.which ? e.which == 3 : e.button == 2; - // Conversion Functions - // -------------------- + if (!rightclick && !dragging) { + if (onstart.apply(element, arguments) !== false) { + dragging = true; + maxHeight = $(element).height(); + maxWidth = $(element).width(); + offset = $(element).offset(); - // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: - // - - // `rgbToRgb` - // Handle bounds / percentage checking to conform to CSS color spec - // - // *Assumes:* r, g, b in [0, 255] or [0, 1] - // *Returns:* { r, g, b } in [0, 255] - function rgbToRgb(r, g, b){ - return { - r: bound01(r, 255) * 255, - g: bound01(g, 255) * 255, - b: bound01(b, 255) * 255 - }; - } + $(doc).bind(duringDragEvents); + $(doc.body).addClass('sp-dragging'); - // `rgbToHsl` - // Converts an RGB color value to HSL. - // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] - // *Returns:* { h, s, l } in [0,1] - function rgbToHsl(r, g, b) { + move(e); - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); - - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, l = (max + min) / 2; - - if(max == min) { - h = s = 0; // achromatic - } - else { - var d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; - } - - h /= 6; + prevent(e); } - - return { h: h, s: s, l: l }; + } } - // `hslToRgb` - // Converts an HSL color value to RGB. - // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] - // *Returns:* { r, g, b } in the set [0, 255] - function hslToRgb(h, s, l) { - var r, g, b; - - h = bound01(h, 360); - s = bound01(s, 100); - l = bound01(l, 100); - - function hue2rgb(p, q, t) { - if(t < 0) t += 1; - if(t > 1) t -= 1; - if(t < 1/6) return p + (q - p) * 6 * t; - if(t < 1/2) return q; - if(t < 2/3) return p + (q - p) * (2/3 - t) * 6; - return p; - } - - if(s === 0) { - r = g = b = l; // achromatic - } - else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hue2rgb(p, q, h + 1/3); - g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1/3); - } - - return { r: r * 255, g: g * 255, b: b * 255 }; + function stop() { + if (dragging) { + $(doc).unbind(duringDragEvents); + $(doc.body).removeClass('sp-dragging'); + + // Wait a tick before notifying observers to allow the click event + // to fire in Chrome. + setTimeout(function() { + onstop.apply(element, arguments); + }, 0); + } + dragging = false; } - // `rgbToHsv` - // Converts an RGB color value to HSV - // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] - // *Returns:* { h, s, v } in [0,1] - function rgbToHsv(r, g, b) { - - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); - - var max = mathMax(r, g, b), min = mathMin(r, g, b); - var h, s, v = max; - - var d = max - min; - s = max === 0 ? 0 : d / max; + $(element).bind('touchstart mousedown', start); + } + + function throttle(func, wait, debounce) { + var timeout; + return function() { + var context = this, + args = arguments; + var throttler = function() { + timeout = null; + func.apply(context, args); + }; + if (debounce) clearTimeout(timeout); + if (debounce || !timeout) timeout = setTimeout(throttler, wait); + }; + } + + function inputTypeColorSupport() { + return $.fn.spectrum.inputTypeColorSupport(); + } + + /** + * Define a jQuery plugin + */ + var dataID = 'spectrum.id'; + $.fn.spectrum = function(opts, extra) { + if (typeof opts == 'string') { + var returnValue = this; + var args = Array.prototype.slice.call(arguments, 1); + + this.each(function() { + var spect = spectrums[$(this).data(dataID)]; + if (spect) { + var method = spect[opts]; + if (!method) { + throw new Error("Spectrum: no such method: '" + opts + "'"); + } + + if (opts == 'get') { + returnValue = spect.get(); + } else if (opts == 'container') { + returnValue = spect.container; + } else if (opts == 'option') { + returnValue = spect.option.apply(spect, args); + } else if (opts == 'destroy') { + spect.destroy(); + $(this).removeData(dataID); + } else { + method.apply(spect, args); + } + } + }); + + return returnValue; + } - if(max == min) { - h = 0; // achromatic - } - else { - switch(max) { - case r: h = (g - b) / d + (g < b ? 6 : 0); break; - case g: h = (b - r) / d + 2; break; - case b: h = (r - g) / d + 4; break; - } - h /= 6; - } - return { h: h, s: s, v: v }; - } - - // `hsvToRgb` - // Converts an HSV color value to RGB. - // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] - // *Returns:* { r, g, b } in the set [0, 255] - function hsvToRgb(h, s, v) { - - h = bound01(h, 360) * 6; - s = bound01(s, 100); - v = bound01(v, 100); - - var i = math.floor(h), - f = h - i, - p = v * (1 - s), - q = v * (1 - f * s), - t = v * (1 - (1 - f) * s), - mod = i % 6, - r = [v, q, p, p, t, v][mod], - g = [t, v, v, q, p, p][mod], - b = [p, p, t, v, v, q][mod]; - - return { r: r * 255, g: g * 255, b: b * 255 }; - } - - // `rgbToHex` - // Converts an RGB color to hex - // Assumes r, g, and b are contained in the set [0, 255] - // Returns a 3 or 6 character hex - function rgbToHex(r, g, b, allow3Char) { - - var hex = [ - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; - - // Return a 3 character hex if possible - if (allow3Char && hex[0].charAt(0) == hex[0].charAt(1) && hex[1].charAt(0) == hex[1].charAt(1) && hex[2].charAt(0) == hex[2].charAt(1)) { - return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); - } + // Initializing a new instance of spectrum + return this.spectrum('destroy').each(function() { + var options = $.extend({}, opts, $(this).data()); + var spect = spectrum(this, options); + $(this).data(dataID, spect.id); + }); + }; + + $.fn.spectrum.load = true; + $.fn.spectrum.loadOpts = {}; + $.fn.spectrum.draggable = draggable; + $.fn.spectrum.defaults = defaultOpts; + $.fn.spectrum.inputTypeColorSupport = function inputTypeColorSupport() { + if (typeof inputTypeColorSupport._cachedResult === 'undefined') { + var colorInput = $("")[0]; // if color element is supported, value will default to not null + inputTypeColorSupport._cachedResult = + colorInput.type === 'color' && colorInput.value !== ''; + } + return inputTypeColorSupport._cachedResult; + }; + + $.spectrum = {}; + $.spectrum.localization = {}; + $.spectrum.palettes = {}; + + $.fn.spectrum.processNativeColorInputs = function() { + var colorInputs = $('input[type=color]'); + if (colorInputs.length && !inputTypeColorSupport()) { + colorInputs.spectrum({ + preferredFormat: 'hex6' + }); + } + }; + + // TinyColor v1.1.2 + // https://github.com/bgrins/TinyColor + // Brian Grinstead, MIT License + + //(function() { + + var trimLeft = /^[\s,#]+/, + trimRight = /\s+$/, + tinyCounter = 0, + math = Math, + mathRound = math.round, + mathMin = math.min, + mathMax = math.max, + mathRandom = math.random; + + var tinycolor = function(color, opts) { + color = color ? color : ''; + opts = opts || {}; + + // If input is already a tinycolor, return itself + if (color instanceof tinycolor) { + return color; + } + // If we are called as a function, call using new instead + if (!(this instanceof tinycolor)) { + return new tinycolor(color, opts); + } - return hex.join(""); + var rgb = inputToRGB(color); + (this._originalInput = color), + (this._r = rgb.r), + (this._g = rgb.g), + (this._b = rgb.b), + (this._a = rgb.a), + (this._roundA = mathRound(100 * this._a) / 100), + (this._format = opts.format || rgb.format); + this._gradientType = opts.gradientType; + + // Don't let the range of [0,255] come back in [0,1]. + // Potentially lose a little bit of precision here, but will fix issues where + // .5 gets interpreted as half of the total, instead of half of 1 + // If it was supposed to be 128, this was already taken care of by `inputToRgb` + if (this._r < 1) { + this._r = mathRound(this._r); + } + if (this._g < 1) { + this._g = mathRound(this._g); + } + if (this._b < 1) { + this._b = mathRound(this._b); } - // `rgbaToHex` - // Converts an RGBA color plus alpha transparency to hex - // Assumes r, g, b and a are contained in the set [0, 255] - // Returns an 8 character hex - function rgbaToHex(r, g, b, a) { - var hex = [ - pad2(convertDecimalToHex(a)), - pad2(mathRound(r).toString(16)), - pad2(mathRound(g).toString(16)), - pad2(mathRound(b).toString(16)) - ]; + this._ok = rgb.ok; + this._tc_id = tinyCounter++; + }; - return hex.join(""); - } + tinycolor.prototype = { + isDark: function() { + return this.getBrightness() < 128; + }, + isLight: function() { + return !this.isDark(); + }, + isValid: function() { + return this._ok; + }, + getOriginalInput: function() { + return this._originalInput; + }, + getFormat: function() { + return this._format; + }, + getAlpha: function() { + return this._a; + }, + getBrightness: function() { + var rgb = this.toRgb(); + return (rgb.r * 299 + rgb.g * 587 + rgb.b * 114) / 1000; + }, + setAlpha: function(value) { + this._a = boundAlpha(value); + this._roundA = mathRound(100 * this._a) / 100; + return this; + }, + toHsv: function() { + var hsv = rgbToHsv(this._r, this._g, this._b); + return { h: hsv.h * 360, s: hsv.s, v: hsv.v, a: this._a }; + }, + toHsvString: function() { + var hsv = rgbToHsv(this._r, this._g, this._b); + var h = mathRound(hsv.h * 360), + s = mathRound(hsv.s * 100), + v = mathRound(hsv.v * 100); + return this._a == 1 + ? 'hsv(' + h + ', ' + s + '%, ' + v + '%)' + : 'hsva(' + h + ', ' + s + '%, ' + v + '%, ' + this._roundA + ')'; + }, + toHsl: function() { + var hsl = rgbToHsl(this._r, this._g, this._b); + return { h: hsl.h * 360, s: hsl.s, l: hsl.l, a: this._a }; + }, + toHslString: function() { + var hsl = rgbToHsl(this._r, this._g, this._b); + var h = mathRound(hsl.h * 360), + s = mathRound(hsl.s * 100), + l = mathRound(hsl.l * 100); + return this._a == 1 + ? 'hsl(' + h + ', ' + s + '%, ' + l + '%)' + : 'hsla(' + h + ', ' + s + '%, ' + l + '%, ' + this._roundA + ')'; + }, + toHex: function(allow3Char) { + return rgbToHex(this._r, this._g, this._b, allow3Char); + }, + toHexString: function(allow3Char) { + return '#' + this.toHex(allow3Char); + }, + toHex8: function() { + return rgbaToHex(this._r, this._g, this._b, this._a); + }, + toHex8String: function() { + return '#' + this.toHex8(); + }, + toRgb: function() { + return { + r: mathRound(this._r), + g: mathRound(this._g), + b: mathRound(this._b), + a: this._a + }; + }, + toRgbString: function() { + return this._a == 1 + ? 'rgb(' + + mathRound(this._r) + + ', ' + + mathRound(this._g) + + ', ' + + mathRound(this._b) + + ')' + : 'rgba(' + + mathRound(this._r) + + ', ' + + mathRound(this._g) + + ', ' + + mathRound(this._b) + + ', ' + + this._roundA + + ')'; + }, + toPercentageRgb: function() { + return { + r: mathRound(bound01(this._r, 255) * 100) + '%', + g: mathRound(bound01(this._g, 255) * 100) + '%', + b: mathRound(bound01(this._b, 255) * 100) + '%', + a: this._a + }; + }, + toPercentageRgbString: function() { + return this._a == 1 + ? 'rgb(' + + mathRound(bound01(this._r, 255) * 100) + + '%, ' + + mathRound(bound01(this._g, 255) * 100) + + '%, ' + + mathRound(bound01(this._b, 255) * 100) + + '%)' + : 'rgba(' + + mathRound(bound01(this._r, 255) * 100) + + '%, ' + + mathRound(bound01(this._g, 255) * 100) + + '%, ' + + mathRound(bound01(this._b, 255) * 100) + + '%, ' + + this._roundA + + ')'; + }, + toName: function() { + if (this._a === 0) { + return 'transparent'; + } - // `equals` - // Can be called with any tinycolor input - tinycolor.equals = function (color1, color2) { - if (!color1 || !color2) { return false; } - return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); - }; - tinycolor.random = function() { - return tinycolor.fromRatio({ - r: mathRandom(), - g: mathRandom(), - b: mathRandom() - }); - }; + if (this._a < 1) { + return false; + } + return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; + }, + toFilter: function(secondColor) { + var hex8String = '#' + rgbaToHex(this._r, this._g, this._b, this._a); + var secondHex8String = hex8String; + var gradientType = this._gradientType ? 'GradientType = 1, ' : ''; + + if (secondColor) { + var s = tinycolor(secondColor); + secondHex8String = s.toHex8String(); + } + + return ( + 'progid:DXImageTransform.Microsoft.gradient(' + + gradientType + + 'startColorstr=' + + hex8String + + ',endColorstr=' + + secondHex8String + + ')' + ); + }, + toString: function(format) { + var formatSet = !!format; + format = format || this._format; + + var formattedString = false; + var hasAlpha = this._a < 1 && this._a >= 0; + var needsAlphaFormat = + !formatSet && + hasAlpha && + (format === 'hex' || + format === 'hex6' || + format === 'hex3' || + format === 'name'); + + if (needsAlphaFormat) { + // Special case for "transparent", all other non-alpha formats + // will return rgba when there is transparency. + if (format === 'name' && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); + } + if (format === 'rgb') { + formattedString = this.toRgbString(); + } + if (format === 'prgb') { + formattedString = this.toPercentageRgbString(); + } + if (format === 'hex' || format === 'hex6') { + formattedString = this.toHexString(); + } + if (format === 'hex3') { + formattedString = this.toHexString(true); + } + if (format === 'hex8') { + formattedString = this.toHex8String(); + } + if (format === 'name') { + formattedString = this.toName(); + } + if (format === 'hsl') { + formattedString = this.toHslString(); + } + if (format === 'hsv') { + formattedString = this.toHsvString(); + } + + return formattedString || this.toHexString(); + }, - // Modification Functions - // ---------------------- - // Thanks to less.js for some of the basics here - // + _applyModification: function(fn, args) { + var color = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color._r; + this._g = color._g; + this._b = color._b; + this.setAlpha(color._a); + return this; + }, + lighten: function() { + return this._applyModification(lighten, arguments); + }, + brighten: function() { + return this._applyModification(brighten, arguments); + }, + darken: function() { + return this._applyModification(darken, arguments); + }, + desaturate: function() { + return this._applyModification(desaturate, arguments); + }, + saturate: function() { + return this._applyModification(saturate, arguments); + }, + greyscale: function() { + return this._applyModification(greyscale, arguments); + }, + spin: function() { + return this._applyModification(spin, arguments); + }, - function desaturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s -= amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); + _applyCombination: function(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function() { + return this._applyCombination(analogous, arguments); + }, + complement: function() { + return this._applyCombination(complement, arguments); + }, + monochromatic: function() { + return this._applyCombination(monochromatic, arguments); + }, + splitcomplement: function() { + return this._applyCombination(splitcomplement, arguments); + }, + triad: function() { + return this._applyCombination(triad, arguments); + }, + tetrad: function() { + return this._applyCombination(tetrad, arguments); } - - function saturate(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.s += amount / 100; - hsl.s = clamp01(hsl.s); - return tinycolor(hsl); + }; + + // If input is an object, force 1 into "1.0" to handle ratios properly + // String input requires "1.0" as input, so 1 will be treated as 1 + tinycolor.fromRatio = function(color, opts) { + if (typeof color == 'object') { + var newColor = {}; + for (var i in color) { + if (color.hasOwnProperty(i)) { + if (i === 'a') { + newColor[i] = color[i]; + } else { + newColor[i] = convertToPercentage(color[i]); + } + } + } + color = newColor; } - function greyscale(color) { - return tinycolor(color).desaturate(100); + return tinycolor(color, opts); + }; + + // Given a string or object, convert that input to RGB + // Possible string inputs: + // + // "red" + // "#f00" or "f00" + // "#ff0000" or "ff0000" + // "#ff000000" or "ff000000" + // "rgb 255 0 0" or "rgb (255, 0, 0)" + // "rgb 1.0 0 0" or "rgb (1, 0, 0)" + // "rgba (255, 0, 0, 1)" or "rgba 255, 0, 0, 1" + // "rgba (1.0, 0, 0, 1)" or "rgba 1.0, 0, 0, 1" + // "hsl(0, 100%, 50%)" or "hsl 0 100% 50%" + // "hsla(0, 100%, 50%, 1)" or "hsla 0 100% 50%, 1" + // "hsv(0, 100%, 100%)" or "hsv 0 100% 100%" + // + function inputToRGB(color) { + var rgb = { r: 0, g: 0, b: 0 }; + var a = 1; + var ok = false; + var format = false; + + if (typeof color == 'string') { + color = stringInputToObject(color); } - function lighten (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l += amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); + if (typeof color == 'object') { + if ( + color.hasOwnProperty('r') && + color.hasOwnProperty('g') && + color.hasOwnProperty('b') + ) { + rgb = rgbToRgb(color.r, color.g, color.b); + ok = true; + format = String(color.r).substr(-1) === '%' ? 'prgb' : 'rgb'; + } else if ( + color.hasOwnProperty('h') && + color.hasOwnProperty('s') && + color.hasOwnProperty('v') + ) { + color.s = convertToPercentage(color.s); + color.v = convertToPercentage(color.v); + rgb = hsvToRgb(color.h, color.s, color.v); + ok = true; + format = 'hsv'; + } else if ( + color.hasOwnProperty('h') && + color.hasOwnProperty('s') && + color.hasOwnProperty('l') + ) { + color.s = convertToPercentage(color.s); + color.l = convertToPercentage(color.l); + rgb = hslToRgb(color.h, color.s, color.l); + ok = true; + format = 'hsl'; + } + + if (color.hasOwnProperty('a')) { + a = color.a; + } } - function brighten(color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var rgb = tinycolor(color).toRgb(); - rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * - (amount / 100)))); - rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * - (amount / 100)))); - rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * - (amount / 100)))); - return tinycolor(rgb); - } + a = boundAlpha(a); - function darken (color, amount) { - amount = (amount === 0) ? 0 : (amount || 10); - var hsl = tinycolor(color).toHsl(); - hsl.l -= amount / 100; - hsl.l = clamp01(hsl.l); - return tinycolor(hsl); + return { + ok: ok, + format: color.format || format, + r: mathMin(255, mathMax(rgb.r, 0)), + g: mathMin(255, mathMax(rgb.g, 0)), + b: mathMin(255, mathMax(rgb.b, 0)), + a: a + }; + } + + // Conversion Functions + // -------------------- + + // `rgbToHsl`, `rgbToHsv`, `hslToRgb`, `hsvToRgb` modified from: + // + + // `rgbToRgb` + // Handle bounds / percentage checking to conform to CSS color spec + // + // *Assumes:* r, g, b in [0, 255] or [0, 1] + // *Returns:* { r, g, b } in [0, 255] + function rgbToRgb(r, g, b) { + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; + } + + // `rgbToHsl` + // Converts an RGB color value to HSL. + // *Assumes:* r, g, and b are contained in [0, 255] or [0, 1] + // *Returns:* { h, s, l } in [0,1] + function rgbToHsl(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + + var max = mathMax(r, g, b), + min = mathMin(r, g, b); + var h, + s, + l = (max + min) / 2; + + if (max == min) { + h = s = 0; // achromatic + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + + h /= 6; } - // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. - // Values outside of this range will be wrapped into this range. - function spin(color, amount) { - var hsl = tinycolor(color).toHsl(); - var hue = (mathRound(hsl.h) + amount) % 360; - hsl.h = hue < 0 ? 360 + hue : hue; - return tinycolor(hsl); + return { h: h, s: s, l: l }; + } + + // `hslToRgb` + // Converts an HSL color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and l are contained [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hslToRgb(h, s, l) { + var r, g, b; + + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + + function hue2rgb(p, q, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p + (q - p) * 6 * t; + if (t < 1 / 2) return q; + if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6; + return p; } - // Combination Functions - // --------------------- - // Thanks to jQuery xColor for some of the ideas behind these - // - - function complement(color) { - var hsl = tinycolor(color).toHsl(); - hsl.h = (hsl.h + 180) % 360; - return tinycolor(hsl); + if (s === 0) { + r = g = b = l; // achromatic + } else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); } - function triad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) - ]; + return { r: r * 255, g: g * 255, b: b * 255 }; + } + + // `rgbToHsv` + // Converts an RGB color value to HSV + // *Assumes:* r, g, and b are contained in the set [0, 255] or [0, 1] + // *Returns:* { h, s, v } in [0,1] + function rgbToHsv(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + + var max = mathMax(r, g, b), + min = mathMin(r, g, b); + var h, + s, + v = max; + + var d = max - min; + s = max === 0 ? 0 : d / max; + + if (max == min) { + h = 0; // achromatic + } else { + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; } - - function tetrad(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), - tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) - ]; + return { h: h, s: s, v: v }; + } + + // `hsvToRgb` + // Converts an HSV color value to RGB. + // *Assumes:* h is contained in [0, 1] or [0, 360] and s and v are contained in [0, 1] or [0, 100] + // *Returns:* { r, g, b } in the set [0, 255] + function hsvToRgb(h, s, v) { + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + + var i = math.floor(h), + f = h - i, + p = v * (1 - s), + q = v * (1 - f * s), + t = v * (1 - (1 - f) * s), + mod = i % 6, + r = [v, q, p, p, t, v][mod], + g = [t, v, v, q, p, p][mod], + b = [p, p, t, v, v, q][mod]; + + return { r: r * 255, g: g * 255, b: b * 255 }; + } + + // `rgbToHex` + // Converts an RGB color to hex + // Assumes r, g, and b are contained in the set [0, 255] + // Returns a 3 or 6 character hex + function rgbToHex(r, g, b, allow3Char) { + var hex = [ + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; + + // Return a 3 character hex if possible + if ( + allow3Char && + hex[0].charAt(0) == hex[0].charAt(1) && + hex[1].charAt(0) == hex[1].charAt(1) && + hex[2].charAt(0) == hex[2].charAt(1) + ) { + return hex[0].charAt(0) + hex[1].charAt(0) + hex[2].charAt(0); } - function splitcomplement(color) { - var hsl = tinycolor(color).toHsl(); - var h = hsl.h; - return [ - tinycolor(color), - tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l}), - tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l}) - ]; - } - - function analogous(color, results, slices) { - results = results || 6; - slices = slices || 30; - - var hsl = tinycolor(color).toHsl(); - var part = 360 / slices; - var ret = [tinycolor(color)]; - - for (hsl.h = ((hsl.h - (part * results >> 1)) + 720) % 360; --results; ) { - hsl.h = (hsl.h + part) % 360; - ret.push(tinycolor(hsl)); - } - return ret; + return hex.join(''); + } + // `rgbaToHex` + // Converts an RGBA color plus alpha transparency to hex + // Assumes r, g, b and a are contained in the set [0, 255] + // Returns an 8 character hex + function rgbaToHex(r, g, b, a) { + var hex = [ + pad2(convertDecimalToHex(a)), + pad2(mathRound(r).toString(16)), + pad2(mathRound(g).toString(16)), + pad2(mathRound(b).toString(16)) + ]; + + return hex.join(''); + } + + // `equals` + // Can be called with any tinycolor input + tinycolor.equals = function(color1, color2) { + if (!color1 || !color2) { + return false; } - - function monochromatic(color, results) { - results = results || 6; - var hsv = tinycolor(color).toHsv(); - var h = hsv.h, s = hsv.s, v = hsv.v; - var ret = []; - var modification = 1 / results; - - while (results--) { - ret.push(tinycolor({ h: h, s: s, v: v})); - v = (v + modification) % 1; - } - - return ret; + return tinycolor(color1).toRgbString() == tinycolor(color2).toRgbString(); + }; + tinycolor.random = function() { + return tinycolor.fromRatio({ + r: mathRandom(), + g: mathRandom(), + b: mathRandom() + }); + }; + + // Modification Functions + // ---------------------- + // Thanks to less.js for some of the basics here + // + + function desaturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s -= amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + + function saturate(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.s += amount / 100; + hsl.s = clamp01(hsl.s); + return tinycolor(hsl); + } + + function greyscale(color) { + return tinycolor(color).desaturate(100); + } + + function lighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l += amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + + function brighten(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var rgb = tinycolor(color).toRgb(); + rgb.r = mathMax(0, mathMin(255, rgb.r - mathRound(255 * -(amount / 100)))); + rgb.g = mathMax(0, mathMin(255, rgb.g - mathRound(255 * -(amount / 100)))); + rgb.b = mathMax(0, mathMin(255, rgb.b - mathRound(255 * -(amount / 100)))); + return tinycolor(rgb); + } + + function darken(color, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl = tinycolor(color).toHsl(); + hsl.l -= amount / 100; + hsl.l = clamp01(hsl.l); + return tinycolor(hsl); + } + + // Spin takes a positive or negative amount within [-360, 360] indicating the change of hue. + // Values outside of this range will be wrapped into this range. + function spin(color, amount) { + var hsl = tinycolor(color).toHsl(); + var hue = (mathRound(hsl.h) + amount) % 360; + hsl.h = hue < 0 ? 360 + hue : hue; + return tinycolor(hsl); + } + + // Combination Functions + // --------------------- + // Thanks to jQuery xColor for some of the ideas behind these + // + + function complement(color) { + var hsl = tinycolor(color).toHsl(); + hsl.h = (hsl.h + 180) % 360; + return tinycolor(hsl); + } + + function triad(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 120) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 240) % 360, s: hsl.s, l: hsl.l }) + ]; + } + + function tetrad(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 90) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 180) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 270) % 360, s: hsl.s, l: hsl.l }) + ]; + } + + function splitcomplement(color) { + var hsl = tinycolor(color).toHsl(); + var h = hsl.h; + return [ + tinycolor(color), + tinycolor({ h: (h + 72) % 360, s: hsl.s, l: hsl.l }), + tinycolor({ h: (h + 216) % 360, s: hsl.s, l: hsl.l }) + ]; + } + + function analogous(color, results, slices) { + results = results || 6; + slices = slices || 30; + + var hsl = tinycolor(color).toHsl(); + var part = 360 / slices; + var ret = [tinycolor(color)]; + + for (hsl.h = (hsl.h - ((part * results) >> 1) + 720) % 360; --results; ) { + hsl.h = (hsl.h + part) % 360; + ret.push(tinycolor(hsl)); + } + return ret; + } + + function monochromatic(color, results) { + results = results || 6; + var hsv = tinycolor(color).toHsv(); + var h = hsv.h, + s = hsv.s, + v = hsv.v; + var ret = []; + var modification = 1 / results; + + while (results--) { + ret.push(tinycolor({ h: h, s: s, v: v })); + v = (v + modification) % 1; } - // Utility Functions - // --------------------- - - tinycolor.mix = function(color1, color2, amount) { - amount = (amount === 0) ? 0 : (amount || 50); - - var rgb1 = tinycolor(color1).toRgb(); - var rgb2 = tinycolor(color2).toRgb(); - - var p = amount / 100; - var w = p * 2 - 1; - var a = rgb2.a - rgb1.a; - - var w1; - - if (w * a == -1) { - w1 = w; - } else { - w1 = (w + a) / (1 + w * a); - } + return ret; + } - w1 = (w1 + 1) / 2; + // Utility Functions + // --------------------- - var w2 = 1 - w1; + tinycolor.mix = function(color1, color2, amount) { + amount = amount === 0 ? 0 : amount || 50; - var rgba = { - r: rgb2.r * w1 + rgb1.r * w2, - g: rgb2.g * w1 + rgb1.g * w2, - b: rgb2.b * w1 + rgb1.b * w2, - a: rgb2.a * p + rgb1.a * (1 - p) - }; + var rgb1 = tinycolor(color1).toRgb(); + var rgb2 = tinycolor(color2).toRgb(); - return tinycolor(rgba); - }; + var p = amount / 100; + var w = p * 2 - 1; + var a = rgb2.a - rgb1.a; + var w1; - // Readability Functions - // --------------------- - // - - // `readability` - // Analyze the 2 colors and returns an object with the following properties: - // `brightness`: difference in brightness between the two colors - // `color`: difference in color/hue between the two colors - tinycolor.readability = function(color1, color2) { - var c1 = tinycolor(color1); - var c2 = tinycolor(color2); - var rgb1 = c1.toRgb(); - var rgb2 = c2.toRgb(); - var brightnessA = c1.getBrightness(); - var brightnessB = c2.getBrightness(); - var colorDiff = ( - Math.max(rgb1.r, rgb2.r) - Math.min(rgb1.r, rgb2.r) + - Math.max(rgb1.g, rgb2.g) - Math.min(rgb1.g, rgb2.g) + - Math.max(rgb1.b, rgb2.b) - Math.min(rgb1.b, rgb2.b) - ); + if (w * a == -1) { + w1 = w; + } else { + w1 = (w + a) / (1 + w * a); + } - return { - brightness: Math.abs(brightnessA - brightnessB), - color: colorDiff - }; - }; + w1 = (w1 + 1) / 2; - // `readable` - // http://www.w3.org/TR/AERT#color-contrast - // Ensure that foreground and background color combinations provide sufficient contrast. - // *Example* - // tinycolor.isReadable("#000", "#111") => false - tinycolor.isReadable = function(color1, color2) { - var readability = tinycolor.readability(color1, color2); - return readability.brightness > 125 && readability.color > 500; - }; + var w2 = 1 - w1; - // `mostReadable` - // Given a base color and a list of possible foreground or background - // colors for that base, returns the most readable color. - // *Example* - // tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000" - tinycolor.mostReadable = function(baseColor, colorList) { - var bestColor = null; - var bestScore = 0; - var bestIsReadable = false; - for (var i=0; i < colorList.length; i++) { - - // We normalize both around the "acceptable" breaking point, - // but rank brightness constrast higher than hue. - - var readability = tinycolor.readability(baseColor, colorList[i]); - var readable = readability.brightness > 125 && readability.color > 500; - var score = 3 * (readability.brightness / 125) + (readability.color / 500); - - if ((readable && ! bestIsReadable) || - (readable && bestIsReadable && score > bestScore) || - ((! readable) && (! bestIsReadable) && score > bestScore)) { - bestIsReadable = readable; - bestScore = score; - bestColor = tinycolor(colorList[i]); - } - } - return bestColor; + var rgba = { + r: rgb2.r * w1 + rgb1.r * w2, + g: rgb2.g * w1 + rgb1.g * w2, + b: rgb2.b * w1 + rgb1.b * w2, + a: rgb2.a * p + rgb1.a * (1 - p) }; - - // Big List of Colors - // ------------------ - // - var names = tinycolor.names = { - aliceblue: "f0f8ff", - antiquewhite: "faebd7", - aqua: "0ff", - aquamarine: "7fffd4", - azure: "f0ffff", - beige: "f5f5dc", - bisque: "ffe4c4", - black: "000", - blanchedalmond: "ffebcd", - blue: "00f", - blueviolet: "8a2be2", - brown: "a52a2a", - burlywood: "deb887", - burntsienna: "ea7e5d", - cadetblue: "5f9ea0", - chartreuse: "7fff00", - chocolate: "d2691e", - coral: "ff7f50", - cornflowerblue: "6495ed", - cornsilk: "fff8dc", - crimson: "dc143c", - cyan: "0ff", - darkblue: "00008b", - darkcyan: "008b8b", - darkgoldenrod: "b8860b", - darkgray: "a9a9a9", - darkgreen: "006400", - darkgrey: "a9a9a9", - darkkhaki: "bdb76b", - darkmagenta: "8b008b", - darkolivegreen: "556b2f", - darkorange: "ff8c00", - darkorchid: "9932cc", - darkred: "8b0000", - darksalmon: "e9967a", - darkseagreen: "8fbc8f", - darkslateblue: "483d8b", - darkslategray: "2f4f4f", - darkslategrey: "2f4f4f", - darkturquoise: "00ced1", - darkviolet: "9400d3", - deeppink: "ff1493", - deepskyblue: "00bfff", - dimgray: "696969", - dimgrey: "696969", - dodgerblue: "1e90ff", - firebrick: "b22222", - floralwhite: "fffaf0", - forestgreen: "228b22", - fuchsia: "f0f", - gainsboro: "dcdcdc", - ghostwhite: "f8f8ff", - gold: "ffd700", - goldenrod: "daa520", - gray: "808080", - green: "008000", - greenyellow: "adff2f", - grey: "808080", - honeydew: "f0fff0", - hotpink: "ff69b4", - indianred: "cd5c5c", - indigo: "4b0082", - ivory: "fffff0", - khaki: "f0e68c", - lavender: "e6e6fa", - lavenderblush: "fff0f5", - lawngreen: "7cfc00", - lemonchiffon: "fffacd", - lightblue: "add8e6", - lightcoral: "f08080", - lightcyan: "e0ffff", - lightgoldenrodyellow: "fafad2", - lightgray: "d3d3d3", - lightgreen: "90ee90", - lightgrey: "d3d3d3", - lightpink: "ffb6c1", - lightsalmon: "ffa07a", - lightseagreen: "20b2aa", - lightskyblue: "87cefa", - lightslategray: "789", - lightslategrey: "789", - lightsteelblue: "b0c4de", - lightyellow: "ffffe0", - lime: "0f0", - limegreen: "32cd32", - linen: "faf0e6", - magenta: "f0f", - maroon: "800000", - mediumaquamarine: "66cdaa", - mediumblue: "0000cd", - mediumorchid: "ba55d3", - mediumpurple: "9370db", - mediumseagreen: "3cb371", - mediumslateblue: "7b68ee", - mediumspringgreen: "00fa9a", - mediumturquoise: "48d1cc", - mediumvioletred: "c71585", - midnightblue: "191970", - mintcream: "f5fffa", - mistyrose: "ffe4e1", - moccasin: "ffe4b5", - navajowhite: "ffdead", - navy: "000080", - oldlace: "fdf5e6", - olive: "808000", - olivedrab: "6b8e23", - orange: "ffa500", - orangered: "ff4500", - orchid: "da70d6", - palegoldenrod: "eee8aa", - palegreen: "98fb98", - paleturquoise: "afeeee", - palevioletred: "db7093", - papayawhip: "ffefd5", - peachpuff: "ffdab9", - peru: "cd853f", - pink: "ffc0cb", - plum: "dda0dd", - powderblue: "b0e0e6", - purple: "800080", - rebeccapurple: "663399", - red: "f00", - rosybrown: "bc8f8f", - royalblue: "4169e1", - saddlebrown: "8b4513", - salmon: "fa8072", - sandybrown: "f4a460", - seagreen: "2e8b57", - seashell: "fff5ee", - sienna: "a0522d", - silver: "c0c0c0", - skyblue: "87ceeb", - slateblue: "6a5acd", - slategray: "708090", - slategrey: "708090", - snow: "fffafa", - springgreen: "00ff7f", - steelblue: "4682b4", - tan: "d2b48c", - teal: "008080", - thistle: "d8bfd8", - tomato: "ff6347", - turquoise: "40e0d0", - violet: "ee82ee", - wheat: "f5deb3", - white: "fff", - whitesmoke: "f5f5f5", - yellow: "ff0", - yellowgreen: "9acd32" + return tinycolor(rgba); + }; + + // Readability Functions + // --------------------- + // + + // `readability` + // Analyze the 2 colors and returns an object with the following properties: + // `brightness`: difference in brightness between the two colors + // `color`: difference in color/hue between the two colors + tinycolor.readability = function(color1, color2) { + var c1 = tinycolor(color1); + var c2 = tinycolor(color2); + var rgb1 = c1.toRgb(); + var rgb2 = c2.toRgb(); + var brightnessA = c1.getBrightness(); + var brightnessB = c2.getBrightness(); + var colorDiff = + Math.max(rgb1.r, rgb2.r) - + Math.min(rgb1.r, rgb2.r) + + Math.max(rgb1.g, rgb2.g) - + Math.min(rgb1.g, rgb2.g) + + Math.max(rgb1.b, rgb2.b) - + Math.min(rgb1.b, rgb2.b); + + return { + brightness: Math.abs(brightnessA - brightnessB), + color: colorDiff }; - - // Make it easy to access colors via `hexNames[hex]` - var hexNames = tinycolor.hexNames = flip(names); - - - // Utilities - // --------- - - // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` - function flip(o) { - var flipped = { }; - for (var i in o) { - if (o.hasOwnProperty(i)) { - flipped[o[i]] = i; - } - } - return flipped; + }; + + // `readable` + // http://www.w3.org/TR/AERT#color-contrast + // Ensure that foreground and background color combinations provide sufficient contrast. + // *Example* + // tinycolor.isReadable("#000", "#111") => false + tinycolor.isReadable = function(color1, color2) { + var readability = tinycolor.readability(color1, color2); + return readability.brightness > 125 && readability.color > 500; + }; + + // `mostReadable` + // Given a base color and a list of possible foreground or background + // colors for that base, returns the most readable color. + // *Example* + // tinycolor.mostReadable("#123", ["#fff", "#000"]) => "#000" + tinycolor.mostReadable = function(baseColor, colorList) { + var bestColor = null; + var bestScore = 0; + var bestIsReadable = false; + for (var i = 0; i < colorList.length; i++) { + // We normalize both around the "acceptable" breaking point, + // but rank brightness constrast higher than hue. + + var readability = tinycolor.readability(baseColor, colorList[i]); + var readable = readability.brightness > 125 && readability.color > 500; + var score = 3 * (readability.brightness / 125) + readability.color / 500; + + if ( + (readable && !bestIsReadable) || + (readable && bestIsReadable && score > bestScore) || + (!readable && !bestIsReadable && score > bestScore) + ) { + bestIsReadable = readable; + bestScore = score; + bestColor = tinycolor(colorList[i]); + } } + return bestColor; + }; + + // Big List of Colors + // ------------------ + // + var names = (tinycolor.names = { + aliceblue: 'f0f8ff', + antiquewhite: 'faebd7', + aqua: '0ff', + aquamarine: '7fffd4', + azure: 'f0ffff', + beige: 'f5f5dc', + bisque: 'ffe4c4', + black: '000', + blanchedalmond: 'ffebcd', + blue: '00f', + blueviolet: '8a2be2', + brown: 'a52a2a', + burlywood: 'deb887', + burntsienna: 'ea7e5d', + cadetblue: '5f9ea0', + chartreuse: '7fff00', + chocolate: 'd2691e', + coral: 'ff7f50', + cornflowerblue: '6495ed', + cornsilk: 'fff8dc', + crimson: 'dc143c', + cyan: '0ff', + darkblue: '00008b', + darkcyan: '008b8b', + darkgoldenrod: 'b8860b', + darkgray: 'a9a9a9', + darkgreen: '006400', + darkgrey: 'a9a9a9', + darkkhaki: 'bdb76b', + darkmagenta: '8b008b', + darkolivegreen: '556b2f', + darkorange: 'ff8c00', + darkorchid: '9932cc', + darkred: '8b0000', + darksalmon: 'e9967a', + darkseagreen: '8fbc8f', + darkslateblue: '483d8b', + darkslategray: '2f4f4f', + darkslategrey: '2f4f4f', + darkturquoise: '00ced1', + darkviolet: '9400d3', + deeppink: 'ff1493', + deepskyblue: '00bfff', + dimgray: '696969', + dimgrey: '696969', + dodgerblue: '1e90ff', + firebrick: 'b22222', + floralwhite: 'fffaf0', + forestgreen: '228b22', + fuchsia: 'f0f', + gainsboro: 'dcdcdc', + ghostwhite: 'f8f8ff', + gold: 'ffd700', + goldenrod: 'daa520', + gray: '808080', + green: '008000', + greenyellow: 'adff2f', + grey: '808080', + honeydew: 'f0fff0', + hotpink: 'ff69b4', + indianred: 'cd5c5c', + indigo: '4b0082', + ivory: 'fffff0', + khaki: 'f0e68c', + lavender: 'e6e6fa', + lavenderblush: 'fff0f5', + lawngreen: '7cfc00', + lemonchiffon: 'fffacd', + lightblue: 'add8e6', + lightcoral: 'f08080', + lightcyan: 'e0ffff', + lightgoldenrodyellow: 'fafad2', + lightgray: 'd3d3d3', + lightgreen: '90ee90', + lightgrey: 'd3d3d3', + lightpink: 'ffb6c1', + lightsalmon: 'ffa07a', + lightseagreen: '20b2aa', + lightskyblue: '87cefa', + lightslategray: '789', + lightslategrey: '789', + lightsteelblue: 'b0c4de', + lightyellow: 'ffffe0', + lime: '0f0', + limegreen: '32cd32', + linen: 'faf0e6', + magenta: 'f0f', + maroon: '800000', + mediumaquamarine: '66cdaa', + mediumblue: '0000cd', + mediumorchid: 'ba55d3', + mediumpurple: '9370db', + mediumseagreen: '3cb371', + mediumslateblue: '7b68ee', + mediumspringgreen: '00fa9a', + mediumturquoise: '48d1cc', + mediumvioletred: 'c71585', + midnightblue: '191970', + mintcream: 'f5fffa', + mistyrose: 'ffe4e1', + moccasin: 'ffe4b5', + navajowhite: 'ffdead', + navy: '000080', + oldlace: 'fdf5e6', + olive: '808000', + olivedrab: '6b8e23', + orange: 'ffa500', + orangered: 'ff4500', + orchid: 'da70d6', + palegoldenrod: 'eee8aa', + palegreen: '98fb98', + paleturquoise: 'afeeee', + palevioletred: 'db7093', + papayawhip: 'ffefd5', + peachpuff: 'ffdab9', + peru: 'cd853f', + pink: 'ffc0cb', + plum: 'dda0dd', + powderblue: 'b0e0e6', + purple: '800080', + rebeccapurple: '663399', + red: 'f00', + rosybrown: 'bc8f8f', + royalblue: '4169e1', + saddlebrown: '8b4513', + salmon: 'fa8072', + sandybrown: 'f4a460', + seagreen: '2e8b57', + seashell: 'fff5ee', + sienna: 'a0522d', + silver: 'c0c0c0', + skyblue: '87ceeb', + slateblue: '6a5acd', + slategray: '708090', + slategrey: '708090', + snow: 'fffafa', + springgreen: '00ff7f', + steelblue: '4682b4', + tan: 'd2b48c', + teal: '008080', + thistle: 'd8bfd8', + tomato: 'ff6347', + turquoise: '40e0d0', + violet: 'ee82ee', + wheat: 'f5deb3', + white: 'fff', + whitesmoke: 'f5f5f5', + yellow: 'ff0', + yellowgreen: '9acd32' + }); + + // Make it easy to access colors via `hexNames[hex]` + var hexNames = (tinycolor.hexNames = flip(names)); + + // Utilities + // --------- + + // `{ 'name1': 'val1' }` becomes `{ 'val1': 'name1' }` + function flip(o) { + var flipped = {}; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; + } - // Return a valid alpha value [0,1] with all invalid values being set to 1 - function boundAlpha(a) { - a = parseFloat(a); + // Return a valid alpha value [0,1] with all invalid values being set to 1 + function boundAlpha(a) { + a = parseFloat(a); - if (isNaN(a) || a < 0 || a > 1) { - a = 1; - } - - return a; + if (isNaN(a) || a < 0 || a > 1) { + a = 1; } - // Take input from [0, n] and return it as [0, 1] - function bound01(n, max) { - if (isOnePointZero(n)) { n = "100%"; } - - var processPercent = isPercentage(n); - n = mathMin(max, mathMax(0, parseFloat(n))); + return a; + } - // Automatically convert percentage into number - if (processPercent) { - n = parseInt(n * max, 10) / 100; - } + // Take input from [0, n] and return it as [0, 1] + function bound01(n, max) { + if (isOnePointZero(n)) { + n = '100%'; + } - // Handle floating point rounding errors - if ((math.abs(n - max) < 0.000001)) { - return 1; - } + var processPercent = isPercentage(n); + n = mathMin(max, mathMax(0, parseFloat(n))); - // Convert into [0, 1] range if it isn't already - return (n % max) / parseFloat(max); + // Automatically convert percentage into number + if (processPercent) { + n = parseInt(n * max, 10) / 100; } - // Force a number between 0 and 1 - function clamp01(val) { - return mathMin(1, mathMax(0, val)); + // Handle floating point rounding errors + if (math.abs(n - max) < 0.000001) { + return 1; } - // Parse a base-16 hex value into a base-10 integer - function parseIntFromHex(val) { - return parseInt(val, 16); + // Convert into [0, 1] range if it isn't already + return (n % max) / parseFloat(max); + } + + // Force a number between 0 and 1 + function clamp01(val) { + return mathMin(1, mathMax(0, val)); + } + + // Parse a base-16 hex value into a base-10 integer + function parseIntFromHex(val) { + return parseInt(val, 16); + } + + // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 + // + function isOnePointZero(n) { + return typeof n == 'string' && n.indexOf('.') != -1 && parseFloat(n) === 1; + } + + // Check to see if string passed in is a percentage + function isPercentage(n) { + return typeof n === 'string' && n.indexOf('%') != -1; + } + + // Force a hex value to have 2 characters + function pad2(c) { + return c.length == 1 ? '0' + c : '' + c; + } + + // Replace a decimal with it's percentage value + function convertToPercentage(n) { + if (n <= 1) { + n = n * 100 + '%'; } - // Need to handle 1.0 as 100%, since once it is a number, there is no difference between it and 1 - // - function isOnePointZero(n) { - return typeof n == "string" && n.indexOf('.') != -1 && parseFloat(n) === 1; + return n; + } + + // Converts a decimal to a hex value + function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); + } + // Converts a hex value to a decimal + function convertHexToDecimal(h) { + return parseIntFromHex(h) / 255; + } + + var matchers = (function() { + // + var CSS_INTEGER = '[-\\+]?\\d+%?'; + + // + var CSS_NUMBER = '[-\\+]?\\d*\\.\\d+%?'; + + // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. + var CSS_UNIT = '(?:' + CSS_NUMBER + ')|(?:' + CSS_INTEGER + ')'; + + // Actual matching. + // Parentheses and commas are optional, but not required. + // Whitespace can take the place of commas or opening paren + var PERMISSIVE_MATCH3 = + '[\\s|\\(]+(' + + CSS_UNIT + + ')[,|\\s]+(' + + CSS_UNIT + + ')[,|\\s]+(' + + CSS_UNIT + + ')\\s*\\)?'; + var PERMISSIVE_MATCH4 = + '[\\s|\\(]+(' + + CSS_UNIT + + ')[,|\\s]+(' + + CSS_UNIT + + ')[,|\\s]+(' + + CSS_UNIT + + ')[,|\\s]+(' + + CSS_UNIT + + ')\\s*\\)?'; + + return { + rgb: new RegExp('rgb' + PERMISSIVE_MATCH3), + rgba: new RegExp('rgba' + PERMISSIVE_MATCH4), + hsl: new RegExp('hsl' + PERMISSIVE_MATCH3), + hsla: new RegExp('hsla' + PERMISSIVE_MATCH4), + hsv: new RegExp('hsv' + PERMISSIVE_MATCH3), + hsva: new RegExp('hsva' + PERMISSIVE_MATCH4), + hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; + })(); + + // `stringInputToObject` + // Permissive string parsing. Take in a number of formats, and output an object + // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` + function stringInputToObject(color) { + color = color + .replace(trimLeft, '') + .replace(trimRight, '') + .toLowerCase(); + var named = false; + if (names[color]) { + color = names[color]; + named = true; + } else if (color == 'transparent') { + return { r: 0, g: 0, b: 0, a: 0, format: 'name' }; } - // Check to see if string passed in is a percentage - function isPercentage(n) { - return typeof n === "string" && n.indexOf('%') != -1; + // Try to match string input using regular expressions. + // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] + // Just return an object and let the conversion functions handle that. + // This way the result will be the same whether the tinycolor is initialized with string or object. + var match; + if ((match = matchers.rgb.exec(color))) { + return { r: match[1], g: match[2], b: match[3] }; } - - // Force a hex value to have 2 characters - function pad2(c) { - return c.length == 1 ? '0' + c : '' + c; + if ((match = matchers.rgba.exec(color))) { + return { r: match[1], g: match[2], b: match[3], a: match[4] }; } - - // Replace a decimal with it's percentage value - function convertToPercentage(n) { - if (n <= 1) { - n = (n * 100) + "%"; - } - - return n; + if ((match = matchers.hsl.exec(color))) { + return { h: match[1], s: match[2], l: match[3] }; } - - // Converts a decimal to a hex value - function convertDecimalToHex(d) { - return Math.round(parseFloat(d) * 255).toString(16); + if ((match = matchers.hsla.exec(color))) { + return { h: match[1], s: match[2], l: match[3], a: match[4] }; } - // Converts a hex value to a decimal - function convertHexToDecimal(h) { - return (parseIntFromHex(h) / 255); + if ((match = matchers.hsv.exec(color))) { + return { h: match[1], s: match[2], v: match[3] }; } - - var matchers = (function() { - - // - var CSS_INTEGER = "[-\\+]?\\d+%?"; - - // - var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; - - // Allow positive/negative integer/number. Don't capture the either/or, just the entire outcome. - var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; - - // Actual matching. - // Parentheses and commas are optional, but not required. - // Whitespace can take the place of commas or opening paren - var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; - var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; - - return { - rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), - rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), - hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), - hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), - hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), - hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), - hex3: /^([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex6: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, - hex8: /^([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ - }; - })(); - - // `stringInputToObject` - // Permissive string parsing. Take in a number of formats, and output an object - // based on detected format. Returns `{ r, g, b }` or `{ h, s, l }` or `{ h, s, v}` - function stringInputToObject(color) { - - color = color.replace(trimLeft,'').replace(trimRight, '').toLowerCase(); - var named = false; - if (names[color]) { - color = names[color]; - named = true; - } - else if (color == 'transparent') { - return { r: 0, g: 0, b: 0, a: 0, format: "name" }; - } - - // Try to match string input using regular expressions. - // Keep most of the number bounding out of this function - don't worry about [0,1] or [0,100] or [0,360] - // Just return an object and let the conversion functions handle that. - // This way the result will be the same whether the tinycolor is initialized with string or object. - var match; - if ((match = matchers.rgb.exec(color))) { - return { r: match[1], g: match[2], b: match[3] }; - } - if ((match = matchers.rgba.exec(color))) { - return { r: match[1], g: match[2], b: match[3], a: match[4] }; - } - if ((match = matchers.hsl.exec(color))) { - return { h: match[1], s: match[2], l: match[3] }; - } - if ((match = matchers.hsla.exec(color))) { - return { h: match[1], s: match[2], l: match[3], a: match[4] }; - } - if ((match = matchers.hsv.exec(color))) { - return { h: match[1], s: match[2], v: match[3] }; - } - if ((match = matchers.hsva.exec(color))) { - return { h: match[1], s: match[2], v: match[3], a: match[4] }; - } - if ((match = matchers.hex8.exec(color))) { - return { - a: convertHexToDecimal(match[1]), - r: parseIntFromHex(match[2]), - g: parseIntFromHex(match[3]), - b: parseIntFromHex(match[4]), - format: named ? "name" : "hex8" - }; - } - if ((match = matchers.hex6.exec(color))) { - return { - r: parseIntFromHex(match[1]), - g: parseIntFromHex(match[2]), - b: parseIntFromHex(match[3]), - format: named ? "name" : "hex" - }; - } - if ((match = matchers.hex3.exec(color))) { - return { - r: parseIntFromHex(match[1] + '' + match[1]), - g: parseIntFromHex(match[2] + '' + match[2]), - b: parseIntFromHex(match[3] + '' + match[3]), - format: named ? "name" : "hex" - }; - } - - return false; + if ((match = matchers.hsva.exec(color))) { + return { h: match[1], s: match[2], v: match[3], a: match[4] }; + } + if ((match = matchers.hex8.exec(color))) { + return { + a: convertHexToDecimal(match[1]), + r: parseIntFromHex(match[2]), + g: parseIntFromHex(match[3]), + b: parseIntFromHex(match[4]), + format: named ? 'name' : 'hex8' + }; + } + if ((match = matchers.hex6.exec(color))) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named ? 'name' : 'hex' + }; + } + if ((match = matchers.hex3.exec(color))) { + return { + r: parseIntFromHex(match[1] + '' + match[1]), + g: parseIntFromHex(match[2] + '' + match[2]), + b: parseIntFromHex(match[3] + '' + match[3]), + format: named ? 'name' : 'hex' + }; } - window.tinycolor = tinycolor; - //})(); + return false; + } - $(function () { - if ($.fn.spectrum.load) { - $.fn.spectrum.processNativeColorInputs(); - } - }); + window.tinycolor = tinycolor; + //})(); + $(function() { + if ($.fn.spectrum.load) { + $.fn.spectrum.processNativeColorInputs(); + } + }); }); diff --git a/src/utils/Dragger.js b/src/utils/Dragger.js index 597af15232..9d28774d65 100644 --- a/src/utils/Dragger.js +++ b/src/utils/Dragger.js @@ -12,7 +12,6 @@ var getBoundingRect = (el, win) => { }; module.exports = { - // TODO move to opts setKey(keys, command) { //key(keys, command); @@ -25,9 +24,11 @@ module.exports = { */ getElementRect(el) { var posFetcher = this.opts.posFetcher || ''; - return posFetcher ? posFetcher(el, { - avoidFrameOffset: 1, - }) : getBoundingRect(el); + return posFetcher + ? posFetcher(el, { + avoidFrameOffset: 1 + }) + : getBoundingRect(el); }, /** @@ -67,7 +68,6 @@ module.exports = { this.el = el; this.handlers = this.opts.dragHandlers || [el]; - var elRect = this.getElementRect(el); //<-- TODO have wrong top:left this.elRect = elRect; this.startTop = elRect.top; @@ -75,7 +75,7 @@ module.exports = { // TODO init snapper - this.getDocumentEl().on('mousedown', this.handleMouseDown); + this.getDocumentEl().on('mousedown', this.handleMouseDown); }, /** @@ -98,12 +98,12 @@ module.exports = { // Start callback var onStart = this.opts.onStart; - if(typeof onStart === 'function') { + if (typeof onStart === 'function') { onStart(e, { docs, el: this.el, start: this.startPos, - elRect: this.elRect, + elRect: this.elRect }); } @@ -121,13 +121,13 @@ module.exports = { // Stop callback var onEnd = this.opts.onEnd; - if(typeof onEnd === 'function') { + if (typeof onEnd === 'function') { onEnd(e, { docs, delta: this.delta, end: { x: this.startLeft + this.delta.x, - y: this.startTop + this.delta.y, + y: this.startTop + this.delta.y } }); } @@ -203,10 +203,12 @@ module.exports = { */ getMousePos(e) { var mouseFetch = this.opts.mousePosFetcher; - return mouseFetch ? mouseFetch(e) : { - x: e.clientX, - y: e.clientY - }; + return mouseFetch + ? mouseFetch(e) + : { + x: e.clientX, + y: e.clientY + }; }, /** @@ -253,7 +255,7 @@ module.exports = { // Drag callback const onDrag = this.opts.onDrag; - if(typeof onDrag === 'function') { + if (typeof onDrag === 'function') { onDrag(e, { delta, current: { @@ -294,10 +296,10 @@ module.exports = { setX(xPos, { el, start: this.startLeft, - delta: x, + delta: x }); } else { - el.style.left = xPos + 'px'; + el.style.left = xPos + 'px'; } }, @@ -315,11 +317,10 @@ module.exports = { setY(yPos, { el, start: this.startTop, - delta: y, + delta: y }); } else { - el.style.top = yPos + 'px'; + el.style.top = yPos + 'px'; } - }, - + } }; diff --git a/src/utils/Resizer.js b/src/utils/Resizer.js index f35c560ad2..327d204aed 100644 --- a/src/utils/Resizer.js +++ b/src/utils/Resizer.js @@ -46,7 +46,7 @@ var defaultOpts = { cr: 1, // Center right bl: 1, // Bottom left bc: 1, // Bottom center - br: 1, // Bottom right + br: 1 // Bottom right }; var createHandler = (name, opts) => { @@ -69,18 +69,16 @@ var getBoundingRect = (el, win) => { }; class Resizer { - /** * Init the Resizer with options * @param {Object} options */ constructor(opts = {}) { this.setOptions(opts); - bindAll(this, 'handleKeyDown', 'handleMouseDown', 'move', 'stop') + bindAll(this, 'handleKeyDown', 'handleMouseDown', 'move', 'stop'); return this; } - /** * Get current connfiguration options * @return {Object} @@ -89,7 +87,6 @@ class Resizer { return this.opts; } - /** * Setup options * @param {Object} options @@ -122,8 +119,9 @@ class Resizer { // Create handlers const handlers = {}; - ['tl', 'tc', 'tr', 'cl', 'cr', 'bl', 'bc', 'br'].forEach(hdl => - handlers[hdl] = opts[hdl] ? createHandler(hdl, opts) : ''); + ['tl', 'tc', 'tr', 'cl', 'cr', 'bl', 'bc', 'br'].forEach( + hdl => (handlers[hdl] = opts[hdl] ? createHandler(hdl, opts) : '') + ); for (let n in handlers) { const handler = handlers[n]; @@ -238,13 +236,13 @@ class Resizer { t: rect.top, l: rect.left, w: rect.width, - h: rect.height, + h: rect.height }; this.rectDim = { t: rect.top, l: rect.left, w: rect.width, - h: rect.height, + h: rect.height }; this.startPos = { x: e.clientX, @@ -256,7 +254,8 @@ class Resizer { on(doc, 'mousemove', this.move); on(doc, 'keydown', this.handleKeyDown); on(doc, 'mouseup', this.stop); - isFunction(this.onStart) && this.onStart(e, {docs: doc, config, el, resizer}); + isFunction(this.onStart) && + this.onStart(e, { docs: doc, config, el, resizer }); this.move(e); } @@ -267,15 +266,17 @@ class Resizer { move(e) { const onMove = this.onMove; var mouseFetch = this.mousePosFetcher; - var currentPos = mouseFetch ? mouseFetch(e) : { - x: e.clientX, - y: e.clientY - }; + var currentPos = mouseFetch + ? mouseFetch(e) + : { + x: e.clientX, + y: e.clientY + }; this.currentPos = currentPos; this.delta = { x: currentPos.x - this.startPos.x, - y: currentPos.y - this.startPos.y, + y: currentPos.y - this.startPos.y }; this.keys = { shift: e.shiftKey, @@ -306,7 +307,7 @@ class Resizer { off(doc, 'keydown', this.handleKeyDown); off(doc, 'mouseup', this.stop); this.updateRect(1); - isFunction(this.onEnd) && this.onEnd(e, {docs: doc, config}); + isFunction(this.onEnd) && this.onEnd(e, { docs: doc, config }); } /** @@ -381,7 +382,7 @@ class Resizer { if (this.isHandler(el)) { this.selectedHandler = el; this.start(e); - }else if(el !== this.el){ + } else if (el !== this.el) { this.selectedHandler = ''; this.blur(); } @@ -409,8 +410,7 @@ class Resizer { h: startH }; - if (!data) - return; + if (!data) return; var attr = data.handlerAttr; if (~attr.indexOf('r')) { diff --git a/src/utils/Sorter.js b/src/utils/Sorter.js index 737a5e8a4c..36307504fe 100644 --- a/src/utils/Sorter.js +++ b/src/utils/Sorter.js @@ -3,10 +3,17 @@ import { on, off, matches } from 'utils/mixins'; const $ = Backbone.$; module.exports = Backbone.View.extend({ - initialize(opt) { this.opt = opt || {}; - _.bindAll(this,'startSort','onMove','endMove','rollback', 'udpateOffset', 'moveDragHelper'); + _.bindAll( + this, + 'startSort', + 'onMove', + 'endMove', + 'rollback', + 'udpateOffset', + 'moveDragHelper' + ); var o = opt || {}; this.elT = 0; this.elL = 0; @@ -43,7 +50,7 @@ module.exports = Backbone.View.extend({ this.canvasRelative = o.canvasRelative || 0; this.selectOnEnd = !o.avoidSelectOnEnd; - if(this.em && this.em.on){ + if (this.em && this.em.on) { this.em.on('change:canvasOffset', this.udpateOffset); this.udpateOffset(); } @@ -58,7 +65,6 @@ module.exports = Backbone.View.extend({ return this.el; }, - getDocuments() { const em = this.em; const canvasDoc = em && em.get('Canvas').getBody().ownerDocument; @@ -134,12 +140,14 @@ module.exports = Backbone.View.extend({ ev && this.moveDragHelper(ev); // Listen mouse move events - if(this.em) { + if (this.em) { $(this.em.get('Canvas').getBody().ownerDocument) - .off('mousemove', this.moveDragHelper).on('mousemove', this.moveDragHelper); + .off('mousemove', this.moveDragHelper) + .on('mousemove', this.moveDragHelper); } $(document) - .off('mousemove', this.moveDragHelper).on('mousemove', this.moveDragHelper); + .off('mousemove', this.moveDragHelper) + .on('mousemove', this.moveDragHelper); }, /** @@ -149,7 +157,7 @@ module.exports = Backbone.View.extend({ moveDragHelper(e) { const doc = e.target.ownerDocument; - if(!this.dragHelper || !doc) { + if (!this.dragHelper || !doc) { return; } @@ -174,11 +182,10 @@ module.exports = Backbone.View.extend({ posX = e.clientX; } - dragHelperStyle.top = (posY + addTop) + 'px'; - dragHelperStyle.left = (posX + addLeft) + 'px'; + dragHelperStyle.top = posY + addTop + 'px'; + dragHelperStyle.left = posX + addLeft + 'px'; }, - /** * Returns true if the element matches with selector * @param {Element} el @@ -196,12 +203,10 @@ module.exports = Backbone.View.extend({ * @return {Element|null} */ closest(el, selector) { - if(!el) - return; + if (!el) return; var elem = el.parentNode; while (elem && elem.nodeType === 1) { - if (this.matches(elem, selector)) - return elem; + if (this.matches(elem, selector)) return elem; elem = elem.parentNode; } return null; @@ -231,7 +236,7 @@ module.exports = Backbone.View.extend({ el.className = pfx + 'placeholder'; el.style.display = 'none'; el.style['pointer-events'] = 'none'; - ins.className = pfx + "placeholder-int"; + ins.className = pfx + 'placeholder-int'; el.appendChild(ins); return el; }, @@ -293,7 +298,6 @@ module.exports = Backbone.View.extend({ return $(elem).data('model'); }, - /** * Get the model of the current source element (element to drag) * @return {Model} @@ -307,8 +311,11 @@ module.exports = Backbone.View.extend({ if (dropContent && em) { if (!dropModel) { let comps = em.get('DomComponents').getComponents(); - let tempModel = comps.add(dropContent, {avoidUpdateStyle: 1, temporary: 1}); - dropModel = comps.remove(tempModel, {temporary: 1}); + let tempModel = comps.add(dropContent, { + avoidUpdateStyle: 1, + temporary: 1 + }); + dropModel = comps.remove(tempModel, { temporary: 1 }); this.dropModel = dropModel instanceof Array ? dropModel[0] : dropModel; } return dropModel; @@ -319,7 +326,6 @@ module.exports = Backbone.View.extend({ } }, - /** * Highlight target * @param {Model|null} model @@ -351,15 +357,14 @@ module.exports = Backbone.View.extend({ // Turn placeholder visibile var plh = this.plh; var dsp = plh.style.display; - if (!dsp || dsp === 'none') - plh.style.display = 'block'; + if (!dsp || dsp === 'none') plh.style.display = 'block'; // Cache all necessary positions var eO = this.offset(this.el); this.elT = this.wmargin ? Math.abs(eO.top) : eO.top; - this.elL = this.wmargin ? Math.abs(eO.left): eO.left; - var rY = (e.pageY - this.elT) + this.el.scrollTop; - var rX = (e.pageX - this.elL) + this.el.scrollLeft; + this.elL = this.wmargin ? Math.abs(eO.left) : eO.left; + var rY = e.pageY - this.elT + this.el.scrollTop; + var rX = e.pageX - this.elL + this.el.scrollLeft; if (this.canvasRelative && em) { var mousePos = em.get('Canvas').getMouseRelativeCanvas(e); @@ -380,35 +385,34 @@ module.exports = Backbone.View.extend({ this.lastDims = dims; var pos = this.findPosition(dims, rX, rY); // If there is a significant changes with the pointer - if( !this.lastPos || - (this.lastPos.index != pos.index || this.lastPos.method != pos.method)){ + if ( + !this.lastPos || + (this.lastPos.index != pos.index || this.lastPos.method != pos.method) + ) { this.movePlaceholder(this.plh, dims, pos, this.prevTargetDim); - if(!this.$plh) - this.$plh = $(this.plh); + if (!this.$plh) this.$plh = $(this.plh); // With canvasRelative the offset is calculated automatically for // each element if (!this.canvasRelative) { - if(this.offTop) - this.$plh.css('top', '+=' + this.offTop + 'px'); - if(this.offLeft) - this.$plh.css('left', '+=' + this.offLeft + 'px'); + if (this.offTop) this.$plh.css('top', '+=' + this.offTop + 'px'); + if (this.offLeft) this.$plh.css('left', '+=' + this.offLeft + 'px'); } this.lastPos = pos; } - if(typeof this.onMoveClb === 'function') - this.onMoveClb(e); - - em && em.trigger('sorter:drag', { - target, - targetModel, - dims, - pos, - x: rX, - y: rY, - }); + if (typeof this.onMoveClb === 'function') this.onMoveClb(e); + + em && + em.trigger('sorter:drag', { + target, + targetModel, + dims, + pos, + x: rX, + y: rY + }); }, /** @@ -420,17 +424,15 @@ module.exports = Backbone.View.extend({ * @private * */ isInFlow(el, parent) { - if(!el) - return false; - - parent = parent || document.body; - var ch = -1, h; - var elem = el; - h = elem.offsetHeight; - if (/*h < ch || */!this.styleInFlow(elem, parent)) - return false; - else - return true; + if (!el) return false; + + parent = parent || document.body; + var ch = -1, + h; + var elem = el; + h = elem.offsetHeight; + if (/*h < ch || */ !this.styleInFlow(elem, parent)) return false; + else return true; }, /** @@ -443,28 +445,30 @@ module.exports = Backbone.View.extend({ styleInFlow(el, parent) { var style = el.style; var $el = $(el); - if (style.overflow && style.overflow !== 'visible') - return; - if ($el.css('float') !== 'none') - return; - if(parent && $(parent).css('display') == 'flex') - return; + if (style.overflow && style.overflow !== 'visible') return; + if ($el.css('float') !== 'none') return; + if (parent && $(parent).css('display') == 'flex') return; switch (style.position) { - case 'static': case 'relative': case '': - break; - default: - return; + case 'static': + case 'relative': + case '': + break; + default: + return; } switch (el.tagName) { - case 'TR': case 'TBODY': case 'THEAD': case 'TFOOT': - return true; + case 'TR': + case 'TBODY': + case 'THEAD': + case 'TFOOT': + return true; } switch ($el.css('display')) { - case 'block': - case 'list-item': - case 'table': - case 'flex': - return true; + case 'block': + case 'list-item': + case 'table': + case 'flex': + return true; } return; }, @@ -545,7 +549,7 @@ module.exports = Backbone.View.extend({ // Check if the target is different from the previous one if (this.prevTarget && this.prevTarget != target) { - this.prevTarget = null; + this.prevTarget = null; } // New target found @@ -567,29 +571,29 @@ module.exports = Backbone.View.extend({ } // If the target is the previous one will return the cached dims - if(this.prevTarget == target) - dims = this.cacheDims; + if (this.prevTarget == target) dims = this.cacheDims; // Target when I will drop element to sort this.target = this.prevTarget; // Generally, on any new target the poiner enters inside its area and // triggers nearBorders(), so have to take care of this - if(this.nearBorders(this.prevTargetDim, rX, rY) || - (!this.nested && !this.cacheDims.length)) { - const targetParent = this.targetP; + if ( + this.nearBorders(this.prevTargetDim, rX, rY) || + (!this.nested && !this.cacheDims.length) + ) { + const targetParent = this.targetP; - if (targetParent && this.validTarget(targetParent).valid) { - dims = this.cacheDimsP; - this.target = targetParent; - } + if (targetParent && this.validTarget(targetParent).valid) { + dims = this.cacheDimsP; + this.target = targetParent; + } } this.lastPos = null; return dims; }, - /** * Get valid target from element * This method should replace dimsFromTarget() @@ -617,7 +621,7 @@ module.exports = Backbone.View.extend({ // Check if the target is different from the previous one if (targetPrev && targetPrev != target) { - this.targetPrev = ''; + this.targetPrev = ''; } // New target found @@ -649,7 +653,6 @@ module.exports = Backbone.View.extend({ return target; }, - /** * Check if the current pointer is neare to element borders * @return {Boolen} @@ -658,28 +661,28 @@ module.exports = Backbone.View.extend({ const off = 10; const rect = el.getBoundingClientRect(); const body = el.ownerDocument.body; - const {x, y} = this.getCurrentPos(); + const { x, y } = this.getCurrentPos(); const top = rect.top + body.scrollTop; const left = rect.left + body.scrollLeft; const width = rect.width; const height = rect.height; //console.log(pos, {top, left}); - if ( y < (top + off) || // near top edge - y > (top + height - off) || // near bottom edge - x < (left + off) || // near left edge - x > (left + width - off) // near right edge - ) { - return 1; + if ( + y < top + off || // near top edge + y > top + height - off || // near bottom edge + x < left + off || // near left edge + x > left + width - off // near right edge + ) { + return 1; } }, - getCurrentPos() { const ev = this.eventMove; const x = ev.pageX || 0; const y = ev.pageY || 0; - return {x, y}; + return { x, y }; }, /** @@ -703,8 +706,12 @@ module.exports = Backbone.View.extend({ width = pos.width + marginLeft + marginRight; } else { var o = this.offset(el); - top = this.relative ? el.offsetTop : o.top - (this.wmargin ? -1 : 1) * this.elT; - left = this.relative ? el.offsetLeft : o.left - (this.wmargin ? -1 : 1) * this.elL; + top = this.relative + ? el.offsetTop + : o.top - (this.wmargin ? -1 : 1) * this.elT; + left = this.relative + ? el.offsetLeft + : o.left - (this.wmargin ? -1 : 1) * this.elL; height = el.offsetHeight; width = el.offsetWidth; } @@ -721,8 +728,7 @@ module.exports = Backbone.View.extend({ * */ getChildrenDim(trg) { var dims = []; - if(!trg) - return dims; + if (!trg) return dims; // Get children based on getChildrenContainer var trgModel = this.getTargetModel(trg); @@ -742,12 +748,9 @@ module.exports = Backbone.View.extend({ var dim = this.getDim(el); var dir = this.direction; - if(dir == 'v') - dir = true; - else if(dir == 'h') - dir = false; - else - dir = this.isInFlow(el, trg); + if (dir == 'v') dir = true; + else if (dir == 'h') dir = false; + else dir = this.isInFlow(el, trg); dim.push(dir); dim.push(el); @@ -773,8 +776,7 @@ module.exports = Backbone.View.extend({ var l = dim[1]; var h = dim[2]; var w = dim[3]; - if( ((t + off) > y) || (y > (t + h - off)) || - ((l + off) > x) || (x > (l + w - off)) ) + if (t + off > y || y > t + h - off || l + off > x || x > l + w - off) result = 1; return !!result; @@ -788,50 +790,56 @@ module.exports = Backbone.View.extend({ * @retun {Object} * */ findPosition(dims, posX, posY) { - var result = {index: 0, method: 'before'}; - var leftLimit = 0, xLimit = 0, dimRight = 0, yLimit = 0, xCenter = 0, yCenter = 0, dimDown = 0, dim = 0; + var result = { index: 0, method: 'before' }; + var leftLimit = 0, + xLimit = 0, + dimRight = 0, + yLimit = 0, + xCenter = 0, + yCenter = 0, + dimDown = 0, + dim = 0; // Each dim is: Top, Left, Height, Width - for(var i = 0, len = dims.length; i < len; i++){ + for (var i = 0, len = dims.length; i < len; i++) { dim = dims[i]; // Right position of the element. Left + Width dimRight = dim[1] + dim[3]; // Bottom position of the element. Top + Height dimDown = dim[0] + dim[2]; // X center position of the element. Left + (Width / 2) - xCenter = dim[1] + (dim[3] / 2); + xCenter = dim[1] + dim[3] / 2; // Y center position of the element. Top + (Height / 2) - yCenter = dim[0] + (dim[2] / 2); + yCenter = dim[0] + dim[2] / 2; // Skip if over the limits - if( (xLimit && dim[1] > xLimit) || - (yLimit && yCenter >= yLimit) || // >= avoid issue with clearfixes - (leftLimit && dimRight < leftLimit) ) - continue; + if ( + (xLimit && dim[1] > xLimit) || + (yLimit && yCenter >= yLimit) || // >= avoid issue with clearfixes + (leftLimit && dimRight < leftLimit) + ) + continue; result.index = i; // If it's not in flow (like 'float' element) - if(!dim[4]){ - if(posY < dimDown) - yLimit = dimDown; + if (!dim[4]) { + if (posY < dimDown) yLimit = dimDown; //If x lefter than center - if(posX < xCenter){ + if (posX < xCenter) { xLimit = xCenter; - result.method = "before"; - }else{ + result.method = 'before'; + } else { leftLimit = xCenter; - result.method = "after"; + result.method = 'after'; } - }else{ + } else { // If y upper than center - if(posY < yCenter){ - result.method = "before"; + if (posY < yCenter) { + result.method = 'before'; break; - }else - result.method = "after"; // After last element + } else result.method = 'after'; // After last element } } return result; }, - /** * Updates the position of the placeholder * @param {HTMLElement} phl @@ -840,47 +848,52 @@ module.exports = Backbone.View.extend({ * @param {Array} trgDim target dimensions * */ movePlaceholder(plh, dims, pos, trgDim) { - var marg = 0, t = 0, l = 0, w = 0, h = 0, - un = 'px', margI = 5, brdCol = '#62c462', brd = 3, - method = pos.method; + var marg = 0, + t = 0, + l = 0, + w = 0, + h = 0, + un = 'px', + margI = 5, + brdCol = '#62c462', + brd = 3, + method = pos.method; var elDim = dims[pos.index]; plh.style.borderColor = 'transparent ' + brdCol; plh.style.borderWidth = brd + un + ' ' + (brd + 2) + un; plh.style.margin = '-' + brd + 'px 0 0'; - if(elDim){ + if (elDim) { // If it's not in flow (like 'float' element) - if(!elDim[4]){ + if (!elDim[4]) { w = 'auto'; - h = elDim[2] - (marg * 2) + un; + h = elDim[2] - marg * 2 + un; t = elDim[0] + marg; - l = (method == 'before') ? (elDim[1] - marg) : (elDim[1] + elDim[3] - marg); + l = method == 'before' ? elDim[1] - marg : elDim[1] + elDim[3] - marg; plh.style.borderColor = brdCol + ' transparent'; - plh.style.borderWidth = (brd + 2) + un + ' ' + brd + un; + plh.style.borderWidth = brd + 2 + un + ' ' + brd + un; plh.style.margin = '0 0 0 -' + brd + 'px'; - }else{ + } else { w = elDim[3] + un; h = 'auto'; - t = (method == 'before') ? (elDim[0] - marg) : (elDim[0] + elDim[2] - marg); + t = method == 'before' ? elDim[0] - marg : elDim[0] + elDim[2] - marg; l = elDim[1]; } - }else{ - if(!this.nested){ + } else { + if (!this.nested) { plh.style.display = 'none'; return; } - if(trgDim){ + if (trgDim) { t = trgDim[0] + margI; l = trgDim[1] + margI; - w = (parseInt(trgDim[3]) - margI * 2) + un; + w = parseInt(trgDim[3]) - margI * 2 + un; h = 'auto'; } } plh.style.top = t + un; plh.style.left = l + un; - if(w) - plh.style.width = w; - if(h) - plh.style.height = h; + if (w) plh.style.width = w; + if (h) plh.style.height = h; }, /** @@ -899,7 +912,7 @@ module.exports = Backbone.View.extend({ //this.$document.off('mouseup', this.endMove); //this.$document.off('keydown', this.rollback); this.plh.style.display = 'none'; - var clsReg = new RegExp('(?:^|\\s)'+this.freezeClass+'(?!\\S)', 'gi'); + var clsReg = new RegExp('(?:^|\\s)' + this.freezeClass + '(?!\\S)', 'gi'); let src = this.eV; if (src) { @@ -915,15 +928,13 @@ module.exports = Backbone.View.extend({ created = this.move(this.target, src, this.lastPos); } - if(this.plh) - this.plh.style.display = 'none'; + if (this.plh) this.plh.style.display = 'none'; - if(typeof this.onEndMove === 'function') - this.onEndMove(created); + if (typeof this.onEndMove === 'function') this.onEndMove(created); var dragHelper = this.dragHelper; - if(dragHelper) { + if (dragHelper) { dragHelper.parentNode.removeChild(dragHelper); this.dragHelper = null; } @@ -952,11 +963,12 @@ module.exports = Backbone.View.extend({ var dropInfo = validResult.dropInfo; var dragInfo = validResult.dragInfo; var dropContent = this.dropContent; - droppable = validResult.trgModel instanceof Backbone.Collection ? 1 : droppable; + droppable = + validResult.trgModel instanceof Backbone.Collection ? 1 : droppable; if (targetCollection && droppable && draggable) { index = pos.method === 'after' ? index + 1 : index; - var opts = {at: index, noIncrement: 1}; + var opts = { at: index, noIncrement: 1 }; if (!dropContent) { modelTemp = targetCollection.add({}, opts); @@ -1015,6 +1027,5 @@ module.exports = Backbone.View.extend({ this.moved = 0; this.endMove(); } - }, - + } }); diff --git a/src/utils/extender.js b/src/utils/extender.js index f9d3146193..baca168e24 100644 --- a/src/utils/extender.js +++ b/src/utils/extender.js @@ -1,4 +1,4 @@ -module.exports = ({$, Backbone}) => { +module.exports = ({ $, Backbone }) => { if (Backbone) { const ViewProt = Backbone.View.prototype; const eventNsMap = {}; @@ -15,7 +15,7 @@ module.exports = ({$, Backbone}) => { eventNsMap[vid] = eventMap; } - eventMap.push({eventName, selector, listener}); + eventMap.push({ eventName, selector, listener }); return this; }; @@ -26,7 +26,7 @@ module.exports = ({$, Backbone}) => { let eventMap = eventNsMap[vid]; if (eventMap) { - eventMap.forEach(({eventName, selector, listener}) => { + eventMap.forEach(({ eventName, selector, listener }) => { this.$el.off(eventName); }); } @@ -40,7 +40,7 @@ module.exports = ({$, Backbone}) => { let eventMap = eventNsMap[vid]; if (eventMap) { - eventMap.forEach(({eventName, selector, listener}) => { + eventMap.forEach(({ eventName, selector, listener }) => { if (eventName == ev && selector == sel) { this.$el.off(eventName); } @@ -55,9 +55,11 @@ module.exports = ({$, Backbone}) => { const fn = $.fn; const splitNamespace = function(name) { - const namespaceArray = name.split('.') - return ( name.indexOf('.') !== 0 ? [namespaceArray[0], namespaceArray.slice(1)] : [null, namespaceArray] ); - } + const namespaceArray = name.split('.'); + return name.indexOf('.') !== 0 + ? [namespaceArray[0], namespaceArray.slice(1)] + : [null, namespaceArray]; + }; /* const CashEvent = function(node, eventName, namespaces, delegate, originalCallback, runOnce) { @@ -103,11 +105,10 @@ module.exports = ({$, Backbone}) => { const off = $.prototype.off; const trigger = $.prototype.trigger; const offset = $.prototype.offset; - const getEvents = (eventName) => eventName.split(/[,\s]+/g); - const getNamespaces = (eventName) => eventName.split('.'); + const getEvents = eventName => eventName.split(/[,\s]+/g); + const getNamespaces = eventName => eventName.split('.'); fn.on = function(eventName, delegate, callback, runOnce) { - if (typeof eventName == 'string') { const events = getEvents(eventName); @@ -130,14 +131,15 @@ module.exports = ({$, Backbone}) => { return on.call(this, eventName, delegate, callback, runOnce); } else { - events.forEach((eventName) => - this.on(eventName, delegate, callback, runOnce)); + events.forEach(eventName => + this.on(eventName, delegate, callback, runOnce) + ); return this; } } else { - return on.call(this, eventName, delegate, callback, runOnce) + return on.call(this, eventName, delegate, callback, runOnce); } - } + }; fn.off = function(eventName, callback) { if (typeof eventName == 'string') { @@ -159,13 +161,13 @@ module.exports = ({$, Backbone}) => { return off.call(this, eventName, callback); } else { - events.forEach((eventName) => this.off(eventName, callback)); + events.forEach(eventName => this.off(eventName, callback)); return this; } } else { return off.call(this, eventName, callback); } - } + }; fn.trigger = function(eventName, data) { if (eventName instanceof $.Event) { @@ -191,54 +193,53 @@ module.exports = ({$, Backbone}) => { return trigger.call(this, eventName, data); } else { - events.forEach((eventName) => this.trigger(eventName, data)); + events.forEach(eventName => this.trigger(eventName, data)); return this; } } else { return trigger.call(this, eventName, data); } - } + }; fn.hide = function() { return this.css('display', 'none'); - } + }; fn.show = function() { return this.css('display', 'block'); - } + }; fn.focus = function() { const el = this.get(0); el && el.focus(); return this; - } + }; - fn.remove = function () { + (fn.remove = function() { return this.each(node => { return node.parentNode && node.parentNode.removeChild(node); }); - }, - - // For spectrum compatibility - fn.bind = function(ev, h) { - return this.on(ev, h); - } + }), + // For spectrum compatibility + (fn.bind = function(ev, h) { + return this.on(ev, h); + }); fn.unbind = function(ev, h) { return this.off(ev, h); - } + }; fn.click = function(h) { return h ? this.on('click', h) : this.trigger('click'); - } + }; fn.change = function(h) { return h ? this.on('change', h) : this.trigger('change'); - } + }; fn.keydown = function(h) { return h ? this.on('keydown', h) : this.trigger('keydown'); - } + }; fn.delegate = function(selector, events, data, handler) { if (!handler) { @@ -249,21 +250,21 @@ module.exports = ({$, Backbone}) => { e.data = data; handler(e); }); - } + }; fn.scrollLeft = function() { let el = this.get(0); el = el.nodeType == 9 ? el.defaultView : el; let win = el instanceof Window ? el : null; return win ? win.pageXOffset : el.scrollLeft || 0; - } + }; fn.scrollTop = function() { let el = this.get(0); el = el.nodeType == 9 ? el.defaultView : el; let win = el instanceof Window ? el : null; return win ? win.pageYOffset : el.scrollTop || 0; - } + }; fn.offset = function(coords) { let top, left; @@ -291,21 +292,21 @@ module.exports = ({$, Backbone}) => { } return ar; - } + }; const indexOf = Array.prototype.indexOf; $.inArray = function(val, arr, i) { - return arr == null ? -1 : indexOf.call( arr, val, i ); - } + return arr == null ? -1 : indexOf.call(arr, val, i); + }; $.Event = function(src, props) { - if (!(this instanceof $.Event) ) { + if (!(this instanceof $.Event)) { return new $.Event(src, props); } this.type = src; this.isDefaultPrevented = () => false; - } + }; } -} +}; diff --git a/src/utils/fetch.js b/src/utils/fetch.js index 33bdd5ebdb..8db987abbc 100644 --- a/src/utils/fetch.js +++ b/src/utils/fetch.js @@ -2,29 +2,32 @@ import Promise from 'promise-polyfill'; window.Promise = window.Promise || Promise; -export default typeof fetch == 'function' ? fetch.bind() : (url, options) => { - return new Promise((res, rej) => { - const req = new XMLHttpRequest(); - req.open(options.method || 'get', url); - req.withCredentials = options.credentials == 'include'; +export default (typeof fetch == 'function' + ? fetch.bind() + : (url, options) => { + return new Promise((res, rej) => { + const req = new XMLHttpRequest(); + req.open(options.method || 'get', url); + req.withCredentials = options.credentials == 'include'; - for (let k in options.headers || {}) { - req.setRequestHeader(k, options.headers[k]); - } + for (let k in options.headers || {}) { + req.setRequestHeader(k, options.headers[k]); + } - req.onload = e => res({ - status: req.status, - statusText: req.statusText, - text: () => Promise.resolve(req.responseText) - }); - req.onerror = rej; + req.onload = e => + res({ + status: req.status, + statusText: req.statusText, + text: () => Promise.resolve(req.responseText) + }); + req.onerror = rej; - // Actually, fetch doesn't support onProgress feature - if (req.upload && options.onProgress) { - req.upload.onprogress = options.onProgress; - } + // Actually, fetch doesn't support onProgress feature + if (req.upload && options.onProgress) { + req.upload.onprogress = options.onProgress; + } - // Include body only if present - options.body ? req.send(options.body) : req.send(); - }); -} + // Include body only if present + options.body ? req.send(options.body) : req.send(); + }); + }); diff --git a/src/utils/index.js b/src/utils/index.js index e4fcd5aa72..58c12d46a9 100644 --- a/src/utils/index.js +++ b/src/utils/index.js @@ -1,5 +1,4 @@ module.exports = () => { - const Sorter = require('./Sorter'); const Resizer = require('./Resizer'); const Dragger = require('./Dragger'); @@ -21,6 +20,6 @@ module.exports = () => { Sorter, Resizer, - Dragger, + Dragger }; }; diff --git a/src/utils/mixins.js b/src/utils/mixins.js index 84d339e5fa..1d21cbc892 100644 --- a/src/utils/mixins.js +++ b/src/utils/mixins.js @@ -1,7 +1,11 @@ import { omit, keys, isUndefined } from 'underscore'; const elProt = window.Element.prototype; -const matches = elProt.matches || elProt.webkitMatchesSelector || elProt.mozMatchesSelector || elProt.msMatchesSelector; +const matches = + elProt.matches || + elProt.webkitMatchesSelector || + elProt.mozMatchesSelector || + elProt.msMatchesSelector; /** * Returns shallow diff between 2 objects @@ -44,7 +48,6 @@ const shallowDiff = (objOrig, objNew) => { return result; }; - const on = (el, ev, fn) => { ev = ev.split(/\s+/); el = el instanceof Array ? el : [el]; @@ -52,8 +55,7 @@ const on = (el, ev, fn) => { for (let i = 0; i < ev.length; ++i) { el.forEach(elem => elem.addEventListener(ev[i], fn)); } -} - +}; const off = (el, ev, fn) => { ev = ev.split(/\s+/); @@ -62,21 +64,18 @@ const off = (el, ev, fn) => { for (let i = 0; i < ev.length; ++i) { el.forEach(elem => elem.removeEventListener(ev[i], fn)); } -} - +}; -const getUnitFromValue = (value) => { +const getUnitFromValue = value => { return value.replace(parseFloat(value), ''); -} - +}; const upFirst = value => value[0].toUpperCase() + value.toLowerCase().slice(1); - const camelCase = value => { const values = value.split('-'); return values[0].toLowerCase() + values.slice(1).map(upFirst); -} +}; const normalizeFloat = (value, step = 1, valueDef = 0) => { let stepDecimals = 0; @@ -89,8 +88,7 @@ const normalizeFloat = (value, step = 1, valueDef = 0) => { } return stepDecimals ? parseFloat(value.toFixed(stepDecimals)) : value; -} - +}; export { on, @@ -101,4 +99,4 @@ export { shallowDiff, normalizeFloat, getUnitFromValue -} +}; diff --git a/src/utils/polyfills.js b/src/utils/polyfills.js index eb5449044d..9b6a6e179c 100644 --- a/src/utils/polyfills.js +++ b/src/utils/polyfills.js @@ -4,7 +4,6 @@ */ export default () => { - /** * Check if IE/Edge * @return {Boolean} @@ -13,10 +12,10 @@ export default () => { let match; const agent = window.navigator.userAgent; const rules = [ - [ 'edge', /Edge\/([0-9\._]+)/ ], - [ 'ie', /MSIE\s(7\.0)/ ], - [ 'ie', /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/ ], - [ 'ie', /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/ ], + ['edge', /Edge\/([0-9\._]+)/], + ['ie', /MSIE\s(7\.0)/], + ['ie', /MSIE\s([0-9\.]+);.*Trident\/[4-7].0/], + ['ie', /Trident\/7\.0.*rv\:([0-9\.]+).*\).*Gecko$/] ]; for (let i = 0; i < rules.length; i++) { @@ -26,13 +25,14 @@ export default () => { } return !!match; - } + }; if (isIE()) { - const originalCreateHTMLDocument = DOMImplementation.prototype.createHTMLDocument - DOMImplementation.prototype.createHTMLDocument = (title) => { + const originalCreateHTMLDocument = + DOMImplementation.prototype.createHTMLDocument; + DOMImplementation.prototype.createHTMLDocument = title => { if (!title) title = ''; return originalCreateHTMLDocument.apply(document.implementation, [title]); - } + }; } -} +}; diff --git a/test/helper.js b/test/helper.js index 7a590681bd..1a7db08bcf 100644 --- a/test/helper.js +++ b/test/helper.js @@ -39,9 +39,9 @@ global.Backbone = require('backbone'); global.localStorage = localStorage; global.SVGElement = global.Element; window.$ = Backbone.$; -global.navigator = {userAgent: 'node.js'}; +global.navigator = { userAgent: 'node.js' }; -Object.keys(window).forEach((key) => { +Object.keys(window).forEach(key => { if (!(key in global)) { global[key] = window[key]; } diff --git a/test/main.js b/test/main.js index d345e69b28..a5aa5ebc8b 100644 --- a/test/main.js +++ b/test/main.js @@ -1,7 +1,6 @@ //import grapesjs from './../src'; describe('Main', () => { - describe('Startup', () => { it('Main object should be loaded', () => { expect(grapesjs).toExist(); diff --git a/test/specs/asset_manager/index.js b/test/specs/asset_manager/index.js index 5025642ad5..2a043a4eb1 100644 --- a/test/specs/asset_manager/index.js +++ b/test/specs/asset_manager/index.js @@ -3,9 +3,7 @@ var AssetManager = require('asset_manager'); var FileUploader = require('./view/FileUploader'); describe('Asset Manager', () => { - describe('Main', () => { - var obj; var imgObj; @@ -17,7 +15,7 @@ describe('Asset Manager', () => { }, load(keys) { return storage; - }, + } }; beforeEach(() => { @@ -26,7 +24,7 @@ describe('Asset Manager', () => { type: 'image', src: 'path/to/image', width: 101, - height: 102, + height: 102 }; obj = new AssetManager(); obj.init(); @@ -86,7 +84,6 @@ describe('Asset Manager', () => { }); describe('With storage', () => { - var storageManager; beforeEach(() => { @@ -94,9 +91,9 @@ describe('Asset Manager', () => { storageManager = new StorageManager().init({ autoload: 0, type: storageId - }) + }); obj = new AssetManager().init({ - stm: storageManager, + stm: storageManager }); storageManager.add(storageId, storageMock); document.body.querySelector('#asset-c').appendChild(obj.render()); @@ -110,15 +107,13 @@ describe('Asset Manager', () => { obj.add(imgObj); obj.store(); obj.remove(imgObj.src); - obj.load({assets: storage['gjs-assets']}); + obj.load({ assets: storage['gjs-assets'] }); var asset = obj.get(imgObj.src); expect(asset.get('width')).toEqual(imgObj.width); expect(asset.get('height')).toEqual(imgObj.height); expect(asset.get('type')).toEqual('image'); }); - }); - }); require('./model/Asset').run(); diff --git a/test/specs/asset_manager/model/Asset.js b/test/specs/asset_manager/model/Asset.js index 5f46eda218..091c887a88 100644 --- a/test/specs/asset_manager/model/Asset.js +++ b/test/specs/asset_manager/model/Asset.js @@ -2,14 +2,13 @@ var Asset = require('asset_manager/model/Asset'); module.exports = { run() { - describe('Asset', () => { it('Object exists', () => { expect(Asset).toExist(); }); it('Has default values', () => { - var obj = new Asset({}); + var obj = new Asset({}); expect(obj.get('type')).toNotExist(); expect(obj.get('src')).toNotExist(); expect(obj.getExtension()).toNotExist(); @@ -17,18 +16,18 @@ module.exports = { }); it('Test getFilename', () => { - var obj = new Asset({ type:'image', src: 'ch/eck/t.e.s.t'}); + var obj = new Asset({ type: 'image', src: 'ch/eck/t.e.s.t' }); expect(obj.getFilename()).toEqual('t.e.s.t'); - var obj = new Asset({ type:'image', src: 'ch/eck/1234abc'}); + var obj = new Asset({ type: 'image', src: 'ch/eck/1234abc' }); expect(obj.getFilename()).toEqual('1234abc'); }); it('Test getExtension', () => { - var obj = new Asset({ type:'image', src: 'ch/eck/t.e.s.t'}); + var obj = new Asset({ type: 'image', src: 'ch/eck/t.e.s.t' }); expect(obj.getExtension()).toEqual('t'); - var obj = new Asset({ type:'image', src: 'ch/eck/1234abc.'}); + var obj = new Asset({ type: 'image', src: 'ch/eck/1234abc.' }); expect(obj.getExtension()).toEqual(''); }); }); } -} +}; diff --git a/test/specs/asset_manager/model/AssetImage.js b/test/specs/asset_manager/model/AssetImage.js index 737e320800..25409a43fd 100644 --- a/test/specs/asset_manager/model/AssetImage.js +++ b/test/specs/asset_manager/model/AssetImage.js @@ -2,7 +2,6 @@ var AssetImage = require('asset_manager/model/AssetImage'); module.exports = { run() { - describe('AssetImage', () => { it('Object exists', () => { expect(AssetImage).toExist(); @@ -18,8 +17,6 @@ module.exports = { expect(obj.getExtension()).toNotExist(); expect(obj.getFilename()).toNotExist(); }); - }); - } }; diff --git a/test/specs/asset_manager/model/Assets.js b/test/specs/asset_manager/model/Assets.js index 6252ff363b..545ec30136 100644 --- a/test/specs/asset_manager/model/Assets.js +++ b/test/specs/asset_manager/model/Assets.js @@ -3,7 +3,6 @@ var Assets = require('asset_manager/model/Assets'); module.exports = { run() { describe('Assets', () => { - var obj; beforeEach(() => { diff --git a/test/specs/asset_manager/view/AssetImageView.js b/test/specs/asset_manager/view/AssetImageView.js index 3afbb4b9c0..58acceda48 100644 --- a/test/specs/asset_manager/view/AssetImageView.js +++ b/test/specs/asset_manager/view/AssetImageView.js @@ -7,20 +7,19 @@ module.exports = { let obj; describe('AssetImageView', () => { - - beforeEach(function () { - var coll = new Assets(); - var model = coll.add({ type:'image', src: '/test' }); + beforeEach(function() { + var coll = new Assets(); + var model = coll.add({ type: 'image', src: '/test' }); obj = new AssetImageView({ collection: new Assets(), - config : {}, + config: {}, model }); document.body.innerHTML = '
'; document.body.querySelector('#fixtures').appendChild(obj.render().el); }); - afterEach(function () { + afterEach(function() { obj = null; document.body.innerHTML = ''; }); @@ -30,22 +29,20 @@ module.exports = { }); describe('Asset should be rendered correctly', () => { + it('Has preview box', function() { + var $asset = obj.$el; + expect($asset.find('.preview').length).toEqual(1); + }); - it('Has preview box', function() { - var $asset = obj.$el; - expect($asset.find('.preview').length).toEqual(1); - }); - - it('Has meta box', function() { - var $asset = obj.$el; - expect($asset.find('.meta').length).toEqual(1); - }); - - it('Has close button', function() { - var $asset = obj.$el; - expect($asset.find('[data-toggle=asset-remove]').length).toEqual(1); - }); + it('Has meta box', function() { + var $asset = obj.$el; + expect($asset.find('.meta').length).toEqual(1); + }); + it('Has close button', function() { + var $asset = obj.$el; + expect($asset.find('[data-toggle=asset-remove]').length).toEqual(1); + }); }); it('Could be selected', function() { @@ -65,12 +62,10 @@ module.exports = { it('Could be removed', function() { var spy = sinon.spy(); - obj.model.on("remove", spy); - obj.onRemove({stopImmediatePropagation() {}}); + obj.model.on('remove', spy); + obj.onRemove({ stopImmediatePropagation() {} }); expect(spy.called).toEqual(true); }); - }); - } }; diff --git a/test/specs/asset_manager/view/AssetView.js b/test/specs/asset_manager/view/AssetView.js index 4e866d3e25..677cdf3889 100644 --- a/test/specs/asset_manager/view/AssetView.js +++ b/test/specs/asset_manager/view/AssetView.js @@ -4,21 +4,21 @@ var Assets = require('asset_manager/model/Assets'); module.exports = { run() { - describe('AssetView', () => { - - beforeEach(function () { - var coll = new Assets(); - var model = coll.add({src: 'test'}); + beforeEach(function() { + var coll = new Assets(); + var model = coll.add({ src: 'test' }); this.view = new AssetView({ - config : {}, + config: {}, model }); document.body.innerHTML = '
'; - document.body.querySelector('#fixtures').appendChild(this.view.render().el); + document.body + .querySelector('#fixtures') + .appendChild(this.view.render().el); }); - afterEach(function () { + afterEach(function() { this.view.remove(); }); @@ -29,8 +29,6 @@ module.exports = { it('Has correct prefix', function() { expect(this.view.pfx).toEqual(''); }); - }); - } -} +}; diff --git a/test/specs/asset_manager/view/AssetsView.js b/test/specs/asset_manager/view/AssetsView.js index 94d13d3e26..3a1bdb8433 100644 --- a/test/specs/asset_manager/view/AssetsView.js +++ b/test/specs/asset_manager/view/AssetsView.js @@ -4,13 +4,11 @@ var Assets = require('asset_manager/model/Assets'); module.exports = { run() { - describe('AssetsView', () => { - var obj; var coll; - beforeEach(function () { + beforeEach(function() { coll = new Assets([]); obj = new AssetsView({ config: {}, @@ -24,7 +22,7 @@ module.exports = { document.body.querySelector('#fixtures').appendChild(obj.el); }); - afterEach(function () { + afterEach(function() { obj.collection.reset(); }); @@ -32,60 +30,58 @@ module.exports = { expect(AssetsView).toExist(); }); - it("Collection is empty", function (){ + it('Collection is empty', function() { expect(obj.getAssetsEl().innerHTML).toNotExist(); }); - it("Add new asset", function (){ - sinon.stub(obj, "addAsset"); - coll.add({src: 'test'}); + it('Add new asset', function() { + sinon.stub(obj, 'addAsset'); + coll.add({ src: 'test' }); expect(obj.addAsset.calledOnce).toEqual(true); }); - it("Render new asset", function (){ - coll.add({src: 'test'}); + it('Render new asset', function() { + coll.add({ src: 'test' }); expect(obj.getAssetsEl().innerHTML).toExist(); }); - it("Render correctly new image asset", function (){ - coll.add({ type: 'image', src: 'test'}); + it('Render correctly new image asset', function() { + coll.add({ type: 'image', src: 'test' }); var asset = obj.getAssetsEl().firstChild; expect(asset.tagName).toEqual('DIV'); expect(asset.innerHTML).toExist(); }); - it("Clean collection from asset", function (){ - var model = coll.add({src: 'test'}); + it('Clean collection from asset', function() { + var model = coll.add({ src: 'test' }); coll.remove(model); expect(obj.getAssetsEl().innerHTML).toNotExist(); }); - it("Deselect works", function (){ - coll.add([{},{}]); + it('Deselect works', function() { + coll.add([{}, {}]); var $asset = obj.$el.children().first(); $asset.attr('class', obj.pfx + 'highlight'); coll.trigger('deselectAll'); expect($asset.attr('class')).toNotExist(); }); - it("Returns not empty assets element", () => { + it('Returns not empty assets element', () => { expect(obj.getAssetsEl()).toExist(); }); - it("Returns not empty url input", () => { + it('Returns not empty url input', () => { expect(obj.getAddInput()).toExist(); }); - it("Add image asset from input string", () => { - obj.getAddInput().value = "test"; + it('Add image asset from input string', () => { + obj.getAddInput().value = 'test'; obj.handleSubmit({ preventDefault() {} }); var asset = obj.options.globalCollection.at(0); expect(asset.get('src')).toEqual('test'); }); - }); - } -} +}; diff --git a/test/specs/asset_manager/view/FileUploader.js b/test/specs/asset_manager/view/FileUploader.js index 27a89ae0d9..b7a381b806 100644 --- a/test/specs/asset_manager/view/FileUploader.js +++ b/test/specs/asset_manager/view/FileUploader.js @@ -1,20 +1,17 @@ var FileUploader = require('asset_manager/view/FileUploader'); - module.exports = { run() { - describe('File Uploader', () => { - let obj; - beforeEach(function () { - obj = new FileUploader({ config : {} }); + beforeEach(function() { + obj = new FileUploader({ config: {} }); document.body.innerHTML = '
'; document.body.querySelector('#fixtures').appendChild(obj.render().el); }); - afterEach(function () { + afterEach(function() { obj.remove(); }); @@ -27,55 +24,62 @@ module.exports = { }); describe('Should be rendered correctly', () => { - - it('Has title', function() { - expect(obj.$el.find('#title').length).toEqual(1); - }); - - it('Title is empty', function() { - expect(obj.$el.find('#title').html()).toEqual(''); - }); - - it('Has file input', function() { - expect(obj.$el.find('input[type=file]').length).toEqual(1); - }); - - it('File input is enabled', function() { - expect(obj.$el.find('input[type=file]').prop('disabled')).toEqual(true); - }); - + it('Has title', function() { + expect(obj.$el.find('#title').length).toEqual(1); + }); + + it('Title is empty', function() { + expect(obj.$el.find('#title').html()).toEqual(''); + }); + + it('Has file input', function() { + expect(obj.$el.find('input[type=file]').length).toEqual(1); + }); + + it('File input is enabled', function() { + expect(obj.$el.find('input[type=file]').prop('disabled')).toEqual( + true + ); + }); }); describe('Interprets configurations correctly', () => { - - it('Has correct title', () => { - var view = new FileUploader({ config : { - uploadText : 'Test', - } }); - view.render(); - expect(view.$el.find('#title').html()).toEqual('Test'); + it('Has correct title', () => { + var view = new FileUploader({ + config: { + uploadText: 'Test' + } }); + view.render(); + expect(view.$el.find('#title').html()).toEqual('Test'); + }); - it('Could be disabled', () => { - var view = new FileUploader({ config : { + it('Could be disabled', () => { + var view = new FileUploader({ + config: { disableUpload: true, upload: 'something' - } }); - view.render(); - expect(view.$el.find('input[type=file]').prop('disabled')).toEqual(true); + } }); - - it('Handles embedAsBase64 parameter', () => { - var view = new FileUploader({ config : { + view.render(); + expect(view.$el.find('input[type=file]').prop('disabled')).toEqual( + true + ); + }); + + it('Handles embedAsBase64 parameter', () => { + var view = new FileUploader({ + config: { embedAsBase64: true - } }); - view.render(); - expect(view.$el.find('input[type=file]').prop('disabled')).toEqual(false); - expect(view.uploadFile).toEqual(FileUploader.embedAsBase64); + } }); - + view.render(); + expect(view.$el.find('input[type=file]').prop('disabled')).toEqual( + false + ); + expect(view.uploadFile).toEqual(FileUploader.embedAsBase64); + }); }); - }); } -} +}; diff --git a/test/specs/block_manager/index.js b/test/specs/block_manager/index.js index 877f083c86..3f242729ae 100644 --- a/test/specs/block_manager/index.js +++ b/test/specs/block_manager/index.js @@ -2,9 +2,7 @@ var BlockManager = require('block_manager'); var BlocksView = require('./view/BlocksView'); describe('BlockManager', () => { - describe('Main', () => { - var obj; var idTest; var optsTest; @@ -47,14 +45,14 @@ describe('BlockManager', () => { }); it('Add block with attributes', () => { - optsTest.attributes = {'class':'test'}; + optsTest.attributes = { class: 'test' }; var model = obj.add(idTest, optsTest); expect(model.get('attributes').class).toEqual('test'); }); it('The id of the block is unique', () => { var model = obj.add(idTest, optsTest); - var model2 = obj.add(idTest, {other: 'test'}); + var model2 = obj.add(idTest, { other: 'test' }); expect(model).toEqual(model2); }); @@ -68,9 +66,7 @@ describe('BlockManager', () => { obj.render(); expect(obj.getContainer()).toExist(); }); - }); BlocksView.run(); - }); diff --git a/test/specs/block_manager/view/BlocksView.js b/test/specs/block_manager/view/BlocksView.js index e324cf6dce..b956a2c900 100644 --- a/test/specs/block_manager/view/BlocksView.js +++ b/test/specs/block_manager/view/BlocksView.js @@ -4,76 +4,76 @@ var Blocks = require('block_manager/model/Blocks'); module.exports = { run() { - describe('BlocksView', () => { + describe('BlocksView', () => { + var $fixtures; + var $fixture; + var model; + var view; + var editorModel; + var ppfx; - var $fixtures; - var $fixture; - var model; - var view; - var editorModel; - var ppfx; + beforeEach(() => { + model = new Blocks([]); + view = new BlocksView({ collection: model }); + document.body.innerHTML = '
'; + document.body.querySelector('#fixtures').appendChild(view.render().el); + }); - beforeEach(() => { - model = new Blocks([]); - view = new BlocksView({ collection: model }); - document.body.innerHTML = '
'; - document.body.querySelector('#fixtures').appendChild(view.render().el); - }); + afterEach(() => { + view.collection.reset(); + }); - afterEach(() => { - view.collection.reset(); - }); + it('The container is not empty', () => { + expect(view.el.outerHTML).toExist(); + }); - it("The container is not empty", () => { - expect(view.el.outerHTML).toExist(); - }); + it('No children inside', () => { + expect(view.getBlocksEl().children.length).toEqual(0); + }); - it("No children inside", () => { - expect(view.getBlocksEl().children.length).toEqual(0); - }); + it('Render children on add', () => { + model.add({}); + expect(view.getBlocksEl().children.length).toEqual(1); + model.add([{}, {}]); + expect(view.getBlocksEl().children.length).toEqual(3); + }); - it("Render children on add", () => { - model.add({}); - expect(view.getBlocksEl().children.length).toEqual(1); - model.add([{},{}]); - expect(view.getBlocksEl().children.length).toEqual(3); + it('Destroy children on remove', () => { + model.add([{}, {}]); + expect(view.getBlocksEl().children.length).toEqual(2); + model.at(0).destroy(); + expect(view.getBlocksEl().children.length).toEqual(1); + }); + + describe('With configs', () => { + beforeEach(() => { + ppfx = 'pfx-t-'; + editorModel = new Backbone.Model(); + model = new Blocks([{ name: 'test1' }, { name: 'test2' }]); + view = new BlocksView( + { + collection: model + }, + { + pStylePrefix: ppfx + } + ); + document.body.innerHTML = '
'; + document.body + .querySelector('#fixtures') + .appendChild(view.render().el); }); - it("Destroy children on remove", () => { - model.add([{},{}]); + it('Render children', () => { expect(view.getBlocksEl().children.length).toEqual(2); - model.at(0).destroy(); - expect(view.getBlocksEl().children.length).toEqual(1); }); - describe('With configs', () => { - - beforeEach(() => { - ppfx = 'pfx-t-'; - editorModel = new Backbone.Model(); - model = new Blocks([ - {name:'test1'}, - {name:'test2'} - ]); - view = new BlocksView({ - collection: model, - },{ - pStylePrefix: ppfx - }); - document.body.innerHTML = '
'; - document.body.querySelector('#fixtures').appendChild(view.render().el); - }); - - it("Render children", () => { - expect(view.getBlocksEl().children.length).toEqual(2); - }); - - it("Render container", () => { - expect(view.getBlocksEl().getAttribute('class')).toEqual(ppfx + 'blocks-c'); - }); - + it('Render container', () => { + expect(view.getBlocksEl().getAttribute('class')).toEqual( + ppfx + 'blocks-c' + ); }); - + }); }); } }; diff --git a/test/specs/code_manager/index.js b/test/specs/code_manager/index.js index 944bcc4e76..39f514268f 100644 --- a/test/specs/code_manager/index.js +++ b/test/specs/code_manager/index.js @@ -2,9 +2,7 @@ var CodeManager = require('code_manager'); var Models = require('./model/CodeModels'); describe('Code Manager', () => { - describe('Main', () => { - let obj; beforeEach(() => { @@ -36,7 +34,6 @@ describe('Code Manager', () => { obj.addViewer('test', 'view'); expect(obj.getViewer('test')).toEqual('view'); }); - }); Models.run(); diff --git a/test/specs/code_manager/model/CodeModels.js b/test/specs/code_manager/model/CodeModels.js index 636a30bf27..d3c9c3d825 100644 --- a/test/specs/code_manager/model/CodeModels.js +++ b/test/specs/code_manager/model/CodeModels.js @@ -7,263 +7,292 @@ const CssComposer = require('css_composer'); module.exports = { run() { - let comp; - let dcomp; - let obj; - let em; - let cc; - - describe('HtmlGenerator', () => { - beforeEach(() => { - em = new Editor(); - obj = new HtmlGenerator(); - dcomp = new DomComponents(); - comp = new Component({}, { + let comp; + let dcomp; + let obj; + let em; + let cc; + + describe('HtmlGenerator', () => { + beforeEach(() => { + em = new Editor(); + obj = new HtmlGenerator(); + dcomp = new DomComponents(); + comp = new Component( + {}, + { em, - componentTypes: dcomp.componentTypes, - }); + componentTypes: dcomp.componentTypes + } + ); + }); + + afterEach(() => { + obj = null; + }); + + it('Build correctly one component', () => { + expect(obj.build(comp)).toEqual(''); + }); + + it('Build correctly empty component inside', () => { + var m1 = comp.get('components').add({}); + expect(obj.build(comp)).toEqual('
'); + }); + + it('Build correctly not empty component inside', () => { + var m1 = comp.get('components').add({ + tagName: 'article', + attributes: { + 'data-test1': 'value1', + 'data-test2': 'value2' + } }); - - afterEach(() => { - obj = null; + expect(obj.build(comp)).toEqual( + '
' + ); + }); + + it('Build correctly component with classes', () => { + var m1 = comp.get('components').add({ + tagName: 'article', + attributes: { + 'data-test1': 'value1', + 'data-test2': 'value2' + } }); - - it('Build correctly one component', () => { - expect(obj.build(comp)).toEqual(''); - - }); - - it('Build correctly empty component inside', () => { - var m1 = comp.get('components').add({}); - expect(obj.build(comp)).toEqual('
'); - }); - - it('Build correctly not empty component inside', () => { - var m1 = comp.get('components').add({ - tagName: 'article', - attributes: { - 'data-test1': 'value1', - 'data-test2': 'value2' - } - }); - expect(obj.build(comp)).toEqual('
'); - }); - - it('Build correctly component with classes', () => { - var m1 = comp.get('components').add({ - tagName: 'article', - attributes: { - 'data-test1': 'value1', - 'data-test2': 'value2' - } - }); - ['class1', 'class2'].forEach(item => { - m1.get('classes').add({name: item}); - }); - expect(obj.build(comp)).toEqual('
'); + ['class1', 'class2'].forEach(item => { + m1.get('classes').add({ name: item }); }); + expect(obj.build(comp)).toEqual( + '
' + ); + }); }); describe('CssGenerator', () => { - var newCssComp = () => new CssComposer().init(); - beforeEach(() => { - em = new Editor({}); - cc = em.get('CssComposer'); - obj = new CssGenerator(); - dcomp = new DomComponents(); - comp = new Component({}, { + var newCssComp = () => new CssComposer().init(); + beforeEach(() => { + em = new Editor({}); + cc = em.get('CssComposer'); + obj = new CssGenerator(); + dcomp = new DomComponents(); + comp = new Component( + {}, + { em, - componentTypes: dcomp.componentTypes, - }); - }); - - afterEach(() => { - obj = null; - }); - - it('Build correctly one component', () => { - expect(obj.build(comp)).toEqual(''); - }); - - it('Build correctly empty component inside', () => { - var m1 = comp.get('components').add({tagName: 'article'}); - expect(obj.build(comp)).toEqual(''); - }); - - it('Build correctly component with style inside', () => { - var m1 = comp.get('components').add({ - tagName: 'article', - style: { - 'prop1': 'value1', - 'prop2': 'value2' - } - }); - expect(obj.build(comp)).toEqual('#' + m1.cid +'{prop1:value1;prop2:value2;}'); + componentTypes: dcomp.componentTypes + } + ); + }); + + afterEach(() => { + obj = null; + }); + + it('Build correctly one component', () => { + expect(obj.build(comp)).toEqual(''); + }); + + it('Build correctly empty component inside', () => { + var m1 = comp.get('components').add({ tagName: 'article' }); + expect(obj.build(comp)).toEqual(''); + }); + + it('Build correctly component with style inside', () => { + var m1 = comp.get('components').add({ + tagName: 'article', + style: { + prop1: 'value1', + prop2: 'value2' + } }); - - it('Build correctly component with class styled', () => { - var m1 = comp.get('components').add({tagName: 'article'}); - var cls1 = m1.get('classes').add({name: 'class1'}); - - var cssc = newCssComp(); - var rule = cssc.add(cls1); - rule.set('style',{'prop1':'value1', 'prop2':'value2'}); - - expect(obj.build(comp, {cssc})).toEqual('.class1{prop1:value1;prop2:value2;}'); - }); - - it('Build correctly component styled with class and state', () => { - var m1 = comp.get('components').add({tagName: 'article'}); - var cls1 = m1.get('classes').add({name: 'class1'}); - - var cssc = newCssComp(); - var rule = cssc.add(cls1); - rule.set('style',{'prop1':'value1', 'prop2':'value2'}); - rule.set('state', 'hover'); - - expect(obj.build(comp, {cssc})).toEqual('.class1:hover{prop1:value1;prop2:value2;}'); - }); - - - it('Build correctly with more classes', () => { - var m1 = comp.get('components').add({tagName: 'article'}); - var cls1 = m1.get('classes').add({name: 'class1'}); - var cls2 = m1.get('classes').add({name: 'class2'}); - - var cssc = newCssComp(); - var rule = cssc.add([cls1, cls2]); - rule.set('style',{'prop1':'value1', 'prop2':'value2'}); - - expect(obj.build(comp, {cssc})).toEqual('.class1.class2{prop1:value1;prop2:value2;}'); - }); - - it('Build rules with mixed classes', () => { - var m1 = comp.get('components').add({tagName: 'article'}); - var cls1 = m1.get('classes').add({name: 'class1'}); - var cls2 = m1.get('classes').add({name: 'class2'}); - - var cssc = newCssComp(); - var rule = cssc.add([cls1, cls2]); - rule.set('style',{'prop1':'value1', 'prop2':'value2'}); - rule.set('selectorsAdd', '.class1 .class2, div > .class4'); - - expect(obj.build(comp, {cssc})).toEqual('.class1.class2, .class1 .class2, div > .class4{prop1:value1;prop2:value2;}'); - }); - - it('Build rules with only not class based selectors', () => { - var cssc = newCssComp(); - var rule = cssc.add([]); - rule.set('style',{'prop1':'value1', 'prop2':'value2'}); - rule.set('selectorsAdd', '.class1 .class2, div > .class4'); - - expect(obj.build(comp, {cssc})).toEqual('.class1 .class2, div > .class4{prop1:value1;prop2:value2;}'); - }); - - it('Build correctly with class styled out', () => { - var m1 = comp.get('components').add({tagName: 'article'}); - var cls1 = m1.get('classes').add({name: 'class1'}); - var cls2 = m1.get('classes').add({name: 'class2'}); - - var cssc = newCssComp(); - var rule = cssc.add([cls1, cls2]); - rule.set('style',{'prop1':'value1'}); - var rule2 = cssc.add(cls2); - rule2.set('style',{'prop2':'value2'}); - - expect(obj.build(comp, {cssc})).toEqual('.class1.class2{prop1:value1;}.class2{prop2:value2;}'); - }); - - it('Rule with media query', () => { - var m1 = comp.get('components').add({tagName: 'article'}); - var cls1 = m1.get('classes').add({name: 'class1'}); - var cls2 = m1.get('classes').add({name: 'class2'}); - - var cssc = newCssComp(); - var rule = cssc.add([cls1, cls2]); - rule.set('style',{'prop1':'value1'}); - rule.set('mediaText', '(max-width: 999px)'); - - expect(obj.build(comp, {cssc})).toEqual('@media (max-width: 999px){.class1.class2{prop1:value1;}}'); - }); - - it('Rules mixed with media queries', () => { - var m1 = comp.get('components').add({tagName: 'article'}); - var cls1 = m1.get('classes').add({name: 'class1'}); - var cls2 = m1.get('classes').add({name: 'class2'}); - - var cssc = newCssComp(); - - var rule = cssc.add([cls1, cls2]); - rule.set('style',{'prop1':'value1'}); - var rule2 = cssc.add(cls2); - rule2.set('style',{'prop2':'value2'}); - - var rule3 = cssc.add(cls1, '', '(max-width: 999px)'); - rule3.set('style',{'prop3':'value3'}); - var rule4 = cssc.add(cls2, '', '(max-width: 999px)'); - rule4.set('style',{'prop4':'value4'}); - - var rule5 = cssc.add(cls1, '', '(max-width: 100px)'); - rule5.set('style',{'prop5':'value5'}); - - expect(obj.build(comp, {cssc})).toEqual('.class1.class2{prop1:value1;}.class2{prop2:value2;}'+ - '@media (max-width: 999px){.class1{prop3:value3;}.class2{prop4:value4;}}'+ - '@media (max-width: 100px){.class1{prop5:value5;}}'); - }); - - it('Avoid useless code', () => { - var m1 = comp.get('components').add({tagName: 'article'}); - var cls1 = m1.get('classes').add({name: 'class1'}); - - var cssc = newCssComp(); - var rule = cssc.add(cls1); - rule.set('style',{'prop1':'value1', 'prop2':'value2'}); - - comp.get('components').remove(m1); - expect(obj.build(comp, {cssc})).toEqual(''); - }); - - it('Render correctly a rule without avoidInlineStyle option', () => { - comp.setStyle({color: 'red'}); - const id = comp.getId(); - const result = `#${id}{color:red;}`; - expect(obj.build(comp, {cssc: cc})).toEqual(result); - }); - - it('Render correctly a rule with avoidInlineStyle option', () => { - em.getConfig().avoidInlineStyle = 1; - comp = new Component({}, { + expect(obj.build(comp)).toEqual( + '#' + m1.cid + '{prop1:value1;prop2:value2;}' + ); + }); + + it('Build correctly component with class styled', () => { + var m1 = comp.get('components').add({ tagName: 'article' }); + var cls1 = m1.get('classes').add({ name: 'class1' }); + + var cssc = newCssComp(); + var rule = cssc.add(cls1); + rule.set('style', { prop1: 'value1', prop2: 'value2' }); + + expect(obj.build(comp, { cssc })).toEqual( + '.class1{prop1:value1;prop2:value2;}' + ); + }); + + it('Build correctly component styled with class and state', () => { + var m1 = comp.get('components').add({ tagName: 'article' }); + var cls1 = m1.get('classes').add({ name: 'class1' }); + + var cssc = newCssComp(); + var rule = cssc.add(cls1); + rule.set('style', { prop1: 'value1', prop2: 'value2' }); + rule.set('state', 'hover'); + + expect(obj.build(comp, { cssc })).toEqual( + '.class1:hover{prop1:value1;prop2:value2;}' + ); + }); + + it('Build correctly with more classes', () => { + var m1 = comp.get('components').add({ tagName: 'article' }); + var cls1 = m1.get('classes').add({ name: 'class1' }); + var cls2 = m1.get('classes').add({ name: 'class2' }); + + var cssc = newCssComp(); + var rule = cssc.add([cls1, cls2]); + rule.set('style', { prop1: 'value1', prop2: 'value2' }); + + expect(obj.build(comp, { cssc })).toEqual( + '.class1.class2{prop1:value1;prop2:value2;}' + ); + }); + + it('Build rules with mixed classes', () => { + var m1 = comp.get('components').add({ tagName: 'article' }); + var cls1 = m1.get('classes').add({ name: 'class1' }); + var cls2 = m1.get('classes').add({ name: 'class2' }); + + var cssc = newCssComp(); + var rule = cssc.add([cls1, cls2]); + rule.set('style', { prop1: 'value1', prop2: 'value2' }); + rule.set('selectorsAdd', '.class1 .class2, div > .class4'); + + expect(obj.build(comp, { cssc })).toEqual( + '.class1.class2, .class1 .class2, div > .class4{prop1:value1;prop2:value2;}' + ); + }); + + it('Build rules with only not class based selectors', () => { + var cssc = newCssComp(); + var rule = cssc.add([]); + rule.set('style', { prop1: 'value1', prop2: 'value2' }); + rule.set('selectorsAdd', '.class1 .class2, div > .class4'); + + expect(obj.build(comp, { cssc })).toEqual( + '.class1 .class2, div > .class4{prop1:value1;prop2:value2;}' + ); + }); + + it('Build correctly with class styled out', () => { + var m1 = comp.get('components').add({ tagName: 'article' }); + var cls1 = m1.get('classes').add({ name: 'class1' }); + var cls2 = m1.get('classes').add({ name: 'class2' }); + + var cssc = newCssComp(); + var rule = cssc.add([cls1, cls2]); + rule.set('style', { prop1: 'value1' }); + var rule2 = cssc.add(cls2); + rule2.set('style', { prop2: 'value2' }); + + expect(obj.build(comp, { cssc })).toEqual( + '.class1.class2{prop1:value1;}.class2{prop2:value2;}' + ); + }); + + it('Rule with media query', () => { + var m1 = comp.get('components').add({ tagName: 'article' }); + var cls1 = m1.get('classes').add({ name: 'class1' }); + var cls2 = m1.get('classes').add({ name: 'class2' }); + + var cssc = newCssComp(); + var rule = cssc.add([cls1, cls2]); + rule.set('style', { prop1: 'value1' }); + rule.set('mediaText', '(max-width: 999px)'); + + expect(obj.build(comp, { cssc })).toEqual( + '@media (max-width: 999px){.class1.class2{prop1:value1;}}' + ); + }); + + it('Rules mixed with media queries', () => { + var m1 = comp.get('components').add({ tagName: 'article' }); + var cls1 = m1.get('classes').add({ name: 'class1' }); + var cls2 = m1.get('classes').add({ name: 'class2' }); + + var cssc = newCssComp(); + + var rule = cssc.add([cls1, cls2]); + rule.set('style', { prop1: 'value1' }); + var rule2 = cssc.add(cls2); + rule2.set('style', { prop2: 'value2' }); + + var rule3 = cssc.add(cls1, '', '(max-width: 999px)'); + rule3.set('style', { prop3: 'value3' }); + var rule4 = cssc.add(cls2, '', '(max-width: 999px)'); + rule4.set('style', { prop4: 'value4' }); + + var rule5 = cssc.add(cls1, '', '(max-width: 100px)'); + rule5.set('style', { prop5: 'value5' }); + + expect(obj.build(comp, { cssc })).toEqual( + '.class1.class2{prop1:value1;}.class2{prop2:value2;}' + + '@media (max-width: 999px){.class1{prop3:value3;}.class2{prop4:value4;}}' + + '@media (max-width: 100px){.class1{prop5:value5;}}' + ); + }); + + it('Avoid useless code', () => { + var m1 = comp.get('components').add({ tagName: 'article' }); + var cls1 = m1.get('classes').add({ name: 'class1' }); + + var cssc = newCssComp(); + var rule = cssc.add(cls1); + rule.set('style', { prop1: 'value1', prop2: 'value2' }); + + comp.get('components').remove(m1); + expect(obj.build(comp, { cssc })).toEqual(''); + }); + + it('Render correctly a rule without avoidInlineStyle option', () => { + comp.setStyle({ color: 'red' }); + const id = comp.getId(); + const result = `#${id}{color:red;}`; + expect(obj.build(comp, { cssc: cc })).toEqual(result); + }); + + it('Render correctly a rule with avoidInlineStyle option', () => { + em.getConfig().avoidInlineStyle = 1; + comp = new Component( + {}, + { em, - componentTypes: dcomp.componentTypes, - }); - comp.setStyle({color: 'red'}); - const id = comp.getId(); - const result = `#${id}{color:red;}`; - expect(obj.build(comp, {cssc: cc, em})).toEqual(result); - }); - - it('Render correctly a rule with avoidInlineStyle and state', () => { - em.getConfig().avoidInlineStyle = 1; - const state = 'hover'; - comp.config.avoidInlineStyle = 1; - comp.set('state', state); - comp.setStyle({color: 'red'}); - const id = comp.getId(); - const result = `#${id}:${state}{color:red;}`; - expect(obj.build(comp, {cssc: cc, em})).toEqual(result); - }); - - it('Render correctly a rule with avoidInlineStyle and w/o state', () => { - em.getConfig().avoidInlineStyle = 1; - const state = 'hover'; - comp.config.avoidInlineStyle = 1; - comp.setStyle({color: 'blue'}); - comp.set('state', state); - comp.setStyle({color: 'red'}); - const id = comp.getId(); - const result = `#${id}{color:blue;}#${id}:${state}{color:red;}`; - expect(obj.build(comp, {cssc: cc, em})).toEqual(result); - }); - }) + componentTypes: dcomp.componentTypes + } + ); + comp.setStyle({ color: 'red' }); + const id = comp.getId(); + const result = `#${id}{color:red;}`; + expect(obj.build(comp, { cssc: cc, em })).toEqual(result); + }); + + it('Render correctly a rule with avoidInlineStyle and state', () => { + em.getConfig().avoidInlineStyle = 1; + const state = 'hover'; + comp.config.avoidInlineStyle = 1; + comp.set('state', state); + comp.setStyle({ color: 'red' }); + const id = comp.getId(); + const result = `#${id}:${state}{color:red;}`; + expect(obj.build(comp, { cssc: cc, em })).toEqual(result); + }); + + it('Render correctly a rule with avoidInlineStyle and w/o state', () => { + em.getConfig().avoidInlineStyle = 1; + const state = 'hover'; + comp.config.avoidInlineStyle = 1; + comp.setStyle({ color: 'blue' }); + comp.set('state', state); + comp.setStyle({ color: 'red' }); + const id = comp.getId(); + const result = `#${id}{color:blue;}#${id}:${state}{color:red;}`; + expect(obj.build(comp, { cssc: cc, em })).toEqual(result); + }); + }); } }; diff --git a/test/specs/commands/index.js b/test/specs/commands/index.js index 42316ad43e..dc09a0b617 100644 --- a/test/specs/commands/index.js +++ b/test/specs/commands/index.js @@ -2,9 +2,7 @@ var Commands = require('commands'); var Models = require('./model/CommandModels'); describe('Commands', () => { - describe('Main', () => { - let obj; beforeEach(() => { @@ -20,7 +18,7 @@ describe('Commands', () => { }); it('Push new command', () => { - var comm = { test: 'test'}; + var comm = { test: 'test' }; obj.add('test', comm); expect(obj.get('test').test).toEqual('test'); }); @@ -59,9 +57,7 @@ describe('Commands', () => { it('Commands module should not have toLoad property', () => { expect(obj.toLoad).toEqual(null); }); - }); - }); Models.run(); diff --git a/test/specs/commands/model/CommandModels.js b/test/specs/commands/model/CommandModels.js index b31179dd60..fd94204e25 100644 --- a/test/specs/commands/model/CommandModels.js +++ b/test/specs/commands/model/CommandModels.js @@ -17,7 +17,6 @@ module.exports = { it('Has id property', () => { expect(obj.has('id')).toEqual(true); }); - }); describe('Commands', () => { @@ -34,8 +33,6 @@ module.exports = { it('Object is ok', () => { expect(obj).toExist(); }); - }); - } }; diff --git a/test/specs/css_composer/e2e/CssComposer.js b/test/specs/css_composer/e2e/CssComposer.js index fab1e33d85..ed76754462 100644 --- a/test/specs/css_composer/e2e/CssComposer.js +++ b/test/specs/css_composer/e2e/CssComposer.js @@ -2,208 +2,213 @@ const $ = Backbone.$; module.exports = { run() { - describe('E2E tests', () => { - var fixtures; - var fixture; - var gjs; - var cssc; - var clsm; - var domc; - var rulesSet; - var rulesSet2; - - before(() => { - fixtures = $("#fixtures"); - fixture = $('
'); - }); + describe('E2E tests', () => { + var fixtures; + var fixture; + var gjs; + var cssc; + var clsm; + var domc; + var rulesSet; + var rulesSet2; + + before(() => { + fixtures = $('#fixtures'); + fixture = $('
'); + }); - beforeEach(done => { - //this.timeout(5000); - gjs = grapesjs.init({ - stylePrefix: '', - storageManager: { autoload: 0, type:'none' }, - assetManager: { storageType: 'none', }, - container: 'csscomposer-fixture', - }); - cssc = gjs.CssComposer; - clsm = gjs.SelectorManager; - domc = gjs.DomComponents; - fixture.empty().appendTo(fixtures); - gjs.render(); - rulesSet = [ - { selectors: [{name: 'test1'}, {name: 'test2'}] }, - { selectors: [{name: 'test2'}, {name: 'test3'}] }, - { selectors: [{name: 'test3'}] } - ]; - rulesSet2 = [ - { selectors: [{name: 'test1'}, {name: 'test2'}], state:':active' }, - { selectors: [{name: 'test2'}, {name: 'test3'}] }, - { selectors: [{name: 'test3'}], mediaText:'(max-width: 900px)' } - ]; - done(); + beforeEach(done => { + //this.timeout(5000); + gjs = grapesjs.init({ + stylePrefix: '', + storageManager: { autoload: 0, type: 'none' }, + assetManager: { storageType: 'none' }, + container: 'csscomposer-fixture' }); + cssc = gjs.CssComposer; + clsm = gjs.SelectorManager; + domc = gjs.DomComponents; + fixture.empty().appendTo(fixtures); + gjs.render(); + rulesSet = [ + { selectors: [{ name: 'test1' }, { name: 'test2' }] }, + { selectors: [{ name: 'test2' }, { name: 'test3' }] }, + { selectors: [{ name: 'test3' }] } + ]; + rulesSet2 = [ + { + selectors: [{ name: 'test1' }, { name: 'test2' }], + state: ':active' + }, + { selectors: [{ name: 'test2' }, { name: 'test3' }] }, + { selectors: [{ name: 'test3' }], mediaText: '(max-width: 900px)' } + ]; + done(); + }); - afterEach(() => { - gjs = null; - cssc = null; - clsm = null; - }); + afterEach(() => { + gjs = null; + cssc = null; + clsm = null; + }); - after(() => { - fixture.remove(); - }); + after(() => { + fixture.remove(); + }); - it('Rules are correctly imported from default property', () => { - var gj = grapesjs.init({ - stylePrefix: '', - storageManager: {autoload: 0, type:'none'}, - cssComposer: {rules: rulesSet}, - container: 'csscomposer-fixture', - }); - var cssc = gj.editor.get('CssComposer'); - expect(cssc.getAll().length).toEqual(rulesSet.length); - var cls = gj.editor.get('SelectorManager').getAll(); - expect(cls.length).toEqual(3); + it('Rules are correctly imported from default property', () => { + var gj = grapesjs.init({ + stylePrefix: '', + storageManager: { autoload: 0, type: 'none' }, + cssComposer: { rules: rulesSet }, + container: 'csscomposer-fixture' }); + var cssc = gj.editor.get('CssComposer'); + expect(cssc.getAll().length).toEqual(rulesSet.length); + var cls = gj.editor.get('SelectorManager').getAll(); + expect(cls.length).toEqual(3); + }); + it('New rule adds correctly the class inside selector manager', () => { + var rules = cssc.getAll(); + rules.add({ selectors: [{ name: 'test1', private: true }] }); + var rule = clsm.getAll().at(0); + expect(rule.get('name')).toEqual('test1'); + expect(rule.get('private')).toEqual(true); + }); - it('New rule adds correctly the class inside selector manager', () => { - var rules = cssc.getAll(); - rules.add({ selectors: [{name: 'test1', private: true}] }); - var rule = clsm.getAll().at(0); - expect(rule.get('name')).toEqual('test1'); - expect(rule.get('private')).toEqual(true); - }); - - it('New rules are correctly imported inside selector manager', () => { - var rules = cssc.getAll(); - rulesSet.forEach(item => { - rules.add(item); - }); - var cls = clsm.getAll(); - expect(cls.length).toEqual(3); - expect(cls.at(0).get('name')).toEqual('test1'); - expect(cls.at(1).get('name')).toEqual('test2'); - expect(cls.at(2).get('name')).toEqual('test3'); + it('New rules are correctly imported inside selector manager', () => { + var rules = cssc.getAll(); + rulesSet.forEach(item => { + rules.add(item); }); + var cls = clsm.getAll(); + expect(cls.length).toEqual(3); + expect(cls.at(0).get('name')).toEqual('test1'); + expect(cls.at(1).get('name')).toEqual('test2'); + expect(cls.at(2).get('name')).toEqual('test3'); + }); - it('Add rules from the new component added as a string with style tag', () => { - var comps = domc.getComponents(); - var rules = cssc.getAll(); - comps.add("
Test
"); - expect(comps.length).toEqual(1); - expect(rules.length).toEqual(2); - }); + it('Add rules from the new component added as a string with style tag', () => { + var comps = domc.getComponents(); + var rules = cssc.getAll(); + comps.add( + '
Test
' + ); + expect(comps.length).toEqual(1); + expect(rules.length).toEqual(2); + }); - it('Add raw rule objects with addCollection', () => { - cssc.addCollection(rulesSet); - expect(cssc.getAll().length).toEqual(3); - expect(clsm.getAll().length).toEqual(3); - }); + it('Add raw rule objects with addCollection', () => { + cssc.addCollection(rulesSet); + expect(cssc.getAll().length).toEqual(3); + expect(clsm.getAll().length).toEqual(3); + }); - it('Add raw rule objects twice with addCollection do not duplucate rules', () => { - var rulesSet2Copy = JSON.parse(JSON.stringify(rulesSet2)); - var coll1 = cssc.addCollection(rulesSet2); - var coll2 = cssc.addCollection(rulesSet2Copy); - expect(cssc.getAll().length).toEqual(3); - expect(clsm.getAll().length).toEqual(3); - expect(coll1).toEqual(coll2); - }); + it('Add raw rule objects twice with addCollection do not duplucate rules', () => { + var rulesSet2Copy = JSON.parse(JSON.stringify(rulesSet2)); + var coll1 = cssc.addCollection(rulesSet2); + var coll2 = cssc.addCollection(rulesSet2Copy); + expect(cssc.getAll().length).toEqual(3); + expect(clsm.getAll().length).toEqual(3); + expect(coll1).toEqual(coll2); + }); - it("Extend css rule style, if requested", () => { - var style1 = {color: 'red', width: '10px'}; - var style2 = {height: '20px', width: '20px'}; - var rule1 = { - selectors: ['test1'], - style: style1, - }; - var rule2 = { - selectors: ['test1'], - style: style2, - }; - var ruleOut = cssc.addCollection(rule1)[0]; - // ruleOut is a Model - ruleOut = JSON.parse(JSON.stringify(ruleOut)); - var ruleResult = { - mediaText: '', - selectors: [{ - active: true, - label: 'test1', - name: 'test1', - type: clsm.Selector.TYPE_CLASS, - private: false, - protected: false, - }], - important: 0, - selectorsAdd: '', - state: '', - stylable: true, - style: { - color: 'red', - width: '10px' + it('Extend css rule style, if requested', () => { + var style1 = { color: 'red', width: '10px' }; + var style2 = { height: '20px', width: '20px' }; + var rule1 = { + selectors: ['test1'], + style: style1 + }; + var rule2 = { + selectors: ['test1'], + style: style2 + }; + var ruleOut = cssc.addCollection(rule1)[0]; + // ruleOut is a Model + ruleOut = JSON.parse(JSON.stringify(ruleOut)); + var ruleResult = { + mediaText: '', + selectors: [ + { + active: true, + label: 'test1', + name: 'test1', + type: clsm.Selector.TYPE_CLASS, + private: false, + protected: false } - }; - expect(ruleOut).toEqual(ruleResult); - var ruleOut = cssc.addCollection(rule2, {extend: 1})[0]; - ruleOut = JSON.parse(JSON.stringify(ruleOut)); - ruleResult.style = { + ], + important: 0, + selectorsAdd: '', + state: '', + stylable: true, + style: { color: 'red', - height: '20px', - width: '20px', + width: '10px' } - expect(ruleOut).toEqual(ruleResult); - - }); + }; + expect(ruleOut).toEqual(ruleResult); + var ruleOut = cssc.addCollection(rule2, { extend: 1 })[0]; + ruleOut = JSON.parse(JSON.stringify(ruleOut)); + ruleResult.style = { + color: 'red', + height: '20px', + width: '20px' + }; + expect(ruleOut).toEqual(ruleResult); + }); - it("Do not extend with different selectorsAdd", () => { - var style1 = {color: 'red', width: '10px'}; - var style2 = {height: '20px', width: '20px'}; - var rule1 = { - selectors: [], - selectorsAdd: '*', - style: style1, - }; - var rule2 = { - selectors: [], - selectorsAdd: 'p', - style: style2, - }; - var rule1Out = cssc.addCollection(rule1, {extend: 1})[0]; - var rule2Out = cssc.addCollection(rule2, {extend: 1})[0]; - rule1Out = JSON.parse(JSON.stringify(rule1Out)); - rule2Out = JSON.parse(JSON.stringify(rule2Out)); - var rule1Result = { - important: 0, - mediaText: '', - selectors: [], - selectorsAdd: '*', - state: '', - stylable: true, - style: { - color: 'red', - width: '10px' - } - }; - var rule2Result = { - important: 0, - mediaText: '', - selectors: [], - selectorsAdd: 'p', - state: '', - stylable: true, - style: { - height: '20px', - width: '20px', - } - }; - expect(rule1Out).toEqual(rule1Result); - expect(rule2Out).toEqual(rule2Result); - }); + it('Do not extend with different selectorsAdd', () => { + var style1 = { color: 'red', width: '10px' }; + var style2 = { height: '20px', width: '20px' }; + var rule1 = { + selectors: [], + selectorsAdd: '*', + style: style1 + }; + var rule2 = { + selectors: [], + selectorsAdd: 'p', + style: style2 + }; + var rule1Out = cssc.addCollection(rule1, { extend: 1 })[0]; + var rule2Out = cssc.addCollection(rule2, { extend: 1 })[0]; + rule1Out = JSON.parse(JSON.stringify(rule1Out)); + rule2Out = JSON.parse(JSON.stringify(rule2Out)); + var rule1Result = { + important: 0, + mediaText: '', + selectors: [], + selectorsAdd: '*', + state: '', + stylable: true, + style: { + color: 'red', + width: '10px' + } + }; + var rule2Result = { + important: 0, + mediaText: '', + selectors: [], + selectorsAdd: 'p', + state: '', + stylable: true, + style: { + height: '20px', + width: '20px' + } + }; + expect(rule1Out).toEqual(rule1Result); + expect(rule2Out).toEqual(rule2Result); + }); - it('Add raw rule objects with width via addCollection', () => { - var coll1 = cssc.addCollection(rulesSet2); - expect(coll1[2].get('mediaText')).toEqual(rulesSet2[2].mediaText); - }); + it('Add raw rule objects with width via addCollection', () => { + var coll1 = cssc.addCollection(rulesSet2); + expect(coll1[2].get('mediaText')).toEqual(rulesSet2[2].mediaText); }); + }); } }; diff --git a/test/specs/css_composer/index.js b/test/specs/css_composer/index.js index 80767c75e1..79d416291e 100644 --- a/test/specs/css_composer/index.js +++ b/test/specs/css_composer/index.js @@ -7,15 +7,15 @@ const utils = require('./../test_utils.js'); const Editor = require('editor/model/Editor'); describe('Css Composer', () => { - describe('Main', () => { - var obj; var em; var config; var storagMock = utils.storageMock(); var editorModel = { - getCss() {return 'testCss';}, + getCss() { + return 'testCss'; + }, getCacheLoad() { return storagMock.load(); } @@ -23,19 +23,18 @@ describe('Css Composer', () => { var setSmConfig = () => { config.stm = storagMock; - config.stm.getConfig = () => ({ + config.stm.getConfig = () => ({ storeCss: 1, storeStyles: 1 }); }; var setEm = () => { config.em = editorModel; - } - + }; beforeEach(() => { em = new Editor({}); - config = {em}; + config = { em }; obj = new CssComposer().init(config); }); @@ -59,68 +58,75 @@ describe('Css Composer', () => { it('Store data', () => { setSmConfig(); setEm(); - var expected = { css: 'testCss', styles: '[]',}; + var expected = { css: 'testCss', styles: '[]' }; expect(obj.store(1)).toEqual(expected); }); - it("Rules are empty", () => { + it('Rules are empty', () => { expect(obj.getAll().length).toEqual(0); }); it('Create new rule with correct selectors', () => { var sel = new obj.Selectors(); - var s1 = sel.add({name: 'test1'}); + var s1 = sel.add({ name: 'test1' }); var rule = obj.add(sel.models); expect(rule.get('selectors').at(0)).toEqual(s1); }); it('Create new rule correctly', () => { var sel = new obj.Selectors(); - var s1 = sel.add({name: 'test1'}); + var s1 = sel.add({ name: 'test1' }); var rule = obj.add(sel.models, 'state1', 'width1'); expect(rule.get('state')).toEqual('state1'); expect(rule.get('mediaText')).toEqual('width1'); }); - it("Add rule to collection", () => { - var sel = new obj.Selectors([{name: 'test1'}]); + it('Add rule to collection', () => { + var sel = new obj.Selectors([{ name: 'test1' }]); var rule = obj.add(sel.models); expect(obj.getAll().length).toEqual(1); - expect(obj.getAll().at(0).get('selectors').at(0).get('name')).toEqual('test1'); - }); - - it("Returns correct rule with the same selector", () => { - var sel = new obj.Selectors([{name: 'test1'}]); + expect( + obj + .getAll() + .at(0) + .get('selectors') + .at(0) + .get('name') + ).toEqual('test1'); + }); + + it('Returns correct rule with the same selector', () => { + var sel = new obj.Selectors([{ name: 'test1' }]); var rule1 = obj.add(sel.models); var rule2 = obj.get(sel.models); expect(rule1).toEqual(rule2); }); - it("Returns correct rule with the same selectors", () => { - var sel1 = new obj.Selectors([{name: 'test1'}]); + it('Returns correct rule with the same selectors', () => { + var sel1 = new obj.Selectors([{ name: 'test1' }]); var rule1 = obj.add(sel1.models); - var sel2 = new obj.Selectors([{name: 'test21'}, {name: 'test22'}]); + var sel2 = new obj.Selectors([{ name: 'test21' }, { name: 'test22' }]); var rule2 = obj.add(sel2.models); var rule3 = obj.get(sel2.models); expect(rule3).toEqual(rule2); }); - it("Do not create multiple rules with the same name selectors", () => { - var sel1 = new obj.Selectors([{name: 'test21'}, {name: 'test22'}]); + it('Do not create multiple rules with the same name selectors', () => { + var sel1 = new obj.Selectors([{ name: 'test21' }, { name: 'test22' }]); var rule1 = obj.add(sel1.models); - var sel2 = new obj.Selectors([{name: 'test22'}, {name: 'test21'}]); + var sel2 = new obj.Selectors([{ name: 'test22' }, { name: 'test21' }]); var rule2 = obj.add(sel2.models); expect(rule2).toEqual(rule1); }); it("Don't duplicate rules", () => { var sel = new obj.Selectors([]); - var s1 = sel.add({name: 'test1'}); - var s2 = sel.add({name: 'test2'}); - var s3 = sel.add({name: 'test3'}); + var s1 = sel.add({ name: 'test1' }); + var s2 = sel.add({ name: 'test2' }); + var s3 = sel.add({ name: 'test3' }); var rule1 = obj.add([s1, s3]); var rule2 = obj.add([s3, s1]); @@ -128,61 +134,65 @@ describe('Css Composer', () => { expect(rule2).toEqual(rule1); }); - it("Returns correct rule with the same mixed selectors", () => { + it('Returns correct rule with the same mixed selectors', () => { var sel = new obj.Selectors([]); - var s1 = sel.add({name: 'test1'}); - var s2 = sel.add({name: 'test2'}); - var s3 = sel.add({name: 'test3'}); + var s1 = sel.add({ name: 'test1' }); + var s2 = sel.add({ name: 'test2' }); + var s3 = sel.add({ name: 'test3' }); var rule1 = obj.add([s1, s3]); var rule2 = obj.get([s3, s1]); expect(rule2).toEqual(rule1); }); - it("Returns correct rule with the same selectors and state", () => { + it('Returns correct rule with the same selectors and state', () => { var sel = new obj.Selectors([]); - var s1 = sel.add({name: 'test1'}); - var s2 = sel.add({name: 'test2'}); - var s3 = sel.add({name: 'test3'}); + var s1 = sel.add({ name: 'test1' }); + var s2 = sel.add({ name: 'test2' }); + var s3 = sel.add({ name: 'test3' }); var rule1 = obj.add([s1, s3], 'hover'); var rule2 = obj.get([s3, s1], 'hover'); expect(rule2).toEqual(rule1); }); - it("Returns correct rule with the same selectors, state and width", () => { + it('Returns correct rule with the same selectors, state and width', () => { var sel = new obj.Selectors([]); - var s1 = sel.add({name: 'test1'}); - var rule1 = obj.add([s1], 'hover','1'); + var s1 = sel.add({ name: 'test1' }); + var rule1 = obj.add([s1], 'hover', '1'); var rule2 = obj.get([s1], 'hover', '1'); expect(rule2).toEqual(rule1); }); - it("Renders correctly", () => { + it('Renders correctly', () => { expect(obj.render()).toExist(); }); it('Create a rule with id selector by using setIdRule()', () => { const name = 'test'; - obj.setIdRule(name, {color: 'red'}); + obj.setIdRule(name, { color: 'red' }); expect(obj.getAll().length).toEqual(1); const rule = obj.getIdRule(name); expect(rule.selectorsToString()).toEqual(`#${name}`); expect(rule.styleToString()).toEqual(`color:red;`); - expect(rule.styleToString({important: 1})).toEqual(`color:red !important;`); - expect(rule.styleToString({important: ['color']})).toEqual(`color:red !important;`); + expect(rule.styleToString({ important: 1 })).toEqual( + `color:red !important;` + ); + expect(rule.styleToString({ important: ['color'] })).toEqual( + `color:red !important;` + ); }); it('Create a rule with id selector and state by using setIdRule()', () => { const name = 'test'; const state = 'hover'; - obj.setIdRule(name, {color: 'red'}, {state}); + obj.setIdRule(name, { color: 'red' }, { state }); expect(obj.getAll().length).toEqual(1); - const rule = obj.getIdRule(name, {state}); + const rule = obj.getIdRule(name, { state }); expect(rule.selectorsToString()).toEqual(`#${name}:${state}`); }); it('Create a rule with class selector by using setClassRule()', () => { const name = 'test'; - obj.setClassRule(name, {color: 'red'}); + obj.setClassRule(name, { color: 'red' }); expect(obj.getAll().length).toEqual(1); const rule = obj.getClassRule(name); expect(rule.selectorsToString()).toEqual(`.${name}`); @@ -192,12 +202,11 @@ describe('Css Composer', () => { it('Create a rule with class selector and state by using setClassRule()', () => { const name = 'test'; const state = 'hover'; - obj.setClassRule(name, {color: 'red'}, {state}); + obj.setClassRule(name, { color: 'red' }, { state }); expect(obj.getAll().length).toEqual(1); - const rule = obj.getClassRule(name, {state}); + const rule = obj.getClassRule(name, { state }); expect(rule.selectorsToString()).toEqual(`.${name}:${state}`); }); - }); Models.run(); diff --git a/test/specs/css_composer/model/CssModels.js b/test/specs/css_composer/model/CssModels.js index f9a6e63d54..44ea7753b4 100644 --- a/test/specs/css_composer/model/CssModels.js +++ b/test/specs/css_composer/model/CssModels.js @@ -5,101 +5,96 @@ var Selector = require('selector_manager/model/Selector'); module.exports = { run() { - describe('CssRule', () => { - let obj; - - beforeEach(() => { - obj = new CssRule(); - }); - - afterEach(() => { - obj = null; - }); - - it('Has selectors property', () => { - expect(obj.has('selectors')).toEqual(true); - }); - - it('Has style property', () => { - expect(obj.has('style')).toEqual(true); - }); - - it('Has state property', () => { - expect(obj.has('state')).toEqual(true); - }); - - it('No default selectors', () => { - expect(obj.get('selectors').length).toEqual(0); - }); - - it('Compare returns true with the same selectors', () => { - var s1 = obj.get('selectors').add({ name: 'test1' }); - var s2 = obj.get('selectors').add({ name: 'test2' }); - expect(obj.compare([s1, s2])).toEqual(true); - }); - - it('Compare with different state', () => { - var s1 = obj.get('selectors').add({ name: 'test1' }); - var s2 = obj.get('selectors').add({ name: 'test2' }); - obj.set('state','hover'); - expect(obj.compare([s1, s2])).toEqual(false); - expect(obj.compare([s1, s2], 'hover')).toEqual(true); - }); - - it('Compare with different mediaText', () => { - var s1 = obj.get('selectors').add({ name: 'test1' }); - var s2 = obj.get('selectors').add({ name: 'test2' }); - obj.set('state','hover'); - obj.set('mediaText','1000'); - expect(obj.compare([s1, s2])).toEqual(false); - expect(obj.compare([s1, s2], 'hover')).toEqual(false); - expect(obj.compare([s2, s1], 'hover', '1000')).toEqual(true); - }); - - it('toCSS returns empty if there is no style', () => { - var s1 = obj.get('selectors').add({ name: 'test1' }); - expect(obj.toCSS()).toEqual(''); - }); - - it('toCSS returns empty if there is no selectors', () => { - obj.setStyle({color: 'red'}); - expect(obj.toCSS()).toEqual(''); - }); - - it('toCSS returns simple CSS', () => { - obj.get('selectors').add({ name: 'test1' }); - obj.setStyle({color: 'red'}); - expect(obj.toCSS()).toEqual(`.test1{color:red;}`); - }); - - it('toCSS wraps correctly inside media rule', () => { - const media = '(max-width: 768px)'; - obj.set('mediaText', media); - obj.get('selectors').add({ name: 'test1' }); - obj.setStyle({color: 'red'}); - expect(obj.toCSS()).toEqual(`@media ${media}{.test1{color:red;}}`); - }); - + describe('CssRule', () => { + let obj; + + beforeEach(() => { + obj = new CssRule(); + }); + + afterEach(() => { + obj = null; + }); + + it('Has selectors property', () => { + expect(obj.has('selectors')).toEqual(true); + }); + + it('Has style property', () => { + expect(obj.has('style')).toEqual(true); + }); + + it('Has state property', () => { + expect(obj.has('state')).toEqual(true); + }); + + it('No default selectors', () => { + expect(obj.get('selectors').length).toEqual(0); + }); + + it('Compare returns true with the same selectors', () => { + var s1 = obj.get('selectors').add({ name: 'test1' }); + var s2 = obj.get('selectors').add({ name: 'test2' }); + expect(obj.compare([s1, s2])).toEqual(true); + }); + + it('Compare with different state', () => { + var s1 = obj.get('selectors').add({ name: 'test1' }); + var s2 = obj.get('selectors').add({ name: 'test2' }); + obj.set('state', 'hover'); + expect(obj.compare([s1, s2])).toEqual(false); + expect(obj.compare([s1, s2], 'hover')).toEqual(true); + }); + + it('Compare with different mediaText', () => { + var s1 = obj.get('selectors').add({ name: 'test1' }); + var s2 = obj.get('selectors').add({ name: 'test2' }); + obj.set('state', 'hover'); + obj.set('mediaText', '1000'); + expect(obj.compare([s1, s2])).toEqual(false); + expect(obj.compare([s1, s2], 'hover')).toEqual(false); + expect(obj.compare([s2, s1], 'hover', '1000')).toEqual(true); + }); + + it('toCSS returns empty if there is no style', () => { + var s1 = obj.get('selectors').add({ name: 'test1' }); + expect(obj.toCSS()).toEqual(''); + }); + + it('toCSS returns empty if there is no selectors', () => { + obj.setStyle({ color: 'red' }); + expect(obj.toCSS()).toEqual(''); + }); + + it('toCSS returns simple CSS', () => { + obj.get('selectors').add({ name: 'test1' }); + obj.setStyle({ color: 'red' }); + expect(obj.toCSS()).toEqual(`.test1{color:red;}`); + }); + + it('toCSS wraps correctly inside media rule', () => { + const media = '(max-width: 768px)'; + obj.set('mediaText', media); + obj.get('selectors').add({ name: 'test1' }); + obj.setStyle({ color: 'red' }); + expect(obj.toCSS()).toEqual(`@media ${media}{.test1{color:red;}}`); + }); }); describe('CssRules', () => { - - it('Creates collection item correctly', () => { - var c = new CssRules(); - var m = c.add({}); - expect(m instanceof CssRule).toEqual(true); - }); - + it('Creates collection item correctly', () => { + var c = new CssRules(); + var m = c.add({}); + expect(m instanceof CssRule).toEqual(true); + }); }); - describe('Selectors', () => { - - it('Creates collection item correctly', () => { - var c = new Selectors(); - var m = c.add({}); - expect(m instanceof Selector).toEqual(true); - }); - + describe('Selectors', () => { + it('Creates collection item correctly', () => { + var c = new Selectors(); + var m = c.add({}); + expect(m instanceof Selector).toEqual(true); + }); }); } }; diff --git a/test/specs/css_composer/view/CssRuleView.js b/test/specs/css_composer/view/CssRuleView.js index 55dee4e1bc..4827eab81d 100644 --- a/test/specs/css_composer/view/CssRuleView.js +++ b/test/specs/css_composer/view/CssRuleView.js @@ -3,95 +3,93 @@ var CssRule = require('css_composer/model/CssRule'); module.exports = { run() { - describe('CssRuleView', () => { - - let obj; - let fixtures; - - beforeEach(function () { - var m = new CssRule(); - obj = new CssRuleView({ + describe('CssRuleView', () => { + let obj; + let fixtures; + + beforeEach(function() { + var m = new CssRule(); + obj = new CssRuleView({ + model: m + }); + document.body.innerHTML = '
'; + fixtures = document.body.querySelector('#fixtures'); + fixtures.appendChild(obj.render().el); + }); + + afterEach(() => { + obj.model.destroy(); + }); + + it('Object exists', () => { + expect(CssRuleView).toExist(); + }); + + it('Empty style inside', function() { + expect(fixtures.innerHTML).toEqual(''); + }); + + it('On update of style always empty as there is no selectors', function() { + obj.model.set('style', { prop: 'value' }); + expect(fixtures.innerHTML).toEqual(''); + }); + + describe('CssRuleView with selectors', () => { + let objReg; + + beforeEach(() => { + var m = new CssRule({ + selectors: [{ name: 'test1' }, { name: 'test2' }] + }); + objReg = new CssRuleView({ model: m }); + objReg.render(); document.body.innerHTML = '
'; fixtures = document.body.querySelector('#fixtures'); - fixtures.appendChild(obj.render().el); + fixtures.appendChild(objReg.el); }); afterEach(() => { - obj.model.destroy(); + objReg.model.destroy(); }); - it('Object exists', () => { - expect(CssRuleView).toExist(); + it('Empty with no style', () => { + expect(objReg.$el.html()).toEqual(''); }); - it('Empty style inside', function() { - expect(fixtures.innerHTML).toEqual(''); + it('Not empty on update of style', () => { + objReg.model.set('style', { prop: 'value' }); + expect(objReg.$el.html()).toEqual('.test1.test2{prop:value;}'); }); - it('On update of style always empty as there is no selectors', function() { - obj.model.set('style', {'prop':'value'}); - expect(fixtures.innerHTML).toEqual(''); + it('State correctly rendered', () => { + objReg.model.set('style', { prop: 'value' }); + objReg.model.set('state', 'hover'); + expect(objReg.$el.html()).toEqual('.test1.test2:hover{prop:value;}'); }); - describe('CssRuleView with selectors', () => { - - let objReg; - - beforeEach(() => { - var m = new CssRule({ - selectors: [{name:'test1'}, {name:'test2'}] - }); - objReg = new CssRuleView({ - model: m - }); - objReg.render(); - document.body.innerHTML = '
'; - fixtures = document.body.querySelector('#fixtures'); - fixtures.appendChild(objReg.el); - }); - - afterEach(() => { - objReg.model.destroy(); - }); - - it('Empty with no style', () => { - expect(objReg.$el.html()).toEqual(''); - }); - - it('Not empty on update of style', () => { - objReg.model.set('style', {'prop':'value'}); - expect(objReg.$el.html()).toEqual('.test1.test2{prop:value;}'); - }); - - it('State correctly rendered', () => { - objReg.model.set('style', {'prop':'value'}); - objReg.model.set('state', 'hover'); - expect(objReg.$el.html()).toEqual('.test1.test2:hover{prop:value;}'); - }); - - it('State render changes on update', () => { - objReg.model.set('style', {'prop':'value'}); - objReg.model.set('state', 'hover'); - objReg.model.set('state', ''); - expect(objReg.$el.html()).toEqual('.test1.test2{prop:value;}'); - }); - - it('Render media queries', () => { - objReg.model.set('style', {'prop':'value'}); - objReg.model.set('mediaText', '(max-width: 999px)'); - expect(objReg.$el.html()).toEqual('@media (max-width: 999px){.test1.test2{prop:value;}}'); - }); - - it('Empty on clear', () => { - objReg.model.set('style', {'prop':'value'}); - objReg.model.set('style', {}); - expect(objReg.$el.html()).toEqual(''); - }); + it('State render changes on update', () => { + objReg.model.set('style', { prop: 'value' }); + objReg.model.set('state', 'hover'); + objReg.model.set('state', ''); + expect(objReg.$el.html()).toEqual('.test1.test2{prop:value;}'); + }); + it('Render media queries', () => { + objReg.model.set('style', { prop: 'value' }); + objReg.model.set('mediaText', '(max-width: 999px)'); + expect(objReg.$el.html()).toEqual( + '@media (max-width: 999px){.test1.test2{prop:value;}}' + ); }); + it('Empty on clear', () => { + objReg.model.set('style', { prop: 'value' }); + objReg.model.set('style', {}); + expect(objReg.$el.html()).toEqual(''); + }); + }); }); } }; diff --git a/test/specs/css_composer/view/CssRulesView.js b/test/specs/css_composer/view/CssRulesView.js index d5a6ac777c..d885fccdc0 100644 --- a/test/specs/css_composer/view/CssRulesView.js +++ b/test/specs/css_composer/view/CssRulesView.js @@ -3,42 +3,40 @@ var CssRules = require('css_composer/model/CssRules'); module.exports = { run() { - describe('CssRulesView', () => { + describe('CssRulesView', () => { + let obj; - let obj; - - beforeEach(function () { - var col = new CssRules([]); - obj = new CssRulesView({ - collection: col - }); - document.body.innerHTML = '
'; - document.body.querySelector('#fixtures').appendChild(obj.render().el); - }); - - afterEach(() => { - obj.collection.reset(); - }); - - it('Object exists', () => { - expect(CssRulesView).toExist(); - }); - - it("Collection is empty", () => { - expect(obj.$el.html()).toNotExist(); - }); - - it("Add new rule", () => { - sinon.stub(obj, "addToCollection"); - obj.collection.add({}); - expect(obj.addToCollection.calledOnce).toExist(true); + beforeEach(function() { + var col = new CssRules([]); + obj = new CssRulesView({ + collection: col }); - - it("Render new rule", () => { - obj.collection.add({}); - expect(obj.$el.html()).toExist(); - }); - + document.body.innerHTML = '
'; + document.body.querySelector('#fixtures').appendChild(obj.render().el); + }); + + afterEach(() => { + obj.collection.reset(); + }); + + it('Object exists', () => { + expect(CssRulesView).toExist(); + }); + + it('Collection is empty', () => { + expect(obj.$el.html()).toNotExist(); + }); + + it('Add new rule', () => { + sinon.stub(obj, 'addToCollection'); + obj.collection.add({}); + expect(obj.addToCollection.calledOnce).toExist(true); + }); + + it('Render new rule', () => { + obj.collection.add({}); + expect(obj.$el.html()).toExist(); + }); }); } }; diff --git a/test/specs/device_manager/index.js b/test/specs/device_manager/index.js index 78d4d8bcda..304814daf5 100644 --- a/test/specs/device_manager/index.js +++ b/test/specs/device_manager/index.js @@ -2,9 +2,7 @@ const DeviceManager = require('device_manager'); const DevicesView = require('./view/DevicesView'); describe('DeviceManager', () => { - describe('Main', () => { - var obj; var testNameDevice; var testWidthDevice; @@ -40,7 +38,7 @@ describe('DeviceManager', () => { }); it('Add device width options', () => { - var model = obj.add(testNameDevice, testWidthDevice, {opt: 'value'}); + var model = obj.add(testNameDevice, testWidthDevice, { opt: 'value' }); expect(model.get('opt')).toEqual('value'); }); @@ -59,9 +57,7 @@ describe('DeviceManager', () => { it('Render devices', () => { expect(obj.render()).toExist(); }); - }); DevicesView.run(); - }); diff --git a/test/specs/device_manager/view/DevicesView.js b/test/specs/device_manager/view/DevicesView.js index 262bd60e0a..b1dbe64023 100644 --- a/test/specs/device_manager/view/DevicesView.js +++ b/test/specs/device_manager/view/DevicesView.js @@ -3,68 +3,65 @@ const Devices = require('device_manager/model/Devices'); module.exports = { run() { - describe('DevicesView', () => { + describe('DevicesView', () => { + var $fixtures; + var $fixture; + var model; + var view; + var editorModel; - var $fixtures; - var $fixture; - var model; - var view; - var editorModel; - - beforeEach(() => { - model = new Devices([]); - view = new DevicesView({ - collection: model - }); - document.body.innerHTML = '
'; - document.body.querySelector('#fixtures').appendChild(view.render().el); + beforeEach(() => { + model = new Devices([]); + view = new DevicesView({ + collection: model }); + document.body.innerHTML = '
'; + document.body.querySelector('#fixtures').appendChild(view.render().el); + }); - afterEach(() => { - view.collection.reset(); - }); + afterEach(() => { + view.collection.reset(); + }); - it("The content is not empty", () => { - expect(view.el.innerHTML).toExist(); - }); + it('The content is not empty', () => { + expect(view.el.innerHTML).toExist(); + }); - it("No options without devices", () => { - expect(view.getOptions()).toEqual(''); - }); - - it("Render new button", () => { - view.collection.add({}); - expect(view.$el.html()).toExist(); - }); + it('No options without devices', () => { + expect(view.getOptions()).toEqual(''); + }); - describe('With configs', () => { + it('Render new button', () => { + view.collection.add({}); + expect(view.$el.html()).toExist(); + }); - beforeEach(() => { - editorModel = new Backbone.Model(); - model = new Devices([ - {name:'test1'}, - {name:'test2'} - ]); - view = new DevicesView({ - collection: model, - config: { em: editorModel } - }); - document.body.innerHTML = '
'; - document.body.querySelector('#fixtures').appendChild(view.render().el); - }); - - it("Update device on select change", () => { - view.$el.find('select').val('test2'); - view.updateDevice(); - expect(view.config.em.get('device')).toEqual('test2'); - }); - - it("Render options", () => { - expect(view.getOptions()).toEqual(''); + describe('With configs', () => { + beforeEach(() => { + editorModel = new Backbone.Model(); + model = new Devices([{ name: 'test1' }, { name: 'test2' }]); + view = new DevicesView({ + collection: model, + config: { em: editorModel } }); + document.body.innerHTML = '
'; + document.body + .querySelector('#fixtures') + .appendChild(view.render().el); + }); + it('Update device on select change', () => { + view.$el.find('select').val('test2'); + view.updateDevice(); + expect(view.config.em.get('device')).toEqual('test2'); }); + it('Render options', () => { + expect(view.getOptions()).toEqual( + '' + ); + }); + }); }); } }; diff --git a/test/specs/dom_components/index.js b/test/specs/dom_components/index.js index 5cab2699b6..19391c4d25 100644 --- a/test/specs/dom_components/index.js +++ b/test/specs/dom_components/index.js @@ -9,20 +9,24 @@ const Editor = require('editor/model/Editor'); const utils = require('./../test_utils.js'); describe('DOM Components', () => { - describe('Main', () => { - var em; var obj; var config; var storagMock = utils.storageMock(); var editorModel = { config: { - loadCompsOnRender: 0, + loadCompsOnRender: 0 + }, + get() { + return; + }, + getHtml() { + return 'testHtml'; + }, + getComponents() { + return { test: 1 }; }, - get() {return;}, - getHtml() {return 'testHtml';}, - getComponents() {return {test: 1};}, getCacheLoad() { return storagMock.load(); } @@ -30,21 +34,20 @@ describe('DOM Components', () => { // Methods var setSmConfig = () => { config.stm = storagMock; - config.stm.getConfig = () => ({ + config.stm.getConfig = () => ({ storeHtml: 1, storeComponents: 1 }); }; var setEm = () => { config.em = editorModel; - } - + }; beforeEach(() => { em = new Editor(); config = { em, - storeWrapper: 1, + storeWrapper: 1 }; obj = new DomComponents().init(config); }); @@ -66,8 +69,8 @@ describe('DOM Components', () => { getConfig() { return { storeHtml: 1, - storeComponents: 1, - } + storeComponents: 1 + }; } }; expect(obj.storageKey()).toEqual(['html', 'components']); @@ -79,7 +82,7 @@ describe('DOM Components', () => { //obj.getWrapper().get('components').add({}); var expected = { html: 'testHtml', - components: JSON.stringify(obj.getWrapper()), + components: JSON.stringify(obj.getWrapper()) }; expect(obj.store(1)).toEqual(expected); }); @@ -90,7 +93,7 @@ describe('DOM Components', () => { const comps = new Components({}, {}); obj.getWrapper().set('components', comps); obj.store(); - expect(obj.load()).toEqual([{test: 1}]); + expect(obj.load()).toEqual([{ test: 1 }]); }); it('Wrapper exists', () => { @@ -107,7 +110,7 @@ describe('DOM Components', () => { }); it('Add more components at once', () => { - var comp = obj.addComponent([{},{}]); + var comp = obj.addComponent([{}, {}]); expect(obj.getComponents().length).toEqual(2); }); @@ -124,5 +127,4 @@ describe('DOM Components', () => { ComponentTextView.run(); ComponentImageView.run(); }); - }); diff --git a/test/specs/dom_components/model/Component.js b/test/specs/dom_components/model/Component.js index fb32d393f8..ccc051a260 100644 --- a/test/specs/dom_components/model/Component.js +++ b/test/specs/dom_components/model/Component.js @@ -12,277 +12,292 @@ const $ = Backbone.$; module.exports = { run() { - let obj; - let dcomp; - let compOpts; - let em; - - describe('Component', () => { - - beforeEach(() => { - em = new Editor({}); - dcomp = new DomComponents(); - compOpts = { - em, - componentTypes: dcomp.componentTypes, - }; - obj = new Component({}, compOpts); - }); + let obj; + let dcomp; + let compOpts; + let em; + + describe('Component', () => { + beforeEach(() => { + em = new Editor({}); + dcomp = new DomComponents(); + compOpts = { + em, + componentTypes: dcomp.componentTypes + }; + obj = new Component({}, compOpts); + }); - afterEach(() => { - obj = null; - }); + afterEach(() => { + obj = null; + }); - it('Has no children', () => { - expect(obj.get('components').length).toEqual(0); - }); + it('Has no children', () => { + expect(obj.get('components').length).toEqual(0); + }); - it('Clones correctly', () => { - var sAttr = obj.attributes; - var cloned = obj.clone(); - var eAttr = cloned.attributes; - eAttr.components = {}; - sAttr.components = {}; - eAttr.traits = {}; - sAttr.traits = {}; - expect(sAttr.length).toEqual(eAttr.length); - }); + it('Clones correctly', () => { + var sAttr = obj.attributes; + var cloned = obj.clone(); + var eAttr = cloned.attributes; + eAttr.components = {}; + sAttr.components = {}; + eAttr.traits = {}; + sAttr.traits = {}; + expect(sAttr.length).toEqual(eAttr.length); + }); - it('Clones correctly with traits', () => { - obj.get('traits').at(0).set('value', 'testTitle'); - var cloned = obj.clone(); - cloned.set('stylable', 0); - cloned.get('traits').at(0).set('value', 'testTitle2'); - expect(obj.get('traits').at(0).get('value')).toEqual('testTitle'); - expect(obj.get('stylable')).toEqual(true); - }); + it('Clones correctly with traits', () => { + obj + .get('traits') + .at(0) + .set('value', 'testTitle'); + var cloned = obj.clone(); + cloned.set('stylable', 0); + cloned + .get('traits') + .at(0) + .set('value', 'testTitle2'); + expect( + obj + .get('traits') + .at(0) + .get('value') + ).toEqual('testTitle'); + expect(obj.get('stylable')).toEqual(true); + }); - it('Has expected name', () => { - expect(obj.getName()).toEqual('Box'); - }); + it('Has expected name', () => { + expect(obj.getName()).toEqual('Box'); + }); - it('Has expected name 2', () => { - obj.cid = 'c999'; - obj.set('type','testType'); - expect(obj.getName()).toEqual('TestType'); - }); + it('Has expected name 2', () => { + obj.cid = 'c999'; + obj.set('type', 'testType'); + expect(obj.getName()).toEqual('TestType'); + }); - it('Component toHTML', () => { - expect(obj.toHTML()).toEqual('
'); - }); + it('Component toHTML', () => { + expect(obj.toHTML()).toEqual('
'); + }); - it('Component toHTML with attributes', () => { - obj = new Component({ - tagName: 'article', - attributes: { - 'data-test1': 'value1', - 'data-test2': 'value2' - } - }); - expect(obj.toHTML()).toEqual('
'); + it('Component toHTML with attributes', () => { + obj = new Component({ + tagName: 'article', + attributes: { + 'data-test1': 'value1', + 'data-test2': 'value2' + } }); + expect(obj.toHTML()).toEqual( + '
' + ); + }); - it('Component toHTML with value-less attribute', () => { - obj = new Component({ - tagName: 'div', - attributes: { - 'data-is-a-test': '' - } - }); - expect(obj.toHTML()).toEqual('
'); + it('Component toHTML with value-less attribute', () => { + obj = new Component({ + tagName: 'div', + attributes: { + 'data-is-a-test': '' + } }); + expect(obj.toHTML()).toEqual('
'); + }); - it('Component toHTML with classes', () => { - obj = new Component({ - tagName: 'article' - }); - ['class1', 'class2'].forEach(item => { - obj.get('classes').add({name: item}); - }); - expect(obj.toHTML()).toEqual('
'); + it('Component toHTML with classes', () => { + obj = new Component({ + tagName: 'article' }); - - it('Component toHTML with children', () => { - obj = new Component({tagName: 'article'}, compOpts); - obj.get('components').add({tagName: 'span'}); - expect(obj.toHTML()).toEqual('
'); + ['class1', 'class2'].forEach(item => { + obj.get('classes').add({ name: item }); }); + expect(obj.toHTML()).toEqual( + '
' + ); + }); - it('Component toHTML with more children', () => { - obj = new Component({tagName: 'article'}, compOpts); - obj.get('components').add([{tagName: 'span'}, {tagName: 'div'}]); - expect(obj.toHTML()).toEqual('
'); - }); + it('Component toHTML with children', () => { + obj = new Component({ tagName: 'article' }, compOpts); + obj.get('components').add({ tagName: 'span' }); + expect(obj.toHTML()).toEqual('
'); + }); - it('Component toHTML with no closing tag', () => { - obj = new Component({void: 1}); - expect(obj.toHTML()).toEqual('
'); - }); + it('Component toHTML with more children', () => { + obj = new Component({ tagName: 'article' }, compOpts); + obj.get('components').add([{ tagName: 'span' }, { tagName: 'div' }]); + expect(obj.toHTML()).toEqual( + '
' + ); + }); - it('Component parse empty div', () => { - var el = document.createElement('div'); - obj = Component.isComponent(el); - expect(obj).toEqual({tagName: 'div'}); - }); + it('Component toHTML with no closing tag', () => { + obj = new Component({ void: 1 }); + expect(obj.toHTML()).toEqual('
'); + }); - it('Component parse span', () => { - var el = document.createElement('span'); - obj = Component.isComponent(el); - expect(obj).toEqual({tagName: 'span'}); - }); + it('Component parse empty div', () => { + var el = document.createElement('div'); + obj = Component.isComponent(el); + expect(obj).toEqual({ tagName: 'div' }); + }); - it('setClass single class string', () => { - obj.setClass('class1'); - const result = obj.get('classes').models; - expect(result.length).toEqual(1); - expect(result[0] instanceof Selector).toEqual(true); - expect(result[0].get('name')).toEqual('class1'); - }); + it('Component parse span', () => { + var el = document.createElement('span'); + obj = Component.isComponent(el); + expect(obj).toEqual({ tagName: 'span' }); + }); - it('setClass multiple class string', () => { - obj.setClass('class1 class2'); - const result = obj.get('classes').models; - expect(result.length).toEqual(2); - }); + it('setClass single class string', () => { + obj.setClass('class1'); + const result = obj.get('classes').models; + expect(result.length).toEqual(1); + expect(result[0] instanceof Selector).toEqual(true); + expect(result[0].get('name')).toEqual('class1'); + }); - it('setClass single class array', () => { - obj.setClass(['class1']); - const result = obj.get('classes').models; - expect(result.length).toEqual(1); - }); + it('setClass multiple class string', () => { + obj.setClass('class1 class2'); + const result = obj.get('classes').models; + expect(result.length).toEqual(2); + }); - it('setClass multiple class array', () => { - obj.setClass(['class1', 'class2']); - const result = obj.get('classes').models; - expect(result.length).toEqual(2); - }); + it('setClass single class array', () => { + obj.setClass(['class1']); + const result = obj.get('classes').models; + expect(result.length).toEqual(1); + }); - it('addClass multiple array', () => { - obj.addClass(['class1', 'class2']); - const result = obj.get('classes').models; - expect(result.length).toEqual(2); - }); + it('setClass multiple class array', () => { + obj.setClass(['class1', 'class2']); + const result = obj.get('classes').models; + expect(result.length).toEqual(2); + }); - it('addClass avoid same name classes', () => { - obj.addClass(['class1', 'class2']); - obj.addClass(['class1', 'class3']); - const result = obj.get('classes').models; - expect(result.length).toEqual(3); - }); + it('addClass multiple array', () => { + obj.addClass(['class1', 'class2']); + const result = obj.get('classes').models; + expect(result.length).toEqual(2); + }); - it('removeClass by string', () => { - obj.addClass(['class1', 'class2']); - obj.removeClass('class2'); - const result = obj.get('classes').models; - expect(result.length).toEqual(1); - }); + it('addClass avoid same name classes', () => { + obj.addClass(['class1', 'class2']); + obj.addClass(['class1', 'class3']); + const result = obj.get('classes').models; + expect(result.length).toEqual(3); + }); - it('removeClass by string with multiple classes', () => { - obj.addClass(['class1', 'class2']); - obj.removeClass('class2 class1'); - const result = obj.get('classes').models; - expect(result.length).toEqual(0); - }); + it('removeClass by string', () => { + obj.addClass(['class1', 'class2']); + obj.removeClass('class2'); + const result = obj.get('classes').models; + expect(result.length).toEqual(1); + }); - it('removeClass by array', () => { - obj.addClass(['class1', 'class2']); - obj.removeClass(['class1', 'class2']); - const result = obj.get('classes').models; - expect(result.length).toEqual(0); - }); + it('removeClass by string with multiple classes', () => { + obj.addClass(['class1', 'class2']); + obj.removeClass('class2 class1'); + const result = obj.get('classes').models; + expect(result.length).toEqual(0); + }); - it('removeClass do nothing with undefined classes', () => { - obj.addClass(['class1', 'class2']); - obj.removeClass(['class3']); - const result = obj.get('classes').models; - expect(result.length).toEqual(2); - }); + it('removeClass by array', () => { + obj.addClass(['class1', 'class2']); + obj.removeClass(['class1', 'class2']); + const result = obj.get('classes').models; + expect(result.length).toEqual(0); + }); - it('removeClass actually removes classes from attributes', () => { - obj.addClass('class1'); - obj.removeClass('class1'); - const result = obj.getAttributes(); - expect(result.class).toEqual(undefined); - }); + it('removeClass do nothing with undefined classes', () => { + obj.addClass(['class1', 'class2']); + obj.removeClass(['class3']); + const result = obj.get('classes').models; + expect(result.length).toEqual(2); + }); - it('setAttributes', () => { - obj.setAttributes({ - id: 'test', - 'data-test': 'value', - class: 'class1 class2', - style: 'color: white; background: #fff' - }); - expect(obj.getAttributes()).toEqual({ - id: 'test', - class: 'class1 class2', - 'data-test': 'value', - }); - expect(obj.get('classes').length).toEqual(2); - expect(obj.getStyle()).toEqual({ - color: 'white', - background: '#fff', - }); - }); + it('removeClass actually removes classes from attributes', () => { + obj.addClass('class1'); + obj.removeClass('class1'); + const result = obj.getAttributes(); + expect(result.class).toEqual(undefined); + }); - it('setAttributes overwrites correctly', () => { - obj.setAttributes({id: 'test', 'data-test': 'value'}); - obj.setAttributes({'data-test': 'value2'}); - expect(obj.getAttributes()).toEqual({'data-test': 'value2'}); + it('setAttributes', () => { + obj.setAttributes({ + id: 'test', + 'data-test': 'value', + class: 'class1 class2', + style: 'color: white; background: #fff' }); - - it('append() returns always an array', () => { - let result = obj.append('text1'); - expect(result.length).toEqual(1); - result = obj.append('text1
text2
'); - expect(result.length).toEqual(2); + expect(obj.getAttributes()).toEqual({ + id: 'test', + class: 'class1 class2', + 'data-test': 'value' }); - - it('append() new components as string', () => { - obj.append('text1
text2
'); - const comps = obj.components(); - expect(comps.length).toEqual(2); - expect(comps.models[0].get('tagName')).toEqual('span'); - expect(comps.models[1].get('tagName')).toEqual('div'); + expect(obj.get('classes').length).toEqual(2); + expect(obj.getStyle()).toEqual({ + color: 'white', + background: '#fff' }); + }); - it('append() new components as Objects', () => { - obj.append([{}, {}]); - const comps = obj.components(); - expect(comps.length).toEqual(2); - obj.append({}); - expect(comps.length).toEqual(3); - }); + it('setAttributes overwrites correctly', () => { + obj.setAttributes({ id: 'test', 'data-test': 'value' }); + obj.setAttributes({ 'data-test': 'value2' }); + expect(obj.getAttributes()).toEqual({ 'data-test': 'value2' }); + }); - it('components() set new collection', () => { - obj.append([{}, {}]); - obj.components('test
'); - const result = obj.components(); - expect(result.length).toEqual(1); - expect(result.models[0].get('tagName')).toEqual('span'); - }); + it('append() returns always an array', () => { + let result = obj.append('text1'); + expect(result.length).toEqual(1); + result = obj.append('text1
text2
'); + expect(result.length).toEqual(2); + }); + it('append() new components as string', () => { + obj.append('text1
text2
'); + const comps = obj.components(); + expect(comps.length).toEqual(2); + expect(comps.models[0].get('tagName')).toEqual('span'); + expect(comps.models[1].get('tagName')).toEqual('div'); + }); - it('Propagate properties to children', () => { - obj.append({propagate: 'removable'}); - const result = obj.components(); - const newObj = result.models[0]; - expect(newObj.get('removable')).toEqual(true); - newObj.set('removable', false); - newObj.append({draggable: false}); - const child = newObj.components().models[0]; - expect(child.get('removable')).toEqual(false); - expect(child.get('propagate')).toEqual(['removable']); - }); + it('append() new components as Objects', () => { + obj.append([{}, {}]); + const comps = obj.components(); + expect(comps.length).toEqual(2); + obj.append({}); + expect(comps.length).toEqual(3); + }); + + it('components() set new collection', () => { + obj.append([{}, {}]); + obj.components('test
'); + const result = obj.components(); + expect(result.length).toEqual(1); + expect(result.models[0].get('tagName')).toEqual('span'); + }); + + it('Propagate properties to children', () => { + obj.append({ propagate: 'removable' }); + const result = obj.components(); + const newObj = result.models[0]; + expect(newObj.get('removable')).toEqual(true); + newObj.set('removable', false); + newObj.append({ draggable: false }); + const child = newObj.components().models[0]; + expect(child.get('removable')).toEqual(false); + expect(child.get('propagate')).toEqual(['removable']); + }); - it('Ability to stop/change propagation chain', () => { - obj.append({ - removable: false, - draggable: false, - propagate: ['removable', 'draggable'] - }); - const result = obj.components(); - const newObj = result.models[0]; - newObj.components(` + it('Ability to stop/change propagation chain', () => { + obj.append({ + removable: false, + draggable: false, + propagate: ['removable', 'draggable'] + }); + const result = obj.components(); + const newObj = result.models[0]; + newObj.components(`
comp1
@@ -295,126 +310,123 @@ module.exports = {
TEST
`); - const notInhereted = model => { - expect(model.get('stop')).toEqual(1); - expect(model.get('removable')).toEqual(true); - expect(model.get('draggable')).toEqual(true); - expect(model.get('propagate')).toEqual(['stop']); - model.components().each(model => inhereted(model)) - }; - const inhereted = model => { - if (model.get('stop')) { - notInhereted(model); - } else { - expect(model.get('removable')).toEqual(false); - expect(model.get('draggable')).toEqual(false); - expect(model.get('propagate')).toEqual(['removable', 'draggable']); - model.components().each(model => inhereted(model)) - } + const notInhereted = model => { + expect(model.get('stop')).toEqual(1); + expect(model.get('removable')).toEqual(true); + expect(model.get('draggable')).toEqual(true); + expect(model.get('propagate')).toEqual(['stop']); + model.components().each(model => inhereted(model)); + }; + const inhereted = model => { + if (model.get('stop')) { + notInhereted(model); + } else { + expect(model.get('removable')).toEqual(false); + expect(model.get('draggable')).toEqual(false); + expect(model.get('propagate')).toEqual(['removable', 'draggable']); + model.components().each(model => inhereted(model)); } - newObj.components().each(model => inhereted(model)) - }); + }; + newObj.components().each(model => inhereted(model)); + }); }); describe('Image Component', () => { + beforeEach(() => { + obj = new ComponentImage(); + }); - beforeEach(() => { - obj = new ComponentImage(); - }); - - afterEach(() => { - obj = null; - }); - - it('Has src property', () => { - expect(obj.has('src')).toEqual(true); - }); + afterEach(() => { + obj = null; + }); - it('Not droppable', () => { - expect(obj.get('droppable')).toEqual(false); - }); + it('Has src property', () => { + expect(obj.has('src')).toEqual(true); + }); - it('ComponentImage toHTML', () => { - obj = new ComponentImage(); - expect(obj.toHTML()).toEqual(''); - }); + it('Not droppable', () => { + expect(obj.get('droppable')).toEqual(false); + }); - it('Component toHTML with attributes', () => { - obj = new ComponentImage({ - attributes: {'alt': 'AltTest'}, - src: 'testPath' - }); - expect(obj.toHTML()).toEqual('AltTest'); - }); + it('ComponentImage toHTML', () => { + obj = new ComponentImage(); + expect(obj.toHTML()).toEqual(''); + }); - it('Refuse not img element', () => { - var el = document.createElement('div'); - obj = ComponentImage.isComponent(el); - expect(obj).toEqual(''); + it('Component toHTML with attributes', () => { + obj = new ComponentImage({ + attributes: { alt: 'AltTest' }, + src: 'testPath' }); + expect(obj.toHTML()).toEqual('AltTest'); + }); - it('Component parse img element', () => { - var el = document.createElement('img'); - obj = ComponentImage.isComponent(el); - expect(obj).toEqual({type: 'image'}); - }); + it('Refuse not img element', () => { + var el = document.createElement('div'); + obj = ComponentImage.isComponent(el); + expect(obj).toEqual(''); + }); - it('Component parse img element with src', () => { - var el = document.createElement('img'); - el.src = 'http://localhost/'; - obj = ComponentImage.isComponent(el); - expect(obj).toEqual({type: 'image'}); - }); + it('Component parse img element', () => { + var el = document.createElement('img'); + obj = ComponentImage.isComponent(el); + expect(obj).toEqual({ type: 'image' }); + }); + it('Component parse img element with src', () => { + var el = document.createElement('img'); + el.src = 'http://localhost/'; + obj = ComponentImage.isComponent(el); + expect(obj).toEqual({ type: 'image' }); + }); }); describe('Text Component', () => { + beforeEach(() => { + obj = new ComponentText(); + }); - beforeEach(() => { - obj = new ComponentText(); - }); - - afterEach(() => { - obj = null; - }); + afterEach(() => { + obj = null; + }); - it('Has content property', () => { - expect(obj.has('content')).toEqual(true); - }); + it('Has content property', () => { + expect(obj.has('content')).toEqual(true); + }); - it('Not droppable', () => { - expect(obj.get('droppable')).toEqual(false); - }); + it('Not droppable', () => { + expect(obj.get('droppable')).toEqual(false); + }); - it('Component toHTML with attributes', () => { - obj = new ComponentText({ - attributes: {'data-test': 'value'}, - content: 'test content' - }); - expect(obj.toHTML()).toEqual('
test content
'); + it('Component toHTML with attributes', () => { + obj = new ComponentText({ + attributes: { 'data-test': 'value' }, + content: 'test content' }); - + expect(obj.toHTML()).toEqual( + '
test content
' + ); + }); }); describe('Link Component', () => { - const aEl = document.createElement('a'); it('Component parse link element', () => { obj = ComponentLink.isComponent(aEl); - expect(obj).toEqual({type: 'link'}); + expect(obj).toEqual({ type: 'link' }); }); it('Component parse link element with text content', () => { aEl.innerHTML = 'some text here '; obj = ComponentLink.isComponent(aEl); - expect(obj).toEqual({type: 'link'}); + expect(obj).toEqual({ type: 'link' }); }); it('Component parse link element with not only text content', () => { aEl.innerHTML = '
Some
text
here
'; obj = ComponentLink.isComponent(aEl); - expect(obj).toEqual({type: 'link'}); + expect(obj).toEqual({ type: 'link' }); }); it('Component parse link element with only not text content', () => { @@ -422,86 +434,82 @@ module.exports = {
text
here
`; obj = ComponentLink.isComponent(aEl); - expect(obj).toEqual({type: 'link', editable: 0}); + expect(obj).toEqual({ type: 'link', editable: 0 }); }); it('Link element with only an image inside is not editable', () => { aEl.innerHTML = ''; obj = ComponentLink.isComponent(aEl); - expect(obj).toEqual({type: 'link', editable: 0}); + expect(obj).toEqual({ type: 'link', editable: 0 }); }); - }); describe('Map Component', () => { - it('Component parse map iframe', () => { - var src = 'https://maps.google.com/maps?&q=London,UK&z=11&t=q&output=embed'; + var src = + 'https://maps.google.com/maps?&q=London,UK&z=11&t=q&output=embed'; var el = $(''); obj = ComponentMap.isComponent(el.get(0)); - expect(obj).toEqual({type: 'map', src}); + expect(obj).toEqual({ type: 'map', src }); }); it('Component parse not map iframe', () => { - var el = $(''); + var el = $( + '' + ); obj = ComponentMap.isComponent(el.get(0)); expect(obj).toEqual(''); }); - }); describe('Video Component', () => { - it('Component parse video', () => { var src = 'http://localhost/'; var el = $(''); obj = ComponentVideo.isComponent(el.get(0)); - expect(obj).toEqual({type: 'video', src}); + expect(obj).toEqual({ type: 'video', src }); }); it('Component parse youtube video iframe', () => { var src = 'http://www.youtube.com/embed/jNQXAC9IVRw?'; var el = $('