The next-generation file converter. Open source, fully local* and free forever.
feat: disable format if unavailable + show reason
JovannMCacb9fde475af
diff --git a/messages/en.json b/messages/en.jsonindex 66c81f7..9abbc82 100644--- a/messages/en.json+++ b/messages/en.json@@ -88,7 +88,11 @@"placeholder": "Search format","no_formats": "No formats available","no_results": "No formats match your search",- "fallback": "An error occurred loading available categories & formats, showing everything."+ "fallback": "An error occurred loading available categories & formats, showing everything.",+ "disabled": {+ "no_converter": "No compatible converter is available for {from} to {to}.",+ "vertd_size_limit": "This file cannot be converted to this format as the file's size is too large for the selected vertd server."+ }},"settings": {"settings": "Settings",diff --git a/src/lib/components/functional/FormatDropdown.svelte b/src/lib/components/functional/FormatDropdown.svelteindex c7b3169..b8ae53b 100644--- a/src/lib/components/functional/FormatDropdown.svelte+++ b/src/lib/components/functional/FormatDropdown.svelte@@ -15,6 +15,9 @@import { VertFile } from "$lib/types";import { log } from "$lib/util/logger";import FancyInput from "./FancyInput.svelte";+ import Tooltip from "../visual/Tooltip.svelte";+ import { vertdSizeLimit } from "$lib/sections/settings/vertdSettings.svelte";+ import { formatBytes } from "$lib/util/file";type Props = {categories: Categories;@@ -72,21 +75,54 @@const normalize = (str: string) => str.replace(/^\./, "").toLowerCase();- const shouldExclude = (format: string): boolean => {- if (- categories["audio"]?.formats.includes(from ?? "") &&- format === ".gif"- )- return true;+ const isUnavailable = (format: string): boolean =>+ !!file && !file.hasAvailableConverter(file.from, format);- if (!file || file.unavailableConverters.length === 0) return false;+ const getUnavailableReason = (format: string): string => {+ if (!file) return "";+ // check if any compatible converters are available for this file and format+ const compatible = file.converters.filter((converter) => {+ const fromInfo = converter.supportedFormats.find(+ (info) => info.name === file.from,+ );+ const toInfo = converter.supportedFormats.find(+ (info) => info.name === format,+ );+ return (+ !!fromInfo &&+ !!toInfo &&+ fromInfo.fromSupported &&+ toInfo.toSupported &&+ (fromInfo.isNative || toInfo.isNative)+ );+ });++ const largeFile = compatible.some(+ (converter) =>+ converter.name === "vertd" &&+ converter.isReady() &&+ file.unavailableConverters[converter.name] ===+ "vertd-size-limit",+ );+ if (largeFile)+ return m["convert.dropdown.disabled.vertd_size_limit"]({+ limit: formatBytes($vertdSizeLimit),+ fileSize: formatBytes(file.size),+ });- return !file.hasAvailableConverter(file.from, format);+ return m["convert.dropdown.disabled.no_converter"]({+ from: file.from,+ to: format,+ });};+ const shouldHide = (format: string): boolean =>+ categories["audio"]?.formats.includes(from ?? "") === true &&+ format === ".gif";+const getFormats = (cat: string) => {let formats = (categories[cat]?.formats ?? []).filter(- (f) => !shouldExclude(f),+ (f) => !shouldHide(f),);// if imageSequence is checked, filter image category to sequence formats only@@ -220,7 +256,7 @@const matches = (f: string, cat?: string) => {if (!normalize(f).includes(query) ||- shouldExclude(f) ||+ shouldHide(f) ||hiddenFormats.includes(f))return false;@@ -285,9 +321,9 @@$effect(() => {// this thing checks if selected format is still valid with the current filters (imageSequence or search query) and falls back if not- const allUnfilteredFormats = availableCategories.flatMap((cat) =>- getFormats(cat),- );+ const allUnfilteredFormats = availableCategories+ .flatMap((cat) => getFormats(cat))+ .filter((format) => !isUnavailable(format));if (allowEmpty && !selected) return;@@ -301,6 +337,7 @@});const selectOption = (option: string) => {+ if (isUnavailable(option)) return;selected = option;// save user's selection to dropdownStates for this session@@ -559,19 +596,35 @@bind:this={formatList}>{#if filteredData.formats.length > 0}- {#each filteredData.formats as format}- <button- data-selected={format === selected}- class="w-full p-2 text-center rounded-xl- {format === selected- ? 'bg-accent text-black'- : format === from- ? 'bg-separator'- : 'hover:bg-panel'}"- onclick={() => selectOption(format)}- >- {format}- </button>+ {#each filteredData.formats as format (format)}+ {@const unavailable = isUnavailable(format)}+ {#if unavailable}+ <Tooltip text={getUnavailableReason(format)}>+ <button+ data-selected={format === selected}+ aria-disabled="true"+ class="w-full p-2 text-center rounded-xl opacity-45 cursor-not-allowed"+ tabindex="0"+ onclick={(e) => e.preventDefault()}+ onkeydown={(e) => e.preventDefault()}+ >+ {format}+ </button>+ </Tooltip>+ {:else}+ <button+ data-selected={format === selected}+ class="w-full p-2 text-center rounded-xl+ {format === selected+ ? 'bg-accent text-black'+ : format === from+ ? 'bg-separator'+ : 'hover:bg-panel'}"+ onclick={() => selectOption(format)}+ >+ {format}+ </button>+ {/if}{/each}{:else}<div class="col-span-3 text-center p-4 text-muted">diff --git a/src/lib/converters/converter.svelte.ts b/src/lib/converters/converter.svelte.tsindex 38f4533..511aa99 100644--- a/src/lib/converters/converter.svelte.ts+++ b/src/lib/converters/converter.svelte.ts@@ -129,6 +129,10 @@ export class Converter {return true;}+ public isReady(): boolean {+ return this.status === "ready" || this.status === "partially-ready";+ }+public formatStrings(predicate?: (f: FormatInfo) => boolean) {if (predicate) {return this.supportedFormats.filter(predicate).map((f) => f.name);diff --git a/src/lib/converters/vertd/vertd.svelte.ts b/src/lib/converters/vertd/vertd.svelte.tsindex f2fd54b..1878ced 100644--- a/src/lib/converters/vertd/vertd.svelte.ts+++ b/src/lib/converters/vertd/vertd.svelte.ts@@ -728,7 +728,7 @@ export class VertdConverter extends Converter {rejectConversion(new Error("vertd websocket error"));};- ws.onclose = (event) => {+ ws.onclose = (e) => {if (settled) return;if (this.cancelledConversions.has(input.id)) {rejectConversion(new Error("Conversion cancelled"));@@ -736,7 +736,7 @@ export class VertdConverter extends Converter {}this.error(- `ws closed unexpectedly for file ${input.name} (code: ${event.code})`,+ `ws closed unexpectedly for file ${input.name} (code: ${e.code})`,);rejectConversion(new Error("vertd websocket closed unexpectedly"),diff --git a/src/lib/store/index.svelte.ts b/src/lib/store/index.svelte.tsindex a886551..f13c535 100644--- a/src/lib/store/index.svelte.ts+++ b/src/lib/store/index.svelte.ts@@ -38,22 +38,13 @@ class Files {return selectedConverter ? [selectedConverter] : compatibleConverters;}- private isConverterReady(converter: Converter): boolean {- return (- converter.status === "ready" ||- converter.status === "partially-ready" // no idea where this could be used actually in a real converter- );- }-public isReady(file: VertFile): boolean {const requiredConverters = this.getRequiredConverters(file);if (requiredConverters.length === 0) return false;return (!file.processing &&- requiredConverters.some((converter) =>- this.isConverterReady(converter),- )+ requiredConverters.some((converter) => converter.isReady()));}diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.tsindex 70aee0a..780f878 100644--- a/src/lib/types/file.svelte.ts+++ b/src/lib/types/file.svelte.ts@@ -18,6 +18,8 @@ import { fileTypeFromBuffer } from "file-type";const LARGE_FILE = 2 * 1024 * 1024 * 1024; // 2GB+export type UnavailableReasons = "vertd-size-limit" | "other-reason"; // find more stuff to add+export class VertFile {public id: string = Math.random().toString(36).slice(2, 8);public readonly file: File;@@ -35,7 +37,7 @@ export class VertFile {public blobUrl = $state<string>();public processing = $state(false);public cancelled = $state(false);- public unavailableConverters = $state<string[]>([]);+ public unavailableConverters = $state<Record<string, UnavailableReasons>>({});public converters: Converter[] = [];private fallbackToastId: number | null = null;@@ -100,11 +102,14 @@ export class VertFile {public findConverters(supportedFormats: string[] = [this.from],- unavailableConverters: string[] = [],+ unavailableConverters: Record<string, UnavailableReasons> = {},) {return this.converters.filter((converter) => {- if (unavailableConverters.includes(converter.name))+ if (+ unavailableConverters[converter.name] ||+ !converter.isReady()+ )return false;if (!converter@@ -152,7 +157,10 @@ export class VertFile {// returns true if there is at least one converter that can convert from `from` to `to`public hasAvailableConverter(from: string, to: string): boolean {return this.converters.some((converter) => {- if (this.unavailableConverters.includes(converter.name))+ if (+ this.unavailableConverters[converter.name] ||+ !converter.isReady()+ )return false;const fromInfo = converter.supportedFormats.find(diff --git a/src/lib/util/sw.ts b/src/lib/util/sw.tsindex b781635..9086edb 100644--- a/src/lib/util/sw.ts+++ b/src/lib/util/sw.ts@@ -53,11 +53,11 @@ class ServiceWorkerManager {reject(new Error("Timeout waiting for cache info"));}, 5000);- messageChannel.port1.onmessage = (event) => {+ messageChannel.port1.onmessage = (e) => {if (settled) return;settled = true;clearTimeout(timeoutId);- resolve(event.data);+ resolve(e.data);};navigator.serviceWorker?.controller?.postMessage(@@ -81,15 +81,15 @@ class ServiceWorkerManager {reject(new Error("Timeout waiting for cache clear"));}, 10000);- messageChannel.port1.onmessage = (event) => {+ messageChannel.port1.onmessage = (e) => {if (settled) return;settled = true;clearTimeout(timeoutId);- if (event.data.success) {+ if (e.data.success) {resolve();} else {reject(- new Error(event.data.error || "Failed to clear cache"),+ new Error(e.data.error || "Failed to clear cache"),);}};diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelteindex 14f24d0..17f9e88 100644--- a/src/routes/+layout.svelte+++ b/src/routes/+layout.svelte@@ -20,10 +20,8 @@import "$lib/css/app.scss";import { browser } from "$app/environment";import { initStores as initAnimStores } from "$lib/util/animation";- import {- useVertdSizeLimit,- VertdInstance,- } from "$lib/sections/settings/vertdSettings.svelte";+ 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 { log } from "$lib/util/logger";@@ -92,15 +90,6 @@Settings.instance.load();- if (!DISABLE_ALL_EXTERNAL_REQUESTS) {- VertdInstance.instance- .url()- .then((u) => fetch(`${u}/api/version`))- .then((res) => {- if (res.ok) $vertdLoaded = true;- });- }-// detect if insecure contextif (!window.isSecureContext) {log(@@ -120,6 +109,29 @@};});+ $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(() => {enablePlausible =!!PUB_PLAUSIBLE_URL &&diff --git a/src/routes/convert/+page.svelte b/src/routes/convert/+page.svelteindex 5a290a1..47b767e 100644--- a/src/routes/convert/+page.svelte+++ b/src/routes/convert/+page.svelte@@ -50,14 +50,22 @@const exceedsLimit = file.size > limit;const unavailable = file.unavailableConverters;const shouldMarkUnavailable = exceedsLimit- ? !unavailable.includes("vertd")- : unavailable.includes("vertd");+ ? !unavailable["vertd"]+ : unavailable["vertd"];if (shouldMarkUnavailable) {file.unavailableConverters = exceedsLimit- ? [...unavailable, "vertd"]- : unavailable.filter((name) => name !== "vertd");+ ? { ...unavailable, vertd: "vertd-size-limit" }+ : Object.fromEntries(+ Object.entries(unavailable).filter(+ ([key]) => key !== "vertd",+ ),+ );}+ if (exceedsLimit)+ file.unavailableConverters["vertd"] = "vertd-size-limit";+ else delete file.unavailableConverters["vertd"];+if (!exceedsLimit || vertdSizeWarningFileIds.has(file.id)) continue;vertdSizeWarningFileIds.add(file.id);@@ -68,7 +76,6 @@fileSize: formatBytes(file.size),limit: formatBytes(limit),}),- disappearing: false,});}});diff --git a/static/sw.js b/static/sw.jsindex 77ce5c3..786f84a 100644--- a/static/sw.js+++ b/static/sw.js@@ -24,10 +24,10 @@ function shouldCacheUrl(url) {);}-self.addEventListener("install", (event) => {+self.addEventListener("install", (e) => {console.log("[SW] installing service worker");- event.waitUntil(+ e.waitUntil(caches.open(CACHE_NAME).then((cache) => {const staticFiles = WASM_FILES.filter((file) =>file.startsWith("/"),@@ -44,8 +44,8 @@ self.addEventListener("install", (event) => {self.skipWaiting();});-self.addEventListener("activate", (event) => {- event.waitUntil(+self.addEventListener("activate", (e) => {+ e.waitUntil(caches.keys().then((cacheNames) => {@@ -67,15 +67,15 @@ self.addEventListener("activate", (event) => {);});-self.addEventListener("fetch", (event) => {- const request = event.request;+self.addEventListener("fetch", (e) => {+ const request = e.request;if (!shouldCacheUrl(request.url)) {return; // Let the request go through normally if not a target URL}// else intercept request- event.respondWith(+ e.respondWith(caches.match(request).then((cachedResponse) => {if (cachedResponse) {console.log("[SW] serving from cache:", request.url);@@ -123,14 +123,14 @@ self.addEventListener("fetch", (event) => {);});-self.addEventListener("message", (event) => {- if (!event.data) return;- const type = event.data.type;- const port = event.ports?.[0];+self.addEventListener("message", (e) => {+ if (!e.data) return;+ const type = e.data.type;+ const port = e.ports?.[0];if (type === "GET_CACHE_INFO") {if (!port) return;- event.waitUntil(+ e.waitUntil(caches.open(CACHE_NAME).then(async (cache) => {const keys = await cache.keys();let totalSize = 0;@@ -172,7 +172,7 @@ self.addEventListener("message", (event) => {if (type === "CLEAR_CACHE") {if (!port) return;- event.waitUntil(+ e.waitUntil(caches.delete(CACHE_NAME).then(() => {