import { paidSubscriptionOf, StorePlacement, StorePlacementSubTab, StorePlacementTab, StorePlacementTabSchema, UserMeResponse, } from "@openfront/shared/ApiSchemas"; import { CosmeticPack, Cosmetics, Pack, Product, Subscription, } from "@openfront/shared/CosmeticSchemas"; import type { PropertyValues, TemplateResult } from "lit"; import { html, nothing } from "lit"; import { customElement, state } from "lit/decorators.js"; import { BaseModal } from "./components/BaseModal"; import "./components/CosmeticCard"; import type { CosmeticCard } from "./components/CosmeticCard"; import { cosmeticSelectionLabel } from "./components/CosmeticPresentation"; import { isPreviewableCosmetic } from "./components/CosmeticPreviewBubble"; import "./components/CosmeticPreviewModal"; import "./components/CurrencyDisplay"; import "./components/CustomCurrencyCard"; import "./components/EffectsGrid"; import type { InlineCheckout } from "./components/InlineCheckout"; import "./components/NotLoggedInWarning"; import "./components/PackContentsDialog"; import { ProgressiveList } from "./components/ProgressiveList"; import "./components/SaleCountdown"; import { alignPurchaseRows } from "./components/PurchaseButton"; import { runningSales, saleCoversEverything } from "./components/SaleBanner"; import "./components/TribesPanel"; import { modalHeader } from "./components/ui/ModalHeader"; import { activeSale, isNew, newUntilMs, currentPrice, fetchCosmetics, invalidateCosmetics, refreshStaleCosmetics, findPackItem, groupCosmeticVariants, ownedPackItems, purchaseCosmetic, resolveCosmetics, saleHasEnded, ResolvedCosmetic, } from "./Cosmetics"; import { matchesStoreItem } from "./EquippedCosmetics"; import { fetchPlayPrices, priceStringToCents, reportPendingSteamAuthorizations, sellsOnlyThroughPlay, } from "./Payments"; import { StoreTracker } from "./StoreTracking"; import { lastUserMeResponse } from "./UserMeBroadcast"; import { translateText } from "./Utils"; // Matches the API's formatting of `product.price`, so a tier priced from its // own cents reads the same as one priced from its Stripe listing. const usdFormatter = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", }); function formatUsdCents(cents: number): string { return usdFormatter.format(cents / 100); } // The store's tabs are the placement schema's: a tab the store analytics API // would reject cannot be added here without failing typecheck. type StoreTab = StorePlacementTab; function isStoreTab(key: string): key is StoreTab { return (StorePlacementTabSchema.options as readonly string[]).includes(key); } // "new" and "sale" list every new or discounted skin, flag, crown, effect and // bundle; each tab shows only while something is new or on sale. const COSMETICS_SUB_TABS = [ "new", "sale", "patterns", "flags", "crowns", ] as const satisfies readonly StorePlacementSubTab[]; type CosmeticsSubTab = (typeof COSMETICS_SUB_TABS)[number]; /** Sub-tab holding the catalog item a store deep link points at. */ export function subTabForItem(itemKey: string): CosmeticsSubTab { if (itemKey.startsWith("crown:")) return "crowns"; if (itemKey.startsWith("flag:")) return "flags"; return "patterns"; } interface StoreBrowserOptions { emptyTranslationKey: string; userHasSubscription?: boolean; trailingContent?: TemplateResult; gridClass?: string; cardClass?: string; previewSize?: "card" | "detail"; emptyClass?: string; } // After a sale ends, how often and how many times the store refetches while // the API's one-minute-cached catalog still lists it (8 x 15s = 2 minutes). const SALE_END_RETRY_MS = 15_000; const SALE_END_RETRIES = 8; /** Whether the catalog still lists a sale whose end time has passed. */ function hasEndedSale(cosmetics: Cosmetics | null): boolean { const now = Date.now(); return (cosmetics?.promotions ?? []).some( (sale) => new Date(sale.endsAt).getTime() <= now, ); } /** The running flash sale's item group, if one is among `groups`. */ function flashGroup( groups: readonly T[], ): T | undefined { return groups.find((group) => group.some((resolved) => activeSale(resolved.cosmetic)?.kind === "flash"), ); } /** Whether a running sale discounts any variant in a card's group. */ function groupOnSale(group: readonly ResolvedCosmetic[]): boolean { return group.some((resolved) => activeSale(resolved.cosmetic) !== null); } /** Whether any variant in a card's group is new to the store. */ function groupIsNew(group: readonly ResolvedCosmetic[]): boolean { return group.some((resolved) => isNew(resolved.cosmetic)); } /** When a card's group stops being new: its latest variant's newUntil. */ function groupNewUntil(group: readonly ResolvedCosmetic[]): number { return Math.max( ...group.map((resolved) => newUntilMs(resolved.cosmetic) ?? 0), ); } /** The most recently added first: the one that stays new longest. */ function newestFirst( groups: readonly T[], ): T[] { return [...groups].sort((a, b) => groupNewUntil(b) - groupNewUntil(a)); } /** The flash item, then the rest on sale, then everything else. */ export function saleFirst( groups: readonly T[], ): T[] { const flash = flashGroup(groups); const rest = groups.filter((group) => group !== flash); return [ ...(flash ? [flash] : []), ...rest.filter(groupOnSale), ...rest.filter((group) => !groupOnSale(group)), ]; } export { saleCoversEverything }; /** The Play products the catalog's currency packs are sold as. */ function playProductIds(cosmetics: Cosmetics | null): string[] { return Object.values(cosmetics?.currencyPacks ?? {}).flatMap((pack) => pack.currency === "hard" && pack.googleProductId !== undefined ? [pack.googleProductId] : [], ); } @customElement("store-modal") export class StoreModal extends BaseModal { protected routerName = "store"; private cosmetics: Cosmetics | null = null; // In the Android app: Play's price for each product it sells, by product id. // Null when Play could not be asked, which lists no pack for real money. private playPrices: ReadonlyMap | null = null; private affiliateCode: string | null = null; private userMeResponse: UserMeResponse | false = false; // `userMeResponse` starts at `false`, which is also what "no session" looks // like, so a tab that renders a sign-in prompt on `false` would show it to a // logged-in player for the whole window before Main's first userMeResponse // broadcast (a Steam ticket exchange on desktop). This distinguishes the // two: nothing is asserted about the session until it has actually settled. // Reactive on its own, unlike `userMeResponse`, so a settled no-session // result never waits on a slow catalog before it may say so. @state() private authSettled = false; private cosmeticsSubTab: CosmeticsSubTab = "patterns"; // Item the URL asked for (`#modal=store&item=`). Held until its group // is visible, then inspected so the store opens on that item. private requestedItem: string | null = null; private inspected: ResolvedCosmetic | null = null; private previewingCosmetic: ResolvedCosmetic | null = null; private visibleGroups: readonly (readonly ResolvedCosmetic[])[] = []; /** The bundle whose contents dialog is open, if any. */ private openedPack: ResolvedCosmetic | null = null; private readonly pages = new ProgressiveList(this); protected modalConfig() { if (this.affiliateCode) { // Affiliate mode: hide tabs, show only items associated with the code. return { showScrollToTop: true }; } return { showScrollToTop: true, tabs: [ { key: "packs", label: translateText("store.packs") }, { key: "subscriptions", label: translateText("store.subscriptions") }, { key: "bundles", label: translateText("store.bundles") }, { key: "cosmetics", label: translateText("store.cosmetics") }, { key: "effects", label: translateText("store.effects") }, { key: "tribes", label: translateText("store.tribes") }, ] satisfies { key: StoreTab; label: string }[], }; } connectedCallback() { super.connectedCallback(); document.addEventListener("userMeResponse", this.onUserMeEvent); // The store loads on demand, usually after Main's broadcast went out. const last = lastUserMeResponse(); if (last !== null) void this.onUserMe(last.response); this.addEventListener("open-cosmetic-preview", this.onOpenCosmeticPreview); // Rows re-wrap on resize, so which currencies share a row changes with it. if (typeof ResizeObserver !== "undefined") { this.rowObserver ??= new ResizeObserver(() => alignPurchaseRows(this)); this.rowObserver.observe(this); } } disconnectedCallback() { document.removeEventListener("userMeResponse", this.onUserMeEvent); this.removeEventListener( "open-cosmetic-preview", this.onOpenCosmeticPreview, ); this.rowObserver?.disconnect(); this.tracker?.dispose(); this.tracker = null; if (this.alignFrame !== null) cancelAnimationFrame(this.alignFrame); this.alignFrame = null; // A store removed while open never gets onClose; don't let a days-long // timeout hold on to it. this.clearNewEnd(); super.disconnectedCallback(); } protected updated(changed: PropertyValues) { super.updated(changed); this.observeProducts(); // The cards are nested components, so their purchase buttons only exist // (and only have positions) after their own updates commit — a frame later. alignPurchaseRows(this); if (typeof requestAnimationFrame === "undefined") return; this.alignFrame ??= requestAnimationFrame(() => { this.alignFrame = null; alignPurchaseRows(this); }); } private onUserMeEvent = (event: Event) => { const customEvent = event as CustomEvent; void this.onUserMe(customEvent.detail); }; private onOpenCosmeticPreview = (event: Event) => { const customEvent = event as CustomEvent; const target = event.target as Element | null; // A preview from inside a bundle's contents is not a click on a store // card: the item has no card on that tab, and counting it would also hide // a real click on the item's own card later in the visit. if (!target?.closest?.("pack-contents-dialog")) { this.trackClick(customEvent.detail, target); } this.previewingCosmetic = customEvent.detail; this.requestUpdate(); }; private rowObserver: ResizeObserver | null = null; /** Fires when the soonest running sale ends, to refetch its prices. */ private saleEndTimer: ReturnType | null = null; /** Fires when the soonest new item stops being new, to drop its badge. */ private newEndTimer: ReturnType | null = null; /** When newEndTimer is due. */ private newEndAt = 0; /** Retries that refetch while the API's cached catalog still has the sale. */ private saleRetryTimer: ReturnType | null = null; /** Bumped on close, so a sale-end refetch still in flight then is dropped. */ private saleRefetchGeneration = 0; /** Bumped by every catalog fetch, so only the newest one's answer is kept. */ private catalogRequest = 0; /** The latest catalogRequest that has finished, whatever it got. */ private settledCatalogRequest = 0; private alignFrame: number | null = null; async onUserMe(userMeResponse: UserMeResponse | false) { this.userMeResponse = userMeResponse; this.authSettled = true; // Show the new account (the balance in the header) now, not after the // catalog: in the Android app that fetch also waits on Play's prices. this.requestUpdate(); await this.loadCatalog(); this.selectVisible(this.groupsForTab(this.activeTab)); await this.refresh(); } private renderHeader(): TemplateResult { const currency = this.userMeResponse === false ? undefined : this.userMeResponse.player.currency; return modalHeader({ title: translateText("store.title"), onBack: () => this.close(), ariaLabel: translateText("common.back"), rightContent: html`
${ currency ? html`` : "" }
`, }); } private resolvedPurchasables(): ResolvedCosmetic[] { return resolveCosmetics( this.cosmetics, this.userMeResponse, this.affiliateCode, ).filter( (resolved) => resolved.relationship === "purchasable" && this.sellable(resolved), ); } /** * In the Android app Play is the only way to pay, so a currency pack is * listed only at a price Play gave (or when it is bought with in-game * currency) and no subscription is sold. Everything else is unaffected. */ private sellable(resolved: ResolvedCosmetic): boolean { if (!sellsOnlyThroughPlay()) return true; if (resolved.type === "subscription") return false; if (resolved.type !== "pack") return true; const pack = resolved.cosmetic as Pack; return ( this.playPrice(resolved) !== null || currentPrice(pack, "hard") !== undefined || currentPrice(pack, "soft") !== undefined ); } /** Play's price for a currency pack, or null when Play does not sell it. */ private playPrice(resolved: ResolvedCosmetic): string | null { if (resolved.type !== "pack") return null; const pack = resolved.cosmetic as Pack; if (pack.currency !== "hard" || pack.googleProductId === undefined) { return null; } return this.playPrices?.get(pack.googleProductId) ?? null; } private cosmeticsGroups( tab: CosmeticsSubTab, ): readonly (readonly ResolvedCosmetic[])[] { const items = this.resolvedPurchasables(); const skins = groupCosmeticVariants( items.filter( (resolved) => resolved.type === "pattern" || resolved.type === "skin", ), ); const flags = items .filter((resolved) => resolved.type === "flag") .map((r) => [r]); const crowns = items .filter((resolved) => resolved.type === "crown") .map((r) => [r]); if (tab === "sale" || tab === "new") { // A sale (a flash sale's pick included) or a new item can be an effect // or a bundle too, and those live on other tabs; list them here as well // so the banner's "On sale" always leads to the item. const others = items .filter( (resolved) => resolved.type === "effect" || resolved.type === "cosmeticPack", ) .map((r) => [r]); const all = [...skins, ...flags, ...crowns, ...others]; return tab === "sale" ? saleFirst(all.filter(groupOnSale)) : newestFirst(all.filter(groupIsNew)); } return saleFirst( tab === "flags" ? flags : tab === "crowns" ? crowns : skins, ); } private groupsForTab(tab: string): readonly (readonly ResolvedCosmetic[])[] { if (this.affiliateCode) { return groupCosmeticVariants( this.resolvedPurchasables().filter((resolved) => { const c = resolved.cosmetic; return ( c !== null && "affiliateCode" in c && c.affiliateCode === this.affiliateCode ); }), ); } if (tab === "cosmetics") { const groups = this.cosmeticsGroups(this.cosmeticsSubTab); // The sale ended, the last item stopped being new, or the catalog // dropped it, while its tab was open. Not while the latest catalog // fetch is pending: a `sub=new` or `sub=sale` link opens the store // before it arrives, and a refreshed catalog may have what the cached // one lacked. if ( groups.length === 0 && (this.cosmeticsSubTab === "sale" || this.cosmeticsSubTab === "new") && this.cosmetics !== null && this.settledCatalogRequest === this.catalogRequest ) { this.cosmeticsSubTab = "patterns"; return this.cosmeticsGroups("patterns"); } return groups; } if (tab === "effects") { return this.resolvedPurchasables() .filter((resolved) => resolved.type === "effect") .map((resolved) => [resolved]); } if (tab === "packs") { return this.resolvedPurchasables() .filter((resolved) => resolved.type === "pack") .map((resolved) => [resolved]); } if (tab === "bundles") { // Owned and partially owned bundles stay listed (as a status, not a // buy button) so the player can see why one isn't for sale to them. return resolveCosmetics( this.cosmetics, this.userMeResponse, this.affiliateCode, ) .filter( (resolved) => resolved.type === "cosmeticPack" && (resolved.relationship !== "blocked" || this.ownedPackItemNames(resolved).length > 0), ) .map((resolved) => [resolved]); } if (tab === "subscriptions") { return resolveCosmetics( this.cosmetics, this.userMeResponse, this.affiliateCode, ) .filter( (resolved) => resolved.type === "subscription" && ((resolved.relationship === "purchasable" && this.sellable(resolved)) || resolved.relationship === "owned"), ) .map((resolved) => [resolved]); } return []; } private inspect(resolved: ResolvedCosmetic): void { this.inspected = resolved; this.requestUpdate(); } // Activating a bundle also opens its contents: the card only has room to // tile a few items, so the dialog is where each one is shown with its name. private activate(resolved: ResolvedCosmetic): void { this.trackClick(resolved, this.productFor(resolved)); if (resolved.type === "cosmeticPack") this.openedPack = resolved; if (isPreviewableCosmetic(resolved)) this.previewingCosmetic = resolved; this.inspect(resolved); } // Store analytics. The tracker is made on the first open and kept. private tracker: StoreTracker | null = null; /** * Where a card sits in the store; purchases are placed the same way. * Undefined only before a tab is active: no placement is sent then. */ private placementFor(el: Element): StorePlacement | undefined { if (el.closest("[data-store-flash]")) return { kind: "flash" }; if (this.affiliateCode) return { kind: "affiliate" }; const tab = this.activeTab; if (!isStoreTab(tab)) return undefined; if (tab === "cosmetics") { return { kind: "tab", tab, subTab: this.cosmeticsSubTab }; } return { kind: "tab", tab }; } // Cards are tracked under their item key; the tracker folds a pattern's // palette keys into the pattern card's key (`pattern:`), so // data-cosmetic-key stays the palette key the store selects by. private observeProducts(): void { if (this.tracker === null || typeof IntersectionObserver === "undefined") { return; } // One prune per update, not one per card. this.tracker.releaseDetached(); for (const el of this.querySelectorAll( "[data-store-product][data-cosmetic-key]", )) { const key = el.dataset.cosmeticKey; const placement = this.placementFor(el); if (key && placement) this.tracker.observe(el, key, placement); } } /** The tile showing this item, or one of its variants. */ private productFor(resolved: ResolvedCosmetic): Element | null { for (const el of this.querySelectorAll( "[data-store-product][data-cosmetic-key]", )) { const card = el as Partial; if ( el.dataset.cosmeticKey === resolved.key || card.resolved?.key === resolved.key || card.variants?.some((variant) => variant.key === resolved.key) ) { return el; } } return null; } private trackClick(resolved: ResolvedCosmetic, el: Element | null): void { try { const placement = this.placementFor(el ?? this); if (placement) this.tracker?.click(resolved.key, placement); } catch { // Analytics must never break the click. } } private closePack(): void { this.openedPack = null; this.requestUpdate(); } private reconcileInspection( groups: readonly (readonly ResolvedCosmetic[])[], ): void { const visible = groups.flat(); const wanted = this.requestedItem; if (wanted !== null) { const match = visible.find((item) => matchesStoreItem(item.key, wanted)); // The catalog loads after open, so keep the request until its item shows. if (match !== undefined) { this.requestedItem = null; this.inspected = match; return; } } const current = visible.find((item) => item.key === this.inspected?.key); this.inspected = current ?? groups[0]?.[0] ?? null; } private selectVisible( groups: readonly (readonly ResolvedCosmetic[])[], ): void { this.visibleGroups = groups; this.reconcileInspection(groups); } protected onTabEnter(key: string): void { this.selectVisible(this.groupsForTab(key)); this.requestUpdate(); } /** * The sub-tabs to show: "New" only while something is new, "On sale" only * while something is discounted. */ private visibleCosmeticsSubTabs(): CosmeticsSubTab[] { const hasNew = this.cosmeticsGroups("new").length > 0; const hasSale = this.cosmeticsGroups("sale").length > 0; return COSMETICS_SUB_TABS.filter( (tab) => (tab !== "new" || hasNew) && (tab !== "sale" || hasSale), ); } private setCosmeticsSubTab(tab: CosmeticsSubTab): void { this.cosmeticsSubTab = tab; this.selectVisible(this.cosmeticsGroups(tab)); this.requestUpdate(); } /** Display names of the bundle's items the player already owns. */ private ownedPackItemNames(resolved: ResolvedCosmetic): string[] { return ownedPackItems( resolved.cosmetic as CosmeticPack, this.userMeResponse, ).map((item) => { const found = findPackItem(item, resolved.packItems ?? []); return found ? cosmeticSelectionLabel(found) : item.name; }); } // Same box as a purchase button (w-full, min-h-11, text-base) so an owned // tier or bundle reads as a peer of its neighbours' buy action instead of // a small tag tucked to one side of the card. private renderStatus(text: string, muted = false): TemplateResult { return html`${text}`; } private renderCardAction( active: ResolvedCosmetic, userHasSubscription: boolean, ): TemplateResult { if (active.type === "subscription" && active.relationship === "owned") { return this.renderStatus(translateText("store.subscribed")); } if (active.type === "cosmeticPack") { if (active.relationship === "owned") { return this.renderStatus(translateText("store.pack_owned")); } if (active.relationship === "blocked") { return this.renderStatus( translateText("store.pack_partially_owned", { items: this.ownedPackItemNames(active).join(", "), }), true, ); } } return this.renderPurchaseAction(active, userHasSubscription); } private renderCosmeticCards( groups: readonly (readonly ResolvedCosmetic[])[] = this.visibleGroups, userHasSubscription = false, cardClass = "block h-full min-w-0", previewSize: "card" | "detail" = "card", ): TemplateResult { return html`${groups.map((group) => { const focused = group.find((item) => item.key === this.inspected?.key); const active = focused ?? group[0]; const action = this.renderCardAction(active, userHasSubscription); return html` 1 || group[0].type === "pattern" || group[0].type === "skin" ? group : [] } .activeVariantKey=${active.key} .actionContent=${action} state=${focused ? "focused" : "idle"} .onActivate=${(resolved: ResolvedCosmetic) => this.activate(resolved)} .onVariantActivate=${(resolved: ResolvedCosmetic) => this.inspect(resolved)} >`; })}`; } private renderPurchaseAction( resolved: ResolvedCosmetic, userHasSubscription: boolean, ): TemplateResult { const priced = resolved.cosmetic as { name?: string; product?: Product | null; priceHard?: number; priceSoft?: number; listPriceHard?: number; listPriceSoft?: number; promotion?: { endsAt: string }; rarity?: string; } | null; const isPurchasable = resolved.relationship === "purchasable"; // In the Android app the only real-money price is Play's own, in the // player's currency, and the only real-money button is a Play purchase. const playOnly = sellsOnlyThroughPlay(); const playPrice = isPurchasable ? this.playPrice(resolved) : null; // Only packs and subscriptions still check out in USD; cosmetics are // currency-only (their catalog product is always null now, but a cached // cosmetics.json may still carry one — never render a dollar button). const product = isPurchasable && !playOnly && (resolved.type === "pack" || resolved.type === "subscription") ? (priced?.product ?? null) : null; // A tier with no Stripe listing (sold only on Steam) has no `product`; // its price is the tier's own, in cents. const subscriptionDollarPrice = isPurchasable && !playOnly && resolved.type === "subscription" && product === null ? formatUsdCents((resolved.cosmetic as Subscription).priceMonthly) : ""; const dollarPrice = playPrice ?? subscriptionDollarPrice; // The price as the server charges it now: once the item's own sale has // ended that is its list price, whatever the catalog in hand says. const saleEnded = priced !== null && saleHasEnded(priced); const priceHard = isPurchasable && priced ? currentPrice(priced, "hard") : undefined; const priceSoft = isPurchasable && priced ? currentPrice(priced, "soft") : undefined; // Resolved when clicked, from the card holding the button, so a purchase // from the flash hero is placed as flash. // Analytics must never break a purchase: a throw means no placement. const placement = (): StorePlacement | undefined => { try { return this.placementFor(this.productFor(resolved) ?? this); } catch { return undefined; } }; const purchase = (method: "dollar" | "hard" | "soft") => purchaseCosmetic(resolved, method, placement()); // Currency packs check out inline (wallet button / in-page card form) // when the display price parses; anything else — including subscriptions, // which are recurring and not a PaymentIntent — keeps the redirect flow, // which is also what an unparseable price degrades to. const amountCents = resolved.type === "pack" && product !== null && priced?.name !== undefined ? priceStringToCents(product.price) : null; const inlineCheckout = amountCents !== null ? { request: { kind: "currency_pack" as const, packName: priced!.name!, }, amountCents, successMessageKey: "store.currency_pack_purchase_success", placement, } : null; // Reserved currency lines are assigned per visual row by // alignPurchaseRows() once the grid has laid out. return html` purchase("dollar") : undefined } .onPurchaseHard=${ priceHard !== undefined ? () => purchase("hard") : undefined } .onPurchaseSoft=${ priceSoft !== undefined ? () => purchase("soft") : undefined } >`; } private renderBrowserLayout( cards: TemplateResult, gridClass = "grid grid-cols-2 gap-3 sm:grid-cols-3 xl:grid-cols-4", ): TemplateResult { return html`
${cards}
`; } private renderBrowser( groups: readonly (readonly ResolvedCosmetic[])[], options: StoreBrowserOptions, ): TemplateResult { const page = this.pages.page( "store-grid", `${this.affiliateCode ?? ""}:${this.activeTab}:${this.cosmeticsSubTab}`, groups, ); const cards = groups.length === 0 ? options.trailingContent ? html`` : html`
${translateText(options.emptyTranslationKey)}
` : this.renderCosmeticCards( page.items, options.userHasSubscription, options.cardClass, options.previewSize, ); return this.renderBrowserLayout( html`${cards}${page.more}${options.trailingContent ?? ""}`, options.gridClass, ); } // Skins / Flags / Crowns grouped under one top-level tab; a sub-tab bar // (styled like effects-grid's) picks which grid shows. private renderCosmeticsPanel(): TemplateResult { const subTabs = this.visibleCosmeticsSubTabs(); const flash = this.cosmeticsSubTab === "sale" ? flashGroup(this.visibleGroups) : undefined; const emptyKey = this.cosmeticsSubTab === "flags" ? "store.no_flags" : this.cosmeticsSubTab === "crowns" ? "store.no_crowns" : "store.no_skins"; return html`
${subTabs.map((tab) => { const active = this.cosmeticsSubTab === tab; return html``; })}
${ flash ? html`${this.renderFlashHero(flash)} ${(() => { // With the flash item the only thing on sale, the hero is the // whole tab: no "No skins available" under it. const rest = this.visibleGroups.filter( (group) => group !== flash, ); return rest.length > 0 ? this.renderBrowser(rest, { emptyTranslationKey: emptyKey }) : nothing; })()}` : this.renderBrowser(this.visibleGroups, { emptyTranslationKey: emptyKey, }) } ${this.renderPackDialog()} `; } /** * The flash sale's item, leading the On sale tab: its card beside what the * sale is and a clock to the next item. */ private renderFlashHero(group: readonly ResolvedCosmetic[]): TemplateResult { const sale = group .map((resolved) => activeSale(resolved.cosmetic)) .find((found) => found !== null); if (!sale) return html``; return html`
${this.renderCosmeticCards([group])}
${translateText("store.flash_sale")} ${translateText("store.flash_sale_hero_title", { name: cosmeticSelectionLabel(group[0]), percent: sale.percentOff, })} ${translateText("store.flash_sale_hero_body")} ${translateText("store.flash_next_in")}
`; } private renderEffectGrid(): TemplateResult { // A sub-tab per effectType (Boat Trail / Nuke Trail); each tab opens that // type's grid. Tabs are always present, even when a type has nothing to buy. return html` this.activate(item)} .renderPurchaseAction=${(item: ResolvedCosmetic) => this.renderPurchaseAction(item, false)} .onVisiblePurchaseItemsChange=${(items: readonly ResolvedCosmetic[]) => { this.selectVisible(items.map((item) => [item])); this.requestUpdate(); }} >`; } private renderPackGrid(): TemplateResult { // The custom-amount card is always purchasable (priced inline server-side, // no catalog entry), and follows the fixed packs at the end of the grid. // On BOTH rails: the Steam rail sells custom amounts since OPE-337, so // there is no longer a rail on which this card is a dead button. Not in // the Android app, though, where Play sells only its fixed packs; there a // Play that could not price them says so instead. const playOnly = sellsOnlyThroughPlay(); return this.renderBrowser(this.visibleGroups, { emptyTranslationKey: "store.no_packs", trailingContent: !playOnly ? html`` : this.cosmetics !== null && this.playPrices === null ? html`
${translateText("store.play_unavailable")}
` : undefined, gridClass: "flex flex-wrap items-stretch justify-center content-start gap-4 p-4 sm:p-8", cardClass: "block w-[calc(50%-0.5rem)] max-w-48 shrink-0 sm:w-48", emptyClass: "w-full py-8 text-center text-sm font-bold uppercase tracking-wider text-white/40", }); } private renderBundleGrid(): TemplateResult { return html`${this.renderBrowser(this.visibleGroups, { emptyTranslationKey: "store.no_bundles", })}${this.renderPackDialog()}`; } /** * The contents of the bundle a player opened, from Bundles or from * Cosmetics → New / On sale, which list bundles too. */ private renderPackDialog(): TemplateResult | string { // The dialog is portaled above the modal's stacking context, so a preview // opened from one of its items would render underneath it. Yield to the // preview; the dialog comes back when it closes. if (!this.openedPack || this.previewingCosmetic) return ""; return html` this.closePack()} >`; } private renderSubscriptionGrid(): TemplateResult { // Drives the "Switch" label on the other tiers' buy buttons. A granted // player is deliberately NOT counted (OPE-440): they have nothing to // switch from — nobody is billing them — so every tier, theirs included, // is a first purchase and reads as a plain price. const userHasSubscription = this.userMeResponse !== false && paidSubscriptionOf(this.userMeResponse.player) !== null; // The Steam store lists one tier; a lone card in the narrow tile column // reads as a cramped list, so it gets a wider card and a larger preview. const lone = this.visibleGroups.length === 1; return this.renderBrowser(this.visibleGroups, { emptyTranslationKey: "store.no_subscriptions", userHasSubscription, gridClass: "flex flex-wrap items-stretch justify-center content-start gap-4 p-4 sm:p-8", cardClass: lone ? "block w-full max-w-xs shrink-0" : "block w-[calc(50%-0.5rem)] max-w-48 shrink-0 sm:w-48", previewSize: lone ? "detail" : "card", emptyClass: "w-full py-8 text-center text-sm font-bold uppercase tracking-wider text-white/40", }); } /** One line per running sale, under the header. */ private renderSaleBanner(): TemplateResult | string { const sales = runningSales(this.cosmetics); this.scheduleSaleEnd(sales); this.scheduleNewEnd(); if (sales.length === 0) return ""; return html` this.openSaleTab()} >`; } /** Cosmetics → On sale, from the flash sale's banner line. */ private openSaleTab(): void { this.cosmeticsSubTab = "sale"; if (this.activeTab === "cosmetics") { this.setCosmeticsSubTab("sale"); } else { this.setActiveTab("cosmetics"); } } /** * When the soonest running sale ends, refetch the catalog so its items go * back to list price and its banner drops, even if the player never touches * the open store. Rescheduled on every render; cleared on close. */ private scheduleSaleEnd(sales: readonly { endsAt: string }[]): void { if (this.saleEndTimer !== null) clearTimeout(this.saleEndTimer); this.saleEndTimer = null; if (sales.length === 0 || !this.isModalOpen) return; const nextEnd = Math.min(...sales.map((s) => new Date(s.endsAt).getTime())); // setTimeout overflows past ~24.8 days; a later end is rescheduled by a // later render. const delay = Math.min(Math.max(nextEnd - Date.now(), 0), 2 ** 31 - 1); this.saleEndTimer = setTimeout(() => { this.saleEndTimer = null; void this.refetchAfterSaleEnd(0); }, delay); } /** * When the soonest new item stops being new, drop its badge, and the New * tab with its last item. No refetch: the catalog's newUntil already says * when. Rescheduled on every render; cleared on close. */ private scheduleNewEnd(): void { const now = Date.now(); // Something on screen has already stopped being new: the deadline passed // before its timer ran (or the clock jumped), or before the first render. const overdue = (this.newEndTimer !== null && this.newEndAt <= now) || (this.activeTab === "cosmetics" && this.cosmeticsSubTab === "new" && this.affiliateCode === null && this.visibleGroups.some((group) => !groupIsNew(group))); this.clearNewEnd(); if (!this.isModalOpen) return; const ends = this.resolvedPurchasables().flatMap((resolved) => { const at = newUntilMs(resolved.cosmetic); return at !== null && at > now ? [at] : []; }); if (!overdue && ends.length === 0) return; // setTimeout overflows past ~24.8 days; newUntil is at most 14 days out. const delay = overdue ? 0 : Math.min(Math.min(...ends) - now, 2 ** 31 - 1); this.newEndAt = now + delay; this.newEndTimer = setTimeout(() => { this.newEndTimer = null; // Only Cosmetics → New changes which cards it lists; other tabs (an // Effects category, say) keep their own selection and just redraw. if (this.activeTab === "cosmetics" && this.affiliateCode === null) { this.selectVisible(this.groupsForTab(this.activeTab)); } // The cards' own properties haven't changed, so ask them to redraw. for (const card of this.querySelectorAll("cosmetic-card")) { card.requestUpdate(); } this.requestUpdate(); }, delay); } private clearNewEnd(): void { if (this.newEndTimer !== null) clearTimeout(this.newEndTimer); this.newEndTimer = null; } /** * Fetches the catalog and shows it, unless a newer fetch started meanwhile * (sign-in, reopening, a sale ending): an older answer landing last would * otherwise replace a newer catalog. A failed fetch keeps the catalog * already shown rather than emptying the store; the purchase endpoint * charges the live price either way. Returns what this fetch got. */ private async loadCatalog(): Promise { const request = ++this.catalogRequest; try { return await this.fetchCatalog(request); } finally { // An older fetch landing after a newer one started settles nothing. if (request === this.catalogRequest) this.settledCatalogRequest = request; } } private async fetchCatalog(request: number): Promise { const fresh = await fetchCosmetics(); // In the Android app, Play prices the packs it sells, in the player's // own currency. const playPrices = sellsOnlyThroughPlay() ? await fetchPlayPrices(playProductIds(fresh ?? this.cosmetics)) : null; if (request === this.catalogRequest) { this.cosmetics = fresh ?? this.cosmetics; this.playPrices = playPrices; } return fresh; } /** * Refetches the catalog after a sale ends. The API serves cosmetics.json * from a one-minute cache, so the first answer may still carry the ended * sale's prices; while it does, try again, for up to two minutes. */ private async refetchAfterSaleEnd(attempt: number): Promise { const generation = this.saleRefetchGeneration; invalidateCosmetics(); const fresh = await this.loadCatalog(); // Closed (and maybe reopened) since: that open's own fetch wins. if (!this.isModalOpen || generation !== this.saleRefetchGeneration) return; this.selectVisible(this.groupsForTab(this.activeTab)); this.requestUpdate(); if ( (fresh === null || hasEndedSale(this.cosmetics)) && attempt < SALE_END_RETRIES ) { if (this.saleRetryTimer !== null) clearTimeout(this.saleRetryTimer); this.saleRetryTimer = setTimeout(() => { this.saleRetryTimer = null; void this.refetchAfterSaleEnd(attempt + 1); }, SALE_END_RETRY_MS); } } protected renderHeaderSlot() { return html`${this.renderHeader()} ${this.renderSaleBanner()} ${ this.previewingCosmetic ? html` { this.previewingCosmetic = null; this.requestUpdate(); }} >` : "" }`; } protected renderBody(key: string): TemplateResult { if (this.affiliateCode) { return this.renderAffiliateGrid(); } switch (key as StoreTab) { case "cosmetics": return this.renderCosmeticsPanel(); case "bundles": return this.renderBundleGrid(); case "effects": return this.renderEffectGrid(); case "subscriptions": return this.renderSubscriptionGrid(); case "tribes": return this.renderTribeGrid(); case "packs": default: return this.renderPackGrid(); } } private renderTribeGrid(): TemplateResult { // The panel's `false` branch is a sign-in prompt, i.e. a logged-out // state; hold it back until the session is known (see authSettled). if (!this.authSettled) return html``; return html``; } private renderAffiliateGrid(): TemplateResult { return this.renderBrowser(this.visibleGroups, { emptyTranslationKey: "store.no_affiliate_items", }); } protected async onOpen(args?: Record) { this.tracker ??= new StoreTracker(); this.tracker.beginPageView(); // Drain any Steam overlay approval parked before this UI existed. The // main process's "something arrived" nudge is contentless, so one that // fired with no window listening is heard by nobody and sits parked until // something drains it -- which makes this required on every open, not an // optimisation. void reportPendingSteamAuthorizations(); const affiliate = typeof args?.affiliateCode === "string" ? args.affiliateCode : null; this.affiliateCode = affiliate; this.requestedItem = typeof args?.item === "string" ? args.item : null; if (this.requestedItem !== null) { this.cosmeticsSubTab = subTabForItem(this.requestedItem); } // `sub=sale` (the home screen's sale banner) opens Cosmetics → On sale, // `sub=new` Cosmetics → New; groupsForTab falls back to Skins if nothing // is on sale or new by now. if (args?.sub === "sale" || args?.sub === "new") { this.cosmeticsSubTab = args.sub; } // Prices change when a sale starts or ends, so a catalog fetched more than // a minute ago is refetched rather than shown with stale prices. In the // Android app, Play is asked again if it could not price the packs. if ( refreshStaleCosmetics() || this.cosmetics === null || (sellsOnlyThroughPlay() && this.playPrices === null) ) { await this.loadCatalog(); } this.selectVisible(this.groupsForTab(this.activeTab)); await this.refresh(); // A catalog still carrying a sale that has ended (the store was closed // while the sale-end refetch was retrying, then reopened within the // stale window) would show its prices with no banner: refetch it. if (hasEndedSale(this.cosmetics)) void this.refetchAfterSaleEnd(0); } protected onClose(): void { this.tracker?.flush(); if (this.saleEndTimer !== null) clearTimeout(this.saleEndTimer); this.saleEndTimer = null; this.clearNewEnd(); if (this.saleRetryTimer !== null) clearTimeout(this.saleRetryTimer); this.saleRetryTimer = null; this.saleRefetchGeneration++; // The store hides via CSS (inline modal), so the tiles never disconnect // and an open card-payment modal — portaled to — would float over // the play page after Escape closes the store. Close it explicitly. for (const inline of this.querySelectorAll( "inline-checkout", )) { inline.closeCardModal(); } this.affiliateCode = null; this.openedPack = null; this.previewingCosmetic = null; this.pages.reset(); this.requestedItem = null; this.selectVisible(this.groupsForTab(this.activeTab)); } public async refresh() { this.requestUpdate(); } }