Files
WT-Offline/packages/local-service/src/inventory/web/app.js
T
N0VAN0M4LY d7fc94e551 Update the store and marketplace pages and image sources
Add catalogue filters, item detail views, and purchase and resale
actions. Resolve images from the player's asset pack, public image
URLs, or local game data. Add a utility for creating the optional
local asset pack.

Type checking and JavaScript syntax checks passed. Embedded browser
appearance and in-game behavior still need acceptance.
2026-11-26 07:12:38 +08:00

205 lines
13 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Local marketplace page (implementation notes; layout after the official Gaijin Market,
// implementation notes), shown in the game's built-in browser.
// The game opens it as <marketplaceURL>?a=<app id>[&viewitem&n=<market_hash_name>] (inventoryClient.nut);
// with `n` the page opens that item's card directly.
'use strict';
const T = {
zh: {
toStore: '前往商城', eagles: '金鹰', filters: '筛选', itemType: '物品类型', country: '国家', vehicleClass: '适用于',
heldOnly: '只看我的库存', search: '搜索', sortPopular: '人气', sortName: '名称(从 A 到 Z)', sortPriceAsc: '价格(从低到高)', sortPriceDesc: '价格(从高到低)',
catVehicle: '载具', catSkin: '涂装', catAttachable: '装饰挂件', catDecal: '贴花', catUnlock: '头像',
allCountries: '全部国家', allClasses: '全部', rank: '{rank} 级', from: '从', held: '库存 ×{n}', owned: '已拥有',
buy: '购买', freeBuy: '老福爷付过了', sell: '出售', pickAccount: '请先在右上角选择账号', empty: '没有符合条件的物品',
buyPrice: '系统售价:<b>{price}</b> GJN', sellPrice: '卖给系统:<b>{price}</b> GJN(扣 {fee}% 手续费)', youHave: '你拥有:<b>{n}</b>',
tagType: '物品类型', tagRarity: '稀有度', tagCountry: '国家', ticker: '离线交易所:按固定价格与系统交易,价格取自官方交易所快照。',
},
en: {
toStore: 'Store', eagles: 'Golden Eagles', filters: 'Filters', itemType: 'Item type', country: 'Country', vehicleClass: 'Vehicle type',
heldOnly: 'Only my inventory', search: 'Search', sortPopular: 'Popular', sortName: 'Name (A to Z)', sortPriceAsc: 'Price (low to high)', sortPriceDesc: 'Price (high to low)',
catVehicle: 'Vehicles', catSkin: 'Camouflages', catAttachable: 'Decorations', catDecal: 'Decals', catUnlock: 'Avatars',
allCountries: 'All countries', allClasses: 'All', rank: 'Rank {rank}', from: 'from', held: 'Owned ×{n}', owned: 'Owned',
buy: 'Buy', freeBuy: '老福爷付过了', sell: 'Sell', pickAccount: 'Pick an account at the top right', empty: 'Nothing matches the filters',
buyPrice: 'System price: <b>{price}</b> GJN', sellPrice: 'Sell to system: <b>{price}</b> GJN ({fee}% fee)', youHave: 'You own: <b>{n}</b>',
tagType: 'Item type', tagRarity: 'Rarity', tagCountry: 'Country', ticker: 'Offline market: fixed-price trades with the system, prices from an official market snapshot.',
},
};
const CATEGORIES = [['vehicle', 'catVehicle', '#fd5f2c'], ['skin', 'catSkin', '#8f7ee7'], ['attachable', 'catAttachable', '#8f7ee7'], ['decal', 'catDecal', '#8f7ee7'], ['unlock', 'catUnlock', '#00ced1']];
const CLASS_LABELS = { aircraft: 'mainmenu/type_aircraft', helicopter: 'mainmenu/type_helicopter', tank: 'mainmenu/type_tank', ship: 'mainmenu/type_ship_only', boat: 'mainmenu/type_boat_only' };
const RARITY = { afafa1: ['常见', 'Common'], '14bd3a': ['罕见', 'Uncommon'], '2965ff': ['稀有', 'Rare'], c816c1: ['超稀有', 'Ultra rare'] };
const ROMAN = ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX', 'X'];
const t = (key, params) => WtoUi.tr(T, key, params);
const $ = (id) => document.getElementById(id);
const wantedItem = WtoUi.query.get('n') || '';
let state = { accounts: [], currentUserId: '', balance: { gjnCents: 0, goldenEagles: 0 }, sellFeeRate: 0.15, listings: [] };
const activeCats = new Set();
let openedWanted = false;
function applyStaticTexts() {
for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t);
$('searchInput').placeholder = t('search');
$('storeLink').href = WtoUi.pageLink('/store');
const types = $('typeFilters');
for (const [cat, key, color] of CATEGORIES) {
const row = document.createElement('label');
row.className = 'check';
row.innerHTML = '<input type="checkbox" /> <span></span>';
row.querySelector('span').textContent = t(key);
row.querySelector('span').style.color = color;
row.querySelector('input').onchange = (e) => { if (e.target.checked) activeCats.add(cat); else activeCats.delete(cat); renderGrid(); };
types.appendChild(row);
}
const classSelect = $('classFilter');
classSelect.appendChild(new Option(t('allClasses'), ''));
for (const [unitClass, key] of Object.entries(CLASS_LABELS)) classSelect.appendChild(new Option(WtoUi.label(key), unitClass));
}
async function loadState(userId) {
state = await WtoUi.getJson('/trade.gaijin.net/api/state' + (userId ? '?userId=' + encodeURIComponent(userId) : ''));
if (userId && !state.currentUserId) { WtoUi.clearSavedAccount(); return loadState(''); }
WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.currentUserId);
$('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents);
$('goldVal').textContent = WtoUi.num(state.balance.goldenEagles);
renderCountries();
renderGrid();
if (wantedItem && !openedWanted) {
openedWanted = true;
const wanted = state.listings.find((l) => l.marketHashName === wantedItem);
if (wanted) openDetail(wanted);
}
}
function renderCountries() {
const select = $('countryFilter');
const previous = select.value;
select.innerHTML = '';
select.appendChild(new Option(t('allCountries'), ''));
for (const country of [...new Set(state.listings.map((l) => l.country).filter(Boolean))]) select.appendChild(new Option(WtoUi.label(country), country, false, country === previous));
}
function matches(listing) {
const query = $('searchInput').value.trim().toLowerCase();
if (activeCats.size && !activeCats.has(listing.category)) return false;
if ($('countryFilter').value && listing.country !== $('countryFilter').value) return false;
if ($('classFilter').value && listing.unitClass !== $('classFilter').value) return false;
if ($('heldOnly').checked && !listing.couponCount) return false;
return !query || [listing.title.zh, listing.title.en, listing.marketHashName, String(listing.itemdefId)].some((s) => (s || '').toLowerCase().includes(query));
}
function sorted(listings) {
const mode = $('sortSelect').value;
const copy = [...listings];
if (mode === 'name') copy.sort((a, b) => WtoUi.text(a.title).localeCompare(WtoUi.text(b.title)));
if (mode === 'priceAsc') copy.sort((a, b) => a.gjnCostCents - b.gjnCostCents);
if (mode === 'priceDesc') copy.sort((a, b) => b.gjnCostCents - a.gjnCostCents);
return copy;
}
function listingImage(listing, className) {
return listing.category === 'vehicle' ? WtoUi.vehicleImg(listing.targetKey, className) : WtoUi.itemImg(listing.targetKey, '', className);
}
function renderGrid() {
const grid = $('grid');
grid.innerHTML = '';
const listings = sorted(state.listings.filter(matches));
if (!listings.length) grid.innerHTML = '<div class="empty">' + WtoUi.escapeHtml(t('empty')) + '</div>';
for (const listing of listings) grid.appendChild(lotCard(listing));
}
function lotCard(listing) {
const card = document.createElement('a');
card.className = 'lot' + (listing.marketHashName === wantedItem ? ' highlight' : '');
const color = '#' + (listing.nameColor || 'afafa1');
card.innerHTML = '<div class="rarity"></div><div class="lot-image"></div><div class="lot-meta"><div class="project"></div><div class="lot-name"></div></div><div class="lot-stats"></div>';
card.querySelector('.rarity').style.background = 'linear-gradient(180deg, ' + color + ', transparent)';
card.querySelector('.lot-image').appendChild(listingImage(listing, ''));
const project = card.querySelector('.project');
if (listing.country) project.appendChild(WtoUi.iconImg('flag', listing.country, ''));
project.appendChild(document.createTextNode(listing.rank ? 'War Thunder · ' + t('rank', { rank: ROMAN[listing.rank] || listing.rank }) : 'War Thunder'));
card.querySelector('.lot-name').textContent = WtoUi.text(listing.title);
const stats = card.querySelector('.lot-stats');
if (listing.couponCount) stats.appendChild(Object.assign(document.createElement('div'), { className: 'lot-held', textContent: t('held', { n: listing.couponCount }) }));
else if (listing.alreadyActivated) stats.appendChild(Object.assign(document.createElement('div'), { className: 'lot-held', textContent: t('owned') }));
const price = document.createElement('div');
price.className = 'lot-price';
price.innerHTML = '<small></small><span></span> GJN';
price.querySelector('small').textContent = t('from');
price.querySelector('span').textContent = WtoUi.gjn(listing.gjnCostCents);
stats.appendChild(price);
card.onclick = () => openDetail(listing);
return card;
}
function tag(text, color, extraClass) {
const el = Object.assign(document.createElement('span'), { className: 'tag' + (extraClass ? ' ' + extraClass : ''), textContent: text });
if (color) el.style.background = color;
return el;
}
function openDetail(listing) {
const color = '#' + (listing.nameColor || 'afafa1');
const detail = $('detail');
detail.style.setProperty('--glow', color);
detail.innerHTML = '<div class="detail-glow"></div><button class="detail-close">×</button><h2 class="detail-title"></h2>'
+ '<div class="detail-info"><div class="detail-image"></div><div class="detail-side"><div class="tags"></div><div class="detail-desc"></div></div></div>'
+ '<div class="orders"><div class="sell-col"></div><div class="buy-col"></div></div><div class="ticker"></div>';
detail.querySelector('.detail-title').textContent = WtoUi.text(listing.title);
detail.querySelector('.detail-image').appendChild(listingImage(listing, ''));
const tags = detail.querySelector('.tags');
tags.appendChild(tag('War Thunder', '', 'game'));
const cat = CATEGORIES.find((c) => c[0] === listing.category);
if (cat) tags.appendChild(tag(t('tagType') + ': ' + t(cat[1]), cat[2]));
const rarity = RARITY[(listing.nameColor || '').toLowerCase()];
if (rarity) tags.appendChild(tag(t('tagRarity') + ': ' + (WtoUi.lang === 'zh' ? rarity[0] : rarity[1]), color));
if (listing.country) tags.appendChild(tag(t('tagCountry') + ': ' + WtoUi.label(listing.country), '#68838c'));
detail.querySelector('.detail-desc').textContent = WtoUi.text(listing.subtitle);
fillOrderColumns(detail, listing);
detail.querySelector('.ticker').textContent = t('ticker');
detail.querySelector('.detail-close').onclick = closeDetail;
$('modal').hidden = false;
}
function fillOrderColumns(detail, listing) {
const fee = Math.round((state.sellFeeRate || 0) * 100);
const sellCol = detail.querySelector('.sell-col');
const buyCol = detail.querySelector('.buy-col');
const noAccount = !state.currentUserId;
const sellBtn = Object.assign(document.createElement('button'), { className: 'big sell', textContent: t('sell'), disabled: noAccount || !listing.couponCount });
sellBtn.onclick = () => trade('/trade.gaijin.net/api/sell', { itemdefId: listing.itemdefId, quantity: 1 }, listing);
sellCol.append(sellBtn, html('totals', t('sellPrice', { price: WtoUi.gjn(listing.sellCents), fee })), html('totals', t('youHave', { n: listing.couponCount || 0 })));
const buyBtn = Object.assign(document.createElement('button'), { className: 'big buy', textContent: noAccount ? t('pickAccount') : t('buy'), disabled: noAccount });
buyBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'gjn' }, listing);
const freeBtn = Object.assign(document.createElement('button'), { className: 'big free', textContent: t('freeBuy'), disabled: noAccount });
freeBtn.onclick = () => trade('/trade.gaijin.net/api/buy', { itemdefId: listing.itemdefId, quantity: 1, payMethod: 'free' }, listing);
buyCol.append(buyBtn, freeBtn, html('totals', t('buyPrice', { price: WtoUi.gjn(listing.gjnCostCents) })));
}
function html(className, markup) {
const el = document.createElement('div');
el.className = className;
el.innerHTML = markup;
return el;
}
function closeDetail() { $('modal').hidden = true; }
async function trade(url, body, listing) {
const result = await WtoUi.postJson(url, { userId: state.currentUserId, ...body });
WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok);
await loadState(state.currentUserId);
const fresh = state.listings.find((l) => l.itemdefId === listing.itemdefId);
if (fresh && !$('modal').hidden) openDetail(fresh);
}
$('modal').onclick = (event) => { if (event.target === $('modal')) closeDetail(); };
$('accountSelect').onchange = (event) => { WtoUi.saveAccount(event.target.value); loadState(event.target.value); };
for (const id of ['countryFilter', 'classFilter', 'sortSelect', 'heldOnly']) $(id).onchange = renderGrid;
$('searchInput').oninput = renderGrid;
Promise.all([WtoUi.loadLabels(), WtoUi.loadImageSources()]).then(() => {
applyStaticTexts();
return loadState(WtoUi.savedAccount());
});