summaryrefslogtreecommitdiffstatshomepage
path: root/frontend/src/lib/reader/PageView.svelte
blob: 59136b4ca1dbbcf4bb920f4b2f6e9f23bb08e91a (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
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
<script lang="ts">
	import { Direction, Layout, type PageFragment } from '$gql/graphql';
	import { getReaderContext, partition, type Chunk } from '$lib/Reader';
	import { binds } from '$lib/Shortcuts';
	import { src } from '$lib/Utils';
	import ReaderPage from './ReaderPage.svelte';

	const reader = getReaderContext();

	export let direction: Direction;
	export let layout: Layout;

	let chunks: Chunk[] = [];
	let lookup: number[] = [];

	let main: PageFragment;
	let secondary: PageFragment | undefined;

	function gotoChunk(to: number) {
		if (to < 0 || to >= chunks.length) return;

		$reader.page = chunks[to].index;
	}

	function pagesAround(around: number) {
		const peek = (at: number) => {
			if (at < 0 || at >= chunks.length) return [];

			const pages = [chunks[at].main];

			if (chunks[at].secondary) {
				pages.push(chunks[at].secondary);
			}

			return pages;
		};

		return [...peek(lookup[around] + 1), ...peek(lookup[around] - 1)];
	}

	const next = () => gotoChunk(lookup[$reader.page] + 1);
	const prev = () => gotoChunk(lookup[$reader.page] - 1);

	const clickLeft = () => (direction === Direction.LeftToRight ? prev() : next());
	const clickRight = () => (direction === Direction.RightToLeft ? prev() : next());

	function clickMain(event: MouseEvent & { currentTarget: EventTarget | null }) {
		if (event.currentTarget instanceof Element) {
			const rect = event.currentTarget.getBoundingClientRect();

			if (event.clientX - rect.left < rect.width / 2) {
				clickLeft();
			} else {
				clickRight();
			}
		}
	}

	$: [chunks, lookup] = partition($reader.pages, layout);
	$: layout, ({ main, secondary } = chunks[lookup[$reader.page]]);
</script>

<svelte:document
	use:binds={[
		['ArrowLeft', clickLeft],
		['ArrowRight', clickRight],
		['ArrowUp', prev],
		['ArrowDown', next],
		['PageUp', prev],
		['PageDown', next],
		[' ', next],
		['Backspace', prev]
	]}
/>

{#if !secondary}
	<ReaderPage page={main} on:click={clickMain} --justify="center" />
{:else if direction === Direction.LeftToRight}
	<ReaderPage page={main} on:click={prev} --justify="flex-end" />
	<ReaderPage page={secondary} on:click={next} --justify="flex-start" />
{:else}
	<ReaderPage page={secondary} on:click={next} --justify="flex-end" />
	<ReaderPage page={main} on:click={prev} --justify="flex-start" />
{/if}
<div class="invisible absolute">
	{#each pagesAround($reader.page) as page}
		<img src={src(page.image, 'full')} alt="" />
	{/each}
</div>