feat: pipeline templates, analytics opt-out, 83 conversion presets, positioning + e2e modernization

Lands five integrated branches: pipeline templates (#355), analytics opt-out (#354), 83 conversion presets bringing the catalog to 240 tools (#356), self-hosted positioning (#353), and e2e modernization (#351).

Integration fixes: aligned stale web analytics tests with the opt-out/allow-list model, closed 3 CodeQL incomplete-sanitization alerts in the i18n generator, resolved settings/index/docs/format-matrix conflicts, and corrected tool counts to 240.
This commit is contained in:
SnapOtter
2026-06-28 18:57:53 +08:00
committed by GitHub
parent 88af8d46fb
commit 63a03d26f2
421 changed files with 17308 additions and 2540 deletions
@@ -14,6 +14,15 @@ export interface CompressControlsProps {
onChange?: (settings: Record<string, unknown>) => void;
}
/** Stable serialization (sorted keys) for comparing two settings payloads. */
function canonicalSettings(settings: Record<string, unknown>): string {
const sorted: Record<string, unknown> = {};
for (const key of Object.keys(settings).sort()) {
sorted[key] = settings[key];
}
return JSON.stringify(sorted);
}
export function CompressControls({ settings: initialSettings, onChange }: CompressControlsProps) {
const { t } = useTranslation();
const [mode, setMode] = useState<CompressMode>("targetSize");
@@ -21,12 +30,15 @@ export function CompressControls({ settings: initialSettings, onChange }: Compre
const [targetSizeValue, setTargetSizeValue] = useState("");
const [sizeUnit, setSizeUnit] = useState<SizeUnit>("KB");
const prevSettingsKeyRef = useRef<string | null>(null);
// Seed local state from preloaded settings exactly once (a pipeline step can
// mount this control with non-default settings). One-time, not a re-sync: a
// re-sync would keep pulling the store's value back into local state and fight
// the emit effect below, ping-ponging into an infinite render loop (React
// error #185). Mirrors resize-settings / convert-settings.
const initializedRef = useRef(false);
useEffect(() => {
if (!initialSettings) return;
const key = JSON.stringify(initialSettings);
if (prevSettingsKeyRef.current === key) return;
prevSettingsKeyRef.current = key;
if (!initialSettings || initializedRef.current) return;
initializedRef.current = true;
if (initialSettings.mode != null) setMode(initialSettings.mode as CompressMode);
if (initialSettings.quality != null) setQuality(Number(initialSettings.quality));
if (initialSettings.targetSizeKb != null)
@@ -38,15 +50,28 @@ export function CompressControls({ settings: initialSettings, onChange }: Compre
onChangeRef.current = onChange;
});
// Emit settings on change. Once local state has converged on initialSettings
// (a preloaded pipeline step), the computed payload equals initialSettings, so
// we skip the echo. A genuine user edit produces a payload that differs, so it
// still emits. This idempotent guard replaces an earlier one-shot flag that
// could dangle and silently swallow a real edit when the sync effect's
// setState calls were no-ops; it has no such failure mode.
useEffect(() => {
if (mode === "quality") {
onChangeRef.current?.({ mode, quality });
} else {
const valueNum = Number(targetSizeValue);
const targetSizeKb = sizeUnit === "MB" ? valueNum * 1024 : valueNum;
onChangeRef.current?.({ mode, targetSizeKb });
const next: Record<string, unknown> =
mode === "quality"
? { mode, quality }
: {
mode,
targetSizeKb:
sizeUnit === "MB" ? Number(targetSizeValue) * 1024 : Number(targetSizeValue),
};
if (initialSettings && canonicalSettings(next) === canonicalSettings(initialSettings)) {
return;
}
}, [mode, quality, targetSizeValue, sizeUnit]);
onChangeRef.current?.(next);
}, [mode, quality, targetSizeValue, sizeUnit, initialSettings]);
return (
<div className="space-y-4">
@@ -0,0 +1,170 @@
import { BASE_CONFIG, CONVERSION_PRESET_BY_ID } from "@snapotter/shared";
import { Download } from "lucide-react";
import { useState } from "react";
import { useParams } from "react-router-dom";
import { ProgressCard } from "@/components/common/progress-card";
import { useTranslation } from "@/contexts/i18n-context";
import { useToolProcessor } from "@/hooks/use-tool-processor";
import { format } from "@/lib/format";
import { useFileStore } from "@/stores/file-store";
/** Target formats that honor a quality knob (lossy raster encodings). */
const LOSSY = new Set(["jpg", "jpeg", "webp", "avif"]);
/**
* One settings panel shared by every conversion preset. Reads the active tool
* id from the route (the /:section/:toolId param), looks up the preset and its
* base settingsKind from shared metadata, and renders the matching controls:
* a quality slider for lossy raster/svg targets, a quality select for
* convert-video, page size + orientation for image-to-pdf, nothing otherwise.
*/
export function ConversionPresetSettings() {
const { t } = useTranslation();
const params = useParams<{ toolId: string }>();
const toolId = params.toolId ?? "";
const preset = CONVERSION_PRESET_BY_ID[toolId];
const kind = preset ? BASE_CONFIG[preset.base].settingsKind : "none";
const { files } = useFileStore();
const { processFiles, processAllFiles, processing, error, downloadUrl, progress } =
useToolProcessor(toolId);
const [quality, setQuality] = useState(85);
const [videoQuality, setVideoQuality] = useState<"high" | "balanced" | "small">("balanced");
const [pageSize, setPageSize] = useState<"A4" | "Letter" | "A3" | "A5">("A4");
const [orientation, setOrientation] = useState<"portrait" | "landscape">("portrait");
const hasFile = files.length > 0;
const targetIsLossy = preset ? LOSSY.has(String(preset.locked.format ?? "")) : false;
const buildSettings = (): Record<string, unknown> => {
if (kind === "quality" && targetIsLossy) return { quality };
if (kind === "video") return { quality: videoQuality };
if (kind === "pdf") return { pageSize, orientation };
return {};
};
const handleProcess = () => {
const settings = buildSettings();
if (files.length > 1) processAllFiles(files, settings);
else processFiles(files, settings);
};
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (hasFile && !processing) handleProcess();
};
return (
<form onSubmit={handleSubmit} className="space-y-4">
{kind === "quality" && targetIsLossy && (
<div>
<div className="flex justify-between items-center">
<label htmlFor="preset-quality" className="text-xs text-muted-foreground">
Quality
</label>
<span className="text-xs font-mono text-foreground">{quality}</span>
</div>
<input
id="preset-quality"
type="range"
min={1}
max={100}
value={quality}
onChange={(e) => setQuality(Number(e.target.value))}
className="w-full mt-1"
/>
</div>
)}
{kind === "video" && (
<div>
<label htmlFor="preset-vq" className="text-xs text-muted-foreground">
Quality
</label>
<select
id="preset-vq"
value={videoQuality}
onChange={(e) => setVideoQuality(e.target.value as "high" | "balanced" | "small")}
className="w-full mt-0.5 px-2 py-1.5 rounded border border-border bg-background text-sm text-foreground"
>
<option value="high">High</option>
<option value="balanced">Balanced</option>
<option value="small">Small</option>
</select>
</div>
)}
{kind === "pdf" && (
<div className="grid grid-cols-2 gap-2">
<div>
<label htmlFor="preset-page" className="text-xs text-muted-foreground">
Page size
</label>
<select
id="preset-page"
value={pageSize}
onChange={(e) => setPageSize(e.target.value as "A4" | "Letter" | "A3" | "A5")}
className="w-full mt-0.5 px-2 py-1.5 rounded border border-border bg-background text-sm text-foreground"
>
<option value="A4">A4</option>
<option value="Letter">Letter</option>
<option value="A3">A3</option>
<option value="A5">A5</option>
</select>
</div>
<div>
<label htmlFor="preset-orient" className="text-xs text-muted-foreground">
Orientation
</label>
<select
id="preset-orient"
value={orientation}
onChange={(e) => setOrientation(e.target.value as "portrait" | "landscape")}
className="w-full mt-0.5 px-2 py-1.5 rounded border border-border bg-background text-sm text-foreground"
>
<option value="portrait">Portrait</option>
<option value="landscape">Landscape</option>
</select>
</div>
</div>
)}
{error && <p className="text-xs text-red-500">{error}</p>}
{processing ? (
<ProgressCard
active={processing}
phase={progress.phase === "idle" ? "uploading" : progress.phase}
label={t.toolSettings.convert.progressLabel}
stage={progress.stage}
percent={progress.percent}
elapsed={progress.elapsed}
/>
) : (
<button
type="submit"
data-testid="preset-submit"
disabled={!hasFile || processing}
className="w-full py-2.5 rounded-lg bg-primary text-primary-foreground font-medium disabled:opacity-50 disabled:cursor-not-allowed"
>
{files.length > 1
? format(t.toolSettings.convert.submitBatch, { count: files.length })
: t.toolSettings.convert.submit}
</button>
)}
{downloadUrl && (
<a
href={downloadUrl}
download
data-testid="preset-download"
className="w-full py-2.5 rounded-lg border border-primary text-primary font-medium flex items-center justify-center gap-2 hover:bg-primary/5"
>
<Download className="h-4 w-4" />
{t.common.download}
</a>
)}
</form>
);
}
@@ -103,7 +103,14 @@ export function CropCanvas({
crop={crop}
onChange={(_pixelCrop, percentCrop) => onCropChange(percentCrop)}
aspect={aspect}
className="max-h-full"
// ReactCrop's own CSS forces `.ReactCrop__child-wrapper>img` to
// max-height:inherit, which overrides the img's own max-h utility
// (higher specificity). So the viewport cap has to live on the
// ReactCrop element itself; the child-wrapper and img then inherit
// it. Without this a tall portrait renders at full natural height
// and overflows the viewport. max-h-full doesn't help because the
// ancestor chain isn't reliably height-bounded.
className="max-h-[calc(100dvh-12rem)]"
ruleOfThirds={showGrid}
>
<img
@@ -86,7 +86,7 @@ export interface RemoveBgControlsProps {
onChange: (settings: Record<string, unknown>) => void;
}
export function RemoveBgControls({ settings: _settings, onChange }: RemoveBgControlsProps) {
export function RemoveBgControls({ settings, onChange }: RemoveBgControlsProps) {
const { t } = useTranslation();
const [subject, setSubject] = useState<SubjectType>("people");
const [quality, setQuality] = useState<Quality>("balanced");
@@ -116,6 +116,39 @@ export function RemoveBgControls({ settings: _settings, onChange }: RemoveBgCont
// Expandable sections
const [effectsOpen, setEffectsOpen] = useState(false);
// Seed local state from preloaded settings exactly once. Pipeline steps (e.g.
// a template) mount this control with non-default settings; without seeding,
// the emit effect below would overwrite them with the hardcoded defaults.
// Mirrors the initializedRef pattern in resize-settings / convert-settings.
const initializedRef = useRef(false);
useEffect(() => {
if (!settings || initializedRef.current) return;
initializedRef.current = true;
if (settings.backgroundType != null) setBgType(settings.backgroundType as BackgroundType);
if (settings.backgroundColor != null) setBgColor(String(settings.backgroundColor));
if (settings.gradientColor1 != null) setGradColor1(String(settings.gradientColor1));
if (settings.gradientColor2 != null) setGradColor2(String(settings.gradientColor2));
if (settings.gradientAngle != null) setGradAngle(Number(settings.gradientAngle));
if (settings.blurEnabled != null) setBlurEnabled(Boolean(settings.blurEnabled));
if (settings.blurIntensity != null) setBlurIntensity(Number(settings.blurIntensity));
if (settings.shadowEnabled != null) setShadowEnabled(Boolean(settings.shadowEnabled));
if (settings.shadowOpacity != null) setShadowOpacity(Number(settings.shadowOpacity));
if (settings.edgeRefine != null) setEdgeRefine(Number(settings.edgeRefine));
if (settings.decontaminate != null) setDecontaminate(Boolean(settings.decontaminate));
if (settings.outputFormat != null)
setOutputFormat(settings.outputFormat as "png" | "webp" | "avif");
// Reveal the effects section when any seeded effect is active so the
// preloaded values are immediately visible (and adjustable).
if (
settings.blurEnabled ||
settings.shadowEnabled ||
settings.edgeRefine ||
settings.decontaminate
) {
setEffectsOpen(true);
}
}, [settings]);
// Filter quality options based on subject (Ultra only for People)
const qualityOptions = ALL_QUALITY_OPTIONS.filter(
(opt) => !opt.peopleOnly || subject === "people",
@@ -409,6 +442,8 @@ export function RemoveBgControls({ settings: _settings, onChange }: RemoveBgCont
<button
key={fmt}
type="button"
data-testid={`remove-background-format-${fmt}`}
aria-pressed={outputFormat === fmt}
onClick={() => setOutputFormat(fmt)}
className={`py-2 px-2 rounded-lg border text-xs font-medium uppercase transition-colors ${
outputFormat === fmt
@@ -520,6 +555,7 @@ export function RemoveBgControls({ settings: _settings, onChange }: RemoveBgCont
</div>
<input
type="range"
data-testid="remove-background-edge-refine"
min={0}
max={3}
step={1}
@@ -534,6 +570,7 @@ export function RemoveBgControls({ settings: _settings, onChange }: RemoveBgCont
<label className="flex items-center gap-2 cursor-pointer">
<input
type="checkbox"
data-testid="remove-background-decontaminate"
checked={decontaminate}
onChange={(e) => setDecontaminate(e.target.checked)}
className="rounded border-border accent-primary"
@@ -3,6 +3,7 @@ import { FileImage, Plus } from "lucide-react";
import { useEffect, useMemo, useState } from "react";
import { SearchBar } from "@/components/common/search-bar";
import { useTranslation } from "@/contexts/i18n-context";
import { useFuseSearch } from "@/hooks/use-fuse-search";
import { apiGet } from "@/lib/api";
import { ICON_MAP } from "@/lib/icon-map";
import { getCategoryName, getToolDescription, getToolName } from "@/lib/tool-i18n";
@@ -37,19 +38,17 @@ export function ToolPalette({ onAddStep, className }: ToolPaletteProps) {
.catch(() => {});
}, []);
const availableTools = useMemo(() => {
const q = search.toLowerCase();
const preFiltered = useMemo(() => {
return TOOLS.filter((t) => {
if (EXCLUDED_TOOLS.has(t.id)) return false;
if (disabledTools.includes(t.id)) return false;
if (t.experimental && !experimentalEnabled) return false;
if (pipelineToolIds && !pipelineToolIds.includes(t.id)) return false;
if (q && !t.name.toLowerCase().includes(q) && !t.description.toLowerCase().includes(q)) {
return false;
}
return true;
});
}, [disabledTools, experimentalEnabled, pipelineToolIds, search]);
}, [disabledTools, experimentalEnabled, pipelineToolIds]);
const availableTools = useFuseSearch(preFiltered, search);
const groupedTools = useMemo(() => {
const groups: Record<string, typeof availableTools> = {};