Source: widgets/SpwShareLink.js

Retour à la documentation
/**
 * @class spw.widgets.SpwShareLink
 */
define([
        "dojo/_base/declare",
        "spw/api/SpwBaseTemplatedWidget",
        "dojo/text!./templates/SpwShareLink.html",
        "spw/api/ConfigLoader",
        "spw/api/Utils",
        "dijit/layout/ContentPane",
        "dojo/_base/array",
        "dojo/_base/lang",
        "dojo/dom-construct",
        "dojo/dom-class",
        "dojo/dom-style",
        "dojo/request/xhr",
        "dojo/on",
        "dojo/dom-geometry",
        "dojo/i18n!./nls/SpwShareLink",
        "dojo/dom-attr",
        "spw/api/StateManager",
        "dojo/io-query",
        "dojo/query",
        "dijit/form/NumberTextBox",
        "dijit/form/TextBox",
        "dijit/Dialog",
        "dojo/json",
        "dijit/Tooltip"
    ],
    function(
        declare, SpwBaseTemplatedWidget, template, ConfigLoader, Utils,
        ContentPane, array, lang, domConstruct, domClass, domStyle, request, on,
        domGeom, labels, domAttr, StateManager, ioQuery, query, NumberTextBox, TextBox, Dialog, JSON,
        Tooltip
    ) {

        var SpwShareLink = null;
        SpwShareLink = declare('spw.widgets.SpwShareLink', [SpwBaseTemplatedWidget], /** @lends spw.widgets.SpwShareLink.prototype */{

            templateString: template,
            labels: labels,

            /** START WIDGET CONFIG */
            // types possibles (mail, url, iframe, facebook, twitter, google, linkedin)
            "widgetTitle": null,
            "iconClass": "shareIcon",
            "position": "none",
            "shareUrl": "http://localhost:8080/geoviewer_4.0/",
            "api_key": "AIzaSyCWThdtYpzdF1GhCvErW3i05X9kNX-nIQA",
            "shareTypes": [
                "mail",
                "linkedin",
                "skype",
                "twitter",
                "facebook",
                "url",
                "iframe"
            ],
            "shareTitle": "WalOnMap",
            "shareSource": "WalOnMap",
            "shareSummary": "Venez voir ma carte créée à l'aide de WalOnMap !",
            "style": {
                "width": "390px"
            },

            builtShareType: {},

            shareLabels: {
                mail: 'Partager par email',
                facebook: 'Partager sur Facebook',
                twitter: 'Partager sur Twitter',
                linkedin: 'Partager sur LinkedIn',
                google: 'Partager sur Google+',
                url: 'Afficher l\'URL',
                iframe: 'Intégrer une mini-carte à votre site',
                skype: 'Partager sur Skype'
            },

            api_type: 'geoviewer',
            useCors: true,
            /** END WIDGET CONFIG */

            width: "350px",
            height: "auto",

            constructor: function(){
                this.inherited(arguments);
            },

            buildRendering: function(){
                this.inherited(arguments);

                var first = true;

                // build share links based on config
                array.forEach(this.shareTypes, lang.hitch(this, function(item) {
                    var url = this.shareUrl || Utils.cleanUrl();;
                    item = typeof(item) === 'string' ? item : (url=item.shareUrl||url, item.type);
                    if (!/mail|url|iframe|facebook|twitter|google|linkedin|skype/.test(item)) {
                        return;
                    }
                    // if first, empty the dom element so we clear it before adding
                    if (first) {
                        first = false;
                        domConstruct.empty(this.linksGallery);
                    }

                    // create nodes and add them
                    var container = domConstruct.create('div', {
                        'class': 'SpwShareLinkNode'
                    }, this.linksGallery);

                    var img = domConstruct.create('div', {
                        'class': 'thumbnail ' + item,
                        'data-item': item,
                        'data-url': url
                    }, container);

                    var tp = new Tooltip({
                        connectId: container,
                        label: this.shareLabels[item],
                        position: ['below', 'above']
                    });

                    this.own(on(img, 'click', lang.hitch(this, this.imageClicked)));
                }));
                this.api_url = this.api_url ? this.api_url : this.spwViewer.shareServlet;
            },

            _getUrlAttr: function() {
                if (/^(http|https):\/\//.test(this.api_url) && this.spwViewer.get('proxyPageUrl') && this.useCors !== true) {
                    if (this.api_url.indexOf(this.spwViewer.get('proxyPageUrl')) < 0) {
                        return this.spwViewer.get('proxyPageUrl') + '?' + this.api_url;
                    }
                }

                return this.api_url;
            },

            onActivate: function() {
                this.inherited(arguments);

                // reset ui on activation
                this._resetDisplay();
            },

            onDeactivate: function() {
                this.inherited(arguments);
            },

            _resetDisplay: function() {
                // hide the additional options
                domConstruct.empty(this.showMoreNode);
                domStyle.set(this.showMoreNode, 'display', 'none');

                query('.thumbnail').forEach(function(n) {
                    domClass.remove(n, 'selected');
                });
            },

            imageClicked: function(item) {
                this._resetDisplay();

                // get complete url (with all data) from state manager
                // var completeUrl = StateManager.getInstance().getCompleteUrl();
                var anchors = StateManager.getInstance().getAnchors({
                    full: true,
                    extent: this.spwViewer.get('spwMap').getCurrentExtent()
                });
                var query;

                var data = {
                    basemaps: null,
                    services: null,
                    bbox: null,
                    token: window.geoviewerToken || '',
                    srid: this.spwViewer.get('spatialReference').wkid
                };

                array.forEach(anchors, function(a) {
                    if (a.key === 'BBOX') {
                        data.bbox = a.value;
                    }
                    else if (a.key === StateManager.BASEMAP_ID) {
                        data.basemaps = a.value;
                    }
                    else if (a.key === StateManager.MAP_SERVICES_ID) {
                        data.services = a.value;
                    }
                });

                this.showLoading();

                var promise = null;

                /*if (this.api_type === 'google') {
                    promise = request.post(this.get('url') + '?key=' + this.api_key, {
                        data: JSON.stringify({longUrl: completeUrl}),
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                }
                else */
                if (this.api_type === 'geoviewer') {
                    promise = request.post(this.get('url') + '?method=share', {
                        data: JSON.stringify(data),
                        headers: {
                            'Content-type': 'application/json; charset=UTF-8'
                        }
                    });
                }

                if (promise == null) {
                    this.hideLoading();

                    new Dialog({
                        title: 'Problème de configuration',
                        content: 'La méthode de partage décrite dans la configuration est inconnue...'
                    }).show();
                    return;
                }

                promise.then(lang.hitch(this, function(json) {
                    this.hideLoading();

                    // read JSON and parse it
                    var resp = JSON.parse(json);

                    var shortUrl = null;

                    if (this.api_type === 'google') {
                        // get shortened url
                        shortUrl = resp.id;

                        this.doActionUrl(item, shortUrl);
                    }
                    else {
                        if (!resp.success) {
                            var errMsg = labels.errorApiContent;

                            if (resp.errorMessage === 'max_length') {
                                errMsg = labels.errorApiMaxLength;
                            }

                            new Dialog({
                                title: labels.errorApiTitle,
                                content: errMsg
                            }).show();

                            console.error(resp.errorMessage);
                            return;
                        }

                        var ctx = ConfigLoader.getInstance().currentContext;
                        var startUrl = item.target['dataset'].url;

                        shortUrl = Utils.addAnchor('SHARE', resp.token, startUrl);

                        if (ctx !== 'default') {
                            shortUrl = Utils.addAnchor('CTX', ctx, shortUrl);
                        }
                    }

                    this.doActionUrl(item, shortUrl);

                }), lang.hitch(this, function(err) {
                    this.hideLoading();

                    new Dialog({
                        title: labels.errorApiTitle,
                        content: labels.errorApiContent
                    }).show();

                    console.error(err);
                }));
            },

            doActionUrl: function(item, shortUrl) {
                var query = null;
                // if mail was clicked
                if (domClass.contains(item.target, 'mail')) {
                    // build query params
                    query = ioQuery.objectToQuery({
                        body: shortUrl
                    });

                    window.location.href = 'mailto:?' + query;
                }
                else if (domClass.contains(item.target, 'skype')) {
                    query = ioQuery.objectToQuery({
                        url: shortUrl,
                        text: this.shareTitle
                    });

                    window.open('http://web.skype.com/share?' + query, '_blank');
                }
                // if facebook
                else if (domClass.contains(item.target, 'facebook')) {
                    query = ioQuery.objectToQuery({
                        u: shortUrl
                    });

                    window.open('https://www.facebook.com/sharer/sharer.php?' + query, '_blank');
                }
                // if twitter
                else if (domClass.contains(item.target, 'twitter')) {
                    var query = ioQuery.objectToQuery({
                        url: shortUrl
                    });

                    var width  = 575,
                        height = 400,
                        left   = ($(window).width()  - width)  / 2,
                        top    = ($(window).height() - height) / 2,
                        url    = 'http://twitter.com/share?' + query,
                        opts   = 'status=1' +
                            ',width='  + width  +
                            ',height=' + height +
                            ',top='    + top    +
                            ',left='   + left;

                    window.open(url, 'twitter', opts);
                }
                // if linkedin
                else if (domClass.contains(item.target, 'linkedin')) {
                    var query = ioQuery.objectToQuery({
                        url: shortUrl,
                        mini: true,
                        title: this.shareTitle,
                        summary: this.shareSummary,
                        source: this.shareSource
                    });

                    window.open('https://www.linkedin.com/shareArticle?' + query, '_blank');
                }
                // if google+
                else if (domClass.contains(item.target, 'google')) {
                    var query = ioQuery.objectToQuery({
                        url: shortUrl
                    });

                    window.open('https://plus.google.com/share?' + query, '_blank');
                }
                // if link
                else if (domClass.contains(item.target, 'url')) {
                    domClass.add(item.target, 'selected');

                    // show the url
                    this.createCopyLinkNode(shortUrl);
                }
                else if (domClass.contains(item.target, 'iframe')) {
                    domClass.add(item.target, 'selected');

                    // show options for iframe
                    this.createIframeNode(shortUrl);
                }
            },

            createCopyLinkNode: function(url) {
                domStyle.set(this.showMoreNode, 'display', 'block');

                // show help message
                domConstruct.create('p', {
                    style: 'text-align: center;',
                    innerHTML: labels.copyMessage
                }, this.showMoreNode);

                // input with link
                var node = domConstruct.create('input', {
                    type: 'text',
                    value: url
                }, this.showMoreNode);
                node.focus();
                node.select();
            },

            createIframeNode: function(url) {
                domStyle.set(this.showMoreNode, 'display', 'block');

                // show help message
                domConstruct.create('p', {
                    style: 'text-align: center;',
                    innerHTML: labels.copyMessage
                }, this.showMoreNode);

                // build input with iframe code
                var tmp = '<iframe width="500" height="500" src="' + url + '"></iframe>'

                var inputNode = domConstruct.create('input', {type: 'text', value: tmp}, this.showMoreNode);

                // build inputs to set width and height
                var infoNode = domConstruct.place('<table style="margin: 0 auto;"><tbody><tr></tr></tbody></table>', this.showMoreNode, 'last');

                domConstruct.create('td', {innerHTML: labels.formatMessage}, infoNode);

                var tdWidth = domConstruct.create('td', null, infoNode);
                domConstruct.create('td', {innerHTML: 'px X '}, infoNode);

                var tdHeight = domConstruct.create('td', null, infoNode);
                domConstruct.create('td', {innerHTML: 'px'}, infoNode);

                var widthNode = new NumberTextBox({
                    constraints: {
                        min: 1,
                        places: 0
                    },
                    value: 500,
                    style: 'width: 100px',
                    invalidMessage: labels.formatError,
                    rangeMessage: labels.formatError,
                    required: true
                }, tdWidth);

                var heightNode = new NumberTextBox({
                    constraints: {
                        min: 1,
                        places: 0
                    },
                    value: 500,
                    style: 'width: 100px',
                    invalidMessage: labels.formatError,
                    rangeMessage: labels.formatError,
                    required: true
                }, tdHeight);

                var updateValue = function() {
                    if (widthNode.validate() && heightNode.validate()) {
                        domAttr.set(inputNode, 'value', '<iframe width="' + widthNode.get('value') +
                            '" height="' + heightNode.get('value') + '" src="' + url + '"></iframe>');
                    }
                }

                on(widthNode, 'keyup', updateValue);
                on(heightNode, 'keyup', updateValue);

                widthNode.startup();
                heightNode.startup();

                inputNode.focus();
                inputNode.select();
            }
        });

        var IframeNode = declare(null, [SpwBaseTemplatedWidget], {
            templateString: "<table><tbody><tr><td data-dojo-attach-point='formatNode'></td>" +
            "<td data-dojo-attach-point='widthNode'></td><td>px x </td><td data-dojo-attach-point='heightNode'>" +
            "</td><td>px</td></tbody></table>",

            buildRendering: function(){
                this.inherited(arguments);
            }
        });

        return SpwShareLink;
    });