feat: extended village profile (#9)
continuous-integration/drone/push Build is passing Details
continuous-integration/drone/tag Build is passing Details

Reviewed-on: #9
This commit is contained in:
Dawid Wysokiński 2023-02-05 07:33:32 +00:00
parent 938142a298
commit 93961c1778
8 changed files with 269 additions and 7 deletions

View File

@ -2,7 +2,7 @@ const preambles = {
'extended-player-profile': `// ==UserScript==
// @name Extended player profile
// @version 1.1.1
// @description Adds additional info and actions to a player's profile.
// @description Adds additional info and actions on a player overview.
// @author Dawid Wysokiński - Kichiyaki - contact@dwysokinski.me
// @match https://*/game.php?*screen=info_player*
// @downloadURL ${process.env.PUBLIC_URL}/extended-player-profile.user.js
@ -22,6 +22,18 @@ const preambles = {
// @icon https://www.google.com/s2/favicons?domain=plemiona.pl
// @grant none
// @run-at document-end
// ==/UserScript==`,
'extended-village-profile': `// ==UserScript==
// @name Extended village profile
// @version 1.0.0
// @description Adds additional info and actions on a village overview.
// @author Dawid Wysokiński - Kichiyaki - contact@dwysokinski.me
// @match https://*/game.php?*screen=info_village*
// @downloadURL ${process.env.PUBLIC_URL}/extended-village-profile.user.js
// @updateURL ${process.env.PUBLIC_URL}/extended-village-profile.user.js
// @icon https://www.google.com/s2/favicons?domain=plemiona.pl
// @grant none
// @run-at document-end
// ==/UserScript==`,
};

View File

@ -6,7 +6,7 @@ This repo contains a variety of scripts for [Tribal Wars](https://www.tribalwars
### Extended player profile
This script adds additional info and actions to a player's profile.
This script adds additional info and actions on a player overview.
![img.png](docs/extended-player-profile.png)
@ -36,6 +36,22 @@ javascript:
$.getScript('https://scripts.tribalwarshelp.com/extended-map-popup.quickbar.js')
```
### Extended village profile
This script adds additional info and actions on a village overview.
![img.png](docs/extended-village-profile.png)
#### Installation
[User script](https://scripts.tribalwarshelp.com/extended-village-profile.user.js)
Quick bar:
```javascript
javascript:
$.getScript('https://scripts.tribalwarshelp.com/extended-village-profile.quickbar.js')
```
## License
Distributed under the MIT License. See ``LICENSE`` for more information.

Binary file not shown.

After

Width:  |  Height:  |  Size: 51 KiB

View File

@ -8,6 +8,8 @@
"build:extended-player-profile-quickbar": "yarn build-single ./src/extended-player-profile.quickbar.ts",
"build:extended-map-popup-user": "PREAMBLE=extended-map-popup yarn build-single ./src/extended-map-popup.user.ts",
"build:extended-map-popup-quickbar": "yarn build-single ./src/extended-map-popup.quickbar.ts",
"build:extended-village-profile-user": "PREAMBLE=extended-village-profile yarn build-single ./src/extended-village-profile.user.ts",
"build:extended-village-profile-quickbar": "yarn build-single ./src/extended-village-profile.quickbar.ts",
"build": "npm-run-all build:*",
"lint": "eslint src/**/*.ts"
},

View File

@ -225,10 +225,7 @@ class Popup {
{
id: Popup.ID_LOYALTY,
title: t('Loyalty'),
value: calcLoyalty(
ennoblement?.createdAt ?? new Date(0),
this.config.speed
),
value: calcLoyalty(ennoblement?.createdAt ?? 0, this.config.speed),
},
].forEach(({ id, title, value }) => {
let tr = tbody.querySelector('#' + id);

View File

@ -313,7 +313,6 @@ class UI {
a.innerText = name;
a.href = '#';
a.addEventListener('click', handler);
a.setAttribute('data-player-id', this.player.id.toString());
td.appendChild(a);
tr.appendChild(td);
tbody.appendChild(tr);

View File

@ -0,0 +1,2 @@
// Parcel doesn't have an option to rename output files
import './extended-village-profile.user';

View File

@ -0,0 +1,234 @@
import { Ennoblement, ServerConfig, TWHelpClient } from './lib/twhelp';
import { createTranslationFunc } from './utils';
import { DialogTable } from './common/dialog-table';
import { calcLoyalty } from './lib/tw';
import { Cache } from './lib/cache';
const t = createTranslationFunc({
pl_PL: {
'Show ennoblements': 'Pokaż przejęcia',
'Date/time': 'Data/czas',
Village: 'Wioska',
'Old owner': 'Stary właściciel',
'New owner': 'Nowy właściciel',
Points: 'Punkty',
Barbarian: 'Barbarzyńska',
'Ennobled at': 'Ostatnio przejęta',
Unknown: 'Nieznany',
Loyalty: 'Poparcie',
Never: 'Nigdy',
},
});
class TWHelpConnector {
private static SERVER_CONFIG_CACHE_KEY =
'extended_village_profile_server_config';
private cache = new Cache(localStorage);
constructor(
private readonly client: TWHelpClient,
private readonly version: string,
private readonly server: string,
private readonly id: number
) {}
serverConfig() {
return this.cache.load(
TWHelpConnector.SERVER_CONFIG_CACHE_KEY,
3600,
() => {
return this.client.serverConfig(this.version, this.server);
}
);
}
async latestEnnoblement() {
const ennoblements = await this.client.villageEnnoblements(
this.version,
this.server,
this.id,
{
limit: 1,
sort: ['createdAt:DESC'],
}
);
return ennoblements.data.length > 0 ? ennoblements.data[0] : null;
}
villageEnnoblements(page: number, limit: number) {
return this.client.villageEnnoblements(this.version, this.server, this.id, {
offset: (page - 1) * limit,
limit,
sort: ['createdAt:desc'],
});
}
}
enum DialogId {
ENNOBLEMENTS = 'extended_village_profile_ennoblements',
}
class UI {
constructor(
private readonly config: ServerConfig,
private readonly ennoblement: Ennoblement | null,
private readonly connector: TWHelpConnector
) {}
render() {
this.renderAdditionalInfo();
this.renderActions();
}
private renderAdditionalInfo() {
const tbody = document.querySelector('#embedmap_village')?.closest('tbody');
if (!(tbody instanceof HTMLTableSectionElement)) {
return;
}
tbody.insertAdjacentHTML(
'beforeend',
`
<tr>
<td>${t('Ennobled at')}:</td>
<td>${
this.ennoblement
? new Date(this.ennoblement.createdAt).toLocaleString()
: t('Never')
}</td>
</tr>
<tr>
<td>${t('Loyalty')}:</td>
<td>${calcLoyalty(
this.ennoblement?.createdAt ?? 0,
this.config.speed
)}</td>
</tr>
`
);
}
private renderActions() {
const tbody = document
.querySelector('#content_value a[href*="twstats"]')
?.closest('tbody');
if (!(tbody instanceof HTMLTableSectionElement)) {
return;
}
[
{
name: t('Show ennoblements'),
handler: this.showEnnoblements.bind(this),
},
].forEach(({ name, handler }) => {
const tr = document.createElement('tr');
const td = document.createElement('td');
td.colSpan = 2;
const a = document.createElement('a');
a.innerText = name;
a.href = '#';
a.addEventListener('click', handler);
td.appendChild(a);
tr.appendChild(td);
tbody.appendChild(tr);
});
}
private async showEnnoblements(e: Event) {
e.preventDefault();
await new DialogTable(
DialogId.ENNOBLEMENTS,
[
{
header: t('Village'),
accessor: (e) =>
`<a href="${e.village.profileUrl}">${e.village.fullName}</a>`,
},
{
header: t('Points'),
accessor: (e) => e.points.toLocaleString(),
},
{
header: t('Old owner'),
accessor: ({ village: { player } }) => {
if (!player) {
return t('Barbarian');
}
return `<a href="${player.profileUrl}">${player.name}</a>${
player.tribe
? ` (<a href="${player.tribe.profileUrl}">${player.tribe.tag}</a>)`
: ''
}`;
},
},
{
header: t('New owner'),
accessor: ({ newOwner }) => {
if (!newOwner) {
return t('Unknown');
}
return `<a href="${newOwner.profileUrl}">${newOwner.name}</a>${
newOwner.tribe
? ` (<a href="${newOwner.tribe.profileUrl}">${newOwner.tribe.tag}</a>)`
: ''
}`;
},
},
{
header: t('Date/time'),
accessor: (e) => new Date(e.createdAt).toLocaleString(),
},
],
30,
(page: number, limit: number) => {
return this.connector.villageEnnoblements(page, limit);
}
).render();
}
}
class ExtendedVillageProfile {
connector: TWHelpConnector;
constructor(client: TWHelpClient) {
this.connector = new TWHelpConnector(
client,
window.game_data.market,
window.game_data.world,
this.getVillageId()
);
}
async run() {
const config = await this.connector.serverConfig();
const ennoblement = await this.connector.latestEnnoblement();
new UI(config, ennoblement, this.connector).render();
}
private getVillageId() {
const str = new URLSearchParams(window.location.search).get('id');
if (!str) {
return 0;
}
return parseInt(str);
}
}
(async () => {
if (
window.game_data.screen !== 'info_village' ||
window.game_data.mode !== null
) {
return;
}
await new ExtendedVillageProfile(
new TWHelpClient(process.env.TWHELP_API_BASE_URL ?? '')
)
.run()
.catch((err) => {
console.log(err);
});
})();