mirror of
https://github.com/Ku6epXBOCTuK/easy-png-tools.git
synced 2026-11-13 17:08:20 +00:00
feat: add download size limit warning
This commit is contained in:
@@ -15,6 +15,9 @@
|
||||
dims?: string;
|
||||
note?: string;
|
||||
noteTone?: "warning" | "info";
|
||||
// Runtime warnings (chain/download events): shown as badges next to the
|
||||
// derived result note, but from a different source.
|
||||
warnings?: string[];
|
||||
actions?: Snippet;
|
||||
}
|
||||
let {
|
||||
@@ -27,6 +30,7 @@
|
||||
dims = undefined,
|
||||
note = undefined,
|
||||
noteTone = "warning",
|
||||
warnings = [],
|
||||
actions = undefined,
|
||||
}: Props = $props();
|
||||
</script>
|
||||
@@ -52,6 +56,9 @@
|
||||
{#if note}
|
||||
<Badge tone={noteTone} label={note} />
|
||||
{/if}
|
||||
{#each warnings as warning (warning)}
|
||||
<Badge tone="warning" label={warning} role="status" />
|
||||
{/each}
|
||||
</span>
|
||||
</figcaption>
|
||||
<div class="canvas" class:checker={mode === "image"}>
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
resultKind?: ResultKind;
|
||||
result: PixelImage | null;
|
||||
resultNote?: ResultNote | null;
|
||||
warnings?: string[];
|
||||
fileResult?: FileResult | null;
|
||||
textResult?: string | null;
|
||||
textVars?: Record<string, string | number>;
|
||||
@@ -28,6 +29,7 @@
|
||||
resultKind = "image",
|
||||
result,
|
||||
resultNote = null,
|
||||
warnings = [],
|
||||
fileResult = null,
|
||||
textResult = null,
|
||||
textVars = undefined,
|
||||
@@ -68,6 +70,7 @@
|
||||
dims={resultDims}
|
||||
note={resultNote ? t(resultNote.key) : undefined}
|
||||
noteTone={resultNote?.tone ?? "warning"}
|
||||
{warnings}
|
||||
>
|
||||
{#snippet actions()}
|
||||
{#if ontogglemask}
|
||||
|
||||
@@ -123,7 +123,11 @@
|
||||
const stepFileSets = $derived(runner.stepFileSets);
|
||||
const runWarnings = $derived(runner.runWarnings);
|
||||
const displayError = $derived(runner.displayError);
|
||||
const allWarnings = $derived([...upload.sourceWarnings, ...runWarnings]);
|
||||
const warningTexts = $derived(
|
||||
[...upload.sourceWarnings, ...runWarnings, ...runner.downloadWarnings].map(
|
||||
chainWarningText,
|
||||
),
|
||||
);
|
||||
|
||||
const masks = createStepMasks({
|
||||
steps: () => steps,
|
||||
@@ -316,6 +320,7 @@
|
||||
resultKind={displayResultKind}
|
||||
result={out}
|
||||
{resultNote}
|
||||
warnings={warningTexts}
|
||||
{fileResult}
|
||||
{textResult}
|
||||
textVars={verdictVars}
|
||||
@@ -440,9 +445,6 @@
|
||||
{#if errorText}
|
||||
<p class="error" role="alert">{errorText}</p>
|
||||
{/if}
|
||||
{#each allWarnings as w (chainWarningText(w))}
|
||||
<p class="warn" role="status">{chainWarningText(w)}</p>
|
||||
{/each}
|
||||
<StepReorderOverlay {steps} dnd={stepDnd} />
|
||||
</DragDropProvider>
|
||||
</div>
|
||||
@@ -620,11 +622,6 @@
|
||||
.no-schema {
|
||||
font: var(--font-size-s) var(--font-mono);
|
||||
}
|
||||
.warn {
|
||||
margin: var(--space-s) 0 0;
|
||||
color: var(--color-warning);
|
||||
font: var(--font-size-s) var(--font-mono);
|
||||
}
|
||||
@media (--bp-tablet) {
|
||||
.workspace,
|
||||
.workspace.aligned {
|
||||
|
||||
@@ -56,6 +56,8 @@ interface RunnerState {
|
||||
// Full named set per step (batch/fan-out); intermediate tiles show a grid.
|
||||
stepFileSets: ToolImageFile[][];
|
||||
runWarnings: ChainWarning[];
|
||||
// Size-limit feedback from the last download (limit unreachable etc.).
|
||||
downloadWarnings: ChainWarning[];
|
||||
displayError: DisplayError | null;
|
||||
}
|
||||
|
||||
@@ -153,10 +155,29 @@ async function download(s: RunnerState, ctx: SchemaToolRunnerCtx) {
|
||||
const q = ctx.quality();
|
||||
const limit = ctx.limitKb();
|
||||
const quality = q !== undefined ? q / 100 : undefined;
|
||||
const blob = limit
|
||||
? await fitWithinBytes(s.result, out.mime, limit * 1024, quality, encode)
|
||||
: await encode(s.result, out.mime, quality);
|
||||
downloadBlob(blob, `${ctx.pageSlug()}.${out.ext}`);
|
||||
s.downloadWarnings = [];
|
||||
if (limit) {
|
||||
const fitted = await fitWithinBytes(
|
||||
s.result,
|
||||
out.mime,
|
||||
limit * 1024,
|
||||
quality,
|
||||
encode,
|
||||
);
|
||||
if (fitted.achievedBytes > limit * 1024) {
|
||||
s.downloadWarnings = [
|
||||
{
|
||||
kind: "sizeLimitMiss",
|
||||
limitKb: limit,
|
||||
actualKb: Math.ceil(fitted.achievedBytes / 1024),
|
||||
},
|
||||
];
|
||||
}
|
||||
downloadBlob(fitted.blob, `${ctx.pageSlug()}.${out.ext}`);
|
||||
} else {
|
||||
const blob = await encode(s.result, out.mime, quality);
|
||||
downloadBlob(blob, `${ctx.pageSlug()}.${out.ext}`);
|
||||
}
|
||||
} catch (e) {
|
||||
s.displayError = toDisplayError(e);
|
||||
} finally {
|
||||
@@ -193,6 +214,7 @@ function clearResults(s: RunnerState) {
|
||||
s.fileResult = null;
|
||||
s.textResult = null;
|
||||
s.verdictVars = undefined;
|
||||
s.downloadWarnings = [];
|
||||
s.displayError = null;
|
||||
}
|
||||
|
||||
@@ -211,6 +233,7 @@ export function createSchemaToolRunner(ctx: SchemaToolRunnerCtx) {
|
||||
stepResults: [],
|
||||
stepFileSets: [],
|
||||
runWarnings: [],
|
||||
downloadWarnings: [],
|
||||
displayError: null,
|
||||
});
|
||||
return {
|
||||
@@ -244,6 +267,9 @@ export function createSchemaToolRunner(ctx: SchemaToolRunnerCtx) {
|
||||
get runWarnings() {
|
||||
return s.runWarnings;
|
||||
},
|
||||
get downloadWarnings() {
|
||||
return s.downloadWarnings;
|
||||
},
|
||||
get displayError() {
|
||||
return s.displayError;
|
||||
},
|
||||
|
||||
@@ -3,7 +3,16 @@ import {
|
||||
COMPRESSION_LEVELS,
|
||||
findMaxColorsWithin,
|
||||
findQualityWithin,
|
||||
fitWithinBytes,
|
||||
} from "./compress";
|
||||
import { createPixelImage, type PixelImage } from "./types";
|
||||
|
||||
const img: PixelImage = createPixelImage(4, 4);
|
||||
const blobOf = (size: number) => new Blob([new Uint8Array(size)]);
|
||||
const encodeByQuality =
|
||||
(sizeOf: (q: number) => number) =>
|
||||
async (_img: PixelImage, _mime: string, quality?: number) =>
|
||||
blobOf(sizeOf(Math.round((quality ?? 1) * 100)));
|
||||
|
||||
describe("COMPRESSION_LEVELS", () => {
|
||||
it("presets ordered by descending colors", () => {
|
||||
@@ -77,3 +86,31 @@ describe("findQualityWithin", () => {
|
||||
expect(calls).toBeLessThanOrEqual(10); // log2(99)+2 probes
|
||||
});
|
||||
});
|
||||
|
||||
describe("fitWithinBytes", () => {
|
||||
it("bmp ignores the limit and reports the raw size", async () => {
|
||||
const r = await fitWithinBytes(img, "image/bmp", 100, undefined, async () =>
|
||||
blobOf(5000),
|
||||
);
|
||||
expect(r.achievedBytes).toBe(5000);
|
||||
expect(r.achievedBytes).toBeGreaterThan(100);
|
||||
});
|
||||
|
||||
it("returns the initial encode when it already fits", async () => {
|
||||
const encode = encodeByQuality(() => 500);
|
||||
const r = await fitWithinBytes(img, "image/jpeg", 1000, 0.8, encode);
|
||||
expect(r.achievedBytes).toBe(500);
|
||||
});
|
||||
|
||||
it("lossy: searches quality until the target fits", async () => {
|
||||
const encode = encodeByQuality((q) => 500 + q * 50);
|
||||
const r = await fitWithinBytes(img, "image/jpeg", 5000, 1, encode);
|
||||
expect(r.achievedBytes).toBeLessThanOrEqual(5000);
|
||||
});
|
||||
|
||||
it("lossy: unreachable target reports achievedBytes above the limit", async () => {
|
||||
const encode = encodeByQuality((q) => 500 + q * 50);
|
||||
const r = await fitWithinBytes(img, "image/webp", 100, 1, encode);
|
||||
expect(r.achievedBytes).toBeGreaterThan(100);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -91,6 +91,12 @@ export type EncodeFn = (
|
||||
quality?: number,
|
||||
) => Promise<Blob>;
|
||||
|
||||
export interface FitWithinBytesResult {
|
||||
blob: Blob;
|
||||
/** Size of the returned blob; > targetBytes means the limit was unreachable. */
|
||||
achievedBytes: number;
|
||||
}
|
||||
|
||||
/** Encodes img to fit targetBytes (quality search for lossy, color count for
|
||||
* PNG; BMP as-is). `encodeFn` injected (core/io.encode): policy stays DOM-free. */
|
||||
export async function fitWithinBytes(
|
||||
@@ -99,18 +105,24 @@ export async function fitWithinBytes(
|
||||
targetBytes: number,
|
||||
quality: number | undefined,
|
||||
encodeFn: EncodeFn,
|
||||
): Promise<Blob> {
|
||||
if (mime === "image/bmp") return encodeFn(img, mime);
|
||||
): Promise<FitWithinBytesResult> {
|
||||
if (mime === "image/bmp") {
|
||||
const blob = await encodeFn(img, mime);
|
||||
return { blob, achievedBytes: blob.size };
|
||||
}
|
||||
const initial = await encodeFn(img, mime, quality);
|
||||
if (initial.size <= targetBytes) return initial;
|
||||
if (initial.size <= targetBytes)
|
||||
return { blob: initial, achievedBytes: initial.size };
|
||||
if (mime === "image/png") {
|
||||
const encodeSize = async (k: number) =>
|
||||
(await encodeFn(quantizeImage(img, k).image, mime)).size;
|
||||
const k = await findMaxColorsWithin(targetBytes, 256, encodeSize);
|
||||
return encodeFn(quantizeImage(img, k).image, mime);
|
||||
const blob = await encodeFn(quantizeImage(img, k).image, mime);
|
||||
return { blob, achievedBytes: blob.size };
|
||||
}
|
||||
const encodeSize = async (q: number) =>
|
||||
(await encodeFn(img, mime, q / 100)).size;
|
||||
const q = await findQualityWithin(targetBytes, encodeSize);
|
||||
return encodeFn(img, mime, q / 100);
|
||||
const blob = await encodeFn(img, mime, q / 100);
|
||||
return { blob, achievedBytes: blob.size };
|
||||
}
|
||||
|
||||
@@ -67,6 +67,8 @@ export const en: Dict = {
|
||||
warnFirstOnly:
|
||||
"Step {n}: analyze works on one image — showing the first of {total}",
|
||||
warnSourceSkip: "{skipped} of {total} files could not be read",
|
||||
warnSizeLimitMiss:
|
||||
"Could not fit into {limit} KB — downloaded file is {actual} KB",
|
||||
},
|
||||
savedChains: {
|
||||
pageTitle: "Saved pipelines — easy-png-tools",
|
||||
|
||||
@@ -69,6 +69,8 @@ export const ru: Dict = {
|
||||
warnFirstOnly:
|
||||
"Шаг {n}: анализ работает с одним изображением — показан первый из {total}",
|
||||
warnSourceSkip: "{skipped} из {total} файлов не удалось прочитать",
|
||||
warnSizeLimitMiss:
|
||||
"Не удалось ужаться до {limit} КБ — скачан файл на {actual} КБ",
|
||||
},
|
||||
savedChains: {
|
||||
pageTitle: "Сохранённые пайплайны — easy-png-tools",
|
||||
|
||||
@@ -80,6 +80,11 @@ export function chainWarningText(w: ChainWarning): string {
|
||||
skipped: w.skipped,
|
||||
total: w.total,
|
||||
});
|
||||
case "sizeLimitMiss":
|
||||
return t("chain.warnSizeLimitMiss", {
|
||||
limit: w.limitKb,
|
||||
actual: w.actualKb,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,8 @@ export type ChainExecutor = (
|
||||
export type ChainWarning =
|
||||
| { kind: "partial"; step: number; ok: number; total: number }
|
||||
| { kind: "firstOnly"; step: number; total: number }
|
||||
| { kind: "sourceSkip"; skipped: number; total: number };
|
||||
| { kind: "sourceSkip"; skipped: number; total: number }
|
||||
| { kind: "sizeLimitMiss"; limitKb: number; actualKb: number };
|
||||
|
||||
export class ChainStepError extends Error {
|
||||
constructor(
|
||||
|
||||
Reference in New Issue
Block a user