social-share-button
Version:
Sharing button behaviour.
527 lines (440 loc) • 17.4 kB
JavaScript
var socialShareButton = (function () {
'use strict';
function _defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("value" in descriptor) descriptor.writable = true;
Object.defineProperty(target, descriptor.key, descriptor);
}
}
function _createClass(Constructor, protoProps, staticProps) {
if (protoProps) _defineProperties(Constructor.prototype, protoProps);
if (staticProps) _defineProperties(Constructor, staticProps);
return Constructor;
}
function _inheritsLoose(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype);
subClass.prototype.constructor = subClass;
subClass.__proto__ = superClass;
}
function isWindow(obj) {
return obj != null && obj === obj.window;
}
function find(selector, context) {
if (context === void 0) {
context = null;
}
if (selector instanceof HTMLElement || selector instanceof Node || isWindow(selector)) {
return [selector];
} else if (selector instanceof NodeList) {
return [].slice.call(selector);
} else if (typeof selector === 'string') {
var startElement = context ? find(context)[0] : document;
return [].slice.call(startElement.querySelectorAll(selector));
}
return [];
}
function on(selector, event, cb, options) {
if (Array.isArray(selector)) {
selector.forEach(function (item) {
return on(item, event, cb, options);
});
return;
}
var eventOptions = {};
if (typeof options === 'boolean') {
eventOptions.capture = options;
} else if (typeof options === 'object') {
eventOptions = Object.assign({}, options);
}
var data = {
cb: cb,
options: eventOptions
}; // _domassistevents keeps track of events we registered
// with 'domassist.on' so they can be deregistered by
// 'domassist.off' without affecting events registered
// by other libraries:
if (!window._domassistevents) {
window._domassistevents = {};
}
window._domassistevents["_" + event] = data;
var el = find(selector);
if (el.length) {
el.forEach(function (item) {
item.addEventListener(event, cb, eventOptions);
});
}
}
function findOne(selector, el) {
var found = find(selector, el);
if (found.length) {
return found[0];
}
return null;
} //
/* global window */
function attrobj(key, el) {
var values = {};
Object.keys(el.dataset).forEach(function (data) {
if (data.match(new RegExp("^" + key)) && data !== key) {
var optionName = data.replace(key, '');
var isGlobal = false;
if (optionName.match(/^Global/)) {
optionName = optionName.replace('Global', '');
isGlobal = true;
}
optionName = "" + optionName[0].toLowerCase() + optionName.slice(1);
if (isGlobal) {
values[optionName] = window[el.dataset[data]];
} else {
values[optionName] = el.dataset[data];
}
if (typeof values[optionName] === 'undefined' || values[optionName] === '') {
values[optionName] = true;
}
}
});
return values;
}
var l = function l() {
var l = [].slice.call(arguments);
return l.unshift(!1), t.apply(null, l);
};
function t() {
var t = [].slice.call(arguments),
e = t[0],
n = {};
return t.slice(1, t.length).forEach(function (r) {
Object.keys(r).forEach(function (a) {
if (!e || void 0 !== t[1][a]) {
var c = r[a];
n[a] = Array.isArray(c) || "object" != typeof c || "object" != typeof n[a] ? c : (e ? l.defaults : l)(n[a], c);
}
});
}), n;
}
l.defaults = function () {
var l = [].slice.call(arguments);
return l.unshift(!0), t.apply(null, l);
};
function s(t) {
return t.parentNode ? JSON.parse(JSON.stringify(t.parentNode.dataset)).module ? t.parentNode : s(t.parentNode) : t;
}
var r = {
find: find,
findOne: findOne,
on: on
},
d = function () {
function t(e, o) {
return void 0 === o && (o = ""), this.log("begin setup"), this.el = e, this.els = {}, this.options = l({}, this.defaults, attrobj("module", this.el)), this.moduleName = o || this.el.dataset.module, this.setUps = {
actions: [],
named: [],
options: []
}, this.boundActionRouter = this.actionRouter.bind(this), this.preInit(), this.storeRef(), this.setupActions(), this.setupNamed(), this.verifyRequired(), this.postInit(), this.log("initalized"), t.debug && (this.el.module = this), this;
}
var e,
o = t.prototype;
return o.preInit = function () {}, o.postInit = function () {}, o.verifyRequired = function () {
var t = this;
return this.required === {} || (void 0 !== this.required.options && (this.setUps.options = Object.keys(this.options)), Object.keys(this.required).forEach(function (e) {
t.required[e].forEach(function (o) {
if (t.setUps[e].indexOf(o) < 0) throw new Error(o + " is required as " + e + " for " + t.moduleName + ", but is missing!");
});
})), this;
}, o.setupActions = function () {
var t = this;
this.setupAction(this.el), this.find("[data-action]").forEach(function (e) {
s(e) === t.el && t.setupAction(e);
});
}, o.setupAction = function (e) {
if ("true" !== e.dataset.domoduleActionProcessed) {
var o = t.parseAction(e),
i = o.name,
n = o.type;
i && ("function" == typeof this[i] ? (this.log(i + " bound"), this.storeSetUp(i, "actions"), r.on(e, n, this.boundActionRouter), e.dataset.domoduleActionProcessed = "true") : this.log(i + " was registered, but there is no function set up"));
}
}, o.actionRouter = function (e) {
var o = e.currentTarget,
n = t.parseAction(o).name,
s = attrobj("action", o);
this[n].call(this, o, e, s);
}, o.setupNamed = function () {
var t = this;
this.find("[data-name]").forEach(function (e) {
s(e) === t.el && (e.dataset.domoduleNameProcessed || (t.els[e.dataset.name] = e, t.storeSetUp(e.dataset.name, "named"), e.dataset.domoduleNameProcessed = "true", e.dataset.domoduleOwner = t.id));
});
}, o.storeRef = function () {
if (void 0 === window.domorefs && (window.domorefs = {}), void 0 !== window.domorefs[this.el.dataset.moduleUid]) return !1;
this.id = this.uuid, this.el.dataset.moduleUid = this.id, window.domorefs[this.el.dataset.moduleUid] = this;
}, o.find = function (t) {
return r.find(t, this.el);
}, o.findOne = function (t) {
return r.findOne(t, this.el);
}, o.findByName = function (t) {
return this.els[t];
}, o.getOption = function (t) {
return this.options[t];
}, o.storeSetUp = function (t, e) {
this.setUps[e].indexOf(t) < 0 && this.setUps[e].push(t);
}, o.destroy = function () {
var e = this;
r.find("[data-action]", this.el.parentNode).forEach(function (o) {
if ("true" === o.dataset.domoduleActionProcessed) {
var i = t.parseAction(o);
o.removeEventListener(i.type, e.boundActionRouter), o.dataset.domoduleActionProcessed = "false";
}
});
}, t.parseAction = function (t) {
var e = t.dataset,
o = e.actionType;
return {
name: e.action,
type: void 0 === o ? "click" : o
};
}, t.getInstance = function (t) {
if (t instanceof Node) return window.domorefs[t.dataset.moduleUid];
throw new Error("getInstance expects a dom node");
}, t.register = function (e, o) {
"function" == typeof e && (e = (o = e).prototype.constructor.name), window.domodules || (window.domodules = {}), t.log("Registering " + e), window.domodules[e] = o;
}, t.discover = function (e) {
if (void 0 === e && (e = "body"), t.log("Discovering modules..."), window.domodules) {
var o;
o = e instanceof Node ? [e] : Array.isArray(e) ? e : r.find(e);
var i = [];
return o.forEach(function (e) {
r.find("[data-module]", e).forEach(function (e) {
var o = e.dataset.module;
if (o && "function" == typeof window.domodules[o]) {
if ("object" == typeof window.domorefs && void 0 !== window.domorefs[e.dataset.moduleUid]) return;
t.log(o + " found"), i.push(new window.domodules[o](e));
}
});
}), i;
}
t.log("No modules found");
}, o.log = function (e) {
t.log(this.constructor.name + ": " + e);
}, t.log = function (e) {
t.debug && console.log("[DOMODULE] " + e);
}, (e = [{
key: "required",
get: function get() {
return {};
}
}, {
key: "defaults",
get: function get() {
return {};
}
}, {
key: "uuid",
get: function get() {
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (t) {
var e = 16 * Math.random() | 0;
return ("x" === t ? e : 3 & e | 8).toString(16);
});
}
}]) && function (t, e) {
for (var o = 0; o < e.length; o++) {
var i = e[o];
i.enumerable = i.enumerable || !1, i.configurable = !0, "value" in i && (i.writable = !0), Object.defineProperty(t, i.key, i);
}
}(t.prototype, e), t;
}();
d.debug = "object" == typeof window.localStorage && window.localStorage.getItem("DomoduleDebug"), d.autoDiscover = !0, window.addEventListener("DOMContentLoaded", function () {
d.autoDiscover && d.discover();
});
var BASE_URLS = {
facebook: 'https://www.facebook.com/sharer/sharer.php',
linkedin: 'https://www.linkedin.com/shareArticle',
pinterest: 'https://pinterest.com/pin/create/button',
reddit: 'https://reddit.com/submit',
twitter: 'https://twitter.com/intent/tweet',
bluesky: 'https://bsky.app/intent/compose',
whatsapp: 'https://api.whatsapp.com/send'
};
var SocialShareButton =
/*#__PURE__*/
function (_Domodule) {
_inheritsLoose(SocialShareButton, _Domodule);
function SocialShareButton() {
return _Domodule.apply(this, arguments) || this;
}
var _proto = SocialShareButton.prototype;
_proto.postInit = function postInit() {
var _this = this;
var setupMethod = this.options.net + "Setup";
var shareMethod = this.options.net + "Share";
if (!this[shareMethod] && !this[setupMethod]) {
throw new Error("Sharing method for " + this.options.net + " is not implemented");
}
if (this[setupMethod]) {
this[setupMethod]();
}
if (this[shareMethod]) {
on(this.el, 'click', function (event) {
event.preventDefault();
_this[shareMethod]();
});
}
};
_proto.getShareUrl = function getShareUrl() {
var url = window.location.href;
if (this.options.baseUrl) {
if (this.options.relative) {
url = "" + window.location.origin + window.location.pathname + this.options.baseUrl;
} else {
url = this.options.baseUrl;
}
}
return url;
};
_proto.twitterShare = function twitterShare() {
SocialShareButton.openWindow(this.el.href, '260', '500', 'twitterWindow');
};
_proto.blueSkyShare = function blueSkyShare() {
SocialShareButton.openWindow(this.el.href, '260', '500', 'blueskyWindow');
};
_proto.linkedinShare = function linkedinShare() {
SocialShareButton.openWindow(this.el.href, '520', '570', 'linkedinWindow');
};
_proto.pinterestShare = function pinterestShare() {
SocialShareButton.openWindow(this.el.href, '600', '600', 'pinterestWindow');
};
_proto.redditShare = function redditShare() {
SocialShareButton.openWindow(this.el.href, '600', '600', 'redditWindow');
};
_proto.whatsappShare = function whatsappShare() {
SocialShareButton.openWindow(this.el.href, '550', '400', 'whatsappWindow');
};
_proto.facebookShare = function facebookShare() {
if (typeof window.FB !== 'undefined' && typeof window.FB.ui !== 'undefined') {
var object = {
method: 'share',
href: this.getShareUrl()
};
if (this.options.tag) {
object.hashtag = "#" + this.options.tag;
}
if (this.options.text) {
object.quote = this.options.text;
}
FB.ui(object);
} else {
SocialShareButton.openWindow(this.el.href, '440', '600', 'facebookWindow');
}
};
_proto.facebookSetup = function facebookSetup() {
var params = ["u=" + this.getShareUrl()];
if (this.options.tag) {
params.push("hashtag=" + encodeURIComponent("#" + this.options.tag));
}
if (this.options.text) {
params.push("quote=" + encodeURIComponent(this.options.text));
}
this.el.href = BASE_URLS.facebook + "?" + params.join('&');
};
_proto.emailSetup = function emailSetup() {
var title = encodeURIComponent(this.options.subject || document.title);
var body = this.options.body || 'Check this out #url';
body = body.replace(/#url/gi, this.getShareUrl());
body = encodeURIComponent(body);
this.el.href = "mailto:?subject=" + title + "&body=" + body;
};
_proto.linkedinSetup = function linkedinSetup() {
// linkedin only allows the url param for security reasons:
this.el.href = BASE_URLS.linkedin + "?mini=true&url=" + encodeURIComponent(this.getShareUrl());
};
_proto.twitterSetup = function twitterSetup() {
var shareText = this.options.text || SocialShareButton.getMeta('text', 'twi');
var shareTag = this.options.tags || SocialShareButton.getMeta('hashtag', 'twi');
var shareVia = this.options.via || SocialShareButton.getMeta('author', 'twi');
var shareImage = this.options.image || SocialShareButton.getMeta('image', 'twi');
var params = [];
params.push("url=" + encodeURIComponent(this.getShareUrl()));
if (shareText) {
params.push("text=" + encodeURIComponent(shareText));
}
if (shareTag && shareTag !== 'none') {
params.push("hashtags=" + encodeURIComponent(shareTag));
}
if (shareVia && shareVia !== 'none') {
params.push("via=" + encodeURIComponent(shareVia));
}
if (shareImage) {
params.push("media=" + encodeURIComponent(shareImage));
}
this.el.href = BASE_URLS.twitter + "?" + params.join('&');
};
_proto.blueskySetup = function blueskySetup() {
var shareText = this.options.text || SocialShareButton.getMeta('text', 'twi');
var params = [];
var fullText = shareText + "\n" + this.getShareUrl();
if (shareText) {
params.push("text=" + encodeURIComponent(fullText));
}
this.el.href = BASE_URLS.bluesky + "?" + params.join('&');
};
_proto.pinterestSetup = function pinterestSetup() {
var shareTitle = this.options.title || SocialShareButton.getMeta('title');
var shareMedia = this.options.media || SocialShareButton.getMeta('image');
var params = ["url=" + encodeURIComponent(this.getShareUrl())];
if (shareTitle) {
params.push("description=" + encodeURIComponent(shareTitle));
}
if (shareMedia) {
params.push("media=" + encodeURIComponent(shareMedia));
}
this.el.href = BASE_URLS.pinterest + "?" + params.join('&');
};
_proto.redditSetup = function redditSetup() {
var shareTitle = this.options.title;
var params = ["url=" + encodeURIComponent(this.getShareUrl())];
if (shareTitle) {
params.push("title=" + encodeURIComponent(shareTitle));
}
this.el.href = BASE_URLS.reddit + "?" + params.join('&');
};
_proto.whatsappSetup = function whatsappSetup() {
var shareText = this.options.text || SocialShareButton.getMeta('text');
var params = [];
if (shareText) {
params.push("text=" + encodeURIComponent(shareText));
}
this.el.href = BASE_URLS.whatsapp + "?" + params.join('&');
};
SocialShareButton.getMeta = function getMeta(tag, prop) {
if (prop === void 0) {
prop = 'og';
}
var meta = findOne("meta[property=\"" + prop + ":" + tag + "\"]");
return meta ? meta.getAttribute('content') : null;
};
SocialShareButton.openWindow = function openWindow(url, height, width, key) {
window.open(url, key, "menubar=no,toolbar=no,left=200,top=200,resizable=yes,scrollbars=no,height=" + height + ",width=" + width);
};
_createClass(SocialShareButton, [{
key: "required",
get: function get() {
return {
options: ['net']
};
}
}, {
key: "defaults",
get: function get() {
return {
relative: false,
baseUrl: false
};
}
}]);
return SocialShareButton;
}(d);
d.register('SocialShareButton', SocialShareButton);
return SocialShareButton;
}());
//# sourceMappingURL=social-share-button.bundle.js.map