feat(store): add store and marketplace item views 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.
This commit is contained in:
N0VAN0M4LY committed 2026-11-26 07:12:38 +08:00
1 parent a73635407d
commit 98812fa9c2
39 files changed
+1309 -400

No files matched your search

+146 -99
View File
@@ -1,41 +1,55 @@
// Local marketplace page, shown in the game's built-in browser.
// The game opens it as <marketplaceURL>?a=<app id>[&viewitem&n=<market_hash_name>] (inventoryClient.nut).
// 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: {
title: 'WTOffline 本地交易所', hint: '买到的兑换券直接进游戏库存(机库 → 道具 → 库存)', toStore: '前往商店',
eagles: '金鹰', lions: '银狮',
catAll: '全部', catVehicle: '载具券', catSkin: '涂装券', catAttachable: '挂件券', catDecal: '贴花券', catUnlock: '头像与解锁券',
search: '搜索名称或编号', allCountries: '全部国家', allClasses: '全部兵种', rank: '{rank} 级',
held: '库存 ×{n}', activated: '已拥有', buy: '购买', freeBuy: '老福爷付过了', pickAccount: '请先选择账号', empty: '没有符合条件的兑换券',
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: {
title: 'WTOffline Marketplace', hint: 'Coupons go straight to your inventory (Items → Inventory in the hangar)', toStore: 'Go to Store',
eagles: 'Golden Eagles', lions: 'Silver Lions',
catAll: 'All', catVehicle: 'Vehicles', catSkin: 'Camouflages', catAttachable: 'Decorations', catDecal: 'Decals', catUnlock: 'Icons and unlocks',
search: 'Search name or id', allCountries: 'All nations', allClasses: 'All types', rank: 'Rank {rank}',
held: 'In inventory ×{n}', activated: 'Owned', buy: 'Buy', freeBuy: '老福爷付过了', pickAccount: 'Pick an account first', empty: 'Nothing matches the filters',
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.',
},
};
// Vehicle class of a listing -> the game's own type name (lang/menu.csv).
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 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, silverLions: 0 }, listings: [] };
let activeCat = 'all';
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');
$('searchInput').value = wantedItem;
$('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));
@@ -43,16 +57,17 @@ function applyStaticTexts() {
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('');
}
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);
$('silverVal').textContent = WtoUi.num(state.balance.silverLions);
renderCountries();
renderGrid();
if (wantedItem && !openedWanted) {
openedWanted = true;
const wanted = state.listings.find((l) => l.marketHashName === wantedItem);
if (wanted) openDetail(wanted);
}
}
function renderCountries() {
@@ -60,98 +75,130 @@ function renderCountries() {
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));
}
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 country = $('countryFilter').value;
const unitClass = $('classFilter').value;
const query = $('searchInput').value.trim().toLowerCase();
if (activeCat !== 'all' && listing.category !== activeCat) return false;
if (country && listing.country !== country) return false;
if (unitClass && listing.unitClass !== unitClass) return false;
return !query || [listing.title.zh, listing.title.en, listing.marketHashName, String(listing.itemdefId)].some((s) => s.toLowerCase().includes(query));
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 = state.listings.filter(matches);
if (listings.length === 0) grid.innerHTML = '<div class="empty">' + WtoUi.escapeHtml(t('empty')) + '</div>';
for (const listing of listings) grid.appendChild(listingCard(listing));
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 listingCard(listing) {
const card = document.createElement('div');
card.className = 'card' + (wantedItem && listing.marketHashName === wantedItem ? ' highlight' : '');
const head = document.createElement('div');
head.className = 'card-head';
if (listing.category === 'vehicle') head.appendChild(WtoUi.iconImg('vehicle', listing.targetKey, 'vehicle-icon'));
const titles = document.createElement('div');
titles.innerHTML = '<h3 class="card-title quality"></h3><div class="card-sub"></div>';
const title = titles.querySelector('.card-title');
title.textContent = WtoUi.text(listing.title);
if (listing.nameColor) title.style.setProperty('--quality', '#' + listing.nameColor);
const sub = titles.querySelector('.card-sub');
if (listing.country) sub.appendChild(WtoUi.iconImg('flag', listing.country, 'flag'));
const parts = [];
if (listing.country) parts.push(WtoUi.label(listing.country));
if (listing.rank) parts.push(t('rank', { rank: ROMAN[listing.rank] || listing.rank }));
if (!parts.length) parts.push(WtoUi.text(listing.subtitle));
sub.appendChild(document.createTextNode(parts.join(' · ')));
head.appendChild(titles);
card.appendChild(head);
const badges = document.createElement('div');
badges.className = 'badges';
const badge = (text, owned) => badges.appendChild(Object.assign(document.createElement('span'), { className: 'badge' + (owned ? ' owned' : ''), textContent: text }));
badge('#' + listing.itemdefId, false);
if (listing.couponCount > 0) badge(t('held', { n: listing.couponCount }), true);
if (listing.alreadyActivated) badge(t('activated'), true);
card.appendChild(badges);
const foot = document.createElement('div');
foot.className = 'card-foot';
foot.innerHTML = '<span class="price"></span><div class="buy-actions"></div>';
foot.querySelector('.price').textContent = WtoUi.gjn(listing.gjnCostCents) + ' GJN';
const actions = foot.querySelector('.buy-actions');
if (!state.currentUserId) {
actions.appendChild(Object.assign(document.createElement('button'), { className: 'buy', textContent: t('pickAccount'), disabled: true }));
} else {
const gjnBtn = Object.assign(document.createElement('button'), { className: 'buy', textContent: t('buy') });
gjnBtn.onclick = () => buy(listing.itemdefId, 'gjn');
const freeBtn = Object.assign(document.createElement('button'), { className: 'buy free', textContent: t('freeBuy') });
freeBtn.onclick = () => buy(listing.itemdefId, 'free');
actions.append(gjnBtn, freeBtn);
}
card.appendChild(foot);
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;
}
async function buy(itemdefId, payMethod) {
const result = await WtoUi.postJson('/trade.gaijin.net/api/buy', { userId: state.currentUserId, itemdefId, quantity: 1, payMethod });
WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok);
if (result.ok) await loadState(state.currentUserId);
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;
}
$('tabs').onclick = (event) => {
const tab = event.target.closest('.tab');
if (!tab) return;
for (const other of document.querySelectorAll('.tab')) other.classList.toggle('active', other === tab);
activeCat = tab.dataset.cat;
renderGrid();
};
$('accountSelect').onchange = (event) => {
WtoUi.saveAccount(event.target.value);
loadState(event.target.value);
};
$('countryFilter').onchange = renderGrid;
$('classFilter').onchange = renderGrid;
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;
WtoUi.loadLabels().then(() => {
Promise.all([WtoUi.loadLabels(), WtoUi.loadImageSources()]).then(() => {
applyStaticTexts();
return loadState(WtoUi.savedAccount());
});