Note: After publishing, you may have to bypass your browser's cache to see the changes.

  • Firefox / Safari: Hold Shift while clicking Reload, or press either Ctrl-F5 or Ctrl-R (⌘-R on a Mac)
  • Google Chrome: Press Ctrl-Shift-R (⌘-Shift-R on a Mac)
  • Edge: Hold Ctrl while clicking Refresh, or press Ctrl-F5.
(() => {
	'use strict';

	const KEY      = 'mw-tds-dailystore';
	const VERSION  = 7;
	const DAY      = 86400e3;
	const SEL      = '.tds-dailystore[data-section]';
	const SECTIONS = ['featured', 'skins', 'emotes', 'stickers', 'nametags'];
	const FIELDS   = ['item', 'subtext', 'price', 'currency'];
	const ORDER    = ['daily', 'skins', 'emotes', 'stickers', 'nametags'];
	const api      = new mw.Api();

	const nextReset = (now = Date.now()) => Math.floor(now / DAY) * DAY + DAY;
	const todayUTC = () => new Date().toISOString().slice(0, 10);
	const secsToReset = (now = Date.now()) => Math.round((nextReset(now) - now) / 1000);

	const slim = (day) => {
		const out = { date: String(day.date || '').replace(/\//g, '-') };
		for (const sec of SECTIONS) {
			if (Array.isArray(day[sec])) {
				out[sec] = day[sec].map((it) => {
					const item = {};
					for (const f of FIELDS) if (it[f] != null && it[f] !== '') item[f] = String(it[f]);
					return item;
				});
			}
		}
		return out;
	};

	const hash = (s) => {
		let h = 0x811c9dc5;
		for (let i = 0; i < s.length; i++) h = Math.imul(h ^ s.charCodeAt(i), 16777619);
		return (h >>> 0).toString(36);
	};

	const fetchDay = async (date) => {
		const res = await fetch(`https://lackey.tds.wiki/dailystore?${date ? `date=${encodeURIComponent(date)}` : 'limit=1'}`, {
			credentials: 'omit',
			headers: { Accept: 'application/json' },
		});
		if (!res.ok) throw new Error(`Store API returned HTTP ${res.status}`);
		const json = await res.json();
		const day = Array.isArray(json) ? json[0] : json;
		if (!day || !day.date) throw new Error('No store data yet');
		return slim(day);
	};

	const parse = async (day) => {
		const encoded = JSON.stringify(day).replace(/[&<>[\]{}|_~'=:]/g, (c) => `&#${c.charCodeAt(0)};`);
		const text = `{{#invoke:DailyStore|render|json=${encoded}}}`;
		const ttl = Math.max(60, secsToReset());
		const params = {
			action: 'parse',
			text,
			title: mw.config.get('wgPageName'),
			contentmodel: 'wikitext',
			prop: 'text',
			wrapoutputclass: '',
			disablelimitreport: true,
			disableeditsection: true,
			formatversion: 2,
			uselang: 'content',
			maxage: ttl,
			smaxage: ttl,
		};
		return (await (text.length > 6000 ? api.post(params) : api.get(params))).parse.text;
	};

	const box = (cls, ico, text) => {
		const d = document.createElement('div');
		d.className = cls;
		d.innerHTML = `<span class="ego-i ${ico}" aria-hidden="true"></span>`;
		d.append(text);
		return d;
	};

	let ticking;
	const tick = () => {
		const now = Date.now();
		for (const t of document.querySelectorAll('.tds-dailystore .tds-ds-timer')) {
			const left = (Number(t.dataset.reset) * 1000 || nextReset(now)) - now;
			t.classList.toggle('is-due', left <= 0);
			const out = t.querySelector('.tds-ds-countdown');
			if (out) {
				const s = Math.floor(left / 1000);
				out.textContent = left > 0
					? [Math.floor(s / 3600), Math.floor(s / 60) % 60, s % 60].map((n) => String(n).padStart(2, '0')).join(':')
					: 'any moment';
			}
		}
	};

	const nodesOf = (block) => [...block.cloneNode(true).childNodes].filter(
		(n) => !(n.classList && n.classList.contains('tds-ds-nojs'))
	);

	const apply = (els, html, day) => {
		const tpl = document.createElement('template');
		tpl.innerHTML = html;
		const bundle = tpl.content.querySelector('.tds-ds-bundle') || tpl.content;
		let first = true;
		for (const el of els) {
			const isAll = el.dataset.section === 'all';
			let rendered = isAll;
			if (isAll) {
				const nodes = [];
				for (const key of ORDER) {
					const block = bundle.querySelector(`.tds-dailystore[data-section="${key}"]`);
					if (!block) continue;
					const slot = document.createElement('div');
					slot.className = 'tds-ds-slot';
					slot.dataset.section = key;
					slot.append(...nodesOf(block));
					nodes.push(slot);
				}
				if (bundle.dataset.foot) {
					const foot = document.createElement('div');
					foot.className = 'tds-ds-foot';
					foot.textContent = bundle.dataset.foot;
					nodes.push(foot);
				}
				el.replaceChildren(...nodes);
			} else {
				const block = bundle.querySelector(`.tds-dailystore[data-section="${el.dataset.section}"]`);
				if (block) {
					el.replaceChildren(...nodesOf(block));
					rendered = true;
				}
			}
			if (rendered) {
				el.classList.remove('is-loading', 'is-updating');
				el.classList.add('is-rendered');
				if (isAll) el.classList.add('is-all');
				el.removeAttribute('aria-busy');
			}
			el.dataset.storeDate = day.date;
			if (first && !el.dataset.date && day.date !== todayUTC()) {
				first = false;
				const when = new Date(`${day.date}T00:00:00Z`).toLocaleDateString(undefined, {
					month: 'long',
					day: 'numeric',
					timeZone: 'UTC',
				});
				el.prepend(box('tds-ds-notice', 'i-hourglass-split', `Today's store hasn't been logged yet. Showing ${when}.`));
				for (const t of el.querySelectorAll('.tds-ds-timer')) t.dataset.reset = String(nextReset() / 1000);
			}
			if (window.$) mw.hook('wikipage.content').fire($(el));
		}
		if (!ticking) {
			tick();
			ticking = setInterval(tick, 1000); // probably a better way to tackle this
		}
	};

	const loadGroup = async (date, els) => {
		const cKey = `${KEY}:${date || 'latest'}`;
		const raw = mw.storage.getObject(cKey);
		const cached = raw && raw.v === VERSION && raw.html ? raw : null;
		if (cached) apply(els, cached.html, cached.day);
		try {
			const day = await fetchDay(date);
			const h = hash(JSON.stringify(day));
			if (cached && cached.hash === h) return day;
			for (const el of els) if (el.classList.contains('is-rendered')) el.classList.add('is-updating');
			const html = await parse(day);
			mw.storage.setObject(cKey, { v: VERSION, hash: h, html, day: { date: day.date } }, date ? 30 * 86400 : secsToReset() + 3600);
			apply(els, html, day);
			return day;
		} catch (err) {
			mw.log.warn('[DailyStore]', err);
			if (!cached) {
				for (const el of els) {
					el.classList.remove('is-loading', 'is-updating');
					el.removeAttribute('aria-busy');
					const msg = box('tds-ds-error', 'i-exclamation-triangle', `Couldn't load the daily store (${err.message || err}).`);
					const btn = document.createElement('button');
					btn.type = 'button';
					btn.className = 'tds-ds-retry';
					btn.textContent = 'Retry';
					btn.addEventListener('click', () => {
						for (const b of els) {
							const errBox = b.querySelector('.tds-ds-error');
							if (errBox) errBox.remove();
						}
						loadGroup(date, els);
					}, { once: true });
					msg.append(btn);
					el.replaceChildren(msg);
				}
			}
			return null;
		}
	};

	const scheduleRefresh = (els) => {
		setTimeout(async function poll(tries = 12) {
			const day = await loadGroup('', els);
			if ((!day || day.date !== todayUTC()) && tries > 1) setTimeout(() => poll(tries - 1), 300e3);
			else scheduleRefresh(els);
		}, nextReset() - Date.now() + 60e3);
	};

	mw.hook('wikipage.content').add(($content) => {
		const root = ($content && $content[0]) || document;
		const list = root.matches && root.matches(SEL) ? [root] : [];
		if (root.querySelectorAll) list.push(...root.querySelectorAll(SEL));
		const groups = {};
		for (const el of list) {
			if (!el.dataset.section || el.dataset.section === 'crates' || el.dataset.dsInit) continue;
			el.dataset.dsInit = '1';
			const k = el.dataset.date || '';
			(groups[k] = groups[k] || []).push(el);
		}
		for (const [date, els] of Object.entries(groups)) {
			loadGroup(date, els).then(() => !date && scheduleRefresh(els));
		}
	});
})();