aboutsummaryrefslogtreecommitdiff
path: root/src/lib/Tools/Hayai.svelte
blob: b782f579a417745efccd661115d34f1674d0b21e (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
<script lang="ts">
	import { onMount } from 'svelte';
	import JSZip from 'jszip';

	let fileInput: HTMLInputElement | null = null;

	const handleFileUpload = async () => {
		if (!fileInput || !fileInput.files || fileInput.files.length === 0) return;

		const file = fileInput.files[0];
		const reader = new FileReader();

		reader.onload = async (event) => {
			const zip = await JSZip.loadAsync((event.target as FileReader).result as ArrayBuffer);
			const newZip = new JSZip();

			for (const relativePath in zip.files) {
				const zipEntry = zip.files[relativePath];

				if (zipEntry.dir) {
					newZip.folder(relativePath);
				} else if (relativePath.endsWith('.xhtml') || relativePath.endsWith('.html')) {
					newZip.file(relativePath, applyBionicReading(await zipEntry.async('text')));
				} else {
					newZip.file(relativePath, await zipEntry.async('arraybuffer'));
				}
			}

			downloadEpub(
				await newZip.generateAsync({ type: 'blob' }),
				`${file.name.split('.epub')[0]}_hayai.epub`
			);
		};

		reader.readAsArrayBuffer(file);
	};

	const applyBionicReading = (content: string) => {
		const contentParser = new DOMParser().parseFromString(content, 'text/html');

		for (const paragraph of contentParser.getElementsByTagName('p'))
			paragraph.innerHTML = (paragraph.textContent ?? '')
				.split(/\s+/)
				.map((word) => {
					const strippedWord = word.replace(/[^\w]/g, '');
					const halfLength = Math.ceil(strippedWord.length * 0.6);
					const firstHalf = `<strong>${strippedWord.slice(0, halfLength)}</strong>`;
					const secondHalf = strippedWord.slice(halfLength);
					return `${firstHalf}${secondHalf}${word.slice(strippedWord.length)}`;
				})
				.join(' ');

		return contentParser.documentElement.outerHTML;
	};

	const downloadEpub = (blob: Blob | MediaSource, fileName: string) => {
		const link = document.createElement('a');

		link.href = URL.createObjectURL(blob);
		link.download = fileName;

		link.click();
		URL.revokeObjectURL(link.href);
	};

	onMount(() => (fileInput = document.getElementById('epub-file') as HTMLInputElement));
</script>

<div class="card">
	Upload an EPUB, receive a "<b>bi</b>onic" <b>EP</b>UB.

	<p />

	<input type="file" id="epub-file" accept=".epub" on:change={handleFileUpload} />
</div>