All files / src/scripts pros-infinite-scroll.ts

97.46% Statements 77/79
93.02% Branches 40/43
100% Functions 10/10
97.18% Lines 69/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165                      1x     10x                 17x 17x 17x       11x       4x             14x 14x     14x 2x   12x   12x 12x 2x     12x 1x 1x   3x       1x 2x 4x         12x 12x       10x     10x 9x   9x     9x     9x 9x     9x 9x       9x   8x 16x   8x   7x 7x     7x   7x 1x 1x 1x     6x   6x 5x   4x 4x 4x 4x 3x 1x 1x 1x   2x 2x     1x 1x 1x   1x 1x   4x 4x           6x       1x 1x     1x               1x    
// Infinite-scroll for /pros. Fetches server-rendered ProCard HTML fragments
// and appends to both the mobile vertical grid and the desktop grid. SSR
// Pagination on desktop stays in the DOM as a fallback for crawlers / no-JS.
 
export type InfiniteScrollState = {
	currentPage: number;
	totalPages: number;
	loading: boolean;
	done: boolean;
};
 
export const FETCH_TRIGGER_MARGIN = "600px";
 
export function readInitialState(root: HTMLElement): InfiniteScrollState {
	return {
		currentPage: parseInt(root.dataset.currentPage || "1", 10),
		totalPages: parseInt(root.dataset.totalPages || "1", 10),
		loading: false,
		done: false,
	};
}
 
export function buildNextUrl(page: number): string {
	const url = new URL(window.location.href);
	url.searchParams.set("page", String(page));
	return `/api/pros-fragment${url.search}`;
}
 
export function showLoading(el: HTMLElement | null, visible: boolean) {
	if (el) el.hidden = !visible;
}
 
export function showEndMessage(el: HTMLElement | null) {
	if (el) el.hidden = false;
}
 
export async function fetchNextPage(
	state: InfiniteScrollState,
	grids: HTMLElement[],
): Promise<boolean> {
	const nextPage = state.currentPage + 1;
	const res = await fetch(buildNextUrl(nextPage), {
		headers: { Accept: "text/html" },
	});
	if (!res.ok) {
		throw new Error(`fragment fetch failed: ${res.status}`);
	}
	const html = await res.text();
 
	const totalPagesHeader = res.headers.get("X-Total-Pages");
	if (totalPagesHeader) {
		state.totalPages = parseInt(totalPagesHeader, 10) || state.totalPages;
	}
 
	if (html.trim()) {
		const parsed = new DOMParser().parseFromString(html, "text/html");
		const cards = Array.from(parsed.body.children).filter(
			(el) =>
				el.tagName !== "STYLE" &&
				el.tagName !== "SCRIPT" &&
				el.tagName !== "TEMPLATE",
		) as HTMLElement[];
		for (const grid of grids) {
			for (const card of cards) {
				grid.appendChild(card.cloneNode(true));
			}
		}
	}
 
	state.currentPage = nextPage;
	return nextPage >= state.totalPages;
}
 
export function init() {
	const root = document.querySelector<HTMLElement>(
		"[data-pros-infinite-scroll-root]",
	);
	if (!root || root.dataset.infiniteScrollInitialized) return;
	root.dataset.infiniteScrollInitialized = "true";
 
	const mobileGrid = root.querySelector<HTMLElement>(
		'[data-pros-grid="mobile"]',
	);
	const desktopGrid = document.querySelector<HTMLElement>(
		'[data-pros-grid="desktop"]',
	);
	const sentinel = document.querySelector<HTMLElement>("[data-pros-sentinel]");
	const loadingEl = document.querySelector<HTMLElement>(
		"[data-pros-loading]",
	);
	const endEl = document.querySelector<HTMLElement>("[data-pros-end]");
	const ssrPagination = document.querySelectorAll<HTMLElement>(
		"[data-pros-ssr-pagination]",
	);
 
	if (!sentinel) return;
 
	const grids = [mobileGrid, desktopGrid].filter(
		(g): g is HTMLElement => g !== null,
	);
	if (grids.length === 0) return;
 
	for (const el of ssrPagination) {
		el.hidden = true;
	}
 
	const state = readInitialState(root);
 
	if (state.currentPage >= state.totalPages) {
		state.done = true;
		showEndMessage(endEl);
		return;
	}
 
	const observer = new IntersectionObserver(
		async (entries) => {
			if (state.loading || state.done) return;
			if (!entries.some((e) => e.isIntersecting)) return;
 
			state.loading = true;
			showLoading(loadingEl, true);
			try {
				const finished = await fetchNextPage(state, grids);
				if (finished) {
					state.done = true;
					observer.disconnect();
					showEndMessage(endEl);
				} else {
					observer.unobserve(sentinel);
					observer.observe(sentinel);
				}
			} catch (err) {
				console.error("[pros] infinite scroll fetch failed", err);
				for (const el of ssrPagination) {
					el.hidden = false;
				}
				state.done = true;
				observer.disconnect();
			} finally {
				state.loading = false;
				showLoading(loadingEl, false);
			}
		},
		{ rootMargin: FETCH_TRIGGER_MARGIN, threshold: 0 },
	);
 
	observer.observe(sentinel);
}
 
/* istanbul ignore next -- auto-init guard */
Eif (typeof document !== "undefined") {
	Iif (document.readyState === "loading") {
		document.addEventListener("DOMContentLoaded", init, { once: true });
	} else {
		Iif (document.querySelector("[data-pros-infinite-scroll-root]")) {
			init();
		}
	}
	// Astro ClientRouter view transitions don't refire DOMContentLoaded.
	// Re-init on every page-load so navigating back to /pros rebinds the
	// observer. The dataset guard inside init() prevents double-binding when
	// the same root persists across transitions.
	document.addEventListener("astro:page-load", init);
}