VincentLoy/share-selected-text · shareSelectedText.js
javascript logo
function (exports) {
    'use strict';

    var getPageUrl = function getPageUrl() {
        if (document.querySelector('meta[property="og:url"]') && document.querySelector('meta[property="og:url"]').getAttribute('content')) {
            return document.querySelector('meta[property="og:url"]').getAttribute('content');
        }

        return window.location.href;
    };

    // constants
    var TOOLTIP_HEIGHT = 50;
    var FACTOR = 1.33;
    var TWITTER_LIMIT_LENGTH = 140;
    var TWITTER_URL_LENGTH_COUNT = 24;
    var TWITTER_QUOTES = 2;
    var TWITTER_DOTS = 3;
    var TOOLTIP_TIMEOUT = 250;
    var FACEBOOK_DISPLAY_MODES = {
        popup: 'popup',
        page: 'page'
    };

    var REAL_TWITTER_LIMIT = TWITTER_LIMIT_LENGTH - TWITTER_URL_LENGTH_COUNT - TWITTER_QUOTES - TWITTER_DOTS;

    var SOCIAL = {
        twitter: 'twitter',
        buffer: 'buffer',
        digg: 'digg',
        linkedin: 'linkedin',
        stumbleupon: 'stumbleupon',
        reddit: 'reddit',
        tumblr: 'tumblr',
        facebook: 'facebook'
    };

    var NO_START_WITH = /[ .,!?/\\\+\-=*£$€:~§%^µ)(|@"{}&#><_]/g;
    var NO_ENDS_WITH = /[ ,/\\\+\-=*£$€:~§%^µ)(|@"{}&#><_]/g;
    var PAGE_URL = getPageUrl();

    // globals
    var tooltip = undefined;
    var parameters = undefined;
    var selected = {};

    var extend = function extend(out) {
        out = out || {};

        for (var i = 1; i < arguments.length; i += 1) {
            if (arguments[i]) {
                for (var key in arguments[i]) {
                    if (arguments[i].hasOwnProperty(key)) {
                        out[key] = arguments[i][key];
                    }
                }
            }
        }
        return out;
    };

    var hideTooltip = function hideTooltip() {
        tooltip.classList.remove('active');
    };

    var showTooltip = function showTooltip() {
        tooltip.classList.add('active');
    };

    var smartSanitize = function smartSanitize(text) {
        while (text.length && text[0].match(NO_START_WITH)) {
            text = text.substring(1, text.length);
        }

        while (text.length && text[text.length - 1].match(NO_ENDS_WITH)) {
            text = text.substring(0, text.length - 1);
        }

        return text;
    };

    var sanitizeText = function sanitizeText(text) {
        var sociaType = arguments.length <= 1 || arguments[1] === undefined ? '' : arguments[1];

        var author = '';
        var tweetLimit = REAL_TWITTER_LIMIT;

        if (!text) {
            return '';
        }

        if (parameters.twitterUsername && sociaType === SOCIAL.twitter) {
            author = ' via @' + parameters.twitterUsername;
            tweetLimit = REAL_TWITTER_LIMIT - author.length;
        }

        if (text.length > REAL_TWITTER_LIMIT) {
            text = text.substring(0, tweetLimit);
            text = text.substring(0, text.lastIndexOf(' ')) + '...';
        } else {
            text = text.substring(0, tweetLimit + TWITTER_DOTS);
        }

        return smartSanitize(text);
    };

    var generateSocialUrl = function generateSocialUrl(socialType, text) {
        if (parameters.sanitize) {
            text = sanitizeText(text, socialType);
        } else {
            text = smartSanitize(text);
        }

        var twitterUrl = 'https://twitter.com/intent/tweet?url=' + PAGE_URL + '&text="' + text + '"';

        if (parameters.twitterUsername && parameters.twitterUsername.length) {
            twitterUrl += '&via=' + parameters.twitterUsername;
        }

        var facebookUrl = 'https://facebook.com/dialog/share?display=' + parameters.facebookDisplayMode + '&href=' + PAGE_URL + '&quote=' + text;

        if (document.querySelector('meta[property="fb:app_id"]') && document.querySelector('meta[property="fb:app_id"]').getAttribute('content')) {
            var content = document.querySelector('meta[property="fb:app_id"]');
            facebookUrl += '&app_id=' + content;
        } else if (parameters.facebookAppID && parameters.facebookAppID.length) {
            facebookUrl += '&app_id=' + parameters.facebookAppID;
        } else {
            var idx = parameters.buttons.indexOf('facebook');
            if (idx > -1) {
                parameters.buttons.splice(idx, 1);
            }
        }

        var urls = {
            twitter: twitterUrl,
            buffer: 'https://buffer.com/add?text="' + text + '"&url=' + PAGE_URL,
            digg: 'http://digg.com/submit?url=' + PAGE_URL + '&title=' + text,
            linkedin: 'https://www.linkedin.com/shareArticle?url=' + PAGE_URL + '&title=' + text,
            stumbleupon: 'http://www.stumbleupon.com/submit?url=' + PAGE_URL + '&title=' + text,
            reddit: 'https://reddit.com/submit?url=' + PAGE_URL + '&title=' + text,
            tumblr: 'https://www.tumblr.com/widgets/share/tool?canonicalUrl=' + PAGE_URL + '&caption=' + text,
            facebook: facebookUrl
        };

        if (urls.hasOwnProperty(socialType)) {
            return urls[socialType];
        }

        return '';
    };

    var updateTooltip = function updateTooltip(rect) {
        var actualPosition = document.documentElement.scrollTop || document.body.scrollTop;
        var body = document.querySelector('body');

        tooltip.style.top = actualPosition + rect.top - TOOLTIP_HEIGHT * FACTOR + 'px';
        tooltip.style.left = rect.left + rect.width / 2 - body.getBoundingClientRect().width / 2 + 'px';

        Array.prototype.forEach.call(parameters.buttons, function (btn) {
            tooltip.querySelector('.share-selected-text-btn-' + btn).href = generateSocialUrl(btn, selected.text);
        });

        window.setTimeout(function () {
            showTooltip();
        }, parameters.tooltipTimeout);
    };

    var generateAnchorTag = function generateAnchorTag(anchorType) {
        var customIconClass = arguments.length <= 1 || arguments[1] === undefined ? null : arguments[1];

        var anchorTag = document.createElement('A');
        var anchorIcon = document.createElement('i');

        if (parameters.anchorsClass) {
            ['share-selected-text-btn', 'share-selected-text-btn-' + anchorType, '' + parameters.anchorsClass].map(function (item) {
                return anchorTag.classList.add(item);
            });
        } else {
            ['share-selected-text-btn', 'share-selected-text-btn-' + anchorType].map(function (item) {
                return anchorTag.classList.add(item);
            });
        }

        if (customIconClass) {
            anchorIcon.classList.add('' + customIconClass);
        } else {
            ['icon-sst-' + anchorType, 'fa', 'fa-' + anchorType].map(function (item) {
                return anchorIcon.classList.add(item);
            });
        }

        anchorIcon.style.pointerEvents = 'none';
        anchorTag.addEventListener('click', function (e) {
            e.preventDefault();
            var windowFeatures = 'status=no,menubar=no,location=no,scrollbars=no,width=720,height=540';
            var url = e.target.href;
            window.open(url, 'Share this post', windowFeatures);
        });

        anchorTag.href = generateSocialUrl(anchorType, selected.text ? selected.text : '');
        anchorTag.appendChild(anchorIcon);
        return anchorTag;
    };

    var generateTooltip = function generateTooltip() {
        var body = document.querySelector('body');
        var mainDiv = document.createElement('DIV');
        var btnContainer = document.createElement('DIV');

        mainDiv.classList.add('share-selected-text-main-container');
        btnContainer.classList.add('share-selected-text-inner');

        if (parameters.tooltipClass) {
            btnContainer.classList.add(parameters.tooltipClass);
        }

        mainDiv.style.height = TOOLTIP_HEIGHT + 'px';
        mainDiv.style.top = 0;
        mainDiv.style.left = 0;

        Array.prototype.forEach.call(parameters.buttons, function (btn) {
            var aTag = generateAnchorTag(btn);
            btnContainer.appendChild(aTag);
        });

        mainDiv.appendChild(btnContainer);
        body.appendChild(mainDiv);

        return mainDiv;
    };

    var getSelectedText = function getSelectedText() {
        var text = '';
        var selection = undefined;

        if (window.getSelection) {
            selection = window.getSelection();
            text = selection.toString();
        } else if (document.selection && document.selection.type !== 'Control') {
            selection = document.selection.createRange();
            text = selection.text;
        }

        return {
            selection: selection,
            text: text
        };
    };

    var shareTooltip = function shareTooltip() {
        selected = getSelectedText();

        if (selected.text.length) {
            var oRange = selected.selection.getRangeAt(0);
            var oRect = oRange.getBoundingClientRect();
            updateTooltip(oRect);
        } else {
            hideTooltip();
        }
    };

    exports.shareSelectedText = function (element, args) {
        var elt = document.querySelectorAll(element);

        parameters = extend({
            tooltipClass: '',
            sanitize: true,
            buttons: [SOCIAL.twitter, SOCIAL.buffer],
            anchorsClass: '',
            twitterUsername: '',
            facebookAppID: '',
            facebookDisplayMode: FACEBOOK_DISPLAY_MODES.popup,
            tooltipTimeout: TOOLTIP_TIMEOUT
        }, args);

        tooltip = generateTooltip();

        Array.prototype.forEach.call(elt, function (el) {
            el.addEventListener('mouseup', function () {
                shareTooltip();
            });
        });
    };
}
Similar code snippets
1.
EclairJS/eclairjs · twitter.js
Match rating: 59.24% · See similar code snippets
javascript logo
function () {
    /**
     * streaming twitter module.
     * @example
     * var twitter = require('eclairjs/streaming/twitter');
     * @module eclairjs/streaming/twitter
     */
    module.exports = {
        TwitterAuthorization: require(EclairJS_Globals.NAMESPACE + '/streaming/twitter/TwitterAuthorization'),
        TwitterUtils: require(EclairJS_Globals.NAMESPACE + '/streaming/twitter/TwitterUtils')
    }

}
2.
osmlab/name-suggestion-index · build_wikidata.js
Match rating: 57.83% · See similar code snippets
javascript logo
function fetchTwitterUserDetails(qid, username) {
    let target = _wikidata[qid];
    let twitterAPI = twitterAPIs[_twitterAPIIndex];

    return twitterAPI
        .get('users/show', { screen_name: username })
        .then(user => {
            target.logos.twitter = user.profile_image_url_https.replace('_normal', '_bigger');
        })
        .catch(e => {
            let msg = `Error: Twitter username @${username} for ${qid}: ` + JSON.stringify(e);
            _errors.push(msg);
            console.error(colors.red(msg));
        });
}
3.
vodolaz095/hunt · twitter.js
Match rating: 55.82% · See similar code snippets
javascript logo
function (core) {
  return new TwitterStrategy({
    consumerKey: core.config.passport.TWITTER_CONSUMER_KEY,
    consumerSecret: core.config.passport.TWITTER_CONSUMER_SECRET,
    callbackURL: core.config.hostUrl + 'auth/twitter/callback',
    passReqToCallback: true
  }, function (request, token, tokenSecret, profile, done) {
//    console.log('==============AUTH VIA TWITTER');
//    console.log(profile);
//    console.log('==============');
    if (profile.provider === 'twitter' && profile.id) {
      request.session.twitterToken = token;
      request.session.twitterSecret = tokenSecret;
      core.model.User.processOAuthProfile(request, profile, done);
    } else {
      return done(new Error('There is something strange instead of user profile!'));
    }
  });

}
4.
mrhenry/custom-elements-helpers · index.js
Match rating: 54.19% · See similar code snippets
javascript logo
function shareOnTwitter() {
				var values = getMetaValues(document.head, '[name^="twitter:"]');

				var params = {
					url: values.url || this.url,
					text: values.title || this.title,
					via: values.site ? values.site.replace('@', '') : undefined
				};

				openWindow('https://twitter.com/intent/tweet', params, { name: 'Share on Twitter', width: 580, height: 253 });
			}
5.
prebid/Prebid.js · medianetBidAdapter.js
Match rating: 52.81% · See similar code snippets
javascript logo
function getPageMeta() {
  if (mnData.pageMeta) {
    return mnData.pageMeta;
  }
  let canonicalUrl = getUrlFromSelector('link[rel="canonical"]', 'href');
  let ogUrl = getUrlFromSelector('meta[property="og:url"]', 'content');
  let twitterUrl = getUrlFromSelector('meta[name="twitter:url"]', 'content');

  mnData.pageMeta = Object.assign({},
    canonicalUrl && { 'canonical_url': canonicalUrl },
    ogUrl && { 'og_url': ogUrl },
    twitterUrl && { 'twitter_url': twitterUrl }
  );

  return mnData.pageMeta;
}
6.
adobe/brackets · InlineTextEditor.js
Match rating: 47.04% · See similar code snippets
javascript logo
function (editor) {
            var $gutter = $(editor._codeMirror.getGutterElement()).find(".CodeMirror-linenumbers");
            $gutter.css("min-width", "");
            var curWidth = $gutter.width();
            if (curWidth > maxWidth) {
                maxWidth = curWidth;
            }
        }
7.
shama/voxel-critter · demo.js
Match rating: 45.76% · See similar code snippets
javascript logo
function(err, resp, data) {
    if (err) {
      alert('error loading critters!')
      hideCritterBrowser()
      return
    }
    content.innerHTML = ""
    data.rows.map(function(row) {
      if (!row || !row.doc) return
      if (row.doc.link && row.doc.link.match(/imgur/)) {
        content.innerHTML += ('<img class="critterImage" src="' + row.doc.link + '"/>')
      }
    })
    
  }
8.
brython-dev/brython · brython_dist.js
Match rating: 44.77% · See similar code snippets
javascript logo
function(self){var src=self.source,len=src.length
buffer=src.slice(),current_char_is_letter=false,prev_char_was_letter=false,is_uppercase=false,is_lowercase=false
for(var i=0;i < len;++i){is_lowercase=buffer[i]> 96 && buffer[i]< 123
is_uppercase=buffer[i]> 64 && buffer[i]< 91
current_char_is_letter=is_lowercase ||is_uppercase
if(current_char_is_letter){if(prev_char_was_letter && is_uppercase){buffer[i]+=32}else if(! prev_char_was_letter && is_lowercase){buffer[i]-=32}}
prev_char_was_letter=current_char_is_letter}
return bytes.$factory(buffer)}
9.
joemccann/photopipe · pipe.js
Match rating: 43.77% · See similar code snippets
javascript logo
function(data){ 
      
      $spin.hide()
      
      // console.dir(data)
      
      var sorted = []
      var thumbs = ""
      
      if(data.error){
        console.dir(data.error)
        alert(data.error_message)
        return false
      }
      
      $.each(data.media,function(i,el){
        
        thumbs += "<img data-standard-resolution='"
                  + el.full_url
                  +"' src='"+ el.thumb_url+"' />"

      }) // end $.each()
      
      // Add to photoPicker div
      $oneUpTwitterWrapper
        .before(thumbs)

      // Show the photo picker fb section
      $photoPickerTwitter
        .show()

      // Wire up the events to the images...
      wireTwitterGalleryPicker()

      // Progress to Step 2
      progressToNextStep($stepOne, function(){

        $stepTwo.slideDown(333)

      })
      
      // console.dir(sorted)
      
    }
10.
Kolbaskin/yode-server · ext-all.js
Match rating: 43.4% · See similar code snippets
javascript logo
function() {
        var me = this,
            seriesItems = me.series.items,
            i, ln, series, gutters,
            lowerH = 0, upperH = 0, lowerV = 0, upperV = 0;

        for (i = 0, ln = seriesItems.length; i < ln; i++) {
            gutters = seriesItems[i].getGutters();
            if (gutters) {
                if (gutters.verticalAxis) {
                    lowerV = Math.max(lowerV, gutters.lower);
                    upperV = Math.max(upperV, gutters.upper);
                }
                else {
                    lowerH = Math.max(lowerH, gutters.lower);
                    upperH = Math.max(upperH, gutters.upper);
                }
            }
        }
        me.maxGutters = {
            left: lowerH,
            right: upperH,
            bottom: lowerV,
            top: upperV
        };
    }