Skip to content

armgit / VERT

Public Imported from GitHub
0

The next-generation file converter. Open source, fully local* and free forever.

7.9 KB
Raw Blame
<script lang="ts">
	import { onMount } from "svelte";
	import { goto, beforeNavigate, afterNavigate } from "$app/navigation";
	import { resolve } from "$app/paths";

	import { PUB_PLAUSIBLE_URL, PUB_HOSTNAME } from "$app/env/public";
	import { DISABLE_ALL_EXTERNAL_REQUESTS, VERT_NAME } from "#lib/util/consts";
	import * as Layout from "#lib/components/layout";
	import * as Navbar from "#lib/components/layout/Navbar";
	import { Settings } from "#lib/sections/settings/index.svelte";
	import {
		files,
		isMobile,
		effects,
		theme,
		dropping,
		vertdLoaded,
		locale,
		updateLocale,
	} from "#lib/store/index.svelte";
	import "#lib/css/app.scss";
	import { browser } from "$app/env";
	import { initStores } from "#lib/util/animation";
	import { useVertdSizeLimit } from "#lib/sections/settings/vertdSettings.svelte";
	import { converters } from "#lib/converters";
	import { ToastManager } from "#lib/util/toast.svelte";
	import { m } from "#lib/paraglide/messages";
	import { getLocale } from "#lib/paraglide/runtime";
	import {
		addLog,
		installConsoleCapture,
		log,
	} from "#lib/util/logger.svelte";

	let { children } = $props();
	let isAprilFools = $state(false);
	let enablePlausible = $derived(
		!!PUB_PLAUSIBLE_URL &&
			Settings.instance.settings.plausible &&
			!DISABLE_ALL_EXTERNAL_REQUESTS,
	);

	// eslint-disable-next-line svelte/prefer-svelte-reactivity
	let scrollPositions = new Map<string, number>();

	beforeNavigate((nav) => {
		if (!nav.from || !$isMobile) return;
		scrollPositions.set(nav.from.url.pathname, window.scrollY);
	});

	afterNavigate((nav) => {
		if (!$isMobile) return;
		const scrollY = nav.to
			? scrollPositions.get(nav.to.url.pathname) || 0
			: 0;
		window.scrollTo(0, scrollY);
	});

	const dropFiles = async (e: DragEvent) => {
		e.preventDefault();
		dropping.set(false);
		const oldLength = files.files.length;
		await files.addAsync(e.dataTransfer?.files);
		if (files.files.length !== oldLength) goto(resolve("/convert"));
	};

	const handleDrag = (e: DragEvent, drag: boolean) => {
		e.preventDefault();
		dropping.set(drag);
	};

	const handlePaste = async (e: ClipboardEvent) => {
		const clipboardData = e.clipboardData;
		if (!clipboardData || !clipboardData.files.length) return;
		e.preventDefault();
		const oldLength = files.files.length;
		await files.addAsync(clipboardData.files);
		if (files.files.length !== oldLength) goto(resolve("/convert"));
	};

	onMount(() => {
		// captures console output for debugging page
		installConsoleCapture();

		// catch global errors and unhandled promise rejections for debugging page
		const handleGlobalError = (event: ErrorEvent) =>
			addLog("error", ["window"], event.message);
		const handleUnhandledRejection = (event: PromiseRejectionEvent) =>
			addLog("error", ["window", "unhandledrejection"], event.reason);
		window.addEventListener("error", handleGlobalError);
		window.addEventListener("unhandledrejection", handleUnhandledRejection);

		const now = new Date();
		isAprilFools = now.getDate() === 1 && now.getMonth() === 3;

		initStores();

		const handleResize = () => {
			isMobile.set(window.innerWidth <= 768);
		};

		isMobile.set(window.innerWidth <= 768); // initial page load
		window.addEventListener("resize", handleResize); // handle window resize
		window.addEventListener("paste", handlePaste);

		effects.set(localStorage.getItem("effects") !== "false"); // defaults to true if not set
		theme.set(
			(localStorage.getItem("theme") as "light" | "dark") || "light",
		);
		const storedLocale = localStorage.getItem("locale");
		if (storedLocale) updateLocale(storedLocale);
		else locale.set(getLocale()); // e.g. resolved from preferredLanguage

		Settings.instance.load();

		// detect if insecure context
		if (!window.isSecureContext) {
			log(
				["layout"],
				'Insecure context (HTTP) detected, some features may not work as expected -- you may want to enable "PUB_DISABLE_FAILURE_BLOCKS" on local deployments.',
			);
			ToastManager.add({
				type: "warning",
				message: m["toast.insecure_context"](),
				disappearing: false,
			});
		}

		return () => {
			window.removeEventListener("paste", handlePaste);
			window.removeEventListener("resize", handleResize);
			window.removeEventListener("error", handleGlobalError);
			window.removeEventListener(
				"unhandledrejection",
				handleUnhandledRejection,
			);
		};
	});

	$effect(() => {
		if (DISABLE_ALL_EXTERNAL_REQUESTS) return;
		let cancelled = false;
		const vertd = converters.find(
			(converter) => converter.name === "vertd",
		);
		if (!vertd) return;

		void vertd
			.valid()
			.then((valid) => {
				if (cancelled) return;
				vertdLoaded.set(valid);
				vertd.status = valid ? "ready" : "error";
				if (!valid) log(["layout", "vertd"], "health check failed");
			})
			.catch((error) => {
				if (cancelled) return;
				vertdLoaded.set(false);
				vertd.status = "error";
				log(["layout", "vertd"], `health check failed: ${error}`);
			});

		return () => {
			cancelled = true;
		};
	});

	$effect(() => {
		if (!enablePlausible && browser) {
			// reset pushState on opt-out so that plausible stops firing events on page navigation
			history.pushState = History.prototype.pushState;
		}
	});

	onMount(() => {
		// query vertd server for size limit on mount and on settings change
		useVertdSizeLimit();
	});
</script>

<svelte:head>
	<title>{VERT_NAME}</title>
	<meta name="theme-color" content="#F2ABEE" />
	<meta
		name="title"
		content="{VERT_NAME} — Free, fast, and awesome file converter"
	/>
	<meta
		name="description"
		content="With VERT, you can quickly convert any image, video, audio, and document file. No ads, no tracking, open source, and all processing is done on your device."
	/>
	<meta property="og:url" content="https://vert.sh" />
	<meta property="og:type" content="website" />
	<meta
		property="og:title"
		content="{VERT_NAME} — Free, fast, and awesome file converter"
	/>
	<meta
		property="og:description"
		content="With VERT, you can quickly convert any image, video, audio, and document file. No ads, no tracking, open source, and all processing is done on your device."
	/>
	<meta property="og:image" content="https://vert.sh/VERT_Feature.webp" />
	<meta name="twitter:card" content="summary_large_image" />
	<meta property="twitter:domain" content="vert.sh" />
	<meta property="twitter:url" content="https://vert.sh" />
	<meta
		property="twitter:title"
		content="{VERT_NAME} — Free, fast, and awesome file converter"
	/>
	<meta
		property="twitter:description"
		content="With VERT, you can quickly convert any image, video, audio, and document file. No ads, no tracking, open source, and all processing is done on your device."
	/>
	<meta
		property="twitter:image"
		content="https://vert.sh/VERT_Feature.webp"
	/>
	<link rel="manifest" href="/manifest.json" />
	<link rel="canonical" href="https://vert.sh/" />
	{#if enablePlausible}
		<script
			defer
			data-domain={PUB_HOSTNAME || "vert.sh"}
			src="{PUB_PLAUSIBLE_URL}/js/script.js"
		></script>
	{/if}
	{#if isAprilFools}
		<style>
			* {
				font-family: "Comic Sans MS", "Comic Sans", cursive !important;
			}
		</style>
	{/if}
</svelte:head>

<!-- FIXME: if user resizes between desktop/mobile, highlight of page disappears (only shows on original size) -->
{#key $locale}
	<div
		class="flex h-full min-h-screen w-full flex-col overflow-x-hidden"
		ondrop={dropFiles}
		ondragenter={(e) => handleDrag(e, true)}
		ondragover={(e) => handleDrag(e, true)}
		ondragleave={(e) => handleDrag(e, false)}
		role="region"
	>
		<Layout.UploadRegion />

		<div>
			<Layout.MobileLogo />
			<Navbar.Desktop />
		</div>

		<!-- 
		SvelteKit throws the following warning when developing - safe to ignore as we render the children in this component:
		`<slot />` or `{@render ...}` tag missing — inner content will not be rendered
		-->
		<Layout.PageContent {children} />

		<Layout.Toasts />
		<Layout.Dialogs />

		<div>
			<Layout.Footer />
			<Navbar.Mobile />
		</div>
	</div>
{/key}

<!-- Gradients placed here to prevent it overlapping in transitions -->
<Layout.Gradients />