summaryrefslogblamecommitdiffstatshomepage
path: root/frontend/src/lib/Reader.svelte.ts
blob: f5a5322acc71e489ef703cfd279a4b37ee6f2683 (plain) (tree)


























































                                                                                         
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<ReaderContext>('reader', new ReaderContext());
}

export function getReaderContext() {
	return getContext<ReaderContext>('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<number>(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];
}