PageRenderTime 38ms CodeModel.GetById 12ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/js_composer/assets/js/params/css_editor.js

https://gitlab.com/oxidigitaluser/liguelista
JavaScript | 343 lines | 314 code | 3 blank | 26 comment | 89 complexity | 2602ff283393e44cfca13ccab11825f7 MD5 | raw file
  1. /* =========================================================
  2. * css_editor.js v1.0.1
  3. * =========================================================
  4. * Copyright 2014 Wpbakery
  5. *
  6. * Shortcodes css editor for edit form backbone/underscore version
  7. * ========================================================= */
  8. // Safety first
  9. /** global window.i18nLocale */
  10. if (_.isUndefined(window.vc)) var vc = {atts: {}};
  11. (function ($) {
  12. var preloaderUrl = ajaxurl.replace(/admin\-ajax\.php/, 'images/wpspin_light.gif'),
  13. template_options = {
  14. evaluate: /<#([\s\S]+?)#>/g,
  15. interpolate: /\{\{\{([\s\S]+?)\}\}\}/g,
  16. escape: /\{\{([^\}]+?)\}\}(?!\})/g
  17. },
  18. removeOldDesignOptions;
  19. wp.media.controller.VcCssSingleImage = wp.media.controller.VcSingleImage.extend({
  20. setCssEditor: function (view) {
  21. if (view) this._css_editor = view;
  22. return this;
  23. },
  24. updateSelection: function () {
  25. var selection = this.get('selection'),
  26. id = this._css_editor.getBackgroundImage(),
  27. attachment;
  28. if (id) {
  29. attachment = wp.media.model.Attachment.get(id);
  30. attachment.fetch();
  31. }
  32. selection.reset(attachment ? [attachment] : []);
  33. }
  34. });
  35. /**
  36. * Css editor view.
  37. * @type {*}
  38. */
  39. var VcCssEditor;
  40. VcCssEditor = vc.CssEditor = Backbone.View.extend({
  41. attrs: {},
  42. layouts: ['margin', 'border-width', 'padding'],
  43. positions: ['top', 'right', 'bottom', 'left'],
  44. $field: false,
  45. simplify: false,
  46. $simplify: false,
  47. events: {
  48. 'click .icon-remove': 'removeImage',
  49. 'click .vc_add-image': 'addBackgroundImage',
  50. 'change .vc_simplify': 'changeSimplify'
  51. },
  52. initialize: function () {
  53. // _.bindAll(wp.media.vc_css_editor, 'open');
  54. _.bindAll(this, 'setSimplify')
  55. },
  56. render: function (value) {
  57. this.attrs = {};
  58. this.$simplify = this.$el.find('.vc_simplify');
  59. _.isString(value) && this.parse(value);
  60. // wp.media.vc_css_editor.init(this);
  61. return this;
  62. },
  63. parse: function (value) {
  64. var data_split = value.split(/\s*(\.[^\{]+)\s*\{\s*([^\}]+)\s*\}\s*/g);
  65. data_split[2] && this.parseAtts(data_split[2].replace(/\s+!important/g, ''));
  66. },
  67. addBackgroundImage: function (e) {
  68. e.preventDefault();
  69. if (this.image_media)
  70. return this.image_media.open('vc_editor');
  71. this.image_media = wp.media({
  72. state: 'vc_single-image',
  73. states: [new wp.media.controller.VcCssSingleImage().setCssEditor(this)]
  74. });
  75. this.image_media.on('toolbar:create:vc_single-image', function (toolbar) {
  76. this.createSelectToolbar(toolbar, {
  77. text: window.i18nLocale.set_image
  78. });
  79. }, this.image_media);
  80. this.image_media.state('vc_single-image').on('select', this.setBgImage);
  81. this.image_media.open('vc_editor');
  82. },
  83. setBgImage: function () {
  84. var selection = this.get('selection').single();
  85. selection && this._css_editor.$el.find('.vc_background-image .vc_image').html(_.template($('#vc_css-editor-image-block').html(), selection.attributes, _.extend({variable: 'img'}, template_options)));
  86. },
  87. setCurrentBgImage: function (value) {
  88. var image_regexp = /([^\?]+)(\?id=\d+){0,1}/, url = '', id = '', image_split;
  89. if (value.match(/^\d+$/)) {
  90. this.$el.find('.vc_background-image .vc_image').html(_.template($('#vc_css-editor-image-block').html(), {
  91. url: preloaderUrl,
  92. id: value,
  93. css_class: 'vc_preview'
  94. }, _.extend({variable: 'img'}, template_options)));
  95. $.ajax({
  96. type: 'POST',
  97. url: window.ajaxurl,
  98. data: {
  99. action: 'wpb_single_image_src',
  100. content: value,
  101. size: 'full'
  102. },
  103. dataType: 'html',
  104. context: this
  105. }).done(function (url) {
  106. this.$el.find('.vc_ce-image').attr('src', url + '?id=' + value).removeClass('vc_preview');
  107. });
  108. } else if (value.match(image_regexp)) {
  109. image_split = value.split(image_regexp);
  110. url = image_split[1];
  111. if (image_split[2]) id = image_split[2].replace(/[^\d]+/, '');
  112. this.$el.find('.vc_background-image .vc_image').html(_.template($('#vc_css-editor-image-block').html(), {
  113. url: url,
  114. id: id
  115. }, _.extend({variable: 'img'}, template_options)));
  116. }
  117. },
  118. changeSimplify: function () {
  119. var f = _.debounce(this.setSimplify, 100);
  120. f && f();
  121. },
  122. setSimplify: function () {
  123. this.simplifiedMode(this.$simplify.is(':checked'));
  124. },
  125. simplifiedMode: function (enable) {
  126. if (enable) {
  127. this.simplify = true;
  128. this.$el.addClass('vc_simplified');
  129. } else {
  130. this.simplify = false;
  131. this.$el.removeClass('vc_simplified');
  132. _.each(this.layouts, function (attr) {
  133. if (attr === 'border-width') attr = 'border';
  134. var $control = $('[data-attribute=' + attr + '].vc_top');
  135. this.$el.find('[data-attribute=' + attr + ']:not(.vc_top)').val($control.val());
  136. }, this);
  137. }
  138. },
  139. removeImage: function (e) {
  140. var $control = $(e.currentTarget);
  141. e.preventDefault();
  142. $control.parent().remove();
  143. },
  144. getBackgroundImage: function () {
  145. return this.$el.find('.vc_ce-image').data('imageId');
  146. },
  147. parseAtts: function (string) {
  148. var border_regex, background_regex, background_size;
  149. border_regex = /(\d+\S*)\s+(\w+)\s+([\d\w#\(,]+)/;
  150. background_regex = /^([^\s]+)\s+url\(([^\)]+)\)([\d\w]+\s+[\d\w]+)?$/;
  151. background_size = false;
  152. _.map(string.split(';'), function (val) {
  153. var val_s = val.split(/:\s/), val_pos, border_split, background_split,
  154. value = val_s[1] || '',
  155. name = val_s[0] || '';
  156. if (value) value = value.trim();
  157. if (name.match(new RegExp('^(' + this.layouts.join('|').replace('-', '\\-') + ')$')) && value) {
  158. val_pos = value.split(/\s+/g);
  159. if (val_pos.length == 1) {
  160. val_pos = [val_pos[0], val_pos[0], val_pos[0], val_pos[0]];
  161. } else if (val_pos.length === 2) {
  162. val_pos[2] = val_pos[0];
  163. val_pos[3] = val_pos[1];
  164. } else if (val_pos.length === 3) {
  165. val_pos[3] = val_pos[1];
  166. }
  167. _.each(this.positions, function (pos, key) {
  168. this.$el.find('[data-name=' + name + '-' + pos + ']').val(val_pos[key]);
  169. }, this);
  170. } else if (name === 'background-size') {
  171. background_size = value;
  172. this.$el.find('[name=background_style]').val(value);
  173. } else if (name === 'background-repeat' && !background_size) {
  174. this.$el.find('[name=background_style]').val(value);
  175. } else if (name === 'background-image') {
  176. this.setCurrentBgImage(value.replace(/url\(([^\)]+)\)/, '$1'));
  177. } else if (name === 'background' && value) {
  178. background_split = value.split(background_regex);
  179. background_split[1] && this.$el.find('[name=' + name + '_color]').val(background_split[1]);
  180. background_split[2] && this.setCurrentBgImage(background_split[2]);
  181. } else if (name == 'border' && value && value.match(border_regex)) {
  182. border_split = value.split(border_regex);
  183. val_pos = [border_split[1], border_split[1], border_split[1], border_split[1]];
  184. _.each(this.positions, function (pos, key) {
  185. this.$el.find('[name=' + name + '_' + pos + '_width]').val(val_pos[key]);
  186. }, this);
  187. this.$el.find('[name=border_style]').val(border_split[2]);
  188. this.$el.find('[name=border_color]').val(border_split[3]).trigger('change');
  189. } else if (name.indexOf('border') != -1 && value) {
  190. if (name.indexOf('style') != -1) {
  191. this.$el.find('[name=border_style]').val(value);
  192. } else if (name.indexOf('color') != -1) {
  193. this.$el.find('[name=border_color]').val(value).trigger('change');
  194. } else if (name.match(/^[\w\-\d]+$/)) {
  195. this.$el.find('[name=' + name.replace(/\-+/g, '_') + ']').val(value);
  196. }
  197. } else if (name.match(/^[\w\-\d]+$/) && value) {
  198. this.$el.find('[name=' + name.replace(/\-+/g, '_') + ']').val(value);
  199. }
  200. }, this);
  201. },
  202. save: function () {
  203. var string = '';
  204. this.attrs = {};
  205. _.each(this.layouts, function (type) {
  206. this.getFields(type)
  207. }, this);
  208. this.getBackground();
  209. this.getBorder();
  210. if (!_.isEmpty(this.attrs)) {
  211. string = '.vc_custom_' + (+new Date) + '{' + _.reduce(this.attrs, function (memo, value, key) {
  212. return value ? memo + key + ': ' + value + ' !important;' : memo;
  213. }, '', this) + '}';
  214. }
  215. string && vc.frame_window && vc.frame_window.vc_iframe.setCustomShortcodeCss(string);
  216. return string;
  217. },
  218. getBackgroundImageSrc: function () {
  219. return this.$el.find('.vc_background-image img').attr('src');
  220. },
  221. getBackgroundColor: function () {
  222. return this.$el.find('[name=background_color]').val();
  223. },
  224. getBackgroundStyle: function () {
  225. return this.$el.find('[name=background_style]').val();
  226. },
  227. getBackground: function () {
  228. var color = this.getBackgroundColor(),
  229. image = this.getBackgroundImageSrc(),
  230. style = this.getBackgroundStyle();
  231. if (color && image) {
  232. this.attrs['background'] = color + ' ' + 'url(' + image + ')';
  233. } else if (color) {
  234. this.attrs['background-color'] = color;
  235. } else if (image) {
  236. this.attrs['background-image'] = 'url(' + image + ')';
  237. }
  238. if (style.match(/repeat/)) {
  239. this.attrs['background-position'] = '0 0';
  240. this.attrs['background-repeat'] = style;
  241. } else if (style.match(/cover|contain/)) {
  242. this.attrs['background-position'] = 'center';
  243. this.attrs['background-repeat'] = 'no-repeat';
  244. this.attrs['background-size'] = style;
  245. }
  246. if (color.match(/^rgba/)) {
  247. this.attrs['*background-color'] = color.replace(/\s+/, '').replace(/(rgb)a\((\d+)\,(\d+),(\d+),[^\)]+\)/, '$1($2,$3,$4)');
  248. }
  249. },
  250. getBorder: function () {
  251. var style = this.$el.find('[name=border_style]').val(),
  252. color = this.$el.find('[name=border_color]').val();
  253. var sides = ['left', 'right', 'top', 'bottom'];
  254. if (style && color && this.attrs['border-width'] && this.attrs['border-width'].match(/^\d+\S+$/)) {
  255. this.attrs.border = this.attrs['border-width'] + ' ' + style + ' ' + color;
  256. this.attrs['border-width'] = undefined;
  257. } else {
  258. _.each(sides, function (side) {
  259. if (this.attrs['border-' + side + '-width']) {
  260. if (color) this.attrs['border-' + side + '-color'] = color;
  261. if (style) this.attrs['border-' + side + '-style'] = style;
  262. }
  263. }, this);
  264. }
  265. },
  266. getFields: function (type) {
  267. var data = [];
  268. if (this.simplify) return this.getSimplifiedField(type);
  269. _.each(this.positions, function (pos) {
  270. var val = this.$el.find('[data-name=' + type + '-' + pos + ']').val().replace(/\s+/, '');
  271. if (!val.match(/^\d*(\.\d?){0,1}(%|in|cm|mm|em|rem|ex|pt|pc|px|vw|vh|vmin|vmax)$/)) {
  272. val = (isNaN(parseFloat(val)) ? '' : '' + parseFloat(val) + 'px');
  273. }
  274. val.length && data.push({name: pos, val: val});
  275. }, this);
  276. _.each(data, function (attr) {
  277. var attr_name = type == 'border-width' ? 'border-' + attr.name + '-width' : type + '-' + attr.name;
  278. this.attrs[attr_name] = attr.val;
  279. }, this);
  280. },
  281. getSimplifiedField: function (type) {
  282. var pos = 'top',
  283. val = this.$el.find('[data-name=' + type + '-' + pos + ']').val().replace(/\s+/, '');
  284. if (!val.match(/^-?\d*(\.\d?){0,1}(%|in|cm|mm|em|rem|ex|pt|pc|px|vw|vh|vmin|vmax)$/)) {
  285. val = (isNaN(parseFloat(val)) ? '' : '' + parseFloat(val) + 'px');
  286. }
  287. if (val.length) this.attrs[type] = val;
  288. }
  289. });
  290. /**
  291. * Add new param to atts types list for vc
  292. * @type {Object}
  293. */
  294. vc.atts.css_editor = {
  295. parse: function (param) {
  296. var $field, css_editor, result;
  297. $field = this.content().find('input.wpb_vc_param_value[name="' + param.param_name + '"]' );
  298. css_editor = $field.data('vcFieldManager');
  299. result = css_editor.save();
  300. if (result) vc.edit_form_callbacks.push(removeOldDesignOptions);
  301. return result;
  302. },
  303. init: function (param, $field) {
  304. /**
  305. * Find all fields with css_editor type and initialize.
  306. */
  307. $('[data-css-editor=true]', this.content()).each(function () {
  308. var $editor = $(this),
  309. $param = $editor.find('input.wpb_vc_param_value[name="' + param.param_name +'"]' ),
  310. value = $param.val();
  311. if (!value) value = parseOldDesignOptions();
  312. $param.data('vcFieldManager', new VcCssEditor({el: $editor}).render(value));
  313. });
  314. vc.atts.colorpicker.init.call(this, param, $field);
  315. }
  316. };
  317. /**
  318. * Backward capability for old css attributes
  319. * @return {String} - Css settings with class name and css attributes settings.
  320. */
  321. var parseOldDesignOptions = function () {
  322. var keys = {
  323. 'bg_color': 'background-color',
  324. 'padding': 'padding',
  325. 'margin_bottom': 'margin-bottom',
  326. 'bg_image': 'background-image'
  327. },
  328. params = vc.edit_element_block_view.model.get('params'),
  329. cssString = _.reduce(keys, function (memo, css_name, attr_name) {
  330. var value = params[attr_name];
  331. if (_.isUndefined(value) || !value.length) return memo;
  332. if (attr_name === 'bg_image') value = 'url(' + value + ')';
  333. return memo + css_name + ': ' + value + ';';
  334. }, '', this);
  335. return cssString ? '.tmp_class{' + cssString + '}' : '';
  336. };
  337. removeOldDesignOptions = function () {
  338. this.params = _.omit(this.params, 'bg_color', 'padding', 'margin_bottom', 'bg_image');
  339. };
  340. })(window.jQuery);