import { Layout, type PageFragment } from '$gql/graphql'; import { getContext, setContext } from 'svelte'; export interface Chunk { main: PageFragment; secondary?: PageFragment; index: number; } class ReaderContext { visible = $state(false); sidebar = $state(false); pages: PageFragment[] = $state([]); page = $state(0); open = (page: number) => { this.page = page; this.visible = true; }; } export function initReaderContext() { return setContext('reader', new ReaderContext()); } export function getReaderContext() { return getContext('reader'); } export function partition(pages: PageFragment[], layout: Layout): [Chunk[], number[]] { const single = layout === Layout.Single; const offset = layout === Layout.DoubleOffset; const chunks: Chunk[] = []; const lookup: number[] = Array(pages.length); for (let chunkIndex = 0, pageIndex = 0; pageIndex < pages.length; chunkIndex++) { const wide = () => pages[pageIndex].image.aspectRatio > 1; const nextPage = () => { lookup[pageIndex] = chunkIndex; return pages[pageIndex++]; }; const offsetFirst = pageIndex === 0 && offset; const full = single || wide() || offsetFirst; const chunk: Chunk = { index: pageIndex, main: nextPage() }; if (!full && pageIndex < pages.length) { if (!wide()) { chunk.secondary = nextPage(); } } chunks.push(chunk); } return [chunks, lookup]; }