fix: formatdropdown logic rework & bug fixes

This commit is contained in:
Maya 2026-03-06 14:29:47 +03:00
parent 96da202e6c
commit 9164dc8824
No known key found for this signature in database
3 changed files with 133 additions and 226 deletions

View File

@ -30,159 +30,110 @@
dropdownSize = "default", dropdownSize = "default",
file, file,
}: Props = $props(); }: Props = $props();
let open = $state(false); let open = $state(false);
let dropdown = $state<HTMLDivElement>(); let dropdown = $state<HTMLDivElement>();
let currentCategory = $state<string | null>();
let searchQuery = $state("");
let dropdownMenu: HTMLElement | undefined = $state(); let dropdownMenu: HTMLElement | undefined = $state();
let rootCategory: string | null = null;
let dropdownPosition = $state<"left" | "center" | "right">("center"); let dropdownPosition = $state<"left" | "center" | "right">("center");
let showSettingsModal = $state(false);
let currentCategory = $state<string | null>(null);
let searchQuery = $state("");
let rootCategory: string | null = null;
// initialize current category const normalize = (str: string) => str.replace(/^\./, "").toLowerCase();
$effect(() => {
if (currentCategory) return;
log( const shouldExclude = (format: string): boolean =>
["dropdown", "init"], !!(
`initializing category, file: ${file?.name}, from: ${from}`, categories["audio"]?.formats.includes(from ?? "") &&
format === ".gif"
); );
// find the category whose formats overlap most with the converters for this file (or all files) const getFormats = (cat: string) =>
// this finds the best matching category based on the formats supported by the converters (categories[cat]?.formats ?? []).filter((f) => !shouldExclude(f));
const pickCategoryFromConverters = (
convList: VertFile["converters"],
) => {
let bestCategory: string | null = null;
let maxOverlap = 0;
for (const cat of Object.keys(categories)) { const detectCategory = (): string => {
const overlapCount = categories[cat].formats.filter((fmt) => if (from) {
convList.some((conv) => conv.formatStrings().includes(fmt)), // find category containing the input format, if any
).length; const match = Object.keys(categories).find((cat) =>
categories[cat].formats.includes(from),
if (overlapCount > maxOverlap) {
maxOverlap = overlapCount;
bestCategory = cat;
}
}
return bestCategory;
};
// decide which converters to use to detect category:
// - if file provided, prefer its primary converter -- individual file dropdown
// - if no file provided, use all converters from all files -- "set all to" dropdown
const primaryConverter = file ? (file.isZip() ? file.converters[0] : file.findConverters()[0]) : null;
const convertersToCheck = file
? primaryConverter
? [primaryConverter]
: file.converters
: files.files.flatMap((f) => f.converters);
log(
["dropdown", "init"],
`checking converters:`,
convertersToCheck.map((c) => c.formatStrings()),
);
// if file is provided, first try to find its category by input format
let detectedCategory: string | null = null;
if (file && from) {
detectedCategory =
Object.keys(categories).find((cat) =>
categories[cat].formats.includes(from),
) || null;
log(
["dropdown", "init"],
`detected category from input format (${from}):`,
detectedCategory,
); );
if (match) return match;
} }
// fallback to category with most converter overlap if input category not found // else, fall back by finding the category whose formats overlap most with the converters for this file
detectedCategory = // this finds the best matching category based on the formats supported by the converters
detectedCategory || const converters = file
pickCategoryFromConverters(convertersToCheck) || ? file.findConverters()
Object.keys(categories)[0]; : files.files.flatMap((f) => f.findConverters());
log(["dropdown", "init"], `final detected category:`, detectedCategory); let best: string | null = null;
let maxOverlap = 0;
for (const cat of Object.keys(categories)) {
const count = categories[cat].formats.filter((fmt) =>
converters.some((c) => c.formatStrings().includes(fmt)),
).length;
if (count > maxOverlap) {
maxOverlap = count;
best = cat;
}
}
currentCategory = detectedCategory; return best ?? Object.keys(categories)[0];
rootCategory = detectedCategory; };
$effect(() => {
if (currentCategory) return;
const detected = detectCategory();
log(
["dropdown", "init"],
`root category: ${detected} (file: ${file?.name}, from: ${from})`,
);
currentCategory = detected;
rootCategory = detected;
}); });
// other available categories based on current category (e.g. converting between video and audio) // other available categories based on current category (e.g. converting between video and audio)
const availableCategories = $derived.by(() => { const availableCategories = $derived.by(() => {
if (!rootCategory) return Object.keys(categories); if (!rootCategory) return Object.keys(categories);
let finalCategories = Object.keys(categories).filter( let cats = Object.keys(categories).filter(
(cat) => (cat) =>
cat === rootCategory || cat === rootCategory ||
categories[rootCategory!]?.canConvertTo?.includes(cat), categories[rootCategory!]?.canConvertTo?.includes(cat),
); );
// handle special cases // handle special cases
if (from === ".gif" || from === ".webp") finalCategories.push("video"); if (from === ".gif" || from === ".webp") cats.push("video");
if (from === ".apng") { if (from === ".apng") {
//finalCategories.push("image"); // -- buggy, magick can't convert from or to apng properly //cats.push("image"); // -- buggy, magick can't convert from or to apng properly
finalCategories = finalCategories.filter((cat) => cat !== "audio"); cats = cats.filter((cat) => cat !== "audio");
} }
// filter out categories that can't handle large files (due to browser/device limitations) // large videos can't be extracted to audio (browser/device limitations)
if (file && file.isLarge()) { if (file && file.isLarge() && rootCategory === "video")
// if file is large video, disable audio conversion cats = cats.filter((cat) => cat !== "audio");
if (rootCategory === "video")
finalCategories = finalCategories.filter(
(cat) => cat !== "audio",
);
}
return finalCategories; return cats.filter(
(cat) => (categories[cat]?.formats?.length ?? 0) > 0,
);
}); });
const shouldInclude = (format: string, category: string): boolean => {
// if converting from audio to video, dont show gifs
if (
categories["audio"]?.formats.includes(from ?? "") &&
format === ".gif"
) {
return false;
}
return true;
};
const filteredData = $derived.by(() => { const filteredData = $derived.by(() => {
const normalize = (str: string) => str.replace(/^\./, "").toLowerCase();
// if no query, return formats for current category // if no query, return formats for current category
if (!searchQuery) { if (!searchQuery) {
let formats = currentCategory const formats = getFormats(currentCategory ?? "");
? categories[currentCategory].formats.filter((format) =>
shouldInclude(format, currentCategory!),
)
: [];
// if no formats found at all, show everything
if (formats.length === 0) {
const allCategories = Object.keys(categories);
// show formats for current category if set, otherwise all formats
const fallbackFormats =
currentCategory && allCategories.includes(currentCategory)
? categories[currentCategory].formats
: allCategories.flatMap(
(cat) => categories[cat].formats,
);
// if no formats & categories for some reason, fall back and show all categories/formats
if (formats.length === 0 && availableCategories.length === 0) {
log( log(
["dropdown", "filter"], ["dropdown", "filter"],
`no formats found for category ${currentCategory}, showing all categories and formats as fallback`, `no formats or available categories found for file ${file?.name}, falling back to all categories and formats`,
); );
return { return {
categories: allCategories, categories: Object.keys(categories),
formats: fallbackFormats, formats: categories[currentCategory ?? ""]?.formats ?? [],
isFallback: true, isFallback: true,
resolvedCategory: currentCategory,
}; };
} }
@ -190,87 +141,70 @@
categories: availableCategories, categories: availableCategories,
formats, formats,
isFallback: false, isFallback: false,
resolvedCategory: currentCategory,
}; };
} }
const searchLower = normalize(searchQuery);
// find all categories that have formats matching the search query const query = normalize(searchQuery);
const matches = (f: string) =>
normalize(f).includes(query) && !shouldExclude(f);
const matchingCategories = availableCategories.filter((cat) => const matchingCategories = availableCategories.filter((cat) =>
categories[cat].formats.some( (categories[cat]?.formats ?? []).some(matches),
(format) =>
normalize(format).includes(searchLower) &&
shouldInclude(format, cat),
),
); );
if (matchingCategories.length === 0) { if (matchingCategories.length === 0) {
return { return {
categories: availableCategories, categories: availableCategories,
formats: [], formats: [],
isFallback: false, isFallback: false,
resolvedCategory: currentCategory,
}; };
} }
// if current category has no matches, switch to first category that does // stay on current category if it matches, else move to first matched category
const currentCategoryHasMatches = const resolvedCategory =
currentCategory && currentCategory && matchingCategories.includes(currentCategory)
matchingCategories.some((cat) => cat === currentCategory); ? currentCategory
if (!currentCategoryHasMatches && matchingCategories.length > 0) { : matchingCategories[0];
const newCategory = matchingCategories[0];
currentCategory = newCategory;
}
// return formats only from the current category that match the search const formats = (categories[resolvedCategory ?? ""]?.formats ?? [])
let filteredFormats = currentCategory .filter(matches)
? categories[currentCategory].formats.filter( .sort((a, b) => {
(format) => // exact matches first, then original order
normalize(format).includes(searchLower) && const aExact = normalize(a) === query;
shouldInclude(format, currentCategory!), const bExact = normalize(b) === query;
) if (aExact !== bExact) return aExact ? -1 : 1;
: []; return 0;
});
// sorting exact match first, then others
filteredFormats = filteredFormats.sort((a, b) => {
const aExact = normalize(a) === searchLower;
const bExact = normalize(b) === searchLower;
if (aExact && !bExact) return -1;
if (!aExact && bExact) return 1;
return 0;
});
// show categories with matches, formats from within resolved category
return { return {
categories: categories: matchingCategories,
matchingCategories.length > 0 formats,
? matchingCategories
: availableCategories,
formats: filteredFormats,
isFallback: false, isFallback: false,
resolvedCategory,
}; };
}); });
$effect(() => {
if (
filteredData.resolvedCategory &&
filteredData.resolvedCategory !== currentCategory
)
currentCategory = filteredData.resolvedCategory;
});
const selectOption = (option: string) => { const selectOption = (option: string) => {
selected = option; selected = option;
open = false; open = false;
// save user's selection to dropdownStates for this session // save user's selection to dropdownStates for this session
if (file) { if (file) {
dropdownStates.update((states) => { dropdownStates.update((states) => ({
const updated = { ...states, [file.name]: option }; ...states,
return updated; [file.name]: option,
}); }));
}
// find the category of this option if it's not in the current category
if (
currentCategory &&
!categories[currentCategory].formats.includes(option)
) {
const formatCategory = Object.keys(categories).find((cat) =>
categories[cat].formats.includes(option),
);
if (formatCategory) {
currentCategory = formatCategory;
}
} }
onselect?.(option); onselect?.(option);
@ -282,39 +216,14 @@
}; };
const handleSearch = (event: Event) => { const handleSearch = (event: Event) => {
const query = (event.target as HTMLInputElement).value; searchQuery = (event.target as HTMLInputElement).value;
searchQuery = query;
// find which categories have matching formats & switch
if (query) {
const queryLower = query.toLowerCase();
const categoriesWithMatches = availableCategories.filter((cat) =>
categories[cat].formats.some((format) =>
format.toLowerCase().includes(queryLower),
),
);
if (categoriesWithMatches.length > 0) {
const currentHasMatches =
currentCategory &&
categories[currentCategory].formats.some((format) =>
format.toLowerCase().includes(queryLower),
);
if (!currentHasMatches) {
currentCategory = categoriesWithMatches[0];
}
}
}
}; };
const onEnter = (event: KeyboardEvent) => { const onEnter = (event: KeyboardEvent) => {
if (event.key === "Enter") { if (event.key !== "Enter") return;
event.preventDefault(); event.preventDefault();
if (filteredData.formats.length > 0) { if (filteredData.formats.length > 0)
selectOption(filteredData.formats[0]); selectOption(filteredData.formats[0]);
}
}
}; };
const clickDropdown = () => { const clickDropdown = () => {
@ -327,25 +236,18 @@
const viewportWidth = window.innerWidth; const viewportWidth = window.innerWidth;
let dropdownWidth: number; let dropdownWidth: number;
if (dropdownSize === "large") { if (dropdownSize === "large") dropdownWidth = rect.width * 3.2;
dropdownWidth = rect.width * 3.2; else if (dropdownSize === "default")
} else if (dropdownSize === "default") {
dropdownWidth = rect.width * 2.5; dropdownWidth = rect.width * 2.5;
} else { else dropdownWidth = rect.width * 1.5;
dropdownWidth = rect.width * 1.5;
}
const centerX = rect.left + rect.width / 2; const centerX = rect.left + rect.width / 2;
const leftEdge = centerX - dropdownWidth / 2; const leftEdge = centerX - dropdownWidth / 2;
const rightEdge = centerX + dropdownWidth / 2; const rightEdge = centerX + dropdownWidth / 2;
if (leftEdge < 0) { if (leftEdge < 0) dropdownPosition = "left";
dropdownPosition = "left"; else if (rightEdge > viewportWidth) dropdownPosition = "right";
} else if (rightEdge > viewportWidth) { else dropdownPosition = "center";
dropdownPosition = "right";
} else {
dropdownPosition = "center";
}
} }
setTimeout(() => { setTimeout(() => {
@ -387,8 +289,6 @@
newFiles.forEach((f) => files.add(f)); newFiles.forEach((f) => files.add(f));
}; };
let showSettingsModal = $state(false);
const settings = () => { const settings = () => {
if (!file) return; if (!file) return;
showSettingsModal = true; showSettingsModal = true;
@ -396,9 +296,7 @@
onMount(() => { onMount(() => {
const handleClickOutside = (e: MouseEvent) => { const handleClickOutside = (e: MouseEvent) => {
if (dropdown && !dropdown.contains(e.target as Node)) { if (dropdown && !dropdown.contains(e.target as Node)) open = false;
open = false;
}
}; };
const handleResize = () => { const handleResize = () => {

View File

@ -43,11 +43,17 @@ categories.audio.formats =
.find((c) => c.name === "ffmpeg") .find((c) => c.name === "ffmpeg")
?.supportedFormats.filter((f) => f.toSupported && f.isNative) ?.supportedFormats.filter((f) => f.toSupported && f.isNative)
.map((f) => f.name) || []; .map((f) => f.name) || [];
categories.video.formats = categories.video.formats = [
converters ...new Set(
.find((c) => c.name === "mediabunny") converters
?.supportedFormats.filter((f) => f.toSupported && f.isNative) .filter((c) => c.name === "mediabunny" || c.name === "vertd")
.map((f) => f.name) || []; .flatMap((c) =>
c.supportedFormats
.filter((f) => f.toSupported && f.isNative)
.map((f) => f.name),
),
),
];
categories.image.formats = categories.image.formats =
converters converters
.find((c) => c.name === "imagemagick") .find((c) => c.name === "imagemagick")

View File

@ -8,6 +8,7 @@ import type {
ConversionSettings, ConversionSettings,
SettingDefinition, SettingDefinition,
} from "./conversion-settings"; } from "./conversion-settings";
import { log } from "$lib/util/logger";
const MAX_BLOB_SIZE_LIMIT = 2 * 1024 * 1024 * 1024; // 2GB const MAX_BLOB_SIZE_LIMIT = 2 * 1024 * 1024 * 1024; // 2GB
@ -98,10 +99,12 @@ export class VertFile {
public supportsStreaming(): boolean { public supportsStreaming(): boolean {
// only vertd (video/gif -> video/gif) supports streaming // only vertd (video/gif -> video/gif) supports streaming
// rest of converters need entire file in memory, limited by ArrayBuffer limits // rest of converters need entire file in memory, limited by ArrayBuffer limits
const converter = this.isZip() const availableConverters = this.isZip()
? this.converters[0] ? this.converters
: this.findConverters()[0]; : this.findConverters();
return converter?.name === "vertd"; return availableConverters.some(
(converter) => converter.name === "vertd",
);
} }
constructor(file: File, to: string, blobUrl?: string) { constructor(file: File, to: string, blobUrl?: string) {
@ -119,8 +122,8 @@ export class VertFile {
this.download = this.download.bind(this); this.download = this.download.bind(this);
this.blobUrl = blobUrl; this.blobUrl = blobUrl;
console.log(`VertFile: ${this.name}`); log(
console.log( ["file", "init"],
`findConverters: ${this.findConverters() `findConverters: ${this.findConverters()
.map((c) => c.name) .map((c) => c.name)
.join(", ")}`, .join(", ")}`,