From fed24237268b378d530805d4be775e6979cb326f Mon Sep 17 00:00:00 2001 From: Artur Arseniev Date: Thu, 1 Jun 2017 00:12:13 +0200 Subject: [PATCH] Remove all define in src --- package.json | 11 +- src/asset_manager/config/config.js | 26 +- src/asset_manager/index.js | 408 +++-- src/asset_manager/model/Asset.js | 52 +- src/asset_manager/model/AssetImage.js | 24 +- src/asset_manager/model/Assets.js | 138 +- src/asset_manager/view/AssetImageView.js | 174 +- src/asset_manager/view/AssetView.js | 26 +- src/asset_manager/view/AssetsView.js | 270 ++- src/asset_manager/view/FileUploader.js | 182 +- src/block_manager/config/config.js | 8 +- src/block_manager/index.js | 166 +- src/block_manager/model/Block.js | 19 +- src/block_manager/model/Blocks.js | 15 +- src/block_manager/view/BlockView.js | 85 +- src/block_manager/view/BlocksView.js | 241 ++- src/canvas/config/config.js | 22 +- src/canvas/index.js | 652 ++++--- src/canvas/model/Canvas.js | 29 +- src/canvas/model/Frame.js | 21 +- src/canvas/view/CanvasView.js | 481 +++--- src/canvas/view/FrameView.js | 105 +- src/code_manager/config/config.js | 12 +- src/code_manager/index.js | 410 +++-- src/code_manager/model/CodeMirrorEditor.js | 87 +- src/code_manager/model/CssGenerator.js | 283 ++- src/code_manager/model/HtmlGenerator.js | 35 +- src/code_manager/model/JsGenerator.js | 107 +- src/code_manager/model/JsonGenerator.js | 67 +- src/code_manager/view/EditorView.js | 49 +- src/commands/config/config.js | 32 +- src/commands/index.js | 388 +++-- src/commands/model/Command.js | 23 +- src/commands/model/Commands.js | 21 +- src/commands/view/CommandAbstract.js | 228 ++- src/commands/view/CreateComponent.js | 463 +++-- src/commands/view/DeleteComponent.js | 145 +- src/commands/view/ExportTemplate.js | 128 +- src/commands/view/Fullscreen.js | 157 +- src/commands/view/ImageComponent.js | 68 +- src/commands/view/InsertCustom.js | 142 +- src/commands/view/MoveComponent.js | 299 ++-- src/commands/view/OpenAssets.js | 35 +- src/commands/view/OpenBlocks.js | 49 +- src/commands/view/OpenLayers.js | 62 +- src/commands/view/OpenStyleManager.js | 142 +- src/commands/view/OpenTraitManager.js | 57 +- src/commands/view/Preview.js | 121 +- src/commands/view/Resize.js | 52 +- src/commands/view/SelectComponent.js | 998 ++++++----- src/commands/view/SelectPosition.js | 187 +- src/commands/view/ShowOffset.js | 296 ++-- src/commands/view/SwitchVisibility.js | 18 +- src/commands/view/TextComponent.js | 62 +- src/css_composer/config/config.js | 18 +- src/css_composer/index.js | 442 +++-- src/css_composer/model/CssRule.js | 188 +- src/css_composer/model/CssRules.js | 52 +- src/css_composer/model/Selectors.js | 32 +- src/css_composer/view/CssRuleView.js | 136 +- src/css_composer/view/CssRulesView.js | 124 +- src/device_manager/config/config.js | 10 +- src/device_manager/index.js | 178 +- src/device_manager/model/Device.js | 19 +- src/device_manager/view/DevicesView.js | 145 +- src/dom_components/config/config.js | 48 +- src/dom_components/index.js | 663 ++++--- src/dom_components/model/Component.js | 727 ++++---- src/dom_components/model/ComponentImage.js | 183 +- src/dom_components/model/ComponentLink.js | 71 +- src/dom_components/model/ComponentMap.js | 197 ++- src/dom_components/model/ComponentScript.js | 43 +- src/dom_components/model/ComponentTable.js | 159 +- .../model/ComponentTableCell.js | 59 +- src/dom_components/model/ComponentTableRow.js | 77 +- src/dom_components/model/ComponentText.js | 19 +- src/dom_components/model/ComponentTextNode.js | 45 +- src/dom_components/model/ComponentVideo.js | 593 ++++--- src/dom_components/model/Components.js | 129 +- src/dom_components/model/Toolbar.js | 10 +- src/dom_components/model/ToolbarButton.js | 18 +- src/dom_components/view/ComponentImageView.js | 121 +- src/dom_components/view/ComponentLinkView.js | 31 +- src/dom_components/view/ComponentMapView.js | 89 +- .../view/ComponentScriptView.js | 69 +- .../view/ComponentTableCellView.js | 10 +- .../view/ComponentTableRowView.js | 10 +- src/dom_components/view/ComponentTableView.js | 15 +- .../view/ComponentTextNodeView.js | 7 +- src/dom_components/view/ComponentTextView.js | 215 ++- src/dom_components/view/ComponentVideoView.js | 211 ++- src/dom_components/view/ComponentView.js | 781 +++++---- src/dom_components/view/ComponentsView.js | 189 +- src/dom_components/view/ToolbarButtonView.js | 56 +- src/domain_abstract/ui/Input.js | 145 +- src/domain_abstract/ui/InputColor.js | 133 +- src/domain_abstract/ui/InputNumber.js | 481 +++--- src/domain_abstract/view/DomainViews.js | 107 +- src/editor/config/config.js | 555 +++--- src/editor/index.js | 836 +++++---- src/editor/model/Editor.js | 1101 ++++++------ src/editor/view/EditorView.js | 93 +- src/grapesjs/config/config.js | 48 +- src/grapesjs/index.js | 152 +- src/index.js | 2 + src/main.js | 1 - src/modal_dialog/config/config.js | 14 +- src/modal_dialog/index.js | 280 ++- src/modal_dialog/model/Modal.js | 20 +- src/modal_dialog/view/ModalView.js | 197 ++- src/navigator/config/config.js | 20 +- src/navigator/index.js | 47 +- src/navigator/view/ItemView.js | 521 +++--- src/navigator/view/ItemsView.js | 223 ++- src/panels/config/config.js | 174 +- src/panels/index.js | 335 ++-- src/panels/model/Button.js | 49 +- src/panels/model/Buttons.js | 81 +- src/panels/model/Panel.js | 43 +- src/panels/model/Panels.js | 15 +- src/panels/view/ButtonView.js | 643 ++++--- src/panels/view/ButtonsView.js | 117 +- src/panels/view/PanelView.js | 103 +- src/panels/view/PanelsView.js | 120 +- src/parser/config/config.js | 8 +- src/parser/index.js | 122 +- src/parser/model/ParserCss.js | 286 ++- src/parser/model/ParserHtml.js | 428 +++-- src/plugin_manager/config/config.js | 10 +- src/plugin_manager/index.js | 114 +- src/rich_text_editor/config/config.js | 72 +- src/rich_text_editor/index.js | 442 +++-- src/rich_text_editor/model/CommandButton.js | 36 +- src/rich_text_editor/model/CommandButtons.js | 14 +- .../view/CommandButtonSelectView.js | 78 +- .../view/CommandButtonView.js | 29 +- .../view/CommandButtonsView.js | 132 +- src/rich_text_editor/view/TextEditorView.js | 441 +++-- src/selector_manager/config/config.js | 34 +- src/selector_manager/index.js | 188 +- src/selector_manager/model/Selector.js | 54 +- src/selector_manager/model/Selectors.js | 15 +- src/selector_manager/view/ClassTagView.js | 263 ++- src/selector_manager/view/ClassTagsView.js | 564 +++--- src/storage_manager/config/config.js | 81 +- src/storage_manager/index.js | 458 +++-- src/storage_manager/model/LocalStorage.js | 119 +- src/storage_manager/model/RemoteStorage.js | 119 +- src/style_manager/config/config.js | 23 +- src/style_manager/index.js | 383 ++--- src/style_manager/model/Layer.js | 49 +- src/style_manager/model/Layers.js | 37 +- src/style_manager/model/Properties.js | 15 +- src/style_manager/model/Property.js | 121 +- src/style_manager/model/PropertyFactory.js | 889 +++++----- src/style_manager/model/Sector.js | 173 +- src/style_manager/model/Sectors.js | 15 +- src/style_manager/view/LayerView.js | 349 ++-- src/style_manager/view/LayersView.js | 233 ++- src/style_manager/view/PropertiesView.js | 127 +- src/style_manager/view/PropertyColorView.js | 49 +- .../view/PropertyCompositeView.js | 281 ++- src/style_manager/view/PropertyFileView.js | 261 ++- src/style_manager/view/PropertyIntegerView.js | 71 +- src/style_manager/view/PropertyRadioView.js | 109 +- src/style_manager/view/PropertySelectView.js | 65 +- src/style_manager/view/PropertyStackView.js | 613 ++++--- src/style_manager/view/PropertyView.js | 783 +++++---- src/style_manager/view/SectorView.js | 193 +-- src/style_manager/view/SectorsView.js | 261 ++- src/trait_manager/config/config.js | 10 +- src/trait_manager/index.js | 141 +- src/trait_manager/model/Trait.js | 47 +- src/trait_manager/model/TraitFactory.js | 119 +- src/trait_manager/model/Traits.js | 49 +- src/trait_manager/view/TraitCheckboxView.js | 77 +- src/trait_manager/view/TraitColorView.js | 71 +- src/trait_manager/view/TraitNumberView.js | 87 +- src/trait_manager/view/TraitSelectView.js | 117 +- src/trait_manager/view/TraitView.js | 272 ++- src/trait_manager/view/TraitsView.js | 84 +- src/utils/Resizer.js | 758 ++++---- src/utils/Sorter.js | 1529 ++++++++--------- src/utils/index.js | 43 +- src/wrappers/jquery.js | 5 +- test/helper.js | 11 + test/main.js | 13 + test/specs/asset_manager/main.js | 16 +- test/specs/asset_manager/model/Asset.js | 7 +- test/specs/asset_manager/model/AssetImage.js | 7 +- test/specs/asset_manager/model/Assets.js | 7 +- .../asset_manager/view/AssetImageView.js | 11 +- test/specs/asset_manager/view/AssetView.js | 9 +- test/specs/asset_manager/view/AssetsView.js | 8 +- test/specs/asset_manager/view/FileUploader.js | 7 +- test/specs/block_manager/main.js | 10 +- test/specs/block_manager/view/BlocksView.js | 9 +- test/specs/code_manager/main.js | 14 +- test/specs/code_manager/model/CodeModels.js | 19 +- test/specs/commands/main.js | 14 +- test/specs/commands/model/CommandModels.js | 8 +- test/specs/css_composer/e2e/CssComposer.js | 9 +- test/specs/css_composer/main.js | 25 +- test/specs/css_composer/model/CssModels.js | 16 +- test/specs/css_composer/view/CssRuleView.js | 11 +- test/specs/css_composer/view/CssRulesView.js | 9 +- test/specs/device_manager/main.js | 10 +- test/specs/device_manager/view/DevicesView.js | 9 +- test/specs/dom_components/main.js | 26 +- test/specs/dom_components/model/Component.js | 26 +- .../dom_components/view/ComponentImageView.js | 11 +- .../dom_components/view/ComponentTextView.js | 11 +- test/specs/dom_components/view/ComponentV.js | 12 +- .../dom_components/view/ComponentsView.js | 12 +- test/specs/grapesjs/main.js | 9 +- test/specs/main.js | 11 - test/specs/modal/main.js | 10 +- test/specs/modal/view/ModalView.js | 9 +- test/specs/panels/e2e/PanelsE2e.js | 8 +- test/specs/panels/main.js | 24 +- test/specs/panels/model/PanelModels.js | 13 +- test/specs/panels/view/ButtonView.js | 9 +- test/specs/panels/view/ButtonsView.js | 9 +- test/specs/panels/view/PanelView.js | 9 +- test/specs/panels/view/PanelsView.js | 9 +- test/specs/parser/main.js | 16 +- test/specs/parser/model/ParserCss.js | 10 +- test/specs/parser/model/ParserHtml.js | 11 +- test/specs/plugin_manager/main.js | 6 +- .../selector_manager/e2e/ClassManager.js | 12 +- test/specs/selector_manager/main.js | 20 +- .../selector_manager/model/SelectorModels.js | 11 +- .../selector_manager/view/ClassTagView.js | 9 +- .../selector_manager/view/ClassTagsView.js | 9 +- test/specs/storage_manager/main.js | 14 +- test/specs/storage_manager/model/Models.js | 11 +- test/specs/style_manager/main.js | 34 +- test/specs/style_manager/model/Models.js | 24 +- test/specs/style_manager/view/LayerView.js | 9 +- .../style_manager/view/PropertyColorView.js | 12 +- .../view/PropertyCompositeView.js | 10 +- .../style_manager/view/PropertyIntegerView.js | 12 +- .../style_manager/view/PropertyRadioView.js | 10 +- .../style_manager/view/PropertySelectView.js | 10 +- .../style_manager/view/PropertyStackView.js | 12 +- test/specs/style_manager/view/PropertyView.js | 10 +- test/specs/style_manager/view/SectorView.js | 11 +- test/specs/style_manager/view/SectorsView.js | 9 +- test/specs/trait_manager/main.js | 13 +- test/specs/trait_manager/model/TraitsModel.js | 10 +- test/specs/trait_manager/view/TraitsView.js | 13 +- test/specs/utils/Sorter.js | 8 +- test/specs/utils/main.js | 14 +- webpack.config.js | 2 +- yarn.lock | 682 +++----- 255 files changed, 17243 insertions(+), 18107 deletions(-) create mode 100644 src/index.js delete mode 100644 src/main.js create mode 100644 test/helper.js create mode 100644 test/main.js delete mode 100644 test/specs/main.js diff --git a/package.json b/package.json index 3823a2cb5..aec35dfae 100644 --- a/package.json +++ b/package.json @@ -30,7 +30,9 @@ "babel-preset-es2015": "^6.24.1", "chai": "^3.5.0", "documentation": "^4.0.0-beta2", + "expect": "^1.20.2", "istanbul": "^0.4.2", + "jsdom": "^11.0.0", "mocha": "^3.1.2", "node-sass": "^3.4.2", "requirejs": "^2.3.2", @@ -55,14 +57,19 @@ "template", "editor" ], + "babel": { + "presets": [ + "es2015" + ] + }, "scripts": { "lint": "eslint src", - "build": "WEBPACK_ENV=prod && npm run v:patch && webpack && npm run build:css", + "build": "WEBPACK_ENV=prod && npm run test && npm run v:patch && webpack && npm run build:css", "build:css": "node-sass styles/scss/main.scss dist/css/grapesjs.min.css", "build:fonts": "./node_modules/.bin/grunt build:fonts", "v:patch": "npm version --no-git-tag-version patch", "start": "WEBPACK_ENV=dev webpack-dev-server --progress --colors & npm run build:css -- -w", - "test": "mocha --compilers js:babel-core/register --require ./test/helper.js --recursive ./test/*.js", + "test": "NODE_PATH=./src mocha --compilers js:babel-core/register --require test/helper.js --recursive test/main.js", "test:dev": "npm test -- -R min -w" } } diff --git a/src/asset_manager/config/config.js b/src/asset_manager/config/config.js index 6ee2ad3ff..1c1bdf983 100644 --- a/src/asset_manager/config/config.js +++ b/src/asset_manager/config/config.js @@ -1,18 +1,16 @@ -define(function () { - return { - // Default assets - assets: [], +module.exports = { + // Default assets + assets: [], - // Style prefix - stylePrefix: 'am-', + // Style prefix + stylePrefix: 'am-', - // Url where uploads will be send, set false to disable upload - upload: 'http://localhost/assets/upload', + // Url where uploads will be send, set false to disable upload + upload: 'http://localhost/assets/upload', - // Text on upload input - uploadText: 'Drop files here or click to upload', + // Text on upload input + uploadText: 'Drop files here or click to upload', - // Label for the add button - addBtnText: 'Add image', - }; -}); + // Label for the add button + addBtnText: 'Add image', +}; diff --git a/src/asset_manager/index.js b/src/asset_manager/index.js index 120dc4e5f..49ba769e2 100644 --- a/src/asset_manager/index.js +++ b/src/asset_manager/index.js @@ -33,209 +33,207 @@ * uploadText: 'Drop files here or click to upload', * } */ -define(function(require) { - - return function() { - var c = {}, - Assets = require('./model/Assets'), - AssetsView = require('./view/AssetsView'), - FileUpload = require('./view/FileUploader'), - assets, am, fu; - - return { - - /** - * Name of the module - * @type {String} - * @private - */ - name: 'AssetManager', - - /** - * Mandatory for the storage manager - * @type {String} - * @private - */ - storageKey: 'assets', - - /** - * Initialize module - * @param {Object} config Configurations - * @private - */ - init: function(config){ - c = config || {}; - var defaults = require('./config/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; - - assets = new Assets(c.assets); - var obj = { - collection: assets, - config: c, - }; - am = new AssetsView(obj); - fu = new FileUpload(obj); - return this; - }, - - /** - * Add new asset/s to the collection. URLs are supposed to be unique - * @param {string|Object|Array|Array} asset URL strings or an objects representing the resource. - * @return {Model} - * @example - * // In case of strings, would be interpreted as images - * assetManager.add('http://img.jpg'); - * assetManager.add(['http://img.jpg', './path/to/img.png']); - * - * // Using objects you could indicate the type and other meta informations - * assetManager.add({ - * src: 'http://img.jpg', - * //type: 'image', //image is default - * height: 300, - * width: 200, - * }); - * assetManager.add([{ - * src: 'http://img.jpg', - * },{ - * src: './path/to/img.png', - * }]); - */ - add: function(asset){ - return assets.add(asset); - }, - - /** - * Returns the asset by URL - * @param {string} src URL of the asset - * @return {Object} Object representing the asset - * @example - * var asset = assetManager.get('http://img.jpg'); - */ - get: function(src){ - return assets.where({src: src})[0]; - }, - - /** - * Return all assets - * @return {Collection} - */ - getAll: function(){ - return assets; - }, - - /** - * Remove the asset by its URL - * @param {string} src URL of the asset - * @return {this} - * @example - * assetManager.remove('http://img.jpg'); - */ - remove: function(src){ - var asset = this.get(src); - this.getAll().remove(asset); - return this; - }, - - /** - * Store assets data to the selected storage - * @param {Boolean} noStore If true, won't store - * @return {Object} Data to store - * @example - * var assets = assetManager.store(); - */ - store: function(noStore){ - var obj = {}; - var assets = JSON.stringify(this.getAll().toJSON()); - obj[this.storageKey] = assets; - if(!noStore && c.stm) - c.stm.store(obj); - return obj; - }, - - /** - * 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 assets - * @example - * var assets = assetManager.load(); - * // The format below will be used by the editor model - * // to load automatically all the stuff - * var assets = assetManager.load({ - * assets: [...] - * }); - * - */ - load: function(data){ - var d = data || ''; - var name = this.storageKey; - if(!d && c.stm) - d = c.stm.load(name); - var assets = []; - try{ - assets = JSON.parse(d[name]); - }catch(err){} - this.getAll().add(assets); - return assets; - }, - - /** - * Render assets - * @param {Boolean} f Force to render, otherwise cached version will be returned - * @return {HTMLElement} - * @private - */ - render: function(f){ - if(!this.rendered || f) - this.rendered = am.render().$el.add(fu.render().$el); - return this.rendered; - }, - - //------- - - /** - * Set new target - * @param {Object} m Model - * @private - * */ - setTarget: function(m){ - am.collection.target = m; - }, - - /** - * Set callback after asset was selected - * @param {Object} f Callback function - * @private - * */ - onSelect: function(f){ - am.collection.onSelect = f; - }, - - /** - * Set callback to fire when the asset is clicked - * @param {function} func - */ - onClick: function(func) { - c.onClick = func; - }, - - /** - * Set callback to fire when the asset is double clicked - * @param {function} func - */ - onDblClick: function(func) { - c.onDblClick = func; - }, - - }; + +module.exports = function() { + var c = {}, + Assets = require('./model/Assets'), + AssetsView = require('./view/AssetsView'), + FileUpload = require('./view/FileUploader'), + assets, am, fu; + + return { + + /** + * Name of the module + * @type {String} + * @private + */ + name: 'AssetManager', + + /** + * Mandatory for the storage manager + * @type {String} + * @private + */ + storageKey: 'assets', + + /** + * Initialize module + * @param {Object} config Configurations + * @private + */ + init: function(config){ + c = config || {}; + var defaults = require('./config/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; + + assets = new Assets(c.assets); + var obj = { + collection: assets, + config: c, + }; + am = new AssetsView(obj); + fu = new FileUpload(obj); + return this; + }, + + /** + * Add new asset/s to the collection. URLs are supposed to be unique + * @param {string|Object|Array|Array} asset URL strings or an objects representing the resource. + * @return {Model} + * @example + * // In case of strings, would be interpreted as images + * assetManager.add('http://img.jpg'); + * assetManager.add(['http://img.jpg', './path/to/img.png']); + * + * // Using objects you could indicate the type and other meta informations + * assetManager.add({ + * src: 'http://img.jpg', + * //type: 'image', //image is default + * height: 300, + * width: 200, + * }); + * assetManager.add([{ + * src: 'http://img.jpg', + * },{ + * src: './path/to/img.png', + * }]); + */ + add: function(asset){ + return assets.add(asset); + }, + + /** + * Returns the asset by URL + * @param {string} src URL of the asset + * @return {Object} Object representing the asset + * @example + * var asset = assetManager.get('http://img.jpg'); + */ + get: function(src){ + return assets.where({src: src})[0]; + }, + + /** + * Return all assets + * @return {Collection} + */ + getAll: function(){ + return assets; + }, + + /** + * Remove the asset by its URL + * @param {string} src URL of the asset + * @return {this} + * @example + * assetManager.remove('http://img.jpg'); + */ + remove: function(src){ + var asset = this.get(src); + this.getAll().remove(asset); + return this; + }, + + /** + * Store assets data to the selected storage + * @param {Boolean} noStore If true, won't store + * @return {Object} Data to store + * @example + * var assets = assetManager.store(); + */ + store: function(noStore){ + var obj = {}; + var assets = JSON.stringify(this.getAll().toJSON()); + obj[this.storageKey] = assets; + if(!noStore && c.stm) + c.stm.store(obj); + return obj; + }, + + /** + * 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 assets + * @example + * var assets = assetManager.load(); + * // The format below will be used by the editor model + * // to load automatically all the stuff + * var assets = assetManager.load({ + * assets: [...] + * }); + * + */ + load: function(data){ + var d = data || ''; + var name = this.storageKey; + if(!d && c.stm) + d = c.stm.load(name); + var assets = []; + try{ + assets = JSON.parse(d[name]); + }catch(err){} + this.getAll().add(assets); + return assets; + }, + + /** + * Render assets + * @param {Boolean} f Force to render, otherwise cached version will be returned + * @return {HTMLElement} + * @private + */ + render: function(f){ + if(!this.rendered || f) + this.rendered = am.render().$el.add(fu.render().$el); + return this.rendered; + }, + + //------- + + /** + * Set new target + * @param {Object} m Model + * @private + * */ + setTarget: function(m){ + am.collection.target = m; + }, + + /** + * Set callback after asset was selected + * @param {Object} f Callback function + * @private + * */ + onSelect: function(f){ + am.collection.onSelect = f; + }, + + /** + * Set callback to fire when the asset is clicked + * @param {function} func + */ + onClick: function(func) { + c.onClick = func; + }, + + /** + * Set callback to fire when the asset is double clicked + * @param {function} func + */ + onDblClick: function(func) { + c.onDblClick = func; + }, + }; -}); +}; diff --git a/src/asset_manager/model/Asset.js b/src/asset_manager/model/Asset.js index 539508a66..0aec9217e 100644 --- a/src/asset_manager/model/Asset.js +++ b/src/asset_manager/model/Asset.js @@ -1,32 +1,30 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - module.exports = Backbone.Model.extend({ +var Backbone = require('backbone'); - idAttribute: 'src', +module.exports = Backbone.Model.extend({ - defaults: { - type: '', - src: '', - }, + idAttribute: 'src', - /** - * Get filename of the asset - * @return {string} - * @private - * */ - getFilename: function(){ - return this.get('src').split('/').pop(); - }, + defaults: { + type: '', + src: '', + }, - /** - * Get extension of the asset - * @return {string} - * @private - * */ - getExtension: function(){ - return this.getFilename().split('.').pop(); - }, + /** + * Get filename of the asset + * @return {string} + * @private + * */ + getFilename: function(){ + return this.get('src').split('/').pop(); + }, - }); -}); \ No newline at end of file + /** + * Get extension of the asset + * @return {string} + * @private + * */ + getExtension: function(){ + return this.getFilename().split('.').pop(); + }, + +}); diff --git a/src/asset_manager/model/AssetImage.js b/src/asset_manager/model/AssetImage.js index 273d683c8..207a86b73 100644 --- a/src/asset_manager/model/AssetImage.js +++ b/src/asset_manager/model/AssetImage.js @@ -1,15 +1,13 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var Asset = require('./Asset'); - module.exports = Asset.extend({ +var Backbone = require('backbone'); +var Asset = require('./Asset'); - defaults: _.extend({}, Asset.prototype.defaults, { - type: 'image', - unitDim: 'px', - height: 0, - width: 0, - }), +module.exports = Asset.extend({ - }); -}); \ No newline at end of file + defaults: _.extend({}, Asset.prototype.defaults, { + type: 'image', + unitDim: 'px', + height: 0, + width: 0, + }), + +}); diff --git a/src/asset_manager/model/Assets.js b/src/asset_manager/model/Assets.js index 9d736945e..371710df6 100644 --- a/src/asset_manager/model/Assets.js +++ b/src/asset_manager/model/Assets.js @@ -1,70 +1,68 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var Asset = require('./Asset'); - var AssetImage = require('./AssetImage'); - module.exports = Backbone.Collection.extend({ - - model: AssetImage, - - initialize: function(models, opt){ - - this.model = function(attrs, options) { - var model; - switch(attrs.type){ - default: - model = new AssetImage(attrs, options); - } - return model; - }; - - }, - - /** - * Add new image asset to the collection - * @param {string} url URL of the image - * @param {Object} opts Options - * @return {this} - * @private - */ - addImg: function(url, opts){ - this.add({ - type: 'image', - src: url, - }, opts); - return this; - }, - - /** - * Prevent inserting assets with the same 'src' - * Seems like idAttribute is not working with dynamic model assignament - * @private - */ - add: function(models, opt) { - var mods = []; - models = models instanceof Array ? models : [models]; - - for (var i = 0, len = models.length; i < len; i++) { - var model = models[i]; - - if(typeof model === 'string') - model = {src: model, type: 'image'}; - - if(!model || !model.src) - continue; - - var found = this.where({src: model.src}); - - if(!found.length) - mods.push(model); - } - - if(mods.length == 1) - mods = mods[0]; - - return Backbone.Collection.prototype.add.apply(this, [mods, opt]); - }, - - - }); -}); \ No newline at end of file +var Backbone = require('backbone'); +var Asset = require('./Asset'); +var AssetImage = require('./AssetImage'); + +module.exports = Backbone.Collection.extend({ + + model: AssetImage, + + initialize: function(models, opt){ + + this.model = function(attrs, options) { + var model; + switch(attrs.type){ + default: + model = new AssetImage(attrs, options); + } + return model; + }; + + }, + + /** + * Add new image asset to the collection + * @param {string} url URL of the image + * @param {Object} opts Options + * @return {this} + * @private + */ + addImg: function(url, opts){ + this.add({ + type: 'image', + src: url, + }, opts); + return this; + }, + + /** + * Prevent inserting assets with the same 'src' + * Seems like idAttribute is not working with dynamic model assignament + * @private + */ + add: function(models, opt) { + var mods = []; + models = models instanceof Array ? models : [models]; + + for (var i = 0, len = models.length; i < len; i++) { + var model = models[i]; + + if(typeof model === 'string') + model = {src: model, type: 'image'}; + + if(!model || !model.src) + continue; + + var found = this.where({src: model.src}); + + if(!found.length) + mods.push(model); + } + + if(mods.length == 1) + mods = mods[0]; + + return Backbone.Collection.prototype.add.apply(this, [mods, opt]); + }, + + +}); diff --git a/src/asset_manager/view/AssetImageView.js b/src/asset_manager/view/AssetImageView.js index e1052a85c..d5d32b794 100644 --- a/src/asset_manager/view/AssetImageView.js +++ b/src/asset_manager/view/AssetImageView.js @@ -1,99 +1,97 @@ -define(function(require, exports, module){ - 'use strict'; - var AssetView = require('./AssetView'); - var assetTemplate = require('text!./../template/assetImage.html'); - module.exports = AssetView.extend({ +var AssetView = require('./AssetView'); +var assetTemplate = require('text!./../template/assetImage.html'); - events:{ - 'click': 'handleClick', - 'dblclick': 'handleDblClick', - }, +module.exports = AssetView.extend({ - template: _.template(assetTemplate), + events:{ + 'click': 'handleClick', + 'dblclick': 'handleDblClick', + }, - initialize: function(o) { - AssetView.prototype.initialize.apply(this, arguments); - this.className += ' ' + this.pfx + 'asset-image'; - this.events['click #' + this.pfx + 'close'] = 'removeItem'; - this.delegateEvents(); - }, + template: _.template(assetTemplate), - /** - * Trigger when the asset is clicked - * @private - * */ - handleClick: function() { - var onClick = this.config.onClick; - var model = this.model; - model.collection.trigger('deselectAll'); - this.$el.addClass(this.pfx + 'highlight'); + initialize: function(o) { + AssetView.prototype.initialize.apply(this, arguments); + this.className += ' ' + this.pfx + 'asset-image'; + this.events['click #' + this.pfx + 'close'] = 'removeItem'; + this.delegateEvents(); + }, - if (typeof onClick === 'function') { - onClick(model); - } else { - this.updateTarget(model.get('src')); - } - }, + /** + * Trigger when the asset is clicked + * @private + * */ + handleClick: function() { + var onClick = this.config.onClick; + var model = this.model; + model.collection.trigger('deselectAll'); + this.$el.addClass(this.pfx + 'highlight'); - /** - * Trigger when the asset is double clicked - * @private - * */ - handleDblClick: function() { - var onDblClick = this.config.onDblClick; - var model = this.model; + if (typeof onClick === 'function') { + onClick(model); + } else { + this.updateTarget(model.get('src')); + } + }, - if (typeof onDblClick === 'function') { - onDblClick(model); - } else { - this.updateTarget(model.get('src')); - } + /** + * Trigger when the asset is double clicked + * @private + * */ + handleDblClick: function() { + var onDblClick = this.config.onDblClick; + var model = this.model; - var onSelect = model.collection.onSelect; - if(typeof onSelect == 'function'){ - onSelect(this.model); - } - }, + if (typeof onDblClick === 'function') { + onDblClick(model); + } else { + this.updateTarget(model.get('src')); + } - /** - * Update target if exists - * @param {String} v Value - * @private - * */ - updateTarget: function(v){ - var target = this.model.collection.target; - if(target && target.set) { - var attr = _.clone( target.get('attributes') ); - target.set('attributes', attr ); - target.set('src', v ); - } - }, + var onSelect = model.collection.onSelect; + if(typeof onSelect == 'function'){ + onSelect(this.model); + } + }, - /** - * Remove asset from collection - * @private - * */ - removeItem: function(e){ - e.stopPropagation(); - this.model.collection.remove(this.model); - }, + /** + * Update target if exists + * @param {String} v Value + * @private + * */ + updateTarget: function(v){ + var target = this.model.collection.target; + if(target && target.set) { + var attr = _.clone( target.get('attributes') ); + target.set('attributes', attr ); + target.set('src', v ); + } + }, - render : function(){ - var name = this.model.get('name'), - dim = this.model.get('width') && this.model.get('height') ? - this.model.get('width')+' x '+this.model.get('height') : ''; - name = name ? name : this.model.get('src').split("/").pop(); - name = name && name.length > 30 ? name.substring(0, 30)+'...' : name; - dim = dim ? dim + (this.model.get('unitDim') ? this.model.get('unitDim') : ' px' ) : ''; - this.$el.html( this.template({ - name: name, - src: this.model.get('src'), - dim: dim, - pfx: this.pfx, - ppfx: this.ppfx - })); - this.$el.attr('class', this.className); - return this; - }, - }); -}); \ No newline at end of file + /** + * Remove asset from collection + * @private + * */ + removeItem: function(e){ + e.stopPropagation(); + this.model.collection.remove(this.model); + }, + + render : function(){ + var name = this.model.get('name'), + dim = this.model.get('width') && this.model.get('height') ? + this.model.get('width')+' x '+this.model.get('height') : ''; + name = name ? name : this.model.get('src').split("/").pop(); + name = name && name.length > 30 ? name.substring(0, 30)+'...' : name; + dim = dim ? dim + (this.model.get('unitDim') ? this.model.get('unitDim') : ' px' ) : ''; + this.$el.html( this.template({ + name: name, + src: this.model.get('src'), + dim: dim, + pfx: this.pfx, + ppfx: this.ppfx + })); + this.$el.attr('class', this.className); + return this; + }, +}); diff --git a/src/asset_manager/view/AssetView.js b/src/asset_manager/view/AssetView.js index 7bd5a11d5..3f8f40754 100644 --- a/src/asset_manager/view/AssetView.js +++ b/src/asset_manager/view/AssetView.js @@ -1,16 +1,12 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); +var Backbone = require('backbone'); - module.exports = Backbone.View.extend({ - initialize: function(o) { - this.options = o; - this.config = o.config || {}; - this.pfx = this.config.stylePrefix || ''; - this.ppfx = this.config.pStylePrefix || ''; - this.className = this.pfx + 'asset'; - this.listenTo( this.model, 'destroy remove', this.remove); - }, - }); - -}); \ No newline at end of file +module.exports = Backbone.View.extend({ + initialize: function(o) { + this.options = o; + this.config = o.config || {}; + this.pfx = this.config.stylePrefix || ''; + this.ppfx = this.config.pStylePrefix || ''; + this.className = this.pfx + 'asset'; + this.listenTo( this.model, 'destroy remove', this.remove); + }, +}); diff --git a/src/asset_manager/view/AssetsView.js b/src/asset_manager/view/AssetsView.js index 855309ab8..16ce777f6 100644 --- a/src/asset_manager/view/AssetsView.js +++ b/src/asset_manager/view/AssetsView.js @@ -1,136 +1,134 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var AssetView = require('./AssetView'); - var AssetImageView = require('./AssetImageView'); - var FileUploader = require('./FileUploader'); - var assetsTemplate = require('text!./../template/assets.html'); - module.exports = Backbone.View.extend({ - - template: _.template(assetsTemplate), - - initialize: function(o) { - this.options = o; - this.config = o.config; - this.pfx = this.config.stylePrefix || ''; - this.ppfx = this.config.pStylePrefix || ''; - this.listenTo( this.collection, 'add', this.addToAsset ); - this.listenTo( this.collection, 'deselectAll', this.deselectAll ); - this.className = this.pfx + 'assets'; - - this.events = {}; - this.events.submit = 'addFromStr'; - this.delegateEvents(); - }, - - /** - * Add new asset to the collection via string - * @param {Event} e Event object - * @return {this} - * @private - */ - addFromStr: function(e){ - e.preventDefault(); - - var input = this.getInputUrl(); - - var url = input.value.trim(); - - if(!url) - return; - - this.collection.addImg(url, {at: 0}); - - this.getAssetsEl().scrollTop = 0; - input.value = ''; - return this; - }, - - /** - * Returns assets element - * @return {HTMLElement} - * @private - */ - getAssetsEl: function(){ - //if(!this.assets) // Not able to cache as after the rerender it losses the ref - this.assets = this.el.querySelector('.' + this.pfx + 'assets'); - return this.assets; - }, - - /** - * Returns input url element - * @return {HTMLElement} - * @private - */ - getInputUrl: function(){ - if(!this.inputUrl || !this.inputUrl.value) - this.inputUrl = this.el.querySelector('.'+this.pfx+'add-asset input'); - return this.inputUrl; - }, - - /** - * Add asset to collection - * @private - * */ - addToAsset: function(model){ - this.addAsset(model); - }, - - /** - * Add new asset to collection - * @param Object Model - * @param Object Fragment collection - * @return Object Object created - * @private - * */ - addAsset: function(model, fragmentEl){ - var fragment = fragmentEl || null; - var viewObject = AssetView; - - if(model.get('type').indexOf("image") > -1) - viewObject = AssetImageView; - - var view = new viewObject({ - model : model, - config : this.config, - }); - var rendered = view.render().el; - - if(fragment){ - fragment.appendChild( rendered ); - }else{ - var assetsEl = this.getAssetsEl(); - if(assetsEl) - assetsEl.insertBefore(rendered, assetsEl.firstChild); - } - - return rendered; - }, - - /** - * Deselect all assets - * @private - * */ - deselectAll: function(){ - this.$el.find('.' + this.pfx + 'highlight').removeClass(this.pfx + 'highlight'); - }, - - render: function() { - var fragment = document.createDocumentFragment(); - this.$el.empty(); - - this.collection.each(function(model){ - this.addAsset(model, fragment); - },this); - - this.$el.html(this.template({ - pfx: this.pfx, - ppfx: this.ppfx, - btnText: this.config.addBtnText, - })); - - this.$el.find('.'+this.pfx + 'assets').append(fragment); - return this; - } - }); -}); \ No newline at end of file +var Backbone = require('backbone'); +var AssetView = require('./AssetView'); +var AssetImageView = require('./AssetImageView'); +var FileUploader = require('./FileUploader'); +var assetsTemplate = require('text!./../template/assets.html'); + +module.exports = Backbone.View.extend({ + + template: _.template(assetsTemplate), + + initialize: function(o) { + this.options = o; + this.config = o.config; + this.pfx = this.config.stylePrefix || ''; + this.ppfx = this.config.pStylePrefix || ''; + this.listenTo( this.collection, 'add', this.addToAsset ); + this.listenTo( this.collection, 'deselectAll', this.deselectAll ); + this.className = this.pfx + 'assets'; + + this.events = {}; + this.events.submit = 'addFromStr'; + this.delegateEvents(); + }, + + /** + * Add new asset to the collection via string + * @param {Event} e Event object + * @return {this} + * @private + */ + addFromStr: function(e){ + e.preventDefault(); + + var input = this.getInputUrl(); + + var url = input.value.trim(); + + if(!url) + return; + + this.collection.addImg(url, {at: 0}); + + this.getAssetsEl().scrollTop = 0; + input.value = ''; + return this; + }, + + /** + * Returns assets element + * @return {HTMLElement} + * @private + */ + getAssetsEl: function(){ + //if(!this.assets) // Not able to cache as after the rerender it losses the ref + this.assets = this.el.querySelector('.' + this.pfx + 'assets'); + return this.assets; + }, + + /** + * Returns input url element + * @return {HTMLElement} + * @private + */ + getInputUrl: function(){ + if(!this.inputUrl || !this.inputUrl.value) + this.inputUrl = this.el.querySelector('.'+this.pfx+'add-asset input'); + return this.inputUrl; + }, + + /** + * Add asset to collection + * @private + * */ + addToAsset: function(model){ + this.addAsset(model); + }, + + /** + * Add new asset to collection + * @param Object Model + * @param Object Fragment collection + * @return Object Object created + * @private + * */ + addAsset: function(model, fragmentEl){ + var fragment = fragmentEl || null; + var viewObject = AssetView; + + if(model.get('type').indexOf("image") > -1) + viewObject = AssetImageView; + + var view = new viewObject({ + model : model, + config : this.config, + }); + var rendered = view.render().el; + + if(fragment){ + fragment.appendChild( rendered ); + }else{ + var assetsEl = this.getAssetsEl(); + if(assetsEl) + assetsEl.insertBefore(rendered, assetsEl.firstChild); + } + + return rendered; + }, + + /** + * Deselect all assets + * @private + * */ + deselectAll: function(){ + this.$el.find('.' + this.pfx + 'highlight').removeClass(this.pfx + 'highlight'); + }, + + render: function() { + var fragment = document.createDocumentFragment(); + this.$el.empty(); + + this.collection.each(function(model){ + this.addAsset(model, fragment); + },this); + + this.$el.html(this.template({ + pfx: this.pfx, + ppfx: this.ppfx, + btnText: this.config.addBtnText, + })); + + this.$el.find('.'+this.pfx + 'assets').append(fragment); + return this; + } +}); diff --git a/src/asset_manager/view/FileUploader.js b/src/asset_manager/view/FileUploader.js index 4c6c3ab9f..c137c8ebe 100644 --- a/src/asset_manager/view/FileUploader.js +++ b/src/asset_manager/view/FileUploader.js @@ -1,99 +1,97 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var fileUploaderTemplate = require('text!./../template/fileUploader.html'); - module.exports = Backbone.View.extend({ +var Backbone = require('backbone'); +var fileUploaderTemplate = require('text!./../template/fileUploader.html'); - template: _.template(fileUploaderTemplate), +module.exports = Backbone.View.extend({ - events: {}, + template: _.template(fileUploaderTemplate), - initialize: function(o) { - this.options = o || {}; - this.config = o.config || {}; - this.pfx = this.config.stylePrefix || ''; - this.target = this.collection || {}; - this.uploadId = this.pfx + 'uploadFile'; - this.disabled = !this.config.upload; - this.events['change #' + this.uploadId] = 'uploadFile'; - this.delegateEvents(); - }, + events: {}, - /** - * Upload files - * @param {Object} e Event - * @private - * */ - uploadFile : function(e){ - var files = e.dataTransfer ? e.dataTransfer.files : e.target.files, - formData = new FormData(); - for (var i = 0; i < files.length; i++) { - formData.append('files[]', files[i]); - } - var target = this.target; - $.ajax({ - url : this.config.upload, - type : 'POST', - data : formData, - beforeSend : this.config.beforeSend, - complete : this.config.onComplete, - xhrFields : { - onprogress: function (e) { - if (e.lengthComputable) { - /*var result = e.loaded / e.total * 100 + '%';*/ - } - }, - onload: function (e) { - //progress.value = 100; - } - }, - cache: false, contentType: false, processData: false - }).done(function(data){ - target.add(data.data); - }).always(function(){ - //turnOff loading - }); - }, + initialize: function(o) { + this.options = o || {}; + this.config = o.config || {}; + this.pfx = this.config.stylePrefix || ''; + this.target = this.collection || {}; + this.uploadId = this.pfx + 'uploadFile'; + this.disabled = !this.config.upload; + this.events['change #' + this.uploadId] = 'uploadFile'; + this.delegateEvents(); + }, - /** - * Make input file droppable - * @private - * */ - initDrop: function(){ - 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; - }; - } - } - }, + /** + * Upload files + * @param {Object} e Event + * @private + * */ + uploadFile : function(e){ + var files = e.dataTransfer ? e.dataTransfer.files : e.target.files, + formData = new FormData(); + for (var i = 0; i < files.length; i++) { + formData.append('files[]', files[i]); + } + var target = this.target; + $.ajax({ + url : this.config.upload, + type : 'POST', + data : formData, + beforeSend : this.config.beforeSend, + complete : this.config.onComplete, + xhrFields : { + onprogress: function (e) { + if (e.lengthComputable) { + /*var result = e.loaded / e.total * 100 + '%';*/ + } + }, + onload: function (e) { + //progress.value = 100; + } + }, + cache: false, contentType: false, processData: false + }).done(function(data){ + target.add(data.data); + }).always(function(){ + //turnOff loading + }); + }, - render : function(){ - 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; - }, + /** + * Make input file droppable + * @private + * */ + initDrop: function(){ + 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; + }; + } + } + }, - }); -}); \ No newline at end of file + render : function(){ + 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; + }, + +}); diff --git a/src/block_manager/config/config.js b/src/block_manager/config/config.js index f0085db79..78a2a186a 100644 --- a/src/block_manager/config/config.js +++ b/src/block_manager/config/config.js @@ -1,7 +1,5 @@ -define(function () { - return { +module.exports = { - 'blocks': [], + 'blocks': [], - }; -}); \ No newline at end of file +}; diff --git a/src/block_manager/index.js b/src/block_manager/index.js index 60d7a740e..a8d33292f 100644 --- a/src/block_manager/index.js +++ b/src/block_manager/index.js @@ -25,98 +25,94 @@ * } * ... */ -define(function(require) { +module.exports = function() { + var c = {}, + defaults = require('./config/config'), + Blocks = require('./model/Blocks'), + BlocksView = require('./view/BlocksView'); + var blocks, view; - return function() { - var c = {}, - defaults = require('./config/config'), - Blocks = require('./model/Blocks'), - BlocksView = require('./view/BlocksView'); - var blocks, view; + return { - return { + /** + * Name of the module + * @type {String} + * @private + */ + name: 'BlockManager', - /** - * 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: function(config) { + c = config || {}; + for (var name in defaults) { + if (!(name in c)) + c[name] = defaults[name]; + } + blocks = new Blocks(c.blocks); + view = new BlocksView({ collection: blocks }, c); + return this; + }, - /** - * Initialize module. Automatically called with a new instance of the editor - * @param {Object} config Configurations - * @return {this} - * @private - */ - init: function(config) { - c = config || {}; - for (var name in defaults) { - if (!(name in c)) - c[name] = defaults[name]; - } - blocks = new Blocks(c.blocks); - view = new BlocksView({ collection: blocks }, c); - return this; - }, + /** + * 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 {Object} [opts.attributes={}] Block attributes + * @return {Block} Added block + * @example + * blockManager.add('h1-block', { + * label: 'Heading', + * content: '

Put your title here

', + * attributes: { + * title: 'Insert h1 block' + * } + * }); + */ + add: function(id, opts){ + var obj = opts || {}; + obj.id = id; + return blocks.add(obj); + }, - /** - * 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 {Object} [opts.attributes={}] Block attributes - * @return {Block} Added block - * @example - * blockManager.add('h1-block', { - * label: 'Heading', - * content: '

Put your title here

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

Put your ...', ...} + */ + get: function(id){ + return blocks.get(id); + }, - /** - * Return block by id - * @param {string} id Block id - * @example - * var block = blockManager.get('h1-block'); - * console.log(JSON.stringify(block)); - * // {label: 'Heading', content: '

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

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

Put your ...'}, ...] - */ - getAll: function(){ - return blocks; - }, - - /** - * Render blocks - * @return {HTMLElement} - */ - render: function(){ - return view.render().el; - }, - - }; + /** + * Render blocks + * @return {HTMLElement} + */ + render: function(){ + return view.render().el; + }, }; -}); \ No newline at end of file +}; diff --git a/src/block_manager/model/Block.js b/src/block_manager/model/Block.js index 29aeb9fde..c567769b5 100644 --- a/src/block_manager/model/Block.js +++ b/src/block_manager/model/Block.js @@ -1,14 +1,11 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); +var Backbone = require('backbone'); - module.exports = Backbone.Model.extend({ +module.exports = Backbone.Model.extend({ - defaults :{ - label: '', - content: '', - attributes: {}, - }, + defaults :{ + label: '', + content: '', + attributes: {}, + }, - }); - }); \ No newline at end of file +}); diff --git a/src/block_manager/model/Blocks.js b/src/block_manager/model/Blocks.js index 377339187..0522254e6 100644 --- a/src/block_manager/model/Blocks.js +++ b/src/block_manager/model/Blocks.js @@ -1,11 +1,6 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var Block = require('./Block'); +var Backbone = require('backbone'); +var Block = require('./Block'); - module.exports = Backbone.Collection.extend({ - - model: Block, - - }); -}); \ No newline at end of file +module.exports = Backbone.Collection.extend({ + model: Block, +}); diff --git a/src/block_manager/view/BlockView.js b/src/block_manager/view/BlockView.js index ab26809e4..d9976c9d4 100644 --- a/src/block_manager/view/BlockView.js +++ b/src/block_manager/view/BlockView.js @@ -1,51 +1,48 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); +var Backbone = require('backbone'); - module.exports = Backbone.View.extend({ +module.exports = Backbone.View.extend({ - events: { - mousedown: 'onDrag' - }, + events: { + mousedown: 'onDrag' + }, - initialize: function(o, config) { - _.bindAll(this, 'onDrop'); - this.config = config || {}; - this.ppfx = this.config.pStylePrefix || ''; - this.listenTo(this.model, 'destroy', this.remove); - this.doc = $(document); - }, + initialize: function(o, config) { + _.bindAll(this, 'onDrop'); + this.config = config || {}; + this.ppfx = this.config.pStylePrefix || ''; + this.listenTo(this.model, 'destroy', this.remove); + this.doc = $(document); + }, - /** - * Start block dragging - * @private - */ - onDrag: function(e) { - if(!this.config.getSorter) - return; - this.config.em.refreshCanvas(); - var sorter = this.config.getSorter(); - sorter.setDragHelper(this.el, e); - sorter.startSort(this.el); - sorter.setDropContent(this.model.get('content')); - this.doc.on('mouseup', this.onDrop); - }, + /** + * Start block dragging + * @private + */ + onDrag: function(e) { + if(!this.config.getSorter) + return; + this.config.em.refreshCanvas(); + var sorter = this.config.getSorter(); + sorter.setDragHelper(this.el, e); + sorter.startSort(this.el); + sorter.setDropContent(this.model.get('content')); + this.doc.on('mouseup', this.onDrop); + }, - /** - * Drop block - * @private - */ - onDrop: function() { - this.doc.off('mouseup', this.onDrop); - this.config.getSorter().endMove(); - }, + /** + * Drop block + * @private + */ + onDrop: function() { + this.doc.off('mouseup', this.onDrop); + this.config.getSorter().endMove(); + }, - render: function() { - var className = this.ppfx + 'block'; - this.$el.addClass(className); - this.el.innerHTML = '
' + this.model.get('label') + '
'; - return this; - }, + render: function() { + var className = this.ppfx + 'block'; + this.$el.addClass(className); + this.el.innerHTML = '
' + this.model.get('label') + '
'; + return this; + }, - }); -}); \ No newline at end of file +}); diff --git a/src/block_manager/view/BlocksView.js b/src/block_manager/view/BlocksView.js index 44946e3e0..f44bdebcc 100644 --- a/src/block_manager/view/BlocksView.js +++ b/src/block_manager/view/BlocksView.js @@ -1,123 +1,120 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var BlockView = require('./BlockView'); - - module.exports = Backbone.View.extend({ - - initialize: function(opts, config) { - _.bindAll(this, 'getSorter', 'onDrag', 'onDrop'); - this.config = config || {}; - this.ppfx = this.config.pStylePrefix || ''; - this.listenTo(this.collection, 'add', this.addTo); - this.em = this.config.em; - this.tac = 'test-tac'; - this.grabbingCls = this.ppfx + 'grabbing'; - - if(this.em){ - this.config.getSorter = this.getSorter; - this.canvas = this.em.get('Canvas'); +var Backbone = require('backbone'); +var BlockView = require('./BlockView'); + +module.exports = Backbone.View.extend({ + + initialize: function(opts, config) { + _.bindAll(this, 'getSorter', 'onDrag', 'onDrop'); + this.config = config || {}; + this.ppfx = this.config.pStylePrefix || ''; + this.listenTo(this.collection, 'add', this.addTo); + this.em = this.config.em; + this.tac = 'test-tac'; + this.grabbingCls = this.ppfx + 'grabbing'; + + if(this.em){ + this.config.getSorter = this.getSorter; + this.canvas = this.em.get('Canvas'); + } + }, + + /** + * Get sorter + * @private + */ + getSorter: function(){ + if(!this.em) + return; + if(!this.sorter){ + var utils = this.em.get('Utils'); + var canvas = this.canvas; + this.sorter = new utils.Sorter({ + container: canvas.getBody(), + placer: canvas.getPlacerEl(), + containerSel: '*', + itemSel: '*', + pfx: this.ppfx, + onStart: this.onDrag, + onEndMove: this.onDrop, + document: canvas.getFrameEl().contentDocument, + direction: 'a', + wmargin: 1, + nested: 1, + em: this.em, + canvasRelative: 1, + }); + } + return this.sorter; + }, + + /** + * Callback when block is on drag + * @private + */ + onDrag: function(){ + this.em.stopDefault(); + }, + + /** + * Callback when block is dropped + * @private + */ + onDrop: function(model){ + this.em.runDefault(); + + if (model && model.get) { + if(model.get('activeOnRender')) { + model.trigger('active'); + model.set('activeOnRender', 0); } - }, - - /** - * Get sorter - * @private - */ - getSorter: function(){ - if(!this.em) - return; - if(!this.sorter){ - var utils = this.em.get('Utils'); - var canvas = this.canvas; - this.sorter = new utils.Sorter({ - container: canvas.getBody(), - placer: canvas.getPlacerEl(), - containerSel: '*', - itemSel: '*', - pfx: this.ppfx, - onStart: this.onDrag, - onEndMove: this.onDrop, - document: canvas.getFrameEl().contentDocument, - direction: 'a', - wmargin: 1, - nested: 1, - em: this.em, - canvasRelative: 1, - }); - } - return this.sorter; - }, - - /** - * Callback when block is on drag - * @private - */ - onDrag: function(){ - this.em.stopDefault(); - }, - - /** - * Callback when block is dropped - * @private - */ - onDrop: function(model){ - this.em.runDefault(); - - if (model && model.get) { - if(model.get('activeOnRender')) { - model.trigger('active'); - model.set('activeOnRender', 0); - } - - // Register all its components (eg. for the Undo Manager) - this.em.initChildrenComp(model); - } - }, - - /** - * Add new model to the collection - * @param {Model} model - * @private - * */ - addTo: function(model){ - this.add(model); - }, - - /** - * Render new model inside the view - * @param {Model} model - * @param {Object} fragment Fragment collection - * @private - * */ - add: function(model, fragment){ - var frag = fragment || null; - var view = new BlockView({ - model: model, - attributes: model.get('attributes'), - }, this.config); - var rendered = view.render().el; - - if(frag) - frag.appendChild(rendered); - else - this.$el.append(rendered); - }, - - - - render: function() { - var frag = document.createDocumentFragment(); - this.$el.empty(); - - this.collection.each(function(model){ - this.add(model, frag); - }, this); - - this.$el.append(frag); - this.$el.addClass(this.ppfx + 'blocks-c'); - return this; - }, - - }); -}); \ No newline at end of file + + // Register all its components (eg. for the Undo Manager) + this.em.initChildrenComp(model); + } + }, + + /** + * Add new model to the collection + * @param {Model} model + * @private + * */ + addTo: function(model){ + this.add(model); + }, + + /** + * Render new model inside the view + * @param {Model} model + * @param {Object} fragment Fragment collection + * @private + * */ + add: function(model, fragment){ + var frag = fragment || null; + var view = new BlockView({ + model: model, + attributes: model.get('attributes'), + }, this.config); + var rendered = view.render().el; + + if(frag) + frag.appendChild(rendered); + else + this.$el.append(rendered); + }, + + + + render: function() { + var frag = document.createDocumentFragment(); + this.$el.empty(); + + this.collection.each(function(model){ + this.add(model, frag); + }, this); + + this.$el.append(frag); + this.$el.addClass(this.ppfx + 'blocks-c'); + return this; + }, + +}); diff --git a/src/canvas/config/config.js b/src/canvas/config/config.js index ffd5c5c4c..023df4222 100644 --- a/src/canvas/config/config.js +++ b/src/canvas/config/config.js @@ -1,16 +1,14 @@ -define(function () { - return { +module.exports = { - stylePrefix: 'cv-', + stylePrefix: 'cv-', - // Coming soon - rulers: false, + // Coming soon + rulers: false, - /* - * append scripts in head of iframe before renderBody content - * need to manually maintain the same scripts in cms's render template - */ - scripts: [] + /* + * append scripts in head of iframe before renderBody content + * need to manually maintain the same scripts in cms's render template + */ + scripts: [] - }; -}); \ No newline at end of file +}; diff --git a/src/canvas/index.js b/src/canvas/index.js index 2bcc01f35..54b020c2d 100644 --- a/src/canvas/index.js +++ b/src/canvas/index.js @@ -1,329 +1,325 @@ -define(function(require) { - - return function() { - var c = {}, - defaults = require('./config/config'), - Canvas = require('./model/Canvas'), - CanvasView = require('./view/CanvasView'); - var canvas; - - return { - - /** - * Used inside RTE - * @private - */ - getCanvasView: function() { - return CanvasView; - }, - - /** - * Name of the module - * @type {String} - * @private - */ - name: 'Canvas', - - /** - * Initialize module. Automatically called with a new instance of the editor - * @param {Object} config Configurations - */ - init: function(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; - - canvas = new Canvas(config); - CanvasView = new CanvasView({ - model: canvas, - config: c, - }); - - var cm = c.em.get('DomComponents'); - if(cm) - this.setWrapper(cm); - - return this; - }, - - /** - * Add wrapper - * @param {Object} wrp Wrapper - * - * */ - setWrapper: function(wrp) { - canvas.set('wrapper', wrp); - }, - - /** - * Returns canvas element - * @return {HTMLElement} - */ - getElement: function(){ - return CanvasView.el; - }, - - /** - * Returns frame element of the canvas - * @return {HTMLElement} - */ - getFrameEl: function(){ - return CanvasView.frame.el; - }, - - /** - * Returns body element of the frame - * @return {HTMLElement} - */ - getBody: function(){ - return CanvasView.frame.el.contentDocument.body; - }, - - /** - * Returns body wrapper element of the frame - * @return {HTMLElement} - */ - getWrapperEl: function(){ - return this.getBody().querySelector('#wrapper'); - }, - - /** - * Returns element containing canvas tools - * @return {HTMLElement} - */ - getToolsEl: function(){ - return CanvasView.toolsEl; - }, - - /** - * Returns highlighter element - * @return {HTMLElement} - */ - getHighlighter: function(){ - return CanvasView.hlEl; - }, - - /** - * Returns badge element - * @return {HTMLElement} - */ - getBadgeEl: function(){ - return CanvasView.badgeEl; - }, - - /** - * Returns placer element - * @return {HTMLElement} - */ - getPlacerEl: function(){ - return CanvasView.placerEl; - }, - - /** - * Returns ghost element - * @return {HTMLElement} - * @private - */ - getGhostEl: function(){ - return CanvasView.ghostEl; - }, - - /** - * Returns toolbar element - * @return {HTMLElement} - */ - getToolbarEl: function() { - return CanvasView.toolbarEl; - }, - - /** - * Returns resizer element - * @return {HTMLElement} - */ - getResizerEl: function() { - return CanvasView.resizerEl; - }, - - /** - * Returns offset viewer element - * @return {HTMLElement} - */ - getOffsetViewerEl: function() { - return CanvasView.offsetEl; - }, - - /** - * Returns fixed offset viewer element - * @return {HTMLElement} - */ - getFixedOffsetViewerEl: function() { - return CanvasView.fixedOffsetEl; - }, - - /** - * Render canvas - * */ - render: function() { - return CanvasView.render().el; - }, - - /** - * Get frame position - * @return {Object} - * @private - */ - getOffset: function() { - var frameOff = this.offset(this.getFrameEl()); - var canvasOff = this.offset(this.getElement()); - return { - top: frameOff.top - canvasOff.top, - left: frameOff.left - canvasOff.left - }; - }, - - /** - * Get the offset of the element - * @param {HTMLElement} el - * @return {Object} - * @private - */ - offset: function(el){ - var rect = el.getBoundingClientRect(); - return { - top: rect.top + document.body.scrollTop, - left: rect.left + document.body.scrollLeft - }; - }, - - /** - * Get element position relative to the canvas - * @param {HTMLElement} el - * @return {Object} - */ - getElementPos: function(el) { - return CanvasView.getElementPos(el); - }, - - /** - * This method comes handy when you need to attach something like toolbars - * to elements inside the canvas, dealing with all relative position, - * offsets, etc. and returning as result the object with positions which are - * viewable by the user (when the canvas is scrolled the top edge of the element - * is not viewable by the user anymore so the new top edge is the one of the canvas) - * - * The target should be visible before being passed here as invisible elements - * return empty string as width - * @param {HTMLElement} target The target in this case could be the toolbar - * @param {HTMLElement} element The element on which I'd attach the toolbar - * @param {Object} options Custom options - * @param {Boolean} options.toRight Set to true if you want the toolbar attached to the right - * @return {Object} - */ - getTargetToElementDim: function (target, element, options) { - var opts = options || {}; - var canvasPos = CanvasView.getPosition(); - var pos = opts.elPos || CanvasView.getElementPos(element); - var toRight = options.toRight || 0; - var targetHeight = opts.targetHeight || target.offsetHeight; - var targetWidth = opts.targetWidth || target.offsetWidth; - var eventToTrigger = opts.event || null; - - var elTop = pos.top - targetHeight; - var elLeft = pos.left; - elLeft += toRight ? pos.width : 0; - 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; - - var result = { - top: topPos, - left: leftPos, - elementTop: pos.top, - elementLeft: pos.left, - elementWidth: pos.width, - elementHeight: pos.height, - targetWidth: target.offsetWidth, - targetHeight: target.offsetHeight, - canvasTop: canvasPos.top, - canvasLeft: canvasPos.left, - }; - - // In this way I can catch data and also change the position strategy - if(eventToTrigger && c.em) { - c.em.trigger(eventToTrigger, result); - } - - return result; - }, - - /** - * Instead of simply returning e.clientX and e.clientY this function - * calculates also the offset based on the canvas. This is helpful when you - * need to get X and Y position while moving between the editor area and - * canvas area, which is in the iframe - * @param {Event} e - * @return {Object} - */ - getMouseRelativePos: function (e, options) { - var opts = options || {}; - var addTop = 0; - var addLeft = 0; - var subWinOffset = opts.subWinOffset; - var doc = e.target.ownerDocument; - var win = doc.defaultView || doc.parentWindow; - var frame = win.frameElement; - var yOffset = subWinOffset ? win.pageYOffset : 0; - var xOffset = subWinOffset ? win.pageXOffset : 0; - - if (frame) { - var frameRect = frame.getBoundingClientRect(); - addTop = frameRect.top || 0; - addLeft = frameRect.left || 0; - } - - return { - y: e.clientY + addTop - yOffset, - x: e.clientX + addLeft - xOffset, - }; - }, - - /** - * X and Y mouse position relative to the canvas - * @param {Event} e - * @return {Object} - */ - getMouseRelativeCanvas: function (e, options) { - var opts = options || {}; - var frame = this.getFrameEl(); - var body = this.getBody(); - var addTop = frame.offsetTop || 0; - var addLeft = frame.offsetLeft || 0; - var yOffset = body.scrollTop || 0; - var xOffset = body.scrollLeft || 0; - - return { - y: e.clientY + addTop + yOffset, - x: e.clientX + addLeft + xOffset, - }; - }, - - /** - * Returns wrapper element - * @return {HTMLElement} - * ???? - */ - getFrameWrapperEl: function(){ - return CanvasView.frame.getWrapper(); - }, - }; +module.exports = function() { + var c = {}, + defaults = require('./config/config'), + Canvas = require('./model/Canvas'), + CanvasView = require('./view/CanvasView'); + var canvas; + + return { + + /** + * Used inside RTE + * @private + */ + getCanvasView: function() { + return CanvasView; + }, + + /** + * Name of the module + * @type {String} + * @private + */ + name: 'Canvas', + + /** + * Initialize module. Automatically called with a new instance of the editor + * @param {Object} config Configurations + */ + init: function(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; + + canvas = new Canvas(config); + CanvasView = new CanvasView({ + model: canvas, + config: c, + }); + + var cm = c.em.get('DomComponents'); + if(cm) + this.setWrapper(cm); + + return this; + }, + + /** + * Add wrapper + * @param {Object} wrp Wrapper + * + * */ + setWrapper: function(wrp) { + canvas.set('wrapper', wrp); + }, + + /** + * Returns canvas element + * @return {HTMLElement} + */ + getElement: function(){ + return CanvasView.el; + }, + + /** + * Returns frame element of the canvas + * @return {HTMLElement} + */ + getFrameEl: function(){ + return CanvasView.frame.el; + }, + + /** + * Returns body element of the frame + * @return {HTMLElement} + */ + getBody: function(){ + return CanvasView.frame.el.contentDocument.body; + }, + + /** + * Returns body wrapper element of the frame + * @return {HTMLElement} + */ + getWrapperEl: function(){ + return this.getBody().querySelector('#wrapper'); + }, + + /** + * Returns element containing canvas tools + * @return {HTMLElement} + */ + getToolsEl: function(){ + return CanvasView.toolsEl; + }, + + /** + * Returns highlighter element + * @return {HTMLElement} + */ + getHighlighter: function(){ + return CanvasView.hlEl; + }, + + /** + * Returns badge element + * @return {HTMLElement} + */ + getBadgeEl: function(){ + return CanvasView.badgeEl; + }, + + /** + * Returns placer element + * @return {HTMLElement} + */ + getPlacerEl: function(){ + return CanvasView.placerEl; + }, + + /** + * Returns ghost element + * @return {HTMLElement} + * @private + */ + getGhostEl: function(){ + return CanvasView.ghostEl; + }, + + /** + * Returns toolbar element + * @return {HTMLElement} + */ + getToolbarEl: function() { + return CanvasView.toolbarEl; + }, + + /** + * Returns resizer element + * @return {HTMLElement} + */ + getResizerEl: function() { + return CanvasView.resizerEl; + }, + + /** + * Returns offset viewer element + * @return {HTMLElement} + */ + getOffsetViewerEl: function() { + return CanvasView.offsetEl; + }, + + /** + * Returns fixed offset viewer element + * @return {HTMLElement} + */ + getFixedOffsetViewerEl: function() { + return CanvasView.fixedOffsetEl; + }, + + /** + * Render canvas + * */ + render: function() { + return CanvasView.render().el; + }, + + /** + * Get frame position + * @return {Object} + * @private + */ + getOffset: function() { + var frameOff = this.offset(this.getFrameEl()); + var canvasOff = this.offset(this.getElement()); + return { + top: frameOff.top - canvasOff.top, + left: frameOff.left - canvasOff.left + }; + }, + + /** + * Get the offset of the element + * @param {HTMLElement} el + * @return {Object} + * @private + */ + offset: function(el){ + var rect = el.getBoundingClientRect(); + return { + top: rect.top + document.body.scrollTop, + left: rect.left + document.body.scrollLeft + }; + }, + + /** + * Get element position relative to the canvas + * @param {HTMLElement} el + * @return {Object} + */ + getElementPos: function(el) { + return CanvasView.getElementPos(el); + }, + + /** + * This method comes handy when you need to attach something like toolbars + * to elements inside the canvas, dealing with all relative position, + * offsets, etc. and returning as result the object with positions which are + * viewable by the user (when the canvas is scrolled the top edge of the element + * is not viewable by the user anymore so the new top edge is the one of the canvas) + * + * The target should be visible before being passed here as invisible elements + * return empty string as width + * @param {HTMLElement} target The target in this case could be the toolbar + * @param {HTMLElement} element The element on which I'd attach the toolbar + * @param {Object} options Custom options + * @param {Boolean} options.toRight Set to true if you want the toolbar attached to the right + * @return {Object} + */ + getTargetToElementDim: function (target, element, options) { + var opts = options || {}; + var canvasPos = CanvasView.getPosition(); + var pos = opts.elPos || CanvasView.getElementPos(element); + var toRight = options.toRight || 0; + var targetHeight = opts.targetHeight || target.offsetHeight; + var targetWidth = opts.targetWidth || target.offsetWidth; + var eventToTrigger = opts.event || null; + + var elTop = pos.top - targetHeight; + var elLeft = pos.left; + elLeft += toRight ? pos.width : 0; + 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; + + var result = { + top: topPos, + left: leftPos, + elementTop: pos.top, + elementLeft: pos.left, + elementWidth: pos.width, + elementHeight: pos.height, + targetWidth: target.offsetWidth, + targetHeight: target.offsetHeight, + canvasTop: canvasPos.top, + canvasLeft: canvasPos.left, + }; + + // In this way I can catch data and also change the position strategy + if(eventToTrigger && c.em) { + c.em.trigger(eventToTrigger, result); + } + + return result; + }, + + /** + * Instead of simply returning e.clientX and e.clientY this function + * calculates also the offset based on the canvas. This is helpful when you + * need to get X and Y position while moving between the editor area and + * canvas area, which is in the iframe + * @param {Event} e + * @return {Object} + */ + getMouseRelativePos: function (e, options) { + var opts = options || {}; + var addTop = 0; + var addLeft = 0; + var subWinOffset = opts.subWinOffset; + var doc = e.target.ownerDocument; + var win = doc.defaultView || doc.parentWindow; + var frame = win.frameElement; + var yOffset = subWinOffset ? win.pageYOffset : 0; + var xOffset = subWinOffset ? win.pageXOffset : 0; + + if (frame) { + var frameRect = frame.getBoundingClientRect(); + addTop = frameRect.top || 0; + addLeft = frameRect.left || 0; + } + + return { + y: e.clientY + addTop - yOffset, + x: e.clientX + addLeft - xOffset, + }; + }, + + /** + * X and Y mouse position relative to the canvas + * @param {Event} e + * @return {Object} + */ + getMouseRelativeCanvas: function (e, options) { + var opts = options || {}; + var frame = this.getFrameEl(); + var body = this.getBody(); + var addTop = frame.offsetTop || 0; + var addLeft = frame.offsetLeft || 0; + var yOffset = body.scrollTop || 0; + var xOffset = body.scrollLeft || 0; + + return { + y: e.clientY + addTop + yOffset, + x: e.clientX + addLeft + xOffset, + }; + }, + + /** + * Returns wrapper element + * @return {HTMLElement} + * ???? + */ + getFrameWrapperEl: function(){ + return CanvasView.frame.getWrapper(); + }, }; - -}); +}; diff --git a/src/canvas/model/Canvas.js b/src/canvas/model/Canvas.js index e9d762553..46098cc6e 100644 --- a/src/canvas/model/Canvas.js +++ b/src/canvas/model/Canvas.js @@ -1,20 +1,17 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var Frame = require('./Frame'); +var Backbone = require('backbone'); +var Frame = require('./Frame'); - module.exports = Backbone.Model.extend({ +module.exports = Backbone.Model.extend({ - defaults :{ - frame: '', - wrapper: '', - rulers: false, - }, + defaults :{ + frame: '', + wrapper: '', + rulers: false, + }, - initialize: function(config) { - var conf = this.conf || {}; - this.set('frame', new Frame(conf.frame)); - }, + initialize: function(config) { + var conf = this.conf || {}; + this.set('frame', new Frame(conf.frame)); + }, - }); - }); \ No newline at end of file +}); diff --git a/src/canvas/model/Frame.js b/src/canvas/model/Frame.js index bef54f0dd..aa66331cd 100644 --- a/src/canvas/model/Frame.js +++ b/src/canvas/model/Frame.js @@ -1,15 +1,12 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); +var Backbone = require('backbone'); - module.exports = Backbone.Model.extend({ +module.exports = Backbone.Model.extend({ - defaults :{ - wrapper: '', - width: '', - height: '', - attributes: {}, - }, + defaults :{ + wrapper: '', + width: '', + height: '', + attributes: {}, + }, - }); - }); \ No newline at end of file +}); diff --git a/src/canvas/view/CanvasView.js b/src/canvas/view/CanvasView.js index 0916680eb..0db6dd46f 100644 --- a/src/canvas/view/CanvasView.js +++ b/src/canvas/view/CanvasView.js @@ -1,271 +1,266 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var FrameView = require('./FrameView'); - /** - * @class CanvasView - * */ - module.exports = Backbone.View.extend({ +var Backbone = require('backbone'); +var FrameView = require('./FrameView'); - initialize: function(o) { - _.bindAll(this, 'renderBody', 'onFrameScroll', 'clearOff'); - this.config = o.config || {}; - this.em = this.config.em || {}; - 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'), - config: this.config - }); - }, +module.exports = Backbone.View.extend({ - /** - * Update tools position - * @private - */ - onFrameScroll: function(){ - var u = 'px'; - var body = this.frame.el.contentDocument.body; - this.toolsEl.style.top = '-' + body.scrollTop + u; - this.toolsEl.style.left = '-' + body.scrollLeft + u; - this.em.trigger('canvasScroll'); - }, + initialize: function(o) { + _.bindAll(this, 'renderBody', 'onFrameScroll', 'clearOff'); + this.config = o.config || {}; + this.em = this.config.em || {}; + 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'), + config: this.config + }); + }, - /** - * Insert scripts into head, it will call renderBody after all scripts loaded or failed - * @private - */ - renderScripts: function () { - var frame = this.frame; - var that = this; + /** + * Update tools position + * @private + */ + onFrameScroll: function(){ + var u = 'px'; + var body = this.frame.el.contentDocument.body; + this.toolsEl.style.top = '-' + body.scrollTop + u; + this.toolsEl.style.left = '-' + body.scrollLeft + u; + this.em.trigger('canvasScroll'); + }, - frame.el.onload = function () { - var scripts = that.config.scripts.slice(0), // clone - counter = 0; + /** + * Insert scripts into head, it will call renderBody after all scripts loaded or failed + * @private + */ + renderScripts: function () { + var frame = this.frame; + var that = this; - 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(); - } + frame.el.onload = function () { + 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); + }; + }, - /** - * Render inside frame's body - * @private - */ - renderBody: function() { - var wrap = this.model.get('frame').get('wrapper'); - var em = this.config.em; - if(wrap) { - var ppfx = this.ppfx; - var body = this.frame.$el.contents().find('body'); - var cssc = em.get('CssComposer'); - var conf = em.get('Config'); - body.append(wrap.render()).append(cssc.render()); - var protCss = conf.protectedCss; + /** + * Render inside frame's body + * @private + */ + renderBody: function() { + var wrap = this.model.get('frame').get('wrapper'); + var em = this.config.em; + if(wrap) { + var ppfx = this.ppfx; + var body = this.frame.$el.contents().find('body'); + var cssc = em.get('CssComposer'); + var conf = em.get('Config'); + body.append(wrap.render()).append(cssc.render()); + var protCss = conf.protectedCss; - // I need all this styles to make the editor work properly - var frameCss = '* {box-sizing: border-box;} body{margin:0;height:auto;background-color:#fff} #wrapper{min-height:100%; overflow:auto}' + - '.' + ppfx + 'dashed :not([contenteditable]) > *[data-highlightable]{outline: 1px dashed rgba(170,170,170,0.7); outline-offset: -2px}' + - '.' + ppfx + 'comp-selected{outline: 3px solid #3b97e3 !important}' + - '.' + ppfx + 'no-select{user-select: none; -webkit-user-select:none; -moz-user-select: none}'+ - '.' + ppfx + 'freezed{opacity: 0.5; pointer-events: none}' + - '.' + ppfx + 'no-pointer{pointer-events: none}' + - '.' + ppfx + 'plh-image{background:#f5f5f5; border:none; height:50px; width:50px; display:block; outline:3px solid #ffca6f; cursor:pointer}' + - '.' + ppfx + 'grabbing{cursor: grabbing; cursor: -webkit-grabbing}' + - '* ::-webkit-scrollbar-track {background: rgba(0, 0, 0, 0.1)}' + - '* ::-webkit-scrollbar-thumb {background: rgba(255, 255, 255, 0.2)}' + - '* ::-webkit-scrollbar {width: 10px}' + - (conf.canvasCss || ''); - frameCss += protCss || ''; - body.append(''); - body.append(this.getJsContainer()); - em.trigger('loaded'); - this.frame.el.contentWindow.onscroll = this.onFrameScroll; - this.frame.udpateOffset(); + // I need all this styles to make the editor work properly + var frameCss = '* {box-sizing: border-box;} body{margin:0;height:auto;background-color:#fff} #wrapper{min-height:100%; overflow:auto}' + + '.' + ppfx + 'dashed :not([contenteditable]) > *[data-highlightable]{outline: 1px dashed rgba(170,170,170,0.7); outline-offset: -2px}' + + '.' + ppfx + 'comp-selected{outline: 3px solid #3b97e3 !important}' + + '.' + ppfx + 'no-select{user-select: none; -webkit-user-select:none; -moz-user-select: none}'+ + '.' + ppfx + 'freezed{opacity: 0.5; pointer-events: none}' + + '.' + ppfx + 'no-pointer{pointer-events: none}' + + '.' + ppfx + 'plh-image{background:#f5f5f5; border:none; height:50px; width:50px; display:block; outline:3px solid #ffca6f; cursor:pointer}' + + '.' + ppfx + 'grabbing{cursor: grabbing; cursor: -webkit-grabbing}' + + '* ::-webkit-scrollbar-track {background: rgba(0, 0, 0, 0.1)}' + + '* ::-webkit-scrollbar-thumb {background: rgba(255, 255, 255, 0.2)}' + + '* ::-webkit-scrollbar {width: 10px}' + + (conf.canvasCss || ''); + frameCss += protCss || ''; + body.append(''); + body.append(this.getJsContainer()); + em.trigger('loaded'); + this.frame.el.contentWindow.onscroll = this.onFrameScroll; + this.frame.udpateOffset(); - // When the iframe is focused the event dispatcher is not the same so - // I need to delegate all events to the parent document - var doc = document; - var fdoc = this.frame.el.contentDocument; - fdoc.addEventListener('keydown', function(e){ - doc.dispatchEvent(new KeyboardEvent(e.type, e)); - }); - fdoc.addEventListener('keyup', function(e){ - doc.dispatchEvent(new KeyboardEvent(e.type, e)); - }); - } - }, + // When the iframe is focused the event dispatcher is not the same so + // I need to delegate all events to the parent document + var doc = document; + var fdoc = this.frame.el.contentDocument; + fdoc.addEventListener('keydown', function(e){ + doc.dispatchEvent(new KeyboardEvent(e.type, e)); + }); + fdoc.addEventListener('keyup', function(e){ + doc.dispatchEvent(new KeyboardEvent(e.type, e)); + }); + } + }, - /** - * Get the offset of the element - * @param {HTMLElement} el - * @return {Object} - */ - offset: function(el){ - var rect = el.getBoundingClientRect(); - var docBody = el.ownerDocument.body; - return { - top: rect.top + docBody.scrollTop, - left: rect.left + docBody.scrollLeft - }; - }, + /** + * Get the offset of the element + * @param {HTMLElement} el + * @return {Object} + */ + offset: function(el){ + var rect = el.getBoundingClientRect(); + var docBody = el.ownerDocument.body; + return { + top: rect.top + docBody.scrollTop, + left: rect.left + docBody.scrollLeft + }; + }, - /** - * Cleare cached offsets - * @private - */ - clearOff: function(){ - this.frmOff = null; - this.cvsOff = null; - }, + /** + * Cleare cached offsets + * @private + */ + clearOff: function(){ + this.frmOff = null; + this.cvsOff = null; + }, - /** - * Return frame offset - * @return {Object} - * @private - */ - getFrameOffset: function () { - if(!this.frmOff) - this.frmOff = this.offset(this.frame.el); - return this.frmOff; - }, + /** + * Return frame offset + * @return {Object} + * @private + */ + getFrameOffset: function () { + if(!this.frmOff) + this.frmOff = this.offset(this.frame.el); + return this.frmOff; + }, - /** - * Return canvas offset - * @return {Object} - * @private - */ - getCanvasOffset: function () { - if(!this.cvsOff) - this.cvsOff = this.offset(this.el); - return this.cvsOff; - }, + /** + * Return canvas offset + * @return {Object} + * @private + */ + getCanvasOffset: function () { + if(!this.cvsOff) + this.cvsOff = this.offset(this.el); + return this.cvsOff; + }, - /** - * Returns element's data info - * @param {HTMLElement} el - * @return {Object} - * @private - */ - getElementPos: function(el) { - var frmOff = this.getFrameOffset(); - var cvsOff = this.getCanvasOffset(); - var eo = this.offset(el); - var top = eo.top + frmOff.top - cvsOff.top; - var left = eo.left + frmOff.left - cvsOff.left; - return { - top: top, - left: left, - height: el.offsetHeight, - width: el.offsetWidth - }; - }, + /** + * Returns element's data info + * @param {HTMLElement} el + * @return {Object} + * @private + */ + getElementPos: function(el) { + var frmOff = this.getFrameOffset(); + var cvsOff = this.getCanvasOffset(); + var eo = this.offset(el); + var top = eo.top + frmOff.top - cvsOff.top; + var left = eo.left + frmOff.left - cvsOff.left; + return { + top: top, + left: left, + height: el.offsetHeight, + width: el.offsetWidth + }; + }, - /** - * Returns position data of the canvas element - * @return {Object} obj Position object - * @private - */ - getPosition: function() { - var bEl = this.frame.el.contentDocument.body; - var fo = this.getFrameOffset(); - var co = this.getCanvasOffset(); - return { - top: fo.top + bEl.scrollTop - co.top, - left: fo.left + bEl.scrollLeft - co.left - }; - }, + /** + * Returns position data of the canvas element + * @return {Object} obj Position object + * @private + */ + getPosition: function() { + var bEl = this.frame.el.contentDocument.body; + var fo = this.getFrameOffset(); + var co = this.getCanvasOffset(); + return { + top: fo.top + bEl.scrollTop - co.top, + left: fo.left + bEl.scrollLeft - co.left + }; + }, - /** - * Update javascript of a specific component passed by its View - * @param {View} view Component's View - * @private - */ - updateScript: function(view) { - if(!view.scriptContainer) { - view.scriptContainer = $('
'); - this.getJsContainer().append(view.scriptContainer.get(0)); - } + /** + * Update javascript of a specific component passed by its View + * @param {View} view Component's View + * @private + */ + updateScript: function(view) { + if(!view.scriptContainer) { + view.scriptContainer = $('
'); + this.getJsContainer().append(view.scriptContainer.get(0)); + } - var id = view.model.cid; - var script = view.model.get('script'); - var scrStr = 'function(){' + script + '}'; - scrStr = typeof script == 'function' ? script.toString() : scrStr; + var id = view.model.cid; + var script = view.model.get('script'); + var scrStr = 'function(){' + script + '}'; + scrStr = typeof script == 'function' ? script.toString() : scrStr; - view.el.id = id; - view.scriptContainer.html(''); + view.el.id = id; + view.scriptContainer.html(''); - view.scriptContainer.append(''); - }, + view.scriptContainer.append(''); + }, - /** - * Get javascript container - * @private - */ - getJsContainer: function () { - if (!this.jsContainer) { - this.jsContainer = $('
', {class: this.ppfx + 'js-cont'}).get(0); - } - return this.jsContainer; - }, + /** + * Get javascript container + * @private + */ + getJsContainer: function () { + if (!this.jsContainer) { + this.jsContainer = $('
', {class: this.ppfx + 'js-cont'}).get(0); + } + return this.jsContainer; + }, - render: function() { - this.wrapper = this.model.get('wrapper'); + render: function() { + this.wrapper = this.model.get('wrapper'); - 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; - if (this.config.scripts.length === 0) { - frame.el.onload = this.renderBody; - } else { - this.renderScripts(); // will call renderBody later - } + 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; + if (this.config.scripts.length === 0) { + frame.el.onload = this.renderBody; + } else { + this.renderScripts(); // will call renderBody later } - var ppfx = this.ppfx; - var toolsEl = $('
', { id: ppfx + 'tools' }).get(0); - this.hlEl = $('
', { class: ppfx + 'highlighter' }).get(0); - this.badgeEl = $('
', {class: ppfx + 'badge'}).get(0); - this.placerEl = $('
', {class: ppfx + 'placeholder'}).get(0); - this.placerIntEl = $('
', {class: ppfx + 'placeholder-int'}).get(0); - this.ghostEl = $('
', {class: ppfx + 'ghost'}).get(0); - this.toolbarEl = $('
', {class: ppfx + 'toolbar'}).get(0); - this.resizerEl = $('
', {class: ppfx + 'resizer'}).get(0); - this.offsetEl = $('
', {class: ppfx + 'offset-v'}).get(0); - this.fixedOffsetEl = $('
', {class: ppfx + 'offset-fixed-v'}).get(0); - this.placerEl.appendChild(this.placerIntEl); - toolsEl.appendChild(this.hlEl); - toolsEl.appendChild(this.badgeEl); - toolsEl.appendChild(this.placerEl); - toolsEl.appendChild(this.ghostEl); - toolsEl.appendChild(this.toolbarEl); - toolsEl.appendChild(this.resizerEl); - toolsEl.appendChild(this.offsetEl); - toolsEl.appendChild(this.fixedOffsetEl); - this.$el.append(toolsEl); - var rte = this.em.get('rte'); + } + var ppfx = this.ppfx; + var toolsEl = $('
', { id: ppfx + 'tools' }).get(0); + this.hlEl = $('
', { class: ppfx + 'highlighter' }).get(0); + this.badgeEl = $('
', {class: ppfx + 'badge'}).get(0); + this.placerEl = $('
', {class: ppfx + 'placeholder'}).get(0); + this.placerIntEl = $('
', {class: ppfx + 'placeholder-int'}).get(0); + this.ghostEl = $('
', {class: ppfx + 'ghost'}).get(0); + this.toolbarEl = $('
', {class: ppfx + 'toolbar'}).get(0); + this.resizerEl = $('
', {class: ppfx + 'resizer'}).get(0); + this.offsetEl = $('
', {class: ppfx + 'offset-v'}).get(0); + this.fixedOffsetEl = $('
', {class: ppfx + 'offset-fixed-v'}).get(0); + this.placerEl.appendChild(this.placerIntEl); + toolsEl.appendChild(this.hlEl); + toolsEl.appendChild(this.badgeEl); + toolsEl.appendChild(this.placerEl); + toolsEl.appendChild(this.ghostEl); + toolsEl.appendChild(this.toolbarEl); + toolsEl.appendChild(this.resizerEl); + toolsEl.appendChild(this.offsetEl); + toolsEl.appendChild(this.fixedOffsetEl); + this.$el.append(toolsEl); + var rte = this.em.get('rte'); - if(rte) - toolsEl.appendChild(rte.render()); + if(rte) + toolsEl.appendChild(rte.render()); - this.toolsEl = toolsEl; - this.$el.attr({class: this.className}); - return this; - }, + this.toolsEl = toolsEl; + this.$el.attr({class: this.className}); + return this; + }, - }); }); diff --git a/src/canvas/view/FrameView.js b/src/canvas/view/FrameView.js index 616b7be32..b079ca2be 100644 --- a/src/canvas/view/FrameView.js +++ b/src/canvas/view/FrameView.js @@ -1,56 +1,51 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); +var Backbone = require('backbone'); + +module.exports = Backbone.View.extend({ + + tagName: 'iframe', + + attributes: { + src: 'about:blank', + allowfullscreen: 'allowfullscreen' + }, + + initialize: function(o) { + _.bindAll(this, 'udpateOffset'); + this.config = o.config || {}; + this.ppfx = this.config.pStylePrefix || ''; + this.em = this.config.em; + this.motionsEv = 'transitionend oTransitionEnd transitionend webkitTransitionEnd'; + this.listenTo(this.em, 'change:device', this.updateWidth); + }, + /** - * @class CanvasView - * */ - module.exports = Backbone.View.extend({ - - tagName: 'iframe', - - attributes: { - src: 'about:blank', - allowfullscreen: 'allowfullscreen' - }, - - initialize: function(o) { - _.bindAll(this, 'udpateOffset'); - this.config = o.config || {}; - this.ppfx = this.config.pStylePrefix || ''; - this.em = this.config.em; - this.motionsEv = 'transitionend oTransitionEnd transitionend webkitTransitionEnd'; - this.listenTo(this.em, 'change:device', this.updateWidth); - }, - - /** - * Update width of the frame - * @private - */ - updateWidth: function(model){ - var device = this.em.getDeviceModel(); - this.el.style.width = device ? device.get('width') : ''; - this.udpateOffset(); - this.$el.on(this.motionsEv, this.udpateOffset); - }, - - udpateOffset: function(){ - var offset = this.em.get('Canvas').getOffset(); - this.em.set('canvasOffset', offset); - this.$el.off(this.motionsEv, this.udpateOffset); - }, - - getBody: function(){ - this.$el.contents().find('body'); - }, - - getWrapper: function(){ - return this.$el.contents().find('body > div'); - }, - - render: function() { - this.$el.attr({class: this.ppfx + 'frame'}); - return this; - }, - - }); -}); \ No newline at end of file + * Update width of the frame + * @private + */ + updateWidth: function(model){ + var device = this.em.getDeviceModel(); + this.el.style.width = device ? device.get('width') : ''; + this.udpateOffset(); + this.$el.on(this.motionsEv, this.udpateOffset); + }, + + udpateOffset: function(){ + var offset = this.em.get('Canvas').getOffset(); + this.em.set('canvasOffset', offset); + this.$el.off(this.motionsEv, this.udpateOffset); + }, + + getBody: function(){ + this.$el.contents().find('body'); + }, + + getWrapper: function(){ + return this.$el.contents().find('body > div'); + }, + + render: function() { + 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 c17dc46da..215b6c02e 100644 --- a/src/code_manager/config/config.js +++ b/src/code_manager/config/config.js @@ -1,8 +1,6 @@ -define(function () { - return { - // Style prefix - stylePrefix: 'cm-', +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 33400046a..be34388cb 100644 --- a/src/code_manager/index.js +++ b/src/code_manager/index.js @@ -17,211 +17,205 @@ * * @module CodeManager */ -define(function(require) { - - var CodeManager = function() { - - 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'); - - var generators = {}, - defGenerators = {}, - viewers = {}, - defViewers = {}; - - return { - - getConfig: function() { - return c; - }, - - config: c, - - EditorView: editorView, - - /** - * Name of the module - * @type {String} - * @private - */ - name: 'CodeManager', - - /** - * Initialize module. Automatically called with a new instance of the editor - * @param {Object} config Configurations - */ - init: function(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; - - defGenerators.html = new gHtml(); - defGenerators.css = new gCss(); - defGenerators.json = new gJson(); - defGenerators.js = new gJs(); - - defViewers.CodeMirror = new eCM(); - return this; - }, - - /** - * Callback on load - */ - onLoad: function(){ - this.loadDefaultGenerators().loadDefaultViewers(); - }, - - /** - * Add new code generator to the collection - * @param {string} id Code generator ID - * @param {Object} generator Code generator wrapper - * @param {Function} generator.build Function that builds the code - * @return {this} - * @example - * codeManager.addGenerator('html7',{ - * build: function(model){ - * return 'myCode'; - * } - * }); - * */ - addGenerator: function(id, generator) { - generators[id] = generator; - return this; - }, - - /** - * Get code generator by id - * @param {string} id Code generator ID - * @return {Object|null} - * @example - * var generator = codeManager.getGenerator('html7'); - * generator.build = function(model){ - * //extend - * }; - * */ - getGenerator: function(id) { - return generators[id] || null; - }, - - /** - * Returns all code generators - * @return {Array} - * */ - getGenerators: function() { - return generators; - }, - - /** - * Add new code viewer - * @param {string} id Code viewer ID - * @param {Object} viewer Code viewer wrapper - * @param {Function} viewer.init Set element on which viewer will be displayed - * @param {Function} viewer.setContent Set content to the viewer - * @return {this} - * @example - * codeManager.addViewer('ace',{ - * init: function(el){ - * var ace = require('ace-editor'); - * this.editor = ace.edit(el.id); - * }, - * setContent: function(code){ - * this.editor.setValue(code); - * } - * }); - * */ - addViewer: function(id, viewer) { - viewers[id] = viewer; - return this; - }, - - /** - * Get code viewer by id - * @param {string} id Code viewer ID - * @return {Object|null} - * @example - * var viewer = codeManager.getViewer('ace'); - * */ - getViewer: function(id) { - return viewers[id] || null; - }, - - /** - * Returns all code viewers - * @return {Array} - * */ - getViewers: function() { - return viewers; - }, - - /** - * Update code viewer content - * @param {Object} viewer Viewer instance - * @param {string} code Code string - * @example - * var AceViewer = codeManager.getViewer('ace'); - * // ... - * var viewer = AceViewer.init(el); - * // ... - * codeManager.updateViewer(AceViewer, 'code'); - * */ - updateViewer: function(viewer, code) { - viewer.setContent(code); - }, - - /** - * Get code from model - * @param {Object} model Any kind of model that will be passed to the build method of generator - * @param {string} genId Code generator id - * @param {Object} [opt] Options - * @return {string} - * @example - * var codeStr = codeManager.getCode(model, 'html'); - * */ - getCode: function(model, genId, opt) { - var generator = this.getGenerator(genId); - return generator ? generator.build(model, opt) : ''; - }, - - /** - * Load default code generators - * @return {this} - * @private - * */ - loadDefaultGenerators: function() { - for (var id in defGenerators) - this.addGenerator(id, defGenerators[id]); - - return this; - }, - - /** - * Load default code viewers - * @return {this} - * @private - * */ - loadDefaultViewers: function() { - for (var id in defViewers) - this.addViewer(id, defViewers[id]); - - return this; - }, - - }; - - }; - - return CodeManager; - -}); +module.exports = function() { + + 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'); + + var generators = {}, + defGenerators = {}, + viewers = {}, + defViewers = {}; + + return { + + getConfig: function() { + return c; + }, + + config: c, + + EditorView: editorView, + + /** + * Name of the module + * @type {String} + * @private + */ + name: 'CodeManager', + + /** + * Initialize module. Automatically called with a new instance of the editor + * @param {Object} config Configurations + */ + init: function(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; + + defGenerators.html = new gHtml(); + defGenerators.css = new gCss(); + defGenerators.json = new gJson(); + defGenerators.js = new gJs(); + + defViewers.CodeMirror = new eCM(); + return this; + }, + + /** + * Callback on load + */ + onLoad: function(){ + this.loadDefaultGenerators().loadDefaultViewers(); + }, + + /** + * Add new code generator to the collection + * @param {string} id Code generator ID + * @param {Object} generator Code generator wrapper + * @param {Function} generator.build Function that builds the code + * @return {this} + * @example + * codeManager.addGenerator('html7',{ + * build: function(model){ + * return 'myCode'; + * } + * }); + * */ + addGenerator: function(id, generator) { + generators[id] = generator; + return this; + }, + + /** + * Get code generator by id + * @param {string} id Code generator ID + * @return {Object|null} + * @example + * var generator = codeManager.getGenerator('html7'); + * generator.build = function(model){ + * //extend + * }; + * */ + getGenerator: function(id) { + return generators[id] || null; + }, + + /** + * Returns all code generators + * @return {Array} + * */ + getGenerators: function() { + return generators; + }, + + /** + * Add new code viewer + * @param {string} id Code viewer ID + * @param {Object} viewer Code viewer wrapper + * @param {Function} viewer.init Set element on which viewer will be displayed + * @param {Function} viewer.setContent Set content to the viewer + * @return {this} + * @example + * codeManager.addViewer('ace',{ + * init: function(el){ + * var ace = require('ace-editor'); + * this.editor = ace.edit(el.id); + * }, + * setContent: function(code){ + * this.editor.setValue(code); + * } + * }); + * */ + addViewer: function(id, viewer) { + viewers[id] = viewer; + return this; + }, + + /** + * Get code viewer by id + * @param {string} id Code viewer ID + * @return {Object|null} + * @example + * var viewer = codeManager.getViewer('ace'); + * */ + getViewer: function(id) { + return viewers[id] || null; + }, + + /** + * Returns all code viewers + * @return {Array} + * */ + getViewers: function() { + return viewers; + }, + + /** + * Update code viewer content + * @param {Object} viewer Viewer instance + * @param {string} code Code string + * @example + * var AceViewer = codeManager.getViewer('ace'); + * // ... + * var viewer = AceViewer.init(el); + * // ... + * codeManager.updateViewer(AceViewer, 'code'); + * */ + updateViewer: function(viewer, code) { + viewer.setContent(code); + }, + + /** + * Get code from model + * @param {Object} model Any kind of model that will be passed to the build method of generator + * @param {string} genId Code generator id + * @param {Object} [opt] Options + * @return {string} + * @example + * var codeStr = codeManager.getCode(model, 'html'); + * */ + getCode: function(model, genId, opt) { + var generator = this.getGenerator(genId); + return generator ? generator.build(model, opt) : ''; + }, + + /** + * Load default code generators + * @return {this} + * @private + * */ + loadDefaultGenerators: function() { + for (var id in defGenerators) + this.addGenerator(id, defGenerators[id]); + + return this; + }, + + /** + * Load default code viewers + * @return {this} + * @private + * */ + loadDefaultViewers: function() { + 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 79158d305..136dd8f34 100644 --- a/src/code_manager/model/CodeMirrorEditor.js +++ b/src/code_manager/model/CodeMirrorEditor.js @@ -1,51 +1,46 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var CodeMirror = require('codemirror/lib/codemirror'); - var htmlMode = require('codemirror/mode/htmlmixed/htmlmixed'); - var cssMode = require('codemirror/mode/css/css'); - var formatting = require('formatting'); - /** - * @class CodeViewer - * */ - module.exports = Backbone.Model.extend({ +var Backbone = require('backbone'); +var CodeMirror = require('codemirror/lib/codemirror'); +var htmlMode = require('codemirror/mode/htmlmixed/htmlmixed'); +var cssMode = require('codemirror/mode/css/css'); +var formatting = require('formatting'); - defaults: { - input : '', - label : '', - codeName : '', - theme : '', - readOnly : true, - lineNumbers : true, - }, +module.exports = Backbone.Model.extend({ - /** @inheritdoc */ - init: function(el) - { - this.editor = CodeMirror.fromTextArea(el, { - dragDrop: false, - lineWrapping: true, - lineNumbers: this.get('lineNumbers'), - readOnly: this.get('readOnly'), - mode: this.get('codeName'), - theme: this.get('theme'), - }); + defaults: { + input : '', + label : '', + codeName : '', + theme : '', + readOnly : true, + lineNumbers : true, + }, - return this; - }, + /** @inheritdoc */ + init: function(el) + { + this.editor = CodeMirror.fromTextArea(el, { + dragDrop: false, + lineWrapping: true, + lineNumbers: this.get('lineNumbers'), + readOnly: this.get('readOnly'), + mode: this.get('codeName'), + theme: this.get('theme'), + }); - /** @inheritdoc */ - setContent : function(v) - { - if(!this.editor) - return; - this.editor.setValue(v); - if(this.editor.autoFormatRange){ - CodeMirror.commands.selectAll(this.editor); - this.editor.autoFormatRange(this.editor.getCursor(true), this.editor.getCursor(false) ); - CodeMirror.commands.goDocStart(this.editor); - } - }, + return this; + }, - }); - }); \ No newline at end of file + /** @inheritdoc */ + setContent : function(v) + { + if(!this.editor) + return; + this.editor.setValue(v); + if(this.editor.autoFormatRange){ + CodeMirror.commands.selectAll(this.editor); + 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 0f229d38a..e4c396ccc 100644 --- a/src/code_manager/model/CssGenerator.js +++ b/src/code_manager/model/CssGenerator.js @@ -1,152 +1,147 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - /** - * @class CssGenerator - * */ - module.exports = Backbone.Model.extend({ - - initialize: function() { - this.compCls = []; - }, - - /** - * Get CSS from component - * @param {Model} model - * @return {String} - */ - buildFromModel: function (model) { - var code = ''; - var style = model.get('style'); - var classes = model.get('classes'); - - // Let's know what classes I've found - if(classes) { - classes.each(function(model){ - this.compCls.push(model.get('name')); - }, this); +var Backbone = require('backbone'); + +module.exports = Backbone.Model.extend({ + + initialize: function() { + this.compCls = []; + }, + + /** + * Get CSS from component + * @param {Model} model + * @return {String} + */ + buildFromModel: function (model) { + var code = ''; + var style = model.get('style'); + var classes = model.get('classes'); + + // Let's know what classes I've found + if(classes) { + classes.each(function(model){ + this.compCls.push(model.get('name')); + }, this); + } + + if(style && Object.keys(style).length !== 0) { + code += '#' + model.cid + '{'; + for(var prop in style){ + if(style.hasOwnProperty(prop)) + code += prop + ':' + style[prop] + ';'; + } + code += '}'; + } + + return code; + }, + + /** + * Get CSS from components + * @param {Model} model + * @return {String} + */ + buildFromComp: function(model) { + var coll = model.get('components') || model, + code = ''; + + coll.each(function(m) { + var cln = m.get('components'); + code += this.buildFromModel(m); + + if(cln.length){ + code += this.buildFromComp(cln); + } + + }, this); + + return code; + }, + + /** @inheritdoc */ + build: function(model, cssc) { + this.compCls = []; + var code = this.buildFromModel(model); + code += this.buildFromComp(model); + var compCls = this.compCls; + + if(cssc){ + var rules = cssc.getAll(); + var mediaRules = {}; + rules.each(function(rule) { + var width = rule.get('mediaText'); + + // If width setted will render it later + if(width){ + var mRule = mediaRules[width]; + if(mRule) + mRule.push(rule); + else + mediaRules[width] = [rule]; + return; } - if(style && Object.keys(style).length !== 0) { - code += '#' + model.cid + '{'; - for(var prop in style){ - if(style.hasOwnProperty(prop)) - code += prop + ':' + style[prop] + ';'; - } - code += '}'; - } + code += this.buildFromRule(rule); + }, this); - return code; - }, - - /** - * Get CSS from components - * @param {Model} model - * @return {String} - */ - buildFromComp: function(model) { - var coll = model.get('components') || model, - code = ''; - - coll.each(function(m) { - var cln = m.get('components'); - code += this.buildFromModel(m); - - if(cln.length){ - code += this.buildFromComp(cln); - } - - }, this); - - return code; - }, - - /** @inheritdoc */ - build: function(model, cssc) { - this.compCls = []; - var code = this.buildFromModel(model); - code += this.buildFromComp(model); - var compCls = this.compCls; - - if(cssc){ - var rules = cssc.getAll(); - var mediaRules = {}; - rules.each(function(rule) { - var width = rule.get('mediaText'); - - // If width setted will render it later - if(width){ - var mRule = mediaRules[width]; - if(mRule) - mRule.push(rule); - else - mediaRules[width] = [rule]; - return; - } - - code += this.buildFromRule(rule); - }, this); - - // Get media rules - for (var ruleW in mediaRules) { - var meRules = mediaRules[ruleW]; - var ruleC = ''; - for(var i = 0, len = meRules.length; i < len; i++){ - ruleC += this.buildFromRule(meRules[i]); - } - - if (ruleC) { - code += '@media ' + ruleW + '{' + ruleC + '}'; - } - } + // Get media rules + for (var ruleW in mediaRules) { + var meRules = mediaRules[ruleW]; + var ruleC = ''; + for(var i = 0, len = meRules.length; i < len; i++){ + ruleC += this.buildFromRule(meRules[i]); + } + if (ruleC) { + code += '@media ' + ruleW + '{' + ruleC + '}'; } - return code; - }, - - /** - * Get CSS from the rule model - * @param {Model} rule - * @return {string} CSS string - */ - buildFromRule: function(rule) { - var result = ''; - var selectorsAdd = rule.get('selectorsAdd'); - var selectors = rule.get('selectors'); - var ruleStyle = rule.get('style'); - var state = rule.get('state'); - var strSel = ''; - var found = 0; - var compCls = this.compCls; - - // Get string of selectors - selectors.each(function(selector){ - strSel += '.' + selector.get('name'); - if(compCls.indexOf(selector.get('name')) > -1) - found = 1; - }); - - // With 'found' will skip rules which selectors are not found in - // canvas components. - if ((strSel && found) || selectorsAdd) { - strSel += state ? ':' + state : ''; - strSel += selectorsAdd ? (strSel ? ', ' : '') + selectorsAdd : ''; - var strStyle = ''; - - // Get string of style properties - if(ruleStyle && Object.keys(ruleStyle).length !== 0){ - for(var prop2 in ruleStyle){ - if(ruleStyle.hasOwnProperty(prop2)) - strStyle += prop2 + ':' + ruleStyle[prop2] + ';'; - } - } - - if(strStyle) - result += strSel + '{' + strStyle + '}'; + } + + } + return code; + }, + + /** + * Get CSS from the rule model + * @param {Model} rule + * @return {string} CSS string + */ + buildFromRule: function(rule) { + var result = ''; + var selectorsAdd = rule.get('selectorsAdd'); + var selectors = rule.get('selectors'); + var ruleStyle = rule.get('style'); + var state = rule.get('state'); + var strSel = ''; + var found = 0; + var compCls = this.compCls; + + // Get string of selectors + selectors.each(function(selector){ + strSel += '.' + selector.get('name'); + if(compCls.indexOf(selector.get('name')) > -1) + found = 1; + }); + + // With 'found' will skip rules which selectors are not found in + // canvas components. + if ((strSel && found) || selectorsAdd) { + strSel += state ? ':' + state : ''; + strSel += selectorsAdd ? (strSel ? ', ' : '') + selectorsAdd : ''; + var strStyle = ''; + + // Get string of style properties + if(ruleStyle && Object.keys(ruleStyle).length !== 0){ + for(var prop2 in ruleStyle){ + if(ruleStyle.hasOwnProperty(prop2)) + strStyle += prop2 + ':' + ruleStyle[prop2] + ';'; } + } - return result; - }, + if(strStyle) + result += strSel + '{' + strStyle + '}'; + } - }); -}); \ No newline at end of file + return result; + }, + +}); diff --git a/src/code_manager/model/HtmlGenerator.js b/src/code_manager/model/HtmlGenerator.js index 70e4cbc4b..160eb1c43 100644 --- a/src/code_manager/model/HtmlGenerator.js +++ b/src/code_manager/model/HtmlGenerator.js @@ -1,24 +1,19 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - /** - * @class HtmlGenerator - * */ - module.exports = Backbone.Model.extend({ +var Backbone = require('backbone'); - /** @inheritdoc */ - build: function(model, cssc){ - var coll = model.get('components') || model, - code = ''; +module.exports = Backbone.Model.extend({ - coll.each(function(m){ - code += m.toHTML({ - cssc: cssc - }); - }, this); + /** @inheritdoc */ + build: function(model, cssc){ + var coll = model.get('components') || model, + code = ''; - return code; - }, + coll.each(function(m){ + code += m.toHTML({ + cssc: cssc + }); + }, this); - }); -}); \ No newline at end of file + return code; + }, + +}); diff --git a/src/code_manager/model/JsGenerator.js b/src/code_manager/model/JsGenerator.js index ef2921be9..6dad90f95 100644 --- a/src/code_manager/model/JsGenerator.js +++ b/src/code_manager/model/JsGenerator.js @@ -1,64 +1,61 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - - module.exports = Backbone.Model.extend({ - - mapModel: function (model) { - var code = ''; - var script = model.get('script'); - var type = model.get('type'); - var comps = model.get('components'); - var id = model.cid; - - if (script) { - // If the component has scripts we need to expose his ID - var attr = model.get('attributes'); - attr = _.extend({}, attr, {id: id}); - model.set('attributes', attr); - - var scrStr = 'function(){' + script + '}'; - scrStr = typeof script == 'function' ? script.toString() : scrStr; - - // 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}; - } else { - var mapType = this.mapJs[type]; - - if(mapType) { - mapType.ids.push(id); - } else { - this.mapJs[type] = {ids: [id], code: scrStr}; - } - } +var Backbone = require('backbone'); + +module.exports = Backbone.Model.extend({ + + mapModel: function (model) { + var code = ''; + var script = model.get('script'); + var type = model.get('type'); + var comps = model.get('components'); + var id = model.cid; + + if (script) { + // If the component has scripts we need to expose his ID + var attr = model.get('attributes'); + attr = _.extend({}, attr, {id: id}); + model.set('attributes', attr); + + var scrStr = 'function(){' + script + '}'; + scrStr = typeof script == 'function' ? script.toString() : scrStr; + + // 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}; + } else { + var mapType = this.mapJs[type]; + + if(mapType) { + mapType.ids.push(id); + } else { + this.mapJs[type] = {ids: [id], code: scrStr}; } + } + } - comps.each(function(model) { - code += this.mapModel(model); - }, this); + comps.each(function(model) { + code += this.mapModel(model); + }, this); - return code; - }, + return code; + }, - build: function(model) { - this.mapJs = {}; - this.mapModel(model); + build: function(model) { + this.mapJs = {}; + this.mapModel(model); - var code = ''; + var code = ''; - for(var type in this.mapJs) { - var mapType = this.mapJs[type]; - var ids = '#' + mapType.ids.join(', #'); - code += 'var items = document.querySelectorAll("'+ids+'");' + - 'for (var i = 0, len = items.length; i < len; i++) {'+ - '(' + mapType.code + '.bind(items[i]))();' + - '}'; - } + for(var type in this.mapJs) { + var mapType = this.mapJs[type]; + var ids = '#' + mapType.ids.join(', #'); + code += 'var items = document.querySelectorAll("'+ids+'");' + + 'for (var i = 0, len = items.length; i < len; i++) {'+ + '(' + mapType.code + '.bind(items[i]))();' + + '}'; + } - return code; - }, + return code; + }, - }); -}); \ No newline at end of file +}); diff --git a/src/code_manager/model/JsonGenerator.js b/src/code_manager/model/JsonGenerator.js index df4cff3f6..037497ced 100644 --- a/src/code_manager/model/JsonGenerator.js +++ b/src/code_manager/model/JsonGenerator.js @@ -1,41 +1,36 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - /** - * @class JsonGenerator - * */ - module.exports = Backbone.Model.extend({ +var Backbone = require('backbone'); - /** @inheritdoc */ - build: function(model) { - var json = model.toJSON(); - this.beforeEach(json); +module.exports = Backbone.Model.extend({ - _.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); + /** @inheritdoc */ + build: function(model) { + var json = model.toJSON(); + this.beforeEach(json); - return 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); + } + } + }, this); - /** - * Execute on each object - * @param {Object} obj - */ - beforeEach: function(obj) { - delete obj.status; - } + return json; + }, - }); -}); \ No newline at end of file + /** + * Execute on each object + * @param {Object} obj + */ + beforeEach: function(obj) { + delete obj.status; + } + +}); diff --git a/src/code_manager/view/EditorView.js b/src/code_manager/view/EditorView.js index 37ef003ac..9ba5967c1 100644 --- a/src/code_manager/view/EditorView.js +++ b/src/code_manager/view/EditorView.js @@ -1,27 +1,22 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var vTemplate = require('text!./../template/editor.html'); - /** - * @class EditorView - * */ - module.exports = Backbone.View.extend({ - - template: _.template(vTemplate), - - initialize: function(o){ - this.config = o.config || {}; - this.pfx = this.config.stylePrefix; - }, - - render : function(){ - var obj = this.model.toJSON(); - obj.pfx = this.pfx; - this.$el.html( this.template(obj) ); - this.$el.attr('class', this.pfx + 'editor-c'); - this.$el.find('#'+this.pfx+'code').html(this.model.get('input')); - return this; - }, - - }); -}); \ No newline at end of file +var Backbone = require('backbone'); +var vTemplate = require('text!./../template/editor.html'); + +module.exports = Backbone.View.extend({ + + template: _.template(vTemplate), + + initialize: function(o){ + this.config = o.config || {}; + this.pfx = this.config.stylePrefix; + }, + + render: function(){ + var obj = this.model.toJSON(); + obj.pfx = this.pfx; + this.$el.html( this.template(obj) ); + this.$el.attr('class', this.pfx + 'editor-c'); + this.$el.find('#'+this.pfx+'code').html(this.model.get('input')); + return this; + }, + +}); diff --git a/src/commands/config/config.js b/src/commands/config/config.js index 216b52a10..23351446a 100644 --- a/src/commands/config/config.js +++ b/src/commands/config/config.js @@ -1,25 +1,23 @@ -define(function () { - return { +module.exports = { - ESCAPE_KEY : 27, + ESCAPE_KEY: 27, - stylePrefix : 'com-', + stylePrefix: 'com-', - defaults : [], + defaults: [], - // Editor model - em : null, + // Editor model + em: null, - // If true center new first-level components - firstCentered : true, + // If true center new first-level components + firstCentered: true, - // If true the new component will created with 'height', else 'min-height' - newFixedH : false, + // If true the new component will created with 'height', else 'min-height' + newFixedH: false, - // Minimum height (in px) of new component - minComponentH : 50, + // Minimum height (in px) of new component + minComponentH: 50, - // Minimum width (in px) of component on creation - minComponentW : 50, - }; -}); \ No newline at end of file + // Minimum width (in px) of component on creation + minComponentW: 50, +}; diff --git a/src/commands/index.js b/src/commands/index.js index ee3bc2d5a..8f366aa44 100644 --- a/src/commands/index.js +++ b/src/commands/index.js @@ -38,201 +38,199 @@ * }, * ... */ -define(function(require) { - - return function() { - var c = {}, - commands = {}, - defaultCommands = {}, - defaults = require('./config/config'), - AbsCommands = require('./view/CommandAbstract'); - - // Need it here as it would be used below - var add = function(id, obj){ - delete obj.initialize; - commands[id] = AbsCommands.extend(obj); - return this; - }; - - return { - - /** - * Name of the module - * @type {String} - * @private - */ - name: 'Commands', - - /** - * Initialize module. Automatically called with a new instance of the editor - * @param {Object} config Configurations - * @private - */ - init: function(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; - - // Load commands passed via configuration - for( var k in c.defaults) { - var obj = c.defaults[k]; - if(obj.id) - this.add(obj.id, obj); - } - - defaultCommands['select-comp'] = require('./view/SelectComponent'); - defaultCommands['create-comp'] = require('./view/CreateComponent'); - defaultCommands['delete-comp'] = require('./view/DeleteComponent'); - defaultCommands['image-comp'] = require('./view/ImageComponent'); - defaultCommands['move-comp'] = require('./view/MoveComponent'); - defaultCommands['text-comp'] = require('./view/TextComponent'); - defaultCommands['insert-custom'] = require('./view/InsertCustom'); - defaultCommands['export-template'] = require('./view/ExportTemplate'); - defaultCommands['sw-visibility'] = require('./view/SwitchVisibility'); - defaultCommands['open-layers'] = require('./view/OpenLayers'); - defaultCommands['open-sm'] = require('./view/OpenStyleManager'); - defaultCommands['open-tm'] = require('./view/OpenTraitManager'); - defaultCommands['open-blocks'] = require('./view/OpenBlocks'); - defaultCommands['open-assets'] = require('./view/OpenAssets'); - defaultCommands['show-offset'] = require('./view/ShowOffset'); - defaultCommands.fullscreen = require('./view/Fullscreen'); - defaultCommands.preview = require('./view/Preview'); - defaultCommands.resize = require('./view/Resize'); - - defaultCommands['tlb-delete'] = { - run: function(ed) { - var sel = ed.getSelected(); - - if(!sel || !sel.get('removable')) { - console.warn('The element is not removable'); - return; - } - - sel.set('status', ''); - sel.destroy(); - ed.trigger('component:update', sel); - ed.editor.set('selectedComponent', null); - }, - }; - - defaultCommands['tlb-clone'] = { - run: function(ed) { - var sel = ed.getSelected(); - - if(!sel || !sel.get('copyable')) { - console.warn('The element is not clonable'); - return; - } - - var collection = sel.collection; - var index = collection.indexOf(sel); - collection.add(sel.clone(), {at: index + 1}); + +module.exports = function() { + var c = {}, + commands = {}, + defaultCommands = {}, + defaults = require('./config/config'), + AbsCommands = require('./view/CommandAbstract'); + + // Need it here as it would be used below + var add = function(id, obj){ + delete obj.initialize; + commands[id] = AbsCommands.extend(obj); + return this; + }; + + return { + + /** + * Name of the module + * @type {String} + * @private + */ + name: 'Commands', + + /** + * Initialize module. Automatically called with a new instance of the editor + * @param {Object} config Configurations + * @private + */ + init: function(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; + + // Load commands passed via configuration + for( var k in c.defaults) { + var obj = c.defaults[k]; + if(obj.id) + this.add(obj.id, obj); + } + + defaultCommands['select-comp'] = require('./view/SelectComponent'); + defaultCommands['create-comp'] = require('./view/CreateComponent'); + defaultCommands['delete-comp'] = require('./view/DeleteComponent'); + defaultCommands['image-comp'] = require('./view/ImageComponent'); + defaultCommands['move-comp'] = require('./view/MoveComponent'); + defaultCommands['text-comp'] = require('./view/TextComponent'); + defaultCommands['insert-custom'] = require('./view/InsertCustom'); + defaultCommands['export-template'] = require('./view/ExportTemplate'); + defaultCommands['sw-visibility'] = require('./view/SwitchVisibility'); + defaultCommands['open-layers'] = require('./view/OpenLayers'); + defaultCommands['open-sm'] = require('./view/OpenStyleManager'); + defaultCommands['open-tm'] = require('./view/OpenTraitManager'); + defaultCommands['open-blocks'] = require('./view/OpenBlocks'); + defaultCommands['open-assets'] = require('./view/OpenAssets'); + defaultCommands['show-offset'] = require('./view/ShowOffset'); + defaultCommands.fullscreen = require('./view/Fullscreen'); + defaultCommands.preview = require('./view/Preview'); + defaultCommands.resize = require('./view/Resize'); + + defaultCommands['tlb-delete'] = { + run: function(ed) { + var sel = ed.getSelected(); + + if(!sel || !sel.get('removable')) { + console.warn('The element is not removable'); + return; + } + + sel.set('status', ''); + sel.destroy(); + ed.trigger('component:update', sel); + ed.editor.set('selectedComponent', null); + }, + }; + + defaultCommands['tlb-clone'] = { + run: function(ed) { + var sel = ed.getSelected(); + + if(!sel || !sel.get('copyable')) { + console.warn('The element is not clonable'); + return; + } + + var collection = sel.collection; + var index = collection.indexOf(sel); + collection.add(sel.clone(), {at: index + 1}); + ed.trigger('component:update', sel); + }, + }; + + defaultCommands['tlb-move'] = { + run: function(ed){ + var sel = ed.getSelected(); + + if(!sel || !sel.get('draggable')) { + console.warn('The element is not draggable'); + return; + } + + var toolbarEl = ed.Canvas.getToolbarEl(); + var cmdMove = ed.Commands.get('move-comp'); + + cmdMove.onEndMoveFromModel = function() { + ed.editor.runDefault(); + ed.editor.set('selectedComponent', sel); ed.trigger('component:update', sel); - }, - }; - - defaultCommands['tlb-move'] = { - run: function(ed){ - var sel = ed.getSelected(); - - if(!sel || !sel.get('draggable')) { - console.warn('The element is not draggable'); - return; - } - - var toolbarEl = ed.Canvas.getToolbarEl(); - var cmdMove = ed.Commands.get('move-comp'); - - cmdMove.onEndMoveFromModel = function() { - ed.editor.runDefault(); - ed.editor.set('selectedComponent', sel); - ed.trigger('component:update', sel); - }; - - ed.editor.stopDefault(); - cmdMove.initSorterFromModel(sel); - sel.set('status', 'selected'); - toolbarEl.style.display = 'none'; - }, - }; - - if(c.em) - c.model = c.em.get('Canvas'); - - return this; - }, - - /** - * On load callback - * @private - */ - onLoad: function() { - this.loadDefaultCommands(); - }, - - /** - * Add new command to the collection - * @param {string} id Command's ID - * @param {Object} command Object representing you command. Methods `run` and `stop` are required - * @return {this} - * @example - * commands.add('myCommand', { - * run: function(editor, sender){ - * alert('Hello world!'); - * }, - * stop: function(editor, sender){ - * }, - * }); - * */ - add: add, - - /** - * Get command by ID - * @param {string} id Command's ID - * @return {Object} Object representing the command - * @example - * var myCommand = commands.get('myCommand'); - * myCommand.run(); - * */ - get: function(id) { - var el = commands[id]; - - if(typeof el == 'function'){ - el = new el(c); - commands[id] = el; - } - - return el; - }, - - /** - * Check if command exists - * @param {string} id Command's ID - * @return {Boolean} - * */ - has: function(id) { - return !!commands[id]; - }, - - /** - * Load default commands - * @return {this} - * @private - * */ - loadDefaultCommands: function(){ - for (var id in defaultCommands) { - this.add(id, defaultCommands[id]); - } - - return this; - }, - }; + }; + + ed.editor.stopDefault(); + cmdMove.initSorterFromModel(sel); + sel.set('status', 'selected'); + toolbarEl.style.display = 'none'; + }, + }; + if(c.em) + c.model = c.em.get('Canvas'); + + return this; + }, + + /** + * On load callback + * @private + */ + onLoad: function() { + this.loadDefaultCommands(); + }, + + /** + * Add new command to the collection + * @param {string} id Command's ID + * @param {Object} command Object representing you command. Methods `run` and `stop` are required + * @return {this} + * @example + * commands.add('myCommand', { + * run: function(editor, sender){ + * alert('Hello world!'); + * }, + * stop: function(editor, sender){ + * }, + * }); + * */ + add: add, + + /** + * Get command by ID + * @param {string} id Command's ID + * @return {Object} Object representing the command + * @example + * var myCommand = commands.get('myCommand'); + * myCommand.run(); + * */ + get: function(id) { + var el = commands[id]; + + if(typeof el == 'function'){ + el = new el(c); + commands[id] = el; + } + + return el; + }, + + /** + * Check if command exists + * @param {string} id Command's ID + * @return {Boolean} + * */ + has: function(id) { + return !!commands[id]; + }, + + /** + * Load default commands + * @return {this} + * @private + * */ + loadDefaultCommands: function(){ + for (var id in defaultCommands) { + this.add(id, defaultCommands[id]); + } + + return this; + }, }; -}); + +}; diff --git a/src/commands/model/Command.js b/src/commands/model/Command.js index 0fc0fc1c4..801af11b9 100644 --- a/src/commands/model/Command.js +++ b/src/commands/model/Command.js @@ -1,14 +1,9 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - /** - * @class Command - * */ - module.exports = Backbone.Model.extend({ - - defaults :{ - id : '', - } - - }); -}); \ No newline at end of file +var Backbone = require('backbone'); + +module.exports = Backbone.Model.extend({ + + defaults :{ + id: '', + } + +}); diff --git a/src/commands/model/Commands.js b/src/commands/model/Commands.js index 75dfb446d..1313b3e5f 100644 --- a/src/commands/model/Commands.js +++ b/src/commands/model/Commands.js @@ -1,13 +1,8 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var Command = require('./Command'); - /** - * @class Commands - * */ - module.exports = Backbone.Collection.extend({ - - model: Command, - - }); -}); \ No newline at end of file +var Backbone = require('backbone'); +var Command = require('./Command'); + +module.exports = Backbone.Collection.extend({ + + model: Command, + +}); diff --git a/src/commands/view/CommandAbstract.js b/src/commands/view/CommandAbstract.js index 4f45fb597..9efee4f1a 100644 --- a/src/commands/view/CommandAbstract.js +++ b/src/commands/view/CommandAbstract.js @@ -1,117 +1,111 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - /** - * @class CommandAbstract - * @private - * */ - module.exports = Backbone.View.extend({ - - /** - * Initialize method that can't be removed - * @param {Object} o Options - * @private - * */ - initialize: function(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.canvas = this.em.get && this.em.get('Canvas'); - - if(this.em.get) - this.setElement(this.getCanvas()); - - if(this.canvas){ - this.$canvas = this.$el; - this.$wrapper = $(this.getCanvasWrapper()); - this.frameEl = this.canvas.getFrameEl(); - this.canvasTool = this.getCanvasTools(); - this.bodyEl = this.getCanvasBody(); - } - - this.init(this.config); - }, - - /** - * On frame scroll callback - * @param {[type]} e [description] - * @return {[type]} [description] - */ - onFrameScroll: function(e){}, - - /** - * Returns canval element - * @return {HTMLElement} - */ - getCanvas: function(){ - return this.canvas.getElement(); - }, - - /** - * Get canvas body element - * @return {HTMLElement} - */ - getCanvasBody: function(){ - return this.canvas.getBody(); - }, - - /** - * Get canvas wrapper element - * @return {HTMLElement} - */ - getCanvasWrapper: function(){ - return this.canvas.getWrapperEl(); - }, - - /** - * Get canvas wrapper element - * @return {HTMLElement} - */ - getCanvasTools: function(){ - return this.canvas.getToolsEl(); - }, - - /** - * Get the offset of the element - * @param {HTMLElement} el - * @return {Object} - */ - offset: function(el){ - var rect = el.getBoundingClientRect(); - return { - top: rect.top + el.ownerDocument.body.scrollTop, - left: rect.left + el.ownerDocument.body.scrollLeft - }; - }, - - /** - * Callback triggered after initialize - * @param {Object} o Options - * @private - * */ - init: function(o){}, - - /** - * Method that run command - * @param {Object} em Editor model - * @param {Object} sender Button sender - * @private - * */ - run: function(em, sender) {}, - - /** - * Method that stop command - * @param {Object} em Editor model - * @param {Object} sender Button sender - * @private - * */ - stop: function(em, sender) {}, - - }); - }); \ No newline at end of file +var Backbone = require('backbone'); + +module.exports = Backbone.View.extend({ + + /** + * Initialize method that can't be removed + * @param {Object} o Options + * @private + * */ + initialize: function(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.canvas = this.em.get && this.em.get('Canvas'); + + if(this.em.get) + this.setElement(this.getCanvas()); + + if(this.canvas){ + this.$canvas = this.$el; + this.$wrapper = $(this.getCanvasWrapper()); + this.frameEl = this.canvas.getFrameEl(); + this.canvasTool = this.getCanvasTools(); + this.bodyEl = this.getCanvasBody(); + } + + this.init(this.config); + }, + + /** + * On frame scroll callback + * @param {[type]} e [description] + * @return {[type]} [description] + */ + onFrameScroll: function(e){}, + + /** + * Returns canval element + * @return {HTMLElement} + */ + getCanvas: function(){ + return this.canvas.getElement(); + }, + + /** + * Get canvas body element + * @return {HTMLElement} + */ + getCanvasBody: function(){ + return this.canvas.getBody(); + }, + + /** + * Get canvas wrapper element + * @return {HTMLElement} + */ + getCanvasWrapper: function(){ + return this.canvas.getWrapperEl(); + }, + + /** + * Get canvas wrapper element + * @return {HTMLElement} + */ + getCanvasTools: function(){ + return this.canvas.getToolsEl(); + }, + + /** + * Get the offset of the element + * @param {HTMLElement} el + * @return {Object} + */ + offset: function(el){ + var rect = el.getBoundingClientRect(); + return { + top: rect.top + el.ownerDocument.body.scrollTop, + left: rect.left + el.ownerDocument.body.scrollLeft + }; + }, + + /** + * Callback triggered after initialize + * @param {Object} o Options + * @private + * */ + init: function(o){}, + + /** + * Method that run command + * @param {Object} em Editor model + * @param {Object} sender Button sender + * @private + * */ + run: function(em, sender) {}, + + /** + * Method that stop command + * @param {Object} em Editor model + * @param {Object} sender Button sender + * @private + * */ + stop: function(em, sender) {}, + +}); diff --git a/src/commands/view/CreateComponent.js b/src/commands/view/CreateComponent.js index 008782529..766c06f8b 100644 --- a/src/commands/view/CreateComponent.js +++ b/src/commands/view/CreateComponent.js @@ -1,233 +1,230 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var SelectPosition = require('./SelectPosition'); - - module.exports = _.extend({}, SelectPosition, { - - init: function(opt) { - _.bindAll(this,'startDraw','draw','endDraw','rollback'); - this.config = opt || {}; - this.hType = this.config.newFixedH ? 'height' : 'min-height'; - this.allowDraw = 1; - }, - - /** - * Start with enabling to select position and listening to start drawning - * @private - * */ - enable: function() { - SelectPosition.enable.apply(this, arguments); - this.$wr.css('cursor','crosshair'); - if(this.allowDraw) - this.$wr.on('mousedown', this.startDraw); - this.ghost = this.canvas.getGhostEl(); - }, - - /** - * Start drawing component - * @param {Object} e Event - * @private - * */ - startDraw : function(e) { - e.preventDefault(); - this.stopSelectPosition(); - this.ghost.style.display = 'block'; - this.frameOff = this.getOffsetDim(); - this.startPos = { - top : e.pageY + this.frameOff.top, - left: e.pageX + this.frameOff.left - }; - this.isDragged = false; - this.tempComponent = {style: {}}; - this.beforeDraw(this.tempComponent); - this.updateSize(this.startPos.top, this.startPos.left, 0, 0); - this.toggleEvents(1); - }, - - /** - * Enable/Disable events - * @param {Boolean} enable - */ - toggleEvents: function(enable) { - var method = enable ? 'on' : 'off'; - this.$wr[method]('mousemove', this.draw); - this.$wr[method]('mouseup', this.endDraw); - this.$canvas[method]('mousemove', this.draw); - $(document)[method]('mouseup', this.endDraw); - $(document)[method]('keypress', this.rollback); - }, - - /** - * While drawing the component - * @param {Object} e Event - * @private - * */ - draw: function(e) { - this.isDragged = true; - this.updateComponentSize(e); - }, - - /** - * End drawing component - * @param {Object} e Event - * @private - * */ - endDraw : function(e) { - this.toggleEvents(); - var model = {}; - // Only if the mouse was moved - 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); - this.sorter.prevTarget = null; - } - this.ghost.style.display = 'none'; - this.startSelectPosition(); - this.afterDraw(model); - }, - - /** - * Create new component inside the target - * @param {Object} target Tha target collection - * @param {Object} component New component to create - * @param {number} index Index inside the collection, 0 if no children inside - * @param {string} method Before or after of the children - * @param {Object} opts Options - */ - create: function(target, component, index, method, opts) { - index = method === 'after' ? index + 1 : index; - var opt = opts || {}; - var $trg = $(target); - var trgModel = $trg.data('model'); - 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"); - }, - - /** - * Check and set basic requirements for the component - * @param {Object} component New component to be created - * @return {Object} Component updated - * @private - * */ - setRequirements: function(component) { - var c = this.config; - var compStl = component.style; - // Check min width - 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'; - // Set overflow in case of fixed height - if(c.newFixedH) - compStl.overflow = 'auto'; - if(!this.absoluteMode){ - delete compStl.left; - delete compStl.top; - }else - compStl.position = 'absolute'; - var lp = this.sorter.lastPos; - - if(this.nearFloat(lp.index, lp.method, this.sorter.lastDims)) - compStl.float = 'left'; - - if(this.config.firstCentered && - this.getCanvasWrapper() == this.sorter.target){ - compStl.margin = '0 auto'; - } - - return component; - }, - - /** - * Update new component size while drawing - * @param {Object} e Event - * @private - * */ - updateComponentSize : function (e) { - var y = e.pageY + this.frameOff.top; - 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; - if (x < left) { - left = x; - width = start.left - x; - } - if (y < top) { - top = y; - height = start.top - y; - } - this.updateSize(top, left, width, height); - }, - - /** - * Update size - * @private - */ - updateSize: function(top, left, width, height){ - var u = 'px'; - var ghStl = this.ghost.style; - var compStl = this.tempComponent.style; - 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; - }, - - /** - * Used to bring the previous situation before event started - * @param {Object} e Event - * @param {Boolean} forse Indicates if rollback in anycase - * @private - * */ - rollback: function(e, force) { - var key = e.which || e.keyCode; - if(key == this.config.ESCAPE_KEY || force){ - this.isDragged = false; - this.endDraw(); - } - return; - }, - - /** - * This event is triggered at the beginning of a draw operation - * @param {Object} component Object component before creation - * @private - * */ - beforeDraw: function(component){ - component.editable = false;//set this component editable - }, - - /** - * This event is triggered at the end of a draw operation - * @param {Object} model Component model created - * @private - * */ - afterDraw: function(model){}, - - - run: function(editor, sender, opts){ - this.editor = editor; - this.sender = sender; - this.$wr = this.$wrapper; - this.enable(); - }, - - stop: function(){ - this.stopSelectPosition(); - this.$wrapper.css('cursor',''); - this.$wrapper.unbind(); - } - }); - }); \ No newline at end of file +var Backbone = require('backbone'); +var SelectPosition = require('./SelectPosition'); + +module.exports = _.extend({}, SelectPosition, { + + init: function(opt) { + _.bindAll(this,'startDraw','draw','endDraw','rollback'); + this.config = opt || {}; + this.hType = this.config.newFixedH ? 'height' : 'min-height'; + this.allowDraw = 1; + }, + + /** + * Start with enabling to select position and listening to start drawning + * @private + * */ + enable: function() { + SelectPosition.enable.apply(this, arguments); + this.$wr.css('cursor','crosshair'); + if(this.allowDraw) + this.$wr.on('mousedown', this.startDraw); + this.ghost = this.canvas.getGhostEl(); + }, + + /** + * Start drawing component + * @param {Object} e Event + * @private + * */ + startDraw : function(e) { + e.preventDefault(); + this.stopSelectPosition(); + this.ghost.style.display = 'block'; + this.frameOff = this.getOffsetDim(); + this.startPos = { + top : e.pageY + this.frameOff.top, + left: e.pageX + this.frameOff.left + }; + this.isDragged = false; + this.tempComponent = {style: {}}; + this.beforeDraw(this.tempComponent); + this.updateSize(this.startPos.top, this.startPos.left, 0, 0); + this.toggleEvents(1); + }, + + /** + * Enable/Disable events + * @param {Boolean} enable + */ + toggleEvents: function(enable) { + var method = enable ? 'on' : 'off'; + this.$wr[method]('mousemove', this.draw); + this.$wr[method]('mouseup', this.endDraw); + this.$canvas[method]('mousemove', this.draw); + $(document)[method]('mouseup', this.endDraw); + $(document)[method]('keypress', this.rollback); + }, + + /** + * While drawing the component + * @param {Object} e Event + * @private + * */ + draw: function(e) { + this.isDragged = true; + this.updateComponentSize(e); + }, + + /** + * End drawing component + * @param {Object} e Event + * @private + * */ + endDraw : function(e) { + this.toggleEvents(); + var model = {}; + // Only if the mouse was moved + 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); + this.sorter.prevTarget = null; + } + this.ghost.style.display = 'none'; + this.startSelectPosition(); + this.afterDraw(model); + }, + + /** + * Create new component inside the target + * @param {Object} target Tha target collection + * @param {Object} component New component to create + * @param {number} index Index inside the collection, 0 if no children inside + * @param {string} method Before or after of the children + * @param {Object} opts Options + */ + create: function(target, component, index, method, opts) { + index = method === 'after' ? index + 1 : index; + var opt = opts || {}; + var $trg = $(target); + var trgModel = $trg.data('model'); + 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"); + }, + + /** + * Check and set basic requirements for the component + * @param {Object} component New component to be created + * @return {Object} Component updated + * @private + * */ + setRequirements: function(component) { + var c = this.config; + var compStl = component.style; + // Check min width + 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'; + // Set overflow in case of fixed height + if(c.newFixedH) + compStl.overflow = 'auto'; + if(!this.absoluteMode){ + delete compStl.left; + delete compStl.top; + }else + compStl.position = 'absolute'; + var lp = this.sorter.lastPos; + + if(this.nearFloat(lp.index, lp.method, this.sorter.lastDims)) + compStl.float = 'left'; + + if(this.config.firstCentered && + this.getCanvasWrapper() == this.sorter.target){ + compStl.margin = '0 auto'; + } + + return component; + }, + + /** + * Update new component size while drawing + * @param {Object} e Event + * @private + * */ + updateComponentSize : function (e) { + var y = e.pageY + this.frameOff.top; + 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; + if (x < left) { + left = x; + width = start.left - x; + } + if (y < top) { + top = y; + height = start.top - y; + } + this.updateSize(top, left, width, height); + }, + + /** + * Update size + * @private + */ + updateSize: function(top, left, width, height){ + var u = 'px'; + var ghStl = this.ghost.style; + var compStl = this.tempComponent.style; + 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; + }, + + /** + * Used to bring the previous situation before event started + * @param {Object} e Event + * @param {Boolean} forse Indicates if rollback in anycase + * @private + * */ + rollback: function(e, force) { + var key = e.which || e.keyCode; + if(key == this.config.ESCAPE_KEY || force){ + this.isDragged = false; + this.endDraw(); + } + return; + }, + + /** + * This event is triggered at the beginning of a draw operation + * @param {Object} component Object component before creation + * @private + * */ + beforeDraw: function(component){ + component.editable = false;//set this component editable + }, + + /** + * This event is triggered at the end of a draw operation + * @param {Object} model Component model created + * @private + * */ + afterDraw: function(model){}, + + + run: function(editor, sender, opts){ + this.editor = editor; + this.sender = sender; + this.$wr = this.$wrapper; + this.enable(); + }, + + stop: function(){ + this.stopSelectPosition(); + this.$wrapper.css('cursor',''); + this.$wrapper.unbind(); + } +}); diff --git a/src/commands/view/DeleteComponent.js b/src/commands/view/DeleteComponent.js index 38d250575..685d33fb8 100644 --- a/src/commands/view/DeleteComponent.js +++ b/src/commands/view/DeleteComponent.js @@ -1,90 +1,79 @@ -define(function(require, exports, module){ - 'use strict'; - var Backbone = require('backbone'); - var SelectComponent = require('./SelectComponent'); - /** - * @class DeleteComponent - * @private - * */ - module.exports = _.extend({},SelectComponent,{ +var Backbone = require('backbone'); +var SelectComponent = require('./SelectComponent'); - init: function(o){ - _.bindAll(this, 'startDelete', 'stopDelete', 'onDelete'); - this.hoverClass = this.pfx + 'hover-delete'; - this.badgeClass = this.pfx + 'badge-red'; - }, +module.exports = _.extend({},SelectComponent,{ - enable: function() - { - var that = this; - this.$el.find('*') - .mouseover(this.startDelete) - .mouseout(this.stopDelete) - .click(this.onDelete); - }, + init: function(o){ + _.bindAll(this, 'startDelete', 'stopDelete', 'onDelete'); + this.hoverClass = this.pfx + 'hover-delete'; + this.badgeClass = this.pfx + 'badge-red'; + }, - /** - * Start command - * @param {Object} e - * @private - */ - startDelete: function(e) - { - e.stopPropagation(); - var $this = $(e.target); + enable: function() { + var that = this; + this.$el.find('*') + .mouseover(this.startDelete) + .mouseout(this.stopDelete) + .click(this.onDelete); + }, - // Show badge if possible - if($this.data('model').get('removable')){ - $this.addClass(this.hoverClass); - this.attachBadge($this.get(0)); - } + /** + * Start command + * @param {Object} e + * @private + */ + startDelete: function(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)); + } - /** - * Stop command - * @param {Object} e - * @private - */ - stopDelete: function(e) - { - e.stopPropagation(); - var $this = $(e.target); - $this.removeClass(this.hoverClass); + }, - // Hide badge if possible - if(this.badge) - this.badge.css({ left: -1000, top:-1000 }); - }, + /** + * Stop command + * @param {Object} e + * @private + */ + stopDelete: function(e) { + e.stopPropagation(); + var $this = $(e.target); + $this.removeClass(this.hoverClass); - /** - * Delete command - * @param {Object} e - * @private - */ - onDelete: function(e) - { - e.stopPropagation(); - var $this = $(e.target); + // Hide badge if possible + if(this.badge) + this.badge.css({ left: -1000, top:-1000 }); + }, - // Do nothing in case can't remove - if(!$this.data('model').get('removable')) - return; + /** + * Delete command + * @param {Object} e + * @private + */ + onDelete: function(e) { + e.stopPropagation(); + var $this = $(e.target); - $this.data('model').destroy(); - this.removeBadge(); - this.clean(); - }, + // Do nothing in case can't remove + if(!$this.data('model').get('removable')) + return; - /** - * Updates badge label - * @param {Object} model - * @private - * */ - updateBadgeLabel: function (model) - { - this.badge.html( 'Remove ' + model.getName() ); - }, + $this.data('model').destroy(); + this.removeBadge(); + this.clean(); + }, - }); - }); \ No newline at end of file + /** + * Updates badge label + * @param {Object} model + * @private + * */ + updateBadgeLabel: function (model) { + this.badge.html( 'Remove ' + model.getName() ); + }, + +}); diff --git a/src/commands/view/ExportTemplate.js b/src/commands/view/ExportTemplate.js index 12c9b7223..5a5486cf5 100644 --- a/src/commands/view/ExportTemplate.js +++ b/src/commands/view/ExportTemplate.js @@ -1,78 +1,72 @@ -define(function() { - /** - * @class ExportTemplate - * @private - * */ - return { +module.exports = { - run: function(editor, sender) { - this.sender = sender; - this.wrapper = editor.DomComponents.getWrapper(); - this.components = editor.DomComponents.getComponents(); - this.modal = editor.Modal || null; - this.cm = editor.CodeManager || null; - this.cssc = editor.CssComposer || null; - this.protCss = editor.Config.protectedCss; - this.pfx = editor.Config.stylePrefix || ''; - this.enable(); - }, + run: function(editor, sender) { + this.sender = sender; + this.wrapper = editor.DomComponents.getWrapper(); + this.components = editor.DomComponents.getComponents(); + this.modal = editor.Modal || null; + this.cm = editor.CodeManager || null; + this.cssc = editor.CssComposer || null; + this.protCss = editor.Config.protectedCss; + this.pfx = editor.Config.stylePrefix || ''; + this.enable(); + }, - /** - * Build editor - * @param {String} codeName - * @param {String} theme - * @param {String} label - * - * @return {Object} Editor - * @private - * */ - buildEditor: function(codeName, theme, label) { - if(!this.codeMirror) - this.codeMirror = this.cm.getViewer('CodeMirror'); + /** + * Build editor + * @param {String} codeName + * @param {String} theme + * @param {String} label + * + * @return {Object} Editor + * @private + * */ + buildEditor: function(codeName, theme, label) { + if(!this.codeMirror) + this.codeMirror = this.cm.getViewer('CodeMirror'); - var $input = $('