diff options
| author | qsm-odoo <qsm@odoo.com> | 2018-11-05 17:35:09 +0000 |
|---|---|---|
| committer | qsm-odoo <qsm@odoo.com> | 2018-11-28 10:28:53 +0000 |
| commit | 6d67ce5b7cc6f8686a142ca3a834f5bfd98a56d1 (patch) | |
| tree | dde5d7d0b17e4d43e9f063474ab09019ba484a2f /addons/website_links/static | |
| parent | c64c646d62a658c94f2d81eea9a2797a4ce024ea (diff) | |
[REF] website_*: review reorganization and enforce conventions
Review the JS reorganization made by direct parent commits and do more
to use our defined JS conventions. Also simplify JS which can be
obviously improved.
Diffstat (limited to 'addons/website_links/static')
5 files changed, 519 insertions, 491 deletions
diff --git a/addons/website_links/static/src/js/website_links.js b/addons/website_links/static/src/js/website_links.js index e51926dbccc..afe64642f47 100644 --- a/addons/website_links/static/src/js/website_links.js +++ b/addons/website_links/static/src/js/website_links.js @@ -1,52 +1,62 @@ odoo.define('website_links.website_links', function (require) { 'use strict'; -var sAnimations = require('website.content.snippets.animation'); -var ajax = require('web.ajax'); var core = require('web.core'); var Widget = require('web.Widget'); +var sAnimations = require('website.content.snippets.animation'); + var _t = core._t; -var exports = {}; var SelectBox = Widget.extend({ xmlDependencies: ['/website_links/static/src/xml/recent_link.xml'], + events: { + 'change': '_onChange', + }, + /** - * @override + * @constructor + * @param {Object} parent * @param {Object} obj + * @param {String} placeholder */ - init: function (obj) { + init: function (parent, obj, placeholder) { + this._super.apply(this, arguments); this.obj = obj; + this.placeholder = placeholder; }, /** * @override - * @param {Object} parent - * @param {Object} element - * @param {String} placeholder */ - start: function (element, placeholder, parent) { + willStart: function () { var self = this; - this.element = element; - this.placeholder = placeholder; - - this._fetchObjects().then(function (results) { - self.objects = results; - - element.select2({ - placeholder: self.placeholder, - allowClear: true, - createSearchChoice: function (term) { - if (self._objectExists(term)) { return null; } - - return {id:term, text:_.str.sprintf("Create '%s'", term)}; - }, - createSearchChoicePosition: 'bottom', - multiple: false, - data: self.objects, - }); - - element.on('change', function (e) { - self._onChange(e); + var defs = [this._super.apply(this, arguments)]; + defs.push(this._rpc({ + model: this.obj, + method: 'search_read', + }).then(function (result) { + self.objects = _.map(result, function (val) { + return {id: val.id, text: val.name}; }); + })); + return $.when.apply($, defs); + }, + /** + * @override + */ + start: function () { + var self = this; + this.$el.select2({ + placeholder: self.placeholder, + allowClear: true, + createSearchChoice: function (term) { + if (self._objectExists(term)) { + return null; + } + return {id: term, text: _.str.sprintf("Create '%s'", term)}; + }, + createSearchChoicePosition: 'bottom', + multiple: false, + data: self.objects, }); }, @@ -56,20 +66,6 @@ var SelectBox = Widget.extend({ /** * @private - */ - _fetchObjects: function () { - return this._rpc({ - model: this.obj, - method: 'search_read', - }) - .then(function (result) { - return _.map(result, function (val) { - return {id: val.id, text:val.name}; - }); - }); - }, - /** - * @private * @param {String} query */ _objectExists: function (query) { @@ -84,14 +80,13 @@ var SelectBox = Widget.extend({ _createObject: function (name) { var self = this; return this._rpc({ - model: this.obj, - method: 'create', - args: [{name:name}], - }) - .then(function (record) { - self.element.attr('value', record); - self.objects.push({'id': record, 'text': name}); - }); + model: this.obj, + method: 'create', + args: [{name: name}], + }).then(function (record) { + self.$el.attr('value', record); + self.objects.push({'id': record, 'text': name}); + }); }, //-------------------------------------------------------------------------- @@ -99,53 +94,41 @@ var SelectBox = Widget.extend({ //-------------------------------------------------------------------------- /** - * @override - * @param {Object} e + * @private + * @param {Object} ev */ - _onChange: function (e) { - if (e.added && _.isString(e.added.id)) { - this._createObject(e.added.id); + _onChange: function (ev) { + if (!ev.added || !_.isString(ev.added.id)) { + return; } + this._createObject(ev.added.id); }, - }); var RecentLinkBox = Widget.extend({ template: 'website_links.RecentLink', events: { - 'click .btn_shorten_url_clipboard':'_toggleCopyButton', - 'click .o_website_links_edit_code':'_editCode', - 'click .o_website_links_ok_edit':function (e) { - e.preventDefault(); - this._submitCode(); - }, - 'click .o_website_links_cancel_edit': function (e) { - e.preventDefault(); - this._cancelEdit(); - }, - 'submit #o_website_links_edit_code_form': function (e) { - e.preventDefault(); - this._submitCode(); - }, + 'click .btn_shorten_url_clipboard': '_toggleCopyButton', + 'click .o_website_links_edit_code': '_editCode', + 'click .o_website_links_ok_edit': '_onLinksOkClick', + 'click .o_website_links_cancel_edit': '_onLinksCancelClick', + 'submit #o_website_links_edit_code_form': '_onSubmitCode', }, /** - * @override + * @constructor + * @param {Object} parent * @param {Object} obj */ - init: function (parent, link_obj) { - this._super(parent); - this.link_obj = link_obj; + init: function (parent, obj) { + this._super.apply(this, arguments); + this.link_obj = obj; this.animating_copy = false; }, - /** * @override - * @param {Object} parent - * @param {Object} element - * @param {String} placeholder */ - start: function (element, placeholder, parent) { + start: function () { new ClipboardJS(this.$('.btn_shorten_url_clipboard').get(0)); return this._super.apply(this, arguments); }, @@ -156,36 +139,30 @@ var RecentLinkBox = Widget.extend({ /** * @private - * @param {String} query */ _toggleCopyButton: function () { - var self = this; - - if (!this.animating_copy) { - this.animating_copy = true; - var top = this.$('.o_website_links_short_url').position().top; - this.$('.o_website_links_short_url').clone() - .css('position', 'absolute') - .css('left', 15) - .css('top', top-2) - .css('z-index', 2) - .removeClass('o_website_links_short_url') - .addClass('animated-link') - .insertAfter(this.$('.o_website_links_short_url')) - .animate({ - opacity: 0, - top: "-=20", - }, 500, function () { - self.$('.animated-link').remove(); - self.animating_copy = false; - }); + if (this.animating_copy) { + return; } - }, - /** - * @private - */ - _remove: function () { - this.getParent().remove_link(this); + + var self = this; + this.animating_copy = true; + var top = this.$('.o_website_links_short_url').position().top; + this.$('.o_website_links_short_url').clone() + .css('position', 'absolute') + .css('left', 15) + .css('top', top - 2) + .css('z-index', 2) + .removeClass('o_website_links_short_url') + .addClass('animated-link') + .insertAfter(this.$('.o_website_links_short_url')) + .animate({ + opacity: 0, + top: '-=20', + }, 500, function () { + self.$('.animated-link').remove(); + self.animating_copy = false; + }); }, /** * @private @@ -198,8 +175,8 @@ var RecentLinkBox = Widget.extend({ * @private */ _editCode: function () { - var init_code = this.$('#o_website_links_code').html(); - this.$('#o_website_links_code').html("<form style='display:inline;' id='o_website_links_edit_code_form'><input type='hidden' id='init_code' value='" + init_code + "'/><input type='text' id='new_code' value='" + init_code + "'/></form>"); + var initCode = this.$('#o_website_links_code').html(); + this.$('#o_website_links_code').html('<form style="display:inline;" id="o_website_links_edit_code_form"><input type="hidden" id="init_code" value="' + initCode + '"/><input type="text" id="new_code" value="' + initCode + '"/></form>'); this.$('.o_website_links_edit_code').hide(); this.$('.copy-to-clipboard').hide(); this.$('.o_website_links_edit_tools').show(); @@ -213,8 +190,8 @@ var RecentLinkBox = Widget.extend({ this.$('.o_website_links_edit_tools').hide(); this.$('.o_website_links_code_error').hide(); - var old_code = this.$('#o_website_links_edit_code_form #init_code').val(); - this.$('#o_website_links_code').html(old_code); + var oldCode = this.$('#o_website_links_edit_code_form #init_code').val(); + this.$('#o_website_links_code').html(oldCode); this.$('#code-error').remove(); this.$('#o_website_links_code form').remove(); @@ -225,16 +202,16 @@ var RecentLinkBox = Widget.extend({ _submitCode: function () { var self = this; - var init_code = this.$('#o_website_links_edit_code_form #init_code').val(); - var new_code = this.$('#o_website_links_edit_code_form #new_code').val(); + var initCode = this.$('#o_website_links_edit_code_form #init_code').val(); + var newCode = this.$('#o_website_links_edit_code_form #new_code').val(); - if (new_code === '') { - self.$('.o_website_links_code_error').html("The code cannot be left empty"); + if (newCode === '') { + self.$('.o_website_links_code_error').html(_t("The code cannot be left empty")); self.$('.o_website_links_code_error').show(); return; } - function ShowNewCode(new_code) { + function showNewCode(newCode) { self.$('.o_website_links_code_error').html(''); self.$('.o_website_links_code_error').hide(); @@ -242,10 +219,10 @@ var RecentLinkBox = Widget.extend({ // Show new code var host = self.$('#o_website_links_host').html(); - self.$('#o_website_links_code').html(new_code); + self.$('#o_website_links_code').html(newCode); // Update button copy to clipboard - self.$('.btn_shorten_url_clipboard').attr('data-clipboard-text', host + new_code); + self.$('.btn_shorten_url_clipboard').attr('data-clipboard-text', host + newCode); // Show action again self.$('.o_website_links_edit_code').show(); @@ -253,30 +230,55 @@ var RecentLinkBox = Widget.extend({ self.$('.o_website_links_edit_tools').hide(); } - if (init_code === new_code) { - ShowNewCode(new_code); - } - else { - ajax.jsonRpc('/website_links/add_code', 'call', {'init_code':init_code, 'new_code':new_code}) - .then(function (result) { - ShowNewCode(result[0].code); - }) - .fail(function () { - self.$('.o_website_links_code_error').show(); - self.$('.o_website_links_code_error').html("This code is already taken"); - }) ; + if (initCode === newCode) { + showNewCode(newCode); + } else { + this._rpc({ + route: '/website_links/add_code', + params: { + init_code: initCode, + new_code: newCode, + }, + }).then(function (result) { + showNewCode(result[0].code); + }, function () { + self.$('.o_website_links_code_error').show(); + self.$('.o_website_links_code_error').html(_t("This code is already taken")); + }); } }, -}); + //-------------------------------------------------------------------------- + // Handlers + //-------------------------------------------------------------------------- -var RecentLinks = Widget.extend({ /** - * @override + * @private + * @param {Event} ev */ - init: function () { - this._super(); + _onLinksOkClick: function (ev) { + ev.preventDefault(); + this._submitCode(); + }, + /** + * @private + * @param {Event} ev + */ + _onLinksCancelClick: function (ev) { + ev.preventDefault(); + this._cancelEdit(); + }, + /** + * @private + * @param {Event} ev + */ + _onSubmitCode: function (ev) { + ev.preventDefault(); + this._submitCode(); }, +}); + +var RecentLinks = Widget.extend({ //-------------------------------------------------------------------------- // Private @@ -285,47 +287,42 @@ var RecentLinks = Widget.extend({ /** * @private */ - _getRecentLinks: function (filter) { + getRecentLinks: function (filter) { var self = this; - ajax.jsonRpc('/website_links/recent_links', 'call', {'filter':filter, 'limit':20}) - .then(function (result) { - _.each(result.reverse(), function (link) { - self._addLink(link); - }); - - self._updateNotification(); - }) - .fail(function () { - var message = _t("Unable to get recent links"); - self.$el.append("<div class='alert alert-danger'>" + message + "</div>"); + return this._rpc({ + route: '/website_links/recent_links', + params: { + filter: filter, + limit: 20, + }, + }).then(function (result) { + _.each(result.reverse(), function (link) { + self._addLink(link); }); + self._updateNotification(); + }, function () { + var message = _t("Unable to get recent links"); + self.$el.append('<div class="alert alert-danger">' + message + '</div>'); + }); }, /** * @private */ _addLink: function (link) { - var nb_links = this.getChildren().length; - var recent_link_box = new RecentLinkBox(this, link); - recent_link_box.prependTo(this.$el); + var nbLinks = this.getChildren().length; + var recentLinkBox = new RecentLinkBox(this, link); + recentLinkBox.prependTo(this.$el); $('.link-tooltip').tooltip(); - if (nb_links === 0) { + if (nbLinks === 0) { this._updateNotification(); } }, /** * @private */ - _removeLinks: function () { - $('#o_website_links_recent_links .link-row').each(function () { - this.remove(); - }); - }, - /** - * @private - */ - _removeLink: function (link) { - link.destroy(); + removeLinks: function () { + _.invoke(this.getChildren(), 'destroy'); }, /** * @private @@ -333,55 +330,54 @@ var RecentLinks = Widget.extend({ _updateNotification: function () { if (this.getChildren().length === 0) { var message = _t("You don't have any recent links."); - $('.o_website_links_recent_links_notification').html("<div class='alert alert-info'>" + message + "</div>"); - } - else { + $('.o_website_links_recent_links_notification').html('<div class="alert alert-info">' + message + '</div>'); + } else { $('.o_website_links_recent_links_notification').empty(); } }, - }); sAnimations.registry.websiteLinks = sAnimations.Class.extend({ selector: '.o_website_links_create_tracked_url', read_events: { - 'click #filter-newest-links': '_onFilterNewestLinks', - 'click #filter-most-clicked-links': '_onFilterMostClickedLinks', - 'click #filter-recently-used-links': '_onFilterRecentlyUsedLinks', - 'click #generated_tracked_link a': '_onGeneratedTrackedLink', + 'click #filter-newest-links': '_onFilterNewestLinksClick', + 'click #filter-most-clicked-links': '_onFilterMostClickedLinksClick', + 'click #filter-recently-used-links': '_onFilterRecentlyUsedLinksClick', + 'click #generated_tracked_link a': '_onGeneratedTrackedLinkClick', 'keyup #url': '_onUrlKeyUp', - 'click #btn_shorten_url': '_onBtnShortenUrl', - 'submit #o_website_links_link_tracker_form': '_onSubmitForm' + 'click #btn_shorten_url': '_onShortenUrlButtonClick', + 'submit #o_website_links_link_tracker_form': '_onFormSubmit', }, /** * @override - * @param {Object} parent */ - start: function (parent) { + start: function () { + var defs = [this._super.apply(this, arguments)]; + // UTMS selects widgets - var campaign_select = new SelectBox('utm.campaign'); - campaign_select.start($("#campaign-select"), _t('e.g. Promotion of June, Winter Newsletter, ..')); + var campaignSelect = new SelectBox(this, 'utm.campaign', _t("e.g. Promotion of June, Winter Newsletter, ..")); + defs.push(campaignSelect.attachTo($('#campaign-select'))); - var medium_select = new SelectBox('utm.medium'); - medium_select.start($("#channel-select"), _t('e.g. Newsletter, Social Network, ..')); + var mediumSelect = new SelectBox(this, 'utm.medium', _t("e.g. Newsletter, Social Network, ..")); + defs.push(mediumSelect.attachTo($('#channel-select'))); - var source_select = new SelectBox('utm.source'); - source_select.start($("#source-select"), _t('e.g. Search Engine, Website page, ..')); + var sourceSelect = new SelectBox(this, 'utm.source', _t("e.g. Search Engine, Website page, ..")); + defs.push(sourceSelect.attachTo($('#source-select'))); // Recent Links Widgets - this.recent_links = new RecentLinks(); - this.recent_links.appendTo($("#o_website_links_recent_links")); - this.recent_links._getRecentLinks('newest'); + this.recentLinks = new RecentLinks(); + defs.push(this.recentLinks.appendTo($('#o_website_links_recent_links'))); + this.recentLinks.getRecentLinks('newest'); // Clipboard Library - new ClipboardJS($("#btn_shorten_url").get(0)); + new ClipboardJS($('#btn_shorten_url').get(0)); this.url_copy_animating = false; - $(function () { - $('[data-toggle="tooltip"]').tooltip(); - }); + $('[data-toggle="tooltip"]').tooltip(); + + return $.when.apply($, defs); }, //-------------------------------------------------------------------------- @@ -389,143 +385,148 @@ sAnimations.registry.websiteLinks = sAnimations.Class.extend({ //-------------------------------------------------------------------------- /** - * @override + * @private */ - _onFilterNewestLinks: function () { - this.recent_links._removeLinks(); - this.recent_links._getRecentLinks('newest'); + _onFilterNewestLinksClick: function () { + this.recentLinks.removeLinks(); + this.recentLinks.getRecentLinks('newest'); }, /** - * @override + * @private */ - _onFilterMostClickedLinks: function () { - this.recent_links._removeLinks(); - this.recent_links._getRecentLinks('most-clicked'); + _onFilterMostClickedLinksClick: function () { + this.recentLinks.removeLinks(); + this.recentLinks.getRecentLinks('most-clicked'); }, /** - * @override + * @private */ - _onFilterRecentlyUsedLinks: function () { - this.recent_links._removeLinks(); - this.recent_links._getRecentLinks('recently-used'); + _onFilterRecentlyUsedLinksClick: function () { + this.recentLinks.removeLinks(); + this.recentLinks.getRecentLinks('recently-used'); }, /** - * @override + * @private */ - _onGeneratedTrackedLink: function () { - $("#generated_tracked_link a").text("Copied").removeClass("btn-primary").addClass("btn-success"); + _onGeneratedTrackedLinkClick: function () { + $('#generated_tracked_link a').text(_t("Copied")).removeClass('btn-primary').addClass('btn-success'); setTimeout(function () { - $("#generated_tracked_link a").text("Copy").removeClass("btn-success").addClass("btn-primary"); - }, '5000'); + $('#generated_tracked_link a').text(_t("Copy")).removeClass('btn-success').addClass('btn-primary'); + }, 5000); }, /** - * @override - * @param {Object} e + * @private + * @param {Event} ev */ - _onUrlKeyUp: function (e) { - if ($('#btn_shorten_url').hasClass('btn-copy') && e.which !== 13) { - $('#btn_shorten_url').removeClass('btn-success btn-copy').addClass('btn-primary').html('Get tracked link'); - $('#generated_tracked_link').css('display', 'none'); - $('.o_website_links_utm_forms').show(); + _onUrlKeyUp: function (ev) { + if (!$('#btn_shorten_url').hasClass('btn-copy') || ev.which === 13) { + return; } + + $('#btn_shorten_url').removeClass('btn-success btn-copy').addClass('btn-primary').html('Get tracked link'); + $('#generated_tracked_link').css('display', 'none'); + $('.o_website_links_utm_forms').show(); }, /** - * @override + * @private */ - _onBtnShortenUrl: function () { - if ($('#btn_shorten_url').hasClass('btn-copy')) { - if (!this.url_copy_animating) { - this.url_copy_animating = true; - - $('#generated_tracked_link').clone() - .css('position', 'absolute') - .css('left', '78px') - .css('bottom', '8px') - .css('z-index', 2) - .removeClass('#generated_tracked_link') - .addClass('url-animated-link') - .appendTo($('#generated_tracked_link')) - .animate({ - opacity: 0, - bottom: "+=20", - }, 500, function () { - $('.url-animated-link').remove(); - this.url_copy_animating = false; - }); - } + _onShortenUrlButtonClick: function () { + if (!$('#btn_shorten_url').hasClass('btn-copy') || this.url_copy_animating) { + return; } + + var self = this; + this.url_copy_animating = true; + $('#generated_tracked_link').clone() + .css('position', 'absolute') + .css('left', '78px') + .css('bottom', '8px') + .css('z-index', 2) + .removeClass('#generated_tracked_link') + .addClass('url-animated-link') + .appendTo($('#generated_tracked_link')) + .animate({ + opacity: 0, + bottom: '+=20', + }, 500, function () { + $('.url-animated-link').remove(); + self.url_copy_animating = false; + }); }, /** * Add the RecentLinkBox widget and send the form when the user generate the link * - * @override - * @param {Object} ev + * @private + * @param {Event} ev */ - _onSubmitForm: function (ev) { + _onFormSubmit: function (ev) { + ev.preventDefault(); + if ($('#btn_shorten_url').hasClass('btn-copy')) { - ev.preventDefault(); return; } - ev.preventDefault(); ev.stopPropagation(); // Get URL and UTMs - var campaign_id = $('#campaign-select').attr('value'); - var medium_id = $('#channel-select').attr('value'); - var source_id = $('#source-select').attr('value'); + var campaignID = $('#campaign-select').attr('value'); + var mediumID = $('#channel-select').attr('value'); + var sourceID = $('#source-select').attr('value'); var params = {}; - params.url = $("#url").val(); - if (campaign_id !== '') { params.campaign_id = parseInt(campaign_id); } - if (medium_id !== '') { params.medium_id = parseInt(medium_id); } - if (source_id !== '') { params.source_id = parseInt(source_id); } - - $('#btn_shorten_url').text(_t('Generating link...')); - - ajax.jsonRpc("/website_links/new", 'call', params) - .then(function (result) { - if ('error' in result) { - // Handle errors - if (result.error === 'empty_url') { - $('.notification').html("<div class='alert alert-danger'>The URL is empty.</div>"); - } - else if (result.error === 'url_not_found') { - $('.notification').html("<div class='alert alert-danger'>URL not found (404)</div>"); - } - else { - $('.notification').html("<div class='alert alert-danger'>An error occur while trying to generate your link. Try again later.</div>"); - } + params.url = $('#url').val(); + if (campaignID !== '') { + params.campaign_id = parseInt(campaignID); + } + if (mediumID !== '') { + params.medium_id = parseInt(mediumID); + } + if (sourceID !== '') { + params.source_id = parseInt(sourceID); + } + + $('#btn_shorten_url').text(_t("Generating link...")); + + this._rpc({ + route: '/website_links/new', + params: params, + }).then(function (result) { + if ('error' in result) { + // Handle errors + if (result.error === 'empty_url') { + $('.notification').html('<div class="alert alert-danger">The URL is empty.</div>'); + } else if (result.error === 'url_not_found') { + $('.notification').html('<div class="alert alert-danger">URL not found (404)</div>'); + } else { + $('.notification').html('<div class="alert alert-danger">An error occur while trying to generate your link. Try again later.</div>'); } - else { - // Link generated, clean the form and show the link - var link = result[0]; + } else { + // Link generated, clean the form and show the link + var link = result[0]; - $('#btn_shorten_url').removeClass('btn-primary').addClass('btn-success btn-copy').html('Copy'); - $('#btn_shorten_url').attr('data-clipboard-text', link.short_url); + $('#btn_shorten_url').removeClass('btn-primary').addClass('btn-success btn-copy').html('Copy'); + $('#btn_shorten_url').attr('data-clipboard-text', link.short_url); - $('.notification').html(''); - $('#generated_tracked_link').html(link.short_url); - $('#generated_tracked_link').css('display', 'inline'); + $('.notification').html(''); + $('#generated_tracked_link').html(link.short_url); + $('#generated_tracked_link').css('display', 'inline'); - this.recent_links._addLink(link); + this.recentLinks._addLink(link); - // Clean URL and UTM selects - $('#campaign-select').select2('val', ''); - $('#channel-select').select2('val', ''); - $('#source-select').select2('val', ''); + // Clean URL and UTM selects + $('#campaign-select').select2('val', ''); + $('#channel-select').select2('val', ''); + $('#source-select').select2('val', ''); - $('.o_website_links_utm_forms').hide(); - } - }); + $('.o_website_links_utm_forms').hide(); + } + }); }, - }); -exports.SelectBox = SelectBox; -exports.RecentLinkBox = RecentLinkBox; -exports.RecentLinks = RecentLinks; - -return exports; - +return { + SelectBox: SelectBox, + RecentLinkBox: RecentLinkBox, + RecentLinks: RecentLinks, +}; }); diff --git a/addons/website_links/static/src/js/website_links_charts.js b/addons/website_links/static/src/js/website_links_charts.js index 31e2d4971e9..08ea40f1bed 100644 --- a/addons/website_links/static/src/js/website_links_charts.js +++ b/addons/website_links/static/src/js/website_links_charts.js @@ -1,87 +1,100 @@ odoo.define('website_links.charts', function (require) { 'use strict'; -var sAnimations = require('website.content.snippets.animation'); -var Widget = require('web.Widget'); var core = require('web.core'); +var Widget = require('web.Widget'); +var sAnimations = require('website.content.snippets.animation'); + var _t = core._t; -var exports = {}; var BarChart = Widget.extend({ /** - * @override - * @param {Object} $element - * @param {Object} begin_date - * @param {Object} end_date + * @constructor + * @param {Object} parent + * @param {Object} beginDate + * @param {Object} endDate * @param {Object} dates */ - init: function ($element, begin_date, end_date, dates) { - this.$element = $element; - this.begin_date = begin_date; - this.end_date = end_date; - this.number_of_days = this.end_date.diff(this.begin_date, 'days') + 2; + init: function (parent, beginDate, endDate, dates) { + this._super.apply(this, arguments); + this.beginDate = beginDate; + this.endDate = endDate; + this.number_of_days = this.endDate.diff(this.beginDate, 'days') + 2; this.dates = dates; }, /** * @override - * @param {Object} parent */ - start: function (parent) { + start: function () { var self = this; // Accessor functions - function getDate(d) { return new Date(d[0]); } - function getNbClicks(d) { return d[1]; } + function getDate(d) { + return new Date(d[0]); + } + function getNbClicks(d) { + return d[1]; + } // Prune tick values for visibility purpose - function getPrunedTickValues(ticks, nb_desired_ticks) { - var nb_values = ticks.length; - var keep_one_of = Math.max(1, Math.floor(nb_values / nb_desired_ticks)); + function getPrunedTickValues(ticks, nbDesiredTicks) { + var nbValues = ticks.length; + var keepOneOf = Math.max(1, Math.floor(nbValues / nbDesiredTicks)); return _.filter(ticks, function (d, i) { - return i % keep_one_of === 0; + return i % keepOneOf === 0; }); } // Fill data for each day (with 0 click for days without data) - var clicks_array = []; - var begin_date_copy = this.begin_date; - for (var i = 0 ; i < this.number_of_days ; i++) { - var date_key = begin_date_copy.format('YYYY-MM-DD'); - clicks_array.push([date_key, (date_key in this.dates) ? this.dates[date_key] : 0]); - begin_date_copy.add(1, 'days'); + var clicksArray = []; + var beginDateCopy = this.beginDate; + for (var i = 0; i < this.number_of_days; i++) { + var dateKey = beginDateCopy.format('YYYY-MM-DD'); + clicksArray.push([dateKey, (dateKey in this.dates) ? this.dates[dateKey] : 0]); + beginDateCopy.add(1, 'days'); } // Set title - var nb_clicks = _.reduce(clicks_array, function (total, val) { return total + val[1] ; }, 0); - $(this.$element + ' .title').html(nb_clicks + _t(' clicks')); + var nbClicks = _.reduce(clicksArray, function (total, val) { + return total + val[1]; + }, 0); + this.$('.title').html(nbClicks + _t(' clicks')); // Fit data into the NVD3 scheme - var chart_data = [{}]; - chart_data[0]['key'] = _t('# of clicks'); - chart_data[0]['values'] = clicks_array; + var chartData = [{}]; + chartData[0]['key'] = _t('# of clicks'); + chartData[0]['values'] = clicksArray; nv.addGraph(function () { var chart = nv.models.lineChart() - .x(function (d) { return getDate(d); }) - .y(function (d) { return getNbClicks(d); }) + .x(function (d) { + return getDate(d); + }) + .y(function (d) { + return getNbClicks(d); + }) .showYAxis(true) .showXAxis(true); // Reduce the number of labels on the X axis for visibility - var tick_values = getPrunedTickValues(chart_data[0]['values'], 10); + var tickValues = getPrunedTickValues(chartData[0]['values'], 10); chart.xAxis - .tickFormat(function (d) { return d3.time.format("%d/%m/%y")(new Date(d)); }) - .tickValues(_.map(tick_values, function (d) { return getDate(d).getTime(); })) + .tickFormat(function (d) { + return d3.time.format('%d/%m/%y')(new Date(d)); + }) + .tickValues(_.map(tickValues, function (d) { + return getDate(d).getTime(); + })) .rotateLabels(55); chart.yAxis - .tickFormat(d3.format("d")) - .ticks(chart_data[0]['values'].length - 1); + .tickFormat(d3.format('d')) + .ticks(chartData[0]['values'].length - 1); - d3.select(self.$element + ' svg') - .datum(chart_data) + d3.select(self.$('svg')[0]) + .datum(chartData) .call(chart); return self.chart = chart; @@ -92,38 +105,41 @@ var BarChart = Widget.extend({ var PieChart = Widget.extend({ /** * @override - * @param {Object} $element + * @param {Object} parent * @param {Object} data */ - init: function ($element, data) { + init: function (parent, data) { + this._super.apply(this, arguments); this.data = data; - this.$element = $element; }, /** * @override - * @param {Object} parent */ - start: function (parent) { + start: function () { var self = this; // Process country data to fit into the NVD3 scheme - var processed_data = []; - for (var i = 0 ; i < this.data.length ; i++) { - var country_name = this.data[i]['country_id'] ? this.data[i]['country_id'][1] : _t('Undefined'); - processed_data.push({'label':country_name + ' (' + this.data[i]['country_id_count'] + ')', 'value':this.data[i]['country_id_count']}); + var processedData = []; + for (var i = 0; i < this.data.length; i++) { + var countryName = this.data[i]['country_id'] ? this.data[i]['country_id'][1] : _t('Undefined'); + processedData.push({'label': countryName + ' (' + this.data[i]['country_id_count'] + ')', 'value': this.data[i]['country_id_count']}); } // Set title - $(this.$element + ' .title').html(this.data.length + _t(' countries')); + this.$('.title').html(this.data.length + _t(' countries')); nv.addGraph(function () { var chart = nv.models.pieChart() - .x(function (d) { return d.label; }) - .y(function (d) { return d.value; }) + .x(function (d) { + return d.label; + }) + .y(function (d) { + return d.value; + }) .showLabels(false); - d3.select(self.$element + ' svg') - .datum(processed_data) + d3.select(self.$('svg')[0]) + .datum(processedData) .transition().duration(1200) .call(chart); @@ -135,78 +151,83 @@ var PieChart = Widget.extend({ sAnimations.registry.websiteLinksCharts = sAnimations.Class.extend({ selector: '.o_website_links_chart', read_events: { - 'click .graph-tabs li a': '_onResizeChart', - 'click .copy-to-clipboard': '_onCopyToClipboard' + 'click .graph-tabs li a': '_onGraphTabClick', + 'click .copy-to-clipboard': '_onCopyToClipboardClick', }, /** * @override - * @param {Object} parent */ - start: function (parent) { + start: function () { + var self = this; this.charts = {}; // Get the code of the link - var link_id = $('#link_id').val(); - - this.links_domain = ['link_id', '=', parseInt(link_id)]; - - $.when(this._totalClicks(), - this._clicksByDay(), - this._clicksByCountry(), - this._lastWeekClicksByCountry(), - this._lastMonthClicksByCountry()) - .done(function (_totalClicks, _clicksByDay, _clicksByCountry, _lastWeekClicksByCountry, _lastMonthClicksByCountry) { - - if (_totalClicks) { - this.charts = {}; - var formatted_clicks_by_day = {}; - var begin_date, end_date; - for (var i = 0 ; i < _clicksByDay.length ; i++) { - var date = moment(_clicksByDay[i]['create_date:day'], "DD MMMM YYYY"); - if (i === 0) { begin_date = date; } - if (i === _clicksByDay.length - 1) { end_date = date; } - formatted_clicks_by_day[date.format("YYYY-MM-DD")] = _clicksByDay[i]['create_date_count']; - } + var linkID = parseInt($('#link_id').val()); + this.links_domain = ['link_id', '=', linkID]; - // Process all time line chart data - var now = moment(); - this.charts.all_time_bar = new BarChart('#all_time_clicks_chart', begin_date, now, formatted_clicks_by_day); + var defs = []; + defs.push(this._totalClicks()); + defs.push(this._clicksByDay()); + defs.push(this._clicksByCountry()); + defs.push(this._lastWeekClicksByCountry()); + defs.push(this._lastMonthClicksByCountry()); + defs.push(this._super.apply(this, arguments)); - // Process month line chart data - begin_date = moment().subtract(30, 'days'); - this.charts.last_month_bar = new BarChart('#last_month_clicks_chart', begin_date, now, formatted_clicks_by_day); + new ClipboardJS($('.copy-to-clipboard')[0]); - // Process week line chart data - begin_date = moment().subtract(7, 'days'); - this.charts.last_week_bar = new BarChart('#last_week_clicks_chart', begin_date, now, formatted_clicks_by_day); + this.animating_copy = false; - // Process pie charts - this.charts.all_time_pie = new PieChart('#all_time_countries_charts', _clicksByCountry); - this.charts.last_month_pie = new PieChart('#last_month_countries_charts', _lastMonthClicksByCountry); - this.charts.last_week_pie = new PieChart('#last_week_countries_charts', _lastWeekClicksByCountry); + return $.when.apply($, defs).then(function (_totalClicks, _clicksByDay, _clicksByCountry, _lastWeekClicksByCountry, _lastMonthClicksByCountry) { + if (!_totalClicks) { + $('#all_time_charts').prepend(_t("There is no data to show")); + $('#last_month_charts').prepend(_t("There is no data to show")); + $('#last_week_charts').prepend(_t("There is no data to show")); + } - var row_width = $('#all_time_countries_charts').parent().width(); - var charts_svg = $('#all_time_countries_charts,last_month_countries_charts,last_week_countries_charts').find('svg'); - charts_svg.css('height', Math.max(_clicksByCountry.length * (row_width > 750 ? 1 : 2), 20) + 'em'); + var formattedClicksByDay = {}; + var beginDate; + for (var i = 0; i < _clicksByDay.length; i++) { + var date = moment(_clicksByDay[i]['create_date:day'], 'DD MMMM YYYY'); + if (i === 0) { + beginDate = date; + } + formattedClicksByDay[date.format('YYYY-MM-DD')] = _clicksByDay[i]['create_date_count']; + } - _.invoke(this.charts, 'start'); + // Process all time line chart data + var now = moment(); + self.charts.all_time_bar = new BarChart(beginDate, now, formattedClicksByDay); + self.charts.all_time_bar.attachTo($('#all_time_clicks_chart')); - nv.utils.windowResize(function () { - _.chain(this.charts).pluck('chart').invoke('update'); - }); - } - else { - $('#all_time_charts').prepend(_t('There is no data to show')); - $('#last_month_charts').prepend(_t('There is no data to show')); - $('#last_week_charts').prepend(_t('There is no data to show')); - } - }); + // Process month line chart data + beginDate = moment().subtract(30, 'days'); + self.charts.last_month_bar = new BarChart(beginDate, now, formattedClicksByDay); + self.charts.last_month_bar.attachTo($('#last_month_clicks_chart')); - // Copy to clipboard link - new ClipboardJS($('.copy-to-clipboard')[0]); + // Process week line chart data + beginDate = moment().subtract(7, 'days'); + self.charts.last_week_bar = new BarChart(beginDate, now, formattedClicksByDay); + self.charts.last_week_bar.attachTo($('#last_week_clicks_chart')); - this.animating_copy = false; + // Process pie charts + self.charts.all_time_pie = new PieChart(_clicksByCountry); + self.charts.all_time_pie.attachTo($('#all_time_countries_charts')); + + self.charts.last_month_pie = new PieChart(_lastMonthClicksByCountry); + self.charts.last_month_pie.attachTo($('#last_month_countries_charts')); + + self.charts.last_week_pie = new PieChart(_lastWeekClicksByCountry); + self.charts.last_week_pie.attachTo($('#last_week_countries_charts')); + + var rowWidth = $('#all_time_countries_charts').parent().width(); + var chartsSVG = $('#all_time_countries_charts,last_month_countries_charts,last_week_countries_charts').find('svg'); + chartsSVG.css('height', Math.max(_clicksByCountry.length * (rowWidth > 750 ? 1 : 2), 20) + 'em'); + + nv.utils.windowResize(function () { + _.chain(self.charts).pluck('chart').invoke('update'); + }); + }); }, //-------------------------------------------------------------------------- @@ -231,7 +252,7 @@ sAnimations.registry.websiteLinksCharts = sAnimations.Class.extend({ model: 'link.tracker.click', method: 'read_group', args: [[this.links_domain], ['create_date']], - kwargs: {groupby:'create_date:day'}, + kwargs: {groupby: 'create_date:day'}, }); }, /** @@ -242,26 +263,26 @@ sAnimations.registry.websiteLinksCharts = sAnimations.Class.extend({ model: 'link.tracker.click', method: 'read_group', args: [[this.links_domain], ['country_id']], - kwargs: {groupby:'country_id'}, + kwargs: {groupby: 'country_id'}, }); }, /** * @private */ _lastWeekClicksByCountry: function () { - var interval = moment().subtract(7, 'days').format("YYYY-MM-DD"); + var interval = moment().subtract(7, 'days').format('YYYY-MM-DD'); return this._rpc({ model: 'link.tracker.click', method: 'read_group', args: [[this.links_domain, ['create_date', '>', interval]], ['country_id']], - kwargs: {groupby:'country_id'}, + kwargs: {groupby: 'country_id'}, }); }, /** * @private */ _lastMonthClicksByCountry: function () { - var interval = moment().subtract(30, 'days').format("YYYY-MM-DD"); + var interval = moment().subtract(30, 'days').format('YYYY-MM-DD'); return this._rpc({ model: 'link.tracker.click', method: 'read_group', @@ -275,50 +296,50 @@ sAnimations.registry.websiteLinksCharts = sAnimations.Class.extend({ //-------------------------------------------------------------------------- /** - * Resize the chart when a tab is opened, because NVD3 automatically reduce the size - * of the chart to 5px width when the bootstrap tab is closed. + * Resizes the chart when a tab is opened, because NVD3 automatically reduce + * the size of the chart to 5px width when the bootstrap tab is closed. * - * @override - * @param {Object} e + * @private + * @param {Event} ev */ - _onResizeChart: function (e) { - e.preventDefault(); + _onGraphTabClick: function (ev) { + ev.preventDefault(); $('.graph-tabs li a').tab('show'); _.chain(this.charts).pluck('chart').invoke('update'); // Force NVD3 to redraw the chart }, /** - * @override - * @param {Object} e + * @private + * @param {Event} ev */ - _onCopyToClipboard: function (e) { - e.preventDefault(); - - if (!this.animating_copy) { - this.animating_copy = true; - - $('.o_website_links_short_url').clone() - .css('position', 'absolute') - .css('left', '15px') - .css('bottom', '10px') - .css('z-index', 2) - .removeClass('.o_website_links_short_url') - .addClass('animated-link') - .appendTo($('.o_website_links_short_url')) - .animate({ - opacity: 0, - bottom: "+=20", - }, 500, function () { - $('.animated-link').remove(); - this.animating_copy = false; - }); + _onCopyToClipboardClick: function (ev) { + ev.preventDefault(); + + if (this.animating_copy) { + return; } - }, + this.animating_copy = true; + + $('.o_website_links_short_url').clone() + .css('position', 'absolute') + .css('left', '15px') + .css('bottom', '10px') + .css('z-index', 2) + .removeClass('.o_website_links_short_url') + .addClass('animated-link') + .appendTo($('.o_website_links_short_url')) + .animate({ + opacity: 0, + bottom: '+=20', + }, 500, function () { + $('.animated-link').remove(); + this.animating_copy = false; + }); + }, }); -exports.BarChart = BarChart; -exports.PieChart = PieChart; - -return exports; - +return { + BarChart: BarChart, + PieChart: PieChart, +}; }); diff --git a/addons/website_links/static/src/js/website_links_code_editor.js b/addons/website_links/static/src/js/website_links_code_editor.js index ef01d757578..3d550983e7a 100644 --- a/addons/website_links/static/src/js/website_links_code_editor.js +++ b/addons/website_links/static/src/js/website_links_code_editor.js @@ -1,16 +1,18 @@ odoo.define('website_links.code_editor', function (require) { 'use strict'; +var core = require('web.core'); var sAnimations = require('website.content.snippets.animation'); -var ajax = require('web.ajax'); + +var _t = core._t; sAnimations.registry.websiteLinksCodeEditor = sAnimations.Class.extend({ - selector: '.o_website_links_edit_code', + selector: '#wrapwrap:has(.o_website_links_edit_code)', read_events: { - 'click .o_website_links_edit_code': '_onEdit', - 'click .o_website_links_cancel_edit': '_onCancel', - 'submit #edit-code-form': '_onEditCodeForm', - 'click .o_website_links_ok_edit': '_onEditCodeForm' + 'click .o_website_links_edit_code': '_onEditCodeClick', + 'click .o_website_links_cancel_edit': '_onCancelEditClick', + 'submit #edit-code-form': '_onEditCodeFormSubmit', + 'click .o_website_links_ok_edit': '_onEditCodeFormSubmit', }, //-------------------------------------------------------------------------- @@ -19,9 +21,9 @@ sAnimations.registry.websiteLinksCodeEditor = sAnimations.Class.extend({ /** * @private - * @param {String} new_code + * @param {String} newCode */ - _showNewCode: function (new_code) { + _showNewCode: function (newCode) { $('.o_website_links_code_error').html(''); $('.o_website_links_code_error').hide(); @@ -29,10 +31,10 @@ sAnimations.registry.websiteLinksCodeEditor = sAnimations.Class.extend({ // Show new code var host = $('#short-url-host').html(); - $('#o_website_links_code').html(new_code); + $('#o_website_links_code').html(newCode); // Update button copy to clipboard - $('.copy-to-clipboard').attr('data-clipboard-text', host + new_code); + $('.copy-to-clipboard').attr('data-clipboard-text', host + newCode); // Show action again $('.o_website_links_edit_code').show(); @@ -41,32 +43,39 @@ sAnimations.registry.websiteLinksCodeEditor = sAnimations.Class.extend({ }, /** * @private + * @returns {Deferred} */ _submitCode: function () { - var init_code = $('#edit-code-form #init_code').val(); - var new_code = $('#edit-code-form #new_code').val(); + var initCode = $('#edit-code-form #init_code').val(); + var newCode = $('#edit-code-form #new_code').val(); var self = this; - if (new_code === '') { - self.$('.o_website_links_code_error').html("The code cannot be left empty"); + if (newCode === '') { + self.$('.o_website_links_code_error').html(_t("The code cannot be left empty")); self.$('.o_website_links_code_error').show(); return; } - this._showNewCode(new_code); + this._showNewCode(newCode); - if (init_code === new_code) { - this._showNewCode(new_code); + if (initCode === newCode) { + this._showNewCode(newCode); } else { - ajax.jsonRpc('/website_links/add_code', 'call', {'init_code':init_code, 'new_code':new_code}) - .then(function (result) { - self._showNewCode(result[0].code); - }) - .fail(function () { - $('.o_website_links_code_error').show(); - $('.o_website_links_code_error').html("This code is already taken"); - }); + return this._rpc({ + route: '/website_links/add_code', + params: { + init_code: initCode, + new_code: newCode, + }, + }).then(function (result) { + self._showNewCode(result[0].code); + }, function () { + $('.o_website_links_code_error').show(); + $('.o_website_links_code_error').html(_t("This code is already taken")); + }); } + + return $.when(); }, //-------------------------------------------------------------------------- @@ -74,41 +83,39 @@ sAnimations.registry.websiteLinksCodeEditor = sAnimations.Class.extend({ //-------------------------------------------------------------------------- /** - * @override + * @private */ - _onEdit: function () { - var init_code = $('#o_website_links_code').html(); - $('#o_website_links_code').html("<form style='display:inline;' id='edit-code-form'><input type='hidden' id='init_code' value='" + init_code + "'/><input type='text' id='new_code' value='" + init_code + "'/></form>"); + _onEditCodeClick: function () { + var initCode = $('#o_website_links_code').html(); + $('#o_website_links_code').html('<form style="display:inline;" id="edit-code-form"><input type="hidden" id="init_code" value="' + initCode + '"/><input type="text" id="new_code" value="' + initCode + '"/></form>'); $('.o_website_links_edit_code').hide(); $('.copy-to-clipboard').hide(); $('.o_website_links_edit_tools').show(); }, /** - * @override - * @param {Object} e + * @private + * @param {Event} ev */ - _onCancel: function (e) { - e.preventDefault(); + _onCancelEditClick: function (ev) { + ev.preventDefault(); $('.o_website_links_edit_code').show(); $('.copy-to-clipboard').show(); $('.o_website_links_edit_tools').hide(); $('.o_website_links_code_error').hide(); - var old_code = $('#edit-code-form #init_code').val(); - $('#o_website_links_code').html(old_code); + var oldCode = $('#edit-code-form #init_code').val(); + $('#o_website_links_code').html(oldCode); $('#code-error').remove(); $('#o_website_links_code form').remove(); }, /** - * @override - * @param {Object} e + * @private + * @param {Event} ev */ - _onEditCodeForm: function (e) { - e.preventDefault(); + _onEditCodeFormSubmit: function (ev) { + ev.preventDefault(); this._submitCode(); }, - }); - }); diff --git a/addons/website_links/static/src/js/website_links_menu.js b/addons/website_links/static/src/js/website_links_menu.js index 58b3d487ee0..4adf2b950af 100644 --- a/addons/website_links/static/src/js/website_links_menu.js +++ b/addons/website_links/static/src/js/website_links_menu.js @@ -1,24 +1,23 @@ -/* The purpose of this script is to copy the current URL of the website - * into the URL form of the URL shortener (module website_links) - * when the user click the link "Share this page" on top of the page. -*/ +/** + * The purpose of this script is to copy the current URL of the website + * into the URL form of the URL shortener (module website_links) + * when the user clicks the link "Share this page" on top of the page. + */ odoo.define('website_links.website_links_menu', function (require) { -"use strict"; +'use strict'; var sAnimations = require('website.content.snippets.animation'); sAnimations.registry.websiteLinksMenu = sAnimations.Class.extend({ - selector: '.navbar', + selector: '#o_website_links_share_page', /** * @override - * @param {Object} parent */ - start: function (parent) { - $('#o_website_links_share_page').attr('href', '/r?u=' + encodeURIComponent(window.location.href)); + start: function () { + this.$el.attr('href', '/r?u=' + encodeURIComponent(window.location.href)); + return this._super.apply(this, arguments); }, - }); - }); diff --git a/addons/website_links/static/src/xml/recent_link.xml b/addons/website_links/static/src/xml/recent_link.xml index ef807ad384b..22008b81203 100644 --- a/addons/website_links/static/src/xml/recent_link.xml +++ b/addons/website_links/static/src/xml/recent_link.xml @@ -2,15 +2,15 @@ <templates id="template" xml:space="preserve"> <t t-name="website_links.RecentLink"> - <div class="row mb16 link-row"> + <div class="row mb16"> <div class="col-md-1 col-2 text-center"> <h4><t t-esc="widget.link_obj.count"/></h4> <p class="text-muted" style="margin-top: -5px;">clicks</p> </div> <div class="col-md-7 col-7"> - + <h4 class="truncate_text"> - <img t-att-src="widget.link_obj.icon_src" alt="Icon"/> + <img t-att-src="widget.link_obj.icon_src" alt="Icon"/> <a class="no-link-style" t-att-href="widget.link_obj.url"><t t-esc="widget.link_obj.title"/></a> </h4> <p class="text-muted mb0" style="margin-top: -5px;"> @@ -19,14 +19,14 @@ </span> <span class="o_website_links_edit_tools" style="display:none;"> - <a role="button" class="o_website_links_ok_edit btn btn-sm btn-primary" href="#">ok</a> or + <a role="button" class="o_website_links_ok_edit btn btn-sm btn-primary" href="#">ok</a> or <a class="o_website_links_cancel_edit" href="#">cancel</a> </span> <a class="o_website_links_edit_code" aria-label="Edit code" title="Edit code"><span class="fa fa-pencil gray"></span></a> - + <br/> - <span class="badge badge-success"><t t-esc="widget.link_obj.campaign_id[1]"/></span> + <span class="badge badge-success"><t t-esc="widget.link_obj.campaign_id[1]"/></span> <span class="badge badge-success"><t t-esc="widget.link_obj.medium_id[1]"/></span> <span class="badge badge-success"><t t-esc="widget.link_obj.source_id[1]"/></span> </p> |
