summaryrefslogtreecommitdiffstatshomepage
path: root/frontend/src/lib/Reader.ts
blob: 8777b9b420ed184e2ee5884e33fb6d408fb22b56 (plain) (blame)
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
import { Layout, type PageFragment } from '$gql/graphql';
import { getContext, setContext } from 'svelte';
import { writable, type Writable } from 'svelte/store';

export interface Chunk {
	main: PageFragment;
	secondary?: PageFragment;
	index: number;
}

class ReaderContext {
	visible = false;
	sidebar = false;
	pages: PageFragment[] = [];
	page = 0;

	open(page: number) {
		this.page = page;
		this.visible = true;

		return this;
	}
}

export function initReaderContext() {
	return setContext<Writable<ReaderContext>>('reader', writable(new ReaderContext()));
}

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