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 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 | 1x 12x 12x 21x 21x 21x 15x 3x 15x 15x 15x 2x 13x 13x 13x 2x 13x 13x 26x 4x 13x 13x 13x 12x 12x 11x 11x 11x 11x 11x 11x 11x 11x 10x 20x 10x 9x 9x 9x 9x 9x 9x 2x 2x 2x 2x 1x 1x 2x 2x 9x 9x 2x 2x 7x 6x 5x 4x 4x 4x 4x 3x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 4x 4x 7x 7x 7x 7x 1x 1x 1x 1x | // Infinite-scroll for /projects. Fetches server-rendered ProjectCard HTML
// fragments and appends to both the mobile swipe deck and the desktop grid.
// SSR Pagination stays in the DOM as a <noscript> fallback for crawlers.
// The loaded depth lives in the URL (?page=N) so Back returns to the same
// card; see infinite-scroll-history.ts.
import {
parseCards,
prependPages,
recordPage,
restoreFrom,
trackScroll,
} from "./infinite-scroll-history";
export type InfiniteScrollState = {
/** First page whose cards are in the DOM. */
firstPage: number;
currentPage: number;
totalPages: number;
loading: boolean;
done: boolean;
};
export const FETCH_TRIGGER_MARGIN = "600px"; // how early to prefetch the next page
export function readInitialState(root: HTMLElement): InfiniteScrollState {
const currentPage = parseInt(root.dataset.currentPage || "1", 10);
return {
firstPage: currentPage,
currentPage,
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));
// Fragment endpoint preserves all other filters via the query string.
return `/api/projects-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;
}
const cards = parseCards(html);
for (const grid of grids) {
for (const card of cards) {
grid.appendChild(card.cloneNode(true));
}
}
state.currentPage = nextPage;
recordPage(state.firstPage, nextPage);
return nextPage >= state.totalPages;
}
export function init() {
const root = document.querySelector<HTMLElement>(
"[data-infinite-scroll-root]",
);
if (!root || root.dataset.infiniteScrollInitialized) return;
root.dataset.infiniteScrollInitialized = "true";
// Both breakpoints render a vertical grid; the data-projects-grid marker
// distinguishes them so fetched cards append to the right container.
const mobileGrid = root.querySelector<HTMLElement>(
'[data-projects-grid="mobile"]',
);
const desktopGrid = document.querySelector<HTMLElement>(
'[data-projects-grid="desktop"]',
);
const sentinel = document.querySelector<HTMLElement>(
"[data-projects-sentinel]",
);
const loadingEl = document.querySelector<HTMLElement>(
"[data-projects-loading]",
);
const endEl = document.querySelector<HTMLElement>("[data-projects-end]");
const ssrPagination = document.querySelectorAll<HTMLElement>(
"[data-ssr-pagination]",
);
if (!sentinel) return;
const grids = [mobileGrid, desktopGrid].filter(
(g): g is HTMLElement => g !== null,
);
if (grids.length === 0) return;
// JS is running — hide SSR page-number pagination. The <noscript> copy
// underneath stays in the DOM for crawlers.
for (const el of ssrPagination) {
el.hidden = true;
}
const state = readInitialState(root);
// Back to an entry left on page N: the server rendered page N alone, so put
// the pages before it back, then return to the saved offset.
const restore = restoreFrom(state.currentPage);
let restored: Promise<void> = Promise.resolve();
if (restore) {
state.firstPage = restore.first;
state.loading = true;
showLoading(loadingEl, true);
restored = prependPages(
restore.first,
state.currentPage - 1,
buildNextUrl,
grids,
)
.then(() => window.scrollTo(0, restore.y ?? 0))
.catch((err) =>
console.error("[projects] restoring earlier pages failed", err),
)
.finally(() => {
state.loading = false;
showLoading(loadingEl, false);
});
}
void restored.then(trackScroll);
// Already on the last page: nothing to load. No end message either; it
// would appear at load and push the content below it (layout shift).
if (state.currentPage >= state.totalPages) {
state.done = true;
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 {
// IntersectionObserver only fires on transition. If the sentinel is
// still within the trigger zone after we appended cards (common on
// short mobile pages where the horizontal deck doesn't grow the
// document), re-observe so the next page loads too.
observer.unobserve(sentinel);
observer.observe(sentinel);
}
} catch (err) {
console.error("[projects] infinite scroll fetch failed", err);
// Surface SSR pagination again so the user still has a way forward.
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);
// Re-check the sentinel once restored pages have pushed it down.
void restored.then(() => {
observer.unobserve(sentinel);
observer.observe(sentinel);
});
}
// Auto-init at module load (entry-point behavior). Guarded so tests can
// import helpers without triggering init() in jsdom.
/* istanbul ignore next -- auto-init guard */
Eif (typeof document !== "undefined") {
Iif (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init, { once: true });
} else {
// Only auto-init if the root element exists — prevents jsdom-import-time
// side-effects in tests that haven't built a fixture yet.
Iif (document.querySelector("[data-infinite-scroll-root]")) {
init();
}
}
// Astro ClientRouter navigations don't refire DOMContentLoaded; re-init on
// every page-load (Back to /projects included). init() guards double-binding.
document.addEventListener("astro:page-load", init);
}
|