Add a shopping cart and refresh the local storefront

Save carts per account and settle each order in one profile update. Add featured packs, a screenshot and video gallery, and premium artwork from the game files.
This commit is contained in:
N0VAN0M4LY committed 2026-11-26 19:07:48 +08:00
1 parent 9a495e6a0f
commit 81e3add520
13 files changed
+1392 -356

No files matched your search

@@ -10,10 +10,12 @@
*/
import { setParam, type BlkBlock } from '@wto/blk';
import type { Account } from '../accounts/account-store.ts';
import { clearStoreCart } from './profile-store-cart.ts';
import { serverTimeNow } from './server-time.ts';
export function clientProfile(saved: BlkBlock, account: Account): BlkBlock {
const profile = structuredClone(saved);
clearStoreCart(profile);
setParam(profile, 'charDrivenNick', { type: 'string', value: account.nick });
setParam(profile, 'serverTime', { type: 'int64', value: serverTimeNow() });
return profile;
@@ -0,0 +1,26 @@
/** The local web store cart is saved with the profile so checkout can clear it with the purchase. */
import { ensureBlock, findBlock, type BlkBlock } from '@wto/blk';
const STORE_CART = 'wtoStoreCart';
export function storeCartIds(profile: BlkBlock): readonly string[] {
return findBlock(profile, STORE_CART)?.params.flatMap((param) =>
param.name === 'productId' && param.value.type === 'string' ? [param.value.value] : [],
) ?? [];
}
export function setStoreCart(profile: BlkBlock, productIds: readonly string[]): void {
if (productIds.length === 0) {
clearStoreCart(profile);
return;
}
ensureBlock(profile, STORE_CART).params = productIds.map((id) => ({
name: 'productId',
value: { type: 'string', value: id },
}));
}
export function clearStoreCart(profile: BlkBlock): void {
const index = profile.blocks.findIndex((block) => block.name === STORE_CART);
if (index !== -1) profile.blocks.splice(index, 1);
}
@@ -65,6 +65,37 @@ export function buyFreeStoreProduct(profile: BlkBlock, product: StoreProduct, no
return { ok: true };
}
export type StoreCheckoutOutcome =
| { readonly ok: true; readonly costCents: number }
| { readonly ok: false; readonly reason: 'NOT_FOUND' | 'ALREADY_BOUGHT'; readonly productId: string }
| { readonly ok: false; readonly reason: 'NOT_ENOUGH_GJN'; readonly costCents: number };
/** Stage every grant before committing the rewards and charge to the player's profile. */
export function buyStoreCart(
profile: BlkBlock,
products: readonly StoreProduct[],
payMethod: 'gjn' | 'free',
nowFiletime: bigint,
): StoreCheckoutOutcome {
const draft = structuredClone(profile);
let costCents = 0;
for (const product of products) {
const price = product.gjnCostCents;
if (price === undefined) return { ok: false, reason: 'NOT_FOUND', productId: product.id };
if (!canBuyGjnProduct(draft, product, nowFiletime)) return { ok: false, reason: 'ALREADY_BOUGHT', productId: product.id };
grantProductRewards(draft, product, nowFiletime);
costCents += price;
}
if (payMethod === 'gjn') {
if (balanceOf(draft).gjnCents < costCents) return { ok: false, reason: 'NOT_ENOUGH_GJN', costCents };
payGjnCents(draft, costCents);
}
profile.params = draft.params;
profile.blocks = draft.blocks;
return { ok: true, costCents: payMethod === 'gjn' ? costCents : 0 };
}
function grantProductRewards(profile: BlkBlock, product: StoreProduct, nowFiletime: bigint): void {
const before = balanceOf(profile);
const newVehicles: string[] = [];
@@ -14,7 +14,9 @@ import { StoreWebApi } from './store-web-api.ts';
import { YUPLAY_STORE_PATHS, YuplayStoreApi } from './yuplay-store-api.ts';
const PAGE_PREFIX = '/store';
const STORE_PAGE = createStaticWebSite(new URL('./web/', import.meta.url));
const STORE_PAGE = createStaticWebSite(new URL('./web/', import.meta.url), [
'index.html', 'styles.css', 'product.css', 'checkout.css', 'app.js', 'products.js', 'gallery.js', 'checkout.js',
]);
const STORE_API_HOSTS = new Set(['api.gaijinent.com', 'store.gaijin.net']);
export class StoreService implements Service {
@@ -3,6 +3,8 @@
* implementation notes):
* GET /store/api/state?userId= balances, products and redeem code help for one account
* POST /store/api/buy { userId, productId }
* POST /store/api/cart { userId, productId, action }
* POST /store/api/checkout { userId, productIds, payMethod }
* POST /store/api/redeem { userId, code }
* Texts for the player come in both page languages ({ en, zh }); the page picks one.
*/
@@ -11,16 +13,20 @@ import type { LocalizedText } from '../game-data/datasets/unit-names.ts';
import type { PlayerProfiles } from '../profile/player-profiles.ts';
import { balanceOf } from '../profile/profile-currency.ts';
import { remainingPremiumDays } from '../profile/profile-entitlements.ts';
import { clearStoreCart, setStoreCart, storeCartIds } from '../profile/profile-store-cart.ts';
import { serverTimeNow } from '../profile/server-time.ts';
import type { ServiceRequest, ServiceResponse } from '../server/exchange.ts';
import { jsonResponse, parseJsonBody, requireWebActionAccount, selectWebViewAccount } from '../web-ui/web-helpers.ts';
import { describeRedeemCodes, gjnText, redeemStoreCode, type RedeemOutcome } from './redeem-codes.ts';
import type { RedeemTuning } from './redeem-tuning.ts';
import type { StoreCatalogue, StoreProduct } from './store-catalogue.ts';
import { buyFreeStoreProduct, buyGjnProduct, canBuyGjnProduct, type GjnPurchaseOutcome } from './store-purchase.ts';
import { buyFreeStoreProduct, buyGjnProduct, buyStoreCart, canBuyGjnProduct, type GjnPurchaseOutcome, type StoreCheckoutOutcome } from './store-purchase.ts';
const NO_ACCOUNT: LocalizedText = { zh: '没有找到这个账号,请先在右上角选择账号。', en: 'Account not found. Pick an account at the top right first.' };
const NO_PRODUCT: LocalizedText = { zh: '没有找到这个商品。', en: 'Product not found.' };
const CART_CHANGED: LocalizedText = { zh: '购物车内容已变化,请核对后再结算。', en: 'Your cart has changed. Review it before checking out.' };
export class StoreWebApi {
readonly #accounts: AccountStore;
readonly #profiles: PlayerProfiles;
@@ -38,6 +44,8 @@ export class StoreWebApi {
handle(apiPath: string, request: ServiceRequest): ServiceResponse | undefined {
if (apiPath === '/api/state' && request.method === 'GET') return this.#state(request);
if (apiPath === '/api/buy' && request.method === 'POST') return this.#buy(request);
if (apiPath === '/api/cart' && request.method === 'POST') return this.#cart(request);
if (apiPath === '/api/checkout' && request.method === 'POST') return this.#checkout(request);
if (apiPath === '/api/redeem' && request.method === 'POST') return this.#redeem(request);
return undefined;
}
@@ -55,6 +63,7 @@ export class StoreWebApi {
balance: profile ? balanceOf(profile) : { silverLions: 0, goldenEagles: 0, gjnCents: 0 },
premiumDays: profile ? remainingPremiumDays(profile, now) : 0,
products,
cartProductIds: profile ? storeCartIds(profile) : [],
redeemHelp: describeRedeemCodes(this.#redeemCodes),
}, `store web state (${account?.userId ?? 'no account'})`);
}
@@ -65,7 +74,7 @@ export class StoreWebApi {
const product = typeof body.productId === 'string' ? this.#catalogue.byId(body.productId) : undefined;
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store web buy: unknown account');
if (!product || product.gjnCostCents === undefined) {
return jsonResponse({ ok: false, message: { zh: '没有找到这个商品。', en: 'Product not found.' } }, 'store web buy: unknown product');
return jsonResponse({ ok: false, message: NO_PRODUCT }, 'store web buy: unknown product');
}
if (body.payMethod !== undefined && body.payMethod !== 'gjn' && body.payMethod !== 'free') {
return jsonResponse({ ok: false, message: { zh: '不支持这种支付方式。', en: 'Unsupported payment method.' } }, 'store web buy: bad payMethod');
@@ -73,13 +82,85 @@ export class StoreWebApi {
const isFree = body.payMethod === 'free';
let outcome: GjnPurchaseOutcome = { ok: false, reason: 'NOT_FOUND' };
let cartProductIds: readonly string[] = [];
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
outcome = isFree ? buyFreeStoreProduct(saved, product, now) : buyGjnProduct(saved, product, now);
return outcome.ok;
cartProductIds = storeCartIds(saved);
if (!outcome.ok) return false;
if (cartProductIds.includes(product.id)) {
cartProductIds = cartProductIds.filter((id) => id !== product.id);
setStoreCart(saved, cartProductIds);
}
return true;
});
const modeTag = isFree ? 'free' : 'gjn';
return jsonResponse({ ok: outcome.ok, message: purchaseMessage(outcome, product, isFree) }, `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`);
return jsonResponse({ ok: outcome.ok, cartProductIds, message: purchaseMessage(outcome, product, isFree) }, `store web buy ${product.id} (${modeTag}): ${outcome.ok ? 'OK' : outcome.reason}`);
}
#cart(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store cart: unknown account');
const { action, productId } = body;
if ((action !== 'add' && action !== 'remove') || typeof productId !== 'string' || !productId) {
return jsonResponse({ ok: false }, 'store cart: invalid action');
}
const product = this.#catalogue.byId(productId);
let cartProductIds: readonly string[] = [];
let message: LocalizedText | undefined;
const now = serverTimeNow();
this.#profiles.updateWhen(account.userId, (saved) => {
const previous = storeCartIds(saved);
cartProductIds = previous;
if (action === 'add') {
if (!product || product.gjnCostCents === undefined) {
message = NO_PRODUCT;
return false;
}
if (!canBuyGjnProduct(saved, product, now)) {
message = alreadyBoughtMessage(product);
return false;
}
if (previous.includes(productId)) return false;
cartProductIds = [...previous, productId];
} else {
if (!previous.includes(productId)) return false;
cartProductIds = previous.filter((id) => id !== productId);
}
setStoreCart(saved, cartProductIds);
return true;
});
return jsonResponse({ ok: !message, cartProductIds, message }, `store cart ${action} ${productId}`);
}
#checkout(request: ServiceRequest): ServiceResponse {
const body = parseJsonBody(request.body);
const account = requireWebActionAccount(this.#accounts, body.userId);
if (!account) return jsonResponse({ ok: false, message: NO_ACCOUNT }, 'store checkout: unknown account');
const { productIds, payMethod } = body;
if (!Array.isArray(productIds) || productIds.length === 0 || (payMethod !== 'gjn' && payMethod !== 'free')) {
return jsonResponse({ ok: false, message: CART_CHANGED }, 'store checkout: invalid order');
}
const now = serverTimeNow();
let cartProductIds: readonly string[] = [];
let message = CART_CHANGED;
const saved = this.#profiles.updateWhen(account.userId, (profile) => {
cartProductIds = storeCartIds(profile);
if (cartProductIds.length !== productIds.length || cartProductIds.some((id, i) => id !== productIds[i])) return false;
const products = cartProductIds.map((id) => this.#catalogue.byId(id));
if (!products.every((product): product is StoreProduct => product !== undefined)) {
message = NO_PRODUCT;
return false;
}
const outcome = buyStoreCart(profile, products, payMethod, now);
message = checkoutMessage(outcome, products, payMethod);
if (!outcome.ok) return false;
clearStoreCart(profile);
cartProductIds = [];
return true;
});
return jsonResponse({ ok: !!saved, cartProductIds, message }, `store checkout (${payMethod}): ${saved ? 'OK' : 'refused'}`);
}
#redeem(request: ServiceRequest): ServiceResponse {
@@ -113,10 +194,39 @@ function purchaseMessage(outcome: GjnPurchaseOutcome, product: StoreProduct, isF
if (outcome.reason === 'NOT_ENOUGH_GJN') {
return { zh: `GJN 不够:需要 ${cost} GJN。可直接点「老福爷付过了」,或在"兑换码"页用 GJN 充值码补充。`, en: `Not enough GJN: ${cost} GJN needed. Use "老福爷付过了" or a GJN code on the Redeem tab.` };
}
if (outcome.reason === 'ALREADY_BOUGHT') return { zh: '你已经拥有该礼包内的载具。', en: 'You already own the vehicle(s) in this pack.' };
if (outcome.reason === 'ALREADY_BOUGHT') return alreadyBoughtMessage(product);
return { zh: '这个商品现在买不了。', en: 'This product cannot be bought right now.' };
}
function alreadyBoughtMessage(product: StoreProduct): LocalizedText {
return {
zh: `你已经拥有「${product.title.zh}」中的载具。`,
en: `You already own the vehicles in "${product.title.en}".`,
};
}
function checkoutMessage(
outcome: StoreCheckoutOutcome,
products: readonly StoreProduct[],
payMethod: 'gjn' | 'free',
): LocalizedText {
if (outcome.ok) {
const count = products.length;
const cost = gjnText(outcome.costCents);
return payMethod === 'free'
? { zh: `老福爷付过了!已领取 ${count} 件商品。关闭商城窗口后机库会自动刷新。`,
en: `Paid by 老福爷! Claimed ${count} items. Close the store to refresh the hangar.` }
: { zh: `已购买 ${count} 件商品,花费 ${cost} GJN。关闭商城窗口后机库会自动刷新。`,
en: `Bought ${count} items for ${cost} GJN. Close the store to refresh the hangar.` };
}
if (outcome.reason === 'NOT_ENOUGH_GJN') {
const cost = gjnText(outcome.costCents);
return { zh: `购物车共需 ${cost} GJN,当前余额不足。`, en: `Your cart costs ${cost} GJN. Your balance is too low.` };
}
const product = products.find((item) => item.id === outcome.productId);
return outcome.reason === 'ALREADY_BOUGHT' && product ? alreadyBoughtMessage(product) : NO_PRODUCT;
}
function webProduct(product: StoreProduct, owned: boolean): Record<string, unknown> {
const vehicles = product.vehicles;
const firstVehicle = vehicles?.[0];
@@ -138,6 +248,7 @@ function webProduct(product: StoreProduct, owned: boolean): Record<string, unkno
ranks,
vehicles: vehicles.map((vehicle, index) => ({
unitName: vehicle.name,
country: vehicle.country,
rank: vehicle.rank,
title: product.vehicleTitles?.[index] ?? { en: vehicle.name, zh: vehicle.name },
})),
+167 -230
View File
@@ -1,292 +1,229 @@
// Local store page (implementation notes; layout after the official Gaijin.Net store,
// implementation notes), shown in the game's built-in browser.
// The game opens /store?item=<bundle GUID> for a gift vehicle's own pack (item_info.php `url`,
// implementation notes); the page then shows that pack's detail view.
// The in-game browser can open the storefront or deep-link to a pack by its GUID.
'use strict';
const T = {
zh: {
store: '商店', toMarket: '交易所', eagles: '金鹰', lions: '银狮', premium: '高级账户', premiumOff: '未开通', premiumLeft: '剩余 {days} 天',
tabPacks: '高级载具', tabEagles: '金鹰', tabPremium: '高级帐户', tabRedeem: '优惠码',
search: '搜索礼包或载具', allCountries: '所有国家', allRanks: '所有等级', rank: '{rank} 级', sortBest: '最畅销', sortPriceAsc: '价格从低到高', sortPriceDesc: '价格从高到低',
vehicle: '{name}', containsEagles: '{n} 金鹰', containsSilver: '{n} 银狮', containsPremium: '{days} 天高级账户',
buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先在右上角选择账号', redeem: '兑换', codePlaceholder: '输入兑换码',
empty: '没有符合条件的商品', includes: '本特惠包包含', back: '‹ 返回目录', bonusTitle: 'Premium bonuses', bonusText: '高级载具获得的银狮与研发点有加成,并可直接使用。',
footer: 'WTOffline 本地商店 · 买完关闭本窗口,机库会自动刷新', badgeOwned: '已拥有', badgeHot: '人气商品',
cover: '封面', screenshot: '截图 {index}', video: '演示视频', videoNumber: '演示视频 {index}', videoUnavailable: '暂时无法播放官方视频。',
store: '商城', toMarket: '交易所', account: '本地账号', eagles: '金鹰', lions: '银狮', premium: '高级账户',
premiumOff: '未开通', premiumLeft: '剩余 {days} 天',
tabPacks: '高级载具', tabEagles: '金鹰', tabPremium: '高级账户', tabRedeem: '兑换码',
search: '搜索礼包或载具', allCountries: '所有国家', allRanks: '所有等级', rank: '{rank} 级',
sort: '商品排序', sortBest: '默认排序', sortPriceAsc: '价格从低到高', sortPriceDesc: '价格从高到低',
containsEagles: '{n} 金鹰', containsSilver: '{n} 银狮', containsPremium: '{days} 天高级账户',
buy: '购买', freeBuy: '老福爷付过了', owned: '已拥有', pickAccount: '请先选择账号',
redeem: '兑换', codePlaceholder: '输入兑换码', empty: '没有符合条件的商品',
featured: '推荐礼包', viewPack: '查看礼包', related: '更多推荐', packPrice: '礼包价格',
includes: '礼包内容', back: '返回目录', bonusTitle: '高级载具权益',
bonusText: '驾驶高级载具可在战斗中获得额外的研发点和银狮。',
footer: '购买后关闭商城窗口,机库会自动刷新。',
gallery: '礼包媒体', cover: '封面', screenshot: '截图 {index}', screenshotPending: '官方截图尚未加载', previousMedia: '上一项', nextMedia: '下一项',
video: '演示视频', videoNumber: '演示视频 {index}', playVideo: '播放演示',
videoLoading: '正在加载演示视频…', videoUnavailable: '暂时无法播放官方视频,可以继续浏览其他素材。',
cart: '购物车', addCart: '加入购物车', inCart: '已在购物车', confirmPurchase: '确认购买',
cartEmpty: '购物车里还没有商品。', remove: '移除', removeItem: '移除 {name}', unavailable: '商品已下架',
total: '合计', balance: 'GJN 余额', payGjn: '用 GJN 结算', close: '关闭', keepShopping: '继续逛商城',
cartBlocked: '移除已拥有或已下架的商品后即可结算。', lowBalance: 'GJN 余额不足。',
buyFailed: '暂时无法确认结果,商城会重新读取账号状态。', loadFailed: '商城加载失败,请重新打开商城。',
},
en: {
store: 'Store', toMarket: 'Market', eagles: 'Golden Eagles', lions: 'Silver Lions', premium: 'Premium', premiumOff: 'inactive', premiumLeft: '{days} days left',
tabPacks: 'Premium vehicles', tabEagles: 'Golden Eagles', tabPremium: 'Premium account', tabRedeem: 'Promo code',
search: 'Search packs or vehicles', allCountries: 'All nations', allRanks: 'All ranks', rank: 'Rank {rank}', sortBest: 'Best-selling', sortPriceAsc: 'Price: low to high', sortPriceDesc: 'Price: high to low',
vehicle: '{name}', containsEagles: '{n} Golden Eagles', containsSilver: '{n} Silver Lions', containsPremium: '{days} days of Premium Account',
buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account at the top right', redeem: 'Redeem', codePlaceholder: 'Enter a code',
empty: 'Nothing matches the filters', includes: 'This pack includes', back: '‹ Back to catalog', bonusTitle: 'Premium bonuses', bonusText: 'Premium vehicles earn more Silver Lions and research points and are ready to use.',
footer: 'WTOffline local store · close this window after buying to refresh the hangar', badgeOwned: 'Owned', badgeHot: 'Best seller',
cover: 'Cover', screenshot: 'Screenshot {index}', video: 'Demo video', videoNumber: 'Demo video {index}', videoUnavailable: 'The official video is unavailable.',
store: 'Store', toMarket: 'Market', account: 'Local account', eagles: 'Golden Eagles', lions: 'Silver Lions', premium: 'Premium',
premiumOff: 'Inactive', premiumLeft: '{days} days left',
tabPacks: 'Premium vehicles', tabEagles: 'Golden Eagles', tabPremium: 'Premium account', tabRedeem: 'Redeem code',
search: 'Search packs or vehicles', allCountries: 'All nations', allRanks: 'All ranks', rank: 'Rank {rank}',
sort: 'Sort products', sortBest: 'Default order', sortPriceAsc: 'Price: low to high', sortPriceDesc: 'Price: high to low',
containsEagles: '{n} Golden Eagles', containsSilver: '{n} Silver Lions', containsPremium: '{days} days of Premium Account',
buy: 'Buy', freeBuy: '老福爷付过了', owned: 'Owned', pickAccount: 'Pick an account first',
redeem: 'Redeem', codePlaceholder: 'Enter a code', empty: 'Nothing matches the filters',
featured: 'Featured packs', viewPack: 'View pack', related: 'Explore other packs', packPrice: 'Pack price',
includes: 'Pack contents', back: 'Back to catalog', bonusTitle: 'Premium bonuses',
bonusText: 'Premium vehicles earn extra research points and Silver Lions in battle.',
footer: 'Close the store window after buying to refresh the hangar.',
gallery: 'Pack media', cover: 'Cover', screenshot: 'Screenshot {index}', screenshotPending: 'Official screenshot has not loaded', previousMedia: 'Previous item', nextMedia: 'Next item',
video: 'Demo video', videoNumber: 'Demo video {index}', playVideo: 'Play demo',
videoLoading: 'Loading demo video…', videoUnavailable: 'The official video is unavailable. You can still browse the other media.',
cart: 'Cart', addCart: 'Add to cart', inCart: 'In cart', confirmPurchase: 'Confirm purchase',
cartEmpty: 'Your cart is empty.', remove: 'Remove', removeItem: 'Remove {name}', unavailable: 'No longer available',
total: 'Total', balance: 'GJN balance', payGjn: 'Pay with GJN', close: 'Close', keepShopping: 'Continue shopping',
cartBlocked: 'Remove owned or unavailable products to check out.', lowBalance: 'Your GJN balance is too low.',
buyFailed: 'The result could not be confirmed. The store will reload your account.', loadFailed: 'The store could not load. Reopen the store to retry.',
},
};
const TAB_LABEL = { 'vehicle-pack': 'tabPacks', eagles: 'tabEagles', 'premium-gjn': 'tabPremium' };
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 wantedGuid = (WtoUi.query.get('item') || '').toUpperCase();
let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0, goldenEagles: 0, silverLions: 0 }, premiumDays: 0, products: [], redeemHelp: [] };
let initialGuid = (WtoUi.query.get('item') || '').toUpperCase();
let state = { accounts: [], activeUserId: '', balance: { gjnCents: 0 }, products: [], cartProductIds: [], redeemHelp: [] };
let currentTab = 'vehicle-pack';
let detailId = '';
let catalogScroll = 0;
let loadVersion = 0;
let loading = true;
const checkout = createStoreCheckout(loadState);
function applyStaticTexts() {
for (const el of document.querySelectorAll('[data-t]')) el.textContent = t(el.dataset.t);
for (const el of document.querySelectorAll('[data-label]')) el.setAttribute('aria-label', t(el.dataset.label));
$('searchInput').placeholder = t('search');
$('codeInput').placeholder = t('codePlaceholder');
$('marketLink').href = WtoUi.pageLink('/trade.gaijin.net/');
}
function setLoading(value) {
loading = value;
$('accountSelect').disabled = value || !state.accounts.length;
$('redeemBtn').disabled = value || !state.activeUserId;
checkout.setAccountLoading(value);
}
async function loadState(userId) {
state = await WtoUi.getJson('/store/api/state' + (userId ? '?userId=' + encodeURIComponent(userId) : ''));
if (userId && !state.activeUserId) { WtoUi.clearSavedAccount(); return loadState(''); }
WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.activeUserId);
$('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents);
$('goldVal').textContent = WtoUi.num(state.balance.goldenEagles);
$('silverVal').textContent = WtoUi.num(state.balance.silverLions);
$('premVal').textContent = state.premiumDays > 0 ? t('premiumLeft', { days: state.premiumDays }) : t('premiumOff');
if (wantedGuid && !detailId) {
const wanted = state.products.find((p) => (p.guid || '').toUpperCase() === wantedGuid);
if (wanted) { detailId = wanted.id; currentTab = wanted.kind; }
const version = ++loadVersion;
setLoading(true);
try {
const next = await WtoUi.getJson('/store/api/state' + (userId ? '?userId=' + encodeURIComponent(userId) : ''));
if (version !== loadVersion) return;
if (!Array.isArray(next?.accounts) || !Array.isArray(next.products)) throw new Error('Invalid store state');
if (userId && !next.activeUserId) {
WtoUi.clearSavedAccount();
return await loadState('');
}
state = next;
WtoUi.fillAccountSelect($('accountSelect'), state.accounts, state.activeUserId);
$('gjnVal').textContent = WtoUi.gjn(state.balance.gjnCents);
$('goldVal').textContent = WtoUi.num(state.balance.goldenEagles);
$('silverVal').textContent = WtoUi.num(state.balance.silverLions);
$('premVal').textContent = state.premiumDays > 0 ? t('premiumLeft', { days: state.premiumDays }) : t('premiumOff');
if (initialGuid) {
const wanted = state.products.find((p) => (p.guid || '').toUpperCase() === initialGuid);
if (wanted) { detailId = wanted.id; currentTab = wanted.kind; }
initialGuid = '';
}
checkout.setState(state);
renderFilters();
render();
} catch (error) {
if (version !== loadVersion) return;
$('accountSelect').value = state.activeUserId;
WtoUi.showNotice($('notice'), t('loadFailed'), false);
} finally {
if (version === loadVersion) setLoading(false);
}
renderFilters();
render();
}
function fillSelect(select, firstText, values, textOf) {
const previous = select.value;
select.innerHTML = '';
select.appendChild(new Option(firstText, ''));
select.replaceChildren(new Option(firstText, ''));
for (const value of values) select.appendChild(new Option(textOf(value), String(value), false, String(value) === previous));
}
function renderFilters() {
const packs = state.products.filter((p) => p.kind === 'vehicle-pack');
fillSelect($('countryFilter'), t('allCountries'), [...new Set(packs.map((p) => p.country).filter(Boolean))], WtoUi.label);
fillSelect($('rankFilter'), t('allRanks'), [...new Set(packs.flatMap((p) => p.ranks || []))].sort((a, b) => a - b), (r) => t('rank', { rank: ROMAN[r] || r }));
const countries = packs.flatMap((p) => p.vehicles.map((vehicle) => vehicle.country)).filter(Boolean);
const ranks = [...new Set(packs.flatMap((p) => p.ranks || []))].sort((a, b) => a - b);
fillSelect($('countryFilter'), t('allCountries'), [...new Set(countries)], WtoUi.label);
fillSelect($('rankFilter'), t('allRanks'), ranks, rankLabel);
}
function matches(product) {
if (product.kind !== currentTab) return false;
if (currentTab !== 'vehicle-pack') return true;
function matchesPack(product) {
const query = $('searchInput').value.trim().toLowerCase();
if ($('countryFilter').value && product.country !== $('countryFilter').value) return false;
if ($('rankFilter').value && !(product.ranks || []).map(String).includes($('rankFilter').value)) return false;
const country = $('countryFilter').value;
const rank = $('rankFilter').value;
if (country && !product.vehicles.some((vehicle) => vehicle.country === country)) return false;
if (rank && !product.ranks.map(String).includes(rank)) return false;
if (!query) return true;
const terms = [product.title.zh, product.title.en];
for (const v of product.vehicles || []) terms.push(v.unitName, v.title && v.title.zh, v.title && v.title.en);
return terms.some((s) => (s || '').toLowerCase().includes(query));
for (const vehicle of product.vehicles) terms.push(vehicle.unitName, vehicle.title.zh, vehicle.title.en);
return terms.some((term) => (term || '').toLowerCase().includes(query));
}
function render() {
stopProductVideo($('detail').querySelector('video'));
for (const tab of document.querySelectorAll('.snav-item')) tab.classList.toggle('active', tab.dataset.tab === currentTab);
const product = detailId && state.products.find((p) => p.id === detailId);
$('redeemPanel').hidden = currentTab !== 'redeem';
$('catalog').hidden = currentTab === 'redeem' || !!product;
stopStoreGallery($('detail'));
for (const tab of $('tabs').querySelectorAll('[data-tab]')) tab.setAttribute('aria-pressed', String(tab.dataset.tab === currentTab));
const product = state.products.find((item) => item.id === detailId);
const redeeming = currentTab === 'redeem';
$('catalog').hidden = redeeming || !!product;
$('detail').hidden = !product;
$('packFilters').hidden = currentTab !== 'vehicle-pack';
if (currentTab === 'redeem') return renderRedeemHelp();
if (product) return renderDetail(product);
const items = state.products.filter(matches);
const mode = $('sortSelect').value;
if (mode === 'priceAsc') items.sort((a, b) => a.gjnCostCents - b.gjnCostCents);
if (mode === 'priceDesc') items.sort((a, b) => b.gjnCostCents - a.gjnCostCents);
$('redeemPanel').hidden = !redeeming;
if (!product) $('detail').replaceChildren();
if (redeeming) return renderRedeemHelp();
if (product) return renderPackDetail($('detail'), product, checkout, state.products, openProduct, backToCatalog);
renderCatalog();
}
function renderCatalog() {
const isPacks = currentTab === 'vehicle-pack';
$('catalogTitle').textContent = t(TAB_LABEL[currentTab]);
$('packFilters').hidden = !isPacks;
const sort = $('sortSelect').value;
const filtered = $('countryFilter').value || $('rankFilter').value || $('searchInput').value.trim();
renderFeatured($('featured'), isPacks && !filtered && sort === 'best' ? state.products : [], openProduct);
const items = state.products.filter((p) => p.kind === currentTab && (!isPacks || matchesPack(p)));
if (isPacks && sort === 'priceAsc') items.sort((a, b) => a.gjnCostCents - b.gjnCostCents);
if (isPacks && sort === 'priceDesc') items.sort((a, b) => b.gjnCostCents - a.gjnCostCents);
const grid = $('grid');
grid.innerHTML = '';
if (!items.length) grid.innerHTML = '<div class="empty">' + WtoUi.escapeHtml(t('empty')) + '</div>';
for (const item of items) grid.appendChild(productCard(item));
grid.replaceChildren(...items.map((item) => productCard(item, checkout, openProduct)));
if (!items.length) grid.append(makeElement('p', 'empty', t('empty')));
}
function productArtwork(product) {
const group = product.artworkGroup ? [WtoUi.artworkUrl('group', product.artworkGroup)] : [];
const image = product.unitName ? WtoUi.artworkUrl('vehicle', product.unitName) : WtoUi.artworkUrl('product', product.kind);
return [...group, image];
function openProduct(product) {
if (!detailId) catalogScroll = window.scrollY;
detailId = product.id;
currentTab = product.kind;
render();
window.scrollTo(0, 0);
$('detail').querySelector('h1').focus({ preventScroll: true });
}
function productImage(product) {
const { cover } = WtoUi.storeMedia(product.id);
const urls = product.unitName ? [cover, ...WtoUi.vehicleUrls(product.unitName)] : [cover];
return WtoUi.tieredImg(urls, productArtwork(product), '');
function backToCatalog() {
detailId = '';
render();
window.scrollTo(0, catalogScroll);
$('catalogTitle').focus({ preventScroll: true });
}
function stopProductVideo(video) {
if (!video) return;
video.onerror = null;
video.pause();
video.remove();
video.removeAttribute('src');
video.load();
}
function showPackVideo(media, status, product, urls) {
const player = document.createElement('video');
player.controls = true;
player.playsInline = true;
player.preload = 'metadata';
const sources = urls.filter((url) => player.canPlayType(url.endsWith('.webm') ? 'video/webm' : 'video/mp4'));
let timer;
function next() {
clearTimeout(timer);
if (player.parentNode !== media) return;
const url = sources.shift();
if (!url) {
stopProductVideo(player);
media.replaceChildren(productImage(product));
status.textContent = t('videoUnavailable');
status.hidden = false;
return;
}
player.src = url;
timer = setTimeout(next, 4500);
void player.play().catch(() => {});
}
player.onerror = next;
player.onloadedmetadata = () => clearTimeout(timer);
media.replaceChildren(player);
next();
}
function renderProductMedia(detail, product) {
const media = detail.querySelector('.media');
const status = detail.querySelector('.media-status');
const toolbar = detail.querySelector('.thumbs');
const { screenshots, videos } = WtoUi.storeMedia(product.id);
let selected;
function addChoice(label, show) {
const button = Object.assign(document.createElement('button'), { type: 'button', textContent: label });
button.setAttribute('aria-pressed', 'false');
button.onclick = () => {
stopProductVideo(media.querySelector('video'));
selected?.setAttribute('aria-pressed', 'false');
selected = button;
button.setAttribute('aria-pressed', 'true');
status.hidden = true;
show();
};
toolbar.appendChild(button);
return button;
}
const cover = addChoice(t('cover'), () => media.replaceChildren(productImage(product)));
screenshots.forEach((url, index) => {
addChoice(t('screenshot', { index: index + 1 }), () => media.replaceChildren(WtoUi.tieredImg([url], productArtwork(product), '')));
});
for (const vehicle of product.vehicles || []) {
addChoice(WtoUi.text(vehicle.title), () => media.replaceChildren(WtoUi.vehicleImg(vehicle.unitName, '')));
}
videos.forEach((sources, index) => {
const label = videos.length === 1 ? t('video') : t('videoNumber', { index: index + 1 });
addChoice(label, () => showPackVideo(media, status, product, sources));
});
toolbar.hidden = toolbar.childElementCount <= 1;
cover.click();
}
function contentsOf(product) {
const lines = [];
for (const v of product.vehicles || []) lines.push({ text: WtoUi.text(v.title), vehicle: v });
if (product.premiumDays) lines.push({ text: t('containsPremium', { days: product.premiumDays }) });
if (product.goldIncome) lines.push({ text: t('containsEagles', { n: WtoUi.num(product.goldIncome) }) });
if (product.silverIncome) lines.push({ text: t('containsSilver', { n: WtoUi.num(product.silverIncome) }) });
return lines;
}
function buyButtons(product, mainClass, freeClass) {
const disabled = product.owned || !state.activeUserId;
const main = Object.assign(document.createElement('button'), { className: mainClass, disabled, textContent: product.owned ? t('owned') : (state.activeUserId ? t('buy') : t('pickAccount')) });
main.onclick = (e) => { e.stopPropagation(); buy(product.id, 'gjn'); };
const free = Object.assign(document.createElement('button'), { className: freeClass, disabled, textContent: t('freeBuy') });
free.onclick = (e) => { e.stopPropagation(); buy(product.id, 'free'); };
return [main, free];
}
function productCard(product) {
const card = document.createElement('div');
card.className = 'pw';
card.innerHTML = '<div class="pw-poster"></div><div class="pw-desc"><div class="pw-game">War Thunder</div><div class="pw-title"></div><div class="pw-comment"></div><ul class="pw-contents"></ul></div><div class="pw-price"></div><div class="pw-buy"></div>';
card.querySelector('.pw-poster').appendChild(productImage(product));
if (product.owned) card.querySelector('.pw-poster').appendChild(Object.assign(document.createElement('div'), { className: 'badge owned', textContent: t('badgeOwned') }));
card.querySelector('.pw-title').textContent = WtoUi.text(product.title);
if (product.country) {
const comment = card.querySelector('.pw-comment');
comment.appendChild(WtoUi.iconImg('flag', product.country, ''));
comment.appendChild(document.createTextNode(WtoUi.label(product.country) + ', ' + t('rank', { rank: ROMAN[product.rank] || product.rank })));
}
const list = card.querySelector('.pw-contents');
for (const line of contentsOf(product).slice(1)) list.appendChild(Object.assign(document.createElement('li'), { textContent: line.text }));
card.querySelector('.pw-price').textContent = '$' + WtoUi.gjn(product.gjnCostCents);
card.querySelector('.pw-buy').append(...buyButtons(product, '', ''));
card.onclick = () => { detailId = product.id; render(); window.scrollTo(0, 0); };
return card;
}
function renderDetail(product) {
const detail = $('detail');
detail.innerHTML = '<span class="back"></span><h1></h1><div class="detail-cols"><div class="detail-left"><div class="media"></div><div class="thumbs"></div><p class="media-status" role="status" hidden></p>'
+ '<h2></h2><div class="bonus"><h3></h3><div></div></div></div><div class="detail-right"><div class="buy-panel"><div class="price"></div><div class="btns"></div>'
+ '<div class="includes"><h4></h4><ul></ul></div></div></div></div>';
detail.querySelector('.back').textContent = t('back');
detail.querySelector('.back').onclick = () => { detailId = ''; render(); };
detail.querySelector('h1').textContent = WtoUi.text(product.title);
renderProductMedia(detail, product);
detail.querySelector('.detail-left h2').textContent = product.vehicles ? product.vehicles.map((v) => WtoUi.text(v.title)).join(' / ') : WtoUi.text(product.title);
detail.querySelector('.bonus h3').textContent = t('bonusTitle');
detail.querySelector('.bonus div').textContent = t('bonusText');
detail.querySelector('.bonus').hidden = product.kind !== 'vehicle-pack';
detail.querySelector('.price').textContent = '$' + WtoUi.gjn(product.gjnCostCents) + ' (GJN)';
detail.querySelector('.btns').append(...buyButtons(product, 'btn-main', 'btn-free'));
detail.querySelector('.includes h4').textContent = t('includes');
const list = detail.querySelector('.includes ul');
for (const line of contentsOf(product)) {
const li = document.createElement('li');
if (line.vehicle && product.country) {
li.appendChild(WtoUi.iconImg('flag', product.country, ''));
li.appendChild(Object.assign(document.createElement('span'), { className: 'rank-chip', textContent: ROMAN[line.vehicle.rank] || line.vehicle.rank }));
}
li.appendChild(document.createTextNode(line.text));
list.appendChild(li);
}
function selectTab(tab) {
currentTab = tab;
detailId = '';
render();
window.scrollTo(0, 0);
}
function renderRedeemHelp() {
const list = $('redeemHelp');
list.innerHTML = '';
for (const line of state.redeemHelp) list.appendChild(Object.assign(document.createElement('li'), { textContent: WtoUi.text(line) }));
}
async function buy(productId, payMethod) {
const result = await WtoUi.postJson('/store/api/buy', { userId: state.activeUserId, productId, payMethod });
WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok);
await loadState(state.activeUserId);
$('redeemHelp').replaceChildren(...state.redeemHelp.map((line) => makeElement('li', '', WtoUi.text(line))));
}
async function redeem() {
const result = await WtoUi.postJson('/store/api/redeem', { userId: state.activeUserId, code: $('codeInput').value });
WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok);
if (result.ok) $('codeInput').value = '';
await loadState(state.activeUserId);
const userId = state.activeUserId;
if (!userId || loading) return;
$('redeemBtn').disabled = true;
try {
const result = await WtoUi.postJson('/store/api/redeem', { userId, code: $('codeInput').value });
if ($('accountSelect').value !== userId) return;
WtoUi.showNotice($('notice'), WtoUi.text(result.message), result.ok);
if (result.ok) $('codeInput').value = '';
} catch (error) {
if ($('accountSelect').value !== userId) return;
WtoUi.showNotice($('notice'), t('buyFailed'), false);
}
if ($('accountSelect').value === userId) await loadState(userId);
}
$('accountSelect').onchange = (event) => { WtoUi.saveAccount(event.target.value); loadState(event.target.value); };
$('searchInput').oninput = render;
for (const id of ['countryFilter', 'rankFilter', 'sortSelect']) $(id).onchange = render;
$('accountSelect').onchange = (event) => {
$('notice').className = 'notice';
WtoUi.saveAccount(event.target.value);
void loadState(event.target.value);
};
$('storeHome').onclick = () => selectTab('vehicle-pack');
$('searchInput').oninput = renderCatalog;
for (const id of ['countryFilter', 'rankFilter', 'sortSelect']) $(id).onchange = renderCatalog;
$('redeemBtn').onclick = redeem;
$('tabs').onclick = (event) => {
const tab = event.target.closest('.snav-item');
if (!tab) return;
currentTab = tab.dataset.tab;
detailId = '';
render();
const tab = event.target.closest('[data-tab]');
if (tab) selectTab(tab.dataset.tab);
};
window.addEventListener('pagehide', () => stopStoreGallery($('detail')));
applyStaticTexts();
Promise.all([WtoUi.loadLabels(), WtoUi.loadImageSources(true)]).then(() => loadState(WtoUi.savedAccount()));
render();
Promise.allSettled([WtoUi.loadLabels(), WtoUi.loadImageSources(true)]).then(() => loadState(WtoUi.savedAccount()));
@@ -0,0 +1,64 @@
.checkout {
position: fixed;
inset: 0 0 0 auto;
width: min(100%, 480px);
max-width: 100%;
height: 100%;
max-height: 100%;
margin: 0;
padding: 0;
border: 0;
border-left: 1px solid var(--line);
background: var(--surface);
color: var(--text);
box-shadow: -16px 0 56px #0008;
}
.checkout[open] { display: grid; grid-template-rows: auto minmax(0, 1fr) auto; }
.checkout::backdrop { background: #060c14b3; }
.checkout-head { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 18px 20px; border-bottom: 1px solid var(--line); }
.checkout-head h2 { margin: 0; font-size: 24px; }
.checkout-close {
width: 36px;
height: 36px;
padding: 0;
border: 1px solid var(--line);
border-radius: 6px;
background: #1a2530;
font-size: 24px;
line-height: 1;
}
.checkout-close:hover:not(:disabled) { background: var(--surface-raised); }
.checkout-body { overflow: auto; }
.checkout-empty { margin: 18px 20px; color: var(--muted); }
.checkout-list { display: grid; gap: 1px; margin: 0; padding: 0; list-style: none; background: var(--line); }
.checkout-item {
display: grid;
grid-template-columns: min(85px, 20%) minmax(0, 1fr) auto;
align-items: center;
gap: 12px;
padding: 14px 20px;
background: var(--surface);
}
.checkout-art {
display: grid;
place-items: center;
aspect-ratio: 2 / 1;
overflow: hidden;
border-radius: 4px;
background: #304553;
}
.checkout-art img { width: 100%; height: 100%; object-fit: cover; }
.checkout-item-copy { display: grid; gap: 3px; overflow-wrap: anywhere; }
.checkout-item-status { color: #ffc5b5; font-size: 13px; }
.checkout-item-actions { display: grid; gap: 4px; justify-items: end; color: var(--gold); white-space: nowrap; }
.checkout-remove { padding: 1px 0; border: 0; background: transparent; color: var(--muted); font-size: 13px; }
.checkout-remove:hover:not(:disabled) { color: var(--text); text-decoration: underline; }
.checkout-footer { padding: 16px 20px 20px; border-top: 1px solid var(--line); background: #16242d; }
.checkout-footer .notice { margin: 0 0 12px; }
.checkout-total, .checkout-balance { display: flex; justify-content: space-between; align-items: baseline; flex-wrap: wrap; gap: 5px 10px; }
.checkout-total strong { color: var(--gold); font-size: 25px; }
.checkout-balance { margin: 4px 0 13px; color: var(--muted); font-size: 13px; }
.checkout-hint { margin: 6px 0 12px; color: #ffd5b3; font-size: 13px; }
.checkout-footer button { display: block; width: 100%; }
.checkout-footer #payFree { margin-top: 8px; }
@@ -0,0 +1,184 @@
// The server tracks the cart per account and settles it with a single request.
'use strict';
function createStoreCheckout(refreshAccount) {
const dialog = $('checkout');
const cartButton = $('cartBtn');
let active;
let products = new Map();
let accountLoading = true;
let processing = false;
let directProductId = '';
let complete = false;
let opener;
const cartIds = () => active?.cartProductIds || [];
const locked = () => processing || accountLoading || !active?.activeUserId;
const showsAccount = (userId) => active?.activeUserId === userId && $('accountSelect').value === userId;
function syncProductButton(button, product) {
const adding = button.dataset.cartAction === 'add';
const inCart = adding && cartIds().includes(product.id);
const buyLabel = product.owned ? 'owned' : (active?.activeUserId ? 'buy' : 'pickAccount');
button.disabled = locked() || (product.owned && !inCart);
button.textContent = t(adding ? (inCart ? 'inCart' : 'addCart') : buyLabel);
button.classList.toggle('in-cart', inCart);
button.setAttribute('aria-haspopup', !adding || inCart ? 'dialog' : 'false');
}
function syncControls() {
cartButton.disabled = locked();
$('cartCount').textContent = WtoUi.num(cartIds().length);
for (const button of document.querySelectorAll('[data-cart-action]')) {
const product = products.get(button.dataset.product);
if (product) syncProductButton(button, product);
}
if (dialog.open) renderCheckout();
}
function setState(next) {
active = next;
products = new Map(next.products.map((product) => [product.id, product]));
syncControls();
}
function setAccountLoading(value) {
accountLoading = value;
syncControls();
}
function setProcessing(value) {
processing = value;
syncControls();
}
function productButtons(product, layout) {
const buy = storeButton(layout === 'detail' ? 'btn-main' : 'card-buy');
const add = storeButton(layout === 'detail' ? 'btn-outline' : 'card-add');
buy.dataset.cartAction = 'buy';
add.dataset.cartAction = 'add';
for (const button of [buy, add]) {
button.dataset.product = product.id;
syncProductButton(button, product);
}
buy.onclick = () => open(product.id);
add.onclick = () => {
if (cartIds().includes(product.id)) open();
else void changeCart(product.id, 'add');
};
return [buy, add];
}
function productRow(id) {
const product = products.get(id);
const row = makeElement('li', 'checkout-item');
const title = product ? WtoUi.text(product.title) : id;
const info = makeElement('div', 'checkout-item-copy');
info.append(makeElement('strong', '', title));
if (!product || product.owned) {
info.append(makeElement('span', 'checkout-item-status', t(product ? 'owned' : 'unavailable')));
}
const amounts = makeElement('div', 'checkout-item-actions');
if (product) amounts.append(makeElement('strong', '', storePrice(product.gjnCostCents)));
if (!directProductId) {
const remove = storeButton('checkout-remove', t('remove'));
remove.disabled = locked();
remove.setAttribute('aria-label', t('removeItem', { name: title }));
remove.onclick = () => changeCart(id, 'remove');
amounts.append(remove);
}
const art = makeElement('div', 'checkout-art');
if (product) art.append(productImage(product));
row.append(art, info, amounts);
return row;
}
function renderCheckout() {
const ids = complete ? [] : (directProductId ? [directProductId] : cartIds());
$('checkoutList').replaceChildren(...ids.map(productRow));
$('checkoutTitle').textContent = t(directProductId ? 'confirmPurchase' : 'cart');
$('checkoutClose').disabled = processing;
$('checkoutEmpty').hidden = complete || ids.length > 0;
$('checkoutDone').hidden = !complete;
$('checkoutDone').disabled = processing;
$('checkoutTotals').hidden = ids.length === 0;
if (!ids.length) return;
const items = ids.map((id) => products.get(id));
const total = items.reduce((sum, product) => sum + (product?.gjnCostCents || 0), 0);
const balance = active.balance.gjnCents;
const unavailable = items.some((product) => !product || product.owned);
const hint = unavailable ? t(directProductId ? 'owned' : 'cartBlocked') : (balance < total ? t('lowBalance') : '');
$('checkoutTotal').textContent = storePrice(total);
$('checkoutBalance').textContent = storePrice(balance);
$('checkoutHint').textContent = hint;
$('checkoutHint').hidden = !hint;
$('payGjn').disabled = locked() || unavailable || balance < total;
$('payFree').disabled = locked() || unavailable;
}
function open(productId = '') {
if (locked()) return;
directProductId = productId;
complete = false;
$('checkoutNotice').className = 'notice';
opener = document.activeElement;
renderCheckout();
dialog.showModal();
}
function applyCart(result) {
if (Array.isArray(result.cartProductIds)) active.cartProductIds = result.cartProductIds;
}
async function changeCart(productId, action) {
if (locked()) return;
const userId = active.activeUserId;
const notice = dialog.open ? $('checkoutNotice') : $('notice');
setProcessing(true);
try {
const result = await WtoUi.postJson('/store/api/cart', { userId, productId, action });
if (!showsAccount(userId)) return;
applyCart(result);
if (result.ok) notice.className = 'notice';
else WtoUi.showNotice(notice, WtoUi.text(result.message) || t('buyFailed'), false);
} catch (error) {
if (!showsAccount(userId)) return;
WtoUi.showNotice(notice, t('buyFailed'), false);
await refreshAccount(userId);
} finally {
setProcessing(false);
}
}
async function pay(payMethod) {
if (locked()) return;
const userId = active.activeUserId;
const body = directProductId ? { productId: directProductId } : { productIds: cartIds().slice() };
const route = directProductId ? 'buy' : 'checkout';
const notice = $('checkoutNotice');
setProcessing(true);
try {
const result = await WtoUi.postJson('/store/api/' + route, { userId, payMethod, ...body });
if (!showsAccount(userId)) return;
applyCart(result);
complete = result.ok;
WtoUi.showNotice(notice, WtoUi.text(result.message) || t('buyFailed'), result.ok);
} catch (error) {
WtoUi.showNotice(notice, t('buyFailed'), false);
} finally {
if (showsAccount(userId)) await refreshAccount(userId);
setProcessing(false);
if (complete) $('checkoutDone').focus();
}
}
cartButton.onclick = () => open();
$('checkoutClose').onclick = $('checkoutDone').onclick = () => dialog.close();
$('payGjn').onclick = () => pay('gjn');
$('payFree').onclick = () => pay('free');
dialog.oncancel = (event) => { if (processing) event.preventDefault(); };
dialog.onclose = () => { if (opener?.isConnected && !opener.disabled) opener.focus(); else cartButton.focus(); };
return { productButtons, setState, setAccountLoading };
}
@@ -0,0 +1,165 @@
// Image gallery and on-demand playback for public demo clips.
'use strict';
const galleryPlayers = new WeakMap();
function stopStoreGallery(root) {
const stage = root.querySelector('.media-stage');
galleryPlayers.get(stage)?.();
}
function galleryItems(product) {
const { screenshots, videos } = WtoUi.storeMedia(product.id);
const cover = () => productImage(product);
const demoStill = screenshots[0] ? () => productScreenshot(product, screenshots[0]) : cover;
const entries = videos.map((sources, index) => ({
label: videos.length === 1 ? t('video') : t('videoNumber', { index: index + 1 }),
image: demoStill,
sources,
}));
screenshots.forEach((url, index) => {
entries.push({ label: t('screenshot', { index: index + 1 }), image: () => WtoUi.tieredImg([url], [], ''), screenshot: true });
});
entries.push({ label: t('cover'), image: cover });
if (product.vehicles && (videos.length || screenshots.length || product.vehicles.length > 1)) {
for (const vehicle of product.vehicles) {
entries.push({ label: WtoUi.text(vehicle.title), image: () => WtoUi.vehicleImg(vehicle.unitName, '') });
}
}
return entries;
}
function playStoreClip(stage, sources, poster, onReady, onUnavailable) {
galleryPlayers.get(stage)?.();
const video = document.createElement('video');
video.controls = true;
video.playsInline = true;
if (poster) video.poster = poster;
const playable = sources.filter((url) => video.canPlayType(/\.webm(?:$|\?)/i.test(url) ? 'video/webm' : 'video/mp4'));
let nextSource = 0;
let timer;
function dispose() {
clearTimeout(timer);
galleryPlayers.delete(stage);
video.onerror = video.oncanplay = null;
video.pause();
video.removeAttribute('src');
video.load();
video.remove();
}
function attempt() {
clearTimeout(timer);
const url = playable[nextSource++];
if (!url) {
dispose();
onUnavailable();
return;
}
video.src = url;
timer = setTimeout(attempt, 5500);
void video.play().catch(() => {});
}
video.onerror = attempt;
video.oncanplay = () => {
clearTimeout(timer);
onReady();
};
stage.replaceChildren(video);
galleryPlayers.set(stage, dispose);
attempt();
}
function appendGalleryImage(container, item, placeholder) {
const image = item.image();
if (item.screenshot && !image.naturalWidth) {
const pending = makeElement('span', 'media-placeholder', placeholder);
image.addEventListener('load', () => pending.remove(), { once: true });
container.append(pending);
}
container.append(image);
return image;
}
function mountStoreGallery(root, product) {
const items = galleryItems(product);
root.innerHTML = '<div class="media-stage"></div><div class="media-navigation"><button type="button">‹</button>'
+ '<div class="media-thumbs"></div><button type="button">›</button></div>'
+ '<div class="media-caption"><span class="media-label"></span><span class="media-position"></span></div>'
+ '<p class="media-status" role="status" hidden></p>';
root.setAttribute('aria-label', t('gallery'));
const stage = root.querySelector('.media-stage');
const nav = root.querySelector('.media-navigation');
const rail = root.querySelector('.media-thumbs');
const [prev, next] = nav.querySelectorAll('button');
const caption = root.querySelector('.media-caption');
const status = root.querySelector('.media-status');
let active = 0;
function showImage(item, showPlay) {
stage.replaceChildren();
const image = appendGalleryImage(stage, item, t('screenshotPending'));
image.loading = 'eager';
image.alt = item.label;
if (!showPlay) return;
const play = storeButton('media-play', '▶ ' + t('playVideo'));
play.onclick = () => playItem(item);
stage.append(play);
}
function playItem(item) {
const image = stage.querySelector('img');
const poster = image?.currentSrc || image?.getAttribute('src');
status.textContent = t('videoLoading');
status.hidden = false;
playStoreClip(stage, item.sources, poster, () => { status.hidden = true; }, () => {
showImage(item, true);
status.textContent = t('videoUnavailable');
status.hidden = false;
});
}
function select(index, play = false, scroll = true) {
if (index < 0 || index >= items.length) return;
stopStoreGallery(root);
buttons[active].setAttribute('aria-pressed', 'false');
active = index;
const item = items[index];
const button = buttons[index];
button.setAttribute('aria-pressed', 'true');
if (scroll) button.scrollIntoView({ block: 'nearest', inline: 'nearest' });
prev.disabled = index === 0;
next.disabled = index === items.length - 1;
caption.querySelector('.media-label').textContent = item.label;
caption.querySelector('.media-position').textContent = (index + 1) + ' / ' + items.length;
status.hidden = true;
showImage(item, !!item.sources);
if (play && item.sources) playItem(item);
}
const buttons = items.map((item, index) => {
const button = storeButton('media-thumb');
button.setAttribute('aria-label', item.label);
button.setAttribute('aria-pressed', 'false');
button.title = item.label;
appendGalleryImage(button, item, item.label);
if (item.sources) button.append(makeElement('span', 'thumb-play', '▶'));
button.onclick = () => select(index, true);
return button;
});
prev.setAttribute('aria-label', t('previousMedia'));
next.setAttribute('aria-label', t('nextMedia'));
prev.onclick = () => select(active - 1);
next.onclick = () => select(active + 1);
rail.append(...buttons);
rail.onkeydown = (event) => {
if (event.key !== 'ArrowLeft' && event.key !== 'ArrowRight') return;
event.preventDefault();
select(active + (event.key === 'ArrowRight' ? 1 : -1));
buttons[active].focus({ preventScroll: true });
};
nav.hidden = caption.hidden = items.length === 1;
select(0, false, false);
}
+86 -41
View File
@@ -4,55 +4,100 @@
<meta charset="utf-8" />
<meta name="referrer" content="no-referrer" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Gaijin.Net Store · WTOffline</title>
<title>WTOffline Store</title>
<link rel="stylesheet" href="/store/styles.css" />
<link rel="stylesheet" href="/store/product.css" />
<link rel="stylesheet" href="/store/checkout.css" />
</head>
<body>
<div class="page">
<div class="gbar">
<span class="gbar-logo">G</span>
<span class="gbar-item active" data-t="store"></span>
<a class="gbar-item" id="marketLink" data-t="toMarket"></a>
<span class="gbar-right">
<span class="gbar-money">GJN <b id="gjnVal">0</b></span>
<span class="gbar-money"><span data-t="eagles"></span> <b id="goldVal">0</b></span>
<span class="gbar-money"><span data-t="lions"></span> <b id="silverVal">0</b></span>
<span class="gbar-money"><span data-t="premium"></span> <b id="premVal"></b></span>
<select id="accountSelect"></select>
</span>
</div>
<nav class="snav" id="tabs">
<span class="wt-logo"><span class="wt-mark"></span>WAR THUNDER</span>
<a class="snav-item active" data-tab="vehicle-pack" data-t="tabPacks"></a>
<a class="snav-item" data-tab="eagles" data-t="tabEagles"></a>
<a class="snav-item" data-tab="premium-gjn" data-t="tabPremium"></a>
<a class="snav-item" data-tab="redeem" data-t="tabRedeem"></a>
<header class="store-header">
<button type="button" class="store-brand" id="storeHome">
<span class="store-mark" aria-hidden="true">WT</span>
<span>WTOffline <span data-t="store"></span></span>
</button>
<div class="account-strip">
<span class="balance">GJN <b id="gjnVal">0</b></span>
<span class="balance"><span data-t="eagles"></span> <b id="goldVal">0</b></span>
<span class="balance"><span data-t="lions"></span> <b id="silverVal">0</b></span>
<span class="balance"><span data-t="premium"></span> <b id="premVal"></b></span>
<select id="accountSelect" data-label="account" disabled></select>
</div>
</header>
<nav class="store-nav" data-label="store">
<div class="tabs" id="tabs">
<button type="button" data-tab="vehicle-pack" data-t="tabPacks"></button>
<button type="button" data-tab="eagles" data-t="tabEagles"></button>
<button type="button" data-tab="premium-gjn" data-t="tabPremium"></button>
<button type="button" data-tab="redeem" data-t="tabRedeem"></button>
</div>
<div class="store-links">
<a id="marketLink" data-t="toMarket"></a>
<button type="button" class="cart-link" id="cartBtn" aria-haspopup="dialog" disabled>
<span class="cart-icon" aria-hidden="true"></span>
<span data-t="cart"></span>
<b id="cartCount" aria-live="polite">0</b>
</button>
</div>
</nav>
<div id="notice" class="notice"></div>
<section id="catalog">
<div class="frow" id="packFilters">
<select id="countryFilter"></select>
<select id="rankFilter"></select>
<input id="searchInput" type="search" />
<select id="sortSelect" class="sort">
<option value="best" data-t="sortBest"></option>
<option value="priceAsc" data-t="sortPriceAsc"></option>
<option value="priceDesc" data-t="sortPriceDesc"></option>
</select>
</div>
<div class="grid" id="grid"></div>
</section>
<section class="detail" id="detail" hidden></section>
<section class="redeem" id="redeemPanel" hidden>
<div class="redeem-row">
<input id="codeInput" type="text" />
<button class="btn-main" id="redeemBtn" data-t="redeem"></button>
</div>
<ul class="redeem-help" id="redeemHelp"></ul>
</section>
<div class="notice" id="notice" role="status"></div>
<main>
<section id="catalog" aria-labelledby="catalogTitle">
<div class="catalog-head">
<h1 id="catalogTitle" tabindex="-1"></h1>
<div class="filters" id="packFilters">
<select id="countryFilter" data-label="allCountries"></select>
<select id="rankFilter" data-label="allRanks"></select>
<input id="searchInput" type="search" data-label="search" />
<select id="sortSelect" data-label="sort">
<option value="best" data-t="sortBest"></option>
<option value="priceAsc" data-t="sortPriceAsc"></option>
<option value="priceDesc" data-t="sortPriceDesc"></option>
</select>
</div>
</div>
<section class="featured" id="featured" hidden></section>
<div class="grid" id="grid"></div>
</section>
<section class="detail" id="detail" hidden></section>
<section class="redeem" id="redeemPanel" aria-labelledby="redeemTitle" hidden>
<h1 id="redeemTitle" data-t="tabRedeem"></h1>
<div class="redeem-row">
<input id="codeInput" type="text" data-label="codePlaceholder" />
<button type="button" class="btn-main" id="redeemBtn" data-t="redeem" disabled></button>
</div>
<ul class="redeem-help" id="redeemHelp"></ul>
</section>
</main>
<footer class="foot" data-t="footer"></footer>
</div>
<dialog class="checkout" id="checkout" aria-labelledby="checkoutTitle">
<header class="checkout-head">
<h2 id="checkoutTitle"></h2>
<button type="button" class="checkout-close" id="checkoutClose" data-label="close">×</button>
</header>
<div class="checkout-body">
<p class="checkout-empty" id="checkoutEmpty" data-t="cartEmpty" hidden></p>
<ul class="checkout-list" id="checkoutList"></ul>
</div>
<div class="checkout-footer">
<p class="notice" id="checkoutNotice" role="status"></p>
<div id="checkoutTotals" hidden>
<div class="checkout-total"><span data-t="total"></span><strong id="checkoutTotal"></strong></div>
<div class="checkout-balance"><span data-t="balance"></span><span id="checkoutBalance"></span></div>
<p class="checkout-hint" id="checkoutHint" role="status" hidden></p>
<button type="button" class="btn-main" id="payGjn" data-t="payGjn"></button>
<button type="button" class="btn-outline" id="payFree" data-t="freeBuy"></button>
</div>
<button type="button" class="btn-main" id="checkoutDone" data-t="keepShopping" hidden></button>
</div>
</dialog>
<script src="/_wto/ui/common.js"></script>
<script src="/store/gallery.js"></script>
<script src="/store/products.js"></script>
<script src="/store/checkout.js"></script>
<script src="/store/app.js"></script>
</body>
</html>
@@ -0,0 +1,130 @@
.detail { padding: 23px 0 42px; }
.detail-head { margin-bottom: 17px; }
.detail-head h1 { margin: 6px 0 8px; font-size: clamp(28px, 4.1vw, 45px); line-height: 1.15; }
.detail-meta:empty { display: none; }
.back { padding: 2px 0; border: 0; background: transparent; color: var(--accent); font-weight: 600; }
.back:hover { text-decoration: underline; }
.detail-grid { display: grid; grid-template-columns: minmax(0, 2.25fr) minmax(270px, 1fr); gap: 22px; align-items: start; }
.gallery {
padding: 8px;
border: 1px solid var(--line);
border-radius: 10px;
background: #18252e;
}
.media-stage {
position: relative;
display: grid;
place-items: center;
aspect-ratio: 16 / 9;
overflow: hidden;
border-radius: 5px;
background: radial-gradient(ellipse, #314c5c, #101a22);
}
.media-stage img, .media-stage video { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: contain; }
.media-stage video { background: #000; }
.media-placeholder { color: var(--muted); text-align: center; }
.media-thumb .media-placeholder { position: absolute; inset: 0; display: grid; place-items: center; padding: 3px; font-size: 12px; }
.media-play {
position: relative;
min-height: 44px;
padding: 8px 18px;
border: 1px solid #b6f1e8;
border-radius: 22px;
background: #10292bea;
color: #cff8f1;
font-weight: 700;
}
.media-play:hover { background: #1c4d4e; }
.media-navigation { display: grid; grid-template-columns: 34px minmax(0, 1fr) 34px; align-items: stretch; gap: 6px; margin-top: 8px; }
.media-navigation > button {
padding: 0;
border: 1px solid var(--line);
border-radius: 5px;
background: var(--surface);
font-size: 27px;
}
.media-navigation > button:hover:not(:disabled) { background: var(--surface-raised); }
.media-thumbs { display: flex; gap: 6px; overflow: auto hidden; scrollbar-width: thin; }
.media-thumbs::-webkit-scrollbar { height: 5px; }
.media-thumbs::-webkit-scrollbar-thumb { border-radius: 4px; background: #48606d; }
.media-thumb {
position: relative;
flex: 0 0 clamp(76px, 12vw, 126px);
aspect-ratio: 16 / 9;
overflow: hidden;
padding: 0;
border: 2px solid transparent;
border-radius: 5px;
background: #283b48;
}
.media-thumb[aria-pressed="true"] { border-color: var(--accent); }
.media-thumb:focus-visible { outline-offset: -4px; }
.media-thumb img { position: absolute; inset: 0; width: 100%; height: 100%; object-fit: cover; }
.thumb-play {
position: absolute;
top: 50%;
left: 50%;
display: grid;
place-items: center;
width: 28px;
height: 28px;
padding-left: 2px;
border-radius: 50%;
background: #112f32dc;
color: var(--accent-hover);
transform: translate(-50%, -50%);
}
.media-caption { display: flex; justify-content: space-between; gap: 8px; padding: 7px 3px 0; color: var(--muted); font-size: 13px; }
.media-position { white-space: nowrap; }
.media-status { margin: 8px 3px 2px; color: #ffd5b3; font-size: 13px; }
.buy-panel { padding: 18px 18px 15px; border: 1px solid var(--line); border-top: 2px solid #679d93; border-radius: 9px; background: var(--surface); }
.detail-price { display: flex; justify-content: space-between; align-items: baseline; flex-wrap: wrap; gap: 5px 10px; padding-bottom: 14px; color: var(--muted); }
.detail-price strong { color: var(--gold); font-size: 25px; }
.detail-actions { display: grid; gap: 9px; }
.includes { margin-top: 16px; padding-top: 14px; border-top: 1px solid var(--line); }
.includes h2, .detail-recommendations h2 { margin: 0 0 10px; font-size: 16px; }
.includes ul { display: grid; gap: 8px; margin: 0; padding: 0; list-style: none; }
.included-vehicle { display: grid; grid-template-columns: 58px minmax(0, 1fr); gap: 10px; align-items: center; }
.included-vehicle strong { display: block; margin-bottom: 4px; font-weight: 600; overflow-wrap: anywhere; }
.included-art { width: 58px; height: 43px; object-fit: contain; border-radius: 4px; background: #283b48; }
.included-reward { color: var(--muted); }
.detail-recommendations { display: grid; gap: 8px; margin-top: 18px; }
.detail-recommendations h2 { margin-bottom: 0; }
.bonus {
position: relative;
min-height: 158px;
display: flex;
align-items: center;
overflow: hidden;
isolation: isolate;
margin-top: 18px;
padding: 25px 26px;
border: 1px solid #e1c38d;
border-radius: 9px;
background: linear-gradient(108deg, #e4cd98, #d1aa62 62%, #9b713c);
color: #2e2214;
}
.bonus-art {
position: absolute;
z-index: -1;
right: -4%;
top: -12%;
width: 68%;
height: 125%;
object-fit: cover;
-webkit-mask-image: linear-gradient(90deg, transparent, #000 40%);
mix-blend-mode: multiply;
filter: sepia(1) contrast(1.15);
opacity: .63;
}
.bonus-copy { max-width: 63%; }
.bonus-copy h2 { margin: 0 0 6px; font-size: clamp(21px, 3vw, 29px); }
.bonus-copy p { margin: 0; font-size: 15px; font-weight: 550; }
@media (max-width: 800px) {
.detail-grid { grid-template-columns: minmax(0, 1fr); }
.detail-grid > aside { grid-row: 2; }
}
@@ -0,0 +1,168 @@
// Presentation of store products shared by the catalog, detail view, and checkout.
'use strict';
const FEATURED_PACKS = ['wto_pack_fa_18d_late', 'wto_pack_us_stingray_2', 'wto_pack_cn_ztz_96b', 'wto_pack_f-4s'];
function makeElement(tag, className, text) {
const node = document.createElement(tag);
if (className) node.className = className;
if (text !== undefined) node.textContent = text;
return node;
}
function storeButton(className, text) {
const button = makeElement('button', className, text);
button.type = 'button';
return button;
}
function storePrice(cents) {
return WtoUi.gjn(cents) + ' GJN';
}
function rankLabel(rank) {
return t('rank', { rank: ROMAN[rank] || rank });
}
function productArtwork(product) {
const image = product.unitName ? WtoUi.artworkUrl('vehicle', product.unitName) : WtoUi.artworkUrl('product', product.kind);
return product.artworkGroup ? [WtoUi.artworkUrl('group', product.artworkGroup), image] : [image];
}
function productImage(product, className = '') {
const { cover } = WtoUi.storeMedia(product.id);
const urls = product.unitName ? [cover, ...WtoUi.vehicleUrls(product.unitName)] : [cover];
return WtoUi.tieredImg(urls, productArtwork(product), className);
}
function productScreenshot(product, url, className = '') {
return WtoUi.tieredImg([url], productArtwork(product), className);
}
function vehicleMeta(vehicle) {
const meta = makeElement('span', 'product-meta');
if (vehicle.country) {
meta.append(WtoUi.iconImg('flag', vehicle.country, ''), makeElement('span', '', WtoUi.label(vehicle.country)));
}
if (vehicle.rank) meta.append(makeElement('span', 'rank', rankLabel(vehicle.rank)));
return meta;
}
function productRewards(product) {
const rewards = [];
if (product.premiumDays) rewards.push(t('containsPremium', { days: product.premiumDays }));
if (product.goldIncome) rewards.push(t('containsEagles', { n: WtoUi.num(product.goldIncome) }));
if (product.silverIncome) rewards.push(t('containsSilver', { n: WtoUi.num(product.silverIncome) }));
return rewards;
}
function productCard(product, checkout, openProduct) {
const card = makeElement('article', 'product-card');
const open = storeButton('product-open');
const art = makeElement('span', 'product-art');
art.append(productImage(product));
const info = makeElement('span', 'product-info');
info.append(makeElement('span', 'product-title', WtoUi.text(product.title)));
if (product.unitName) {
info.append(vehicleMeta(product));
const rewards = productRewards(product);
if (rewards.length) info.append(makeElement('span', 'product-rewards', rewards.join(' · ')));
}
open.append(art, info);
open.onclick = () => openProduct(product);
const actions = makeElement('div', 'card-actions');
actions.append(...checkout.productButtons(product, ''));
card.append(open, makeElement('div', 'card-price', storePrice(product.gjnCostCents)), actions);
return card;
}
function recommendedPacks(products) {
return FEATURED_PACKS.map((id) => products.find((product) => product.id === id)).filter(Boolean);
}
function recommendationTile(product, openProduct) {
const tile = storeButton('recommendation-tile');
const copy = makeElement('span', 'recommendation-copy');
copy.append(makeElement('strong', '', WtoUi.text(product.title)), makeElement('span', '', storePrice(product.gjnCostCents)));
tile.append(productImage(product), copy);
tile.onclick = () => openProduct(product);
return tile;
}
function renderFeatured(root, products, openProduct) {
const [lead, ...more] = recommendedPacks(products);
root.hidden = !lead;
if (!lead) {
root.replaceChildren();
return;
}
root.setAttribute('aria-label', t('featured'));
const hero = storeButton('featured-hero');
const { screenshots } = WtoUi.storeMedia(lead.id);
const image = screenshots.length ? productScreenshot(lead, screenshots[0]) : productImage(lead);
image.loading = 'eager';
const copy = makeElement('span', 'featured-copy');
copy.append(
makeElement('span', 'featured-label', t('featured')),
makeElement('strong', 'featured-title', WtoUi.text(lead.title)),
vehicleMeta(lead),
makeElement('span', 'featured-link', t('viewPack') + ' →'),
);
hero.append(image, copy);
hero.onclick = () => openProduct(lead);
const tiles = makeElement('div', 'recommendation-list');
tiles.append(...more.map((product) => recommendationTile(product, openProduct)));
root.replaceChildren(hero, tiles);
}
function renderPackDetail(root, product, checkout, products, openProduct, backToCatalog) {
root.innerHTML = '<header class="detail-head"><button type="button" class="back"></button><h1 tabindex="-1"></h1><div class="detail-meta"></div></header>'
+ '<div class="detail-grid"><div class="detail-main"><section class="gallery"></section><section class="bonus" hidden></section></div>'
+ '<aside><div class="buy-panel"><div class="detail-price"></div><div class="detail-actions"></div><div class="includes"></div></div>'
+ '<section class="detail-recommendations" hidden></section></aside></div>';
const back = root.querySelector('.back');
back.textContent = '‹ ' + t('back');
back.onclick = backToCatalog;
root.querySelector('h1').textContent = WtoUi.text(product.title);
if (product.unitName) root.querySelector('.detail-meta').append(vehicleMeta(product));
mountStoreGallery(root.querySelector('.gallery'), product);
const price = root.querySelector('.detail-price');
price.append(makeElement('span', '', t('packPrice')), makeElement('strong', '', storePrice(product.gjnCostCents)));
root.querySelector('.detail-actions').append(...checkout.productButtons(product, 'detail'));
renderPackContents(root.querySelector('.includes'), product);
if (product.kind !== 'vehicle-pack') return;
renderPremiumBonus(root.querySelector('.bonus'), product);
const related = recommendedPacks(products).filter((item) => item.id !== product.id).slice(0, 2);
if (related.length) {
const section = root.querySelector('.detail-recommendations');
section.hidden = false;
section.append(makeElement('h2', '', t('related')), ...related.map((item) => recommendationTile(item, openProduct)));
}
}
function renderPackContents(root, product) {
const list = makeElement('ul', '');
for (const vehicle of product.vehicles || []) {
const item = makeElement('li', 'included-vehicle');
item.append(
WtoUi.tieredImg([], [WtoUi.artworkUrl('vehicle', vehicle.unitName)], 'included-art'),
);
const vehicleText = makeElement('div', '');
vehicleText.append(makeElement('strong', '', WtoUi.text(vehicle.title)), vehicleMeta(vehicle));
item.append(vehicleText);
list.append(item);
}
for (const reward of productRewards(product)) list.append(makeElement('li', 'included-reward', reward));
root.append(makeElement('h2', '', t('includes')), list);
}
function renderPremiumBonus(root, product) {
const art = WtoUi.tieredImg([], productArtwork(product), 'bonus-art');
const copy = makeElement('div', 'bonus-copy');
copy.append(makeElement('h2', '', t('bonusTitle')), makeElement('p', '', t('bonusText')));
root.hidden = false;
root.replaceChildren(art, copy);
}
+250 -79
View File
@@ -1,90 +1,261 @@
/* Local store page, laid out like the official Gaijin.Net store (implementation notes
section 3; Chromium 100: no :has(), container queries or CSS nesting). Fonts fall back to system fonts. */
:root {
--navy-5: #030c15; --navy-40: #27323f; --navy-60: #2d3a48; --navy-75: #424e5b;
--text: #c0c4c8; --gray-50: #969ca4; --teal: #29b2bc; --teal-hi: #31eeda; --gold: #ffe8aa;
--line: rgba(166, 221, 255, 0.1);
--font: "Fira Sans", "Segoe UI", "Microsoft YaHei", sans-serif; --font-ui: "PT Root UI", var(--font);
color-scheme: dark;
--background: #111b23;
--surface: #1c2933;
--surface-raised: #243541;
--line: #344753;
--text: #f1f4f4;
--muted: #b4c1c8;
--accent: #83dfcf;
--accent-hover: #adf1e4;
--gold: #e6c681;
--font: "Segoe UI", "Microsoft YaHei UI", "Microsoft YaHei", sans-serif;
}
* { box-sizing: border-box; }
[hidden] { display: none !important; }
html, body { margin: 0; }
body { background: var(--navy-40) linear-gradient(180deg, #1b2530 0%, #27323f 420px); color: var(--text); font: 16px/1.5 var(--font); min-width: 1024px; }
.page { width: 1218px; max-width: calc(100% - 32px); margin: 0 auto; }
body {
min-height: 100vh;
background: radial-gradient(ellipse at 45% 0, #263845, var(--background) 540px);
color: var(--text);
font: 15px/1.45 var(--font);
}
button, select, input { font: inherit; }
button { color: inherit; cursor: pointer; }
button:disabled { cursor: default; opacity: .55; }
button:focus-visible, a:focus-visible, input:focus-visible, select:focus-visible {
outline: 2px solid var(--accent);
outline-offset: 3px;
}
a { color: var(--accent); text-decoration: none; }
.page { width: min(1280px, calc(100% - 64px)); margin: 0 auto; }
.gbar { display: flex; align-items: center; gap: 18px; height: 42px; padding: 0 12px; background: var(--navy-5); font-size: 13px; }
.gbar-logo { width: 22px; height: 22px; border-radius: 4px; background: #d32f2f; color: #fff; font-weight: 700; text-align: center; line-height: 22px; }
.gbar-item { color: var(--text); text-decoration: none; cursor: pointer; }
.gbar-item.active { color: #fff; border-bottom: 2px solid #fff; padding-bottom: 2px; }
.gbar-right { margin-left: auto; display: flex; align-items: center; gap: 14px; }
.gbar-money b { color: var(--gold); font-weight: 500; }
.gbar select { height: 28px; border: 1px solid var(--line); border-radius: 3px; background: #0d1823; color: #fff; font: inherit; }
.store-header {
min-height: 76px;
display: flex;
align-items: center;
justify-content: space-between;
gap: 20px;
padding: 12px 0;
}
.store-brand {
display: inline-flex;
align-items: center;
gap: 12px;
padding: 0;
border: 0;
background: transparent;
font-size: 19px;
font-weight: 650;
white-space: nowrap;
}
.store-mark {
display: grid;
place-items: center;
width: 38px;
height: 38px;
border: 1px solid #b99c65;
border-radius: 9px;
background: #352e23;
color: var(--gold);
font-size: 14px;
letter-spacing: .03em;
}
.account-strip {
display: flex;
align-items: center;
justify-content: flex-end;
flex-wrap: wrap;
gap: 8px 16px;
color: var(--muted);
font-size: 13px;
}
.balance { white-space: nowrap; }
.balance b { margin-left: 3px; color: var(--text); font-weight: 600; }
.account-strip select, .filters select, .filters input, .redeem-row input {
min-height: 38px;
padding: 0 10px;
border: 1px solid var(--line);
border-radius: 6px;
background: #15212b;
color: var(--text);
}
.snav { display: flex; align-items: center; gap: 28px; height: 76px; border-bottom: 1px solid var(--line); font: 18px/27px var(--font-ui); }
.wt-logo { display: flex; align-items: center; gap: 8px; color: #b8bcc1; letter-spacing: 0.12em; font-size: 15px; margin-right: 12px; }
.wt-mark { width: 26px; height: 26px; border-radius: 50%; background: radial-gradient(circle, #ff4b3a 30%, #b3170c 70%); }
.snav-item { color: var(--text); text-decoration: none; cursor: pointer; transition: color 0.3s; }
.snav-item:hover, .snav-item.active { color: var(--teal-hi); }
.store-nav { display: flex; justify-content: space-between; gap: 10px 20px; border-bottom: 1px solid var(--line); }
.tabs, .store-links { display: flex; align-items: center; gap: 8px; }
.tabs { flex-wrap: wrap; }
.tabs button {
min-height: 48px;
padding: 0 13px;
border: 0;
border-bottom: 2px solid transparent;
background: transparent;
color: var(--muted);
font-weight: 600;
}
.tabs button:hover, .tabs button[aria-pressed="true"] { color: var(--accent); }
.tabs button[aria-pressed="true"] { border-color: var(--accent); }
.store-links { gap: 16px; padding-bottom: 6px; white-space: nowrap; }
.cart-link {
min-height: 38px;
display: inline-flex;
align-items: center;
gap: 9px;
padding: 4px 10px;
border: 1px solid #518477;
border-radius: 6px;
background: #233e40;
color: var(--accent-hover);
font-weight: 650;
}
.cart-link:hover:not(:disabled) { background: #305453; }
.cart-link b {
min-width: 22px;
padding: 1px 5px;
border-radius: 12px;
background: #132a2c;
text-align: center;
font-size: 12px;
}
.cart-icon { position: relative; width: 16px; height: 16px; }
.cart-icon::before {
content: "";
position: absolute;
inset: 2px 0 6px 1px;
border: 2px solid currentColor;
border-top-width: 1px;
transform: skewX(-12deg);
}
.cart-icon::after {
content: "";
position: absolute;
left: 3px;
bottom: 1px;
width: 3px;
height: 3px;
border-radius: 50%;
background: currentColor;
box-shadow: 8px 0 currentColor;
}
.frow { display: flex; align-items: center; gap: 14px; height: 56px; border-bottom: 1px solid var(--line); }
.frow select, .frow input { height: 34px; padding: 0 10px; border: 1px solid var(--line); border-radius: 3px; background: transparent; color: var(--text); font: 14px var(--font); }
.frow select option { background: var(--navy-60); }
.frow input { width: 260px; }
.frow .sort { margin-left: auto; }
.catalog-head { display: flex; align-items: center; justify-content: space-between; flex-wrap: wrap; gap: 12px 20px; padding: 24px 0 18px; }
.catalog-head h1, .redeem h1 { margin: 0; font-size: clamp(25px, 3vw, 34px); line-height: 1.2; }
.filters { display: flex; flex-wrap: wrap; gap: 8px; font-size: 13px; }
.filters input { width: clamp(150px, 21vw, 245px); }
.filters input::placeholder { color: var(--muted); }
.grid { display: grid; grid-template-columns: repeat(4, 1fr); gap: 24px; padding: 24px 0 40px; }
.pw { position: relative; display: flex; flex-direction: column; height: 344px; background: var(--navy-60); overflow: hidden; cursor: pointer; transition: transform 0.3s; }
.pw:hover { transform: translateY(-3px); }
.pw-poster { position: relative; height: 162px; display: flex; align-items: center; justify-content: center; background: linear-gradient(180deg, #33475a, var(--navy-60)); }
.pw-poster img { width: 92%; height: 92%; object-fit: contain; }
.badge { position: absolute; left: 0; right: 0; top: 0; height: 30px; padding: 0 12px; display: flex; align-items: center; justify-content: space-between; color: #fff; font-size: 14px; text-transform: uppercase; background: linear-gradient(90deg, #0050e0, #1a8cff); }
.badge.owned { background: linear-gradient(90deg, #3a8a2a, #6cc04a); }
.pw-desc { flex: 1; padding: 10px 14px 0; min-height: 0; overflow: hidden; }
.pw-game { color: var(--text); font-size: 12px; text-transform: uppercase; letter-spacing: 0.06em; }
.pw-title { margin: 2px 0 4px; color: #fff; font-size: 18px; line-height: 1.3; max-height: 70px; overflow: hidden; }
.pw-comment { display: flex; align-items: center; gap: 6px; font-size: 13px; color: var(--text); }
.pw-comment img { width: 26px; height: 17px; object-fit: contain; }
.pw-contents { margin: 6px 0 0; padding-left: 16px; font-size: 13px; color: var(--gray-50); }
.pw-price { padding: 0 14px 12px; text-align: right; color: var(--gold); font-size: 20px; }
.pw-buy { display: flex; height: 40px; border-top: 1px solid var(--line); }
.pw-buy button { flex: 1; border: none; border-right: 1px solid var(--line); background: transparent; color: var(--gold); font: 16px var(--font-ui); text-transform: uppercase; cursor: pointer; transition: background 0.3s; }
.pw-buy button:last-child { border-right: none; }
.pw-buy button:hover { background: #ffffff0f; }
.pw-buy button:disabled { color: var(--gray-50); cursor: default; background: transparent; }
.empty { grid-column: 1 / -1; color: var(--gray-50); padding: 40px 0; }
.featured { display: grid; grid-template-columns: minmax(0, 2.15fr) minmax(0, 1fr); gap: 14px; margin-bottom: 24px; }
.featured-hero {
position: relative;
min-height: 260px;
display: flex;
align-items: flex-end;
overflow: hidden;
padding: 24px;
border: 1px solid #617987;
border-radius: 10px;
background: #263c4a;
text-align: left;
isolation: isolate;
}
.featured-hero > img { position: absolute; z-index: -2; inset: 0; width: 100%; height: 100%; object-fit: cover; object-position: center 45%; }
.featured-hero::after {
content: "";
position: absolute;
z-index: -1;
inset: 0;
background: linear-gradient(88deg, #111e29ee 3%, #14212cbb 34%, transparent 76%),
linear-gradient(0deg, #101c26cc, transparent 66%);
}
.featured-copy { display: flex; flex-direction: column; align-items: flex-start; gap: 7px; }
.featured-label { color: var(--gold); font-size: 13px; font-weight: 650; }
.featured-title { max-width: 540px; font-size: clamp(25px, 3.4vw, 42px); line-height: 1.13; overflow-wrap: anywhere; }
.featured-link { margin-top: 6px; color: var(--accent-hover); font-weight: 650; }
.featured-hero:hover .featured-link { text-decoration: underline; }
.recommendation-list { display: grid; grid-auto-rows: 1fr; gap: 9px; }
.recommendation-list:empty { display: none; }
.recommendation-tile {
display: grid;
grid-template-columns: min(38%, 132px) minmax(0, 1fr);
align-items: center;
gap: 12px;
width: 100%;
padding: 0 12px 0 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--surface);
text-align: left;
}
.recommendation-tile:hover { border-color: #779498; background: var(--surface-raised); }
.recommendation-tile img { width: 100%; height: 100%; min-height: 68px; max-height: 91px; object-fit: cover; background: #304856; }
.recommendation-copy { display: grid; gap: 4px; padding: 5px 0; overflow-wrap: anywhere; }
.recommendation-copy > span { color: var(--gold); font-size: 13px; }
.detail { padding: 24px 0 40px; }
.detail h1 { margin: 0 0 20px; color: #fff; font-size: 40px; font-weight: 700; }
.back { color: var(--teal); cursor: pointer; font-size: 15px; display: inline-block; margin-bottom: 12px; }
.detail-cols { display: flex; gap: 24px; align-items: flex-start; }
.detail-left { flex: 1; min-width: 0; }
.media { height: 452px; display: flex; align-items: center; justify-content: center; background: radial-gradient(circle at 50% 40%, #3a4d60, #1b2633 75%); }
.media img, .media video { width: 100%; height: 100%; object-fit: contain; }
.thumbs { display: flex; flex-wrap: wrap; gap: 8px; padding: 8px 0; }
.thumbs[hidden] { display: none; }
.thumbs button { padding: 6px 12px; background: #1b2633; color: var(--text); border: 1px solid #425367; cursor: pointer; }
.thumbs button[aria-pressed='true'] { border-color: #f9ae3d; }
.media-status { margin: 0; color: var(--muted); }
.detail-left h2 { color: #fff; font-size: 32px; font-weight: 300; margin: 24px 0 8px; }
.bonus { margin-top: 24px; padding: 28px 32px; background: linear-gradient(90deg, #5c5030, #e8d08a); color: #3a2a10; }
.bonus h3 { margin: 0 0 8px; font-size: 32px; text-transform: uppercase; }
.detail-right { flex: none; width: 390px; }
.buy-panel { padding: 24px 40px 28px; background: #1f2a36; text-align: center; }
.buy-panel .price { color: #fff; font-size: 26px; margin: 8px 0 16px; }
.btn-main { width: 310px; max-width: 100%; height: 56px; border: none; border-radius: 3px; background: linear-gradient(180deg, #ff7a2f, #d9381e); color: #fff; font: 26px var(--font-ui); text-transform: uppercase; box-shadow: 0 5px 13px rgba(89, 16, 0, 0.65); cursor: pointer; }
.btn-free { width: 310px; max-width: 100%; height: 44px; margin-top: 12px; border: 1px solid var(--gold); border-radius: 3px; background: transparent; color: var(--gold); font: 18px var(--font-ui); cursor: pointer; }
.btn-main:disabled, .btn-free:disabled { filter: grayscale(1); opacity: 0.7; cursor: default; }
.includes { margin-top: 20px; text-align: left; }
.includes h4 { margin: 0 0 8px; color: var(--text); font-size: 17px; font-weight: 400; }
.includes li { list-style: none; display: flex; align-items: center; gap: 8px; color: #fff; padding: 3px 0; }
.includes img { width: 26px; height: 17px; object-fit: contain; }
.rank-chip { padding: 0 6px; border-radius: 2px; background: #f9ae3d; color: #1b1408; font-size: 13px; font-weight: 700; }
.grid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 16px; padding-bottom: 38px; }
.product-card {
display: flex;
flex-direction: column;
min-width: 0;
overflow: hidden;
border: 1px solid var(--line);
border-radius: 8px;
background: var(--surface);
}
.product-card:hover { border-color: #627e89; }
.product-open { display: block; width: 100%; padding: 0; border: 0; background: transparent; text-align: left; }
.product-open:focus-visible { outline-offset: -3px; }
.product-art { display: block; aspect-ratio: 2 / 1; background: radial-gradient(ellipse, #3b5563, #253947); }
.product-art img { display: block; width: 100%; height: 100%; object-fit: cover; }
.product-info { display: grid; gap: 6px; padding: 12px 13px 8px; }
.product-title { font-size: 17px; font-weight: 650; line-height: 1.25; overflow-wrap: anywhere; }
.product-meta { display: inline-flex; flex-wrap: wrap; align-items: center; gap: 5px 8px; color: var(--muted); font-size: 13px; }
.product-meta img { width: 25px; height: 16px; object-fit: contain; }
.product-meta .rank { padding: 1px 6px; border-radius: 4px; background: #ffffff13; color: var(--text); white-space: nowrap; }
.product-rewards { color: var(--muted); font-size: 12px; }
.card-price { margin-top: auto; padding: 10px 13px; color: var(--gold); font-size: 19px; font-weight: 650; }
.card-actions { display: grid; grid-template-columns: minmax(0, .9fr) minmax(0, 1.35fr); border-top: 1px solid var(--line); }
.card-actions button { min-height: 41px; padding: 6px; border: 0; background: transparent; font-size: 14px; font-weight: 600; }
.card-actions .card-buy { color: var(--accent); border-right: 1px solid var(--line); }
.card-actions .card-add { color: var(--text); }
.card-actions button:hover:not(:disabled), .card-actions .in-cart { background: #2a4649; }
.empty { grid-column: 1 / -1; color: var(--muted); }
.notice { display: none; margin: 16px 0 0; padding: 10px 14px; border: 1px solid var(--line); }
.notice.ok { display: block; color: #98ff87; } .notice.err { display: block; color: #ff9270; }
.redeem { padding: 32px 0 48px; max-width: 760px; }
.redeem-row { display: flex; gap: 12px; }
.redeem-row input { flex: 1; height: 44px; padding: 0 12px; border: 1px solid var(--line); background: #1b2633; color: #fff; font: 16px var(--font); }
.redeem-row .btn-main { width: 180px; height: 44px; font-size: 18px; }
.redeem-help { color: var(--gray-50); padding-left: 18px; }
.foot { padding: 32px 0; border-top: 1px solid var(--line); color: var(--gray-50); font-size: 13px; text-align: center; }
.btn-main, .btn-outline {
min-height: 45px;
padding: 9px 14px;
border: 1px solid transparent;
border-radius: 6px;
font-weight: 650;
}
.btn-main { background: var(--accent); color: #172925; }
.btn-main:hover:not(:disabled) { background: var(--accent-hover); }
.btn-outline { border-color: #697c85; background: transparent; color: var(--text); }
.btn-outline:hover:not(:disabled), .btn-outline.in-cart { background: #2b4549; }
.notice { display: none; margin: 14px 0 0; padding: 10px 12px; border: 1px solid var(--line); border-radius: 5px; }
.notice.ok { display: block; background: #18362f; color: #b4eed9; }
.notice.err { display: block; background: #3b2b2b; color: #ffc5b5; }
.redeem { padding: 26px 0 42px; max-width: 740px; }
.redeem-row { display: flex; gap: 10px; margin: 18px 0; }
.redeem-row input { flex: 1; min-width: 0; }
.redeem-help { padding-left: 20px; color: var(--muted); }
.foot { padding: 20px 0 30px; border-top: 1px solid var(--line); color: var(--muted); font-size: 13px; }
@media (max-width: 1000px) {
.page { width: calc(100% - 36px); }
.grid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
}
@media (max-width: 730px) {
.store-header, .store-nav { flex-wrap: wrap; }
.account-strip { justify-content: flex-start; }
.featured { grid-template-columns: minmax(0, 1fr); }
.recommendation-list { grid-template-columns: repeat(2, minmax(0, 1fr)); }
.grid { grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 10px; }
}
@media (max-width: 390px) {
.grid, .recommendation-list { grid-template-columns: minmax(0, 1fr); }
}