-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
86 lines (79 loc) · 2.88 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
class RevShare extends HTMLElement {
connectedCallback() {
this.style.margin = "0";
this.style.padding = "0";
if (this.hasAttribute('exclusive')){
this.classList.add('rs-excl-hid');
}
}
attributeChangedCallback() {
if (!this.hasAttribute('pointers')){
throw "RevSharePointerError: revshare pointer list cannot be found. Check that it exists and is correctly formatted.";
}
else{
this.checkParsedPointers();
genMeta();
}
}
disconnectedCallback() {
if (document.getElementsByTagName('rev-share').length == 0){
console.warn('RevShareNoElementsWarning: no revshare elements found. Check this is the intended behaviour, and reset the monetization pointer.');
}
else{
genMeta();
}
}
static get observedAttributes() {
return ['pointers'];
}
checkParsedPointers() {
var parsedPointers = JSON.parse(this.getAttribute('pointers'));
Object.values(parsedPointers).forEach(function (item){
if (typeof item !== 'number'){
throw "RevShareProportionTypeError: revshare proportions are of incorrect type. Check that your pointers attribute is correctly formatted.";
}
});
if (Object.values(parsedPointers).reduce((a, b) => a + b) != 100) {
console.warn('RevShareProportionSumWarning: revshare proportions do not sum to 100. Check that these proportions are correct.');
}
}
}
if ('customElements' in window){
customElements.define('rev-share', RevShare);
}
function pickPointer() {
var revEls = document.getElementsByTagName('rev-share');
var p = Math.floor(Math.random() * revEls.length);
const sum = revEls[p] && Object.values(revEls[p]).reduce((sum, weight) => sum + weight, 0);
let choice = Math.random() * sum;
if (typeof revEls[p] !== "undefined") {
var choices = JSON.parse(revEls[p].getAttribute('pointers'));
for (const pointer in choices) {
const weight = choices[pointer];
if ((choice -= weight) <= 0) {
return pointer;
}
}
}
}
function genMeta() {
var x = document.querySelector("[name='monetization']")
if(x) {
x.remove();
}
const monTag = document.createElement('meta');
monTag.name = 'monetization';
monTag.content = pickPointer();
document.head.appendChild(monTag);
}
var element = document.createElement("style");
element.innerHTML = ".rs-excl-hid {display: none;}";
document.head.appendChild(element);
window.addEventListener('load', () => {
genMeta();
});
if (document.monetization) {
document.monetization.addEventListener('monetizationstart', () => {
Array.from(document.querySelectorAll('rev-share[exclusive]')).forEach(i => i.classList.remove('rs-excl-hid'));
});
}