shareon/src/shareon.js

81 lines
2.6 KiB
JavaScript
Raw Normal View History

2020-07-31 12:18:17 -04:00
// eslint-disable-next-line import/no-unresolved
import urlBuilderMap from 'consts:urlBuilderMap';
2020-03-25 16:47:00 -04:00
2020-07-31 12:18:17 -04:00
const initializeShareon = () => {
2020-03-25 16:47:00 -04:00
const shareonContainers = document.getElementsByClassName('shareon');
// iterate over <div class="shareon">
2020-03-25 16:47:00 -04:00
for (let i = 0; i < shareonContainers.length; i += 1) {
2020-07-31 12:18:17 -04:00
/** @type Element */
const container = shareonContainers[i];
2020-03-25 16:47:00 -04:00
// iterate over children of <div class="shareon">
2020-03-25 16:47:00 -04:00
for (let j = 0; j < container.children.length; j += 1) {
2020-07-31 12:18:17 -04:00
/** @type Element */
const child = container.children[j];
2020-03-25 16:47:00 -04:00
if (child) {
const classListLength = child.classList.length;
2020-03-25 16:47:00 -04:00
// iterate over classes of the child element
for (let k = 0; k < classListLength; k += 1) {
const cls = child.classList.item(k);
// if it's one of the networks
2020-07-31 12:16:59 -04:00
if (Object.prototype.hasOwnProperty.call(urlBuilderMap, cls)) {
const preset = {
url: encodeURIComponent(
child.dataset.url
2020-07-31 12:18:17 -04:00
|| container.dataset.url
|| window.location.href,
),
title: encodeURIComponent(
child.dataset.title
2020-07-31 12:18:17 -04:00
|| container.dataset.title
|| document.title,
),
media: encodeURIComponent(
child.dataset.media
2020-07-31 12:18:17 -04:00
|| container.dataset.media
|| '',
),
text: encodeURIComponent(
child.dataset.text
2020-07-31 12:18:17 -04:00
|| container.dataset.text
|| '',
),
via: encodeURIComponent(
child.dataset.via
2020-07-31 12:18:17 -04:00
|| container.dataset.via
|| '',
),
fbAppId: encodeURIComponent(
child.dataset.fbAppId
|| container.dataset.fbAppId
|| '',
),
};
2020-07-31 12:16:59 -04:00
const url = urlBuilderMap[cls](preset);
if (child.tagName.toLowerCase() === 'a') {
child.setAttribute('href', url);
child.setAttribute('rel', 'noopener noreferrer');
child.setAttribute('target', '_blank');
} else {
2020-09-18 14:24:22 -04:00
const getButtonListener = (buttonUrl) => () => {
window.open(buttonUrl, '_blank', 'noopener,noreferrer');
};
child.addEventListener('click', getButtonListener(url));
}
break; // once a network is detected we don't want to check further
}
}
}
2020-03-25 16:47:00 -04:00
}
}
};
export default initializeShareon;