chore: format code with Prettier

This commit is contained in:
github-actions[bot] 2024-05-27 22:04:23 +00:00
parent d25b2f97c2
commit cc39111694
37 changed files with 21815 additions and 6019 deletions

View file

@ -41,9 +41,11 @@ And there is more to come!
# Supported Browsers # Supported Browsers
As of right now, Poly+ only works on Chromium-based browsers. Currently, there are no plans to bring it to other browsers in the future. As of right now, Poly+ only works on Chromium-based browsers. Currently, there are no plans to bring it to other browsers in the future.
> TL;DR Chromium-based browsers > TL;DR Chromium-based browsers
## Examples of Browsers that are Chromium-based ## Examples of Browsers that are Chromium-based
- Google Chrome - Google Chrome
- Chromium - Chromium
- Edge - Edge
@ -56,12 +58,12 @@ As of right now, Poly+ only works on Chromium-based browsers. Currently, there a
## How to Download - Stable Build? ## How to Download - Stable Build?
1. Go to the releases section of this GitHub repository 1. Go to the releases section of this GitHub repository
3. Go to the latest release and download the .ZIP file for that release 2. Go to the latest release and download the .ZIP file for that release
4. Extract the .ZIP 3. Extract the .ZIP
5. Enable developer mode on your browser (developer mode allows you to load unpacked extensions) 4. Enable developer mode on your browser (developer mode allows you to load unpacked extensions)
6. Click the "Load Unpacked" button 5. Click the "Load Unpacked" button
7. When the file selector comes up, open the unzipped folder from this GitHub repository 6. When the file selector comes up, open the unzipped folder from this GitHub repository
8. Go to Polytoria and you should see some changes! 7. Go to Polytoria and you should see some changes!
## How to Download - Pre-Release Build? ## How to Download - Pre-Release Build?
@ -73,6 +75,6 @@ As of right now, Poly+ only works on Chromium-based browsers. Currently, there a
4. Extract the .ZIP 4. Extract the .ZIP
5. Enable developer mode on your browser (developer mode allows you to load unpacked extensions) 5. Enable developer mode on your browser (developer mode allows you to load unpacked extensions)
6. Go to your browsers extensions page (usually `browserName://extensions`) 6. Go to your browsers extensions page (usually `browserName://extensions`)
8. Click the "Load Unpacked" button 7. Click the "Load Unpacked" button
9. When the file selector comes up, open the unzipped folder of this repository's source code 8. When the file selector comes up, open the unzipped folder of this repository's source code
10. Go to Polytoria and you should see some changes! 9. Go to Polytoria and you should see some changes!

File diff suppressed because one or more lines are too long

View file

@ -2,22 +2,22 @@
FRONTEND FIXES / SPACING IMPROVEMENTS FRONTEND FIXES / SPACING IMPROVEMENTS
*/ */
body[data-URL^="/my/friends"] .col-lg-3 { body[data-URL^='/my/friends'] .col-lg-3 {
margin-bottom: 20px; margin-bottom: 20px;
} }
body[data-URL^="/create/"] .mt-2.mt-lg-0.col-lg.d-flex.align-content-between.flex-wrap { body[data-URL^='/create/'] .mt-2.mt-lg-0.col-lg.d-flex.align-content-between.flex-wrap {
width: 50%; width: 50%;
} }
body[data-URL^="/create/"] .col.d-flex.align-content-between.flex-wrap { body[data-URL^='/create/'] .col.d-flex.align-content-between.flex-wrap {
width: 50%; width: 50%;
} }
.text-truncate { .text-truncate {
white-space: nowrap !important; white-space: nowrap !important;
overflow: hidden !important; overflow: hidden !important;
text-overflow: ellipsis !important; text-overflow: ellipsis !important;
} }
/* ------------------------------------------ */ /* ------------------------------------------ */
@ -26,11 +26,19 @@ body[data-URL^="/create/"] .col.d-flex.align-content-between.flex-wrap {
INLINE EDITING INLINE EDITING
*/ */
body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-visible {display: block !important;} body[data-polyplus-inlineEditing='true'] .polyplus-inlineEditing-visible {
.polyplus-inlineEditing-visible {display: none;} display: block !important;
}
.polyplus-inlineEditing-visible {
display: none;
}
body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-hidden {display: none !important;} body[data-polyplus-inlineEditing='true'] .polyplus-inlineEditing-hidden {
.polyplus-inlineEditing-hidden {display: block;} display: none !important;
}
.polyplus-inlineEditing-hidden {
display: block;
}
/* ------------------------------------------ */ /* ------------------------------------------ */
@ -38,12 +46,13 @@ body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-hidden {display
MODALS MODALS
*/ */
html:has(.polyplus-modal[open]), body:has(.polyplus-modal[open]) { html:has(.polyplus-modal[open]),
overflow: hidden; body:has(.polyplus-modal[open]) {
overflow: hidden;
} }
.polyplus-modal::backdrop { .polyplus-modal::backdrop {
background: rgba(0, 0, 0, 0.73); background: rgba(0, 0, 0, 0.73);
} }
/* ------------------------------------------ */ /* ------------------------------------------ */

View file

@ -1,24 +1,24 @@
let PageContainer = document.querySelector('.container.p-0.p-lg-5') let PageContainer = document.querySelector('.container.p-0.p-lg-5');
let ItemGrid; let ItemGrid;
let Wearing; let Wearing;
let Tabs; let Tabs;
let IFrame; let IFrame;
let TabSelected = 'hat' let TabSelected = 'hat';
let Search; let Search;
let Page = 1 let Page = 1;
let Avatar = { let Avatar = {
"useCharacter": true, useCharacter: true,
"items": [], items: [],
"shirt": null, shirt: null,
"pants": null, pants: null,
"tool": {ID: -1, URL: null}, tool: {ID: -1, URL: null},
"headColor": "#e0e0e0", headColor: '#e0e0e0',
"torsoColor": "#e0e0e0", torsoColor: '#e0e0e0',
"leftArmColor": "#e0e0e0", leftArmColor: '#e0e0e0',
"rightArmColor": "#e0e0e0", rightArmColor: '#e0e0e0',
"leftLegColor": "#e0e0e0", leftLegColor: '#e0e0e0',
"rightLegColor": "#e0e0e0" rightLegColor: '#e0e0e0'
} };
let ItemCardContents = ` let ItemCardContents = `
<div style="max-width: 150px;"> <div style="max-width: 150px;">
<div class="card mb-2 avatar-item-container"> <div class="card mb-2 avatar-item-container">
@ -37,336 +37,353 @@ let ItemCardContents = `
by <a href="/users/:CreatorID" class="text-reset">:CreatorName</a> by <a href="/users/:CreatorID" class="text-reset">:CreatorName</a>
</small> </small>
</div> </div>
` `;
if (new URLSearchParams(new URL(window.location).search).get('sandbox') === 'true') { if (new URLSearchParams(new URL(window.location).search).get('sandbox') === 'true') {
console.log('Avatar Sandbox!') console.log('Avatar Sandbox!');
LoadFile(chrome.runtime.getURL('resources/avatar-sandbox.html'), function(html){ LoadFile(chrome.runtime.getURL('resources/avatar-sandbox.html'), function (html) {
PageContainer.innerHTML = html PageContainer.innerHTML = html;
ItemGrid = document.getElementById('inventory') ItemGrid = document.getElementById('inventory');
Wearing = document.getElementById('wearing') Wearing = document.getElementById('wearing');
Tabs = document.getElementById('tabs') Tabs = document.getElementById('tabs');
IFrame = document.getElementById('viewFrame') IFrame = document.getElementById('viewFrame');
Search = document.getElementById('item-search') Search = document.getElementById('item-search');
Search.addEventListener('change', function(){ Search.addEventListener('change', function () {
RefreshItems() RefreshItems();
}); });
UpdateAvatar() UpdateAvatar();
RefreshItems() RefreshItems();
Array.from(Tabs.children).forEach(element => { Array.from(Tabs.children).forEach((element) => {
element.addEventListener('click', function(){ element.addEventListener('click', function () {
let Link = element.getElementsByTagName('a')[0] let Link = element.getElementsByTagName('a')[0];
if (!(Link.classList.contains('active'))) { if (!Link.classList.contains('active')) {
Link.classList.add('active') Link.classList.add('active');
Tabs.querySelector(`[data-tab="${TabSelected}"]`).classList.remove('active') Tabs.querySelector(`[data-tab="${TabSelected}"]`).classList.remove('active');
TabSelected = Link.getAttribute('data-tab') TabSelected = Link.getAttribute('data-tab');
Page = 1 Page = 1;
RefreshItems() RefreshItems();
} }
}); });
}); });
let Clear = document.getElementById('clear') let Clear = document.getElementById('clear');
Clear.addEventListener('click', function(){ Clear.addEventListener('click', function () {
Avatar = { Avatar = {
"useCharacter": true, useCharacter: true,
"items": [], items: [],
"shirt": {ID: -1, URL: null}, shirt: {ID: -1, URL: null},
"pants": {ID: -1, URL: null}, pants: {ID: -1, URL: null},
"tool": {ID: -1, URL: null}, tool: {ID: -1, URL: null},
"headColor": "#e0e0e0", headColor: '#e0e0e0',
"torsoColor": "#e0e0e0", torsoColor: '#e0e0e0',
"leftArmColor": "#e0e0e0", leftArmColor: '#e0e0e0',
"rightArmColor": "#e0e0e0", rightArmColor: '#e0e0e0',
"leftLegColor": "#e0e0e0", leftLegColor: '#e0e0e0',
"rightLegColor": "#e0e0e0" rightLegColor: '#e0e0e0'
} };
UpdateAvatar() UpdateAvatar();
}); });
let JSONUpload = document.getElementById('jsonUpload') let JSONUpload = document.getElementById('jsonUpload');
JSONUpload.addEventListener('change', function(){ JSONUpload.addEventListener('change', function () {
let Reader = new FileReader() let Reader = new FileReader();
Reader.addEventListener('loadend', function(){ Reader.addEventListener('loadend', function () {
Avatar = JSON.parse(Reader.result) Avatar = JSON.parse(Reader.result);
UpdateAvatar() UpdateAvatar();
JSONUpload.value = "" JSONUpload.value = '';
}); });
Reader.readAsText(JSONUpload.files[0]) Reader.readAsText(JSONUpload.files[0]);
}); });
let JSONSave = document.getElementById('jsonSave') let JSONSave = document.getElementById('jsonSave');
JSONSave.addEventListener('click', function(){ JSONSave.addEventListener('click', function () {
FormatAvatar().then(FormattedAvatar => { FormatAvatar().then((FormattedAvatar) => {
let Download = document.createElement('a') let Download = document.createElement('a');
Download.href = URL.createObjectURL(new Blob([JSON.stringify(FormattedAvatar)], { Download.href = URL.createObjectURL(
type: "application/json" new Blob([JSON.stringify(FormattedAvatar)], {
})); type: 'application/json'
Download.setAttribute('download', 'AvatarSandbox.json') })
document.body.appendChild(Download) );
Download.click() Download.setAttribute('download', 'AvatarSandbox.json');
document.body.removeChild(Download) document.body.appendChild(Download);
}); Download.click();
}); document.body.removeChild(Download);
});
});
let OpenInNewTab = document.getElementById('openNewTab') let OpenInNewTab = document.getElementById('openNewTab');
OpenInNewTab.addEventListener('click', function(){ OpenInNewTab.addEventListener('click', function () {
UpdateAvatar() UpdateAvatar();
}); });
}); });
} }
function UpdateAvatar() { function UpdateAvatar() {
GenerateHash() GenerateHash().then((hash) => {
.then(hash => { IFrame.addEventListener('load', function () {
IFrame.addEventListener('load', function () { IFrame.src = 'https://polytoria.com/ptstatic/itemview/#' + hash;
IFrame.src = 'https://polytoria.com/ptstatic/itemview/#' + hash; });
}); IFrame.src = 'about:blank';
IFrame.src = 'about:blank'; });
});
} }
function LoadFile(path, callback) { function LoadFile(path, callback) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.onload = function () { return callback(this.responseText); } xhr.onload = function () {
xhr.open("GET", path, true); return callback(this.responseText);
xhr.send(); };
xhr.open('GET', path, true);
xhr.send();
} }
async function GenerateHash() { async function GenerateHash() {
let FormattedAvatar = await FormatAvatar() let FormattedAvatar = await FormatAvatar();
for (let i = 0; i < FormattedAvatar.items.length; i++) { for (let i = 0; i < FormattedAvatar.items.length; i++) {
FormattedAvatar.items[i] = FormattedAvatar.items[i].URL FormattedAvatar.items[i] = FormattedAvatar.items[i].URL;
} }
if (FormattedAvatar.shirt) { if (FormattedAvatar.shirt) {
FormattedAvatar.shirt = FormattedAvatar.shirt.URL FormattedAvatar.shirt = FormattedAvatar.shirt.URL;
} }
if (FormattedAvatar.pants) { if (FormattedAvatar.pants) {
FormattedAvatar.pants = FormattedAvatar.pants.URL FormattedAvatar.pants = FormattedAvatar.pants.URL;
} }
FormattedAvatar.face = FormattedAvatar.face.URL FormattedAvatar.face = FormattedAvatar.face.URL;
if (FormattedAvatar.tool) { if (FormattedAvatar.tool) {
FormattedAvatar.tool = FormattedAvatar.tool.URL FormattedAvatar.tool = FormattedAvatar.tool.URL;
} }
console.log('Formatted Avatar: ', FormattedAvatar) console.log('Formatted Avatar: ', FormattedAvatar);
console.log('Real Avatar: ', Avatar) console.log('Real Avatar: ', Avatar);
return btoa(encodeURIComponent(JSON.stringify(FormattedAvatar))) return btoa(encodeURIComponent(JSON.stringify(FormattedAvatar)));
} }
async function FormatAvatar() { async function FormatAvatar() {
let LocalAvatar = structuredClone(Avatar) let LocalAvatar = structuredClone(Avatar);
if (!LocalAvatar.face) { if (!LocalAvatar.face) {
LocalAvatar.face = {ID: -1, URL: "https://c0.ptacdn.com/static/3dview/DefaultFace.png"} LocalAvatar.face = {ID: -1, URL: 'https://c0.ptacdn.com/static/3dview/DefaultFace.png'};
} }
for (let i = 0; i < LocalAvatar.items.length; i++) { for (let i = 0; i < LocalAvatar.items.length; i++) {
if (LocalAvatar.items[i].URL === null) { if (LocalAvatar.items[i].URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve-mesh/:id".replace(':id', LocalAvatar.items[i].ID)) await fetch('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', LocalAvatar.items[i].ID))
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
} }
return response.json(); return response.json();
}) })
.then(data => { .then((data) => {
Avatar.items[i].URL = data.url Avatar.items[i].URL = data.url;
LocalAvatar.items[i].URL = data.url LocalAvatar.items[i].URL = data.url;
}) })
.catch(error => { .catch((error) => {
console.error('Fetch error:', error); console.error('Fetch error:', error);
}); });
} }
} }
if (LocalAvatar.tool && LocalAvatar.tool.ID !== -1 && LocalAvatar.tool.URL === null) { if (LocalAvatar.tool && LocalAvatar.tool.ID !== -1 && LocalAvatar.tool.URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve-mesh/:id".replace(':id', LocalAvatar.tool.ID)) await fetch('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', LocalAvatar.tool.ID))
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
} }
return response.json(); return response.json();
}) })
.then(data => { .then((data) => {
Avatar.tool.URL = data.url Avatar.tool.URL = data.url;
LocalAvatar.tool.URL = data.url LocalAvatar.tool.URL = data.url;
}) })
.catch(error => { .catch((error) => {
console.error('Fetch error:', error); console.error('Fetch error:', error);
}); });
} }
if (LocalAvatar.face.ID !== -1 && LocalAvatar.face.URL === null) { if (LocalAvatar.face.ID !== -1 && LocalAvatar.face.URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve/:id/Asset".replace(':id', LocalAvatar.face.ID)) await fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', LocalAvatar.face.ID))
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
} }
return response.json(); return response.json();
}) })
.then(data => { .then((data) => {
Avatar.face.URL = data.url Avatar.face.URL = data.url;
LocalAvatar.face.URL = data.url LocalAvatar.face.URL = data.url;
}) })
.catch(error => { .catch((error) => {
console.error('Fetch error:', error); console.error('Fetch error:', error);
}); });
} }
if (LocalAvatar.shirt && LocalAvatar.shirt.ID !== -1 && LocalAvatar.shirt.URL === null) { if (LocalAvatar.shirt && LocalAvatar.shirt.ID !== -1 && LocalAvatar.shirt.URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve/:id/Asset".replace(':id', LocalAvatar.shirt.ID)) await fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', LocalAvatar.shirt.ID))
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
} }
return response.json(); return response.json();
}) })
.then(data => { .then((data) => {
Avatar.shirt.URL = data.url Avatar.shirt.URL = data.url;
LocalAvatar.shirt.URL = data.url LocalAvatar.shirt.URL = data.url;
}) })
.catch(error => { .catch((error) => {
console.error('Fetch error:', error); console.error('Fetch error:', error);
}); });
} }
if (LocalAvatar.pants && LocalAvatar.pants.ID !== -1 && LocalAvatar.pants.URL === null) { if (LocalAvatar.pants && LocalAvatar.pants.ID !== -1 && LocalAvatar.pants.URL === null) {
await fetch("https://api.polytoria.com/v1/assets/serve/:id/Asset".replace(':id', LocalAvatar.pants.ID)) await fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', LocalAvatar.pants.ID))
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
} }
return response.json(); return response.json();
}) })
.then(data => { .then((data) => {
Avatar.pants.URL = data.url Avatar.pants.URL = data.url;
LocalAvatar.pants.URL = data.url LocalAvatar.pants.URL = data.url;
}) })
.catch(error => { .catch((error) => {
console.error('Fetch error:', error); console.error('Fetch error:', error);
}); });
} }
return LocalAvatar return LocalAvatar;
} }
function RefreshItems() { function RefreshItems() {
fetch(`https://api.polytoria.com/v1/store?search=${Search.value}&types%5B%5D=${TabSelected}&sort=createdAt&order=desc&page=${Page}&limit=12`) fetch(`https://api.polytoria.com/v1/store?search=${Search.value}&types%5B%5D=${TabSelected}&sort=createdAt&order=desc&page=${Page}&limit=12`)
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
} }
return response.json(); return response.json();
}) })
.then(data => { .then((data) => {
Array.from(ItemGrid.children).forEach(element => {element.remove()}); Array.from(ItemGrid.children).forEach((element) => {
data = data.assets element.remove();
data.forEach(item => { });
let NewItemCard = document.createElement('div') data = data.assets;
NewItemCard.classList = 'col-auto' data.forEach((item) => {
NewItemCard.innerHTML = ItemCardContents.replace(':ItemName', item.name).replace().replace(':ItemID', item.id).replace(':ItemType', item.type.replace(item.type.charAt(0), item.type.charAt(0).toUpperCase())).replace(':CreatorName', item.creator.name).replace(':CreatorID', item.creator.id).replace(':ItemThumbnail', item.thumbnail) let NewItemCard = document.createElement('div');
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function(){ NewItemCard.classList = 'col-auto';
WearAsset(NewItemCard, item.name, {Name: item.creator.name, ID: item.creator.id}, item.id, item.type, item.thumbnail) NewItemCard.innerHTML = ItemCardContents.replace(':ItemName', item.name)
}); .replace()
.replace(':ItemID', item.id)
.replace(':ItemType', item.type.replace(item.type.charAt(0), item.type.charAt(0).toUpperCase()))
.replace(':CreatorName', item.creator.name)
.replace(':CreatorID', item.creator.id)
.replace(':ItemThumbnail', item.thumbnail);
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function () {
WearAsset(NewItemCard, item.name, {Name: item.creator.name, ID: item.creator.id}, item.id, item.type, item.thumbnail);
});
ItemGrid.appendChild(NewItemCard) ItemGrid.appendChild(NewItemCard);
}); });
}) })
.catch(error => { .catch((error) => {
console.error('Fetch error:', error); console.error('Fetch error:', error);
}); });
} }
function WearAsset(element, name, creator, id, type, thumbnail) { function WearAsset(element, name, creator, id, type, thumbnail) {
switch (type) { switch (type) {
case 'hat': case 'hat':
let Index = CheckItemID(Avatar.items, id) let Index = CheckItemID(Avatar.items, id);
if (Index === -1) { if (Index === -1) {
if (Avatar.items.length !== 3) { if (Avatar.items.length !== 3) {
Avatar.items.push({Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail}) Avatar.items.push({Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail});
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} else { } else {
Avatar.items.splice(0, 1) Avatar.items.splice(0, 1);
Avatar.items.push({Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail}) Avatar.items.push({Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail});
if (TabSelected === type) { if (TabSelected === type) {
console.log('tab is', TabSelected, type) console.log('tab is', TabSelected, type);
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} }
} }
} else { } else {
console.log('remove') console.log('remove');
Avatar.items.splice(Index, 1) Avatar.items.splice(Index, 1);
if (TabSelected === type) { if (TabSelected === type) {
console.log('tab is', TabSelected, type) console.log('tab is', TabSelected, type);
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} }
} }
break break;
case 'face': case 'face':
if (Avatar.face && Avatar.face.ID !== id) { if (Avatar.face && Avatar.face.ID !== id) {
Avatar.face = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail} Avatar.face = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail};
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} else { } else {
Avatar.face = {Name: "Default Face", Creator: {Name: "Polytoria", ID: 1}, ID: -1, URL: "https://c0.ptacdn.com/static/3dview/DefaultFace.png", Thumbnail: "https://c0.ptacdn.com/static/3dview/DefaultFace.png"} Avatar.face = {
if (TabSelected === type) { Name: 'Default Face',
console.log('tab is', TabSelected, type) Creator: {Name: 'Polytoria', ID: 1},
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) ID: -1,
} URL: 'https://c0.ptacdn.com/static/3dview/DefaultFace.png',
} Thumbnail: 'https://c0.ptacdn.com/static/3dview/DefaultFace.png'
break };
case 'tool': if (TabSelected === type) {
if (Avatar.tool && Avatar.tool.ID !== id) { console.log('tab is', TabSelected, type);
Avatar.tool = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail} ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) }
} else { }
Avatar.tool = null break;
if (TabSelected === type) { case 'tool':
console.log('tab is', TabSelected, type) if (Avatar.tool && Avatar.tool.ID !== id) {
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) Avatar.tool = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail};
} Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} } else {
break Avatar.tool = null;
case 'shirt': if (TabSelected === type) {
if (Avatar.shirt.ID !== id) { console.log('tab is', TabSelected, type);
Avatar.shirt = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail} ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) }
} else { }
Avatar.shirt = null break;
if (TabSelected === type) { case 'shirt':
console.log('tab is', TabSelected, type) if (Avatar.shirt.ID !== id) {
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) Avatar.shirt = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail};
} Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} } else {
break Avatar.shirt = null;
case 'pants': if (TabSelected === type) {
if (Avatar.pants.ID !== id) { console.log('tab is', TabSelected, type);
Avatar.pants = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail} ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) }
} else { }
Avatar.pants = null break;
if (TabSelected === type) { case 'pants':
console.log('tab is', TabSelected, type) if (Avatar.pants.ID !== id) {
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`)) Avatar.pants = {Name: name, Creator: creator, ID: id, URL: null, Thumbnail: thumbnail};
} Wearing.prepend(ItemGrid.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
} } else {
break Avatar.pants = null;
} if (TabSelected === type) {
console.log('tab is', TabSelected, type);
ItemGrid.prepend(Wearing.querySelector(`.col-auto:has(a[href="/store/${id}"])`));
}
}
break;
}
UpdateAvatar() UpdateAvatar();
} }
function CheckItemID(object, id) { function CheckItemID(object, id) {
for (let i = 0; i < object.length; i++) { for (let i = 0; i < object.length; i++) {
if (object[i] === id || object[i].ID === id) { if (object[i] === id || object[i].ID === id) {
console.log('Index: ' + i) console.log('Index: ' + i);
return i return i;
} }
} }
return -1 return -1;
} }

View file

@ -1,240 +1,241 @@
const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID;
const BodyColors = [ const BodyColors = [
"#f8f8f8", '#f8f8f8',
"#cdcdcd", '#cdcdcd',
"#111111", '#111111',
"#ff0000", '#ff0000',
"#a34b4b", '#a34b4b',
"#ffc9c9", '#ffc9c9',
"#957977", '#957977',
"#c4281c", '#c4281c',
"#da867a", '#da867a',
"#694028", '#694028',
"#cc8e69", '#cc8e69',
"#a05f35", '#a05f35',
"#7c5c46", '#7c5c46',
"#eab892", '#eab892',
"#da8541", '#da8541',
"#aa5500", '#aa5500',
"#ffcc99", '#ffcc99',
"#e29b40", '#e29b40',
"#ffaf00", '#ffaf00',
"#ffb000", '#ffb000',
"#d7c59a", '#d7c59a',
"#f5cd30", '#f5cd30',
"#fdea8d", '#fdea8d',
"#e5e4df", '#e5e4df',
"#c1be42", '#c1be42',
"#ffff00", '#ffff00',
"#ffffcc", '#ffffcc',
"#a4bd47", '#a4bd47',
"#7f8e64", '#7f8e64',
"#a1c48c", '#a1c48c',
"#3a7d15", '#3a7d15',
"#4b974b", '#4b974b',
"#00ff00", '#00ff00',
"#ccffcc", '#ccffcc',
"#27462d", '#27462d',
"#287f47", '#287f47',
"#789082", '#789082',
"#9ff3e9", '#9ff3e9',
"#12eed4", '#12eed4',
"#f2f3f3", '#f2f3f3',
"#00ffff", '#00ffff',
"#008f9c", '#008f9c',
"#04afec", '#04afec',
"#80bbdb", '#80bbdb',
"#b4d2e4", '#b4d2e4',
"#0d69ac", '#0d69ac',
"#1b2a35", '#1b2a35',
"#afddff", '#afddff',
"#6e99ca", '#6e99ca',
"#74869d", '#74869d',
"#2154b9", '#2154b9',
"#002060", '#002060',
"#0000ff", '#0000ff',
"#b1a7ff", '#b1a7ff',
"#a3a2a5", '#a3a2a5',
"#6225d1", '#6225d1',
"#b480ff", '#b480ff',
"#8c5b9f", '#8c5b9f',
"#6b327c", '#6b327c',
"#aa00aa", '#aa00aa',
"#635f62", '#635f62',
"#ff00bf", '#ff00bf',
"#ff66cc", '#ff66cc',
"#e8bac8" '#e8bac8'
] ];
let PageContainer = document.querySelector('.container.p-0.p-lg-5') let PageContainer = document.querySelector('.container.p-0.p-lg-5');
let ItemGrid; let ItemGrid;
let Wearing; let Wearing;
let Tabs; let Tabs;
let IFrame; let IFrame;
let TabSelected = 'hat' let TabSelected = 'hat';
let Search; let Search;
let Page = 1 let Page = 1;
let Avatar = { let Avatar = {
"useCharacter": true, useCharacter: true,
"items": [ items: [24122],
24122 shirt: 24118,
], pants: 24123,
"shirt": 24118, headColor: '#e0e0e0',
"pants": 24123, torsoColor: '#e0e0e0',
"headColor": "#e0e0e0", leftArmColor: '#e0e0e0',
"torsoColor": "#e0e0e0", rightArmColor: '#e0e0e0',
"leftArmColor": "#e0e0e0", leftLegColor: '#e0e0e0',
"rightArmColor": "#e0e0e0", rightLegColor: '#e0e0e0'
"leftLegColor": "#e0e0e0", };
"rightLegColor": "#e0e0e0"
}
if (new URLSearchParams(window.location.search).has('sandbox')) { if (new URLSearchParams(window.location.search).has('sandbox')) {
console.log('Avatar Sandbox!') console.log('Avatar Sandbox!');
LoadFile(chrome.runtime.getURL('resources/avatar-sandbox.html'), function(html){ LoadFile(chrome.runtime.getURL('resources/avatar-sandbox.html'), function (html) {
PageContainer.innerHTML = html PageContainer.innerHTML = html;
ItemGrid = document.getElementById('inventory') ItemGrid = document.getElementById('inventory');
Wearing = document.getElementById('wearing') Wearing = document.getElementById('wearing');
Tabs = document.getElementById('tabs') Tabs = document.getElementById('tabs');
IFrame = document.getElementById('viewFrame') IFrame = document.getElementById('viewFrame');
Search = document.getElementById('item-search') Search = document.getElementById('item-search');
Search.addEventListener('onchange', function(){ Search.addEventListener('onchange', function () {
RefreshItems() RefreshItems();
}); });
UpdateAvatar() UpdateAvatar();
RefreshItems() RefreshItems();
LoadWearing() LoadWearing();
Array.from(Tabs.children).forEach(element => { Array.from(Tabs.children).forEach((element) => {
element.addEventListener('click', function(){ element.addEventListener('click', function () {
let Link = element.getElementsByTagName('a')[0] let Link = element.getElementsByTagName('a')[0];
if (!(Link.classList.contains('active'))) { if (!Link.classList.contains('active')) {
Link.classList.add('active') Link.classList.add('active');
Tabs.querySelector(`[data-tab="${TabSelected}"]`).classList.remove('active') Tabs.querySelector(`[data-tab="${TabSelected}"]`).classList.remove('active');
TabSelected = Link.getAttribute('data-tab') TabSelected = Link.getAttribute('data-tab');
Page = 1 Page = 1;
RefreshItems() RefreshItems();
} }
}); });
}); });
let Clear = document.getElementById('clear') let Clear = document.getElementById('clear');
Clear.addEventListener('click', function(){ Clear.addEventListener('click', function () {
Avatar = { Avatar = {
"useCharacter": true, useCharacter: true,
"items": [ items: [24122],
24122 shirt: 24118,
], pants: 24123,
"shirt": 24118, headColor: '#e0e0e0',
"pants": 24123, torsoColor: '#e0e0e0',
"headColor": "#e0e0e0", leftArmColor: '#e0e0e0',
"torsoColor": "#e0e0e0", rightArmColor: '#e0e0e0',
"leftArmColor": "#e0e0e0", leftLegColor: '#e0e0e0',
"rightArmColor": "#e0e0e0", rightLegColor: '#e0e0e0'
"leftLegColor": "#e0e0e0", };
"rightLegColor": "#e0e0e0" UpdateAvatar();
} });
UpdateAvatar()
});
let Myself = document.getElementById('myself') let Myself = document.getElementById('myself');
Myself.addEventListener('click', function(){ Myself.addEventListener('click', function () {
LoadMyself() LoadMyself();
}); });
let JSONUpload = document.getElementById('jsonUpload') let JSONUpload = document.getElementById('jsonUpload');
JSONUpload.addEventListener('change', function(){ JSONUpload.addEventListener('change', function () {
let Reader = new FileReader() let Reader = new FileReader();
Reader.addEventListener('loadend', function(){ Reader.addEventListener('loadend', function () {
Avatar = JSON.parse(Reader.result) Avatar = JSON.parse(Reader.result);
UpdateAvatar() UpdateAvatar();
JSONUpload.value = "" JSONUpload.value = '';
}); });
Reader.readAsText(JSONUpload.files[0]) Reader.readAsText(JSONUpload.files[0]);
}); });
let JSONSave = document.getElementById('jsonSave') let JSONSave = document.getElementById('jsonSave');
JSONSave.addEventListener('click', function(){ JSONSave.addEventListener('click', function () {
let Download = document.createElement('a') let Download = document.createElement('a');
Download.href = URL.createObjectURL(new Blob([JSON.stringify(Avatar)], { Download.href = URL.createObjectURL(
type: "application/json" new Blob([JSON.stringify(Avatar)], {
})); type: 'application/json'
Download.setAttribute('download', 'AvatarSandbox.json') })
document.body.appendChild(Download) );
Download.click() Download.setAttribute('download', 'AvatarSandbox.json');
document.body.removeChild(Download) document.body.appendChild(Download);
}); Download.click();
document.body.removeChild(Download);
});
let OpenInNewTab = document.getElementById('openNewTab') let OpenInNewTab = document.getElementById('openNewTab');
OpenInNewTab.addEventListener('click', function(){ OpenInNewTab.addEventListener('click', function () {
UpdateAvatar() UpdateAvatar();
}); });
let LoadAsset = document.getElementById('load-asset') let LoadAsset = document.getElementById('load-asset');
LoadAsset.addEventListener('click', async function(){ LoadAsset.addEventListener('click', async function () {
console.log('clickk') console.log('clickk');
const MeshURL = (await (await fetch('https://api.polytoria.com/v1/assets/serve-mesh/' + LoadAsset.previousElementSibling.value)).json()).url const MeshURL = (await (await fetch('https://api.polytoria.com/v1/assets/serve-mesh/' + LoadAsset.previousElementSibling.value)).json()).url;
Avatar.items.push(MeshURL) Avatar.items.push(MeshURL);
UpdateAvatar() UpdateAvatar();
}) });
}); });
} else { } else {
const SandboxButton = document.createElement('a') const SandboxButton = document.createElement('a');
SandboxButton.classList = 'btn btn-outline-success w-100 mt-3' SandboxButton.classList = 'btn btn-outline-success w-100 mt-3';
SandboxButton.href = '?sandbox=true' SandboxButton.href = '?sandbox=true';
SandboxButton.innerHTML = '<i class="fas fa-shirt"></i> Avatar Sandbox' SandboxButton.innerHTML = '<i class="fas fa-shirt"></i> Avatar Sandbox';
document.getElementById('cont-move').parentElement.appendChild(SandboxButton) document.getElementById('cont-move').parentElement.appendChild(SandboxButton);
} }
function UpdateAvatar() { function UpdateAvatar() {
GenerateHash() GenerateHash().then((hash) => {
.then(hash => { IFrame.addEventListener('load', function () {
IFrame.addEventListener('load', function () { IFrame.src = 'https://polytoria.com/ptstatic/itemview/#' + hash;
IFrame.src = 'https://polytoria.com/ptstatic/itemview/#' + hash; });
}); IFrame.src = 'about:blank';
IFrame.src = 'about:blank'; });
});
} }
function LoadFile(path, callback) { function LoadFile(path, callback) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.onload = function () { return callback(this.responseText); } xhr.onload = function () {
xhr.open("GET", path, true); return callback(this.responseText);
xhr.send(); };
xhr.open('GET', path, true);
xhr.send();
} }
async function GenerateHash(data) { async function GenerateHash(data) {
if (!data) { if (!data) {
console.log('Data not provided') console.log('Data not provided');
let FormattedAvatar = await FormatAvatar() let FormattedAvatar = await FormatAvatar();
return btoa(encodeURIComponent(JSON.stringify(FormattedAvatar))) return btoa(encodeURIComponent(JSON.stringify(FormattedAvatar)));
} else { } else {
console.log('Data provided') console.log('Data provided');
return btoa(encodeURIComponent(JSON.stringify(data))) return btoa(encodeURIComponent(JSON.stringify(data)));
} }
} }
function RefreshItems() { function RefreshItems() {
fetch(`https://api.polytoria.com/v1/store?search=${Search.value}&types%5B%5D=${TabSelected}&sort=createdAt&order=desc&page=${Page}&limit=12`) fetch(`https://api.polytoria.com/v1/store?search=${Search.value}&types%5B%5D=${TabSelected}&sort=createdAt&order=desc&page=${Page}&limit=12`)
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network response was not ok'); throw new Error('Network response was not ok');
} }
return response.json(); return response.json();
}) })
.then(data => { .then((data) => {
Array.from(ItemGrid.children).forEach(element => {element.remove()}); Array.from(ItemGrid.children).forEach((element) => {
data = data.assets element.remove();
data.forEach(item => { });
let NewItemCard = document.createElement('div') data = data.assets;
NewItemCard.setAttribute('data-id', item.id) data.forEach((item) => {
NewItemCard.classList = 'col-auto' let NewItemCard = document.createElement('div');
NewItemCard.innerHTML = ` NewItemCard.setAttribute('data-id', item.id);
NewItemCard.classList = 'col-auto';
NewItemCard.innerHTML = `
<div style="max-width: 150px;"> <div style="max-width: 150px;">
<div class="card mb-2 avatar-item-container"> <div class="card mb-2 avatar-item-container">
<div class="p-2"> <div class="p-2">
@ -252,207 +253,213 @@ function RefreshItems() {
by <a href="/users/${item.creator.id}" class="text-reset">${item.creator.name}</a> by <a href="/users/${item.creator.id}" class="text-reset">${item.creator.name}</a>
</small> </small>
</div> </div>
` `;
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function(){ NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function () {
WearAsset(NewItemCard, item) WearAsset(NewItemCard, item);
}); });
ItemGrid.appendChild(NewItemCard) ItemGrid.appendChild(NewItemCard);
}); });
}) })
.catch(error => { .catch((error) => {
console.error('Fetch error:', error); console.error('Fetch error:', error);
}); });
} }
async function FormatAvatar() { async function FormatAvatar() {
const FormattedAvatar = structuredClone(Avatar) const FormattedAvatar = structuredClone(Avatar);
// Hats, Tools: https://api.polytoria.com/v1/assets/serve-mesh/:id // Hats, Tools: https://api.polytoria.com/v1/assets/serve-mesh/:id
// or: https://api.polytoria.com/v1/assets/serve/:id/Asset // or: https://api.polytoria.com/v1/assets/serve/:id/Asset
Avatar.items.forEach(async (item, index) => { Avatar.items.forEach(async (item, index) => {
if (typeof(item) === 'number') { if (typeof item === 'number') {
console.log(item) console.log(item);
await FetchMesh(item) await FetchMesh(item)
.then(URL => { .then((URL) => {
console.log('URL: ' + URL) console.log('URL: ' + URL);
FormattedAvatar.items[index] = URL FormattedAvatar.items[index] = URL;
}) })
.catch(error => { .catch((error) => {
throw new Error(error) throw new Error(error);
}); });
console.log('after url') console.log('after url');
//Avatar.items[index] = URL //Avatar.items[index] = URL
} }
}); });
if (typeof(FormattedAvatar.tool) === 'number') {console.log(FormattedAvatar.tool); FormattedAvatar.tool = await FetchMesh(FormattedAvatar.tool)} if (typeof FormattedAvatar.tool === 'number') {
console.log(FormattedAvatar.tool);
FormattedAvatar.tool = await FetchMesh(FormattedAvatar.tool);
}
if (FormattedAvatar.face && typeof(FormattedAvatar.face) === 'number') { if (FormattedAvatar.face && typeof FormattedAvatar.face === 'number') {
FormattedAvatar.face = await FetchAsset(FormattedAvatar.face) FormattedAvatar.face = await FetchAsset(FormattedAvatar.face);
} else { } else {
FormattedAvatar.face = "https://c0.ptacdn.com/static/3dview/DefaultFace.png" FormattedAvatar.face = 'https://c0.ptacdn.com/static/3dview/DefaultFace.png';
} }
if (typeof(FormattedAvatar.shirt) === 'number') {FormattedAvatar.shirt = await FetchAsset(FormattedAvatar.shirt)} if (typeof FormattedAvatar.shirt === 'number') {
if (typeof(FormattedAvatar.pants) === 'number') {FormattedAvatar.pants = await FetchAsset(FormattedAvatar.pants)} FormattedAvatar.shirt = await FetchAsset(FormattedAvatar.shirt);
}
if (typeof FormattedAvatar.pants === 'number') {
FormattedAvatar.pants = await FetchAsset(FormattedAvatar.pants);
}
console.log('Real Avatar: ', Avatar, 'Formatted: ', FormattedAvatar) console.log('Real Avatar: ', Avatar, 'Formatted: ', FormattedAvatar);
return FormattedAvatar return FormattedAvatar;
} }
function LoadMyself() { function LoadMyself() {
fetch('https://api.polytoria.com/v1/users/:id/avatar'.replace(':id', UserID)) fetch('https://api.polytoria.com/v1/users/:id/avatar'.replace(':id', UserID))
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
Avatar.items = [] Avatar.items = [];
data.assets.forEach(item => { data.assets.forEach((item) => {
switch(item.type) { switch (item.type) {
case 'hat': case 'hat':
Avatar.items.push(item.id) Avatar.items.push(item.id);
break break;
default: default:
Avatar[item.type] = item.id Avatar[item.type] = item.id;
break break;
} }
}); });
Avatar.headColor = '#' + data.colors.head || '#cdcdcd' Avatar.headColor = '#' + data.colors.head || '#cdcdcd';
Avatar.torsoColor = '#' + data.colors.torso || '#cdcdcd' Avatar.torsoColor = '#' + data.colors.torso || '#cdcdcd';
Avatar.leftArmColor = '#' + data.colors.leftArm || '#cdcdcd' Avatar.leftArmColor = '#' + data.colors.leftArm || '#cdcdcd';
Avatar.rightArmColor = '#' + data.colors.rightArm || '#cdcdcd' Avatar.rightArmColor = '#' + data.colors.rightArm || '#cdcdcd';
Avatar.leftLegColor = '#' + data.colors.leftLeg || '#cdcdcd' Avatar.leftLegColor = '#' + data.colors.leftLeg || '#cdcdcd';
Avatar.rightLegColor = '#' + data.colors.rightLeg || '#cdcdcd' Avatar.rightLegColor = '#' + data.colors.rightLeg || '#cdcdcd';
UpdateAvatar() UpdateAvatar();
}) })
.catch(error => { .catch((error) => {
console.log(error) console.log(error);
}); });
} }
function WearAsset(element, info) { function WearAsset(element, info) {
if (Avatar.items.indexOf(info.id) === -1 && Avatar[info.type] !== info.id) { if (Avatar.items.indexOf(info.id) === -1 && Avatar[info.type] !== info.id) {
console.log('Equip', info) console.log('Equip', info);
switch(info.type) { switch (info.type) {
case 'hat': case 'hat':
Avatar.items.push(info.id) Avatar.items.push(info.id);
break break;
default: default:
Avatar[info.type] = info.id Avatar[info.type] = info.id;
break break;
} }
} else { } else {
console.log('unequip', info) console.log('unequip', info);
switch(info.type) { switch (info.type) {
case 'hat': case 'hat':
Avatar.items.splice(Avatar.items.indexOf(info.id), 1) Avatar.items.splice(Avatar.items.indexOf(info.id), 1);
break break;
case 'face': case 'face':
Avatar.face = "https://c0.ptacdn.com/static/3dview/DefaultFace.png" Avatar.face = 'https://c0.ptacdn.com/static/3dview/DefaultFace.png';
break break;
default: default:
Avatar[info.type] = undefined Avatar[info.type] = undefined;
break break;
} }
} }
const ToggleButton = element.getElementsByClassName('avatarAction')[0] const ToggleButton = element.getElementsByClassName('avatarAction')[0];
ToggleButton.classList.toggle('btn-success') ToggleButton.classList.toggle('btn-success');
ToggleButton.classList.toggle('btn-danger') ToggleButton.classList.toggle('btn-danger');
ToggleButton.children[0].classList.toggle('fa-plus') ToggleButton.children[0].classList.toggle('fa-plus');
ToggleButton.children[0].classList.toggle('fa-minus') ToggleButton.children[0].classList.toggle('fa-minus');
const Duplicate = ItemGrid.querySelector(`[data-id="${info.id}"]`) const Duplicate = ItemGrid.querySelector(`[data-id="${info.id}"]`);
if (Duplicate !== null && Duplicate !== element) { if (Duplicate !== null && Duplicate !== element) {
const DuplicateToggleButton = Duplicate.getElementsByClassName('avatarAction')[0] const DuplicateToggleButton = Duplicate.getElementsByClassName('avatarAction')[0];
DuplicateToggleButton.classList.toggle('btn-success') DuplicateToggleButton.classList.toggle('btn-success');
DuplicateToggleButton.classList.toggle('btn-danger') DuplicateToggleButton.classList.toggle('btn-danger');
DuplicateToggleButton.children[0].classList.toggle('fa-plus') DuplicateToggleButton.children[0].classList.toggle('fa-plus');
DuplicateToggleButton.children[0].classList.toggle('fa-minus') DuplicateToggleButton.children[0].classList.toggle('fa-minus');
} }
LoadWearing() LoadWearing();
UpdateAvatar() UpdateAvatar();
} }
async function FetchMesh(id) { async function FetchMesh(id) {
if (id === null) {return null} if (id === null) {
console.log('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', id)) return null;
return fetch('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', id)) }
.then(response => { console.log('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', id));
if (!response.ok) { return fetch('https://api.polytoria.com/v1/assets/serve-mesh/:id'.replace(':id', id))
throw new Error('Network not ok') .then((response) => {
} if (!response.ok) {
return response.json() throw new Error('Network not ok');
}) }
.then(data => { return response.json();
console.log(data, 'finished', data.url) })
return data.url .then((data) => {
}) console.log(data, 'finished', data.url);
.catch(error => { return data.url;
console.log('Fetch error: ' + error) })
}); .catch((error) => {
console.log('Fetch error: ' + error);
});
} }
async function FetchAsset(id) { async function FetchAsset(id) {
if (id === null) {return null} if (id === null) {
return fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', id)) return null;
.then(response => { }
if (!response.ok) { return fetch('https://api.polytoria.com/v1/assets/serve/:id/Asset'.replace(':id', id))
throw new Error('Network not ok') .then((response) => {
} if (!response.ok) {
return response.json() throw new Error('Network not ok');
}) }
.then(data => { return response.json();
return data.url })
}) .then((data) => {
.catch(error => { return data.url;
console.log('Fetch error: ' + error) })
}); .catch((error) => {
console.log('Fetch error: ' + error);
});
} }
function LoadWearing() { function LoadWearing() {
const WearingItems = [ const WearingItems = [...Avatar.items, Avatar.shirt, Avatar.pants, Avatar.face].filter((item) => item !== null && item !== undefined);
...Avatar.items,
Avatar.shirt,
Avatar.pants,
Avatar.face
].filter(item => item !== null && item !== undefined);
Array.from(Wearing.children).forEach(element => { Array.from(Wearing.children).forEach((element) => {
const ItemID = element.getElementsByTagName('a')[0].href.split('/')[2] const ItemID = element.getElementsByTagName('a')[0].href.split('/')[2];
if (!WearingItems.includes(ItemID)) { if (!WearingItems.includes(ItemID)) {
element.remove(); element.remove();
} }
}); });
WearingItems.forEach(item => { WearingItems.forEach((item) => {
const ExistingElement = Wearing.querySelector(`[data-itemid="${item}"]`); const ExistingElement = Wearing.querySelector(`[data-itemid="${item}"]`);
if (!ExistingElement) { if (!ExistingElement) {
fetch(`https://api.polytoria.com/v1/store/${item}`) fetch(`https://api.polytoria.com/v1/store/${item}`)
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok'); throw new Error('Network not ok');
} }
return response.json(); return response.json();
}) })
.then(item => { .then((item) => {
if (Wearing.innerHTML === 'No items to show.') { if (Wearing.innerHTML === 'No items to show.') {
Wearing.innerHTML = '' Wearing.innerHTML = '';
} }
let NewItemCard = document.createElement('div'); let NewItemCard = document.createElement('div');
NewItemCard.setAttribute('data-id', item.id) NewItemCard.setAttribute('data-id', item.id);
NewItemCard.classList = 'col-auto'; NewItemCard.classList = 'col-auto';
NewItemCard.innerHTML = ` NewItemCard.innerHTML = `
<div style="max-width: 150px;"> <div style="max-width: 150px;">
<div class="card mb-2 avatar-item-container"> <div class="card mb-2 avatar-item-container">
<div class="p-2"> <div class="p-2">
@ -470,19 +477,19 @@ function LoadWearing() {
by <a href="/users/${item.creator.id}" class="text-reset">${item.creator.name}</a> by <a href="/users/${item.creator.id}" class="text-reset">${item.creator.name}</a>
</small> </small>
</div> </div>
` `;
Wearing.appendChild(NewItemCard); Wearing.appendChild(NewItemCard);
NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function () { NewItemCard.getElementsByClassName('p-2')[0].addEventListener('click', function () {
WearAsset(NewItemCard, item); WearAsset(NewItemCard, item);
}); });
}) })
.catch(error => { .catch((error) => {
console.log('Fetch error: ' + error); console.log('Fetch error: ' + error);
}); });
} }
}); });
if (Array.from(Wearing.children).length === 0) { if (Array.from(Wearing.children).length === 0) {
Wearing.innerHTML = 'No items to show.' Wearing.innerHTML = 'No items to show.';
} }
} }

View file

@ -1,41 +1,40 @@
var SelectedFriends = [] var SelectedFriends = [];
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){ chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings; Settings = result.PolyPlus_Settings;
if (Settings.ImprovedFrListsOn === true) { if (Settings.ImprovedFrListsOn === true) {
var Tab = "requests" var Tab = 'requests';
var FriendsContainer = document.getElementById('friends-container') var FriendsContainer = document.getElementById('friends-container');
var Container = document.createElement('div') var Container = document.createElement('div');
Container.classList = 'row mb-3' Container.classList = 'row mb-3';
Container.innerHTML = ` Container.innerHTML = `
<div class="col"><button id="AccAllFrBtn" class="btn btn-success w-100">Accept all Friend Request(s)</button></div> <div class="col"><button id="AccAllFrBtn" class="btn btn-success w-100">Accept all Friend Request(s)</button></div>
<div class="col"><button id="DelAllFrBtn" class="btn btn-danger w-100">Decline all Friend Request(s)</button></div> <div class="col"><button id="DelAllFrBtn" class="btn btn-danger w-100">Decline all Friend Request(s)</button></div>
` `;
FriendsContainer.parentElement.insertBefore(Container, FriendsContainer) FriendsContainer.parentElement.insertBefore(Container, FriendsContainer);
var AccAllFrBtn = document.getElementById('AccAllFrBtn') var AccAllFrBtn = document.getElementById('AccAllFrBtn');
var DelAllFrBtn = document.getElementById('DelAllFrBtn') var DelAllFrBtn = document.getElementById('DelAllFrBtn');
var AccBtns = document.querySelectorAll('[onclick="acceptFriendRequest(this)"]') var AccBtns = document.querySelectorAll('[onclick="acceptFriendRequest(this)"]');
var DelBtns = document.querySelectorAll('[onclick="declineFriendRequest(this)"]') var DelBtns = document.querySelectorAll('[onclick="declineFriendRequest(this)"]');
if (!(AccBtns.length === 0)) { if (!(AccBtns.length === 0)) {
AccAllFrBtn.addEventListener('click', function(){ AccAllFrBtn.addEventListener('click', function () {
AccBtns.forEach(element => { AccBtns.forEach((element) => {
setTimeout(function () {}, 145) setTimeout(function () {}, 145);
fetch('https://polytoria.com/api/friends/send', { fetch('https://polytoria.com/api/friends/send', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value 'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
}, },
body: JSON.stringify({ userID: parseInt(element.getAttribute('data-user-id')) }), body: JSON.stringify({userID: parseInt(element.getAttribute('data-user-id'))})
}) }).catch((error) => {
.catch(error => { // Handle any errors
// Handle any errors console.error('Error:', error);
console.error('Error:', error); Success = false;
Success = false });
});
/* /*
let NewAcceptBtn = document.createElement('a') let NewAcceptBtn = document.createElement('a')
NewAcceptBtn.style.display = 'none' NewAcceptBtn.style.display = 'none'
sNewAcceptBtn.classList = 'btn btn-success' sNewAcceptBtn.classList = 'btn btn-success'
@ -44,30 +43,29 @@ chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
FriendsContainer.appendChild(NewAcceptBtn) FriendsContainer.appendChild(NewAcceptBtn)
NewAcceptBtn.click(); NewAcceptBtn.click();
*/ */
}) });
}); });
} else { } else {
AccAllFrBtn.setAttribute('disabled', 'true') AccAllFrBtn.setAttribute('disabled', 'true');
} }
if (!(DelBtns.length === 0)) { if (!(DelBtns.length === 0)) {
DelAllFrBtn.addEventListener('click', function(){ DelAllFrBtn.addEventListener('click', function () {
DelBtns.forEach(element => { DelBtns.forEach((element) => {
setTimeout(function () {}, 110) setTimeout(function () {}, 110);
fetch('https://polytoria.com/api/friends/remove', { fetch('https://polytoria.com/api/friends/remove', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value 'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
}, },
body: JSON.stringify({ userID: parseInt(element.getAttribute('data-user-id')) }), body: JSON.stringify({userID: parseInt(element.getAttribute('data-user-id'))})
}) }).catch((error) => {
.catch(error => { // Handle any errors
// Handle any errors console.error('Error:', error, document.querySelector('input[name="_csrf"]').value);
console.error('Error:', error, document.querySelector('input[name="_csrf"]').value); Success = false;
Success = false });
});
/* /*
let NewDeclineBtn = document.createElement('a') let NewDeclineBtn = document.createElement('a')
NewDeclineBtn.style.display = 'none' NewDeclineBtn.style.display = 'none'
NewDeclineBtn.classList = 'btn btn-danger' NewDeclineBtn.classList = 'btn btn-danger'
@ -76,135 +74,137 @@ chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
FriendsContainer.appendChild(NewDeclineBtn) FriendsContainer.appendChild(NewDeclineBtn)
NewDeclineBtn.click(); NewDeclineBtn.click();
*/ */
}) });
}); });
} else { } else {
DelAllFrBtn.setAttribute('disabled', 'true') DelAllFrBtn.setAttribute('disabled', 'true');
} }
let Text = document.createElement('p') let Text = document.createElement('p');
Text.classList = 'mx-auto' Text.classList = 'mx-auto';
Text.style.textAlign = 'center' Text.style.textAlign = 'center';
Text.style.fontSize = '1.3rem' Text.style.fontSize = '1.3rem';
Text.style.display = 'none' Text.style.display = 'none';
Text.innerHTML = ` Text.innerHTML = `
<span>0</span> friends selected! <span>0</span> friends selected!
<br> <br>
<button id="viewSelectionBtn" class="btn btn-primary">View Selection</button> <button id="viewSelectionBtn" class="btn btn-primary">View Selection</button>
<button id="clearSelectionBtn" class="btn btn-warning">Clear Selection</button> <button id="clearSelectionBtn" class="btn btn-warning">Clear Selection</button>
<button id="removeSelectionBtn" class="btn btn-danger">Remove Selected Friends</button> <button id="removeSelectionBtn" class="btn btn-danger">Remove Selected Friends</button>
` `;
FriendsContainer.parentElement.insertBefore(Text, FriendsContainer) FriendsContainer.parentElement.insertBefore(Text, FriendsContainer);
let Text_Span = Text.querySelector('span'); let Text_Span = Text.querySelector('span');
let Text_View = document.getElementById('viewSelectionBtn'); let Text_View = document.getElementById('viewSelectionBtn');
let Text_Clear = document.getElementById('clearSelectionBtn'); let Text_Clear = document.getElementById('clearSelectionBtn');
let Text_Remove = document.getElementById('removeSelectionBtn'); let Text_Remove = document.getElementById('removeSelectionBtn');
document.querySelector('[data-friends-tab="requests"]').addEventListener('click', function(){ document.querySelector('[data-friends-tab="requests"]').addEventListener('click', function () {
Tab = "requests" Tab = 'requests';
Container.style.display = ''; Container.style.display = '';
Text.style.display = 'none'; Text.style.display = 'none';
document.querySelectorAll('input[type="check"]').forEach(element => {element.remove();}); document.querySelectorAll('input[type="check"]').forEach((element) => {
}); element.remove();
document.querySelector('[data-friends-tab="friends"]').addEventListener('click', function(){ });
Tab = "friends" });
Container.style.display = 'none'; document.querySelector('[data-friends-tab="friends"]').addEventListener('click', function () {
Text.style.display = ''; Tab = 'friends';
}); Container.style.display = 'none';
var ConfirmRemove = 0 Text.style.display = '';
Text_View.addEventListener('click', function(){}); });
Text_Clear.addEventListener('click', function(){ var ConfirmRemove = 0;
SelectedFriends = [] Text_View.addEventListener('click', function () {});
UpdateCheckboxes(); Text_Clear.addEventListener('click', function () {
Text_Span.innerText = SelectedFriends.length SelectedFriends = [];
}); UpdateCheckboxes();
Text_Remove.addEventListener('click', function(){ Text_Span.innerText = SelectedFriends.length;
ConfirmRemove = ConfirmRemove + 1 });
switch(ConfirmRemove) { Text_Remove.addEventListener('click', function () {
case 0: ConfirmRemove = ConfirmRemove + 1;
Text_Remove.innerText = 'Remove Selected Friends' switch (ConfirmRemove) {
break case 0:
case 1: Text_Remove.innerText = 'Remove Selected Friends';
Text_Remove.innerText = 'Are you sure?' break;
break case 1:
case 2: Text_Remove.innerText = 'Are you sure?';
for (let i = 0; i < SelectedFriends.length; i++) { break;
setTimeout(function () {}, 110) case 2:
let NewDeclineBtn = document.createElement('a') for (let i = 0; i < SelectedFriends.length; i++) {
NewDeclineBtn.style.display = 'none' setTimeout(function () {}, 110);
NewDeclineBtn.classList = 'btn btn-danger' let NewDeclineBtn = document.createElement('a');
NewDeclineBtn.setAttribute('data-user-id', SelectedFriends[i]) NewDeclineBtn.style.display = 'none';
NewDeclineBtn.setAttribute('onclick', 'declineFriendRequest(this)') NewDeclineBtn.classList = 'btn btn-danger';
FriendsContainer.appendChild(NewDeclineBtn) NewDeclineBtn.setAttribute('data-user-id', SelectedFriends[i]);
NewDeclineBtn.click(); NewDeclineBtn.setAttribute('onclick', 'declineFriendRequest(this)');
} FriendsContainer.appendChild(NewDeclineBtn);
SelectedFriends = [] NewDeclineBtn.click();
UpdateCheckboxes(); }
Text_Remove.innerText = 'Remove Selected Friends' SelectedFriends = [];
ConfirmRemove = 0 UpdateCheckboxes();
break Text_Remove.innerText = 'Remove Selected Friends';
} ConfirmRemove = 0;
}); break;
}
});
const observer = new MutationObserver(function (){ const observer = new MutationObserver(function () {
if (FriendsContainer.children.length > 0 && Tab === "friends") { if (FriendsContainer.children.length > 0 && Tab === 'friends') {
LoadCheckBoxes(); LoadCheckBoxes();
} }
}); });
observer.observe(FriendsContainer, {childList: true, subtree: false}); observer.observe(FriendsContainer, {childList: true, subtree: false});
function LoadCheckBoxes() { function LoadCheckBoxes() {
Array.from(FriendsContainer.children).forEach(element => { Array.from(FriendsContainer.children).forEach((element) => {
let DeclineBtn = element.querySelector('a.btn.btn-danger') let DeclineBtn = element.querySelector('a.btn.btn-danger');
let UserID = DeclineBtn.getAttribute('data-user-id') let UserID = DeclineBtn.getAttribute('data-user-id');
let Column = document.createElement('div') let Column = document.createElement('div');
let EditColumn = element.querySelector('.col-9') let EditColumn = element.querySelector('.col-9');
Column.classList = 'col-auto' Column.classList = 'col-auto';
var NewCheckBox = document.createElement('button') var NewCheckBox = document.createElement('button');
NewCheckBox.classList = 'polyplus-multiremovefr-checkbox' NewCheckBox.classList = 'polyplus-multiremovefr-checkbox';
NewCheckBox.setAttribute('style', 'padding: 20px; background-color: #191919; border: 1px solid #393939; border-radius: 1rem;') NewCheckBox.setAttribute('style', 'padding: 20px; background-color: #191919; border: 1px solid #393939; border-radius: 1rem;');
var Index = SelectedFriends.indexOf(UserID) var Index = SelectedFriends.indexOf(UserID);
if (Index !== -1) { if (Index !== -1) {
DeclineBtn.classList.add('disabled') DeclineBtn.classList.add('disabled');
NewCheckBox.style.borderColor = 'lime' NewCheckBox.style.borderColor = 'lime';
} }
EditColumn.classList.remove('col-9') EditColumn.classList.remove('col-9');
EditColumn.classList.add('col') EditColumn.classList.add('col');
Column.appendChild(NewCheckBox) Column.appendChild(NewCheckBox);
EditColumn.parentElement.appendChild(Column) EditColumn.parentElement.appendChild(Column);
NewCheckBox.addEventListener('click', function(){ NewCheckBox.addEventListener('click', function () {
var Index = SelectedFriends.indexOf(UserID) var Index = SelectedFriends.indexOf(UserID);
if (Index === -1) { if (Index === -1) {
DeclineBtn.classList.add('disabled') DeclineBtn.classList.add('disabled');
SelectedFriends.push(UserID) SelectedFriends.push(UserID);
NewCheckBox.style.borderColor = 'lime' NewCheckBox.style.borderColor = 'lime';
} else { } else {
SelectedFriends.splice(Index, 1) SelectedFriends.splice(Index, 1);
NewCheckBox.style.borderColor = '#393939' NewCheckBox.style.borderColor = '#393939';
DeclineBtn.classList.remove('disabled') DeclineBtn.classList.remove('disabled');
} }
Text_Span.innerText = SelectedFriends.length Text_Span.innerText = SelectedFriends.length;
UpdateCheckboxes(); UpdateCheckboxes();
}); });
}); });
} }
function UpdateCheckboxes(){ function UpdateCheckboxes() {
document.querySelectorAll('.polyplus-multiremovefr-checkbox').forEach(element => { document.querySelectorAll('.polyplus-multiremovefr-checkbox').forEach((element) => {
let Parent = element.parentElement.parentElement.parentElement.parentElement.parentElement let Parent = element.parentElement.parentElement.parentElement.parentElement.parentElement;
let DeclineBtn = Parent.querySelector('a.btn.btn-danger') let DeclineBtn = Parent.querySelector('a.btn.btn-danger');
if (element.getAttribute('disabled')) { if (element.getAttribute('disabled')) {
element.removeAttribute('disabled') element.removeAttribute('disabled');
} }
if (SelectedFriends.IndexOf(DeclineBtn.getAttribute('data-user-id')) === -1) { if (SelectedFriends.IndexOf(DeclineBtn.getAttribute('data-user-id')) === -1) {
element.style.borderColor = '#393939' element.style.borderColor = '#393939';
DeclineBtn.classList.remove('disabled') DeclineBtn.classList.remove('disabled');
if (SelectedFriends.length >= 25) { if (SelectedFriends.length >= 25) {
element.setAttribute('disabled', true) element.setAttribute('disabled', true);
} }
} else { } else {
DeclineBtn.classList.add('disabled') DeclineBtn.classList.add('disabled');
element.style.borderColor = 'lime' element.style.borderColor = 'lime';
} }
}) });
} }
} }
}); });

View file

@ -3,25 +3,25 @@ this file needs a rewrite by me lol
*/ */
var Settings; var Settings;
var PinnedGamesData var PinnedGamesData;
var BestFriendsData var BestFriendsData;
let Utilities; let Utilities;
chrome.storage.sync.get(['PolyPlus_Settings'], async function(result) { chrome.storage.sync.get(['PolyPlus_Settings'], async function (result) {
Settings = result.PolyPlus_Settings || Utilities.DefaultSettings Settings = result.PolyPlus_Settings || Utilities.DefaultSettings;
if (Settings.IRLPriceWithCurrency.Enabled === true) { if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice() IRLPrice();
} }
if (Settings.HomeFriendCountOn === true) { if (Settings.HomeFriendCountOn === true) {
ShowFriendCount() ShowFriendCount();
} }
if (Settings.PinnedGamesOn === true || Settings.BestFriendsOn === true) { if (Settings.PinnedGamesOn === true || Settings.BestFriendsOn === true) {
Update() Update();
} }
}); });
let ContainerElement = ` let ContainerElement = `
@ -56,148 +56,151 @@ let TitleElement = `
<h6 class="dash-ctitle2">Jump right back into your favorite games</h6> <h6 class="dash-ctitle2">Jump right back into your favorite games</h6>
<h5 class="dash-ctitle">Pinned Games</h5> <h5 class="dash-ctitle">Pinned Games</h5>
</div>`; </div>`;
var FriendContainer = document.querySelector('.card:has(.friendsPopup) .card-body') var FriendContainer = document.querySelector('.card:has(.friendsPopup) .card-body');
let NewContainer = document.createElement('div'); let NewContainer = document.createElement('div');
NewContainer.style.display = 'none' NewContainer.style.display = 'none';
NewContainer.classList = 'card card-dash mcard'; NewContainer.classList = 'card card-dash mcard';
NewContainer.style.animationDelay = '0.18s'; NewContainer.style.animationDelay = '0.18s';
NewContainer.innerHTML = ContainerElement; NewContainer.innerHTML = ContainerElement;
let NewTitle = document.createElement('div'); let NewTitle = document.createElement('div');
NewTitle.style.display = 'none' NewTitle.style.display = 'none';
NewTitle.classList = 'row reqFadeAnim px-2 px-lg-0'; NewTitle.classList = 'row reqFadeAnim px-2 px-lg-0';
NewTitle.innerHTML = TitleElement; NewTitle.innerHTML = TitleElement;
let BestFriendsContainer = document.createElement('div') let BestFriendsContainer = document.createElement('div');
BestFriendsContainer.classList = 'd-flex' BestFriendsContainer.classList = 'd-flex';
BestFriendsContainer.style = 'display: none; border-bottom: 1px solid #000; padding-bottom: 10px; margin-bottom: 10px; width: 100%;' BestFriendsContainer.style = 'display: none; border-bottom: 1px solid #000; padding-bottom: 10px; margin-bottom: 10px; width: 100%;';
let Spacer = document.createElement('div') let Spacer = document.createElement('div');
Spacer.innerHTML = ' ' Spacer.innerHTML = ' ';
Spacer.style.width = '50px' Spacer.style.width = '50px';
Spacer.prepend(BestFriendsContainer) Spacer.prepend(BestFriendsContainer);
FriendContainer.prepend(BestFriendsContainer) FriendContainer.prepend(BestFriendsContainer);
async function Update() { async function Update() {
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function(result) { chrome.storage.sync.get(['PolyPlus_PinnedGames'], function (result) {
PinnedGamesData = result.PolyPlus_PinnedGames || []; PinnedGamesData = result.PolyPlus_PinnedGames || [];
if (Settings.PinnedGamesOn === true) { if (Settings.PinnedGamesOn === true) {
PinnedGames() PinnedGames();
} else { } else {
NewContainer.style.display = 'none' NewContainer.style.display = 'none';
NewTitle.style.display = 'none' NewTitle.style.display = 'none';
} }
}); });
chrome.storage.sync.get(['PolyPlus_BestFriends'], function(result) { chrome.storage.sync.get(['PolyPlus_BestFriends'], function (result) {
BestFriendsData = result.PolyPlus_BestFriends || []; BestFriendsData = result.PolyPlus_BestFriends || [];
if (Settings.BestFriendsOn === true) { if (Settings.BestFriendsOn === true) {
BestFriends(); BestFriends();
} else { } else {
BestFriendsContainer.style.display = 'none' BestFriendsContainer.style.display = 'none';
Spacer.style.display = 'none' Spacer.style.display = 'none';
} }
}); });
} }
function PinnedGames() { function PinnedGames() {
var Existing = NewContainer.children[0].children var Existing = NewContainer.children[0].children;
Array.from(Existing).forEach(element => { Array.from(Existing).forEach((element) => {
element.remove(); element.remove();
}); });
if (PinnedGamesData.length === 0) { if (PinnedGamesData.length === 0) {
NewContainer.style.display = 'none' NewContainer.style.display = 'none';
NewTitle.style.display = 'none' NewTitle.style.display = 'none';
} else { } else {
NewContainer.style.display = '' NewContainer.style.display = '';
NewTitle.style.display = '' NewTitle.style.display = '';
} }
PinnedGamesData.forEach(element => { PinnedGamesData.forEach((element) => {
fetch('https://api.polytoria.com/v1/places/' + element) fetch('https://api.polytoria.com/v1/places/' + element)
.then(response => response.json()) .then((response) => response.json())
.then(data => { .then((data) => {
let GameName = data.name; let GameName = data.name;
let GameThumbnail = data.thumbnail; let GameThumbnail = data.thumbnail;
var NewGameContainer = document.createElement('a'); var NewGameContainer = document.createElement('a');
NewGameContainer.innerHTML = GameContainerElement.replace(':GameName',GameName).replace(':Thumbnail',GameThumbnail).replace(':Likes', data.rating.likes).replace(':Dislikes', data.rating.dislikes); NewGameContainer.innerHTML = GameContainerElement.replace(':GameName', GameName)
NewGameContainer.href = '/places/' + element .replace(':Thumbnail', GameThumbnail)
.replace(':Likes', data.rating.likes)
.replace(':Dislikes', data.rating.dislikes);
NewGameContainer.href = '/places/' + element;
/* /*
if (new Date().getDate() >= new Date(data.updatedAt).getDate()) { if (new Date().getDate() >= new Date(data.updatedAt).getDate()) {
console.log('Game has updated') console.log('Game has updated')
} }
*/ */
NewContainer.children[0].appendChild(NewGameContainer); NewContainer.children[0].appendChild(NewGameContainer);
}) })
.catch(error => { .catch((error) => {
console.error('Error:', error); console.error('Error:', error);
}); });
}); });
} }
function BestFriends() { function BestFriends() {
Array.from(document.querySelectorAll('[bestFriend]')).forEach(element => { Array.from(document.querySelectorAll('[bestFriend]')).forEach((element) => {
element.removeAttribute('bestFriend') element.removeAttribute('bestFriend');
element.getElementsByClassName('friend-name')[0].style.color = 'initial'; element.getElementsByClassName('friend-name')[0].style.color = 'initial';
FriendContainer.appendChild(element) FriendContainer.appendChild(element);
}); });
if (BestFriendsData.length === 0) { if (BestFriendsData.length === 0) {
BestFriendsContainer.style.visibility = 'hidden' BestFriendsContainer.style.visibility = 'hidden';
BestFriendsContainer.style.padding = '0px !important' BestFriendsContainer.style.padding = '0px !important';
BestFriendsContainer.style.margin = '0px !important' BestFriendsContainer.style.margin = '0px !important';
} else { } else {
BestFriendsContainer.style.visibility = 'visible' BestFriendsContainer.style.visibility = 'visible';
BestFriendsContainer.style.padding = '' BestFriendsContainer.style.padding = '';
BestFriendsContainer.style.margin = '' BestFriendsContainer.style.margin = '';
} }
BestFriendsData.forEach(element => { BestFriendsData.forEach((element) => {
let ExistingFriend = document.getElementById('friend-' + element) let ExistingFriend = document.getElementById('friend-' + element);
if (ExistingFriend) { if (ExistingFriend) {
ExistingFriend.setAttribute('bestFriend', 'true') ExistingFriend.setAttribute('bestFriend', 'true');
ExistingFriend.getElementsByClassName('friend-name')[0].style.color = 'yellow'; ExistingFriend.getElementsByClassName('friend-name')[0].style.color = 'yellow';
BestFriendsContainer.prepend(ExistingFriend) BestFriendsContainer.prepend(ExistingFriend);
} }
}); });
} }
var SecondaryColumn = document.getElementsByClassName('col-lg-8')[0] var SecondaryColumn = document.getElementsByClassName('col-lg-8')[0];
SecondaryColumn.insertBefore(NewContainer, SecondaryColumn.children[0]); SecondaryColumn.insertBefore(NewContainer, SecondaryColumn.children[0]);
SecondaryColumn.insertBefore(NewTitle, SecondaryColumn.children[0]); SecondaryColumn.insertBefore(NewTitle, SecondaryColumn.children[0]);
async function IRLPrice() { async function IRLPrice() {
(async () => { (async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js')); Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default Utilities = Utilities.default;
const TrendingItems = document.getElementById('home-trendingItems') const TrendingItems = document.getElementById('home-trendingItems');
for (let item of TrendingItems.children[1].getElementsByClassName('d-flex')[0].children) { for (let item of TrendingItems.children[1].getElementsByClassName('d-flex')[0].children) {
const Price = item.getElementsByClassName('text-success')[0] const Price = item.getElementsByClassName('text-success')[0];
if (Price !== undefined) { if (Price !== undefined) {
const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency) const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency);
let Span = document.createElement('span') let Span = document.createElement('span');
Span.classList = 'text-muted polyplus-price-tag' Span.classList = 'text-muted polyplus-price-tag';
Span.style = 'font-size: 0.7rem; font-weight: lighter;' Span.style = 'font-size: 0.7rem; font-weight: lighter;';
Span.innerText = "($" + IRLResult.result + " " + IRLResult.display + ")" Span.innerText = '($' + IRLResult.result + ' ' + IRLResult.display + ')';
Price.appendChild(Span) Price.appendChild(Span);
} }
} }
})(); })();
} }
async function ShowFriendCount() { async function ShowFriendCount() {
let FriendCount = (await (await fetch('https://polytoria.com/api/friends?page=1')).json()).meta.total let FriendCount = (await (await fetch('https://polytoria.com/api/friends?page=1')).json()).meta.total;
/* /*
const FirstPage = (await (await fetch('https://polytoria.com/api/friends?page=1')).json()) const FirstPage = (await (await fetch('https://polytoria.com/api/friends?page=1')).json())
if (FirstPage.meta.lastPage > 1) { if (FirstPage.meta.lastPage > 1) {
const LastPage = (await (await fetch('https://polytoria.com/api/friends?page=' + Pages)).json()) const LastPage = (await (await fetch('https://polytoria.com/api/friends?page=' + Pages)).json())
@ -207,9 +210,9 @@ async function ShowFriendCount() {
} }
*/ */
const CountText = document.createElement('small') const CountText = document.createElement('small');
CountText.classList = 'text-muted fw-lighter' CountText.classList = 'text-muted fw-lighter';
CountText.style.fontSize = '0.8rem' CountText.style.fontSize = '0.8rem';
CountText.innerText = ' (' + FriendCount + ')' CountText.innerText = ' (' + FriendCount + ')';
document.querySelector('#home-friendsOnline h5').appendChild(CountText) document.querySelector('#home-friendsOnline h5').appendChild(CountText);
} }

View file

@ -1,47 +1,47 @@
ExpandMessages() ExpandMessages();
function ExpandMessages() { function ExpandMessages() {
const Messages = document.getElementById('messages') const Messages = document.getElementById('messages');
for (let message of Messages.children) { for (let message of Messages.children) {
let Expanded = false let Expanded = false;
let ContentDiv = null let ContentDiv = null;
const ViewButton = message.querySelector('a.btn[href^="/inbox/messages"]') const ViewButton = message.querySelector('a.btn[href^="/inbox/messages"]');
const MessageID = ViewButton.getAttribute('href').split('/')[3] const MessageID = ViewButton.getAttribute('href').split('/')[3];
const ExpandButton = document.createElement('button') const ExpandButton = document.createElement('button');
ExpandButton.classList = 'btn btn-outline-warning px-4 mt-1' ExpandButton.classList = 'btn btn-outline-warning px-4 mt-1';
ExpandButton.innerText = 'Expand' ExpandButton.innerText = 'Expand';
ViewButton.parentElement.appendChild(ExpandButton) ViewButton.parentElement.appendChild(ExpandButton);
ExpandButton.addEventListener('click', function(){ ExpandButton.addEventListener('click', function () {
if (ContentDiv === null) { if (ContentDiv === null) {
fetch('https://polytoria.com/inbox/messages/'+MessageID) fetch('https://polytoria.com/inbox/messages/' + MessageID)
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.text() return response.text();
}) })
.then(data => { .then((data) => {
const Doc = new DOMParser().parseFromString(data, 'text/html') const Doc = new DOMParser().parseFromString(data, 'text/html');
const MessageContent = Doc.querySelector('p.mb-0').innerText const MessageContent = Doc.querySelector('p.mb-0').innerText;
ContentDiv = document.createElement('div') ContentDiv = document.createElement('div');
ContentDiv.classList = 'py-2' ContentDiv.classList = 'py-2';
ContentDiv.innerText = MessageContent ContentDiv.innerText = MessageContent;
message.appendChild(ContentDiv) message.appendChild(ContentDiv);
}) })
.catch(error => { .catch((error) => {
console.log(error) console.log(error);
}); });
} }
Expanded = !Expanded Expanded = !Expanded;
ExpandButton.innerText = (Expanded === false) ? 'Expand' : 'Minimize' ExpandButton.innerText = Expanded === false ? 'Expand' : 'Minimize';
ContentDiv.style.display = (Expanded === false) ? 'none' : 'block' ContentDiv.style.display = Expanded === false ? 'none' : 'block';
}); });
} }
} }

View file

@ -1,20 +1,20 @@
if (window.location.pathname.split('/')[3] === "inventory") { if (window.location.pathname.split('/')[3] === 'inventory') {
const UserID = window.location.pathname.split('/')[2] const UserID = window.location.pathname.split('/')[2];
if (UserID === JSON.parse(window.localStorage.getItem('p+account_info')).ID) { if (UserID === JSON.parse(window.localStorage.getItem('p+account_info')).ID) {
let Nav = document.getElementsByClassName('nav-pills')[0] let Nav = document.getElementsByClassName('nav-pills')[0];
let WishlistNav = document.createElement('li') let WishlistNav = document.createElement('li');
WishlistNav.classList.add('nav-item') WishlistNav.classList.add('nav-item');
WishlistNav.innerHTML = ` WishlistNav.innerHTML = `
<a href="/users/${UserID}/inventory/wishlist/" class="nav-link"> <a href="/users/${UserID}/inventory/wishlist/" class="nav-link">
<i class="fa-regular fa-sparkles me-1"></i> <i class="fa-regular fa-sparkles me-1"></i>
<span class="pilltitle">Item Wishlist</span> <span class="pilltitle">Item Wishlist</span>
</a> </a>
` `;
Nav.appendChild(WishlistNav) Nav.appendChild(WishlistNav);
if (window.location.pathname.split('/')[4] === "wishlist") { if (window.location.pathname.split('/')[4] === 'wishlist') {
const ItemGrid = document.getElementsByClassName('itemgrid')[0] const ItemGrid = document.getElementsByClassName('itemgrid')[0];
const ItemCardContents = ` const ItemCardContents = `
<a href="/store/:ItemID" class="text-reset"> <a href="/store/:ItemID" class="text-reset">
<div class="card mb-2"> <div class="card mb-2">
:LimitedTag :LimitedTag
@ -30,23 +30,23 @@ if (window.location.pathname.split('/')[3] === "inventory") {
by <a href="/users/:CreatorID" class="text-muted">:CreatorName</a> by <a href="/users/:CreatorID" class="text-muted">:CreatorName</a>
</small> </small>
<button class="polyplus-itemwish-removebtn btn btn-danger btn-sm" style="width: 100%;">X</button> <button class="polyplus-itemwish-removebtn btn btn-danger btn-sm" style="width: 100%;">X</button>
` `;
Array.from(ItemGrid.children).forEach(element => { Array.from(ItemGrid.children).forEach((element) => {
element.remove(); element.remove();
}); });
Array.from(Nav.children).forEach(element => { Array.from(Nav.children).forEach((element) => {
element = element.children[0] element = element.children[0];
if (!(element === WishlistNav)) { if (!(element === WishlistNav)) {
if (element.classList.contains('active')) { if (element.classList.contains('active')) {
element.classList.remove('active') element.classList.remove('active');
} }
} }
}); });
WishlistNav.children[0].classList.add('active') WishlistNav.children[0].classList.add('active');
const Search = document.createElement('div') const Search = document.createElement('div');
Search.classList = 'row' Search.classList = 'row';
Search.innerHTML = ` Search.innerHTML = `
<div class="col-auto"> <div class="col-auto">
<select class="form-select" id="polyplus-itemwish-type" style="width: 150px;"> <select class="form-select" id="polyplus-itemwish-type" style="width: 150px;">
<option value="any">Any</option> <option value="any">Any</option>
@ -78,109 +78,121 @@ if (window.location.pathname.split('/')[3] === "inventory") {
</label> </label>
</div> </div>
</div> </div>
` `;
ItemGrid.parentElement.prepend(document.createElement('br'), ItemGrid.parentElement.children[0]) ItemGrid.parentElement.prepend(document.createElement('br'), ItemGrid.parentElement.children[0]);
ItemGrid.parentElement.prepend(Search, ItemGrid.parentElement.children[0]) ItemGrid.parentElement.prepend(Search, ItemGrid.parentElement.children[0]);
let Type = document.getElementById('polyplus-itemwish-type') let Type = document.getElementById('polyplus-itemwish-type');
let SearchBar = document.getElementById('polyplus-itemwish-searchbar') let SearchBar = document.getElementById('polyplus-itemwish-searchbar');
let IsLimited = document.getElementById('polyplus-itemwish-isLimited') let IsLimited = document.getElementById('polyplus-itemwish-isLimited');
let IsAvailable = document.getElementById('polyplus-itemwish-isAvailable') let IsAvailable = document.getElementById('polyplus-itemwish-isAvailable');
Type.addEventListener('change', function(){ Type.addEventListener('change', function () {
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked) Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked);
}); });
SearchBar.addEventListener('change', function(){ SearchBar.addEventListener('change', function () {
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked) Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked);
}); });
IsLimited.addEventListener('change', function(){ IsLimited.addEventListener('change', function () {
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked) Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked);
}); });
IsAvailable.addEventListener('change', function(){ IsAvailable.addEventListener('change', function () {
Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked) Update(Type.options[Type.selectedIndex].value, SearchBar.value, IsLimited.checked, IsAvailable.checked);
}); });
chrome.storage.sync.get(['PolyPlus_ItemWishlist'], function(result){ chrome.storage.sync.get(['PolyPlus_ItemWishlist'], function (result) {
let Wishlist = result.PolyPlus_ItemWishlist || []; let Wishlist = result.PolyPlus_ItemWishlist || [];
console.log('wishlist: ', Wishlist) console.log('wishlist: ', Wishlist);
Wishlist.forEach(element => { Wishlist.forEach((element) => {
let NewItemCard = document.createElement('div') let NewItemCard = document.createElement('div');
NewItemCard.classList = 'px-0' NewItemCard.classList = 'px-0';
fetch('https://api.polytoria.com/v1/store/:id'.replace(':id', element)) fetch('https://api.polytoria.com/v1/store/:id'.replace(':id', element))
.then(response => response.json()) .then((response) => response.json())
.then(data => { .then((data) => {
NewItemCard.innerHTML = ItemCardContents.replace(':ItemID', data.id).replace(':ItemThumbnail', data.thumbnail).replace(':ItemName', data.name).replace(':CreatorID', data.creator.id).replace(':CreatorName', data.creator.name) NewItemCard.innerHTML = ItemCardContents.replace(':ItemID', data.id)
if (data.isLimited === true) { .replace(':ItemThumbnail', data.thumbnail)
NewItemCard.innerHTML = NewItemCard.innerHTML.replace(':LimitedTag', '<div class="ribbon ribbon-limited ribbon-top-right"><span>Limited</span></div>') .replace(':ItemName', data.name)
} else { .replace(':CreatorID', data.creator.id)
NewItemCard.innerHTML = NewItemCard.innerHTML.replace(':LimitedTag', '') .replace(':CreatorName', data.creator.name);
} if (data.isLimited === true) {
NewItemCard.setAttribute('data-id', data.id) NewItemCard.innerHTML = NewItemCard.innerHTML.replace(':LimitedTag', '<div class="ribbon ribbon-limited ribbon-top-right"><span>Limited</span></div>');
NewItemCard.setAttribute('data-name', data.name) } else {
NewItemCard.setAttribute('data-type', data.type) NewItemCard.innerHTML = NewItemCard.innerHTML.replace(':LimitedTag', '');
NewItemCard.setAttribute('data-creator', data.creator.name) }
NewItemCard.setAttribute('data-limited', data.isLimited) NewItemCard.setAttribute('data-id', data.id);
if (data.isLimited === false) { NewItemCard.setAttribute('data-name', data.name);
NewItemCard.setAttribute('data-price', data.price) NewItemCard.setAttribute('data-type', data.type);
} NewItemCard.setAttribute('data-creator', data.creator.name);
NewItemCard.setAttribute('data-limited', data.isLimited);
if (data.isLimited === false) {
NewItemCard.setAttribute('data-price', data.price);
}
ItemGrid.appendChild(NewItemCard) ItemGrid.appendChild(NewItemCard);
NewItemCard.getElementsByClassName('polyplus-itemwish-removebtn')[0].addEventListener('click', function(){ NewItemCard.getElementsByClassName('polyplus-itemwish-removebtn')[0].addEventListener('click', function () {
let Index = Wishlist.indexOf(parseInt(NewItemCard.getAttribute('data-id'))) let Index = Wishlist.indexOf(parseInt(NewItemCard.getAttribute('data-id')));
if (Index === -1) { if (Index === -1) {
NewItemCard.remove(); NewItemCard.remove();
return return;
} else { } else {
Wishlist.splice(Index, 1) Wishlist.splice(Index, 1);
console.log(Wishlist) console.log(Wishlist);
NewItemCard.remove(); NewItemCard.remove();
} }
chrome.storage.sync.set({'PolyPlus_ItemWishlist': Wishlist, arrayOrder: true}, function() { chrome.storage.sync.set({PolyPlus_ItemWishlist: Wishlist, arrayOrder: true}, function () {
console.log('ItemWishlist successfully saved: ' + ItemWishlist) console.log('ItemWishlist successfully saved: ' + ItemWishlist);
}); });
}); });
}) })
.catch(error => { .catch((error) => {
console.error('Error:', error); console.error('Error:', error);
}); });
}); });
}); });
} }
} }
} }
function Update(type, query, isLimited, isAvailable) { function Update(type, query, isLimited, isAvailable) {
let ItemGrid = document.getElementsByClassName('itemgrid')[0] let ItemGrid = document.getElementsByClassName('itemgrid')[0];
let BrickBalance = parseInt(JSON.parse(window.localStorage.getItem('p+account_info')).Bricks) let BrickBalance = parseInt(JSON.parse(window.localStorage.getItem('p+account_info')).Bricks);
query = query.toLowerCase(); query = query.toLowerCase();
let Results = Array.from(ItemGrid.children) let Results = Array.from(ItemGrid.children);
for (let i = 0; i < Results.length; i++) { for (let i = 0; i < Results.length; i++) {
let Show = true let Show = true;
console.log('type: ', type) console.log('type: ', type);
if (!(type === 'any')) { if (!(type === 'any')) {
console.log('isn\'t any') console.log("isn't any");
if (!(Results[i].getAttribute('data-type') === type)) {Show = false} if (!(Results[i].getAttribute('data-type') === type)) {
} Show = false;
}
}
if (!(Results[i].getAttribute('data-name').toLowerCase().startsWith(query))) {Show = false} if (!Results[i].getAttribute('data-name').toLowerCase().startsWith(query)) {
Show = false;
}
if (isLimited === true) { if (isLimited === true) {
if (!(Results[i].getAttribute('data-limited') === 'true')) {Show = false} if (!(Results[i].getAttribute('data-limited') === 'true')) {
} Show = false;
}
}
if (isAvailable === true) { if (isAvailable === true) {
if (!(parseInt(Results[i].getAttribute('data-price')) <= BrickBalance)) {Show = false} if (!(parseInt(Results[i].getAttribute('data-price')) <= BrickBalance)) {
} Show = false;
}
}
if (Show === true) { if (Show === true) {
Results[i].style.display = 'block' Results[i].style.display = 'block';
} else { } else {
Results[i].style.display = 'none' Results[i].style.display = 'none';
} }
} }
} }

View file

@ -1,6 +1,6 @@
let UserID = window.location.pathname.split('/')[2]; let UserID = window.location.pathname.split('/')[2];
const AvatarRow = document.getElementsByClassName('d-flex flex-row flex-nowrap overflow-x-scroll px-3 px-lg-0 mb-2 mb-lg-0')[0] const AvatarRow = document.getElementsByClassName('d-flex flex-row flex-nowrap overflow-x-scroll px-3 px-lg-0 mb-2 mb-lg-0')[0];
const AvatarHeading = document.querySelector('.section-title:has(i.fa-user-crown)') const AvatarHeading = document.querySelector('.section-title:has(i.fa-user-crown)');
var Settings; var Settings;
var BestFriends; var BestFriends;
@ -10,238 +10,244 @@ let CalculateButton;
let Utilities; let Utilities;
if (UserID) { if (UserID) {
(async () => { (async () => {
UserID = (await (await fetch('https://api.polytoria.com/v1/users/')).json()).id UserID = (await (await fetch('https://api.polytoria.com/v1/users/')).json()).id;
Utilities = await import(chrome.runtime.getURL('resources/utils.js')); Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default Utilities = Utilities.default;
chrome.storage.sync.get(['PolyPlus_Settings'], function(result) { chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings || {} Settings = result.PolyPlus_Settings || {};
if (Settings.IRLPriceWithCurrency.Enabled === true) { if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice() IRLPrice();
} }
if (Settings.BestFriendsOn === true) { if (Settings.BestFriendsOn === true) {
BestFriends() BestFriends();
} }
if (Settings.OutfitCostOn === true) { if (Settings.OutfitCostOn === true) {
CalculateButton = document.createElement('small') CalculateButton = document.createElement('small');
CalculateButton.classList = 'fw-normal text-success' CalculateButton.classList = 'fw-normal text-success';
CalculateButton.style.letterSpacing = '0px' CalculateButton.style.letterSpacing = '0px';
CalculateButton.setAttribute('data-bs-toggle', 'tooltip') CalculateButton.setAttribute('data-bs-toggle', 'tooltip');
CalculateButton.setAttribute('data-bs-title', 'Calculate this avatar\'s cost!') CalculateButton.setAttribute('data-bs-title', "Calculate this avatar's cost!");
CalculateButton.setAttribute('data-bs-placement', 'right') CalculateButton.setAttribute('data-bs-placement', 'right');
CalculateButton.innerHTML = ` CalculateButton.innerHTML = `
<a class="text-decoration-underline text-success" style="text-decoration-color: rgb(15, 132, 79) !important;">$ calculate</a> <a class="text-decoration-underline text-success" style="text-decoration-color: rgb(15, 132, 79) !important;">$ calculate</a>
` `;
AvatarHeading.appendChild(CalculateButton) AvatarHeading.appendChild(CalculateButton);
Utilities.InjectResource('registerTooltips') Utilities.InjectResource('registerTooltips');
let Calculating = false let Calculating = false;
CalculateButton.addEventListener('click', function(){ CalculateButton.addEventListener('click', function () {
if (Calculating === false) { if (Calculating === false) {
Calculating = true Calculating = true;
CalculateButton.innerText = '$ Calculating...' CalculateButton.innerText = '$ Calculating...';
OutfitCost() OutfitCost();
} }
}); });
} }
}); });
})(); })();
const AvatarIFrame = document.querySelector('[src^="/ptstatic"]') const AvatarIFrame = document.querySelector('[src^="/ptstatic"]');
const DropdownMenu = document.getElementsByClassName('dropdown-menu dropdown-menu-right')[0] const DropdownMenu = document.getElementsByClassName('dropdown-menu dropdown-menu-right')[0];
const CopyItem = document.createElement('a') const CopyItem = document.createElement('a');
CopyItem.classList = 'dropdown-item text-primary' CopyItem.classList = 'dropdown-item text-primary';
CopyItem.href = '#' CopyItem.href = '#';
CopyItem.innerHTML = ` CopyItem.innerHTML = `
<i class="fa-duotone fa-book"></i> <i class="fa-duotone fa-book"></i>
Copy 3D Avatar URL Copy 3D Avatar URL
` `;
DropdownMenu.appendChild(CopyItem) DropdownMenu.appendChild(CopyItem);
CopyItem.addEventListener('click', function(){ CopyItem.addEventListener('click', function () {
navigator.clipboard.writeText(AvatarIFrame.src) navigator.clipboard
.then(() => { .writeText(AvatarIFrame.src)
alert('Successfully copied 3D avatar URL!') .then(() => {
}) alert('Successfully copied 3D avatar URL!');
.catch(() => { })
alert('Failure to copy 3D avatar URL.') .catch(() => {
}); alert('Failure to copy 3D avatar URL.');
}); });
});
const ShareItem = document.createElement('a') const ShareItem = document.createElement('a');
ShareItem.classList = 'dropdown-item text-warning' ShareItem.classList = 'dropdown-item text-warning';
ShareItem.href = '#' ShareItem.href = '#';
ShareItem.innerHTML = ` ShareItem.innerHTML = `
<i class="fa-duotone fa-book"></i> <i class="fa-duotone fa-book"></i>
Share your 3D Avatar URL! Share your 3D Avatar URL!
` `;
DropdownMenu.appendChild(ShareItem) DropdownMenu.appendChild(ShareItem);
ShareItem.addEventListener('click', function(){ ShareItem.addEventListener('click', function () {
navigator.clipboard.writeText("Hey! Look at my Polytoria avatar in 3D [here](" + AvatarIFrame.src + ")!") navigator.clipboard
.then(() => { .writeText('Hey! Look at my Polytoria avatar in 3D [here](' + AvatarIFrame.src + ')!')
alert('Successfully copied sharable 3D avatar URL!') .then(() => {
}) alert('Successfully copied sharable 3D avatar URL!');
.catch(() => { })
alert('Failure to copy sharable 3D avatar URL.') .catch(() => {
}); alert('Failure to copy sharable 3D avatar URL.');
}); });
} else if (UserID && UserID[0] === "@") { });
const Username = window.location.pathname.split('/')[2].substring(1) } else if (UserID && UserID[0] === '@') {
const Username = window.location.pathname.split('/')[2].substring(1);
let Reference = new URLSearchParams(new URL(window.location.href).search) let Reference = new URLSearchParams(new URL(window.location.href).search);
if (!Reference.has('ref')) { if (!Reference.has('ref')) {
Reference = "" Reference = '';
} }
fetch("https://api.polytoria.com/v1/users/find?username=" + Username) fetch('https://api.polytoria.com/v1/users/find?username=' + Username)
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
window.location.href = window.location.origin + decodeURIComponent(Reference.get('ref')) window.location.href = window.location.origin + decodeURIComponent(Reference.get('ref'));
} else { } else {
return response.json() return response.json();
} }
}) })
.then(data => { .then((data) => {
window.location.href = "https://polytoria.com/users/" + data.id window.location.href = 'https://polytoria.com/users/' + data.id;
}) })
.catch(error => { .catch((error) => {
console.log("An error occurred:", error); console.log('An error occurred:', error);
}); });
} }
async function IRLPrice() { async function IRLPrice() {
const NetWorthElement = document.getElementsByClassName('float-end text-success')[0]; const NetWorthElement = document.getElementsByClassName('float-end text-success')[0];
const IRLResult = await Utilities.CalculateIRL(NetWorthElement.innerText, Settings.IRLPriceWithCurrency.Currency) const IRLResult = await Utilities.CalculateIRL(NetWorthElement.innerText, Settings.IRLPriceWithCurrency.Currency);
NetWorthElement.innerHTML = NetWorthElement.innerHTML + '<div class="text-muted" style="font-size: 0.6rem;">(' + IRLResult.icon + IRLResult.result + ' ' + IRLResult.display + ')</div>' NetWorthElement.innerHTML = NetWorthElement.innerHTML + '<div class="text-muted" style="font-size: 0.6rem;">(' + IRLResult.icon + IRLResult.result + ' ' + IRLResult.display + ')</div>';
} }
function BestFriends() { function BestFriends() {
chrome.storage.sync.get(['PolyPlus_BestFriends'], function(result){ chrome.storage.sync.get(['PolyPlus_BestFriends'], function (result) {
BestFriends = result.PolyPlus_BestFriends || []; BestFriends = result.PolyPlus_BestFriends || [];
FavoriteBtn = document.createElement('button'); FavoriteBtn = document.createElement('button');
FavoriteBtn.classList = 'btn btn-warning btn-sm ml-2'; FavoriteBtn.classList = 'btn btn-warning btn-sm ml-2';
if (!(BestFriends.length === Utilities.Limits.BestFriends)) { if (!(BestFriends.length === Utilities.Limits.BestFriends)) {
if (Array.isArray(BestFriends) && BestFriends.includes(parseInt(UserID))) { if (Array.isArray(BestFriends) && BestFriends.includes(parseInt(UserID))) {
FavoriteBtn.innerText = 'Remove Best Friend Status'; FavoriteBtn.innerText = 'Remove Best Friend Status';
} else { } else {
FavoriteBtn.innerText = 'Best Friend'; FavoriteBtn.innerText = 'Best Friend';
} }
} else { } else {
FavoriteBtn.innerText = 'Remove Best Friend Status (max ' + Utilities.Limits.BestFriends + '/' + Utilities.Limits.BestFriends + ')' FavoriteBtn.innerText = 'Remove Best Friend Status (max ' + Utilities.Limits.BestFriends + '/' + Utilities.Limits.BestFriends + ')';
} }
if (UserID !== JSON.parse(window.localStorage.getItem('p+account_info')).ID && document.getElementById('add-friend-button').classList.contains('btn-success') === false) { if (UserID !== JSON.parse(window.localStorage.getItem('p+account_info')).ID && document.getElementById('add-friend-button').classList.contains('btn-success') === false) {
FavoriteBtn.addEventListener('click', function() { FavoriteBtn.addEventListener('click', function () {
Fav(UserID, FavoriteBtn); Fav(UserID, FavoriteBtn);
}); });
} else { } else {
FavoriteBtn.style.display = 'none' FavoriteBtn.style.display = 'none';
} }
document.querySelectorAll('.section-title.px-3.px-lg-0.mt-3')[0].appendChild(FavoriteBtn); document.querySelectorAll('.section-title.px-3.px-lg-0.mt-3')[0].appendChild(FavoriteBtn);
function Fav(UserID, btn) { function Fav(UserID, btn) {
if (UserID === JSON.parse(window.localStorage.getItem('p+account_info')).ID) { return } if (UserID === JSON.parse(window.localStorage.getItem('p+account_info')).ID) {
btn.setAttribute('disabled', 'true') return;
}
btn.setAttribute('disabled', 'true');
chrome.storage.sync.get(['PolyPlus_BestFriends'], function(result) { chrome.storage.sync.get(['PolyPlus_BestFriends'], function (result) {
const BestFriends = result.PolyPlus_BestFriends || []; const BestFriends = result.PolyPlus_BestFriends || [];
const index = BestFriends.indexOf(parseInt(UserID)); const index = BestFriends.indexOf(parseInt(UserID));
if (index !== -1) { if (index !== -1) {
// Number exists, remove it // Number exists, remove it
BestFriends.splice(index, 1); BestFriends.splice(index, 1);
btn.innerText = "Best Friend" btn.innerText = 'Best Friend';
console.log('Number', parseInt(UserID), 'removed from BestFriends'); console.log('Number', parseInt(UserID), 'removed from BestFriends');
} else { } else {
// Number doesn't exist, add it // Number doesn't exist, add it
BestFriends.push(parseInt(UserID)); BestFriends.push(parseInt(UserID));
btn.innerText = "Remove Best Friend Status" btn.innerText = 'Remove Best Friend Status';
console.log('Number', parseInt(UserID), 'added to BestFriends'); console.log('Number', parseInt(UserID), 'added to BestFriends');
} }
chrome.storage.sync.set({ 'PolyPlus_BestFriends': BestFriends, arrayOrder: true }, function() { chrome.storage.sync.set({PolyPlus_BestFriends: BestFriends, arrayOrder: true}, function () {
console.log('BestFriends saved successfully!'); console.log('BestFriends saved successfully!');
setTimeout(function() { setTimeout(function () {
btn.removeAttribute('disabled') btn.removeAttribute('disabled');
}, 1500) }, 1500);
}); });
}); });
} }
}); });
chrome.storage.onChanged.addListener(function(changes, namespace) { chrome.storage.onChanged.addListener(function (changes, namespace) {
if ('PolyPlus_BestFriends' in changes) { if ('PolyPlus_BestFriends' in changes) {
chrome.storage.sync.get(['PolyPlus_BestFriends'], function(result) { chrome.storage.sync.get(['PolyPlus_BestFriends'], function (result) {
BestFriends = result.PolyPlus_BestFriends || []; BestFriends = result.PolyPlus_BestFriends || [];
if (!(BestFriends.length === Utilities.Limits.BestFriends)) { if (!(BestFriends.length === Utilities.Limits.BestFriends)) {
if (Array.isArray(BestFriends) && BestFriends.includes(parseInt(UserID))) { if (Array.isArray(BestFriends) && BestFriends.includes(parseInt(UserID))) {
FavoriteBtn.innerText = 'Remove Best Friend Status' FavoriteBtn.innerText = 'Remove Best Friend Status';
} else { } else {
FavoriteBtn.innerText = 'Best Friend' FavoriteBtn.innerText = 'Best Friend';
} }
} else { } else {
FavoriteBtn.innerText = 'Remove Best Friend Status (max ' + Utilities.Limits.BestFriends + '/' + Utilities.Limits.BestFriends + ')' FavoriteBtn.innerText = 'Remove Best Friend Status (max ' + Utilities.Limits.BestFriends + '/' + Utilities.Limits.BestFriends + ')';
} }
}); });
} }
}); });
function ClearBestFriends(){ function ClearBestFriends() {
chrome.storage.sync.set({ 'PolyPlus_BestFriends': {"BestFriends": []}, arrayOrder: true }, function() { chrome.storage.sync.set({PolyPlus_BestFriends: {BestFriends: []}, arrayOrder: true}, function () {
console.log('BestFriends saved successfully!'); console.log('BestFriends saved successfully!');
setTimeout(function() { setTimeout(function () {
btn.removeAttribute('disabled') btn.removeAttribute('disabled');
}, 1500) }, 1500);
}); });
} }
} }
async function OutfitCost() { async function OutfitCost() {
const AvatarCost = { const AvatarCost = {
Total: 0, Total: 0,
Collectibles: 0, Collectibles: 0,
Offsale: 0, Offsale: 0,
HasProfileTheme: false HasProfileTheme: false
} };
for (let item of AvatarRow.children) { for (let item of AvatarRow.children) {
const ItemID = item.getElementsByTagName('a')[0].href.split('/')[4] const ItemID = item.getElementsByTagName('a')[0].href.split('/')[4];
await fetch('https://api.polytoria.com/v1/store/'+ItemID) await fetch('https://api.polytoria.com/v1/store/' + ItemID)
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
let Price = data.price let Price = data.price;
if (data.isLimited === true) { if (data.isLimited === true) {
AvatarCost.Collectibles += 1 AvatarCost.Collectibles += 1;
Price = data.averagePrice Price = data.averagePrice;
} else if (data.sales === 0) { } else if (data.sales === 0) {
AvatarCost.Offsale += 1 AvatarCost.Offsale += 1;
Price = 0 Price = 0;
} else if (data.type === 'profileTheme') { } else if (data.type === 'profileTheme') {
AvatarCost.HasProfileTheme = true AvatarCost.HasProfileTheme = true;
Price = 0 Price = 0;
} }
AvatarCost.Total += Price AvatarCost.Total += Price;
}) })
.catch(error => {console.log(error)}); .catch((error) => {
} console.log(error);
const ResultText = document.createElement('small') });
ResultText.classList = 'fw-normal text-success' }
ResultText.style.letterSpacing = '0px' const ResultText = document.createElement('small');
ResultText.innerHTML = `(<i class="pi pi-brick mx-1"></i> ${ (AvatarCost.Collectibles > 0 || AvatarCost.Offsale > 0 || AvatarCost.HasProfileTheme === true) ? '~' : '' }${ AvatarCost.Total.toLocaleString() } | ${ (AvatarCost.Collectibles > 0) ? AvatarCost.Collectibles + ' collectible' : '' }${ (AvatarCost.Offsale > 0) ? `, ${AvatarCost.Offsale} offsale` : '' }${ (AvatarCost.HasProfileTheme === true) ? ', profile theme excluded' : '' })` ResultText.classList = 'fw-normal text-success';
ResultText.style.letterSpacing = '0px';
ResultText.innerHTML = `(<i class="pi pi-brick mx-1"></i> ${AvatarCost.Collectibles > 0 || AvatarCost.Offsale > 0 || AvatarCost.HasProfileTheme === true ? '~' : ''}${AvatarCost.Total.toLocaleString()} | ${AvatarCost.Collectibles > 0 ? AvatarCost.Collectibles + ' collectible' : ''}${AvatarCost.Offsale > 0 ? `, ${AvatarCost.Offsale} offsale` : ''}${AvatarCost.HasProfileTheme === true ? ', profile theme excluded' : ''})`;
CalculateButton.remove() CalculateButton.remove();
AvatarHeading.appendChild(ResultText) AvatarHeading.appendChild(ResultText);
} }

View file

@ -1,30 +1,30 @@
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){ chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
if (result.PolyPlus_Settings.MoreSearchFiltersOn === true) { if (result.PolyPlus_Settings.MoreSearchFiltersOn === true) {
const BlockedUsersCard = document.getElementsByClassName('card-body')[1] const BlockedUsersCard = document.getElementsByClassName('card-body')[1];
const InputGroup = document.createElement('div') const InputGroup = document.createElement('div');
InputGroup.classList = 'input-group mb-2' InputGroup.classList = 'input-group mb-2';
InputGroup.innerHTML = ` InputGroup.innerHTML = `
<input id="blocked-users-search" type="text" class="form-control bg-dark" placeholder="Search blocked users..."> <input id="blocked-users-search" type="text" class="form-control bg-dark" placeholder="Search blocked users...">
<button id="blocked-users-confirm" class="btn btn-secondary"><i class="fad fa-search"></i></button> <button id="blocked-users-confirm" class="btn btn-secondary"><i class="fad fa-search"></i></button>
` `;
BlockedUsersCard.insertBefore(InputGroup, BlockedUsersCard.children[0]) BlockedUsersCard.insertBefore(InputGroup, BlockedUsersCard.children[0]);
const SearchBar = document.getElementById('blocked-users-search') const SearchBar = document.getElementById('blocked-users-search');
const ConfirmBtn = document.getElementById('blocked-users-confirm') const ConfirmBtn = document.getElementById('blocked-users-confirm');
ConfirmBtn.addEventListener('click', function(){ ConfirmBtn.addEventListener('click', function () {
SearchBlockedUsers(SearchBar.value); SearchBlockedUsers(SearchBar.value);
}); });
function SearchBlockedUsers(query) { function SearchBlockedUsers(query) {
query = query.toLowerCase(); query = query.toLowerCase();
for (let i = 1; i < BlockedUsersCard.children.length; i++) { for (let i = 1; i < BlockedUsersCard.children.length; i++) {
let Username = BlockedUsersCard.children[i].getElementsByTagName('h5')[0].innerText.toLowerCase(); let Username = BlockedUsersCard.children[i].getElementsByTagName('h5')[0].innerText.toLowerCase();
if (Username.includes(query)) { if (Username.includes(query)) {
BlockedUsersCard.children[i].style.display = 'block' BlockedUsersCard.children[i].style.display = 'block';
} else { } else {
BlockedUsersCard.children[i].style.display = 'none' BlockedUsersCard.children[i].style.display = 'none';
} }
} }
} }
} }
}); });

View file

@ -1,109 +1,108 @@
var SelectedTrades = [] var SelectedTrades = [];
let Parent = document.getElementsByClassName('card mcard p-5 text-center text-muted')[0].parentElement let Parent = document.getElementsByClassName('card mcard p-5 text-center text-muted')[0].parentElement;
let Text = document.createElement('p') let Text = document.createElement('p');
Text.classList = 'mx-auto' Text.classList = 'mx-auto';
Text.style.textAlign = 'center' Text.style.textAlign = 'center';
Text.style.fontSize = '1.3rem' Text.style.fontSize = '1.3rem';
Text.innerHTML = ` Text.innerHTML = `
<span>0</span> trades selected! <span>0</span> trades selected!
<br> <br>
<button id="viewSelectionBtn" class="btn btn-primary">View Selection</button> <button id="viewSelectionBtn" class="btn btn-primary">View Selection</button>
<button id="clearSelectionBtn" class="btn btn-warning">Clear Selection</button> <button id="clearSelectionBtn" class="btn btn-warning">Clear Selection</button>
<button id="cancelSelectionBtn" class="btn btn-danger">Cancel Selected Trades</button> <button id="cancelSelectionBtn" class="btn btn-danger">Cancel Selected Trades</button>
` `;
Parent.insertBefore(Text, Parent.children[0]) Parent.insertBefore(Text, Parent.children[0]);
let Text_Span = Text.querySelector('span'); let Text_Span = Text.querySelector('span');
let Text_View = document.getElementById('viewSelectionBtn'); let Text_View = document.getElementById('viewSelectionBtn');
let Text_Clear = document.getElementById('clearSelectionBtn'); let Text_Clear = document.getElementById('clearSelectionBtn');
let Text_Cancel = document.getElementById('cancelSelectionBtn'); let Text_Cancel = document.getElementById('cancelSelectionBtn');
var ConfirmCancel = 0 var ConfirmCancel = 0;
Text_View.addEventListener('click', function(){}); Text_View.addEventListener('click', function () {});
Text_Clear.addEventListener('click', function(){ Text_Clear.addEventListener('click', function () {
SelectedTrades = [] SelectedTrades = [];
UpdateCheckboxes(); UpdateCheckboxes();
Text_Span.innerText = SelectedTrades.length Text_Span.innerText = SelectedTrades.length;
}); });
Text_Cancel.addEventListener('click', function(){ Text_Cancel.addEventListener('click', function () {
ConfirmCancel = ConfirmCancel + 1 ConfirmCancel = ConfirmCancel + 1;
switch(ConfirmCancel) { switch (ConfirmCancel) {
case 0: case 0:
Text_Cancel.innerText = 'Cancel Selected Trades' Text_Cancel.innerText = 'Cancel Selected Trades';
break break;
case 1: case 1:
Text_Cancel.innerText = 'Are you sure?' Text_Cancel.innerText = 'Are you sure?';
break break;
case 2: case 2:
let Success = true let Success = true;
for (let i = 0; i < SelectedTrades.length; i++) { for (let i = 0; i < SelectedTrades.length; i++) {
setTimeout(function () {}, 110) setTimeout(function () {}, 110);
console.log(SelectedTrades[i]) console.log(SelectedTrades[i]);
fetch('https://polytoria.com/api/trade/decline', { fetch('https://polytoria.com/api/trade/decline', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value 'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
}, },
body: JSON.stringify({ id: SelectedTrades[i] }), body: JSON.stringify({id: SelectedTrades[i]})
}) }).catch((error) => {
.catch(error => { // Handle any errors
// Handle any errors console.error('Error:', error);
console.error('Error:', error); Success = false;
Success = false });
}); }
} SelectedTrades = [];
SelectedTrades = [] UpdateCheckboxes();
UpdateCheckboxes(); Text_Cancel.innerText = 'Cancel Selected Trades';
Text_Cancel.innerText = 'Cancel Selected Trades' ConfirmCancel = 0;
ConfirmCancel = 0 break;
break }
}
}); });
LoadCheckBoxes(); LoadCheckBoxes();
function LoadCheckBoxes() { function LoadCheckBoxes() {
Array.from(document.getElementsByClassName('card-inbox')).forEach(element => { Array.from(document.getElementsByClassName('card-inbox')).forEach((element) => {
let ViewBtn = element.querySelector('a.btn.btn-primary') let ViewBtn = element.querySelector('a.btn.btn-primary');
let TradeID = parseInt(ViewBtn.getAttribute('href').split('/')[3]) let TradeID = parseInt(ViewBtn.getAttribute('href').split('/')[3]);
var NewCheckBox = document.createElement('button') var NewCheckBox = document.createElement('button');
NewCheckBox.classList = 'polyplus-multicanceltr-checkbox' NewCheckBox.classList = 'polyplus-multicanceltr-checkbox';
NewCheckBox.setAttribute('style', 'padding: 20px; background-color: #191919; border: 1px solid #393939; border-radius: 1rem; margin-left: 10px;') NewCheckBox.setAttribute('style', 'padding: 20px; background-color: #191919; border: 1px solid #393939; border-radius: 1rem; margin-left: 10px;');
var Index = SelectedTrades.indexOf(TradeID) var Index = SelectedTrades.indexOf(TradeID);
if (Index !== -1) { if (Index !== -1) {
NewCheckBox.style.borderColor = 'lime' NewCheckBox.style.borderColor = 'lime';
} }
ViewBtn.parentElement.appendChild(NewCheckBox) ViewBtn.parentElement.appendChild(NewCheckBox);
NewCheckBox.addEventListener('click', function(){ NewCheckBox.addEventListener('click', function () {
var Index = SelectedTrades.indexOf(TradeID) var Index = SelectedTrades.indexOf(TradeID);
if (Index === -1) { if (Index === -1) {
SelectedTrades.push(TradeID) SelectedTrades.push(TradeID);
NewCheckBox.style.borderColor = 'lime' NewCheckBox.style.borderColor = 'lime';
} else { } else {
SelectedTrades.splice(Index, 1) SelectedTrades.splice(Index, 1);
NewCheckBox.style.borderColor = '#393939' NewCheckBox.style.borderColor = '#393939';
} }
Text_Span.innerText = SelectedTrades.length Text_Span.innerText = SelectedTrades.length;
UpdateCheckboxes(); UpdateCheckboxes();
}); });
}); });
} }
function UpdateCheckboxes(){ function UpdateCheckboxes() {
document.querySelectorAll('.polyplus-multicanceltr-checkbox').forEach(element => { document.querySelectorAll('.polyplus-multicanceltr-checkbox').forEach((element) => {
let Parent = element.parentElement let Parent = element.parentElement;
let ViewBtn = Parent.querySelector('a.btn.btn-primary') let ViewBtn = Parent.querySelector('a.btn.btn-primary');
if (element.getAttribute('disabled')) { if (element.getAttribute('disabled')) {
element.removeAttribute('disabled') element.removeAttribute('disabled');
} }
if (SelectedTrades.IndexOf(ViewBtn.getAttribute('data-user-id')) === -1) { if (SelectedTrades.IndexOf(ViewBtn.getAttribute('data-user-id')) === -1) {
element.style.borderColor = '#393939' element.style.borderColor = '#393939';
} else { } else {
element.style.borderColor = 'lime' element.style.borderColor = 'lime';
if (SelectedTrades.length >= 10) { if (SelectedTrades.length >= 10) {
element.setAttribute('disabled', true) element.setAttribute('disabled', true);
} }
} }
}) });
} }

View file

@ -9,12 +9,12 @@ LoadFile(chrome.runtime.getURL('resources/currencies.json'), function(text){
let Utilities; let Utilities;
(async () => { (async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js')); Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default Utilities = Utilities.default;
})(); })();
let Nav = document.getElementsByClassName('nav-pills')[0] let Nav = document.getElementsByClassName('nav-pills')[0];
let DIV = document.createElement('div') let DIV = document.createElement('div');
DIV.innerHTML = ` DIV.innerHTML = `
<input id="polyplus-brickconverter-input" type="number" class="form-control bg-dark mb-2" placeholder="How many Bricks?"> <input id="polyplus-brickconverter-input" type="number" class="form-control bg-dark mb-2" placeholder="How many Bricks?">
<input id="polyplus-brickconverter-output" type="text" class="form-control bg-dark mb-2" placeholder="Result" disabled> <input id="polyplus-brickconverter-output" type="text" class="form-control bg-dark mb-2" placeholder="Result" disabled>
@ -37,24 +37,24 @@ DIV.innerHTML = `
<option value="5">d</option> <option value="5">d</option>
</select> </select>
--> -->
` `;
Nav.appendChild(document.createElement('hr')) Nav.appendChild(document.createElement('hr'));
Nav.appendChild(DIV) Nav.appendChild(DIV);
let Input = document.getElementById('polyplus-brickconverter-input') let Input = document.getElementById('polyplus-brickconverter-input');
let Output = document.getElementById('polyplus-brickconverter-output') let Output = document.getElementById('polyplus-brickconverter-output');
let Type = document.getElementById('polyplus-brickconverter-type') let Type = document.getElementById('polyplus-brickconverter-type');
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){ chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Type.selectedIndex = result.PolyPlus_Settings.IRLPriceWithCurrency.Currency || 0 Type.selectedIndex = result.PolyPlus_Settings.IRLPriceWithCurrency.Currency || 0;
}); });
//let Package = document.getElementById('polyplus-brickconverter-package') //let Package = document.getElementById('polyplus-brickconverter-package')
Input.addEventListener('input', function(){ Input.addEventListener('input', function () {
Update() Update();
}); });
Type.addEventListener('change', function(){ Type.addEventListener('change', function () {
Update() Update();
}); });
/* /*
@ -63,18 +63,20 @@ Package.addEventListener('change', function(){
}); });
*/ */
async function Update(){ async function Update() {
if (Input.value === "") { if (Input.value === '') {
Output.value = '' Output.value = '';
return return;
} }
const IRLResult = await Utilities.CalculateIRL(Input.value, Type.selectedIndex) const IRLResult = await Utilities.CalculateIRL(Input.value, Type.selectedIndex);
Output.value = "$" + IRLResult.result + " " + IRLResult.display Output.value = '$' + IRLResult.result + ' ' + IRLResult.display;
} }
function LoadFile(path, callback) { function LoadFile(path, callback) {
var xhr = new XMLHttpRequest(); var xhr = new XMLHttpRequest();
xhr.onload = function () { return callback(this.responseText); } xhr.onload = function () {
xhr.open("GET", path, true); return callback(this.responseText);
xhr.send(); };
xhr.open('GET', path, true);
xhr.send();
} }

View file

@ -1,5 +1,5 @@
const Manifest = chrome.runtime.getManifest() const Manifest = chrome.runtime.getManifest();
const SettingsURL = chrome.runtime.getURL('settings.html') const SettingsURL = chrome.runtime.getURL('settings.html');
/* /*
ON INSTALL: ON INSTALL:
@ -11,158 +11,147 @@ chrome.runtime.onInstalled.addListener(() => {
// WHEN CLICKING ON EXTENSION ICON OPEN THE SETTINGS PAGE // WHEN CLICKING ON EXTENSION ICON OPEN THE SETTINGS PAGE
chrome.action.onClicked.addListener((tab) => { chrome.action.onClicked.addListener((tab) => {
chrome.tabs.create({ active: true, url: SettingsURL }); chrome.tabs.create({active: true, url: SettingsURL});
}); });
// REGISTER AN ALARM FOR DAILY UPDATE CHECK // REGISTER AN ALARM FOR DAILY UPDATE CHECK
chrome.alarms.create('PolyPlus-UpdateCheck', { chrome.alarms.create('PolyPlus-UpdateCheck', {
when: Date.now() + (GetNext12PM()) when: Date.now() + GetNext12PM()
}); });
function GetNext12PM() { function GetNext12PM() {
const Now = new Date(); const Now = new Date();
const Next = new Date(); const Next = new Date();
Next.setHours(12, 0, 0, 0); Next.setHours(12, 0, 0, 0);
if (Now.getHours() >= 12) { if (Now.getHours() >= 12) {
Next.setDate(Next.getDate() + 1); Next.setDate(Next.getDate() + 1);
} }
return Next - Now; return Next - Now;
} }
// HANDLE ALARMS FIRING // HANDLE ALARMS FIRING
chrome.alarms.onAlarm.addListener(function(alarm){ chrome.alarms.onAlarm.addListener(function (alarm) {
if (alarm.name === 'PolyPlus-UpdateCheck') { if (alarm.name === 'PolyPlus-UpdateCheck') {
RunUpdateNotifier() RunUpdateNotifier();
} }
}); });
function RunUpdateNotifier() { function RunUpdateNotifier() {
chrome.storage.local.get(["PolyPlus_LiveVersion", "PolyPlus_OutOfDate", "PolyPlus_SkipUpdate"], function(result){ chrome.storage.local.get(['PolyPlus_LiveVersion', 'PolyPlus_OutOfDate', 'PolyPlus_SkipUpdate'], function (result) {
const OutOfDate = result.PolyPlus_OutOfDate || false const OutOfDate = result.PolyPlus_OutOfDate || false;
const SkipUpdate = result.PolyPlus_SkipUpdate || null const SkipUpdate = result.PolyPlus_SkipUpdate || null;
const LiveVersion = result.PolyPlus_LiveVersion || Manifest.version const LiveVersion = result.PolyPlus_LiveVersion || Manifest.version;
if (OutOfDate !== true && SkipUpdate !== LiveVersion) { if (OutOfDate !== true && SkipUpdate !== LiveVersion) {
fetch('https://polyplus.vercel.app/data/version.json') fetch('https://polyplus.vercel.app/data/version.json')
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
chrome.storage.local.set({'PolyPlus_LiveVersion': data.version}, function(){ chrome.storage.local.set({PolyPlus_LiveVersion: data.version}, function () {
console.log('Cached live version') console.log('Cached live version');
}) });
if (data.version > Manifest.version) { if (data.version > Manifest.version) {
chrome.storage.local.set({'PolyPlus_OutOfDate': true, 'PolyPlus_ReleaseNotes': data.releaseNotes}, function(){ chrome.storage.local.set({PolyPlus_OutOfDate: true, PolyPlus_ReleaseNotes: data.releaseNotes}, function () {
console.log('Cached update notifier result') console.log('Cached update notifier result');
}); });
chrome.notifications.create("", { chrome.notifications.create(
type: "basic", '',
iconUrl: chrome.runtime.getURL("icon.png"), {
title: "New Update Available", type: 'basic',
message: "A new update is available for Poly+! (v" + data.version + ")" iconUrl: chrome.runtime.getURL('icon.png'),
}, function(notificationID) { title: 'New Update Available',
chrome.notifications.onClicked.addListener(function (id) { message: 'A new update is available for Poly+! (v' + data.version + ')'
if (id === notificationID) { },
chrome.tabs.create({url: 'https://github.com/IndexingGitHub/PolyPlus/releases', active: true}) function (notificationID) {
chrome.notifications.clear(notificationID) chrome.notifications.onClicked.addListener(function (id) {
} if (id === notificationID) {
}) chrome.tabs.create({url: 'https://github.com/IndexingGitHub/PolyPlus/releases', active: true});
}) chrome.notifications.clear(notificationID);
chrome.action.setBadgeBackgroundColor( }
{color: 'red'}, });
() => { /* ... */ }, }
); );
} chrome.action.setBadgeBackgroundColor({color: 'red'}, () => {
}) /* ... */
.catch(error => {console.log(error)}) });
} }
}); })
.catch((error) => {
console.log(error);
});
}
});
} }
chrome.contextMenus.removeAll(function() { chrome.contextMenus.removeAll(function () {
chrome.contextMenus.create({ chrome.contextMenus.create({
title: 'Run Update Notifier', title: 'Run Update Notifier',
id: 'PolyPlus-RunUpdateNotifier', id: 'PolyPlus-RunUpdateNotifier',
contexts: ['all'], contexts: ['all'],
documentUrlPatterns: [ documentUrlPatterns: ['https://polytoria.com/my/settings/polyplus-debug']
"https://polytoria.com/my/settings/polyplus-debug", });
]
});
// COPY ASSET ID CONTEXT MENU ITEM REGISTRATION // COPY ASSET ID CONTEXT MENU ITEM REGISTRATION
chrome.contextMenus.create({ chrome.contextMenus.create({
title: 'Copy Asset ID', title: 'Copy Asset ID',
id: 'PolyPlus-CopyID', id: 'PolyPlus-CopyID',
contexts: ['link'], contexts: ['link'],
documentUrlPatterns: [ documentUrlPatterns: ['https://polytoria.com/*', SettingsURL],
"https://polytoria.com/*", targetUrlPatterns: ['https://polytoria.com/places/**', 'https://polytoria.com/users/**', 'https://polytoria.com/store/**']
SettingsURL });
],
targetUrlPatterns: [
"https://polytoria.com/places/**",
"https://polytoria.com/users/**",
"https://polytoria.com/store/**"
]
});
// COPY AVATAR HASH CONTEXT MENU ITEM REGISTRATION // COPY AVATAR HASH CONTEXT MENU ITEM REGISTRATION
chrome.contextMenus.create({ chrome.contextMenus.create({
title: 'Copy Avatar Hash', title: 'Copy Avatar Hash',
id: 'PolyPlus-CopyAvatarHash', id: 'PolyPlus-CopyAvatarHash',
contexts: ['image'], contexts: ['image'],
documentUrlPatterns: [ documentUrlPatterns: ['https://polytoria.com/*', SettingsURL],
"https://polytoria.com/*", targetUrlPatterns: ['https://c0.ptacdn.com/thumbnails/avatars/**', 'https://c0.ptacdn.com/thumbnails/avatars/**']
SettingsURL });
], });
targetUrlPatterns: [
"https://c0.ptacdn.com/thumbnails/avatars/**",
"https://c0.ptacdn.com/thumbnails/avatars/**"
]
});
})
// HANDLE CONTEXT MENU ITEMS // HANDLE CONTEXT MENU ITEMS
chrome.contextMenus.onClicked.addListener(function (info, tab){ chrome.contextMenus.onClicked.addListener(function (info, tab) {
if (info.menuItemId === 'PolyPlus-CopyID') { if (info.menuItemId === 'PolyPlus-CopyID') {
let ID = parseInt(info.linkUrl.split('/')[4]) let ID = parseInt(info.linkUrl.split('/')[4]);
chrome.scripting chrome.scripting
.executeScript({ .executeScript({
target: {tabId: tab.id}, target: {tabId: tab.id},
func: CopyAssetID, func: CopyAssetID,
args: [ID] args: [ID]
}) })
.then(() => console.log("Copied ID!")); .then(() => console.log('Copied ID!'));
} }
if (info.menuItemId === 'PolyPlus-CopyAvatarHash') { if (info.menuItemId === 'PolyPlus-CopyAvatarHash') {
let Hash = new URL(info.srcUrl).pathname.split('/')[3].replace('-icon', '').replace('.png', '') let Hash = new URL(info.srcUrl).pathname.split('/')[3].replace('-icon', '').replace('.png', '');
chrome.scripting chrome.scripting
.executeScript({ .executeScript({
target: {tabId: tab.id}, target: {tabId: tab.id},
func: CopyAvatarHash, func: CopyAvatarHash,
args: [Hash] args: [Hash]
}) })
.then(() => console.log("Copied ID!")); .then(() => console.log('Copied ID!'));
} }
if (info.menuItemId === 'PolyPlus-RunUpdateNotifier') { if (info.menuItemId === 'PolyPlus-RunUpdateNotifier') {
RunUpdateNotifier() RunUpdateNotifier();
} }
}); });
chrome.runtime.onMessage.addListener(function (message, sender) { chrome.runtime.onMessage.addListener(function (message, sender) {
console.log('hi') console.log('hi');
message = message.message || '' message = message.message || '';
console.log(message) console.log(message);
if (message === 'tooltip') { if (message === 'tooltip') {
console.log('is about tooltip') console.log('is about tooltip');
chrome.scripting chrome.scripting.executeScript({
.executeScript({ target: {tabId: sender.tab.id},
target: {tabId: sender.tab.id}, func: UpdateTooltips
func: UpdateTooltips });
}) }
}
}); });
/* /*
@ -199,32 +188,32 @@ function matchesUrl(patterns, url) {
*/ */
function CopyAssetID(id) { function CopyAssetID(id) {
navigator.clipboard navigator.clipboard
.writeText(id) .writeText(id)
.then(() => { .then(() => {
alert('Successfully copied ID!') alert('Successfully copied ID!');
}) })
.catch(() => { .catch(() => {
alert('Failure to copy ID.') alert('Failure to copy ID.');
}); });
} }
function CopyAvatarHash(hash) { function CopyAvatarHash(hash) {
navigator.clipboard navigator.clipboard
.writeText(hash) .writeText(hash)
.then(() => { .then(() => {
alert('Successfully copied avatar hash!') alert('Successfully copied avatar hash!');
}) })
.catch(() => { .catch(() => {
alert('Failure to copy avatar hash.') alert('Failure to copy avatar hash.');
}); });
} }
function UpdateTooltips() { function UpdateTooltips() {
const Script = document.createElement('script') const Script = document.createElement('script');
Script.innerHTML = ` Script.innerHTML = `
const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]') const tooltipTriggerList = document.querySelectorAll('[data-bs-toggle="tooltip"]')
const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl)) const tooltipList = [...tooltipTriggerList].map(tooltipTriggerEl => new bootstrap.Tooltip(tooltipTriggerEl))
` `;
document.body.appendChild(Script) document.body.appendChild(Script);
} }

View file

@ -3,12 +3,12 @@
Accessable at /my/settings/polyplus#dev Accessable at /my/settings/polyplus#dev
*/ */
if (window.location.pathname.split('/')[3] === "polyplus" && window.location.hash === '#dev') { if (window.location.pathname.split('/')[3] === 'polyplus' && window.location.hash === '#dev') {
document.title = 'Poly+ Debug - Polytoria' document.title = 'Poly+ Debug - Polytoria';
const Version = chrome.runtime.getManifest().version const Version = chrome.runtime.getManifest().version;
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function () {
document.querySelector('#main-content .container').innerHTML = ` document.querySelector('#main-content .container').innerHTML = `
<style> <style>
#main-content .container label { #main-content .container label {
font-size: 0.8rem; font-size: 0.8rem;
@ -101,133 +101,141 @@ if (window.location.pathname.split('/')[3] === "polyplus" && window.location.has
</div> </div>
</div> </div>
</div> </div>
` `;
const CheckForUpdatesButton = document.getElementById('check-for-updates') const CheckForUpdatesButton = document.getElementById('check-for-updates');
function CheckForUpdates() { function CheckForUpdates() {
CheckForUpdatesButton.removeEventListener('click', CheckForUpdates) CheckForUpdatesButton.removeEventListener('click', CheckForUpdates);
CheckForUpdatesButton.disabled = true CheckForUpdatesButton.disabled = true;
fetch('https://polyplus.vercel.app/data/version.json') fetch('https://polyplus.vercel.app/data/version.json')
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
if (data.version === Version || Math.floor((data.version - Version) * 10) === 0) { if (data.version === Version || Math.floor((data.version - Version) * 10) === 0) {
CheckForUpdatesButton.innerText = 'No updates available' CheckForUpdatesButton.innerText = 'No updates available';
} else { } else {
CheckForUpdatesButton.innerText = Math.floor((data.version - Version) * 10) + ' updates available' CheckForUpdatesButton.innerText = Math.floor((data.version - Version) * 10) + ' updates available';
} }
}) })
.catch(error => {console.log(error)}); .catch((error) => {
} console.log(error);
CheckForUpdatesButton.addEventListener('click', CheckForUpdates); });
}
CheckForUpdatesButton.addEventListener('click', CheckForUpdates);
document.getElementById('edit-setting').addEventListener('click', function(){ document.getElementById('edit-setting').addEventListener('click', function () {
const EditSettingName = document.getElementById('edit-setting-name') const EditSettingName = document.getElementById('edit-setting-name');
const EditSettingValue = document.getElementById('edit-setting-value') const EditSettingValue = document.getElementById('edit-setting-value');
chrome.storage.sync.get(['PolyPlus_Settings'], function(result) { chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
result = result.PolyPlus_Settings result = result.PolyPlus_Settings;
let NewValue = EditSettingValue.value let NewValue = EditSettingValue.value;
switch (NewValue) { switch (NewValue) {
case 'true': case 'true':
NewValue = true NewValue = true;
break break;
case 'false': case 'false':
NewValue = false NewValue = false;
break break;
case 'null': case 'null':
NewValue = null NewValue = null;
break break;
case 'undefined': case 'undefined':
NewValue = undefined NewValue = undefined;
break break;
case parseInt(NewValue): case parseInt(NewValue):
NewValue = parseInt(NewValue) NewValue = parseInt(NewValue);
break break;
} }
result[EditSettingName.value] = NewValue result[EditSettingName.value] = NewValue;
chrome.storage.sync.set({ 'PolyPlus_Settings': result }, function() { chrome.storage.sync.set({PolyPlus_Settings: result}, function () {
alert('Successfully set: "' + EditSettingName.value + '" to ' + NewValue) alert('Successfully set: "' + EditSettingName.value + '" to ' + NewValue);
}); });
}); });
}); });
document.getElementById('reset-settings').addEventListener('click', async function(){ document.getElementById('reset-settings').addEventListener('click', async function () {
let Utilities = await import(chrome.runtime.getURL('resources/utils.js')) let Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default Utilities = Utilities.default;
chrome.storage.sync.set({ 'PolyPlus_Settings': Utilities.DefaultSettings }, function() { chrome.storage.sync.set({PolyPlus_Settings: Utilities.DefaultSettings}, function () {
alert('Successfully reset settings to their defaults!') alert('Successfully reset settings to their defaults!');
}); });
}); });
document.getElementById('example-pinnedgames').addEventListener('click', function(){ document.getElementById('example-pinnedgames').addEventListener('click', function () {
chrome.storage.sync.set({ 'PolyPlus_PinnedGames': [6012, 3857, 2537] }, function() { chrome.storage.sync.set({PolyPlus_PinnedGames: [6012, 3857, 2537]}, function () {
alert('Successfully loaded example for Pinned Games!') alert('Successfully loaded example for Pinned Games!');
}); });
}); });
document.getElementById('example-bestfriends').addEventListener('click', function(){ document.getElementById('example-bestfriends').addEventListener('click', function () {
chrome.storage.sync.set({ 'PolyPlus_BestFriends': [1, 2, 3] }, function() { chrome.storage.sync.set({PolyPlus_BestFriends: [1, 2, 3]}, function () {
alert('Successfully loaded example for Best Friends!') alert('Successfully loaded example for Best Friends!');
}); });
}); });
document.getElementById('example-itemwishlist').addEventListener('click', function(){ document.getElementById('example-itemwishlist').addEventListener('click', function () {
chrome.storage.sync.set({ 'PolyPlus_ItemWishlist': [31495, 31493, 31492] }, function() { chrome.storage.sync.set({PolyPlus_ItemWishlist: [31495, 31493, 31492]}, function () {
alert('Successfully loaded example for Item Wishlist!') alert('Successfully loaded example for Item Wishlist!');
}); });
}); });
document.getElementById('clear-pinnedgames').addEventListener('click', function(){ document.getElementById('clear-pinnedgames').addEventListener('click', function () {
chrome.storage.sync.set({ 'PolyPlus_PinnedGames': [] }, function() { chrome.storage.sync.set({PolyPlus_PinnedGames: []}, function () {
alert('Successfully cleared Pinned Games!') alert('Successfully cleared Pinned Games!');
}); });
}); });
document.getElementById('clear-bestfriends').addEventListener('click', function(){ document.getElementById('clear-bestfriends').addEventListener('click', function () {
chrome.storage.sync.set({ 'PolyPlus_BestFriends': [] }, function() { chrome.storage.sync.set({PolyPlus_BestFriends: []}, function () {
alert('Successfully cleared Best Friends!') alert('Successfully cleared Best Friends!');
}); });
}); });
document.getElementById('clear-itemwishlist').addEventListener('click', function(){ document.getElementById('clear-itemwishlist').addEventListener('click', function () {
chrome.storage.sync.set({ 'PolyPlus_ItemWishlist': [] }, function() { chrome.storage.sync.set({PolyPlus_ItemWishlist: []}, function () {
alert('Successfully cleared Item Wishlist!') alert('Successfully cleared Item Wishlist!');
}); });
}); });
document.getElementById('delete-sync').addEventListener('click', function(){ document.getElementById('delete-sync').addEventListener('click', function () {
if (confirm("Are you sure you'd like to delete all sync data associated with the extension?") === false) { return } if (confirm("Are you sure you'd like to delete all sync data associated with the extension?") === false) {
chrome.storage.sync.clear(function() { return;
alert('Successfully deleted all sync data associated with the extension!') }
}); chrome.storage.sync.clear(function () {
}); alert('Successfully deleted all sync data associated with the extension!');
});
});
document.getElementById('delete-local').addEventListener('click', function(){ document.getElementById('delete-local').addEventListener('click', function () {
if (confirm("Are you sure you'd like to delete all local data associated with the extension?") === false) { return } if (confirm("Are you sure you'd like to delete all local data associated with the extension?") === false) {
chrome.storage.local.clear(function() { return;
alert('Successfully deleted all local data associated with the extension!') }
}); chrome.storage.local.clear(function () {
}); alert('Successfully deleted all local data associated with the extension!');
});
});
document.getElementById('delete-all-data').addEventListener('click', function(){ document.getElementById('delete-all-data').addEventListener('click', function () {
if (confirm("Are you sure you'd like to delete all sync and local data associated with the extension?") === false) { return } if (confirm("Are you sure you'd like to delete all sync and local data associated with the extension?") === false) {
chrome.storage.sync.clear(function() { return;
alert('Successfully deleted all sync data associated with the extension!') }
}); chrome.storage.sync.clear(function () {
chrome.storage.local.clear(function() { alert('Successfully deleted all sync data associated with the extension!');
alert('Successfully deleted all local data associated with the extension!') });
}); chrome.storage.local.clear(function () {
}); alert('Successfully deleted all local data associated with the extension!');
});
});
chrome.storage.sync.getBytesInUse(["PolyPlus_Settings", "PolyPlus_PinnedGames", "PolyPlus_BestFriends", "PolyPlus_ItemWishlist"], function(bytes){ chrome.storage.sync.getBytesInUse(['PolyPlus_Settings', 'PolyPlus_PinnedGames', 'PolyPlus_BestFriends', 'PolyPlus_ItemWishlist'], function (bytes) {
document.getElementById('data-size').innerText = bytes.toLocaleString() document.getElementById('data-size').innerText = bytes.toLocaleString();
}); });
}) });
} }

View file

@ -1,40 +1,40 @@
setTimeout(function () {}, 100) setTimeout(function () {}, 100);
var Settings; var Settings;
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){ chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings; Settings = result.PolyPlus_Settings;
if (!(Settings.MoreSearchFiltersOn === true)) { if (!(Settings.MoreSearchFiltersOn === true)) {
return return;
} }
let Form = document.querySelector('form[action="/forum/search"]') let Form = document.querySelector('form[action="/forum/search"]');
let SearchBtn = document.querySelector('button[type="submit"]') let SearchBtn = document.querySelector('button[type="submit"]');
let CreatedByFilter = document.createElement('div') let CreatedByFilter = document.createElement('div');
CreatedByFilter.classList = 'input-group mt-2' CreatedByFilter.classList = 'input-group mt-2';
CreatedByFilter.innerHTML = ` CreatedByFilter.innerHTML = `
<div class="form-check"> <div class="form-check">
<input class="form-check-input" type="checkbox"> <input class="form-check-input" type="checkbox">
<label class="form-check-label" for="createdBy">Created by <input type="text" class="form-control" placeholder="willemsteller" id="createdBy" name="createdBy"></label> <label class="form-check-label" for="createdBy">Created by <input type="text" class="form-control" placeholder="willemsteller" id="createdBy" name="createdBy"></label>
</div> </div>
` `;
console.log(SearchBtn) console.log(SearchBtn);
Form.insertBefore(CreatedByFilter, SearchBtn.parentElement) Form.insertBefore(CreatedByFilter, SearchBtn.parentElement);
let CreatedByFilter_Checkbox = CreatedByFilter.querySelector('input[type="checkbox"]') let CreatedByFilter_Checkbox = CreatedByFilter.querySelector('input[type="checkbox"]');
let CreatedByFilter_Input = CreatedByFilter.querySelector('input[type="text"]') let CreatedByFilter_Input = CreatedByFilter.querySelector('input[type="text"]');
let CreatedByValue = GetURLParameter("createdBy") let CreatedByValue = GetURLParameter('createdBy');
console.log(CreatedByValue) console.log(CreatedByValue);
if (CreatedByValue) { if (CreatedByValue) {
CreatedByFilter_Checkbox.setAttribute('checked', true) CreatedByFilter_Checkbox.setAttribute('checked', true);
CreatedByFilter_Input.setAttribute('value', CreatedByValue) CreatedByFilter_Input.setAttribute('value', CreatedByValue);
CreatedByFilter_Input.removeAttribute('disabled') CreatedByFilter_Input.removeAttribute('disabled');
document.querySelectorAll('.forum-entry').forEach(element => { document.querySelectorAll('.forum-entry').forEach((element) => {
console.log(element.querySelectorAll('a[href^="/users/"]')[1].innerText) console.log(element.querySelectorAll('a[href^="/users/"]')[1].innerText);
if (!(element.querySelectorAll('a[href^="/users/"]')[1].innerText === CreatedByValue)) { if (!(element.querySelectorAll('a[href^="/users/"]')[1].innerText === CreatedByValue)) {
element.remove(); element.remove();
} }
}); });
} }
/* /*
CreatedByFilter_Checkbox.addEventListener('click', function(){ CreatedByFilter_Checkbox.addEventListener('click', function(){
let Status = CreatedByFilter_Checkbox.getAttribute('checked') let Status = CreatedByFilter_Checkbox.getAttribute('checked')
if (Status === true) { if (Status === true) {
@ -47,7 +47,7 @@ chrome.storage.sync.get(['PolyPlus_Settings'], function(result){
}); });
function GetURLParameter(param) { function GetURLParameter(param) {
const queryString = window.location.search; const queryString = window.location.search;
const urlParams = new URLSearchParams(queryString); const urlParams = new URLSearchParams(queryString);
return urlParams.get(param); return urlParams.get(param);
} }

View file

@ -1,51 +1,51 @@
const ForumText = document.querySelectorAll('p:not(.text-muted):not(.mb-0)') const ForumText = document.querySelectorAll('p:not(.text-muted):not(.mb-0)');
var Settings = [] var Settings = [];
chrome.storage.sync.get(['PolyPlus_Settings'], function(result) { chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings || { Settings = result.PolyPlus_Settings || {
ForumMentsOn: false, ForumMentsOn: false,
ForumUnixStampsOn: false ForumUnixStampsOn: false
} };
if (Settings.ForumMentsOn === true) { if (Settings.ForumMentsOn === true) {
ForumMentions() ForumMentions();
} }
if (Settings.ForumUnixStampsOn === true) { if (Settings.ForumUnixStampsOn === true) {
ForumUnixTimestamps() ForumUnixTimestamps();
} }
}); });
function ForumMentions() { function ForumMentions() {
const Regex = /@([\w.]+)/g const Regex = /@([\w.]+)/g;
for (let text of ForumText) { for (let text of ForumText) {
let FormattedText = text.innerHTML let FormattedText = text.innerHTML;
let match; let match;
while ((match = Regex.exec(text.innerText)) !== null) { while ((match = Regex.exec(text.innerText)) !== null) {
const Username = match[0].substring(1) const Username = match[0].substring(1);
FormattedText = FormattedText.replaceAll(match[0], `<a href="/users/@${Username}?ref=${encodeURIComponent(window.location.pathname)}" class="polyplus-mention">${match[0]}</a>`) FormattedText = FormattedText.replaceAll(match[0], `<a href="/users/@${Username}?ref=${encodeURIComponent(window.location.pathname)}" class="polyplus-mention">${match[0]}</a>`);
} }
text.innerHTML = FormattedText text.innerHTML = FormattedText;
} }
} }
function ForumUnixTimestamps() { function ForumUnixTimestamps() {
const Regex = /&lt;t:[A-Za-z0-9]+&gt;/i const Regex = /&lt;t:[A-Za-z0-9]+&gt;/i;
for (let text of ForumText) { for (let text of ForumText) {
let FormattedText = text.innerHTML let FormattedText = text.innerHTML;
let match; let match;
while ((match = Regex.exec(FormattedText)) !== null) { while ((match = Regex.exec(FormattedText)) !== null) {
const Timestamp = new Date(match[0].substring(6, match[0].length - 4) * 1000) const Timestamp = new Date(match[0].substring(6, match[0].length - 4) * 1000);
const Months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] const Months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
const Distance = new Intl.RelativeTimeFormat({numeric: 'auto', style: 'short'}).format(Math.floor((Timestamp - new Date()) / (60 * 1000)), 'day') const Distance = new Intl.RelativeTimeFormat({numeric: 'auto', style: 'short'}).format(Math.floor((Timestamp - new Date()) / (60 * 1000)), 'day');
const Result = `<code style="color: orange;">${Months[Timestamp.getMonth()]} ${Timestamp.getDate()}, ${Timestamp.getFullYear()} (${["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"][Timestamp.getDay()-1]}) at ${Timestamp.getHours()-12}:${String(Timestamp.getMinutes()).padStart(2, "0")} (${Distance})</code>` const Result = `<code style="color: orange;">${Months[Timestamp.getMonth()]} ${Timestamp.getDate()}, ${Timestamp.getFullYear()} (${['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'][Timestamp.getDay() - 1]}) at ${Timestamp.getHours() - 12}:${String(Timestamp.getMinutes()).padStart(2, '0')} (${Distance})</code>`;
FormattedText = FormattedText.replaceAll(match[0], Result) FormattedText = FormattedText.replaceAll(match[0], Result);
console.log(FormattedText) console.log(FormattedText);
} }
text.innerHTML = FormattedText text.innerHTML = FormattedText;
} }
} }

View file

@ -1,52 +1,52 @@
const StoreItems = document.getElementById('store-items') const StoreItems = document.getElementById('store-items');
var Settings; var Settings;
let Utilities; let Utilities;
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){ chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings Settings = result.PolyPlus_Settings;
if (Settings.IRLPriceWithCurrency.Enabled === true) { if (Settings.IRLPriceWithCurrency.Enabled === true) {
(async () => { (async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js')); Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default Utilities = Utilities.default;
for (let item of Array.from(StoreItems.children)) { for (let item of Array.from(StoreItems.children)) {
IRLPrice(item) IRLPrice(item);
} }
const PreviousPage = document.querySelector('#store-prev a') const PreviousPage = document.querySelector('#store-prev a');
const NextPage = document.querySelector('#store-next a') const NextPage = document.querySelector('#store-next a');
//PreviousPage.addEventListener('click', IRLPrice) //PreviousPage.addEventListener('click', IRLPrice)
//NextPage.addEventListener('click', IRLPrice) //NextPage.addEventListener('click', IRLPrice)
})(); })();
} }
}); });
async function IRLPrice(item) { async function IRLPrice(item) {
const Price = item.getElementsByClassName('text-success')[0] const Price = item.getElementsByClassName('text-success')[0];
if (Price !== undefined && Price.innerText !== "Free") { if (Price !== undefined && Price.innerText !== 'Free') {
const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency) const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency);
let Span = document.createElement('span') let Span = document.createElement('span');
Span.classList = 'text-muted polyplus-price-tag' Span.classList = 'text-muted polyplus-price-tag';
Span.style.fontSize = '0.7rem' Span.style.fontSize = '0.7rem';
Span.innerText = " ($" + IRLResult.result + " " + IRLResult.display + ")" Span.innerText = ' ($' + IRLResult.result + ' ' + IRLResult.display + ')';
Price.appendChild(Span) Price.appendChild(Span);
} }
} }
const observer = new MutationObserver(async function (list){ const observer = new MutationObserver(async function (list) {
for (const record of list) { for (const record of list) {
for (const element of record.addedNodes) { for (const element of record.addedNodes) {
if (element.tagName === "DIV" && element.classList.value === 'col-auto mb-3') { if (element.tagName === 'DIV' && element.classList.value === 'col-auto mb-3') {
if (Settings.IRLPriceWithCurrency.Enabled === true) { if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice(element) IRLPrice(element);
} }
} }
} }
observer.observe(StoreItems, {attributes: false,childList: true,subtree: false}); observer.observe(StoreItems, {attributes: false, childList: true, subtree: false});
} }
}); });
observer.observe(StoreItems, {attributes: false,childList: true,subtree: false}); observer.observe(StoreItems, {attributes: false, childList: true, subtree: false});

View file

@ -1,57 +1,56 @@
const AssetID = window.location.pathname.split('/')[2] const AssetID = window.location.pathname.split('/')[2];
const LibraryType = document.querySelectorAll('ol a')[1].innerText const LibraryType = document.querySelectorAll('ol a')[1].innerText;
const LibraryTypes = [ const LibraryTypes = ['Models', 'Audio', 'Decal', 'Mesh'];
"Models",
"Audio",
"Decal",
"Mesh"
]
if (LibraryTypes.indexOf(LibraryType) !== -1) { if (LibraryTypes.indexOf(LibraryType) !== -1) {
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){ chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings || {}; Settings = result.PolyPlus_Settings || {};
if (Settings.LibraryDownloadsOn === false) { return } if (Settings.LibraryDownloadsOn === false) {
return;
}
const Dropdown = document.querySelector('#app div[style] .dropdown-menu li') const Dropdown = document.querySelector('#app div[style] .dropdown-menu li');
const DownloadLink = document.createElement('a') const DownloadLink = document.createElement('a');
DownloadLink.classList = 'dropdown-item text-warning' DownloadLink.classList = 'dropdown-item text-warning';
DownloadLink.href = '#' DownloadLink.href = '#';
DownloadLink.innerHTML = `<i class="fa-duotone fa-download"></i> Download` DownloadLink.innerHTML = `<i class="fa-duotone fa-download"></i> Download`;
Dropdown.insertBefore(DownloadLink, Dropdown.children[Dropdown.children.length-1]) Dropdown.insertBefore(DownloadLink, Dropdown.children[Dropdown.children.length - 1]);
switch(LibraryType) { switch (LibraryType) {
case 'Models': case 'Models':
DownloadLink.href = 'https://api.polytoria.com/v1/models/get-model?id=' + AssetID DownloadLink.href = 'https://api.polytoria.com/v1/models/get-model?id=' + AssetID;
break break;
case 'Audio': case 'Audio':
const AudioBlob = new Blob([document.getElementsByTagName('audio')[0]], {type: 'octet-steam'}) const AudioBlob = new Blob([document.getElementsByTagName('audio')[0]], {type: 'octet-steam'});
DownloadLink.href = URL.createObjectURL(AudioBlob) DownloadLink.href = URL.createObjectURL(AudioBlob);
DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.mp3' DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.mp3';
case 'Decal': case 'Decal':
const DecalBlob = new Blob([document.getElementsByClassName('store-thumbnail')[0]], {type: 'image/png'}) const DecalBlob = new Blob([document.getElementsByClassName('store-thumbnail')[0]], {type: 'image/png'});
DownloadLink.href = URL.createObjectURL(DecalBlob) DownloadLink.href = URL.createObjectURL(DecalBlob);
DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.png' DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.png';
break break;
} }
if (LibraryType === 'Mesh') { if (LibraryType === 'Mesh') {
let MeshURL = null let MeshURL = null;
DownloadLink.addEventListener('click', async function(){ DownloadLink.addEventListener('click', async function () {
if (MeshURL !== null) { return } if (MeshURL !== null) {
MeshURL = await fetch('https://api.polytoria.com/v1/assets/serve-mesh/' + AssetID) return;
MeshURL = await MeshURL.json() }
MeshURL = await fetch('https://api.polytoria.com/v1/assets/serve-mesh/' + AssetID);
MeshURL = await MeshURL.json();
if (MeshURL.success === true) { if (MeshURL.success === true) {
DownloadLink.href = MeshURL.url DownloadLink.href = MeshURL.url;
DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.glb' DownloadLink.download = document.getElementsByTagName('h1')[0].innerText + '.glb';
DownloadLink.click() DownloadLink.click();
} else { } else {
alert('Failure to fetch .glb file for mesh') alert('Failure to fetch .glb file for mesh');
} }
}) });
} }
}); });
} }

View file

@ -1,46 +1,48 @@
chrome.storage.sync.get(['PolyPlus_Settings'], function(result){ chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = result.PolyPlus_Settings || { Settings = result.PolyPlus_Settings || {
ApplyMembershipThemeOn: false, ApplyMembershipThemeOn: false,
ApplyMembershipThemeTheme: 0 ApplyMembershipThemeTheme: 0
}; };
if (Settings.ApplyMembershipThemeOn !== true) {return} if (Settings.ApplyMembershipThemeOn !== true) {
return;
}
MembershipTheme = Settings.ApplyMembershipThemeTheme === 0 ? 'plus': 'plusdx' MembershipTheme = Settings.ApplyMembershipThemeTheme === 0 ? 'plus' : 'plusdx';
document.addEventListener('DOMContentLoaded', function(){ document.addEventListener('DOMContentLoaded', function () {
if (document.getElementsByClassName('card-header')[0] && document.getElementsByClassName('card-header')[0].innerText === ' Page not found') { if (document.getElementsByClassName('card-header')[0] && document.getElementsByClassName('card-header')[0].innerText === ' Page not found') {
return return;
} }
if (document.getElementsByTagName('NAV')[0].classList.contains('navbar-plus') === true || document.getElementsByTagName('NAV')[0].classList.contains('navbar-plusdx') === true) { if (document.getElementsByTagName('NAV')[0].classList.contains('navbar-plus') === true || document.getElementsByTagName('NAV')[0].classList.contains('navbar-plusdx') === true) {
return return;
} }
const Navbar = document.querySelector('.navbar.navbar-expand-lg.navbar-light.bg-navbar.nav-topbar'); const Navbar = document.querySelector('.navbar.navbar-expand-lg.navbar-light.bg-navbar.nav-topbar');
const Sidebar = document.querySelector('.d-flex.flex-column.flex-shrink-0.bg-sidebar.nav-sidebar'); const Sidebar = document.querySelector('.d-flex.flex-column.flex-shrink-0.bg-sidebar.nav-sidebar');
Navbar.classList.add('navbar-' + MembershipTheme); Navbar.classList.add('navbar-' + MembershipTheme);
Sidebar.classList.add('sidebar-' + MembershipTheme); Sidebar.classList.add('sidebar-' + MembershipTheme);
if (MembershipTheme === 'plusdx') { if (MembershipTheme === 'plusdx') {
let SidebarLogo = document.querySelector('.nav-sidebar img'); let SidebarLogo = document.querySelector('.nav-sidebar img');
SidebarLogo.setAttribute('src', 'https://c0.ptacdn.com/static/images/branding/icon-plusdx.bd9daa92.svg') SidebarLogo.setAttribute('src', 'https://c0.ptacdn.com/static/images/branding/icon-plusdx.bd9daa92.svg');
let SidebarLogoLabel = document.createElement('div') let SidebarLogoLabel = document.createElement('div');
SidebarLogoLabel.classList = 'nplusdx-banner' SidebarLogoLabel.classList = 'nplusdx-banner';
SidebarLogoLabel.innerHTML = ` SidebarLogoLabel.innerHTML = `
<i class="pi pi-plusdx" style="margin-right:-0.4em"></i> <i class="pi pi-plusdx" style="margin-right:-0.4em"></i>
` `;
SidebarLogo.parentElement.appendChild(SidebarLogoLabel) SidebarLogo.parentElement.appendChild(SidebarLogoLabel);
if (window.location.pathname === "/home") { if (window.location.pathname === '/home') {
let HomeUsernameText = document.getElementsByClassName('home-title2')[0] let HomeUsernameText = document.getElementsByClassName('home-title2')[0];
HomeUsernameText.children[0].classList.add('text-plusdx') HomeUsernameText.children[0].classList.add('text-plusdx');
let Label = document.createElement('div') let Label = document.createElement('div');
Label.classList = 'hplusdx-banner rounded-2' Label.classList = 'hplusdx-banner rounded-2';
Label.setAttribute('style', 'margin-top: -8px; animation-delay: 0.09s;') Label.setAttribute('style', 'margin-top: -8px; animation-delay: 0.09s;');
Label.innerText = 'Deluxe' Label.innerText = 'Deluxe';
HomeUsernameText.appendChild(Label) HomeUsernameText.appendChild(Label);
} }
} }
}); });
}); });

View file

@ -1,55 +1,57 @@
!(() => { !(() => {
let Comments = document.getElementById('comments') let Comments = document.getElementById('comments');
const Type = window.location.pathname.split('/')[1] const Type = window.location.pathname.split('/')[1];
let CreatorID; let CreatorID;
if (Type === 'store') { if (Type === 'store') {
if (document.querySelector('h5 .text-reset[href^="/users/"]')) { if (document.querySelector('h5 .text-reset[href^="/users/"]')) {
CreatorID = document.querySelector('h5 .text-reset[href^="/users/"]').getAttribute('href').split('/')[2] CreatorID = document.querySelector('h5 .text-reset[href^="/users/"]').getAttribute('href').split('/')[2];
} else { } else {
CreatorID = 1 CreatorID = 1;
} }
} else if (Type === 'places') { } else if (Type === 'places') {
CreatorID = document.querySelector('.mcard .col .text-muted [href^="/users/"]').getAttribute('href').split('/')[2] CreatorID = document.querySelector('.mcard .col .text-muted [href^="/users/"]').getAttribute('href').split('/')[2];
} else if (Type === 'feed') { } else if (Type === 'feed') {
CreatorID = document.querySelector('p a[href^="/users/"].text-reset').getAttribute('href').split('/')[2] CreatorID = document.querySelector('p a[href^="/users/"].text-reset').getAttribute('href').split('/')[2];
} else if (Type === 'guilds') { } else if (Type === 'guilds') {
CreatorID = document.querySelector('[class^="userlink-"][href^="/users/"]').getAttribute('href').split('/')[2] CreatorID = document.querySelector('[class^="userlink-"][href^="/users/"]').getAttribute('href').split('/')[2];
Comments = document.getElementById('wall-posts') Comments = document.getElementById('wall-posts');
} }
const Observer = new MutationObserver(function (list){ const Observer = new MutationObserver(function (list) {
for (let record of list) { for (let record of list) {
for (let element of record.addedNodes) { for (let element of record.addedNodes) {
if (element.classList === 'card mb-3') { if (element.classList === 'card mb-3') {
LoadCreatorTag(element) LoadCreatorTag(element);
} }
} }
} }
}); });
Observer.observe(Comments, {attributes: false, childList: true, subtree: false}) Observer.observe(Comments, {attributes: false, childList: true, subtree: false});
const LoadCreatorTag = function(element) { const LoadCreatorTag = function (element) {
let NameElement = element.querySelector('.text-reset[href^="/users/"]') let NameElement = element.querySelector('.text-reset[href^="/users/"]');
if (Type === 'guilds') { if (Type === 'guilds') {
NameElement = element.querySelector('[class^="userlink-"][href^="/users/"]') NameElement = element.querySelector('[class^="userlink-"][href^="/users/"]');
} }
let UserID = NameElement.getAttribute('href').split('/')[2] let UserID = NameElement.getAttribute('href').split('/')[2];
if (UserID === CreatorID) { if (UserID === CreatorID) {
let Tag = document.createElement('span') let Tag = document.createElement('span');
Tag.classList = 'badge bg-primary' Tag.classList = 'badge bg-primary';
Tag.style.marginLeft = '5px' Tag.style.marginLeft = '5px';
Tag.style.verticalAlign = 'text-top' Tag.style.verticalAlign = 'text-top';
Tag.innerText = 'CREATOR' Tag.innerText = 'CREATOR';
if (Type === 'guilds') { Tag.innerText = 'LEADER' } if (Type === 'guilds') {
NameElement.appendChild(Tag) Tag.innerText = 'LEADER';
}
NameElement.appendChild(Tag);
//new window.bootstrap.Tooltip(Tag, {toggle:"tooltip",title:"This user is the creator of this asset!"}) //new window.bootstrap.Tooltip(Tag, {toggle:"tooltip",title:"This user is the creator of this asset!"})
} }
} };
Array.from(Comments.children).forEach(element => { Array.from(Comments.children).forEach((element) => {
LoadCreatorTag(element) LoadCreatorTag(element);
}); });
})(); })();

View file

@ -1,69 +1,69 @@
const PlaceID = window.location.pathname.split('/')[3] const PlaceID = window.location.pathname.split('/')[3];
const Form = document.querySelector('form[action="/create/place/update"]') const Form = document.querySelector('form[action="/create/place/update"]');
var Settings; var Settings;
var PlaceData = null var PlaceData = null;
!(async () => { !(async () => {
ActivityToggle() ActivityToggle();
//RequestGameProfile() //RequestGameProfile()
CopyOwnedPlace() CopyOwnedPlace();
})() })();
async function ActivityToggle() { async function ActivityToggle() {
if (PlaceData === null) { if (PlaceData === null) {
PlaceData = await fetch('https://api.polytoria.com/v1/places/' + PlaceID) PlaceData = await fetch('https://api.polytoria.com/v1/places/' + PlaceID);
PlaceData = await PlaceData.json() PlaceData = await PlaceData.json();
} }
let Status = PlaceData.isActive let Status = PlaceData.isActive;
const DIV = document.createElement('div') const DIV = document.createElement('div');
DIV.classList = 'form-group mt-4' DIV.classList = 'form-group mt-4';
DIV.innerHTML = ` DIV.innerHTML = `
<label class="mb-2"> <label class="mb-2">
<h5 class="mb-0">Toggle Activity</h5> <h5 class="mb-0">Toggle Activity</h5>
<small class="text-muted">Make your place active or inactive (currently ${(Status === true) ? 'active' : 'inactive'}).</small> <small class="text-muted">Make your place active or inactive (currently ${Status === true ? 'active' : 'inactive'}).</small>
</label> </label>
<br> <br>
` `;
Form.insertBefore(DIV, Form.children[Form.children.length-1]) Form.insertBefore(DIV, Form.children[Form.children.length - 1]);
const ActivityBtn = document.createElement('button') const ActivityBtn = document.createElement('button');
ActivityBtn.type = 'button' ActivityBtn.type = 'button';
ActivityBtn.classList = 'btn ' + (Status === true ? 'btn-danger' : 'btn-success') ActivityBtn.classList = 'btn ' + (Status === true ? 'btn-danger' : 'btn-success');
ActivityBtn.innerText = Status === true ? 'Deactivate' : 'Activate' ActivityBtn.innerText = Status === true ? 'Deactivate' : 'Activate';
DIV.appendChild(ActivityBtn) DIV.appendChild(ActivityBtn);
ActivityBtn.addEventListener('click', function() { ActivityBtn.addEventListener('click', function () {
fetch(`https://polytoria.com/api/places/${PlaceID}/toggle-active`, { fetch(`https://polytoria.com/api/places/${PlaceID}/toggle-active`, {
method: "POST", method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value 'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
} }
}) })
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok ' + response.status) throw new Error('Network not ok ' + response.status);
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
Status = data.isActive Status = data.isActive;
ActivityBtn.innerText = Status === true ? 'Deactivate' : 'Activate' ActivityBtn.innerText = Status === true ? 'Deactivate' : 'Activate';
ActivityBtn.classList = 'btn ' + (Status === true ? 'btn-danger' : 'btn-success') ActivityBtn.classList = 'btn ' + (Status === true ? 'btn-danger' : 'btn-success');
}) })
.catch(error => { .catch((error) => {
console.log(error) console.log(error);
}); });
}); });
} }
function RequestGameProfile() { function RequestGameProfile() {
const Div = document.createElement('div') const Div = document.createElement('div');
Div.classList = 'card mt-4' Div.classList = 'card mt-4';
Div.innerHTML = ` Div.innerHTML = `
<div class="card-body"> <div class="card-body">
<input type="text" class="form-control bg-dark mb-2" placeholder="Game Title.."> <input type="text" class="form-control bg-dark mb-2" placeholder="Game Title..">
<input type="color" class="form-control bg-dark mb-2" placeholder="Background Color.."> <input type="color" class="form-control bg-dark mb-2" placeholder="Background Color..">
@ -73,86 +73,88 @@ function RequestGameProfile() {
<input type="color" class="form-control bg-dark mb-2" placeholder="Text Color.."> <input type="color" class="form-control bg-dark mb-2" placeholder="Text Color..">
<button type="button" class="btn btn-primary">Submit Request</button> <button type="button" class="btn btn-primary">Submit Request</button>
</div> </div>
` `;
Form.insertBefore(Div, Form.children[Form.children.length-1]) Form.insertBefore(Div, Form.children[Form.children.length - 1]);
const SubmitBtn = Div.getElementsByTagName('button')[0] const SubmitBtn = Div.getElementsByTagName('button')[0];
SubmitBtn.addEventListener('click', function(){ SubmitBtn.addEventListener('click', function () {
const CardBody = Div.children[0] const CardBody = Div.children[0];
const Result = { const Result = {
gameTitle: CardBody.children[0].value, gameTitle: CardBody.children[0].value,
bg: CardBody.children[1].value, bg: CardBody.children[1].value,
accent: CardBody.children[2].value, accent: CardBody.children[2].value,
secondary: CardBody.children[3].value, secondary: CardBody.children[3].value,
cardBg: CardBody.children[4].value, cardBg: CardBody.children[4].value,
text: CardBody.children[5].value text: CardBody.children[5].value
} };
window.location.href = 'https://polyplus.vercel.app/app/game-profile.html?gameId=' + PlaceID + '&profile=' + encodeURIComponent(btoa(JSON.stringify(Result))) window.location.href = 'https://polyplus.vercel.app/app/game-profile.html?gameId=' + PlaceID + '&profile=' + encodeURIComponent(btoa(JSON.stringify(Result)));
}); });
} }
async function CopyOwnedPlace() { async function CopyOwnedPlace() {
console.log('ran function') console.log('ran function');
if (PlaceData === null) { if (PlaceData === null) {
PlaceData = await fetch('https://api.polytoria.com/v1/places/' + 2640) PlaceData = await fetch('https://api.polytoria.com/v1/places/' + 2640);
PlaceData = await PlaceData.json() PlaceData = await PlaceData.json();
} }
if (PlaceData.creator.id !== parseInt(JSON.parse(window.localStorage.getItem('p+account_info')).ID)) { if (PlaceData.creator.id !== parseInt(JSON.parse(window.localStorage.getItem('p+account_info')).ID)) {
console.log('returned') console.log('returned');
//return //return
} }
const DIV = document.createElement('div') const DIV = document.createElement('div');
DIV.classList = 'form-group mt-4' DIV.classList = 'form-group mt-4';
DIV.innerHTML = ` DIV.innerHTML = `
<label class="mb-2"> <label class="mb-2">
<h5 class="mb-0">Download <code style="color: orange;">.poly</code> File</h5> <h5 class="mb-0">Download <code style="color: orange;">.poly</code> File</h5>
<small class="text-muted">Quickly download your place from the site!</small> <small class="text-muted">Quickly download your place from the site!</small>
</label> </label>
<br> <br>
<button type="button" class="btn btn-primary">Download</button> <button type="button" class="btn btn-primary">Download</button>
` `;
Form.insertBefore(DIV, Form.children[Form.children.length-1]) Form.insertBefore(DIV, Form.children[Form.children.length - 1]);
const DownloadButton = DIV.getElementsByTagName('button')[0] const DownloadButton = DIV.getElementsByTagName('button')[0];
DownloadButton.addEventListener('click', async function() { DownloadButton.addEventListener('click', async function () {
console.log('clicked download epic') console.log('clicked download epic');
let CreatorToken = await fetch('https://polytoria.com/api/places/edit', { let CreatorToken = await fetch('https://polytoria.com/api/places/edit', {
method: "POST", method: 'POST',
headers: { headers: {
'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value 'X-CSRF-Token': document.querySelector('input[name="_csrf"]').value
}, },
body: JSON.stringify({ placeID: PlaceID }) body: JSON.stringify({placeID: PlaceID})
}) });
CreatorToken = await CreatorToken.json() CreatorToken = await CreatorToken.json();
CreatorToken = CreatorToken.token CreatorToken = CreatorToken.token;
fetch(`https://api.polytoria.com/v1/places/get-place?id=${PlaceID}&tokenType=creator`, { fetch(`https://api.polytoria.com/v1/places/get-place?id=${PlaceID}&tokenType=creator`, {
headers: { headers: {
'Authorization': CreatorToken Authorization: CreatorToken
} }
}) })
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.blob() return response.blob();
}) })
.then(data => { .then((data) => {
//const JSONBlob = new Blob([data], {type: "application/xml"}) //const JSONBlob = new Blob([data], {type: "application/xml"})
const DownloadURL = URL.createObjectURL(data) const DownloadURL = URL.createObjectURL(data);
const Link = document.createElement('a') const Link = document.createElement('a');
Link.href = DownloadURL Link.href = DownloadURL;
Link.download = PlaceData.name + '.poly' Link.download = PlaceData.name + '.poly';
document.body.appendChild(Link) document.body.appendChild(Link);
Link.click() Link.click();
Link.remove() Link.remove();
}) })
.catch(error => {console.log(error)}); .catch((error) => {
}) console.log(error);
});
});
} }

View file

@ -3,43 +3,47 @@
*/ */
!(() => { !(() => {
return return;
const PlaceID = parseInt(window.location.pathname.split('/')[2]) const PlaceID = parseInt(window.location.pathname.split('/')[2]);
fetch('https://polytoria.com/home') fetch('https://polytoria.com/home')
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.text() return response.text();
}) })
.then(data => { .then((data) => {
const Parser = new DOMParser() const Parser = new DOMParser();
const Doc = Parser.parseFromString(data, 'text/html') const Doc = Parser.parseFromString(data, 'text/html');
fetch('https://polytoria.com/api/places/join',{ fetch('https://polytoria.com/api/places/join', {
method: 'POST', method: 'POST',
headers: { headers: {
'Content-Type': 'application/json', 'Content-Type': 'application/json',
'X-Csrf-Token': Doc.querySelector('[name="_csrf"]').value 'X-Csrf-Token': Doc.querySelector('[name="_csrf"]').value
}, },
body: JSON.stringify({ body: JSON.stringify({
'placeID': PlaceID placeID: PlaceID
}) })
}) })
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
if (data.success !== true) {throw new Error(data.message)} if (data.success !== true) {
setTimeout(function(){ throw new Error(data.message);
window.location.href = 'polytoria://client/' + data.token }
window.location.href = 'https://polytoria.com/places/' + PlaceID setTimeout(function () {
}, 5000) window.location.href = 'polytoria://client/' + data.token;
}) window.location.href = 'https://polytoria.com/places/' + PlaceID;
.catch(error => {console.log(error)}) }, 5000);
}) })
.catch((error) => {
console.log(error);
});
});
})(); })();

View file

@ -1,136 +1,138 @@
const PlaceID = window.location.pathname.split('/')[2] const PlaceID = window.location.pathname.split('/')[2];
const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID;
const GameCreator = document.querySelector('#main-content .card-body .col div.text-muted a[href^="/users/"]').getAttribute('href').split('/')[2] const GameCreator = document.querySelector('#main-content .card-body .col div.text-muted a[href^="/users/"]').getAttribute('href').split('/')[2];
let Utilities; let Utilities;
var Settings; var Settings;
var PinnedGamesData = [] var PinnedGamesData = [];
let GamePinned; let GamePinned;
let InfoColumns = document.querySelectorAll('#main-content .col:has(#likes-data-container) .card:has(.fas.fa-chart-bar) ul') let InfoColumns = document.querySelectorAll('#main-content .col:has(#likes-data-container) .card:has(.fas.fa-chart-bar) ul');
let CalculateRevenueButton; let CalculateRevenueButton;
const AchievementsTab = document.getElementById('achievements-tabpane') const AchievementsTab = document.getElementById('achievements-tabpane');
const GamepassesTab = document.getElementById('gamepasses-tabpane') const GamepassesTab = document.getElementById('gamepasses-tabpane');
const Achievements = Array.from(AchievementsTab.getElementsByClassName('card')) || [] const Achievements = Array.from(AchievementsTab.getElementsByClassName('card')) || [];
const Gamepasses = Array.from(GamepassesTab.getElementsByClassName('card')) || [] const Gamepasses = Array.from(GamepassesTab.getElementsByClassName('card')) || [];
!(() => { !(() => {
if (PlaceID === undefined) { return } if (PlaceID === undefined) {
return;
}
const DataContainer = document.getElementById('likes-data-container') const DataContainer = document.getElementById('likes-data-container');
const RatingsData = { const RatingsData = {
Likes: parseInt(DataContainer.getAttribute('data-like-count')), Likes: parseInt(DataContainer.getAttribute('data-like-count')),
Dislikes: parseInt(DataContainer.getAttribute('data-dislike-count')), Dislikes: parseInt(DataContainer.getAttribute('data-dislike-count')),
Percentage: null Percentage: null
} };
RatingsData.Percentage = Math.floor((RatingsData.Likes / (RatingsData.Likes + RatingsData.Dislikes)) * 100) RatingsData.Percentage = Math.floor((RatingsData.Likes / (RatingsData.Likes + RatingsData.Dislikes)) * 100);
const RatingsContainer = document.getElementById('thumbup-btn').parentElement.parentElement const RatingsContainer = document.getElementById('thumbup-btn').parentElement.parentElement;
const PercentageLabel = document.createElement('small') const PercentageLabel = document.createElement('small');
PercentageLabel.classList = 'text-muted' PercentageLabel.classList = 'text-muted';
PercentageLabel.style.fontSize = '0.8rem' PercentageLabel.style.fontSize = '0.8rem';
PercentageLabel.style.marginLeft = '10px' PercentageLabel.style.marginLeft = '10px';
PercentageLabel.style.marginRight = '10px' PercentageLabel.style.marginRight = '10px';
if (!isNaN(RatingsData.Percentage)) { if (!isNaN(RatingsData.Percentage)) {
PercentageLabel.innerText = RatingsData.Percentage + '%' PercentageLabel.innerText = RatingsData.Percentage + '%';
} else { } else {
PercentageLabel.innerText = 'N/A' PercentageLabel.innerText = 'N/A';
} }
RatingsContainer.children[0].appendChild(PercentageLabel) RatingsContainer.children[0].appendChild(PercentageLabel);
chrome.storage.sync.get(['PolyPlus_Settings'], async function(result) { chrome.storage.sync.get(['PolyPlus_Settings'], async function (result) {
Settings = result.PolyPlus_Settings || {} Settings = result.PolyPlus_Settings || {};
Utilities = await import(chrome.runtime.getURL('resources/utils.js')); Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default Utilities = Utilities.default;
if (Settings.PinnedGamesOn === true) { if (Settings.PinnedGamesOn === true) {
PinnedGames() PinnedGames();
} }
if (Settings.InlineEditingOn === true && GameCreator === UserID) { if (Settings.InlineEditingOn === true && GameCreator === UserID) {
InlineEditing() InlineEditing();
} }
const Description = document.querySelector('.col:has(#likes-data-container) .card.mcard.mb-2 .card-body.p-3.small') const Description = document.querySelector('.col:has(#likes-data-container) .card.mcard.mb-2 .card-body.p-3.small');
if (Settings.GameProfilesOn === true && Description !== null) { if (Settings.GameProfilesOn === true && Description !== null) {
const GameProfileRegex = /p\+gp;(#(?:[A-Fa-f0-9]{3}){1,2}\b(;#(?:[A-Fa-f0-9]{3}){1,2}\b)+)/gm const GameProfileRegex = /p\+gp;(#(?:[A-Fa-f0-9]{3}){1,2}\b(;#(?:[A-Fa-f0-9]{3}){1,2}\b)+)/gm;
if (GameProfileRegex.test(Description.innerText)) { if (GameProfileRegex.test(Description.innerText)) {
const Info = GameProfileRegex.exec(Description.innerText)[1].split(';') const Info = GameProfileRegex.exec(Description.innerText)[1].split(';');
GameProfile(Info) GameProfile(Info);
} }
} }
if (Settings.IRLPriceWithCurrency.Enabled === true) { if (Settings.IRLPriceWithCurrency.Enabled === true) {
IRLPrice() IRLPrice();
} }
if (Settings.ShowPlaceRevenueOn === true) { if (Settings.ShowPlaceRevenueOn === true) {
const NameRow = document.createElement('li') const NameRow = document.createElement('li');
NameRow.innerText = 'Revenue:' NameRow.innerText = 'Revenue:';
CalculateRevenueButton = document.createElement('li') CalculateRevenueButton = document.createElement('li');
CalculateRevenueButton.classList = 'fw-normal text-success' CalculateRevenueButton.classList = 'fw-normal text-success';
CalculateRevenueButton.style.letterSpacing = '0px' CalculateRevenueButton.style.letterSpacing = '0px';
CalculateRevenueButton.innerHTML = ` CalculateRevenueButton.innerHTML = `
<a class="text-decoration-underline text-success" style="text-decoration-color: rgb(15, 132, 79) !important;">$ Calculate</a> <a class="text-decoration-underline text-success" style="text-decoration-color: rgb(15, 132, 79) !important;">$ Calculate</a>
` `;
InfoColumns[0].appendChild(NameRow) InfoColumns[0].appendChild(NameRow);
InfoColumns[1].appendChild(CalculateRevenueButton) InfoColumns[1].appendChild(CalculateRevenueButton);
let Calculating = false let Calculating = false;
CalculateRevenueButton.addEventListener('click', function() { CalculateRevenueButton.addEventListener('click', function () {
if (Calculating === false) { if (Calculating === false) {
Calculating = true Calculating = true;
CalculateRevenueButton.innerText = '$ Calculating...' CalculateRevenueButton.innerText = '$ Calculating...';
PlaceRevenue() PlaceRevenue();
} }
}) });
} }
if (AchievementsTab.getElementsByClassName('display-3')[0] === undefined) { if (AchievementsTab.getElementsByClassName('display-3')[0] === undefined) {
AchievementProgressBar() AchievementProgressBar();
AchievementEarnedPercentage() AchievementEarnedPercentage();
for (let achievement of Achievements) { for (let achievement of Achievements) {
if ((achievement.getElementsByClassName('fad fa-check-circle')[0] !== undefined) === false) { if ((achievement.getElementsByClassName('fad fa-check-circle')[0] !== undefined) === false) {
achievement.style.opacity = '0.5' achievement.style.opacity = '0.5';
} }
} }
} }
}); });
})() })();
async function PinnedGames() { async function PinnedGames() {
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function(result){ chrome.storage.sync.get(['PolyPlus_PinnedGames'], function (result) {
PinnedGamesData = result.PolyPlus_PinnedGames || []; PinnedGamesData = result.PolyPlus_PinnedGames || [];
const PinBtn = document.createElement('button'); const PinBtn = document.createElement('button');
PinBtn.classList = 'btn btn-warning btn-sm'; PinBtn.classList = 'btn btn-warning btn-sm';
PinBtn.style = 'position: absolute; right: 0; margin-right: 7px;' PinBtn.style = 'position: absolute; right: 0; margin-right: 7px;';
if (PinnedGamesData.includes(parseInt(PlaceID))) { if (PinnedGamesData.includes(parseInt(PlaceID))) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin'; PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin';
} else { } else {
if (PinnedGamesData.length !== Utilities.Limits.PinnedGames) { if (PinnedGamesData.length !== Utilities.Limits.PinnedGames) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin' PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin';
} else { } else {
PinBtn.setAttribute('disabled', true) PinBtn.setAttribute('disabled', true);
PinBtn.innerHTML = `<i class="fa-duotone fa-star"></i> Pin (max ${Utilities.Limits.PinnedGames}/${Utilities.Limits.PinnedGames})` PinBtn.innerHTML = `<i class="fa-duotone fa-star"></i> Pin (max ${Utilities.Limits.PinnedGames}/${Utilities.Limits.PinnedGames})`;
} }
} }
PinBtn.addEventListener('click', function() { PinBtn.addEventListener('click', function () {
PinBtn.setAttribute('disabled', 'true') PinBtn.setAttribute('disabled', 'true');
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function(result) { chrome.storage.sync.get(['PolyPlus_PinnedGames'], function (result) {
PinnedGamesData = result.PolyPlus_PinnedGames || []; PinnedGamesData = result.PolyPlus_PinnedGames || [];
/* /*
const Index = PinnedGames.indexOf(parseInt(PlaceID)) const Index = PinnedGames.indexOf(parseInt(PlaceID))
if (Index !== -1) { if (Index !== -1) {
//delete PinnedGames[PlaceID] //delete PinnedGames[PlaceID]
@ -142,32 +144,32 @@ async function PinnedGames() {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin' PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin'
} }
*/ */
const Index = PinnedGamesData.indexOf(parseInt(PlaceID)); const Index = PinnedGamesData.indexOf(parseInt(PlaceID));
if (Index !== -1) { if (Index !== -1) {
PinnedGamesData.splice(Index, 1); PinnedGamesData.splice(Index, 1);
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin' PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin';
} else { } else {
PinnedGamesData.push(parseInt(PlaceID)); PinnedGamesData.push(parseInt(PlaceID));
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin' PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin';
} }
chrome.storage.sync.set({ 'PolyPlus_PinnedGames': PinnedGamesData, arrayOrder: true }, function() { chrome.storage.sync.set({PolyPlus_PinnedGames: PinnedGamesData, arrayOrder: true}, function () {
setTimeout(function() { setTimeout(function () {
PinBtn.removeAttribute('disabled') PinBtn.removeAttribute('disabled');
console.log(PinnedGamesData) console.log(PinnedGamesData);
}, 1250) }, 1250);
}); });
}); });
}); });
document.getElementsByClassName('card-header')[2].appendChild(PinBtn); document.getElementsByClassName('card-header')[2].appendChild(PinBtn);
chrome.storage.onChanged.addListener(function(changes, namespace) { chrome.storage.onChanged.addListener(function (changes, namespace) {
if ('PolyPlus_PinnedGames' in changes) { if ('PolyPlus_PinnedGames' in changes) {
chrome.storage.sync.get(['PolyPlus_PinnedGames'], function(result) { chrome.storage.sync.get(['PolyPlus_PinnedGames'], function (result) {
PinnedGamesData = result.PolyPlus_PinnedGames || []; PinnedGamesData = result.PolyPlus_PinnedGames || [];
/* /*
if (PinnedGamesData[PlaceID]) { if (PinnedGamesData[PlaceID]) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin' PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin'
} else { } else {
@ -180,162 +182,160 @@ async function PinnedGames() {
} }
} }
*/ */
if (PinnedGamesData.includes(parseInt(PlaceID))) { if (PinnedGamesData.includes(parseInt(PlaceID))) {
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin' PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Un-pin';
} else { } else {
if (PinnedGamesData.length !== Utilities.Limits.PinnedGames) { if (PinnedGamesData.length !== Utilities.Limits.PinnedGames) {
PinBtn.removeAttribute('disabled') PinBtn.removeAttribute('disabled');
PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin' PinBtn.innerHTML = '<i class="fa-duotone fa-star"></i> Pin';
} else { } else {
PinBtn.setAttribute('disabled', true) PinBtn.setAttribute('disabled', true);
PinBtn.innerHTML = `<i class="fa-duotone fa-star"></i> Pin (max ${Utilities.Limits.PinnedGames}/${Utilities.Limits.PinnedGames})` PinBtn.innerHTML = `<i class="fa-duotone fa-star"></i> Pin (max ${Utilities.Limits.PinnedGames}/${Utilities.Limits.PinnedGames})`;
} }
} }
}); });
} }
}); });
}); });
} }
async function InlineEditing() { async function InlineEditing() {
/* /*
INLINE EDITING TO-DO: INLINE EDITING TO-DO:
- Make it possible to edit the description even if there is no description initially - Make it possible to edit the description even if there is no description initially
- Make it possible to edit the place's genre - Make it possible to edit the place's genre
*/ */
let Editing = false let Editing = false;
const Style = document.createElement('style') const Style = document.createElement('style');
Style.innerHTML = ` Style.innerHTML = `
body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-visible {display: block !important;} body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-visible {display: block !important;}
.polyplus-inlineEditing-visible {display: none;} .polyplus-inlineEditing-visible {display: none;}
body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-hidden {display: none !important;} body[data-polyplus-inlineEditing="true"] .polyplus-inlineEditing-hidden {display: none !important;}
.polyplus-inlineEditing-hidden {display: block;} .polyplus-inlineEditing-hidden {display: block;}
` `;
document.body.prepend(Style) document.body.prepend(Style);
const Inputs = [ const Inputs = [
{ {
name: "name", name: 'name',
element: null, element: null,
reference: '.card-header h1[style="font-weight:800;font-size:1.6em"]', reference: '.card-header h1[style="font-weight:800;font-size:1.6em"]',
placeholder: "Place Title..", placeholder: 'Place Title..',
required: true, required: true,
isTextarea: false, isTextarea: false,
styles: 'font-weight:800;font-size:1.6em' styles: 'font-weight:800;font-size:1.6em'
}, },
{ {
name: "description", name: 'description',
element: null, element: null,
reference: '.col:has(#likes-data-container) .card.mcard.mb-2 .card-body.p-3.small', reference: '.col:has(#likes-data-container) .card.mcard.mb-2 .card-body.p-3.small',
placeholder: "Place Description..", placeholder: 'Place Description..',
required: false, required: false,
isTextarea: true, isTextarea: true,
styles: 'height:300px; overflow-y:auto;' styles: 'height:300px; overflow-y:auto;'
} }
] ];
console.log(Inputs) console.log(Inputs);
for (let input of Inputs) { for (let input of Inputs) {
let Input = (input.isTextarea === true) ? document.createElement('textarea') : document.createElement('input') let Input = input.isTextarea === true ? document.createElement('textarea') : document.createElement('input');
input.element = Input input.element = Input;
const Reference = document.querySelector(input.reference) const Reference = document.querySelector(input.reference);
Input.classList = 'polyplus-inlineEditing-visible form-control' Input.classList = 'polyplus-inlineEditing-visible form-control';
Input.placeholder = input.placeholder Input.placeholder = input.placeholder;
Input.value = Reference.innerText Input.value = Reference.innerText;
Input.style = input.styles Input.style = input.styles;
Reference.classList.add('polyplus-inlineEditing-hidden') Reference.classList.add('polyplus-inlineEditing-hidden');
Reference.parentElement.appendChild(Input) Reference.parentElement.appendChild(Input);
} }
const PlaceGenre = document.getElementsByClassName('list-unstyled m-0 col')[0].children[3] const PlaceGenre = document.getElementsByClassName('list-unstyled m-0 col')[0].children[3];
const Genres = [ const Genres = [
"other", 'other',
"adventure", 'adventure',
"building", 'building',
"competitive", 'competitive',
"creative", 'creative',
"fighting", 'fighting',
"funny", 'funny',
"hangout", 'hangout',
"medieval", 'medieval',
"parkour", 'parkour',
"puzzle", 'puzzle',
"racing", 'racing',
"roleplay", 'roleplay',
"sandbox", 'sandbox',
"showcase", 'showcase',
"simulator", 'simulator',
"sports", 'sports',
"strategy", 'strategy',
"survival", 'survival',
"techdemo", 'techdemo',
"trading", 'trading',
"tycoon", 'tycoon',
"western" 'western'
] ];
const EditBtn = document.createElement('button'); const EditBtn = document.createElement('button');
EditBtn.classList = 'btn btn-primary btn-sm'; EditBtn.classList = 'btn btn-primary btn-sm';
EditBtn.style = 'position: absolute; right: 0; margin-right: 7px;' EditBtn.style = 'position: absolute; right: 0; margin-right: 7px;';
EditBtn.innerHTML = '<i class="fa-duotone fa-hammer"></i> <span>Edit Details</span>' EditBtn.innerHTML = '<i class="fa-duotone fa-hammer"></i> <span>Edit Details</span>';
document.getElementsByClassName('card-header')[3].appendChild(EditBtn); document.getElementsByClassName('card-header')[3].appendChild(EditBtn);
EditBtn.addEventListener('click', function(){ EditBtn.addEventListener('click', function () {
Editing = !Editing Editing = !Editing;
EditBtn.children[0].classList.toggle('fa-hammer') EditBtn.children[0].classList.toggle('fa-hammer');
EditBtn.children[0].classList.toggle('fa-check-double') EditBtn.children[0].classList.toggle('fa-check-double');
EditBtn.children[0].classList.toggle('fa-fade') EditBtn.children[0].classList.toggle('fa-fade');
document.body.setAttribute('data-polyplus-inlineEditing', Editing) document.body.setAttribute('data-polyplus-inlineEditing', Editing);
if (Editing === false) { if (Editing === false) {
const Send = new FormData() const Send = new FormData();
Send.append("_csrf", document.querySelector('input[name="_csrf"]').value) Send.append('_csrf', document.querySelector('input[name="_csrf"]').value);
Send.append("id", PlaceID) Send.append('id', PlaceID);
for (let input of Inputs) { for (let input of Inputs) {
console.log('start of loop') console.log('start of loop');
Send.append(input.name, input.element.value) Send.append(input.name, input.element.value);
} }
console.log('after') console.log('after');
fetch('/create/place/update', {method:"POST",body:Send}) fetch('/create/place/update', {method: 'POST', body: Send})
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.text() return response.text();
}) })
.then(data => { .then((data) => {
console.log('Successfully edited game') console.log('Successfully edited game');
for (let input of Inputs) { for (let input of Inputs) {
const Reference = document.querySelector(input.reference) const Reference = document.querySelector(input.reference);
Reference.innerText = input.element.value Reference.innerText = input.element.value;
} }
}) })
.catch(error => { .catch((error) => {
alert('Error while saving changes') alert('Error while saving changes');
console.log('Error while editing game') console.log('Error while editing game');
}); });
} }
}); });
} }
async function GameProfile(data) { async function GameProfile(data) {
document.querySelector('h1.my-0') document.querySelector('h1.my-0').setAttribute('game-key', 'true');
.setAttribute('game-key', 'true'); document.querySelector('div[style="min-height: 60vh;"]').id = 'gameprofile';
document.querySelector('div[style="min-height: 60vh;"]')
.id = 'gameprofile';
const Style = document.createElement('style') const Style = document.createElement('style');
Style.innerHTML = ` Style.innerHTML = `
div#app { div#app {
background: ${data[0]} !important; background: ${data[0]} !important;
} }
@ -362,58 +362,58 @@ async function GameProfile(data) {
-webkit-background-clip: text; -webkit-background-clip: text;
-webkit-text-fill-color: transparent; -webkit-text-fill-color: transparent;
} }
` `;
document.body.appendChild(Style) document.body.appendChild(Style);
} }
async function IRLPrice() { async function IRLPrice() {
const Gamepasses = document.querySelector('#gamepasses-tabpane .row.flex-row').children const Gamepasses = document.querySelector('#gamepasses-tabpane .row.flex-row').children;
for (let gamepass of Gamepasses) { for (let gamepass of Gamepasses) {
const Price = gamepass.getElementsByClassName('text-success')[0] const Price = gamepass.getElementsByClassName('text-success')[0];
const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency) const IRLResult = await Utilities.CalculateIRL(Price.innerText, Settings.IRLPriceWithCurrency.Currency);
let Span = document.createElement('span') let Span = document.createElement('span');
Span.classList = 'text-muted polyplus-price-tag' Span.classList = 'text-muted polyplus-price-tag';
Span.style.fontSize = '0.7rem' Span.style.fontSize = '0.7rem';
Span.innerText = "($" + IRLResult.result + " " + IRLResult.display + ")" Span.innerText = '($' + IRLResult.result + ' ' + IRLResult.display + ')';
Price.appendChild(Span) Price.appendChild(Span);
} }
} }
async function PlaceRevenue() { async function PlaceRevenue() {
const BricksPerView = 5 const BricksPerView = 5;
let PlaceDetails = await fetch('https://api.polytoria.com/v1/places/' + PlaceID) let PlaceDetails = await fetch('https://api.polytoria.com/v1/places/' + PlaceID);
PlaceDetails = await PlaceDetails.json() PlaceDetails = await PlaceDetails.json();
let CreatorDetails = await fetch('https://api.polytoria.com/v1/users/' + GameCreator) let CreatorDetails = await fetch('https://api.polytoria.com/v1/users/' + GameCreator);
CreatorDetails = await CreatorDetails.json() CreatorDetails = await CreatorDetails.json();
let Total = (round5(PlaceDetails.uniqueVisits) / 5) let Total = round5(PlaceDetails.uniqueVisits) / 5;
let Revenue = (round5(PlaceDetails.uniqueVisits) / 5) let Revenue = round5(PlaceDetails.uniqueVisits) / 5;
let CreatorTax = 0.35 let CreatorTax = 0.35;
switch (CreatorDetails.membershipType) { switch (CreatorDetails.membershipType) {
case 'plus': case 'plus':
CreatorTax = 0.25 CreatorTax = 0.25;
break break;
case 'plusDeluxe': case 'plusDeluxe':
CreatorTax = 0.15 CreatorTax = 0.15;
break break;
} }
let Achievements = await fetch('https://api.polytoria.com/v1/places/' + PlaceID + '/achievements') let Achievements = await fetch('https://api.polytoria.com/v1/places/' + PlaceID + '/achievements');
Achievements = await Achievements.json() Achievements = await Achievements.json();
let Gamepasses = await fetch('https://api.polytoria.com/v1/places/' + PlaceID + '/gamepasses') let Gamepasses = await fetch('https://api.polytoria.com/v1/places/' + PlaceID + '/gamepasses');
Gamepasses = await Gamepasses.json() Gamepasses = await Gamepasses.json();
for (let gamepass of Gamepasses.gamepasses) { for (let gamepass of Gamepasses.gamepasses) {
const PriceAfterTax = Math.floor(gamepass.asset.price - (gamepass.asset.price * CreatorTax)) const PriceAfterTax = Math.floor(gamepass.asset.price - gamepass.asset.price * CreatorTax);
Revenue += (PriceAfterTax * gamepass.asset.sales) Revenue += PriceAfterTax * gamepass.asset.sales;
} }
/* /*
let AchievementCost = 0 let AchievementCost = 0
let FreeAchievements = null; let FreeAchievements = null;
for (let achievement of Achievements.achievements) { for (let achievement of Achievements.achievements) {
@ -423,84 +423,93 @@ async function PlaceRevenue() {
} }
*/ */
const ResultText = document.createElement('li') const ResultText = document.createElement('li');
ResultText.classList = 'fw-normal text-success' ResultText.classList = 'fw-normal text-success';
ResultText.style.letterSpacing = '0px' ResultText.style.letterSpacing = '0px';
ResultText.innerHTML = `<i class="pi pi-brick mx-1"></i> ~` + Revenue.toLocaleString() ResultText.innerHTML = `<i class="pi pi-brick mx-1"></i> ~` + Revenue.toLocaleString();
CalculateRevenueButton.remove() CalculateRevenueButton.remove();
InfoColumns[1].appendChild(ResultText) InfoColumns[1].appendChild(ResultText);
} }
function round5(number) { const remainder = number % 5; if (remainder < 2.5) { return number - remainder; } else { return number + (5 - remainder); } } function round5(number) {
const remainder = number % 5;
if (remainder < 2.5) {
return number - remainder;
} else {
return number + (5 - remainder);
}
}
function AchievementProgressBar() { function AchievementProgressBar() {
const AchievementCount = Achievements.length const AchievementCount = Achievements.length;
let AchievementsEarned = 0 let AchievementsEarned = 0;
for (let achievement of Achievements) { for (let achievement of Achievements) {
Achieved = (achievement.getElementsByClassName('fad fa-check-circle')[0] !== undefined) Achieved = achievement.getElementsByClassName('fad fa-check-circle')[0] !== undefined;
if (Achieved === true) { if (Achieved === true) {
AchievementsEarned++ AchievementsEarned++;
} }
} }
const PercentageEarned = ((AchievementsEarned*100)/AchievementCount).toFixed(0) const PercentageEarned = ((AchievementsEarned * 100) / AchievementCount).toFixed(0);
const ProgressBar = document.createElement('div') const ProgressBar = document.createElement('div');
ProgressBar.role = 'progressbar' ProgressBar.role = 'progressbar';
ProgressBar.classList = 'progress' ProgressBar.classList = 'progress';
ProgressBar.style.background = '#000' ProgressBar.style.background = '#000';
ProgressBar.ariaValueNow = PercentageEarned ProgressBar.ariaValueNow = PercentageEarned;
ProgressBar.ariaValueMin = "0" ProgressBar.ariaValueMin = '0';
ProgressBar.ariaValueMax = "100" ProgressBar.ariaValueMax = '100';
ProgressBar.innerHTML = `<div class="progress-bar progress-bar-striped text-bg-warning" style="width: ${PercentageEarned}%">${PercentageEarned}%</div>` ProgressBar.innerHTML = `<div class="progress-bar progress-bar-striped text-bg-warning" style="width: ${PercentageEarned}%">${PercentageEarned}%</div>`;
AchievementsTab.prepend(document.createElement('hr')) AchievementsTab.prepend(document.createElement('hr'));
AchievementsTab.prepend(ProgressBar) AchievementsTab.prepend(ProgressBar);
} }
function AchievementEarnedPercentage() { function AchievementEarnedPercentage() {
fetch('https://api.polytoria.com/v1/places/' + PlaceID) fetch('https://api.polytoria.com/v1/places/' + PlaceID)
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
const UserCount = data.uniqueVisits const UserCount = data.uniqueVisits;
for (let achievement of Achievements) { for (let achievement of Achievements) {
const OwnerText = achievement.getElementsByClassName('text-muted small my-0')[0] const OwnerText = achievement.getElementsByClassName('text-muted small my-0')[0];
// thanks to Stackoverflow on how to remove everything except numbers from string // thanks to Stackoverflow on how to remove everything except numbers from string
const OwnerCount = parseInt(OwnerText.innerText.replace(/[^0-9]/g, '')) const OwnerCount = parseInt(OwnerText.innerText.replace(/[^0-9]/g, ''));
const PercentageOfPlayers = ((OwnerCount*100)/UserCount).toFixed(2) const PercentageOfPlayers = ((OwnerCount * 100) / UserCount).toFixed(2);
OwnerText.innerHTML += " (" + PercentageOfPlayers + "%, " + GetAchievementDifficulty(PercentageOfPlayers) + ")" OwnerText.innerHTML += ' (' + PercentageOfPlayers + '%, ' + GetAchievementDifficulty(PercentageOfPlayers) + ')';
} }
}) })
.catch(error => {console.log(error)}); .catch((error) => {
console.log(error);
});
} }
function GetAchievementDifficulty(percent) { function GetAchievementDifficulty(percent) {
if (percent >= 90 && percent <= 100) { if (percent >= 90 && percent <= 100) {
return 'Freebie' return 'Freebie';
} else if (percent >= 80 && percent <= 89.9) { } else if (percent >= 80 && percent <= 89.9) {
return 'Cake Walk' return 'Cake Walk';
} else if (percent >= 50 && percent <= 79.9) { } else if (percent >= 50 && percent <= 79.9) {
return 'Easy' return 'Easy';
} else if (percent >= 30 && percent <= 49.9) { } else if (percent >= 30 && percent <= 49.9) {
return 'Moderate' return 'Moderate';
} else if (percent >= 20 && percent <= 29.9) { } else if (percent >= 20 && percent <= 29.9) {
return 'Challenging' return 'Challenging';
} else if (percent >= 10 && percent <= 19.9) { } else if (percent >= 10 && percent <= 19.9) {
return 'Hard' return 'Hard';
} else if (percent >= 5 && percent <= 9.9) { } else if (percent >= 5 && percent <= 9.9) {
return 'Extreme' return 'Extreme';
} else if (percent >= 1 && percent <= 4.9) { } else if (percent >= 1 && percent <= 4.9) {
return 'Insane' return 'Insane';
} else if (percent >= 0 && percent <= 0.9) { } else if (percent >= 0 && percent <= 0.9) {
return 'Impossible' return 'Impossible';
} }
} }

View file

@ -6,25 +6,28 @@
let Settings; let Settings;
let PinnedGamesData; let PinnedGamesData;
chrome.storage.sync.get(['PolyPlus_Settings', 'PolyPlus_PinnedGames'], function(result){ chrome.storage.sync.get(['PolyPlus_Settings', 'PolyPlus_PinnedGames'], function (result) {
Settings = result.PolyPlus_Settings || {} Settings = result.PolyPlus_Settings || {};
PinnedGamesData = result.PolyPlus_PinnedGames || [] PinnedGamesData = result.PolyPlus_PinnedGames || [];
if (Settings.PinnedGamesOn === true) {} if (Settings.PinnedGamesOn === true) {
}) }
});
function PinnedGames() { function PinnedGames() {
for (let game of PinnedGamesData) { for (let game of PinnedGamesData) {
fetch('https://api.polytoria.com/v1/places/' + game) fetch('https://api.polytoria.com/v1/places/' + game)
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
// epic // epic
}) })
.catch(error => {console.log(error)}) .catch((error) => {
} console.log(error);
});
}
} }

View file

@ -1,18 +1,18 @@
const SettingsURL = chrome.runtime.getURL('settings.html') const SettingsURL = chrome.runtime.getURL('settings.html');
const InExtensionSettings = (window.location.pathname.split('/')[3] === "polyplus" && window.location.hash !== "#dev") const InExtensionSettings = window.location.pathname.split('/')[3] === 'polyplus' && window.location.hash !== '#dev';
if (InExtensionSettings === true) { if (InExtensionSettings === true) {
window.location.href = SettingsURL + window.location.hash window.location.href = SettingsURL + window.location.hash;
} }
document.addEventListener('DOMContentLoaded', function(){ document.addEventListener('DOMContentLoaded', function () {
const Nav = document.getElementsByClassName('nav nav-pills')[0] const Nav = document.getElementsByClassName('nav nav-pills')[0];
const PolyPlusItem = document.createElement('a') const PolyPlusItem = document.createElement('a');
PolyPlusItem.classList = 'nav-link' PolyPlusItem.classList = 'nav-link';
PolyPlusItem.href = SettingsURL PolyPlusItem.href = SettingsURL;
PolyPlusItem.innerHTML = ` PolyPlusItem.innerHTML = `
<i class="fa-regular fa-sparkles me-1"></i> <span class="pilltitle">Poly+</span> <i class="fa-regular fa-sparkles me-1"></i> <span class="pilltitle">Poly+</span>
` `;
Nav.insertBefore(PolyPlusItem, Nav.getElementsByTagName('hr')[0]) Nav.insertBefore(PolyPlusItem, Nav.getElementsByTagName('hr')[0]);
}); });

View file

@ -2,28 +2,28 @@ var Settings;
let Theme = ``; let Theme = ``;
(async () => { (async () => {
let Utilities = await import(chrome.runtime.getURL('resources/utils.js')); let Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default Utilities = Utilities.default;
chrome.storage.sync.get(["PolyPlus_Settings"], function(result) { chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
// Merge settings and expected settings to make sure all keys exist // Merge settings and expected settings to make sure all keys exist
const RawSettings = result.PolyPlus_Settings const RawSettings = result.PolyPlus_Settings;
Settings = MergeObjects(RawSettings || Utilities.DefaultSettings, Utilities.DefaultSettings); Settings = MergeObjects(RawSettings || Utilities.DefaultSettings, Utilities.DefaultSettings);
// If theme exists, create a style element to represent it // If theme exists, create a style element to represent it
if (Settings.ThemeCreator.Enabled && Settings.ThemeCreator.Enabled === true) { if (Settings.ThemeCreator.Enabled && Settings.ThemeCreator.Enabled === true) {
switch (Settings.ThemeCreator.BGImageSize) { switch (Settings.ThemeCreator.BGImageSize) {
case 0: case 0:
Settings.ThemeCreator.BGImageSize = 'fit' Settings.ThemeCreator.BGImageSize = 'fit';
break break;
case 1: case 1:
Settings.ThemeCreator.BGImageSize = 'cover' Settings.ThemeCreator.BGImageSize = 'cover';
break break;
case 2: case 2:
Settings.ThemeCreator.BGImageSize = 'contain' Settings.ThemeCreator.BGImageSize = 'contain';
break break;
} }
Theme += ` Theme += `
:root { :root {
--polyplus-navbgcolor: ${Settings.ThemeCreator.NavBGColor}; --polyplus-navbgcolor: ${Settings.ThemeCreator.NavBGColor};
--polyplus-navbordercolor: ${Settings.ThemeCreator.NavBorderColor}; --polyplus-navbordercolor: ${Settings.ThemeCreator.NavBorderColor};
@ -109,99 +109,101 @@ let Theme = ``;
.nav-sidebar-text { .nav-sidebar-text {
color: var(--polyplus-sidebaritemlabelcolor) !important; color: var(--polyplus-sidebaritemlabelcolor) !important;
} }
` `;
} }
}); });
if (Settings.HideUserAdsOn === true) { if (Settings.HideUserAdsOn === true) {
if (Settings.HideUserAdsOn.Banners === true) { if (Settings.HideUserAdsOn.Banners === true) {
Theme += ` Theme += `
div[style^="max-width: 728px;"]:has(.text-center a[href^="/ads/"]) { div[style^="max-width: 728px;"]:has(.text-center a[href^="/ads/"]) {
display: none; display: none;
} }
` `;
} }
if (Settings.HideUserAdsOn.Rectangles === true) { if (Settings.HideUserAdsOn.Rectangles === true) {
Theme += ` Theme += `
div[style^="max-width: 300px;"]:has(.text-center a[href^="/ads/"]) { div[style^="max-width: 300px;"]:has(.text-center a[href^="/ads/"]) {
display: none; display: none;
} }
` `;
} }
} }
if (Settings.HideNotifBadgesOn === true) { if (Settings.HideNotifBadgesOn === true) {
Theme += ` Theme += `
.notif-nav .notif-sidebar { .notif-nav .notif-sidebar {
display: none; display: none;
} }
` `;
} }
// Credit to @SK-Fast (also known as DevPixels) for the improved loading code (taken from his original Poly+, and reformatted to Index Poly+) // Credit to @SK-Fast (also known as DevPixels) for the improved loading code (taken from his original Poly+, and reformatted to Index Poly+)
const ThemeBlob = new Blob([Theme], { type: 'text/css' }) const ThemeBlob = new Blob([Theme], {type: 'text/css'});
const ThemeURL = URL.createObjectURL(ThemeBlob) const ThemeURL = URL.createObjectURL(ThemeBlob);
document.head.innerHTML += `<link href="${ThemeURL}" rel="stylesheet" type="text/css">` document.head.innerHTML += `<link href="${ThemeURL}" rel="stylesheet" type="text/css">`;
document.addEventListener('DOMContentLoaded', async function() { document.addEventListener('DOMContentLoaded', async function () {
if (document.getElementsByClassName('card-header')[0] && document.getElementsByClassName('card-header')[0].innerText === ' Page not found') { if (document.getElementsByClassName('card-header')[0] && document.getElementsByClassName('card-header')[0].innerText === ' Page not found') {
return return;
} }
Utilities.InjectResource('getUserDetails') Utilities.InjectResource('getUserDetails');
document.body.setAttribute('data-URL', window.location.pathname) document.body.setAttribute('data-URL', window.location.pathname);
const UserData = JSON.parse(window.localStorage.getItem('p+account_info')) const UserData = JSON.parse(window.localStorage.getItem('p+account_info'));
if (Settings.IRLPriceWithCurrency.Enabled === true) { if (Settings.IRLPriceWithCurrency.Enabled === true) {
const IRLResult = await Utilities.CalculateIRL(document.querySelector('.brickBalanceCont').innerText.replace(/\s+/g,''), Settings.IRLPriceWithCurrency.Currency) const IRLResult = await Utilities.CalculateIRL(document.querySelector('.brickBalanceCont').innerText.replace(/\s+/g, ''), Settings.IRLPriceWithCurrency.Currency);
// Desktop // Desktop
document.querySelector('.text-success .brickBalanceCount').innerHTML += ` (${IRLResult.icon}${IRLResult.result} ${IRLResult.display})` document.querySelector('.text-success .brickBalanceCount').innerHTML += ` (${IRLResult.icon}${IRLResult.result} ${IRLResult.display})`;
// Mobile // Mobile
document.querySelector('.text-success .brickBalanceCont').innerHTML += ` (${IRLResult.icon}${IRLResult.result} ${IRLResult.display})` document.querySelector('.text-success .brickBalanceCont').innerHTML += ` (${IRLResult.icon}${IRLResult.result} ${IRLResult.display})`;
//document.querySelector('.text-success .brickBalanceCont').innerHTML += `<div class="text-muted" style="font-size: 0.6rem;text-align: right;">(${IRLResult.icon}${IRLResult.result} ${IRLResult.display})</div>` //document.querySelector('.text-success .brickBalanceCont').innerHTML += `<div class="text-muted" style="font-size: 0.6rem;text-align: right;">(${IRLResult.icon}${IRLResult.result} ${IRLResult.display})</div>`
} }
if (Settings.ModifyNavOn && Settings.ModifyNavOn === true) { if (Settings.ModifyNavOn && Settings.ModifyNavOn === true) {
let NavbarItems = document.querySelectorAll('.navbar-nav.me-auto a.nav-link[href]') let NavbarItems = document.querySelectorAll('.navbar-nav.me-auto a.nav-link[href]');
let Needed = [NavbarItems[11],NavbarItems[12],NavbarItems[13],NavbarItems[14],NavbarItems[15]] let Needed = [NavbarItems[11], NavbarItems[12], NavbarItems[13], NavbarItems[14], NavbarItems[15]];
for (let i = 0; i < Settings.ModifyNav.length; i++) { for (let i = 0; i < Settings.ModifyNav.length; i++) {
if (Settings.ModifyNav[i].Label != null) { if (Settings.ModifyNav[i].Label != null) {
console.log(Needed[i], Needed[i].children[1]) console.log(Needed[i], Needed[i].children[1]);
Needed[i].children[1].innerText = Settings.ModifyNav[i].Label Needed[i].children[1].innerText = Settings.ModifyNav[i].Label;
Needed[i].href = Settings.ModifyNav[i].Link Needed[i].href = Settings.ModifyNav[i].Link;
} }
} }
} }
/* /*
if (Settings.HideUserAdsOn === true) { if (Settings.HideUserAdsOn === true) {
Array.from(document.querySelectorAll('.text-center:has(a[href^="/ads"])')).forEach(ad => {ad.remove()}) Array.from(document.querySelectorAll('.text-center:has(a[href^="/ads"])')).forEach(ad => {ad.remove()})
} }
*/ */
if (Settings.HideNotifBadgesOn === true) { if (Settings.HideNotifBadgesOn === true) {
document.getElementsByClassName('notif-nav notif-sidebar').forEach(element => {element.remove();}); document.getElementsByClassName('notif-nav notif-sidebar').forEach((element) => {
} element.remove();
}); });
}
});
})(); })();
function MergeObjects(obj1, obj2) { function MergeObjects(obj1, obj2) {
var mergedObj = {}; var mergedObj = {};
// Copy the values from obj1 to the mergedObj // Copy the values from obj1 to the mergedObj
for (var key in obj1) { for (var key in obj1) {
mergedObj[key] = obj1[key]; mergedObj[key] = obj1[key];
} }
// Merge the values from obj2 into the mergedObj, favoring obj2 for non-existing keys in obj1 // Merge the values from obj2 into the mergedObj, favoring obj2 for non-existing keys in obj1
for (var key in obj2) { for (var key in obj2) {
if (!obj1.hasOwnProperty(key)) { if (!obj1.hasOwnProperty(key)) {
mergedObj[key] = obj2[key]; mergedObj[key] = obj2[key];
} }
} }
return mergedObj; return mergedObj;
} }

File diff suppressed because it is too large Load diff

View file

@ -1,174 +1,184 @@
const ItemID = window.location.pathname.split('/')[2] const ItemID = window.location.pathname.split('/')[2];
const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID const UserID = JSON.parse(window.localStorage.getItem('p+account_info')).ID;
const ItemGrid = document.getElementById('assets') const ItemGrid = document.getElementById('assets');
const Categories = document.getElementById('store-categories').children[0] const Categories = document.getElementById('store-categories').children[0];
var Settings; var Settings;
var Inventory = null; var Inventory = null;
var Utilities; var Utilities;
let EventItemsShown = false let EventItemsShown = false;
chrome.storage.sync.get(['PolyPlus_Settings'], async function(result){ chrome.storage.sync.get(['PolyPlus_Settings'], async function (result) {
Settings = result.PolyPlus_Settings || {}; Settings = result.PolyPlus_Settings || {};
Utilities = await import(chrome.runtime.getURL('resources/utils.js')); Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default Utilities = Utilities.default;
if (Settings.IRLPriceWithCurrency.Enabled === true) { if (Settings.IRLPriceWithCurrency.Enabled === true) {
Array.from(ItemGrid.children).forEach(element => { Array.from(ItemGrid.children).forEach((element) => {
LoadIRLPrices(element) LoadIRLPrices(element);
}); });
} }
if (Settings.StoreOwnTagOn === true) { if (Settings.StoreOwnTagOn === true) {
Inventory = (await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=hat&limit=100')).json()).inventory Inventory = (await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=hat&limit=100')).json()).inventory;
Inventory.concat(await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=face&limit=100')).json()).inventory Inventory.concat(await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=face&limit=100')).json()).inventory;
Inventory.concat(await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=tool&limit=100')).json()).inventory Inventory.concat(await (await fetch('https://api.polytoria.com/v1/users/' + UserID + '/inventory?type=tool&limit=100')).json()).inventory;
console.log(Inventory) console.log(Inventory);
Array.from(ItemGrid.children).forEach(element => { Array.from(ItemGrid.children).forEach((element) => {
LoadOwnedTags(element) LoadOwnedTags(element);
}); });
} }
if (Settings.EventItemsCatOn === true) { if (Settings.EventItemsCatOn === true) {
EventItems() EventItems();
} }
}); });
const observer = new MutationObserver(async function (list){ const observer = new MutationObserver(async function (list) {
if (Settings.EventItemsCatOn === true) { if (Settings.EventItemsCatOn === true) {
if (document.getElementById('event-items-pagination') === null) { if (document.getElementById('event-items-pagination') === null) {
ItemGrid.classList.add('itemgrid') ItemGrid.classList.add('itemgrid');
ItemGrid.parentElement.classList.remove('col-lg-9') ItemGrid.parentElement.classList.remove('col-lg-9');
document.getElementById('pagination').style.display = 'block' document.getElementById('pagination').style.display = 'block';
if (document.getElementById('storecat-eventitems') !== null) { if (document.getElementById('storecat-eventitems') !== null) {
document.getElementById('storecat-eventitems').checked = false document.getElementById('storecat-eventitems').checked = false;
} }
} else { } else {
ItemGrid.classList.remove('itemgrid') ItemGrid.classList.remove('itemgrid');
ItemGrid.parentElement.classList.add('col-lg-9') ItemGrid.parentElement.classList.add('col-lg-9');
document.getElementById('pagination').style.display = 'none' document.getElementById('pagination').style.display = 'none';
} }
} }
for (const record of list) { for (const record of list) {
for (const element of record.addedNodes) { for (const element of record.addedNodes) {
if (element.tagName === "DIV" && element.classList.value === 'mb-3 itemCardCont') { if (element.tagName === 'DIV' && element.classList.value === 'mb-3 itemCardCont') {
if (Settings.IRLPriceWithCurrency.Enabled === true) { if (Settings.IRLPriceWithCurrency.Enabled === true) {
LoadIRLPrices(element) LoadIRLPrices(element);
} }
if (Settings.StoreOwnTagOn === true && Inventory !== null) { if (Settings.StoreOwnTagOn === true && Inventory !== null) {
LoadOwnedTags(element) LoadOwnedTags(element);
} }
} }
} }
observer.observe(ItemGrid, {attributes: false,childList: true,subtree: false}); observer.observe(ItemGrid, {attributes: false, childList: true, subtree: false});
} }
}); });
observer.observe(ItemGrid, {attributes: false,childList: true,subtree: false}); observer.observe(ItemGrid, {attributes: false, childList: true, subtree: false});
async function LoadIRLPrices(element) { async function LoadIRLPrices(element) {
if (element.tagName != "DIV" || element.querySelector('small.text-primary')) {return} if (element.tagName != 'DIV' || element.querySelector('small.text-primary')) {
const Parent = element.getElementsByTagName('small')[1] return;
if (Parent.innerText !== "") { }
const Span = document.createElement('span') const Parent = element.getElementsByTagName('small')[1];
Span.classList = 'text-muted polyplus-price-tag' if (Parent.innerText !== '') {
Span.style = 'font-size: 0.7rem; font-weight: lighter;' const Span = document.createElement('span');
const Price = Parent.innerText.split(' ')[1] Span.classList = 'text-muted polyplus-price-tag';
const IRLResult = await Utilities.CalculateIRL(Price, Settings.IRLPriceWithCurrency.Currency) Span.style = 'font-size: 0.7rem; font-weight: lighter;';
Span.innerText = "($" + IRLResult.result + " " + IRLResult.display + ")" const Price = Parent.innerText.split(' ')[1];
Parent.appendChild(Span) const IRLResult = await Utilities.CalculateIRL(Price, Settings.IRLPriceWithCurrency.Currency);
} Span.innerText = '($' + IRLResult.result + ' ' + IRLResult.display + ')';
Parent.appendChild(Span);
}
} }
function LoadOwnedTags(element) { function LoadOwnedTags(element) {
let Item = CheckInventory(parseInt(element.querySelector('[href^="/store/"]').getAttribute('href').split('/')[2])) let Item = CheckInventory(parseInt(element.querySelector('[href^="/store/"]').getAttribute('href').split('/')[2]));
if (Item !== null) { if (Item !== null) {
const Tag = document.createElement('span') const Tag = document.createElement('span');
Tag.classList = `badge ${ (Item.asset.isLimited === false) ? 'bg-primary' : 'bg-warning' } polyplus-own-tag` Tag.classList = `badge ${Item.asset.isLimited === false ? 'bg-primary' : 'bg-warning'} polyplus-own-tag`;
Tag.style = 'position: absolute;font-size: 0.9rem;top: 0px;left: 0px;padding: 5.5px;border-top-left-radius: var(--bs-border-radius-lg)!important;border-top-right-radius: 0px;border-bottom-left-radius: 0px;font-size: 0.65rem;' Tag.style =
Tag.innerHTML = "<i class='fas fa-star'></i>" 'position: absolute;font-size: 0.9rem;top: 0px;left: 0px;padding: 5.5px;border-top-left-radius: var(--bs-border-radius-lg)!important;border-top-right-radius: 0px;border-bottom-left-radius: 0px;font-size: 0.65rem;';
element.getElementsByTagName('img')[0].parentElement.appendChild(Tag) Tag.innerHTML = "<i class='fas fa-star'></i>";
if (Item.asset.isLimited === true) { element.getElementsByTagName('img')[0].parentElement.appendChild(Tag);
Tag.setAttribute('data-bs-toggle', 'tooltip') if (Item.asset.isLimited === true) {
Tag.setAttribute('data-bs-title', '#' + Item.serial) Tag.setAttribute('data-bs-toggle', 'tooltip');
Tag.setAttribute('data-bs-title', '#' + Item.serial);
Utilities.InjectResource('registerTooltips') Utilities.InjectResource('registerTooltips');
} }
} }
} }
function CheckInventory(id) { function CheckInventory(id) {
let Item = null let Item = null;
Inventory.forEach(element => { Inventory.forEach((element) => {
if (element.asset.id === id) { if (element.asset.id === id) {
Item = element Item = element;
} }
}) });
return Item return Item;
} }
function EventItems() { function EventItems() {
const Selector = document.createElement('div') const Selector = document.createElement('div');
Selector.classList = 'form-check store-category-check fw-bold' Selector.classList = 'form-check store-category-check fw-bold';
Selector.style.borderColor = '#B008B0' Selector.style.borderColor = '#B008B0';
Selector.innerHTML = ` Selector.innerHTML = `
<input class="form-check-input" type="radio" name="storecat" id="storecat-eventitems"> <input class="form-check-input" type="radio" name="storecat" id="storecat-eventitems">
<label class="form-check-label" for="storecat-eventitems"> <label class="form-check-label" for="storecat-eventitems">
<i class="fad fa-party-horn"></i> Event Items <i class="fad fa-party-horn"></i> Event Items
</label> </label>
` `;
Categories.appendChild(Selector) Categories.appendChild(Selector);
let EventData = null let EventData = null;
let Events = [] let Events = [];
let Groups = [] let Groups = [];
let Page = 0 let Page = 0;
Selector.children[0].addEventListener('click', async function() { Selector.children[0].addEventListener('click', async function () {
Array.from(Categories.children).forEach(selector => { Array.from(Categories.children).forEach((selector) => {
selector.classList.remove('active') selector.classList.remove('active');
}) });
Selector.classList.add('active') Selector.classList.add('active');
if (EventData === null) { if (EventData === null) {
EventData = await (await fetch('https://polyplus.vercel.app/data/eventItems.json')).json() EventData = await (await fetch('https://polyplus.vercel.app/data/eventItems.json')).json();
Object.values(EventData.eventDetails).forEach((x, index) => {Events.push({ Object.values(EventData.eventDetails).forEach((x, index) => {
...x, Events.push({
items: EventData.items.filter((x) => x.event === Object.keys(EventData.eventDetails)[index]).sort((a, b) => a.id - b.id) ...x,
})}) items: EventData.items.filter((x) => x.event === Object.keys(EventData.eventDetails)[index]).sort((a, b) => a.id - b.id)
while (Events.length > 0) { });
Groups.push(Events.splice(0, 5)) });
} while (Events.length > 0) {
} Groups.push(Events.splice(0, 5));
}
}
ItemGrid.classList.remove('itemgrid') ItemGrid.classList.remove('itemgrid');
ItemGrid.innerHTML = ` ItemGrid.innerHTML = `
<div id="p+ei"> <div id="p+ei">
${ ${Groups[Page].map(
Groups[Page].map((x, index) => ` (x, index) => `
<div class="row px-2 px-lg-0" style="animation-delay: 0.24s;"> <div class="row px-2 px-lg-0" style="animation-delay: 0.24s;">
<div class="col"> <div class="col">
<h6 class="dash-ctitle2">${x.date}</h6> <h6 class="dash-ctitle2">${x.date}</h6>
<h5 class="dash-ctitle">${x.name}</h5> <h5 class="dash-ctitle">${x.name}</h5>
</div> </div>
${ (x.link !== undefined) ? ` ${
x.link !== undefined
? `
<div class="col-auto d-flex align-items-center"> <div class="col-auto d-flex align-items-center">
<a class="text-muted" href="${x.link}"> <a class="text-muted" href="${x.link}">
<span class="d-none d-lg-inline">${ (x.link.startsWith('https://polytoria.com/places/')) ? 'Event Place' : 'Blog Post' }</span> <span class="d-none d-lg-inline">${x.link.startsWith('https://polytoria.com/places/') ? 'Event Place' : 'Blog Post'}</span>
<i class="fas fa-angle-right ms-2"></i> <i class="fas fa-angle-right ms-2"></i>
</a> </a>
</div> </div>
` : '' } `
: ''
}
</div> </div>
<div class="card card-dash mcard mb-3" style="animation-delay: 0.27s;"> <div class="card card-dash mcard mb-3" style="animation-delay: 0.27s;">
<div class="card-body p-0 m-1 scrollFadeContainer"> <div class="card-body p-0 m-1 scrollFadeContainer">
<div class="d-flex"> <div class="d-flex">
${ ${x.items
x.items.map((x) => ` .map(
(x) => `
<a href="/store/${x.id}"> <a href="/store/${x.id}">
<div class="scrollFade card me-2 place-card force-desktop text-center mb-2" style="opacity: 1;"> <div class="scrollFade card me-2 place-card force-desktop text-center mb-2" style="opacity: 1;">
<div class="card-body"> <div class="card-body">
@ -181,13 +191,14 @@ function EventItems() {
</div> </div>
</div> </div>
</a> </a>
`).join('') `
} )
.join('')}
</div> </div>
</div> </div>
</div> </div>
`).join('') `
} ).join('')}
</div> </div>
<div class="d-flex justify-content-center mt-3"> <div class="d-flex justify-content-center mt-3">
@ -214,62 +225,63 @@ function EventItems() {
</ul> </ul>
</nav> </nav>
</div> </div>
` `;
const Container = document.getElementById('p+ei') const Container = document.getElementById('p+ei');
const Pagination = document.getElementById('event-items-pagination') const Pagination = document.getElementById('event-items-pagination');
const First = document.getElementById('p+ei-pagination-first') const First = document.getElementById('p+ei-pagination-first');
const Prev = document.getElementById('p+ei-pagination-prev') const Prev = document.getElementById('p+ei-pagination-prev');
const Current = document.getElementById('p+ei-pagination-current') const Current = document.getElementById('p+ei-pagination-current');
const Next = document.getElementById('p+ei-pagination-next') const Next = document.getElementById('p+ei-pagination-next');
const Last = document.getElementById('p+ei-pagination-last') const Last = document.getElementById('p+ei-pagination-last');
if (Page > 0) { if (Page > 0) {
Prev.parentElement.classList.remove('disabled') Prev.parentElement.classList.remove('disabled');
First.parentElement.classList.remove('disabled') First.parentElement.classList.remove('disabled');
} else { } else {
Prev.parentElement.classList.add('disabled') Prev.parentElement.classList.add('disabled');
First.parentElement.classList.add('disabled') First.parentElement.classList.add('disabled');
} }
if (Page < Groups.length-1) { if (Page < Groups.length - 1) {
Next.parentElement.classList.remove('disabled') Next.parentElement.classList.remove('disabled');
Last.parentElement.classList.remove('disabled') Last.parentElement.classList.remove('disabled');
} else { } else {
Next.parentElement.classList.add('disabled') Next.parentElement.classList.add('disabled');
Last.parentElement.classList.add('disabled') Last.parentElement.classList.add('disabled');
} }
First.addEventListener('click', function() { First.addEventListener('click', function () {
if (Page > 0) { if (Page > 0) {
Page = 0 Page = 0;
UpdateEventItems() UpdateEventItems();
} }
}) });
Prev.addEventListener('click', function() { Prev.addEventListener('click', function () {
if (Page > 0) { if (Page > 0) {
Page-- Page--;
UpdateEventItems() UpdateEventItems();
} }
}) });
Next.addEventListener('click', function() { Next.addEventListener('click', function () {
if (Page < Groups.length-1) { if (Page < Groups.length - 1) {
Page++ Page++;
UpdateEventItems() UpdateEventItems();
} }
}) });
Last.addEventListener('click', function() { Last.addEventListener('click', function () {
if (Page < Groups.length-1) { if (Page < Groups.length - 1) {
Page = Groups.length-1 Page = Groups.length - 1;
UpdateEventItems() UpdateEventItems();
} }
}) });
const UpdateEventItems = function() { const UpdateEventItems = function () {
Current.innerText = Page+1 Current.innerText = Page + 1;
Container.innerHTML = Groups[Page].map((x, index) => ` Container.innerHTML = Groups[Page].map(
(x, index) => `
<div class="row px-2 px-lg-0" style="animation-delay: 0.24s;"> <div class="row px-2 px-lg-0" style="animation-delay: 0.24s;">
<div class="col"> <div class="col">
<h6 class="dash-ctitle2">${x.date}</h6> <h6 class="dash-ctitle2">${x.date}</h6>
@ -279,8 +291,9 @@ function EventItems() {
<div class="card card-dash mcard mb-3" style="animation-delay: 0.27s;"> <div class="card card-dash mcard mb-3" style="animation-delay: 0.27s;">
<div class="card-body p-0 m-1 scrollFadeContainer"> <div class="card-body p-0 m-1 scrollFadeContainer">
<div class="d-flex"> <div class="d-flex">
${ ${x.items
x.items.map((x) => ` .map(
(x) => `
<a href="/store/${x.id}"> <a href="/store/${x.id}">
<div class="scrollFade card me-2 place-card force-desktop text-center mb-2" style="opacity: 1;"> <div class="scrollFade card me-2 place-card force-desktop text-center mb-2" style="opacity: 1;">
<div class="card-body"> <div class="card-body">
@ -293,28 +306,30 @@ function EventItems() {
</div> </div>
</div> </div>
</a> </a>
`).join('') `
} )
.join('')}
</div> </div>
</div> </div>
</div> </div>
</div> </div>
`).join('') `
).join('');
if (Page > 0) { if (Page > 0) {
Prev.parentElement.classList.remove('disabled') Prev.parentElement.classList.remove('disabled');
First.parentElement.classList.remove('disabled') First.parentElement.classList.remove('disabled');
} else { } else {
Prev.parentElement.classList.add('disabled') Prev.parentElement.classList.add('disabled');
First.parentElement.classList.add('disabled') First.parentElement.classList.add('disabled');
} }
if (Page < Groups.length-1) { if (Page < Groups.length - 1) {
Next.parentElement.classList.remove('disabled') Next.parentElement.classList.remove('disabled');
Last.parentElement.classList.remove('disabled') Last.parentElement.classList.remove('disabled');
} else { } else {
Next.parentElement.classList.add('disabled') Next.parentElement.classList.add('disabled');
Last.parentElement.classList.add('disabled') Last.parentElement.classList.add('disabled');
} }
} };
}) });
} }

View file

@ -1,150 +1,148 @@
{ {
"manifest_version": 3, "manifest_version": 3,
"author": "Index", "author": "Index",
"name": "Poly+", "name": "Poly+",
"version": "1.11", "version": "1.11",
"version_name": "Pre-Release Build (v1.1.1)", "version_name": "Pre-Release Build (v1.1.1)",
"description": "Power-up your Polytoria experience with Poly+! Created by Index.", "description": "Power-up your Polytoria experience with Poly+! Created by Index.",
"homepage_url": "https://polyplus.vercel.app/", "homepage_url": "https://polyplus.vercel.app/",
"permissions": ["storage", "contextMenus", "tabs", "scripting", "alarms", "notifications"], "permissions": ["storage", "contextMenus", "tabs", "scripting", "alarms", "notifications"],
"content_scripts": [ "content_scripts": [
{ {
"matches": ["https://polytoria.com/*"], "matches": ["https://polytoria.com/*"],
"js": ["/js/sitewide.js","/js/membership-themes.js"], "js": ["/js/sitewide.js", "/js/membership-themes.js"],
"css": ["/css/specific.css"], "css": ["/css/specific.css"],
"run_at": "document_start" "run_at": "document_start"
}, },
{ {
"matches": ["https://polytoria.com/my/settings/*"], "matches": ["https://polytoria.com/my/settings/*"],
"js": ["/js/settings.js", "/js/debug.js"], "js": ["/js/settings.js", "/js/debug.js"],
"run_at": "document_start" "run_at": "document_start"
}, },
{ {
"matches": ["https://polytoria.com/", "https://polytoria.com/home"], "matches": ["https://polytoria.com/", "https://polytoria.com/home"],
"js": ["/js/account/home.js"], "js": ["/js/account/home.js"],
"run_at": "document_idle" "run_at": "document_idle"
}, },
{ {
"matches": ["https://polytoria.com/places/**"], "matches": ["https://polytoria.com/places/**"],
"js": ["/js/places/place-view.js"] "js": ["/js/places/place-view.js"]
}, },
{ {
"matches": ["https://polytoria.com/create/place/**"], "matches": ["https://polytoria.com/create/place/**"],
"js": ["/js/places/place-edit.js"] "js": ["/js/places/place-edit.js"]
}, },
{ {
"matches": ["https://polytoria.com/forum/post/**"], "matches": ["https://polytoria.com/forum/post/**"],
"js": ["/js/forum/forum-view.js"] "js": ["/js/forum/forum-view.js"]
}, },
{ {
"matches": ["https://polytoria.com/u/**"], "matches": ["https://polytoria.com/u/**"],
"js": ["/js/account/profile.js"] "js": ["/js/account/profile.js"]
}, },
{ {
"matches": ["https://polytoria.com/my/friends", "https://polytoria.com/my/friends/"], "matches": ["https://polytoria.com/my/friends", "https://polytoria.com/my/friends/"],
"js": ["/js/account/friends.js"] "js": ["/js/account/friends.js"]
}, },
{ {
"matches": ["https://polytoria.com/store", "https://polytoria.com/store/"], "matches": ["https://polytoria.com/store", "https://polytoria.com/store/"],
"js": ["/js/store/store.js"] "js": ["/js/store/store.js"]
}, },
{ {
"matches": ["https://polytoria.com/store/**"], "matches": ["https://polytoria.com/store/**"],
"js": ["/js/store/item-view.js"] "js": ["/js/store/item-view.js"]
}, },
{ {
"matches": ["https://polytoria.com/forum/search","https://polytoria.com/forum/search?*"], "matches": ["https://polytoria.com/forum/search", "https://polytoria.com/forum/search?*"],
"js": ["/js/forum/forum-search.js"] "js": ["/js/forum/forum-search.js"]
}, },
{ {
"matches": ["https://polytoria.com/trade/sent/*"], "matches": ["https://polytoria.com/trade/sent/*"],
"js": ["/js/account/trades-outbound.js"] "js": ["/js/account/trades-outbound.js"]
}, },
{ {
"matches": ["https://polytoria.com/u/*/inventory/"], "matches": ["https://polytoria.com/u/*/inventory/"],
"js": ["/js/account/inventory.js"], "js": ["/js/account/inventory.js"],
"run_at": "document_idle" "run_at": "document_idle"
}, },
{ {
"matches": ["https://polytoria.com/my/settings/privacy"], "matches": ["https://polytoria.com/my/settings/privacy"],
"js": ["/js/account/settings-privacy.js"] "js": ["/js/account/settings-privacy.js"]
}, },
{ {
"matches": ["https://polytoria.com/my/settings/transactions*"], "matches": ["https://polytoria.com/my/settings/transactions*"],
"js": ["/js/account/transactions.js"] "js": ["/js/account/transactions.js"]
}, },
{ {
"matches": ["https://polytoria.com/store/**", "https://polytoria.com/places/**", "https://polytoria.com/guilds/**", "https://polytoria.com/feed/**"], "matches": ["https://polytoria.com/store/**", "https://polytoria.com/places/**", "https://polytoria.com/guilds/**", "https://polytoria.com/feed/**"],
"js": ["/js/op-comments.js"] "js": ["/js/op-comments.js"]
}, },
{ {
"matches": ["https://polytoria.com/my/avatar*"], "matches": ["https://polytoria.com/my/avatar*"],
"js": ["/js/account/avatar-sandbox2.js"] "js": ["/js/account/avatar-sandbox2.js"]
}, },
{ {
"matches": ["https://polytoria.com/inbox*"], "matches": ["https://polytoria.com/inbox*"],
"js": ["/js/account/inbox.js"] "js": ["/js/account/inbox.js"]
}, },
{ {
"matches": ["https://polytoria.com/guilds/**"], "matches": ["https://polytoria.com/guilds/**"],
"js": ["/js/guilds.js"] "js": ["/js/guilds.js"]
}, },
{ {
"matches": ["https://polytoria.com/store/**", "https://polytoria.com/models/**"], "matches": ["https://polytoria.com/store/**", "https://polytoria.com/models/**"],
"js": ["/js/library-download.js"] "js": ["/js/library-download.js"]
} }
], ],
"background": { "background": {
"service_worker": "/js/background.js", "service_worker": "/js/background.js",
"type": "module" "type": "module"
}, },
"host_permissions": [ "host_permissions": ["https://*.polytoria.com/*"],
"https://*.polytoria.com/*" "web_accessible_resources": [
], {
"web_accessible_resources": [ "resources": ["resources/*"],
{ "matches": ["https://polytoria.com/*"]
"resources": ["resources/*"], },
"matches": ["https://polytoria.com/*"]
},
{ {
"resources": ["settings.html", "settings.js"], "resources": ["settings.html", "settings.js"],
"matches": ["https://polytoria.com/*"] "matches": ["https://polytoria.com/*"]
} }
], ],
"short_name": "Poly+", "short_name": "Poly+",
"action": { "action": {
"default_title": "Poly+", "default_title": "Poly+",
"default_icon": { "default_icon": {
"16": "/icons/icon.png", "16": "/icons/icon.png",
"32": "/icons/icon.png", "32": "/icons/icon.png",
"48": "/icons/icon.png", "48": "/icons/icon.png",
"128": "/icons/icon.png" "128": "/icons/icon.png"
} }
}, },
"icons": { "icons": {
"16": "/icons/icon.png", "16": "/icons/icon.png",
"32": "/icons/icon.png", "32": "/icons/icon.png",
"48": "/icons/icon.png", "48": "/icons/icon.png",
"128": "/icons/icon.png" "128": "/icons/icon.png"
} }
} }

View file

@ -1,134 +1,137 @@
<style> <style>
#options { #options {
position: absolute; position: absolute;
bottom: 0; bottom: 0;
margin: 20px; margin: 20px;
margin-bottom: 40px; margin-bottom: 40px;
font-size: 1.25rem; font-size: 1.25rem;
} }
#options *:not(input) { #options *:not(input) {
background: transparent; background: transparent;
border: none; border: none;
color: #fff; color: #fff;
font-size: 1.25rem; font-size: 1.25rem;
} }
#options *:not(input):not(:nth-child(2)) { #options *:not(input):not(:nth-child(2)) {
margin-bottom: 3.5px; margin-bottom: 3.5px;
} }
</style> </style>
<div class="row"> <div class="row">
<div class="col-12 col-lg-3"> <div class="col-12 col-lg-3">
<div class="card mcard mb-3"> <div class="card mcard mb-3">
<h6 class="card-header"> <h6 class="card-header">
<i class="fad fa-user-crown"></i> <i class="fad fa-user-crown"></i>
Avatar Sandbox Avatar Sandbox
</h6> </h6>
<div class="card-body"> <div class="card-body">
<iframe id="viewFrame" style="width: 100%; height: 314px; border-radius: 0.65rem;"></iframe> <iframe id="viewFrame" style="width: 100%; height: 314px; border-radius: 0.65rem;"></iframe>
<div id="options"> <div id="options">
<input name="JSONUpload" type="file" accept="application/json" multiple="false" id="jsonUpload" aria-label="Upload JSON!" style="display: none;"> <input name="JSONUpload" type="file" accept="application/json" multiple="false" id="jsonUpload" aria-label="Upload JSON!" style="display: none;" />
<label for="JSONUpload" style="display: block;"> <label for="JSONUpload" style="display: block;">
<button aria-label="Upload JSON!" onclick="this.parentElement.previousElementSibling.click()"> <button aria-label="Upload JSON!" onclick="this.parentElement.previousElementSibling.click()">
<i class="fa-duotone fa-download"></i> <i class="fa-duotone fa-download"></i>
</button> </button>
</label> </label>
<button id="jsonSave" aria-label="Save as JSON!" style="display: block;"> <button id="jsonSave" aria-label="Save as JSON!" style="display: block;">
<i class="fa-duotone fa-upload"></i> <i class="fa-duotone fa-upload"></i>
</button> </button>
<button id="openNewTab" aria-label="View in a new tab!" style="display: block;"> <button id="openNewTab" aria-label="View in a new tab!" style="display: block;">
<i class="fa-duotone fa-up-right-from-square"></i> <i class="fa-duotone fa-up-right-from-square"></i>
</button> </button>
<button aria-label="View in full screen!" style="display: block;" onclick="document.getElementById('viewFrame').requestFullscreen()"> <button aria-label="View in full screen!" style="display: block;" onclick="document.getElementById('viewFrame').requestFullscreen()">
<i class="fa-duotone fa-minimize"></i> <i class="fa-duotone fa-minimize"></i>
</button> </button>
</div> </div>
</div> </div>
</div> </div>
<div class="row mb-3"> <div class="row mb-3">
<div class="col"> <div class="col">
<button id="myself" class="btn btn-outline-primary w-100"> <button id="myself" class="btn btn-outline-primary w-100">
<i class="fa-duotone fa-shirt"></i> <i class="fa-duotone fa-shirt"></i>
Myself Myself
</button> </button>
</div> </div>
<div class="col"> <div class="col">
<button id="clear" class="btn btn-outline-warning w-100"> <button id="clear" class="btn btn-outline-warning w-100">
<i class="fa-duotone fa-trash"></i> <i class="fa-duotone fa-trash"></i>
Clear Clear
</button> </button>
</div> </div>
</div> </div>
<div class="input-group mb-3"> <div class="input-group mb-3">
<input type="text" class="form-control bg-dark" placeholder="Asset ID.."> <input type="text" class="form-control bg-dark" placeholder="Asset ID.." />
<button class="btn btn-primary" id="load-asset">Load Asset</button> <button class="btn btn-primary" id="load-asset">Load Asset</button>
</div> </div>
<div class="card mcard mb-3"> <div class="card mcard mb-3">
<h6 class="card-header"> <h6 class="card-header">
<i class="fad fa-palette"></i> <i class="fad fa-palette"></i>
Body Colors Body Colors
</h6> </h6>
<div class="card-body"> <div class="card-body">
<div class="card-body text-center" id="body-parts"> <div class="card-body text-center" id="body-parts">
<div style="margin-bottom: 5px"> <div style="margin-bottom: 5px">
<button id="head" class="avatarAction bodypart bp1x1" style="background-color: #e0e0e0;"></button> <button id="head" class="avatarAction bodypart bp1x1" style="background-color: #e0e0e0;"></button>
</div> </div>
<div style="margin-bottom: 5px"> <div style="margin-bottom: 5px">
<button id="rightArm" class="avatarAction bodypart bp1x2" style="background-color: #e0e0e0; margin-right: 5px;"></button><button id="torso" class="avatarAction bodypart bp2x2" style="background-color: #e0e0e0;"></button><button class="avatarAction bodypart bp1x2" id="leftArm" style="background-color: #e0e0e0; margin-left: 5px;"></button> <button id="rightArm" class="avatarAction bodypart bp1x2" style="background-color: #e0e0e0; margin-right: 5px;"></button
</div> ><button id="torso" class="avatarAction bodypart bp2x2" style="background-color: #e0e0e0;"></button
><button class="avatarAction bodypart bp1x2" id="leftArm" style="background-color: #e0e0e0; margin-left: 5px;"></button>
</div>
<div> <div>
<button class="avatarAction bodypart bp1x2" id="rightLeg" style="background-color: #e0e0e0; margin-right: 5px; padding-right: 18px;"></button><button id="leftLeg" class="avatarAction bodypart bp1x2" style="background-color: #e0e0e0; padding-right: 18px;"></button> <button class="avatarAction bodypart bp1x2" id="rightLeg" style="background-color: #e0e0e0; margin-right: 5px; padding-right: 18px;"></button
><button id="leftLeg" class="avatarAction bodypart bp1x2" style="background-color: #e0e0e0; padding-right: 18px;"></button>
</div> </div>
</div> </div>
</div> </div>
</div> </div>
<small class="text-muted text-center" style="font-size: 0.7rem;">feature of Poly+</small> <small class="text-muted text-center" style="font-size: 0.7rem;">feature of Poly+</small>
</div> </div>
<div class="col-12 col-lg-9"> <div class="col-12 col-lg-9">
<ul class="nav nav-pills nav-justified mb-3" id="tabs"> <ul class="nav nav-pills nav-justified mb-3" id="tabs">
<li class="nav-item"> <li class="nav-item">
<a class="nav-link active" data-tab="hat"> <a class="nav-link active" data-tab="hat">
<i class="fas fa-hat-cowboy me-1"></i> <i class="fas fa-hat-cowboy me-1"></i>
Hats Hats
</a> </a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" data-tab="tool"> <a class="nav-link" data-tab="tool">
<i class="fas fa-hammer me-1"></i> <i class="fas fa-hammer me-1"></i>
Tools Tools
</a> </a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" data-tab="face"> <a class="nav-link" data-tab="face">
<i class="fas fa-face-smile me-1"></i> <i class="fas fa-face-smile me-1"></i>
Faces Faces
</a> </a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" data-tab="shirt"> <a class="nav-link" data-tab="shirt">
<i class="fas fa-tshirt me-1"></i> <i class="fas fa-tshirt me-1"></i>
Shirts Shirts
</a> </a>
</li> </li>
<li class="nav-item"> <li class="nav-item">
<a class="nav-link" data-tab="pants"> <a class="nav-link" data-tab="pants">
<i class="fas fa-socks me-1"></i> <i class="fas fa-socks me-1"></i>
Pants Pants
</a> </a>
</li> </li>
</ul> </ul>
<div class="card px-2 pt-2 pb-2 mb-4" style="background: rgba(0, 0, 0, 0.23); border-color: rgba(0, 0, 0, 0.23); border-top-left-radius: 20px; border-top-right-radius: 20px;"> <div class="card px-2 pt-2 pb-2 mb-4" style="background: rgba(0, 0, 0, 0.23); border-color: rgba(0, 0, 0, 0.23); border-top-left-radius: 20px; border-top-right-radius: 20px;">
<input id="item-search" type="text" class="form-control mb-2" placeholder="Search for an item..."> <input id="item-search" type="text" class="form-control mb-2" placeholder="Search for an item..." />
<div class="row alignleft itemgrid" id="inventory"></div> <div class="row alignleft itemgrid" id="inventory"></div>
</div> </div>
<h6 class="card-header mb-2"><i class="fad fa-hat-wizard me-1"></i> Wearing</h6> <h6 class="card-header mb-2"><i class="fad fa-hat-wizard me-1"></i> Wearing</h6>
<div class="card px-2 pt-2 pb-2 mb-4" style="background: rgba(0, 0, 0, 0.23); border-color: rgba(0, 0, 0, 0.23); border-top-left-radius: 20px; border-top-right-radius: 20px;"> <div class="card px-2 pt-2 pb-2 mb-4" style="background: rgba(0, 0, 0, 0.23); border-color: rgba(0, 0, 0, 0.23); border-top-left-radius: 20px; border-top-right-radius: 20px;">
<div class="row alignleft itemgrid" id="wearing"></div> <div class="row alignleft itemgrid" id="wearing"></div>
</div> </div>
</div> </div>
</div> </div>

View file

@ -1,59 +1,59 @@
{ {
"Date": "2023-7-17", "Date": "2023-7-17",
"Data": [ "Data": [
{ {
"USD": 0.009899999999999999, "USD": 0.009899999999999999,
"EUR": 0.011200000000000002, "EUR": 0.011200000000000002,
"CAD": 0.0123, "CAD": 0.0123,
"GBP": 0.008100000000000001, "GBP": 0.008100000000000001,
"MXN": 0.1928, "MXN": 0.1928,
"AUD": 0.014199999999999999, "AUD": 0.014199999999999999,
"TRY": 0.1583 "TRY": 0.1583
}, },
{ {
"USD": 0.009072727272727274, "USD": 0.009072727272727274,
"EUR": 0.010163636363636363, "EUR": 0.010163636363636363,
"CAD": 0.011290909090909091, "CAD": 0.011290909090909091,
"GBP": 0.007363636363636363, "GBP": 0.007363636363636363,
"MXN": 0.17534545454545455, "MXN": 0.17534545454545455,
"AUD": 0.013418181818181819, "AUD": 0.013418181818181819,
"TRY": 0.14616363636363636 "TRY": 0.14616363636363636
}, },
{ {
"USD": 0.00868695652173913, "USD": 0.00868695652173913,
"EUR": 0.009721739130434783, "EUR": 0.009721739130434783,
"CAD": 0.010730434782608695, "CAD": 0.010730434782608695,
"GBP": 0.007043478260869565, "GBP": 0.007043478260869565,
"MXN": 0.1676521739130435, "MXN": 0.1676521739130435,
"AUD": 0.012834782608695652, "AUD": 0.012834782608695652,
"TRY": 0.13767826086956522 "TRY": 0.13767826086956522
}, },
{ {
"USD": 0.009087272727272727, "USD": 0.009087272727272727,
"EUR": 0.00996, "EUR": 0.00996,
"CAD": 0.010625454545454546, "CAD": 0.010625454545454546,
"GBP": 0.006981818181818182, "GBP": 0.006981818181818182,
"MXN": 0.17294545454545454, "MXN": 0.17294545454545454,
"AUD": 0.012698181818181819, "AUD": 0.012698181818181819,
"TRY": 0.14424 "TRY": 0.14424
}, },
{ {
"USD": 0.008331666666666668, "USD": 0.008331666666666668,
"EUR": 0.009323333333333333, "EUR": 0.009323333333333333,
"CAD": 0.00974, "CAD": 0.00974,
"GBP": 0.006066666666666666, "GBP": 0.006066666666666666,
"MXN": 0.15853333333333333, "MXN": 0.15853333333333333,
"AUD": 0.012306666666666667, "AUD": 0.012306666666666667,
"TRY": 0.13222 "TRY": 0.13222
}, },
{ {
"USD": 0.0079992, "USD": 0.0079992,
"EUR": 0.008950399999999999, "EUR": 0.008950399999999999,
"CAD": 0.0093504, "CAD": 0.0093504,
"GBP": 0.005824, "GBP": 0.005824,
"MXN": 0.152192, "MXN": 0.152192,
"AUD": 0.011814400000000001, "AUD": 0.011814400000000001,
"TRY": 0.12693120000000002 "TRY": 0.12693120000000002
} }
] ]
} }

View file

@ -1,4 +1,7 @@
window.localStorage.setItem('p+account_info', JSON.stringify({ window.localStorage.setItem(
ID: userID, 'p+account_info',
Bricks: document.querySelector('.brickBalanceCont').innerText.replace(/\s+/g,'') JSON.stringify({
})) ID: userID,
Bricks: document.querySelector('.brickBalanceCont').innerText.replace(/\s+/g, '')
})
);

View file

@ -1,2 +1,2 @@
var tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]') var tooltips = document.querySelectorAll('[data-bs-toggle="tooltip"]');
var list = [...tooltips].map(tool => new bootstrap.Tooltip(tool)) var list = [...tooltips].map((tool) => new bootstrap.Tooltip(tool));

View file

@ -8,115 +8,107 @@ HOW TO USE IN CONTENT SCRIPTS:
*/ */
function ParseFullNumber(ab) { function ParseFullNumber(ab) {
if (typeof(ab) === "number") { return ab } if (typeof ab === 'number') {
const Suffixes = {"k": 1000, "m": 1000000, "b": 1000000000} return ab;
const Suffix = ab.slice(-1).toLowerCase(); }
if (Suffixes[Suffix]) {return parseFloat(ab)*Suffixes[Suffix]} else {return parseFloat(ab)} const Suffixes = {k: 1000, m: 1000000, b: 1000000000};
const Suffix = ab.slice(-1).toLowerCase();
if (Suffixes[Suffix]) {
return parseFloat(ab) * Suffixes[Suffix];
} else {
return parseFloat(ab);
}
} }
export default { export default {
DefaultSettings: { DefaultSettings: {
PinnedGamesOn: true, PinnedGamesOn: true,
ForumMentsOn: true, ForumMentsOn: true,
BestFriendsOn: false, BestFriendsOn: false,
ImprovedFrListsOn: false, ImprovedFrListsOn: false,
IRLPriceWithCurrency: { IRLPriceWithCurrency: {
Enabled: true, Enabled: true,
Currency: 0, Currency: 0,
Package: 0 Package: 0
}, },
IRLPriceWithCurrencyOn: true, IRLPriceWithCurrencyOn: true,
IRLPriceWithCurrencyCurrency: 0, IRLPriceWithCurrencyCurrency: 0,
IRLPriceWithCurrencyPackage: 0, IRLPriceWithCurrencyPackage: 0,
HideNotifBadgesOn: false, HideNotifBadgesOn: false,
StoreOwnTagOn: true, StoreOwnTagOn: true,
ThemeCreatorOn: false, ThemeCreatorOn: false,
ThemeCreator: { ThemeCreator: {
Enabled: false, Enabled: false,
BGColor: null, BGColor: null,
BGImage: null, BGImage: null,
BGImageSize: 'fit', BGImageSize: 'fit',
PrimaryTextColor: null, PrimaryTextColor: null,
SecondaryTextColor: null, SecondaryTextColor: null,
LinkTextColor: null, LinkTextColor: null,
WebsiteLogo: null WebsiteLogo: null
}, },
ModifyNavOn: false, ModifyNavOn: false,
ModifyNav: [ ModifyNav: [
{ {
Label: "Places", Label: 'Places',
Link: "https://polytoria.com/places" Link: 'https://polytoria.com/places'
}, },
{ {
Label: "Store", Label: 'Store',
Link: "https://polytoria.com/store" Link: 'https://polytoria.com/store'
}, },
{ {
Label: "Guilds", Label: 'Guilds',
Link: "https://polytoria.com/guilds" Link: 'https://polytoria.com/guilds'
}, },
{ {
Label: "People", Label: 'People',
Link: "https://polytoria.com/users" Link: 'https://polytoria.com/users'
}, },
{ {
Label: "Forum", Label: 'Forum',
Link: "https://polytoria.com/forum" Link: 'https://polytoria.com/forum'
} }
], ],
MoreSearchFiltersOn: true, MoreSearchFiltersOn: true,
ApplyMembershipTheme: { ApplyMembershipTheme: {
Enabled: false, Enabled: false,
Theme: 0 Theme: 0
}, },
ApplyMembershipThemeOn: false, ApplyMembershipThemeOn: false,
ApplyMembershipThemeTheme: 0, ApplyMembershipThemeTheme: 0,
MultiCancelOutTradesOn: true, MultiCancelOutTradesOn: true,
ItemWishlistOn: true, ItemWishlistOn: true,
HideUpgradeBtnOn: false, HideUpgradeBtnOn: false,
TryOnItemsOn: true, TryOnItemsOn: true,
OutfitCostOn: true, OutfitCostOn: true,
ShowPlaceRevenueOn: true, ShowPlaceRevenueOn: true,
ReplaceItemSalesOn: false, ReplaceItemSalesOn: false,
HoardersListOn: true, HoardersListOn: true,
HoardersList: { HoardersList: {
Enabled: true, Enabled: true,
AvatarsEnabled: false, AvatarsEnabled: false,
MinCopies: 2 MinCopies: 2
}, },
LibraryDownloadsOn: true, LibraryDownloadsOn: true,
EventItemsCatOn: true, EventItemsCatOn: true,
HomeFriendCountOn: true, HomeFriendCountOn: true,
HideUserAds: { HideUserAds: {
Enabled: false, Enabled: false,
Banners: true, Banners: true,
Rectangles: true Rectangles: true
} }
}, },
Limits: { Limits: {
PinnedGames: 10, PinnedGames: 10,
BestFriends: 15, BestFriends: 15,
ImprovedFrLists: 20, ImprovedFrLists: 20,
ItemWishlist: 20 ItemWishlist: 20
}, },
MeshTypes: [ MeshTypes: ['hat', 'hair', 'head attachment', 'face accessory', 'neck accessory', 'head cover', 'back accessory', 'shoulder accessory', 'tool'],
"hat", TextureTypes: ['shirt', 'pants', 'face'],
"hair", CalculateIRL: async function (bricks, to, brickPackage) {
"head attachment", /*
"face accessory",
"neck accessory",
"head cover",
"back accessory",
"shoulder accessory",
"tool"
],
TextureTypes: [
"shirt",
"pants",
"face"
],
CalculateIRL: async function(bricks, to, brickPackage) {
/*
Disabled for now: currency retrieval from currencies.json Disabled for now: currency retrieval from currencies.json
const response = await fetch(chrome.runtime.getURL('resources/currencies.json')) const response = await fetch(chrome.runtime.getURL('resources/currencies.json'))
@ -127,108 +119,114 @@ export default {
const UnitPrice = data.Data[brickPackage][to] const UnitPrice = data.Data[brickPackage][to]
*/ */
let Icon = "$" let Icon = '$';
let Result = "N/A"; let Result = 'N/A';
let Display = "Currency Not Found"; let Display = 'Currency Not Found';
// is the icon abbreviated text, or an entity // is the icon abbreviated text, or an entity
let IsIconAbbr = false let IsIconAbbr = false;
bricks = ParseFullNumber(bricks.replace(/,/g, '')) bricks = ParseFullNumber(bricks.replace(/,/g, ''));
switch (to) { switch (to) {
// U.S. Dollar // U.S. Dollar
case 0: case 0:
Result = (bricks * 0.0099).toFixed(2) Result = (bricks * 0.0099).toFixed(2);
Display = "USD" Display = 'USD';
break break;
// Euro // Euro
case 1: case 1:
Icon = "&#8364;" Icon = '&#8364;';
Result = (bricks * 0.009).toFixed(2) Result = (bricks * 0.009).toFixed(2);
Display = "EUR" Display = 'EUR';
break break;
// Canadian Dollar // Canadian Dollar
case 2: case 2:
Icon = "CAD$" Icon = 'CAD$';
IsIconAbbr = true IsIconAbbr = true;
Result = (bricks * 0.0131).toFixed(2) Result = (bricks * 0.0131).toFixed(2);
Display = "CAD" Display = 'CAD';
break break;
// Great British Pound // Great British Pound
case 3: case 3:
Icon = "&#163;" Icon = '&#163;';
Result = (bricks * 0.0077).toFixed(2) Result = (bricks * 0.0077).toFixed(2);
Display = "GBP" Display = 'GBP';
break break;
// Mexican Peso // Mexican Peso
case 4: case 4:
Icon = "MXN$" Icon = 'MXN$';
IsIconAbbr = true IsIconAbbr = true;
Result = (bricks * 0.1691).toFixed(2) Result = (bricks * 0.1691).toFixed(2);
Display = "MXN" Display = 'MXN';
break break;
// Australia Dollar // Australia Dollar
case 5: case 5:
Icon = "AU$" Icon = 'AU$';
IsIconAbbr = true IsIconAbbr = true;
Result = (bricks * 0.0144).toFixed(2) Result = (bricks * 0.0144).toFixed(2);
Display = "AUD" Display = 'AUD';
break break;
// Turkish Lira // Turkish Lira
case 6: case 6:
Icon = "&#8378;" Icon = '&#8378;';
Result = (bricks * 0.2338).toFixed(2) Result = (bricks * 0.2338).toFixed(2);
Display = "TRY" Display = 'TRY';
break break;
// Brazillian Real // Brazillian Real
case 7: case 7:
Icon = "R$" Icon = 'R$';
IsIconAbbr = true IsIconAbbr = true;
Result = (bricks * 0.49).toFixed(2) Result = (bricks * 0.49).toFixed(2);
Display = "BRL" Display = 'BRL';
break break;
} }
if (typeof(Result) === "number") { Result = Result.toFixed(2) } if (typeof Result === 'number') {
Result = Result.toFixed(2);
}
return { return {
result: Result, result: Result,
display: Display, display: Display,
icon: Icon, icon: Icon,
isIconAbbr: IsIconAbbr isIconAbbr: IsIconAbbr
} };
}, },
InjectResource: function(path, element) { InjectResource: function (path, element) {
// Function by devjin0617 on GitHub // Function by devjin0617 on GitHub
// Gist: https://gist.github.com/devjin0617/3e8d72d94c1b9e69690717a219644c7a // Gist: https://gist.github.com/devjin0617/3e8d72d94c1b9e69690717a219644c7a
// Slightly modified to use constants and fit the rest of the code style more // Slightly modified to use constants and fit the rest of the code style more
// Function only used for registering bootstrap tooltips currently // Function only used for registering bootstrap tooltips currently
if (element === undefined) { element = 'body' } if (element === undefined) {
const Node = document.getElementsByTagName(element)[0]; element = 'body';
const Script = document.createElement('script'); }
Script.setAttribute('type', 'text/javascript'); const Node = document.getElementsByTagName(element)[0];
Script.setAttribute('src', chrome.runtime.getURL('resources/' + path + '.js')); const Script = document.createElement('script');
Script.addEventListener('load', function(){Script.remove()}) Script.setAttribute('type', 'text/javascript');
Node.appendChild(Script); Script.setAttribute('src', chrome.runtime.getURL('resources/' + path + '.js'));
} Script.addEventListener('load', function () {
} Script.remove();
});
Node.appendChild(Script);
}
};

File diff suppressed because it is too large Load diff

View file

@ -1,400 +1,426 @@
const SaveBtn = document.getElementById('Save') const SaveBtn = document.getElementById('Save');
const Elements = Array.from(document.getElementsByClassName('setting-container')) const Elements = Array.from(document.getElementsByClassName('setting-container'));
var Settings; var Settings;
var Utilities; var Utilities;
(async () => { (async () => {
Utilities = await import(chrome.runtime.getURL('resources/utils.js')); Utilities = await import(chrome.runtime.getURL('resources/utils.js'));
Utilities = Utilities.default Utilities = Utilities.default;
LoadCurrent() LoadCurrent();
document.getElementById('PinnedGames-limit').innerText = Utilities.Limits.PinnedGames document.getElementById('PinnedGames-limit').innerText = Utilities.Limits.PinnedGames;
document.getElementById('BestFriends-limit').innerText = Utilities.Limits.BestFriends document.getElementById('BestFriends-limit').innerText = Utilities.Limits.BestFriends;
document.getElementById('ImprovedFrLists-limit').innerText = Utilities.Limits.ImprovedFrLists document.getElementById('ImprovedFrLists-limit').innerText = Utilities.Limits.ImprovedFrLists;
document.getElementById('ItemWishlist-limit').innerText = Utilities.Limits.ItemWishlist document.getElementById('ItemWishlist-limit').innerText = Utilities.Limits.ItemWishlist;
})(); })();
// Handle buttons at the bottom of the page // Handle buttons at the bottom of the page
document.getElementById('ResetDefaults').addEventListener('click', function() { document.getElementById('ResetDefaults').addEventListener('click', function () {
document.getElementById('ResetDefaults-Modal').showModal(); document.getElementById('ResetDefaults-Modal').showModal();
}); });
SaveBtn.addEventListener("click", function() { SaveBtn.addEventListener('click', function () {
Save(); Save();
}); });
// Handle modal buttons for Reset Defaults modal // Handle modal buttons for Reset Defaults modal
document.getElementById('ResetDefaults-Modal-Yes').addEventListener('click', function() { document.getElementById('ResetDefaults-Modal-Yes').addEventListener('click', function () {
Settings = Utilities.DefaultSettings Settings = Utilities.DefaultSettings;
Save() Save();
setTimeout(function () { setTimeout(function () {
LoadCurrent(); LoadCurrent();
document.getElementById('ResetDefaults-Modal').close(); document.getElementById('ResetDefaults-Modal').close();
}, 400) }, 400);
}); });
document.getElementById('ResetDefaults-Modal-No').addEventListener('click', function() { document.getElementById('ResetDefaults-Modal-No').addEventListener('click', function () {
document.getElementById('ResetDefaults-Modal').close(); document.getElementById('ResetDefaults-Modal').close();
}); });
// Handle leaving the settings page before saving // Handle leaving the settings page before saving
window.onbeforeunload = function() { window.onbeforeunload = function () {
if (SaveBtn.getAttribute('disabled') !== undefined) { if (SaveBtn.getAttribute('disabled') !== undefined) {
return "Are you sure you'd like to leave? Your Poly+ settings haven't been saved." return "Are you sure you'd like to leave? Your Poly+ settings haven't been saved.";
} }
} };
// Loop thru each setting container and handle toggling, selecting, opening modal, etc // Loop thru each setting container and handle toggling, selecting, opening modal, etc
Elements.forEach(element => { Elements.forEach((element) => {
console.log('Handle Element', element) console.log('Handle Element', element);
let Button = element.getElementsByTagName('button')[0] let Button = element.getElementsByTagName('button')[0];
let Options = element.getElementsByTagName('button')[1] let Options = element.getElementsByTagName('button')[1];
let Select = element.getElementsByTagName('select')[0] let Select = element.getElementsByTagName('select')[0];
let Checkbox = element.getElementsByTagName('input')[0] let Checkbox = element.getElementsByTagName('input')[0];
if (Button) { if (Button) {
Button.addEventListener('click', function() { Button.addEventListener('click', function () {
SetSetting(Button, "bool") SetSetting(Button, 'bool');
}); });
} }
if (Select) { if (Select) {
Select.addEventListener('change', function(){ Select.addEventListener('change', function () {
if (Select.getAttribute('data-useValue') !== undefined) { if (Select.getAttribute('data-useValue') !== undefined) {
let Value = Select.options[Select.selectedIndex].value let Value = Select.options[Select.selectedIndex].value;
if (!isNaN(Value)) { Value = parseInt(Value) } if (!isNaN(Value)) {
SetSetting(Select, Value, false) Value = parseInt(Value);
} else { }
SetSetting(Select, Select.selectedIndex, false) SetSetting(Select, Value, false);
} } else {
}) SetSetting(Select, Select.selectedIndex, false);
} }
});
}
if (Checkbox) { if (Checkbox) {
Checkbox.addEventListener('change', function(){ Checkbox.addEventListener('change', function () {
SetSetting(Checkbox, Checkbox.checked, false) SetSetting(Checkbox, Checkbox.checked, false);
}) });
} }
if (Options) { if (Options) {
const Modal = document.getElementById(Options.getAttribute('data-modal') + '-Modal') const Modal = document.getElementById(Options.getAttribute('data-modal') + '-Modal');
const ModalButtons = Modal.getElementsByTagName('button') const ModalButtons = Modal.getElementsByTagName('button');
const ModalInputs = Modal.getElementsByTagName('input') const ModalInputs = Modal.getElementsByTagName('input');
const ModalSelect = Modal.getElementsByTagName('select') const ModalSelect = Modal.getElementsByTagName('select');
Options.addEventListener('click', function(){ Options.addEventListener('click', function () {
Array.from(ModalButtons).filter((x) => !x.classList.contains('ignore')).forEach(button => { Array.from(ModalButtons)
button.addEventListener('click', function(){ .filter((x) => !x.classList.contains('ignore'))
const Setting = button.getAttribute('data-setting') .forEach((button) => {
button.addEventListener('click', function () {
const Setting = button.getAttribute('data-setting');
if (Setting === '[save]') { if (Setting === '[save]') {
// Save Modal Button // Save Modal Button
Array.from(ModalInputs).filter((x) => !x.classList.contains('ignore')).forEach(input => { Array.from(ModalInputs)
SetSetting(input, input.value, false, Modal.getAttribute('data-setting')) .filter((x) => !x.classList.contains('ignore'))
}); .forEach((input) => {
Array.from(ModalSelect).filter((x) => !x.classList.contains('ignore')).forEach(select => { SetSetting(input, input.value, false, Modal.getAttribute('data-setting'));
SetSetting(select, select.selectedIndex, false, Modal.getAttribute('data-setting')) });
}); Array.from(ModalSelect)
Save(); .filter((x) => !x.classList.contains('ignore'))
setTimeout(function () { .forEach((select) => {
LoadCurrent(); SetSetting(select, select.selectedIndex, false, Modal.getAttribute('data-setting'));
Modal.close(); });
}, 400) Save();
} else if (Setting === '[reset-default]') { setTimeout(function () {
// Reset to Defaults Modal Button LoadCurrent();
Modal.close();
}, 400);
} else if (Setting === '[reset-default]') {
// Reset to Defaults Modal Button
if (confirm("Are you sure you'd like to reset these options to their defaults?") === true) { if (confirm("Are you sure you'd like to reset these options to their defaults?") === true) {
Settings[Modal.getAttribute('data-setting')] = Utilities.DefaultSettings[Modal.getAttribute('data-setting')] Settings[Modal.getAttribute('data-setting')] = Utilities.DefaultSettings[Modal.getAttribute('data-setting')];
Save() Save();
Modal.close(); Modal.close();
} }
} else if (Setting === '[cancel]') { } else if (Setting === '[cancel]') {
// Cancel Changes Button // Cancel Changes Button
Modal.close(); Modal.close();
} else { } else {
// Default Toggle Button // Default Toggle Button
SetSetting(button, "bool", false, Modal.getAttribute('data-setting')) SetSetting(button, 'bool', false, Modal.getAttribute('data-setting'));
} }
}) });
}) });
Array.from(ModalInputs).filter((x) => !x.classList.contains('ignore')).forEach(input => { Array.from(ModalInputs)
const Status = GetSettingValue(input, Modal.getAttribute('data-setting')) .filter((x) => !x.classList.contains('ignore'))
if (Status !== "undefined" && Status !== undefined) { .forEach((input) => {
input.value = Status const Status = GetSettingValue(input, Modal.getAttribute('data-setting'));
} else { if (Status !== 'undefined' && Status !== undefined) {
input.value = '' input.value = Status;
} } else {
}); input.value = '';
}
});
Array.from(ModalSelect).filter((x) => !x.classList.contains('ignore')).forEach(select => { Array.from(ModalSelect)
const Status = GetSettingValue(select, Modal.getAttribute('data-setting')) .filter((x) => !x.classList.contains('ignore'))
if (Status !== "undefined" && Status !== undefined) { .forEach((select) => {
select.selectedIndex = Status const Status = GetSettingValue(select, Modal.getAttribute('data-setting'));
} if (Status !== 'undefined' && Status !== undefined) {
}); select.selectedIndex = Status;
}
});
Modal.showModal() Modal.showModal();
}) });
} }
}); });
function LoadCurrent() { function LoadCurrent() {
chrome.storage.sync.get(["PolyPlus_Settings"], function(result) { chrome.storage.sync.get(['PolyPlus_Settings'], function (result) {
Settings = MergeObjects(result.PolyPlus_Settings || Utilities.DefaultSettings, Utilities.DefaultSettings) Settings = MergeObjects(result.PolyPlus_Settings || Utilities.DefaultSettings, Utilities.DefaultSettings);
console.log("Current Settings: ", Settings) console.log('Current Settings: ', Settings);
Elements.forEach(element => { Elements.forEach((element) => {
console.log('For Each Update') console.log('For Each Update');
UpdateElementState(element) UpdateElementState(element);
}); });
}); });
} }
function SetSetting(element, value, update, modalParent) { function SetSetting(element, value, update, modalParent) {
const name = element.getAttribute('data-setting') const name = element.getAttribute('data-setting');
let parent = element.getAttribute('data-parent') let parent = element.getAttribute('data-parent');
if (modalParent !== undefined) { if (modalParent !== undefined) {
console.log(modalParent) console.log(modalParent);
parent = modalParent parent = modalParent;
} }
if (value === "bool") { if (value === 'bool') {
value = !GetSettingValue(element, modalParent) value = !GetSettingValue(element, modalParent);
} }
if (parent !== null) { if (parent !== null) {
let Parent = Object.values(Settings)[Object.keys(Settings).indexOf(parent)] let Parent = Object.values(Settings)[Object.keys(Settings).indexOf(parent)];
if (!isNaN(element.getAttribute('data-parent')) && element.getAttribute('data-parent') !== null) { if (!isNaN(element.getAttribute('data-parent')) && element.getAttribute('data-parent') !== null) {
console.log('is numbere!!!!') console.log('is numbere!!!!');
Parent = Parent[parseInt(element.getAttribute('data-parent'))] Parent = Parent[parseInt(element.getAttribute('data-parent'))];
} }
Parent[name] = value Parent[name] = value;
} else { } else {
Settings[name] = value Settings[name] = value;
} }
if (update !== false) { if (update !== false) {
UpdateElementState(document.querySelector(`.setting-container:has([data-setting="${name}"])${ (parent !== null) ? `:has([data-parent="${parent}"])` : '' }`), value) UpdateElementState(document.querySelector(`.setting-container:has([data-setting="${name}"])${parent !== null ? `:has([data-parent="${parent}"])` : ''}`), value);
} }
if (SaveBtn.getAttribute('disabled')) { if (SaveBtn.getAttribute('disabled')) {
SaveBtn.removeAttribute('disabled') SaveBtn.removeAttribute('disabled');
} }
const getInObject = function(a, b) { return Object.values(a)[Object.keys(a).indexOf(b)] } const getInObject = function (a, b) {
return Object.values(a)[Object.keys(a).indexOf(b)];
};
} }
function GetSettingValue(element, modalParent) { function GetSettingValue(element, modalParent) {
const name = element.getAttribute('data-setting') const name = element.getAttribute('data-setting');
let parent = element.getAttribute('data-parent') let parent = element.getAttribute('data-parent');
if (modalParent !== undefined) { if (modalParent !== undefined) {
parent = modalParent parent = modalParent;
} }
let Status = name; let Status = name;
if (parent !== null) { if (parent !== null) {
let Parent = Object.values(Settings)[Object.keys(Settings).indexOf(parent)];
if (!isNaN(element.getAttribute('data-parent')) && element.getAttribute('data-parent') !== null) {
Parent = Parent[parseInt(element.getAttribute('data-parent'))];
Status = Parent[name];
} else {
Status = Object.values(Parent)[Object.keys(Parent).indexOf(name)];
}
let Parent = Object.values(Settings)[Object.keys(Settings).indexOf(parent)] /*
if (!isNaN(element.getAttribute('data-parent')) && element.getAttribute('data-parent') !== null) {
Parent = Parent[parseInt(element.getAttribute('data-parent'))]
Status = Parent[name]
} else {
Status = Object.values(Parent)[Object.keys(Parent).indexOf(name)]
}
/*
if (!isNaN(element.getAttribute('data-parent'))) { if (!isNaN(element.getAttribute('data-parent'))) {
Parent = Parent[parseInt(element.getAttribute('data-parent'))] Parent = Parent[parseInt(element.getAttribute('data-parent'))]
} }
Status = Object.values(Parent)[Object.keys(Parent).indexOf(Status)] Status = Object.values(Parent)[Object.keys(Parent).indexOf(Status)]
*/ */
} else { } else {
Status = Settings[Status] Status = Settings[Status];
} }
console.log('Get Value Result', Status) console.log('Get Value Result', Status);
return Status return Status;
} }
function UpdateElementState(element, status) { function UpdateElementState(element, status) {
console.log('Update Element State', element, status) console.log('Update Element State', element, status);
const Button = element.getElementsByClassName('toggle-btn')[0] const Button = element.getElementsByClassName('toggle-btn')[0];
if (status === undefined) { if (status === undefined) {
console.log('Update Element State, no status provided') console.log('Update Element State, no status provided');
status = GetSettingValue(Button) status = GetSettingValue(Button);
} }
if (status === true) { if (status === true) {
console.log('Is Enabled so Set False') console.log('Is Enabled so Set False');
element.classList.add('enabled') element.classList.add('enabled');
element.classList.remove('disabled') element.classList.remove('disabled');
Button.innerText = 'Disable' Button.innerText = 'Disable';
Button.classList.add('btn-danger') Button.classList.add('btn-danger');
Button.classList.remove('btn-success') Button.classList.remove('btn-success');
} else { } else {
console.log('Is Disabled so Set True') console.log('Is Disabled so Set True');
element.classList.add('disabled') element.classList.add('disabled');
element.classList.remove('enabled') element.classList.remove('enabled');
Button.innerText = 'Enable' Button.innerText = 'Enable';
Button.classList.add('btn-success') Button.classList.add('btn-success');
Button.classList.remove('btn-danger') Button.classList.remove('btn-danger');
} }
let SelectInput = element.getElementsByTagName('select')[0] let SelectInput = element.getElementsByTagName('select')[0];
if (SelectInput) { if (SelectInput) {
console.log('Select Found') console.log('Select Found');
SelectInput.selectedIndex = GetSettingValue(SelectInput) SelectInput.selectedIndex = GetSettingValue(SelectInput);
} }
let Checkbox = Array.from(element.getElementsByTagName('input')) let Checkbox = Array.from(element.getElementsByTagName('input'));
if (Checkbox.length > 0) { if (Checkbox.length > 0) {
console.log('Checkbox/Input(s) Found', Checkbox) console.log('Checkbox/Input(s) Found', Checkbox);
Checkbox.forEach(check => { Checkbox.forEach((check) => {
console.log('check', GetSettingValue(check)) console.log('check', GetSettingValue(check));
check.checked = GetSettingValue(check) check.checked = GetSettingValue(check);
}) });
} }
} }
function Save() { function Save() {
document.title = 'Poly+ Settings' document.title = 'Poly+ Settings';
SaveBtn.setAttribute('disabled', 'true') SaveBtn.setAttribute('disabled', 'true');
chrome.storage.sync.set({ 'PolyPlus_Settings': Settings, arrayOrder: true }, function() { chrome.storage.sync.set({PolyPlus_Settings: Settings, arrayOrder: true}, function () {
console.log('Saved successfully!'); console.log('Saved successfully!');
}); });
console.log("Save:", Settings); console.log('Save:', Settings);
} }
let LoadThemeFromJSONBtn = document.getElementById('LoadThemeFromJSONBtn') let LoadThemeFromJSONBtn = document.getElementById('LoadThemeFromJSONBtn');
let SaveThemeToJSONInput = document.getElementById('SaveThemeToJSONInput') let SaveThemeToJSONInput = document.getElementById('SaveThemeToJSONInput');
let CopyThemeJSONBtn = document.getElementById('CopyThemeJSONBtn') let CopyThemeJSONBtn = document.getElementById('CopyThemeJSONBtn');
LoadThemeFromJSONBtn.addEventListener('click', function(){ LoadThemeFromJSONBtn.addEventListener('click', function () {
LoadThemeJSON(LoadThemeFromJSONBtn.previousElementSibling.value) LoadThemeJSON(LoadThemeFromJSONBtn.previousElementSibling.value);
}); });
document.getElementById('theme-creator').getElementsByTagName('button')[1].addEventListener('click', function(){ document
SaveThemeToJSONInput.value = JSON.stringify(Settings.ThemeCreator) .getElementById('theme-creator')
}); .getElementsByTagName('button')[1]
CopyThemeJSONBtn.addEventListener('click', function(){ .addEventListener('click', function () {
if (SaveThemeToJSONInput.value.length > 0) { SaveThemeToJSONInput.value = JSON.stringify(Settings.ThemeCreator);
navigator.clipboard.writeText(SaveThemeToJSONInput.value) });
.then(() => { CopyThemeJSONBtn.addEventListener('click', function () {
alert('Successfully copied theme data to clipboard!') if (SaveThemeToJSONInput.value.length > 0) {
}) navigator.clipboard
.catch(() => { .writeText(SaveThemeToJSONInput.value)
alert('Failure to copy theme data to clipboard.') .then(() => {
}); alert('Successfully copied theme data to clipboard!');
} })
.catch(() => {
alert('Failure to copy theme data to clipboard.');
});
}
}); });
function LoadThemeJSON(string) { function LoadThemeJSON(string) {
try { try {
let JSONTable = JSON.parse(string) let JSONTable = JSON.parse(string);
if (JSONTable.length === Utilities.DefaultSettings.ThemeCreator.length) { if (JSONTable.length === Utilities.DefaultSettings.ThemeCreator.length) {
if (confirm('Are you sure you\'d like to replace this theme with the theme specified in the JSON?') === true) { if (confirm("Are you sure you'd like to replace this theme with the theme specified in the JSON?") === true) {
LoadThemeFromJSONBtn.previousElementSibling.value = '' LoadThemeFromJSONBtn.previousElementSibling.value = '';
document.getElementById('ThemeCreator-Modal').close() document.getElementById('ThemeCreator-Modal').close();
for (let i = 0; i < JSONTable.length; i++) { for (let i = 0; i < JSONTable.length; i++) {
if (JSONTable[i][0] !== "#") { if (JSONTable[i][0] !== '#') {
JSONTable[i] = "" JSONTable[i] = '';
} }
} }
Settings.ThemeCreator = MergeObjects(JSONTable, Utilities.DefaultSettings.ThemeCreator) Settings.ThemeCreator = MergeObjects(JSONTable, Utilities.DefaultSettings.ThemeCreator);
Save(); Save();
console.log(JSONTable.length, JSONTable, 'applied') console.log(JSONTable.length, JSONTable, 'applied');
document.getElementById('ThemeCreator').getElementsByTagName('button')[1].click(); document.getElementById('ThemeCreator').getElementsByTagName('button')[1].click();
} }
} else { } else {
alert('JSON is not a theme!') alert('JSON is not a theme!');
} }
} catch (error) { } catch (error) {
alert('JSON is invalid!') alert('JSON is invalid!');
} }
} }
// MergeObjects function was written by ChatGPT cause I was lazy and it was awhile ago // MergeObjects function was written by ChatGPT cause I was lazy and it was awhile ago
function MergeObjects(obj1, obj2) { function MergeObjects(obj1, obj2) {
var mergedObj = {}; var mergedObj = {};
// Copy the values from obj1 to the mergedObj // Copy the values from obj1 to the mergedObj
for (var key in obj1) { for (var key in obj1) {
mergedObj[key] = obj1[key]; mergedObj[key] = obj1[key];
} }
// Merge the values from obj2 into the mergedObj, favoring obj2 for non-existing keys in obj1 // Merge the values from obj2 into the mergedObj, favoring obj2 for non-existing keys in obj1
for (var key in obj2) { for (var key in obj2) {
if (!obj1.hasOwnProperty(key)) { if (!obj1.hasOwnProperty(key)) {
mergedObj[key] = obj2[key]; mergedObj[key] = obj2[key];
} }
} }
return mergedObj; return mergedObj;
} }
function FormatBool(bool){ function FormatBool(bool) {
if (bool === true) { return 'enabled' } if (bool === true) {
else { return 'disabled' } return 'enabled';
} else {
return 'disabled';
}
} }
const Manifest = chrome.runtime.getManifest() const Manifest = chrome.runtime.getManifest();
let BuildType = "Stable" let BuildType = 'Stable';
if (Manifest.version_name !== undefined) {BuildType = "Pre-Release"} if (Manifest.version_name !== undefined) {
BuildType = 'Pre-Release';
}
const FooterText = document.getElementById('footer-text') const FooterText = document.getElementById('footer-text');
FooterText.children[0].innerHTML = `Version: v${Manifest.version} | Build Type: ${BuildType}` FooterText.children[0].innerHTML = `Version: v${Manifest.version} | Build Type: ${BuildType}`;
const CheckForUpdatesButton = document.getElementById('check-for-updates') const CheckForUpdatesButton = document.getElementById('check-for-updates');
function CheckForUpdates() { function CheckForUpdates() {
CheckForUpdatesButton.removeEventListener('click', CheckForUpdates) CheckForUpdatesButton.removeEventListener('click', CheckForUpdates);
CheckForUpdatesButton.disabled = true CheckForUpdatesButton.disabled = true;
fetch('https://polyplus.vercel.app/data/version.json') fetch('https://polyplus.vercel.app/data/version.json')
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
if (data.version === Manifest.version || Math.floor((data.version - Manifest.version) * 10) === 0) { if (data.version === Manifest.version || Math.floor((data.version - Manifest.version) * 10) === 0) {
CheckForUpdatesButton.innerHTML = '<b>No updates available</b>' CheckForUpdatesButton.innerHTML = '<b>No updates available</b>';
alert('No updates available') alert('No updates available');
} else { } else {
const NumberOfUpdatesAvailable = Math.floor((data.version - Version) * 10) const NumberOfUpdatesAvailable = Math.floor((data.version - Version) * 10);
CheckForUpdatesButton.innerHTML = '<b>'+NumberOfUpdatesAvailable+' update(s) available</b>' CheckForUpdatesButton.innerHTML = '<b>' + NumberOfUpdatesAvailable + ' update(s) available</b>';
alert(NumberOfUpdatesAvailable + ' updates available') alert(NumberOfUpdatesAvailable + ' updates available');
} }
}) })
.catch(error => {console.log(error)}); .catch((error) => {
console.log(error);
});
} }
CheckForUpdatesButton.addEventListener('click', CheckForUpdates) CheckForUpdatesButton.addEventListener('click', CheckForUpdates);
fetch(chrome.runtime.getURL('resources/currencies.json')) fetch(chrome.runtime.getURL('resources/currencies.json'))
.then(response => { .then((response) => {
if (!response.ok) { if (!response.ok) {
throw new Error('Network not ok') throw new Error('Network not ok');
} }
return response.json() return response.json();
}) })
.then(data => { .then((data) => {
const DateText = new Date(data.Date).toLocaleDateString("en-US", {day:"numeric",month:"long",year:"numeric"}) const DateText = new Date(data.Date).toLocaleDateString('en-US', {day: 'numeric', month: 'long', year: 'numeric'});
document.getElementById('IRLPriceWithCurrency-Date').innerText = DateText document.getElementById('IRLPriceWithCurrency-Date').innerText = DateText;
}) })
.catch(error => {console.log(error)}) .catch((error) => {
console.log(error);
});
chrome.storage.local.get(['PolyPlus_OutOfDate', 'PolyPlus_LiveVersion', 'PolyPlus_ReleaseNotes', 'PolyPlus_SkipUpdate'], function(result) { chrome.storage.local.get(['PolyPlus_OutOfDate', 'PolyPlus_LiveVersion', 'PolyPlus_ReleaseNotes', 'PolyPlus_SkipUpdate'], function (result) {
const OutOfDate = result.PolyPlus_OutOfDate || false const OutOfDate = result.PolyPlus_OutOfDate || false;
const SkipUpdate = result.PolyPlus_SkipUpdate || null const SkipUpdate = result.PolyPlus_SkipUpdate || null;
const LiveVersion = result.PolyPlus_LiveVersion || Manifest.version const LiveVersion = result.PolyPlus_LiveVersion || Manifest.version;
if (OutOfDate === true && SkipUpdate !== LiveVersion) { if (OutOfDate === true && SkipUpdate !== LiveVersion) {
const Banner = document.createElement('div') const Banner = document.createElement('div');
Banner.classList = 'alert position-sticky p-3' Banner.classList = 'alert position-sticky p-3';
Banner.style = 'top: 30px; box-shadow: 0 0 20px 2px #000; z-index: 2000; background: rgb(163 39 39);' Banner.style = 'top: 30px; box-shadow: 0 0 20px 2px #000; z-index: 2000; background: rgb(163 39 39);';
Banner.innerHTML = ` Banner.innerHTML = `
<b>New Update Available!</b> <b>New Update Available!</b>
<br> <br>
Your Poly+ installation is out of date! If you would like to get the latest and greatest features, improvements, and bug fixes click on one of the links below to dismiss this banner! Your Poly+ installation is out of date! If you would like to get the latest and greatest features, improvements, and bug fixes click on one of the links below to dismiss this banner!
@ -403,15 +429,15 @@ chrome.storage.local.get(['PolyPlus_OutOfDate', 'PolyPlus_LiveVersion', 'PolyPlu
<a href="${result.PolyPlus_ReleaseNotes}" class="btn btn-primary btn-sm w-25" target="_blank">Go to Release Notes</a> <a href="${result.PolyPlus_ReleaseNotes}" class="btn btn-primary btn-sm w-25" target="_blank">Go to Release Notes</a>
<button id="skip-this-update" class="btn btn-warning btn-sm w-25">(Not Recommended) Skip this Update</button> <button id="skip-this-update" class="btn btn-warning btn-sm w-25">(Not Recommended) Skip this Update</button>
</div> </div>
` `;
document.getElementById('page').insertBefore(Banner, document.getElementById('page').children[1]) document.getElementById('page').insertBefore(Banner, document.getElementById('page').children[1]);
const SkipButton = document.getElementById('skip-this-update') const SkipButton = document.getElementById('skip-this-update');
SkipButton.addEventListener('click', function(){ SkipButton.addEventListener('click', function () {
Banner.remove() Banner.remove();
chrome.storage.local.set({'PolyPlus_SkipUpdate': result.PolyPlus_LiveVersion}, function(){ chrome.storage.local.set({PolyPlus_SkipUpdate: result.PolyPlus_LiveVersion}, function () {
console.log('set skip update to live version: ', result.PolyPlus_LiveVersion) console.log('set skip update to live version: ', result.PolyPlus_LiveVersion);
}) });
}); });
} }
}) });