Skip to content

armgit / VERT

Public Imported from GitHub
0

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

feat: clear button dropdown, stopping queued conversions

JovannMC55878cc2da1c
diff --git a/messages/en.json b/messages/en.json
index 70073cd..ed1b0e1 100644
--- a/messages/en.json
+++ b/messages/en.json
@@ -85,7 +85,16 @@
},
"panel": {
"convert_all": "Convert all",
- "download_all": "Download all as .zip",
+ "stop": "Stop all",
+ "stopping": "Stopping conversions…",
+ "clear": {
+ "text": "Clear",
+ "files": "Clear files",
+ "completed": "Clear completed",
+ "failed": "Clear failed",
+ "all": "Clear all"
+ },
+ "download_all": "Download all",
"download_all_toast": "Zipping {count} files ({size}MB) for download. This may take a while for larger files (which may be streamed).",
"remove_all": "Remove all files",
"set_all_to": "Set all to",
diff --git a/src/lib/components/functional/ConversionPanel.svelte b/src/lib/components/functional/ConversionPanel.svelte
index 3284b35..9a12aeb 100644
--- a/src/lib/components/functional/ConversionPanel.svelte
+++ b/src/lib/components/functional/ConversionPanel.svelte
@@ -4,15 +4,26 @@
FolderArchiveIcon,
RefreshCwIcon,
TrashIcon,
+ ChevronDownIcon,
+ SquareIcon,
} from "@lucide/svelte";
import Panel from "../visual/Panel.svelte";
import Dropdown from "./Dropdown.svelte";
- import Tooltip from "../visual/Tooltip.svelte";
import ProgressBar from "../visual/ProgressBar.svelte";
import FormatDropdown from "./FormatDropdown.svelte";
import { categories } from "#lib/converters";
import { m } from "#lib/paraglide/messages";
import { clsx } from "clsx";
+ import { error } from "#lib/util/logger.svelte";
+ import { formatError } from "#lib/util/error";
+ import { ToastManager } from "#lib/util/toast.svelte";
+
+ const converting = $derived(
+ files.queueRunning || files.files.some((file) => file.processing),
+ );
+ const hasFailed = $derived(
+ files.files.some((file) => file.failed && !file.processing),
+ );
const length = $derived(files.files.length);
const progress = $derived(files.files.filter((f) => f.result).length);
@@ -37,6 +48,35 @@
);
});
});
+
+ async function clearFiles(status: "completed" | "failed" | "all") {
+ try {
+ await files.clear(status);
+ } catch (err) {
+ error(
+ ["files"],
+ `error clearing ${status} files: ${formatError(err)}`,
+ );
+ ToastManager.add({ type: "error", message: formatError(err) });
+ }
+ }
+
+ const clearMenuItems = $derived([
+ {
+ label: m["convert.panel.clear.completed"](),
+ disabled: !files.results,
+ onSelect: () => void clearFiles("completed"),
+ },
+ {
+ label: m["convert.panel.clear.failed"](),
+ disabled: !hasFailed,
+ onSelect: () => void clearFiles("failed"),
+ },
+ {
+ label: m["convert.panel.clear.all"](),
+ onSelect: () => void clearFiles("all"),
+ },
+ ]);
</script>
<Panel class="flex flex-col gap-4">
@@ -47,17 +87,34 @@
class="flex flex-col items-center gap-2.5 max-md:w-full md:flex-row"
>
<button
- onclick={() => files.convertAll()}
+ onclick={() =>
+ converting ? files.stopConversions() : files.convertAll()}
+ aria-label={converting
+ ? m["convert.panel.stop"]()
+ : m["convert.panel.convert_all"]()}
+ title={converting
+ ? m["convert.panel.stop"]()
+ : m["convert.panel.convert_all"]()}
class={clsx(
"btn highlight flex gap-3 max-md:w-full",
!$effects && "!scale-100",
compactActions ? "p-4" : "md:max-w-[15.5rem]",
)}
- disabled={!files.allReady}
+ disabled={files.stopping || (!converting && !files.allReady)}
>
- <RefreshCwIcon size="24" />
+ {#if converting}
+ <SquareIcon size="24" />
+ {:else}
+ <RefreshCwIcon size="24" />
+ {/if}
{#if !compactActions}
- <p>{m["convert.panel.convert_all"]()}</p>
+ <p>
+ {files.stopping
+ ? m["convert.panel.stopping"]()
+ : converting
+ ? m["convert.panel.stop"]()
+ : m["convert.panel.convert_all"]()}
+ </p>
{/if}
</button>
<button
@@ -66,7 +123,9 @@
!$effects && "!scale-100",
compactActions ? "p-4" : "md:max-w-[15.5rem]",
)}
- disabled={!files.allReady || !files.results}
+ disabled={converting || files.stopping || !files.results}
+ aria-label={m["convert.panel.download_all"]()}
+ title={m["convert.panel.download_all"]()}
onclick={() => files.downloadAll()}
>
<FolderArchiveIcon size="24" />
@@ -74,35 +133,21 @@
<p>{m["convert.panel.download_all"]()}</p>
{/if}
</button>
- {#if $isMobile}
- <button
- class={clsx(
- "btn flex gap-3 p-4 max-md:w-full",
- !$effects && "!scale-100",
- )}
- disabled={files.files.length === 0}
- onclick={() => files.removeAll()}
- >
+ <Dropdown
+ menuItems={clearMenuItems}
+ ariaLabel={m["convert.panel.clear.files"]()}
+ disabled={files.files.length === 0}
+ buttonClass={clsx(
+ "btn flex gap-3 p-4 text-base max-md:w-full",
+ !$effects && "!scale-100",
+ )}
+ >
+ {#snippet trigger()}
<TrashIcon size="24" />
- <p>{m["convert.panel.remove_all"]()}</p>
- </button>
- {:else}
- <Tooltip
- text={m["convert.panel.remove_all"]()}
- position="right"
- >
- <button
- class={clsx(
- "btn flex gap-3 p-4 max-md:w-full",
- !$effects && "!scale-100",
- )}
- disabled={files.files.length === 0}
- onclick={() => files.removeAll()}
- >
- <TrashIcon size="24" />
- </button>
- </Tooltip>
- {/if}
+ <p>{m["convert.panel.clear.text"]()}</p>
+ <ChevronDownIcon size="16" />
+ {/snippet}
+ </Dropdown>
</div>
<div class="flex h-0.5 w-full bg-separator md:hidden"></div>
{#if manyFiles}
diff --git a/src/lib/components/functional/Dropdown.svelte b/src/lib/components/functional/Dropdown.svelte
index 0f6b5ce..acfd4f8 100644
--- a/src/lib/components/functional/Dropdown.svelte
+++ b/src/lib/components/functional/Dropdown.svelte
@@ -4,25 +4,42 @@
import { quintOut } from "svelte/easing";
import { clsx } from "clsx";
import { popOverlayLayer, pushOverlayLayer } from "#lib/util/overlay";
+ import type { Snippet } from "svelte";
type DropdownStyle = "default" | "settings" | "inline";
+ type DropdownOption =
+ | string
+ | { value: string; label: string; disabled?: boolean };
+ type MenuItem = {
+ label: string;
+ disabled?: boolean;
+ onSelect: () => void;
+ };
type Props = {
- options: string[] | { value: string; label: string }[];
+ options?: DropdownOption[];
+ menuItems?: MenuItem[];
selected?: string;
onselect?: (option: string) => void;
disabled?: boolean;
style?: DropdownStyle;
+ trigger?: Snippet;
+ buttonClass?: string;
+ ariaLabel?: string;
};
let {
options,
selected = $bindable(
- typeof options[0] === "string" ? options[0] : options[0].value,
+ typeof options?.[0] === "string" ? options[0] : options?.[0]?.value,
),
+ menuItems,
onselect,
disabled,
style = "default",
+ trigger,
+ buttonClass,
+ ariaLabel,
}: Props = $props();
let open = $state(false);
@@ -51,19 +68,29 @@
};
});
- const getValue = (option: string | { value: string; label: string }) =>
+ const getValue = (option: DropdownOption) =>
typeof option === "string" ? option : option.value;
- const getLabel = (option: string | { value: string; label: string }) =>
+ const getLabel = (option: DropdownOption) =>
typeof option === "string" ? option : option.label;
- const select = (option: string | { value: string; label: string }) => {
+ const isDisabled = (option: DropdownOption) =>
+ typeof option === "string" ? false : !!option.disabled;
+
+ const select = (option: DropdownOption) => {
+ if (isDisabled(option)) return;
const selectedValue = getValue(option);
selected = selectedValue;
onselect?.(selectedValue);
open = false;
};
+ const selectMenuItem = (item: MenuItem) => {
+ if (item.disabled) return;
+ item.onSelect();
+ open = false;
+ };
+
const toggle = () => {
open = !open;
};
@@ -71,9 +98,14 @@
const updateMenuPosition = () => {
if (open && menuElement && button) {
const rect = button.getBoundingClientRect();
+ const maxMenuWidth = window.innerWidth - 24;
+ menuElement.style.minWidth = `${Math.min(rect.width, maxMenuWidth)}px`;
+ const menuWidth = menuElement.getBoundingClientRect().width;
menuElement.style.top = `${rect.bottom + 4}px`;
- menuElement.style.left = `${rect.left}px`;
- menuElement.style.width = `${rect.width}px`;
+ menuElement.style.left = `${Math.max(
+ 12,
+ Math.min(rect.left, window.innerWidth - menuWidth - 12),
+ )}px`;
}
};
@@ -127,7 +159,7 @@
<div
class={clsx(
"min-w-fit text-center",
- style !== "inline" && "w-full",
+ menuItems ? "max-md:w-full" : style !== "inline" && "w-full",
style === "inline" &&
"inline-flex w-[6.5rem] text-left sm:w-[10.5rem] md:w-52",
style === "default" && "text-xl font-medium",
@@ -137,7 +169,7 @@
>
<button
bind:this={button}
- class={clsx(
+ class={buttonClass ?? clsx(
"relative flex w-full overflow-hidden font-display focus:!outline-none",
style !== "inline" && "bg-button px-3 py-3.5",
style === "inline" && "justify-start",
@@ -147,7 +179,12 @@
)}
onclick={toggle}
{disabled}
+ aria-label={ariaLabel}
+ aria-expanded={open}
>
+ {#if trigger}
+ {@render trigger()}
+ {:else}
<div
class={clsx(
"flex-grow-1 grid min-w-0 grid-cols-1 grid-rows-1 truncate",
@@ -174,12 +211,12 @@
)}
>
{getLabel(
- options.find((opt) => getValue(opt) === selected) ||
+ options?.find((opt) => getValue(opt) === selected) ||
selected,
)}
</p>
{/key}
- {#each options as option (getValue(option))}
+ {#each options ?? [] as option (getValue(option))}
<p
class={clsx(
"pointer-events-none col-start-1 row-start-1",
@@ -196,6 +233,7 @@
? 180
: 0}deg); transition: transform {duration}ms {transition};"
/>
+ {/if}
</button>
</div>
@@ -206,19 +244,39 @@
duration,
easing: quintOut,
}}
- class="bg-background z-[9999] max-h-[23.5vh] overflow-hidden overflow-y-auto rounded-xl bg-panel-alt shadow-xl shadow-black/25"
+ class="bg-background z-[9999] flex max-h-[23.5vh] w-max flex-col items-stretch overflow-hidden overflow-y-auto rounded-xl bg-panel-alt shadow-xl shadow-black/25"
+ style="max-width: calc(100vw - 1.5rem);"
>
- {#each options as option (getValue(option))}
- <button
- data-selected={getValue(option) === selected}
- class={clsx(
- "w-full p-2 px-4 text-left text-sm font-normal text-muted hover:bg-panel",
- getValue(option) === selected && "bg-separator",
- )}
- onclick={() => select(option)}
- >
- {getLabel(option)}
- </button>
- {/each}
+ <!-- menu options (trigger) -->
+ {#if menuItems}
+ {#each menuItems as item (item.label)}
+ <button
+ disabled={item.disabled}
+ class={clsx(
+ "p-2 px-4 text-left text-sm font-normal text-muted hover:bg-panel",
+ item.disabled && "cursor-not-allowed opacity-50",
+ )}
+ onclick={() => selectMenuItem(item)}
+ >
+ {item.label}
+ </button>
+ {/each}
+ {:else}
+ <!-- menu options (select) -->
+ {#each options ?? [] as option (getValue(option))}
+ <button
+ data-selected={getValue(option) === selected}
+ disabled={isDisabled(option)}
+ class={clsx(
+ "p-2 px-4 text-left text-sm font-normal text-muted hover:bg-panel",
+ getValue(option) === selected && "bg-separator",
+ isDisabled(option) && "cursor-not-allowed opacity-50",
+ )}
+ onclick={() => select(option)}
+ >
+ {getLabel(option)}
+ </button>
+ {/each}
+ {/if}
</div>
{/if}
diff --git a/src/lib/store/index.svelte.ts b/src/lib/store/index.svelte.ts
index b767c4b..bdd1bab 100644
--- a/src/lib/store/index.svelte.ts
+++ b/src/lib/store/index.svelte.ts
@@ -64,6 +64,13 @@ function detectSequenceKind(
class Files {
public files = $state<VertFile[]>([]);
+ public queueRunning = $state(false);
+ public stopping = $state(false);
+ private queue: {
+ queue: PQueue;
+ stopped: boolean;
+ stop: () => void;
+ } | null = null;
public async remove(file: VertFile): Promise<void> {
this.files = this.files.filter((entry) => entry !== file);
@@ -75,6 +82,16 @@ class Files {
await Promise.all([...this.files].map((file) => this.remove(file)));
}
+ public async clear(status: "completed" | "failed" | "all"): Promise<void> {
+ const matches = this.files.filter((file) =>
+ status === "all"
+ ? true
+ : !file.processing &&
+ (status === "completed" ? !!file.result : file.failed),
+ );
+ await Promise.all(matches.map((file) => this.remove(file)));
+ }
+
private getRequiredConverters(file: VertFile): Converter[] {
if (file.isZip()) return file.converters;
@@ -169,9 +186,7 @@ class Files {
: this.files.every((file) => this.isReady(file)),
);
- public results = $derived(
- this.files.length === 0 ? false : this.files.every((f) => f.result),
- );
+ public results = $derived(this.files.some((file) => file.result));
private thumbnailQueue = new PQueue({
concurrency: browser ? navigator.hardwareConcurrency || 4 : 4,
@@ -611,34 +626,86 @@ class Files {
}
public async convertAll() {
- const filenames = this.files.map((file) => file.name);
- const promiseFns = this.files.map((f) => () => f.convert());
- const queue = new PQueue({ concurrency: conversionConcurrency() });
- const results = await Promise.allSettled(
- promiseFns.map((fn) => queue.add(fn)),
- );
- for (const [i, result] of results.entries()) {
- if (result.status === "rejected")
- error(
- ["files", "convert"],
- `batch conversion failed for file ${i + 1} (${filenames[i]}): ${result.reason}`,
- );
+ if (this.queueRunning || this.stopping) return;
+
+ const inputs = [...this.files];
+ let stop = () => {};
+ const stopped = new Promise<void>((resolve) => {
+ stop = resolve;
+ });
+ const queue = {
+ queue: new PQueue({ concurrency: conversionConcurrency() }),
+ stopped: false,
+ stop,
+ };
+
+ this.queue = queue;
+ this.queueRunning = true;
+ try {
+ const results = await Promise.allSettled(
+ inputs.map((file) =>
+ queue.queue.add(async () => {
+ if (queue.stopped || !this.files.includes(file)) return;
+ await Promise.race([file.convert(), stopped]);
+ }),
+ ),
+ );
+ for (const [index, result] of results.entries()) {
+ if (result.status === "rejected")
+ error(
+ ["files", "convert"],
+ `batch conversion failed for file ${index + 1} (${inputs[index].name}): ${result.reason}`,
+ );
+ }
+ } finally {
+ this.queue = null;
+ this.queueRunning = false;
+ }
+ }
+
+ public async stopConversions(): Promise<void> {
+ if (this.stopping) return;
+
+ this.stopping = true;
+ const queue = this.queue;
+ if (queue) {
+ queue.stopped = true;
+ queue.queue.pause();
+ }
+
+ try {
+ await Promise.all(this.files.map((file) => file.cancel()));
+ queue?.stop();
+ queue?.queue.start();
+ await queue?.queue.onIdle();
+ log(["files", "convert"], `stopped batch conversions`);
+ } catch (err) {
+ error(
+ ["files", "convert"],
+ `error stopping batch: ${formatError(err)}`,
+ );
+ ToastManager.add({ type: "error", message: formatError(err) });
+ } finally {
+ queue?.stop();
+ queue?.queue.start();
+ this.stopping = false;
}
}
public async downloadAll() {
- if (this.files.length === 0) return;
+ const completed = this.files.filter((file) => file.result);
+ if (completed.length === 0) return;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const dlFiles: any[] = [];
const filenames: string[] = [];
- for (let i = 0; i < this.files.length; i++) {
- const file = this.files[i];
+ for (let i = 0; i < completed.length; i++) {
+ const file = completed[i];
const result = file.result;
if (!result) {
- error(["files"], "No result found");
+ error(["files"], "no result found");
continue;
}
@@ -650,8 +717,8 @@ class Files {
let totalSize = 0;
- for (let i = 0; i < this.files.length; i++) {
- const file = this.files[i];
+ for (let i = 0; i < completed.length; i++) {
+ const file = completed[i];
const result = file.result;
if (!result) continue;
diff --git a/src/lib/types/file.svelte.ts b/src/lib/types/file.svelte.ts
index dad4eec..d33f750 100644
--- a/src/lib/types/file.svelte.ts
+++ b/src/lib/types/file.svelte.ts
@@ -117,6 +117,7 @@ export class VertFile {
public blobUrl = $state<string>();
public processing = $state(false);
public cancelled = $state(false);
+ public failed = $state(false);
public unavailableConverters = $state<Record<string, UnavailableReasons>>(
{},
);
@@ -129,6 +130,7 @@ export class VertFile {
private slowConversionToastId: number | null = null;
private attemptedConverters = new SvelteSet<string>();
private retryingFallback = false;
+ private converting = false;
private postDownload: (() => Promise<void>) | null = null;
private disposal: Promise<void> | null = null;
private disposed = false;
@@ -424,7 +426,9 @@ export class VertFile {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public async convert(...args: any[]) {
- if (this.disposed) return;
+ if (this.disposed || this.converting) return;
+ this.converting = true;
+ this.failed = false;
if (!this.retryingFallback) this.attemptedConverters.clear();
this.cancelled = false;
let res: VertFile | undefined;
@@ -507,7 +511,7 @@ export class VertFile {
if (!converter) throw new Error("No converter found");
const canProceed = await this.confirmServerWarning(converter);
- if (!canProceed) {
+ if (!canProceed || this.cancelled || this.disposed) {
this.cancelled = true;
return;
}
@@ -524,6 +528,8 @@ export class VertFile {
),
});
+ if (this.cancelled || this.disposed) return;
+
for (const change of normalizedSettings.changes) {
log(
["file", "settings"],
@@ -546,6 +552,7 @@ export class VertFile {
log(["file", "convert"], `using converter: ${converter.name}`);
await this.result?.dispose();
+ if (this.cancelled || this.disposed) return;
this.result = null;
this.progress = 0;
this.processing = true;
@@ -583,6 +590,7 @@ export class VertFile {
}
} catch (err) {
if (this.disposed) return;
+ this.failed = !this.cancelled;
if (!this.cancelled) this.toastErr(err);
const compatibleConverters = this.fallbackCandidates();
@@ -644,6 +652,7 @@ export class VertFile {
await this.result?.dispose();
this.result = null;
} finally {
+ this.converting = false;
this.processing = false;
this.activeConverterName = null;
}
@@ -853,11 +862,12 @@ export class VertFile {
}
public async cancel() {
+ if (!this.processing && !this.converting) return;
+ this.cancelled = true;
if (!this.processing) return;
const selectedConverter = this.conversionSettings.converter;
const converterName = selectedConverter || this.activeConverterName;
const converter = this.converters.find((c) => c.name === converterName);
- this.cancelled = true;
try {
if (!converter) return;
await converter.cancel(this);