diff --git a/src/components/editor/ExtraFieldsInput.tsx b/src/components/editor/ExtraFieldsInput.tsx
index 29f9769..f60ecfd 100644
--- a/src/components/editor/ExtraFieldsInput.tsx
+++ b/src/components/editor/ExtraFieldsInput.tsx
@@ -3,6 +3,8 @@ import clsx from "clsx";
import { Input } from "@components/ui/Input";
import { Textarea } from "@components/ui/Textarea";
import { Field, controlClasses } from "@components/ui/Field";
+import { ValidatedInput } from "@components/ui/ValidatedInput";
+import { validateUrl } from "@utils/validation";
import { VIDEO_TYPES } from "@config/video-types";
import {
GACHA_QUEST_TYPE_GROUPS,
@@ -194,12 +196,19 @@ export function ExtraFieldsInput() {
>
)}
{extraFields.includes("liveUrl") && (
- store.set("liveUrl", e.target.value)}
+ onChange={(v) => store.set("liveUrl", v)}
+ validate={validateUrl}
+ inputMode="url"
+ autoComplete="off"
/>
)}
{extraFields.includes("scheduledTime") && (
diff --git a/src/components/editor/GpuList.tsx b/src/components/editor/GpuList.tsx
new file mode 100644
index 0000000..7b566e4
--- /dev/null
+++ b/src/components/editor/GpuList.tsx
@@ -0,0 +1,101 @@
+import { useTranslation } from "react-i18next";
+import { Command } from "cmdk";
+import { Check, PenLine, Search, X } from "lucide-react";
+import { GPU_GROUPS, type GpuModel } from "@config/gpu-catalog";
+
+const itemClass =
+ "flex min-h-8 cursor-pointer items-center gap-2 rounded-lg px-2 py-1 text-sm text-text-primary select-none data-[selected=true]:bg-surface-2";
+
+const headingClass =
+ "[&_[cmdk-group-heading]]:text-text-muted [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:pt-2 [&_[cmdk-group-heading]]:pb-1 [&_[cmdk-group-heading]]:text-[0.6875rem] [&_[cmdk-group-heading]]:font-semibold [&_[cmdk-group-heading]]:tracking-wide [&_[cmdk-group-heading]]:uppercase";
+
+interface GpuListProps {
+ selectedId: string | undefined;
+ hasValue: boolean;
+ onSelect: (model: GpuModel) => void;
+ onCustom: () => void;
+ onClear: () => void;
+}
+
+/**
+ * Every word of the query must appear in the card's name or keywords:
+ * "5080" finds the RTX 5080s only, where cmdk's default fuzzy score also
+ * offered the RX 580 and the HD 7850 ("5…8…0"). Exact model-number hits
+ * rank first.
+ */
+function gpuFilter(value: string, search: string, keywords?: string[]): number {
+ const haystack = [value, ...(keywords ?? [])].join(" ").toLowerCase();
+ const words = search.toLowerCase().split(/\s+/).filter(Boolean);
+ if (words.length === 0) return 1;
+ if (!words.every((word) => haystack.includes(word))) return 0;
+ const whole = words.every((word) =>
+ new RegExp(`(^|[^a-z0-9])${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}($|[^a-z0-9])`).test(
+ haystack,
+ ),
+ );
+ return whole ? 1 : 0.5;
+}
+
+/**
+ * The searchable GPU list in the rig editor ("5080", "9070 xt", "m4 pro",
+ * "rog ally"…). Lazily loaded with the search library it needs.
+ */
+export default function GpuList({
+ selectedId,
+ hasValue,
+ onSelect,
+ onCustom,
+ onClear,
+}: GpuListProps) {
+ const { t } = useTranslation("ui");
+ return (
+
+
+
+
+
+
+
+ {t("editor.gpuNoMatch")}
+
+ {GPU_GROUPS.map((group) => (
+
+ {group.models.map((model) => (
+ onSelect(model)}
+ className={itemClass}
+ >
+
+ {model.id === selectedId && }
+
+ {model.name}
+
+ ))}
+
+ ))}
+
+
+
+ {t("editor.gpuCustom")}
+
+ {hasValue && (
+
+
+ {t("editor.gpuNone")}
+
+ )}
+
+
+
+ );
+}
diff --git a/src/components/editor/LivePreview.tsx b/src/components/editor/LivePreview.tsx
index b4a67f0..e4e38e8 100644
--- a/src/components/editor/LivePreview.tsx
+++ b/src/components/editor/LivePreview.tsx
@@ -4,6 +4,7 @@ import { Eye } from "lucide-react";
import { useGeneratedOutput } from "@hooks/use-generated-output";
import { useOutputLimits } from "@hooks/use-output-limits";
import { useStrictBlock } from "@hooks/use-strict-block";
+import { useCopyGate } from "@hooks/use-copy-gate";
import { EMPTY_GENERATOR_OUTPUT, YT_LIMITS } from "@engine/types";
import { useEditorStore } from "@store/editor-store";
import { Card } from "@components/ui/Card";
@@ -38,7 +39,7 @@ export function LivePreview({
const outputs = useMemo(() => [output], [output]);
const limitStatus = useOutputLimits(outputs);
const strictBlocked = useStrictBlock();
- const blocked = limitStatus.blocked || strictBlocked;
+ const gate = useCopyGate(limitStatus, strictBlocked);
const over = (field: PreviewTab) => limitStatus.overflows.some((o) => o.field === field);
const dot = (field: PreviewTab) =>
@@ -110,14 +111,20 @@ export function LivePreview({
{tab === "description" && (
)}
- {tab === "tags" && }
+ {tab === "tags" && (
+
+ )}
{tab === "title" && (
)}
{tab === "description" && (
@@ -126,16 +133,15 @@ export function LivePreview({
label={t("output.copyDescription")}
limit={YT_LIMITS.DESCRIPTION_MAX}
fieldLabel={t("output.description")}
- blocked={blocked}
+ {...gate("description")}
/>
)}
{tab === "tags" && (
)}
diff --git a/src/components/editor/RigEditor.tsx b/src/components/editor/RigEditor.tsx
index 47bf101..ea4be70 100644
--- a/src/components/editor/RigEditor.tsx
+++ b/src/components/editor/RigEditor.tsx
@@ -1,37 +1,160 @@
+import { lazy, Suspense, useId, useState } from "react";
import { useTranslation } from "react-i18next";
-import { AlertTriangle } from "lucide-react";
+import { AlertTriangle, ChevronsUpDown } from "lucide-react";
+import clsx from "clsx";
import { Input } from "@components/ui/Input";
import { Select } from "@components/ui/Select";
+import { Field, controlClasses } from "@components/ui/Field";
+import { PopoverContent, PopoverRoot, PopoverTrigger } from "@components/ui/Popover";
+import { Spinner } from "@components/icons/animated";
import {
RIG_FIELDS,
- parseCascadingValue,
+ cleanCpuName,
parseCompositeValue,
resolveCompositeOptions,
resolveCompositeLabelKey,
type RigField,
type CompositePart,
} from "@config/rig-fields";
-import { GPU_CUSTOM_BRAND_ID, findGpuBrand } from "@config/gpu-catalog";
+import { gpuValue, migrateGpuValue, modelForGpuValue } from "@config/gpu-catalog";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
-import {
- validateGpuValue,
- validateCompositeField,
- type RigValidationIssue,
-} from "@utils/rig-validation";
+import { validateCompositeField, type RigValidationIssue } from "@utils/rig-validation";
+
+const GpuList = lazy(() => import("./GpuList"));
const CUSTOM_PREFIX = "custom:";
-function joinCascading(brand: string, series: string, model: string): string {
- if (!brand && !series && !model) return "";
- return `${brand}|${series}|${model}`;
-}
-
function joinComposite(parts: readonly string[]): string {
if (parts.every((p) => !p)) return "";
return parts.join("|");
}
+/**
+ * GPU: one searchable picker over the catalog, printing the official name
+ * ("NVIDIA GeForce RTX 5080"), plus a free-text fallback for anything not
+ * listed. Replaces three dependent dropdowns (Brand › Series › Model).
+ */
+function GpuPicker({
+ label,
+ value,
+ onChange,
+}: {
+ label: string;
+ value: string;
+ onChange: (next: string) => void;
+}) {
+ const { t } = useTranslation("ui");
+ const [open, setOpen] = useState(false);
+ const [customMode, setCustomMode] = useState(false);
+ const normalized = migrateGpuValue(value);
+ const model = modelForGpuValue(normalized);
+ const isOwnText = !model && normalized !== "";
+ const showCustom = customMode || isOwnText;
+
+ return (
+
{
+ onChange(gpuValue(next));
+ setCustomMode(false);
+ setOpen(false);
+ }}
+ onCustom={() => {
+ // Start from the current card's name so "RTX 5080" can
+ // become "RTX 5080 (overclocked)" without retyping.
+ onChange(model ? model.name : normalized);
+ setCustomMode(true);
+ setOpen(false);
+ }}
+ onClear={() => {
+ onChange("");
+ setCustomMode(false);
+ setOpen(false);
+ }}
+ />
+
+
+
+ )}
+
+ {showCustom && (
+ onChange(e.target.value)}
+ autoComplete="off"
+ />
+ )}
+
+ );
+}
+
+/** CPU (and any other suggested text field): type freely or pick a suggestion. */
+function SuggestedTextField({
+ field,
+ value,
+ onChange,
+}: {
+ field: RigField;
+ value: string;
+ onChange: (next: string) => void;
+}) {
+ const { t } = useTranslation("ui");
+ const listId = useId();
+ return (
+ <>
+ onChange(e.target.value)}
+ // "Intel(R) Core(TM) i7-12700K CPU @ 3.60GHz", as Windows shows it,
+ // becomes "Intel Core i7-12700K" once the user leaves the field.
+ onBlur={(e) => {
+ const cleaned = field.id === "cpu" ? cleanCpuName(e.target.value) : e.target.value.trim();
+ if (cleaned !== e.target.value) onChange(cleaned);
+ }}
+ />
+
+ {field.suggestions?.map((s) => (
+
+ ))}
+
+ >
+ );
+}
+
export function RigEditor() {
const { t } = useTranslation("ui");
const rig = useEditorStore((s) => s.rig);
@@ -41,186 +164,58 @@ export function RigEditor() {
if (!issue) return null;
return (
-
+
{t(issue.messageKey)}
);
};
- const renderCascading = (field: RigField) => {
- const raw = rig[field.id] ?? "";
- const { brand, series, model } = parseCascadingValue(raw);
- const isCustom = brand === GPU_CUSTOM_BRAND_ID;
- const issue = validateGpuValue(raw);
- const catalog = field.catalog ?? [];
-
- const brandOptions = [
- { value: "", label: "—" },
- ...catalog.map((b) => ({ value: b.id, label: b.label })),
- ];
- const currentBrand = findGpuBrand(brand);
- const seriesOptions = currentBrand
- ? [
- { value: "", label: "—" },
- ...currentBrand.series.map((s) => ({ value: s.id, label: s.label })),
- ]
- : [{ value: "", label: "—" }];
- const currentSeries = currentBrand?.series.find((s) => s.id === series);
- const modelOptions = currentSeries
- ? [{ value: "", label: "—" }, ...currentSeries.models.map((m) => ({ value: m, label: m }))]
- : [{ value: "", label: "—" }];
-
- const setBrand = (next: string) => {
- // Switching brand resets series + model so the user can't end up
- // with mismatched cascading values (NVIDIA brand + AMD series).
- setNested("rig", field.id, next ? joinCascading(next, "", "") : "");
- };
- const setSeries = (next: string) => {
- setNested("rig", field.id, joinCascading(brand, next, ""));
- };
- const setModel = (next: string) => {
- setNested("rig", field.id, joinCascading(brand, series, next));
- };
- const setCustomText = (text: string) => {
- setNested("rig", field.id, text ? joinCascading(GPU_CUSTOM_BRAND_ID, "", text) : "");
- };
-
- return (
-
-
{t(field.labelKey)}
-
-
- {isCustom ? (
-
- setCustomText(e.target.value)}
- />
-
- ) : (
- <>
-
-
- >
- )}
-
- {renderValidationBadge(issue)}
-
- );
- };
-
const renderComposite = (field: RigField) => {
if (!field.composite) return null;
+ const composite = field.composite;
const raw = rig[field.id] ?? "";
const { parts: storedParts } = parseCompositeValue(raw);
- // Validate per field — only RAM has size/DDR semantics. Running the
- // RAM validator on the OS composite mis-fired "Pick a DDR generation."
const issue = validateCompositeField(field.id, raw);
- const partValues = field.composite.parts.map((_p, i) => storedParts[i] ?? "");
+ const partValues = composite.parts.map((_p, i) => storedParts[i] ?? "");
- // v0.23.0: setting a part also resets all downstream parts to "" so
- // a cascading parent change can't leave the form with a stale child
- // value that no longer exists in the new option list (e.g. switching
- // OS name from Windows to macOS clears any leftover "11" / "Pro").
+ // Cascading composites (OS) clear the parts after the one that changed,
+ // so switching Windows → macOS can't leave "Pro" behind. Independent
+ // ones (RAM) keep them: picking 32 GB must not wipe the DDR5 already set.
const setPart = (index: number, next: string) => {
const updated = [...partValues];
updated[index] = next;
- for (let j = index + 1; j < updated.length; j++) {
- updated[j] = "";
+ if (composite.cascade) {
+ for (let j = index + 1; j < updated.length; j++) updated[j] = "";
}
setNested("rig", field.id, joinComposite(updated));
};
- // Walk parts in declaration order; each part's resolvers see the
- // previously-rendered values so cascading option lists / dynamic
- // labels / hidden-when predicates work cleanly.
- const previousValues: string[] = [];
- const renderedParts: React.ReactNode[] = [];
-
- field.composite.parts.forEach((part, index) => {
- const stored = partValues[index] ?? "";
- // hiddenWhen short-circuits BEFORE we render — and we still push
- // the stored value into previousValues so a later visible part
- // sees the full history (though in practice, parts after a
- // hidden one are rare).
- if (part.hiddenWhen?.(previousValues)) {
- previousValues.push(stored);
- return;
- }
- renderedParts.push(renderPart(part, index, previousValues, setPart));
- previousValues.push(stored);
- });
-
- return (
-
-
{t(field.labelKey)}
-
{renderedParts}
- {renderValidationBadge(issue)}
-
- );
-
- // Inner closure — needs access to `t`, `partValues`, and the part-
- // local mutators. Defined as a function so the forEach above stays
- // readable; not hoisted out because it captures lexical state.
- function renderPart(
- part: CompositePart,
- index: number,
- previousValues: readonly string[],
- setPart: (index: number, next: string) => void,
- ) {
+ const renderPart = (part: CompositePart, index: number, previous: readonly string[]) => {
const stored = partValues[index] ?? "";
const isCustom = part.allowCustom && stored.startsWith(CUSTOM_PREFIX);
const customText = isCustom ? stored.slice(CUSTOM_PREFIX.length) : "";
const selectValue = isCustom ? "custom" : stored;
- const options = resolveCompositeOptions(part.options, previousValues);
- const labelKey = resolveCompositeLabelKey(part, previousValues);
-
- const onSelectChange = (next: string) => {
- if (next === "custom" && part.allowCustom) {
- setPart(index, `${CUSTOM_PREFIX}`);
- } else {
- setPart(index, next);
- }
- };
- const onCustomChange = (next: string) => {
- setPart(index, `${CUSTOM_PREFIX}${next}`);
- };
+ const options = resolveCompositeOptions(part.options, previous);
+ const labelKey = resolveCompositeLabelKey(part, previous);
return (
-
+
+ setPart(index, next === "custom" && part.allowCustom ? CUSTOM_PREFIX : next)
+ }
/>
- {isCustom && part.allowCustom && (
+ {isCustom && (
onCustomChange(e.target.value)}
+ inputMode="decimal"
+ onChange={(e) => setPart(index, `${CUSTOM_PREFIX}${e.target.value}`)}
/>
{part.customSuffix && (
{part.customSuffix.trim()}
@@ -229,7 +224,30 @@ export function RigEditor() {
)}
);
- }
+ };
+
+ // Walk parts in declaration order; each part's resolvers see the values
+ // before it, so cascading option lists, dynamic labels and hidden-when
+ // predicates line up.
+ const previousValues: string[] = [];
+ const renderedParts: React.ReactNode[] = [];
+ composite.parts.forEach((part, index) => {
+ const stored = partValues[index] ?? "";
+ if (!part.hiddenWhen?.(previousValues)) {
+ renderedParts.push(renderPart(part, index, [...previousValues]));
+ }
+ previousValues.push(stored);
+ });
+
+ return (
+
+
+ {t(field.labelKey)}
+
+ {renderedParts}
+ {renderValidationBadge(issue)}
+
+ );
};
const renderDropdownWithVersion = (field: RigField) => {
@@ -243,7 +261,7 @@ export function RigEditor() {
};
return (
-
+
- {t("editor.rig")}
{RIG_FIELDS.map((field) => {
- if (field.type === "cascading_dropdown") return renderCascading(field);
+ const value = rig[field.id] ?? "";
+ const set = (next: string) => setNested("rig", field.id, next);
+ if (field.type === "gpu") {
+ return (
+
+ );
+ }
if (field.type === "composite_dropdown") return renderComposite(field);
if (field.type === "dropdown_with_version") return renderDropdownWithVersion(field);
+ if (field.suggestions) {
+ return
;
+ }
return (
setNested("rig", field.id, e.target.value)}
+ value={value}
+ onChange={(e) => set(e.target.value)}
/>
);
})}
diff --git a/src/components/editor/TimestampEditor.tsx b/src/components/editor/TimestampEditor.tsx
index 3752255..fe8f59d 100644
--- a/src/components/editor/TimestampEditor.tsx
+++ b/src/components/editor/TimestampEditor.tsx
@@ -1,21 +1,86 @@
+import { useMemo } from "react";
import { useTranslation } from "react-i18next";
+import { CircleCheck, TriangleAlert, WandSparkles } from "lucide-react";
import { Textarea } from "@components/ui/Textarea";
+import { Button } from "@components/ui/Button";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
+import {
+ checkChapters,
+ normalizeTimeline,
+ parseTimeline,
+ type ChapterIssue,
+} from "@engine/timeline-parser";
+/**
+ * Timestamps, with a live check against YouTube's chapter rules (first at
+ * 0:00, at least three, ten seconds apart, in order) and a button that
+ * rewrites pasted lists ("[00:00] – Intro", editor frame counts) into the
+ * plain "0:00 Intro" form.
+ */
export function TimestampEditor() {
const { t } = useTranslation("ui");
- const timestamps = useEditorStore((s) => s.timestamps);
+ const timestamps = useEditorStore((s) => s.timestamps) ?? "";
const set = useEditorStore((s) => s.set);
+ const entries = useMemo(() => parseTimeline(timestamps), [timestamps]);
+ const timedCount = entries.filter((e) => e.time).length;
+ const issues = useMemo(() => checkChapters(entries), [entries]);
+ const normalized = useMemo(() => normalizeTimeline(timestamps), [timestamps]);
+ const canNormalize = timedCount > 0 && normalized !== timestamps.trim();
+
+ const describe = (issue: ChapterIssue): string => {
+ switch (issue.kind) {
+ case "firstNotZero":
+ return t("editor.chapters.firstNotZero");
+ case "tooFew":
+ return t("editor.chapters.tooFew", { n: issue.count });
+ case "tooShort":
+ return t("editor.chapters.tooShort", { time: issue.time });
+ case "outOfOrder":
+ return t("editor.chapters.outOfOrder", { time: issue.time });
+ }
+ };
+
return (
-
@@ -248,7 +253,7 @@ export function BatchPage() {
label={t("output.copyTitle")}
limit={YT_LIMITS.TITLE_MAX}
fieldLabel={t("output.title")}
- blocked={lang.status.blocked}
+ blocked={isFieldOver(lang.status, "title")}
/>
@@ -268,7 +273,11 @@ export function BatchPage() {
limit={YT_LIMITS.DESCRIPTION_MAX}
/>
{t("output.tags")}
-
+
{lang.status.blocked && (
@@ -281,14 +290,13 @@ export function BatchPage() {
label={t("output.copyDescription")}
limit={YT_LIMITS.DESCRIPTION_MAX}
fieldLabel={t("output.description")}
- blocked={lang.status.blocked}
+ blocked={isFieldOver(lang.status, "description")}
/>
{lang.pinnedComment && (
set("playlistLink", v)}
+ onChange={(v) => set("playlistLink", normalizePlaylistUrl(v))}
validate={validatePlaylistUrl}
inputMode="url"
autoComplete="off"
diff --git a/src/pages/OutputPage.tsx b/src/pages/OutputPage.tsx
index 0c30dcf..e8dad07 100644
--- a/src/pages/OutputPage.tsx
+++ b/src/pages/OutputPage.tsx
@@ -23,6 +23,7 @@ import { useSettingsStore } from "@store/settings-store";
import { SUPPORTED_LANGUAGES } from "@i18n/index";
import type { GeneratorOutput, SupportedLanguage } from "@engine/types";
import { useOutputLimits } from "@hooks/use-output-limits";
+import { fieldsWithForbiddenChars, isCopyAllBlocked } from "@engine/limits";
import { useStrictBlock } from "@hooks/use-strict-block";
import { useClipboard } from "@hooks/use-clipboard";
import { StrictModeBanner } from "@components/ui/StrictModeBanner";
@@ -77,17 +78,10 @@ export function OutputPage() {
const tabStatus = useOutputLimits(shownOutputs);
const allStatus = useOutputLimits(everyOutput);
- // Strict Mode folds into the same "blocked" signal the char-limit gate
- // uses, so a copy button has one reason to be disabled, not two.
+ // Strict Mode blocks every copy; the limits block only the field that is
+ // over (Copy All = title + description, so not the tags).
const strictBlocked = useStrictBlock();
- const tabBlocked = useMemo(
- () => (strictBlocked ? { ...tabStatus, blocked: true } : tabStatus),
- [strictBlocked, tabStatus],
- );
- const allBlocked = useMemo(
- () => (strictBlocked ? { ...allStatus, blocked: true } : allStatus),
- [strictBlocked, allStatus],
- );
+ const copyAllBlocked = strictBlocked || isCopyAllBlocked(allStatus);
// At least one language stays selected; the active tab follows a removal.
const changeLangs = (next: SupportedLanguage[]) => {
@@ -96,9 +90,19 @@ export function OutputPage() {
if (!next.includes(activeTab)) setActiveTab(next[0] as SupportedLanguage);
};
+ // Record what was generated. The store updates an existing entry for the
+ // same video instead of adding another, so this may run on every visit and
+ // whenever the description changes (a setting toggled while here).
useEffect(() => {
if (!gameName || !defaultOutput.title) return;
- const key = `${gameName}-${videoType}-${language}-${defaultOutput.title}`;
+ const key = [
+ gameName,
+ videoType,
+ language,
+ defaultOutput.title,
+ defaultOutput.description,
+ defaultOutput.tagString,
+ ].join("\n");
if (savedRef.current === key) return;
savedRef.current = key;
addEntry(
@@ -142,7 +146,7 @@ export function OutputPage() {
${defaultOutput.description}`;
const copyAll = () => void copy(copyAllText);
- const copyAllDisabled = allBlocked.blocked || !gameName;
+ const copyAllDisabled = copyAllBlocked || !gameName;
const shownOutput = currentOutput ?? defaultOutput;
@@ -183,6 +187,11 @@ ${defaultOutput.description}`;
+ {fieldsWithForbiddenChars(shownOutput).map((field) => (
+
+ {t("output.forbiddenChars", { field: t(`output.${field}`) })}
+
+ ))}
{!gameName ? (
(
{multilangOutputs[lang] && (
-
+
)}
))}
) : (
-
+
)}
| null | undefined): Pa
// become a no-op instead of crashing.
if (!patch || typeof patch !== "object") return {};
const out: Partial = { ...patch };
+ // v1.0.0: profiles and templates saved before the GPU catalog rewrite
+ // carry `brand|series|model` (or `rig: null` when hand-edited).
+ if ("rig" in patch) out.rig = migrateRig((patch as { rig?: unknown }).rig);
const raw: unknown = (patch as { graphicsPreset?: unknown }).graphicsPreset;
if (typeof raw === "string" && !(GRAPHICS_PRESETS as readonly string[]).includes(raw)) {
const { preset, custom } = legacyGraphicsPresetToEnum(raw);
@@ -588,7 +592,7 @@ export const useEditorStore = create()(
// settings toggle is on. Additive: both back-fill to "".
// Non-string values coerce to "". The existing `contactEmail`
// is reused as the general-contact line, so no data moves.
- version: 18,
+ version: 19,
migrate: (persistedState, version) => migrateEditorState(persistedState, version),
partialize: (state) => ({
videoType: state.videoType,
@@ -933,6 +937,11 @@ export function migrateEditorState(persistedState: unknown, version: number): Ed
if (typeof state.adEmail !== "string") state.adEmail = "";
if (typeof state.gameKeyEmail !== "string") state.gameKeyEmail = "";
}
+ if (version < 19) {
+ // v1.0.0 GPU catalog: `brand|series|model` → `gpu:` (or the full
+ // name as the user's own text when the card isn't in the catalog).
+ state.rig = migrateRig(state.rig);
+ }
return { ...initialState, ...state } as EditorData;
}
diff --git a/src/store/history-store.ts b/src/store/history-store.ts
index 3ce8d62..3ad3db9 100644
--- a/src/store/history-store.ts
+++ b/src/store/history-store.ts
@@ -34,20 +34,61 @@ function normaliseEntry(e: LegacyEntry): HistoryEntry {
return { ...rest, genres: [fallback] } as HistoryEntry;
}
+/** Same bounds as the History Limit setting. */
+const LIMIT_MIN = 10;
+const LIMIT_MAX = 500;
+
+/**
+ * Which video an entry is about: the same game, type, language and title
+ * (the title carries the part number, boss name…) is the same video, even
+ * if its description has changed since.
+ */
+export function historyKey(
+ entry: Pick,
+): string {
+ return [
+ entry.gameName.trim().toLowerCase(),
+ entry.videoType,
+ entry.language,
+ entry.title.trim(),
+ ].join("\n");
+}
+
+/** Newest-first entries with every video listed once (its newest entry). */
+export function dedupeHistory(entries: readonly HistoryEntry[]): HistoryEntry[] {
+ const seen = new Set();
+ return entries.filter((entry) => {
+ const key = historyKey(entry);
+ if (seen.has(key)) return false;
+ seen.add(key);
+ return true;
+ });
+}
+
export const useHistoryStore = create()(
persist(
(set) => ({
entries: [],
+ /**
+ * Record a generated output. The Output page calls this every time it
+ * renders a new result — it used to add a new entry on every visit, so
+ * one video filled the history many times over. A video already in the
+ * history is now updated in place (latest description and tags) and
+ * moved to the top.
+ */
addEntry: (data, limit = 100) => {
- const entry: HistoryEntry = {
- ...data,
- id: generateId(),
- createdAt: new Date().toISOString(),
- };
set((state) => {
- const updated = [entry, ...state.entries];
- return { entries: updated.slice(0, limit) };
+ const key = historyKey(data);
+ const existing = state.entries.find((e) => historyKey(e) === key);
+ const entry: HistoryEntry = {
+ ...data,
+ id: existing?.id ?? generateId(),
+ createdAt: new Date().toISOString(),
+ };
+ const others = state.entries.filter((e) => historyKey(e) !== key);
+ const cap = Math.min(LIMIT_MAX, Math.max(LIMIT_MIN, Math.round(limit) || 100));
+ return { entries: [entry, ...others].slice(0, cap) };
});
},
@@ -60,15 +101,18 @@ export const useHistoryStore = create()(
{
name: "ytdescgen-history",
storage: createJSONStorage(() => localStorage),
- // v1 → v2 upgrade: HistoryEntry.genre (single) became genres[] in v0.5.
- version: 2,
+ // v1 → v2: HistoryEntry.genre (single) became genres[] in v0.5.
+ // v2 → v3: v1.0.0 folds the duplicates earlier versions piled up (one
+ // per Output visit) into one entry per video, keeping the newest.
+ version: 3,
migrate: (persistedState: unknown, version: number) => {
- if (version < 2 && persistedState && typeof persistedState === "object") {
- const state = persistedState as { entries?: LegacyEntry[] };
- if (Array.isArray(state.entries)) {
- state.entries = state.entries.map(normaliseEntry);
- }
- }
+ if (!persistedState || typeof persistedState !== "object") return persistedState;
+ const state = persistedState as { entries?: LegacyEntry[] };
+ if (!Array.isArray(state.entries)) return persistedState;
+ let entries = state.entries;
+ if (version < 2) entries = entries.map(normaliseEntry);
+ if (version < 3) entries = dedupeHistory(entries as HistoryEntry[]);
+ state.entries = entries;
return persistedState as { entries: HistoryEntry[] };
},
partialize: (state) => ({ entries: state.entries }),
diff --git a/src/store/profile-store.ts b/src/store/profile-store.ts
index e5168ce..36e4ebc 100644
--- a/src/store/profile-store.ts
+++ b/src/store/profile-store.ts
@@ -2,6 +2,7 @@ import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import { generateId } from "@utils/uuid";
import { saveSettings } from "@utils/storage-adapter";
+import { migrateRig } from "@config/rig-fields";
import type { GraphicsPreset } from "@config/graphics-settings";
/**
@@ -110,7 +111,8 @@ export const useProfileStore = create()(
// as "pre-v0.11" and gets the empty-string back-fill.
// v1 → v2: v0.34.0 added `adEmail` / `gameKeyEmail` (email split).
// Additive — pre-v0.34 profiles get a `""` back-fill.
- version: 2,
+ // v2 → v3: v1.0.0 GPU catalog (`brand|series|model` → `gpu:`).
+ version: 3,
migrate: (persistedState: unknown, version: number) => {
if (!persistedState || typeof persistedState !== "object") return persistedState;
const state = persistedState as { profiles?: Array> };
@@ -126,6 +128,9 @@ export const useProfileStore = create()(
gameKeyEmail: typeof p.gameKeyEmail === "string" ? p.gameKeyEmail : "",
}));
}
+ if (version < 3 && Array.isArray(state.profiles)) {
+ state.profiles = state.profiles.map((p) => ({ ...p, rig: migrateRig(p.rig) }));
+ }
return persistedState as { profiles: Profile[] };
},
partialize: (state) => ({ profiles: state.profiles }),
diff --git a/src/store/settings-heal.ts b/src/store/settings-heal.ts
index b736f6b..baa620d 100644
--- a/src/store/settings-heal.ts
+++ b/src/store/settings-heal.ts
@@ -274,6 +274,14 @@ export function healSettings(raw: unknown): SettingsData {
incoming.logRetentionDays = Math.max(1, Math.min(90, Math.floor(incoming.logRetentionDays)));
}
+ // v1.0.0: the History Limit is clamped like the retention above — a
+ // hand-edited or imported 0 or 1e9 would otherwise reach the history store.
+ if (typeof incoming.historyLimit === "number" && Number.isFinite(incoming.historyLimit)) {
+ incoming.historyLimit = Math.max(10, Math.min(500, Math.floor(incoming.historyLimit)));
+ } else {
+ incoming.historyLimit = initialSettings.historyLimit;
+ }
+
// v0.28.0: `legalConsentVersion` added. A non-number / non-finite / negative
// value must fall through to "never accepted" (0) so a corrupt or
// hand-edited file re-shows the consent gate rather than silently skipping
diff --git a/src/store/settings-store.ts b/src/store/settings-store.ts
index 16a655e..0915165 100644
--- a/src/store/settings-store.ts
+++ b/src/store/settings-store.ts
@@ -106,6 +106,12 @@ export const useSettingsStore = create()(
// lockstep — nothing enforces that mechanically.
version: 12,
migrate: (persistedState: unknown): SettingsData => healSettings(persistedState),
+ // Heal on EVERY load, not only on a version change (which is all
+ // `migrate` covers): a hand-edited value must never reach the app.
+ merge: (persistedState, currentState) => ({
+ ...currentState,
+ ...healSettings(persistedState),
+ }),
partialize: (state) => extractData(state),
onRehydrateStorage: () => {
return () => {
diff --git a/src/store/template-store.ts b/src/store/template-store.ts
index 7421873..cc1eb73 100644
--- a/src/store/template-store.ts
+++ b/src/store/template-store.ts
@@ -26,6 +26,7 @@ import type {
} from "@config/graphics-settings";
import { coerceUpscaleQuality, coerceFrameGenMultiplier } from "@engine/graphics-vendor";
import type { GachaQuestType } from "@config/gacha-quest-types";
+import { migrateRig } from "@config/rig-fields";
/**
* Full snapshot of the editor form. Matches the `partialize` output of
@@ -219,9 +220,20 @@ export const useTemplateStore = create()(
// doesn't push a stale value into the editor's Select. The
// editor's own normalizeEditorPatch repeats this coercion as a
// belt-and-suspenders measure.
- version: 1,
+ // v1 → v2: v1.0.0 GPU catalog (`brand|series|model` → `gpu:`).
+ version: 2,
migrate: (persistedState: unknown, version: number) => {
if (!persistedState || typeof persistedState !== "object") return persistedState;
+ if (version < 2) {
+ const state = persistedState as { templates?: EditorTemplate[] };
+ if (Array.isArray(state.templates)) {
+ for (const tpl of state.templates) {
+ if (tpl?.snapshot && typeof tpl.snapshot === "object") {
+ tpl.snapshot.rig = migrateRig(tpl.snapshot.rig);
+ }
+ }
+ }
+ }
if (version < 1) {
const state = persistedState as { templates?: EditorTemplate[] };
if (Array.isArray(state.templates)) {
diff --git a/src/utils/rig-validation.ts b/src/utils/rig-validation.ts
index d0e3147..43a8ba1 100644
--- a/src/utils/rig-validation.ts
+++ b/src/utils/rig-validation.ts
@@ -1,5 +1,4 @@
-import { parseCascadingValue, parseCompositeValue } from "@config/rig-fields";
-import { GPU_CUSTOM_BRAND_ID } from "@config/gpu-catalog";
+import { parseCompositeValue } from "@config/rig-fields";
/**
* Validation outcome for a rig field. `kind` carries the i18n key used
@@ -8,51 +7,18 @@ import { GPU_CUSTOM_BRAND_ID } from "@config/gpu-catalog";
*/
export interface RigValidationIssue {
kind: "incomplete" | "invalid";
- /** i18n key under `editor.validation.*` (e.g. `editor.validation.incompleteGpu`). */
+ /** i18n key under `editor.validation.*` (e.g. `editor.validation.ramMissingDdr`). */
messageKey: string;
}
-/**
- * GPU cascading-dropdown validator (v0.13). Surfaces a soft warning
- * when the user picks a brand but hasn't drilled down to a concrete
- * model — partial selections cause "AMD" / "NVIDIA" to appear alone in
- * the description, which is technically valid but rarely intentional.
- *
- * Custom brand: requires a non-empty free-text value, otherwise the
- * stored `"custom||"` collapses to nothing in the description.
- *
- * Returns `null` when the value is fully blank (no selection at all is
- * a deliberate "skip rig field" state and shouldn't trip the badge).
- */
-export function validateGpuValue(raw: string): RigValidationIssue | null {
- if (!raw) return null;
- const { brand, series, model, isLegacy } = parseCascadingValue(raw);
- if (isLegacy) return null;
-
- if (brand === GPU_CUSTOM_BRAND_ID) {
- if (!model.trim()) {
- return { kind: "incomplete", messageKey: "editor.validation.gpuCustomEmpty" };
- }
- return null;
- }
-
- if (brand && !series) {
- return { kind: "incomplete", messageKey: "editor.validation.gpuMissingSeries" };
- }
- if (brand && series && !model) {
- return { kind: "incomplete", messageKey: "editor.validation.gpuMissingModel" };
- }
- return null;
-}
-
/**
* RAM composite-dropdown validator (v0.13). Surfaces a warning when the
- * user picks a size but no DDR generation, or vice-versa — the resulting
+ * user picks a size but no memory type, or vice-versa — the resulting
* description line ("32 GB" or just "DDR5") is awkward enough that we
- * nudge the creator to fill in the other half.
+ * nudge the creator to fill in the other half. The speed is optional.
*
- * Custom size with empty numeric input is also flagged so the user
- * doesn't accidentally render a `"GB"` with no number.
+ * Custom size with an empty input is also flagged so the user doesn't
+ * accidentally render a "GB" with no number.
*/
export function validateRamValue(raw: string): RigValidationIssue | null {
if (!raw) return null;
diff --git a/src/utils/validation.ts b/src/utils/validation.ts
index cd484bc..cb55026 100644
--- a/src/utils/validation.ts
+++ b/src/utils/validation.ts
@@ -1,5 +1,7 @@
+// The domain must have a dot and a letters-only TLD: "name@localhost" or
+// "name@gmail" are typos in a description, not addresses (v1.0.0).
const EMAIL_REGEX =
- /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
+ /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*\.[a-zA-Z]{2,63}$/;
const URL_REGEX =
/^https?:\/\/[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]*[a-zA-Z0-9])?)+([/?#].*)?$/;
@@ -91,6 +93,18 @@ export function validateUrl(input: string): ValidationResult {
return { valid: true };
}
+/**
+ * A URL reduced for prefix comparison: lower-case, no `www.` / `m.` /
+ * `mobile.` host prefix, and twitter.com read as x.com — so
+ * "https://www.instagram.com/me" matches the prefix "https://instagram.com/".
+ */
+function comparableUrl(url: string): string {
+ return url
+ .toLowerCase()
+ .replace(/^(https?:\/\/)(?:www\.|m\.|mobile\.)/, "$1")
+ .replace(/^(https?:\/\/)twitter\.com\//, "$1x.com/");
+}
+
export function validateUrlWithPrefix(input: string, expectedPrefix: string): ValidationResult {
const baseResult = validateUrl(input);
if (!baseResult.valid) return baseResult;
@@ -98,7 +112,7 @@ export function validateUrlWithPrefix(input: string, expectedPrefix: string): Va
const trimmed = input.trim();
if (!trimmed) return { valid: true };
- if (expectedPrefix && !trimmed.startsWith(expectedPrefix)) {
+ if (expectedPrefix && !comparableUrl(trimmed).startsWith(comparableUrl(expectedPrefix))) {
return {
valid: true,
error: "validation.urlPrefixMismatch",
@@ -145,9 +159,22 @@ export function validateUrlWithPattern(input: string, pattern: RegExp): Validati
* the path must be exactly `/playlist`.
*/
const YT_PLAYLIST_REGEX =
- /^https:\/\/(?:www\.)?youtube\.com\/playlist\?(?:[^#]*&)?list=[A-Za-z0-9_-]+(?:&[^#]*)?(?:#.*)?$/;
+ /^https:\/\/(?:www\.|m\.|music\.)?youtube\.com\/(?:playlist|watch)\?(?:[^#]*&)?list=[A-Za-z0-9_-]+(?:&[^#]*)?(?:#.*)?$/;
const PLAYLIST_URL_EXPECTED = "https://www.youtube.com/playlist?list=[id]";
+/**
+ * The canonical playlist page for any accepted playlist URL — a phone
+ * (`m.`), YouTube Music or "video in a playlist" (`watch?v=…&list=…`)
+ * link becomes `https://www.youtube.com/playlist?list=`, which is what
+ * the description should point at. Anything else is returned unchanged.
+ */
+export function normalizePlaylistUrl(input: string): string {
+ const trimmed = input.trim();
+ if (!YT_PLAYLIST_REGEX.test(trimmed)) return input;
+ const id = /[?&]list=([A-Za-z0-9_-]+)/.exec(trimmed)?.[1];
+ return id ? `https://www.youtube.com/playlist?list=${id}` : input;
+}
+
export function validatePlaylistUrl(input: string): ValidationResult {
const trimmed = input.trim();
if (!trimmed) return { valid: true };
diff --git a/tests/config/gpu-catalog.test.ts b/tests/config/gpu-catalog.test.ts
new file mode 100644
index 0000000..2b6f818
--- /dev/null
+++ b/tests/config/gpu-catalog.test.ts
@@ -0,0 +1,96 @@
+import { describe, it, expect } from "vitest";
+import {
+ GPU_GROUPS,
+ findGpuModel,
+ formatGpuValue,
+ gpuValue,
+ migrateGpuValue,
+ modelForGpuValue,
+} from "@config/gpu-catalog";
+
+const ALL = GPU_GROUPS.flatMap((g) => g.models);
+
+describe("GPU catalog", () => {
+ it("has unique ids and names", () => {
+ expect(new Set(ALL.map((m) => m.id)).size).toBe(ALL.length);
+ expect(new Set(ALL.map((m) => m.name)).size).toBe(ALL.length);
+ });
+
+ it("uses each vendor's own naming", () => {
+ for (const group of GPU_GROUPS) {
+ for (const model of group.models) {
+ if (group.vendor === "nvidia") expect(model.name).toMatch(/^NVIDIA (GeForce |TITAN)/);
+ if (group.vendor === "amd") expect(model.name).toMatch(/^AMD Radeon /);
+ if (group.vendor === "intel") expect(model.name).toMatch(/^Intel /);
+ if (group.vendor === "apple") expect(model.name).toMatch(/^Apple M\d/);
+ }
+ }
+ });
+
+ it("does not list cards that never shipped", () => {
+ const names = ALL.map((m) => m.name);
+ for (const ghost of ["RX 9080", "RX 9090 XT", "Arc B380", "Arc B770", "RTX 5080 SUPER"]) {
+ expect(names.some((n) => n.endsWith(ghost))).toBe(false);
+ }
+ });
+
+ it("includes laptop, integrated, handheld and current Apple parts", () => {
+ for (const id of [
+ "nvidia-rtx-5070-laptop-gpu",
+ "nvidia-rtx-4050-laptop-gpu",
+ "amd-rx-9070-gre",
+ "amd-890m",
+ "amd-8060s",
+ "intel-arc-140v",
+ "amd-ryzen-z2-extreme",
+ "valve-steam-deck",
+ "apple-m5-max",
+ ]) {
+ expect(findGpuModel(id), id).toBeDefined();
+ }
+ });
+
+ it("round-trips a catalog value", () => {
+ const model = findGpuModel("nvidia-rtx-5080");
+ expect(model).toBeDefined();
+ if (!model) return;
+ expect(modelForGpuValue(gpuValue(model))).toBe(model);
+ expect(formatGpuValue(gpuValue(model))).toBe("NVIDIA GeForce RTX 5080");
+ });
+});
+
+describe("migrateGpuValue", () => {
+ it("maps every v0.13 catalog model to a current id", () => {
+ const cases: Array<[string, string]> = [
+ ["nvidia|rtx_50|RTX 5080", "gpu:nvidia-rtx-5080"],
+ ["nvidia|rtx_40|RTX 4060 Ti", "gpu:nvidia-rtx-4060-ti"],
+ ["nvidia|rtx_20|TITAN RTX", "gpu:nvidia-titan-rtx"],
+ ["nvidia|gtx_900|TITAN X (Maxwell)", "gpu:nvidia-gtx-titan-x"],
+ ["nvidia|gtx_700|TITAN Black", "gpu:nvidia-gtx-titan-black"],
+ ["amd|rx_9000|RX 9070 XT", "gpu:amd-rx-9070-xt"],
+ ["amd|rx_vega|Radeon VII", "gpu:amd-vii"],
+ ["amd|hd_7000|HD 7970", "gpu:amd-hd-7970"],
+ ["intel|arc_b|Arc B580", "gpu:intel-arc-b580"],
+ ["apple|m1|M1 Ultra", "gpu:apple-m1-ultra"],
+ ];
+ for (const [legacy, current] of cases) expect(migrateGpuValue(legacy), legacy).toBe(current);
+ });
+
+ it("keeps an unmatched card as its full name", () => {
+ expect(migrateGpuValue("amd|rx_9000|RX 9080")).toBe("AMD Radeon RX 9080");
+ expect(migrateGpuValue("intel|arc_b|Arc B380")).toBe("Intel Arc B380");
+ expect(migrateGpuValue("nvidia|rtx_40|RTX 4090 D")).toBe("NVIDIA GeForce RTX 4090 D");
+ });
+
+ it("unwraps the old Custom brand and clears half-picked values", () => {
+ expect(migrateGpuValue("custom||My GPU")).toBe("My GPU");
+ expect(migrateGpuValue("nvidia|rtx_40|")).toBe("");
+ expect(migrateGpuValue("||")).toBe("");
+ });
+
+ it("leaves current values and free text alone", () => {
+ expect(migrateGpuValue("gpu:amd-rx-7800-xt")).toBe("gpu:amd-rx-7800-xt");
+ expect(migrateGpuValue("GeForce RTX 3060 12GB")).toBe("GeForce RTX 3060 12GB");
+ expect(migrateGpuValue("")).toBe("");
+ });
+});
diff --git a/tests/config/platforms.test.ts b/tests/config/platforms.test.ts
new file mode 100644
index 0000000..1e5eae1
--- /dev/null
+++ b/tests/config/platforms.test.ts
@@ -0,0 +1,71 @@
+import { describe, it, expect } from "vitest";
+import { PLATFORMS } from "@config/platforms";
+
+const platform = (id: string) => {
+ const p = PLATFORMS.find((x) => x.id === id);
+ if (!p) throw new Error(`no platform ${id}`);
+ return p;
+};
+
+describe("store URL patterns (v1.0.0)", () => {
+ it("accepts Steam apps, packages, bundles and short links", () => {
+ const steam = platform("steam");
+ for (const url of [
+ "https://store.steampowered.com/app/1245620/ELDEN_RING/",
+ "https://store.steampowered.com/sub/469080/",
+ "https://store.steampowered.com/bundle/5699/Portal_Bundle/",
+ "https://s.team/a/1245620",
+ ]) {
+ expect(steam.urlPattern.test(url), url).toBe(true);
+ }
+ expect(steam.urlPattern.test("https://store.steampowered.com/search/?term=elden")).toBe(false);
+ });
+
+ it("normalises Steam links to the canonical page", () => {
+ const normalize = platform("steam").normalize;
+ expect(normalize?.("https://store.steampowered.com/app/1245620/ELDEN_RING/")).toBe(
+ "https://store.steampowered.com/app/1245620",
+ );
+ expect(normalize?.("https://s.team/a/1245620")).toBe(
+ "https://store.steampowered.com/app/1245620",
+ );
+ expect(normalize?.("https://store.steampowered.com/sub/469080/")).toBe(
+ "https://store.steampowered.com/sub/469080",
+ );
+ });
+
+ it("accepts store hosts with or without www", () => {
+ expect(platform("gog").urlPattern.test("https://gog.com/en/game/cyberpunk_2077")).toBe(true);
+ expect(platform("humble").urlPattern.test("https://humblebundle.com/store/hades")).toBe(true);
+ expect(
+ platform("xbox").urlPattern.test("https://xbox.com/en-US/games/store/x/9NBLGGH4R315"),
+ ).toBe(true);
+ });
+
+ it("accepts the Microsoft Store and every regional Nintendo site", () => {
+ expect(platform("xbox").urlPattern.test("https://apps.microsoft.com/detail/9nblggh4r315")).toBe(
+ true,
+ );
+ for (const url of [
+ "https://www.nintendo.com/us/store/products/hades-switch/",
+ "https://www.nintendo.co.uk/Games/Nintendo-Switch-download-software/Hades-1839136.html",
+ "https://www.nintendo.de/Spiele/Hades-1839136.html",
+ "https://store.nintendo.co.uk/en_gb/hades",
+ "https://www.nintendo.co.jp/switch/aqfta/",
+ ]) {
+ expect(platform("nintendo").urlPattern.test(url), url).toBe(true);
+ }
+ });
+
+ it("accepts Amazon Luna's own site", () => {
+ expect(platform("amazon").urlPattern.test("https://luna.amazon.com/game/fortnite/B0C1")).toBe(
+ true,
+ );
+ });
+
+ it("gives every searchable platform a tag name", () => {
+ for (const p of PLATFORMS) {
+ if (p.id !== "publisher") expect(p.tagName, p.id).toBeTruthy();
+ }
+ });
+});
diff --git a/tests/engine/description-builder.test.ts b/tests/engine/description-builder.test.ts
index 166f402..8b506d6 100644
--- a/tests/engine/description-builder.test.ts
+++ b/tests/engine/description-builder.test.ts
@@ -710,14 +710,46 @@ describe("buildDescription", () => {
expect(result).toContain("GPU: RTX 4090");
});
- it("humanises snake_case rig keys (e.g. video_editor → VIDEO EDITOR)", () => {
+ it("labels rig lines in the output language, not as capitalised keys", () => {
+ const rig = { video_editor: "davinci_resolve_studio|19.1", storage: "2TB NVMe" };
+ const en = buildDescription(makeInput({ rig }), createMockT("en"));
+ expect(en).toContain("Video Editor: DaVinci Resolve Studio 19.1");
+ expect(en).not.toContain("VIDEO EDITOR");
+ expect(en).not.toContain("VIDEO_EDITOR");
+
+ const vi = buildDescription(makeInput({ language: "vi", rig }), createMockT("vi"));
+ expect(vi).toContain("Phần mềm dựng video: DaVinci Resolve Studio 19.1");
+ expect(vi).toContain("Ổ cứng: 2TB NVMe");
+ });
+
+ it("prints rig lines in a fixed order, whatever order they were filled in", () => {
const t = createMockT("en");
const result = buildDescription(
- makeInput({ rig: { video_editor: "davinci_resolve_studio|19.1" } }),
+ makeInput({
+ rig: {
+ os: "windows|11|pro",
+ ram: "32|DDR5|6000",
+ gpu: "gpu:nvidia-rtx-5080",
+ cpu: "AMD Ryzen 7 9800X3D",
+ },
+ }),
t,
);
- expect(result).toContain("VIDEO EDITOR: DaVinci Resolve Studio 19.1");
- expect(result).not.toContain("VIDEO_EDITOR");
+ const block = result.slice(result.indexOf("MY RIG"));
+ const order = ["CPU:", "GPU:", "RAM:", "Operating System:"].map((label) =>
+ block.indexOf(label),
+ );
+ expect(order.every((i) => i > 0)).toBe(true);
+ expect([...order].sort((a, b) => a - b)).toEqual(order);
+ expect(block).toContain("GPU: NVIDIA GeForce RTX 5080");
+ expect(block).toContain("RAM: 32 GB DDR5-6000");
+ });
+
+ it("names a pre-v1.0 GPU value properly", () => {
+ const t = createMockT("en");
+ const result = buildDescription(makeInput({ rig: { gpu: "amd|rx_9000|RX 9070 XT" } }), t);
+ expect(result).toContain("GPU: AMD Radeon RX 9070 XT");
+ expect(result).not.toContain("GPU: AMD RX");
});
it("legacy spoilerWarning boolean no longer renders a standalone block (v0.11 deprecation)", () => {
diff --git a/tests/engine/limits.test.ts b/tests/engine/limits.test.ts
index b62cdab..86d89ab 100644
--- a/tests/engine/limits.test.ts
+++ b/tests/engine/limits.test.ts
@@ -3,6 +3,9 @@ import {
getOutputLimitStatus,
mergeLimitStatus,
EMPTY_LIMIT_STATUS,
+ fieldsWithForbiddenChars,
+ isFieldOver,
+ isCopyAllBlocked,
type OutputLimitStatus,
} from "@engine/limits";
import { renderAll } from "@engine/template-renderer";
@@ -129,3 +132,33 @@ describe("integration with renderAll", () => {
expect(getOutputLimitStatus({ warnings: [] }).blocked).toBe(false);
});
});
+
+describe("fieldsWithForbiddenChars", () => {
+ it("names the fields YouTube would refuse", () => {
+ expect(fieldsWithForbiddenChars({ title: "A <3 B", description: "ok" })).toEqual(["title"]);
+ expect(fieldsWithForbiddenChars({ title: "ok", description: "x > y" })).toEqual([
+ "description",
+ ]);
+ expect(fieldsWithForbiddenChars({ title: "ok", description: "ok" })).toEqual([]);
+ });
+});
+
+describe("per-field copy gating (v1.0.0)", () => {
+ const status: OutputLimitStatus = {
+ blocked: true,
+ overflows: [{ field: "tags", current: 520, limit: 500 }],
+ };
+ it("blocks only the field that is over", () => {
+ expect(isFieldOver(status, "tags")).toBe(true);
+ expect(isFieldOver(status, "title")).toBe(false);
+ });
+ it("doesn't block Copy All for tags it doesn't contain", () => {
+ expect(isCopyAllBlocked(status)).toBe(false);
+ expect(
+ isCopyAllBlocked({
+ blocked: true,
+ overflows: [{ field: "description", current: 5100, limit: 5000 }],
+ }),
+ ).toBe(true);
+ });
+});
diff --git a/tests/engine/rig-fields.test.ts b/tests/engine/rig-fields.test.ts
index e3a5d7a..9be44cc 100644
--- a/tests/engine/rig-fields.test.ts
+++ b/tests/engine/rig-fields.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { formatRigValue, RIG_FIELDS } from "@config/rig-fields";
+import { cleanCpuName, formatRigValue, migrateRig, RIG_FIELDS } from "@config/rig-fields";
describe("formatRigValue", () => {
it("passes text fields through unchanged", () => {
@@ -37,44 +37,76 @@ describe("formatRigValue", () => {
expect(field?.options?.length).toBeGreaterThan(3);
});
- describe("cascading_dropdown (GPU, v0.13)", () => {
- it("formats brand + model and drops the redundant series label", () => {
- expect(formatRigValue("gpu", "nvidia|rtx_40|RTX 4090")).toBe("NVIDIA RTX 4090");
+ it("orders the fields CPU, GPU, RAM first", () => {
+ expect(RIG_FIELDS.slice(0, 3).map((f) => f.id)).toEqual(["cpu", "gpu", "ram"]);
+ });
+
+ describe("GPU (v1.0.0 catalog)", () => {
+ it("prints the official name of a catalog card", () => {
+ expect(formatRigValue("gpu", "gpu:nvidia-rtx-5080")).toBe("NVIDIA GeForce RTX 5080");
+ expect(formatRigValue("gpu", "gpu:amd-rx-9070-xt")).toBe("AMD Radeon RX 9070 XT");
+ expect(formatRigValue("gpu", "gpu:apple-m4-pro")).toBe("Apple M4 Pro");
+ expect(formatRigValue("gpu", "gpu:nvidia-titan-rtx")).toBe("NVIDIA TITAN RTX");
});
- it("returns the verbatim model for the Custom brand", () => {
+ it("names pre-v1.0 values properly", () => {
+ expect(formatRigValue("gpu", "nvidia|rtx_40|RTX 4090")).toBe("NVIDIA GeForce RTX 4090");
+ expect(formatRigValue("gpu", "apple|m4|M4 Pro")).toBe("Apple M4 Pro");
+ expect(formatRigValue("gpu", "nvidia|rtx_40|RTX 4050 (laptop)")).toBe(
+ "NVIDIA GeForce RTX 4050 Laptop GPU",
+ );
+ });
+
+ it("returns the verbatim text for the old Custom brand", () => {
expect(formatRigValue("gpu", "custom||RX 7800 XT (OC)")).toBe("RX 7800 XT (OC)");
});
- it("renders just the brand label when model is empty", () => {
- expect(formatRigValue("gpu", "amd|rx_7000|")).toBe("AMD");
- });
-
it("returns empty string when nothing is selected", () => {
expect(formatRigValue("gpu", "")).toBe("");
expect(formatRigValue("gpu", "||")).toBe("");
});
- it("passes legacy free-text values through unchanged", () => {
- // Pre-v0.13 rigs persisted GPU as plain text. Round-trip those.
+ it("passes the user's own text through unchanged", () => {
expect(formatRigValue("gpu", "NVIDIA GeForce RTX 4090")).toBe("NVIDIA GeForce RTX 4090");
});
+
+ it("prints nothing for a catalog id that no longer exists", () => {
+ expect(formatRigValue("gpu", "gpu:does-not-exist")).toBe("");
+ });
});
- describe("composite_dropdown (RAM, v0.13)", () => {
- it("formats preset size + DDR generation", () => {
+ describe("RAM", () => {
+ it("formats size + type", () => {
expect(formatRigValue("ram", "16|DDR5")).toBe("16 GB DDR5");
});
- it("supports a custom numeric size", () => {
+ it("formats size + type + speed the way kits are named", () => {
+ expect(formatRigValue("ram", "32|DDR5|6000")).toBe("32 GB DDR5-6000");
+ expect(formatRigValue("ram", "16|LPDDR5X|8533")).toBe("16 GB LPDDR5X-8533");
+ });
+
+ it("gives a lone speed its unit", () => {
+ expect(formatRigValue("ram", "32||6000")).toBe("32 GB 6000 MT/s");
+ });
+
+ it("supports a custom size", () => {
expect(formatRigValue("ram", "custom:48|DDR5")).toBe("48 GB DDR5");
});
- it("renders only the size when DDR is empty", () => {
+ it("doesn't double the unit when the user typed it (was '48GB GB')", () => {
+ expect(formatRigValue("ram", "custom:48GB|DDR5")).toBe("48 GB DDR5");
+ expect(formatRigValue("ram", "custom:48 gb|DDR5")).toBe("48 GB DDR5");
+ });
+
+ it("prints the first DDR generation as plain DDR", () => {
+ expect(formatRigValue("ram", "4|DDR1")).toBe("4 GB DDR");
+ });
+
+ it("renders only the size when the type is empty", () => {
expect(formatRigValue("ram", "32|")).toBe("32 GB");
});
- it("renders only DDR when size is empty", () => {
+ it("renders only the type when the size is empty", () => {
expect(formatRigValue("ram", "|DDR4")).toBe("DDR4");
});
@@ -89,7 +121,7 @@ describe("formatRigValue", () => {
});
});
- describe("composite_dropdown (OS, v0.22.0)", () => {
+ describe("OS", () => {
it("formats name + version + edition", () => {
expect(formatRigValue("os", "windows|11|pro")).toBe("Windows 11 Pro");
});
@@ -102,13 +134,9 @@ describe("formatRigValue", () => {
expect(formatRigValue("os", "windows||home")).toBe("Windows Home");
});
- it("falls back to raw values when name is empty (v0.23.0 cascading change)", () => {
- // Defensive — pre-v0.23 static OS_EDITION_OPTIONS resolved
- // "enterprise" → "Enterprise" regardless of name. Post-v0.23 the
- // option list cascades from name; an empty name means no option
- // list applies, so the raw stored values pass through verbatim.
- // A real editor session always sets name first, so this is purely
- // a hand-edited / malformed-blob guard.
+ it("falls back to raw values when name is empty", () => {
+ // An empty name means no option list applies, so the raw stored
+ // values pass through verbatim. Only a hand-edited blob does this.
expect(formatRigValue("os", "|10|enterprise")).toBe("10 enterprise");
});
@@ -117,61 +145,73 @@ describe("formatRigValue", () => {
expect(formatRigValue("os", "||")).toBe("");
});
- it("includes an OS entry in RIG_FIELDS as the first field", () => {
- expect(RIG_FIELDS[0]?.id).toBe("os");
- expect(RIG_FIELDS[0]?.type).toBe("composite_dropdown");
- });
- });
-
- describe("composite_dropdown (OS cascading, v0.23.0)", () => {
it("renders macOS version-only — third slot hidden", () => {
expect(formatRigValue("os", "macos|15 Sequoia|")).toBe("macOS 15 Sequoia");
- });
-
- it("renders macOS Tahoe (the 2025 year-aligned jump)", () => {
expect(formatRigValue("os", "macos|26 Tahoe|")).toBe("macOS 26 Tahoe");
});
- it("renders Linux distro + version with three visible parts", () => {
- expect(formatRigValue("os", "linux|ubuntu|22.04 LTS")).toBe("Linux Ubuntu 22.04 LTS");
- });
-
- it("renders Linux rolling distros (Arch) with the placeholder version", () => {
- expect(formatRigValue("os", "linux|arch|rolling")).toBe("Linux Arch rolling");
- });
-
- it("renders Linux Fedora with a numeric version", () => {
- expect(formatRigValue("os", "linux|fedora|40")).toBe("Linux Fedora 40");
- });
-
- it("renders just distro name when version slot is empty", () => {
- expect(formatRigValue("os", "linux|debian|")).toBe("Linux Debian");
- });
-
- it("falls back gracefully when macOS edition slot carries stale data", () => {
- // Hand-edited / future-downgrade case: macOS with a third
- // segment. Engine should skip it (hiddenWhen) rather than
- // surfacing "macOS 15 Sequoia pro".
+ it("skips a stale edition on macOS", () => {
expect(formatRigValue("os", "macos|15 Sequoia|pro")).toBe("macOS 15 Sequoia");
});
- it("preserves v0.22.0 Windows storage shape (backward-compat guard)", () => {
- // Pre-v0.23 stored values must round-trip identically — this
- // case validates the editor-store v13/v14 doesn't need a
- // dedicated OS migration step.
- expect(formatRigValue("os", "windows|11|pro")).toBe("Windows 11 Pro");
+ it("names a Linux system by its distro", () => {
+ expect(formatRigValue("os", "linux|ubuntu|22.04 LTS")).toBe("Ubuntu 22.04 LTS");
+ expect(formatRigValue("os", "linux|fedora|43")).toBe("Fedora 43");
+ expect(formatRigValue("os", "linux|debian|")).toBe("Debian");
+ expect(formatRigValue("os", "linux|steamos|3")).toBe("SteamOS 3");
+ });
+
+ it("puts rolling / latest in parentheses", () => {
+ expect(formatRigValue("os", "linux|arch|rolling")).toBe("Arch Linux (rolling)");
+ expect(formatRigValue("os", "linux|bazzite|latest")).toBe("Bazzite (latest stable)");
+ });
+
+ it("prints plain Linux when no distro is chosen", () => {
+ expect(formatRigValue("os", "linux||")).toBe("Linux");
+ });
+
+ it("preserves the v0.22.0 Windows storage shape", () => {
expect(formatRigValue("os", "windows|10|enterprise")).toBe("Windows 10 Enterprise");
});
});
+});
- describe("RAM composite — regression guard for v0.23.0 type widening", () => {
- it("still resolves static option arrays after CompositePart.options widened to a union", () => {
- // The v0.23.0 change made CompositePart.options accept either a
- // static array (RAM-style) or a function (OS cascading). RAM uses
- // the static form — re-running its formatter ensures the union
- // didn't break the simpler path.
- expect(formatRigValue("ram", "16|DDR5")).toBe("16 GB DDR5");
- expect(formatRigValue("ram", "custom:48|DDR5")).toBe("48 GB DDR5");
+describe("cleanCpuName", () => {
+ it("strips Windows' trademark marks and clock suffix", () => {
+ expect(cleanCpuName("Intel(R) Core(TM) i9-9900K CPU @ 3.60GHz")).toBe("Intel Core i9-9900K");
+ expect(cleanCpuName("12th Gen Intel(R) Core(TM) i7-12700K")).toBe("Intel Core i7-12700K");
+ });
+
+ it("drops AMD's core-count suffix", () => {
+ expect(cleanCpuName("AMD Ryzen 7 7800X3D 8-Core Processor")).toBe("AMD Ryzen 7 7800X3D");
+ expect(cleanCpuName("AMD Ryzen 7 7840HS w/ Radeon 780M Graphics")).toBe(
+ "AMD Ryzen 7 7840HS w/ Radeon 780M Graphics",
+ );
+ expect(cleanCpuName("AMD Ryzen 5 5600G with Radeon Graphics")).toBe("AMD Ryzen 5 5600G");
+ });
+
+ it("leaves clean or unknown text alone apart from whitespace", () => {
+ expect(cleanCpuName(" Apple M4 Pro ")).toBe("Apple M4 Pro");
+ expect(cleanCpuName("Ryzen 9 7950X")).toBe("Ryzen 9 7950X");
+ });
+});
+
+describe("migrateRig", () => {
+ it("converts the GPU and keeps the rest", () => {
+ expect(migrateRig({ gpu: "nvidia|rtx_50|RTX 5080", cpu: "Ryzen 7 9800X3D" })).toEqual({
+ gpu: "gpu:nvidia-rtx-5080",
+ cpu: "Ryzen 7 9800X3D",
});
+ });
+
+ it("drops non-string values and survives null", () => {
+ expect(migrateRig({ gpu: null, ram: 32, cpu: "x" })).toEqual({ cpu: "x" });
+ expect(migrateRig(null)).toEqual({});
+ expect(migrateRig("nope")).toEqual({});
+ });
+
+ it("is idempotent", () => {
+ const once = migrateRig({ gpu: "amd|rx_9000|RX 9080" });
+ expect(migrateRig(once)).toEqual(once);
});
});
diff --git a/tests/engine/tag-generator.test.ts b/tests/engine/tag-generator.test.ts
index 021fab6..eb5bb67 100644
--- a/tests/engine/tag-generator.test.ts
+++ b/tests/engine/tag-generator.test.ts
@@ -4,7 +4,12 @@ import {
formatTagString,
tagFriendlyGameName,
sanitizeForTag,
+ youtubeTagsLength,
+ trimToCharLimit,
+ GENRE_TAG_REGISTRY,
+ GENRE_SEARCH_TERMS,
} from "@engine/tag-generator";
+import { GENRES } from "@config/genres";
import type { GeneratorInput } from "@engine/types";
function makeInput(overrides: Partial = {}): GeneratorInput {
@@ -301,3 +306,69 @@ describe("tagFriendlyGameName — punctuation sanitization (v0.20.0)", () => {
expect(tagFriendlyGameName("Hello, World", 30)).toBe("Hello World");
});
});
+
+describe("tag length as YouTube counts it (v1.0.0)", () => {
+ it("counts quotes around multi-word tags and one comma between tags", () => {
+ expect(youtubeTagsLength([])).toBe(0);
+ expect(youtubeTagsLength(["rpg"])).toBe(3);
+ // "rpg" (3) + "\"open world\"" (12) + one comma
+ expect(youtubeTagsLength(["rpg", "open world"])).toBe(16);
+ });
+
+ it("never produces more than 500 by YouTube's count", () => {
+ const tags = generateTags(
+ makeInput({
+ gameName: "The Legend of Heroes Trails through Daybreak",
+ genres: ["jrpg", "action_rpg", "openworld"],
+ videoType: "collectibles",
+ resolution: "4K",
+ fps: "120",
+ pubDevName: "Nihon Falcom",
+ }),
+ { year: 2026 },
+ );
+ expect(youtubeTagsLength(tags)).toBeLessThanOrEqual(500);
+ });
+
+ it("keeps trying shorter tags after one that doesn't fit", () => {
+ const long = "x".repeat(20) + " long tag";
+ const kept = trimToCharLimit(["a".repeat(10), long, "short"], 20);
+ expect(kept).toEqual(["a".repeat(10), "short"]);
+ });
+});
+
+describe("platform and trending tags (v1.0.0)", () => {
+ it("names the platform the way people search for it", () => {
+ const steam = generateTags(makeInput({ platform: "steam" }));
+ expect(steam).toContain("Elden Ring Steam");
+ expect(steam.some((t) => t.includes("STEAM"))).toBe(false);
+
+ const itch = generateTags(makeInput({ gameName: "Celeste", platform: "itchio" }));
+ expect(itch).toContain("itch.io gameplay");
+ expect(itch.some((t) => t.includes("ITCHIO"))).toBe(false);
+ });
+
+ it("adds no platform tags for a publisher's own site", () => {
+ const tags = generateTags(makeInput({ platform: "publisher" }));
+ expect(tags.some((t) => /publisher/i.test(t))).toBe(false);
+ });
+
+ it("uses search terms and the given year in trending tags", () => {
+ const tags = generateTags(makeInput({ genres: ["openworld"] }), { year: 2031 });
+ expect(tags).toContain("best open world games 2031");
+ expect(tags.some((t) => t.includes("openworld"))).toBe(false);
+ });
+
+ it("has a tag pool and a search term for every genre", () => {
+ const ids = GENRES.map((g) => g.id);
+ expect(Object.keys(GENRE_TAG_REGISTRY).sort()).toEqual([...ids].sort());
+ expect(Object.keys(GENRE_SEARCH_TERMS).sort()).toEqual([...ids].sort());
+ });
+
+ it("keeps each genre's pool on its own genre", () => {
+ const rpg = GENRE_TAG_REGISTRY.rpg?.("X") ?? [];
+ expect(rpg.some((t) => t.includes("JRPG"))).toBe(false);
+ const cards = GENRE_TAG_REGISTRY.card_game?.("X") ?? [];
+ expect(cards.some((t) => t.includes("deck builder"))).toBe(false);
+ });
+});
diff --git a/tests/engine/timeline-rules.test.ts b/tests/engine/timeline-rules.test.ts
new file mode 100644
index 0000000..418bf07
--- /dev/null
+++ b/tests/engine/timeline-rules.test.ts
@@ -0,0 +1,93 @@
+import { describe, it, expect } from "vitest";
+import {
+ checkChapters,
+ formatTimecode,
+ normalizeTimeline,
+ parseTimeline,
+ timecodeSeconds,
+} from "@engine/timeline-parser";
+
+const first = (line: string) => parseTimeline(line)[0];
+
+describe("keyword matching respects word boundaries (v1.0.0)", () => {
+ it("does not read a game title as a keyword", () => {
+ expect(first("1:00 Final Fantasy VII")?.keyword).toBeUndefined();
+ expect(first("1:00 Party time")?.keyword).toBeUndefined();
+ expect(first("1:00 Bossa nova")?.keyword).toBeUndefined();
+ expect(first("1:00 Introspection")?.keyword).toBeUndefined();
+ expect(first("1:00 Creditors")?.keyword).toBeUndefined();
+ });
+
+ it("still recognises the keywords themselves", () => {
+ expect(first("1:00 Introduction")).toMatchObject({ keyword: "intro" });
+ expect(first("1:00 Introduction")?.rest).toBeUndefined();
+ expect(first("1:00 Part 2")).toMatchObject({ keyword: "part", number: 2 });
+ expect(first("1:00 Boss: Malenia")).toMatchObject({ keyword: "boss", rest: ": Malenia" });
+ });
+
+ it("keeps Spanish 'Final' as an ending when it stands alone", () => {
+ expect(first("1:00 Final")).toMatchObject({ keyword: "ending" });
+ expect(first("1:00 Final 2")).toMatchObject({ keyword: "ending", number: 2 });
+ expect(first("1:00 Final: el mejor")).toMatchObject({ keyword: "ending" });
+ });
+
+ it("recognises Portuguese and Indonesian keywords", () => {
+ expect(first("0:00 Introdução")).toMatchObject({ keyword: "intro" });
+ expect(first("5:00 Chefe final")).toMatchObject({ keyword: "final_boss" });
+ expect(first("5:00 Bab 3")).toMatchObject({ keyword: "chapter", number: 3 });
+ expect(first("5:00 Bagian 2")).toMatchObject({ keyword: "part", number: 2 });
+ expect(first("9:00 Bos terakhir")).toMatchObject({ keyword: "final_boss" });
+ });
+
+ it("keeps matching CJK keywords written without spaces", () => {
+ expect(first("1:00 第3章森")).toMatchObject({ keyword: "chapter", number: 3 });
+ expect(first("1:00 オープンワールド探索")?.keyword).toBeUndefined();
+ });
+});
+
+describe("timestamp formats (v1.0.0)", () => {
+ it("accepts brackets, separators and frame counts", () => {
+ expect(first("[0:00] Intro")).toMatchObject({ time: "0:00", rawLabel: "Intro" });
+ expect(first("(1:23) Boss")).toMatchObject({ time: "1:23", rawLabel: "Boss" });
+ expect(first("0:00 - Start")).toMatchObject({ time: "0:00", rawLabel: "Start" });
+ expect(first("0:00 – Start")).toMatchObject({ time: "0:00", rawLabel: "Start" });
+ expect(first("00:01:02:15 Cutscene")).toMatchObject({ time: "00:01:02", rawLabel: "Cutscene" });
+ });
+
+ it("converts timecodes to and from seconds", () => {
+ expect(timecodeSeconds("0:00")).toBe(0);
+ expect(timecodeSeconds("12:34")).toBe(754);
+ expect(timecodeSeconds("1:02:03")).toBe(3723);
+ expect(timecodeSeconds("abc")).toBeNaN();
+ expect(formatTimecode(5)).toBe("0:05");
+ expect(formatTimecode(3723)).toBe("1:02:03");
+ });
+
+ it("normalises a list to YouTube's form", () => {
+ expect(normalizeTimeline("[00:00] Intro\n00:01:30:10 - Part 1\nnotes")).toBe(
+ "0:00 Intro\n1:30 Part 1\nnotes",
+ );
+ });
+});
+
+describe("checkChapters", () => {
+ it("accepts a valid chapter list", () => {
+ expect(checkChapters(parseTimeline("0:00 Intro\n0:30 Part 1\n5:00 Ending"))).toEqual([]);
+ });
+
+ it("has nothing to say about an empty list", () => {
+ expect(checkChapters([])).toEqual([]);
+ });
+
+ it("reports every rule YouTube enforces", () => {
+ const issues = checkChapters(parseTimeline("0:05 Intro\n0:10 Part 1"));
+ expect(issues).toContainEqual({ kind: "firstNotZero" });
+ expect(issues).toContainEqual({ kind: "tooFew", count: 2 });
+ expect(issues).toContainEqual({ kind: "tooShort", time: "0:10" });
+ });
+
+ it("flags timestamps out of order", () => {
+ const issues = checkChapters(parseTimeline("0:00 A\n2:00 B\n1:00 C"));
+ expect(issues).toContainEqual({ kind: "outOfOrder", time: "1:00" });
+ });
+});
diff --git a/tests/store/editor-store.migrate.test.ts b/tests/store/editor-store.migrate.test.ts
index 92ce4d4..c458de1 100644
--- a/tests/store/editor-store.migrate.test.ts
+++ b/tests/store/editor-store.migrate.test.ts
@@ -404,3 +404,25 @@ describe("migrateEditorState — v17 → v18 (v0.34.0 Email split)", () => {
expect(result.contactEmail).toBe("hello@channel.com");
});
});
+
+describe("migrateEditorState — v18 → v19 (v1.0.0 GPU catalog)", () => {
+ it("converts a v0.13 GPU tuple to the catalog id", () => {
+ const result = migrateEditorState({ rig: { gpu: "nvidia|rtx_50|RTX 5080", cpu: "x" } }, 18);
+ expect(result.rig).toEqual({ gpu: "gpu:nvidia-rtx-5080", cpu: "x" });
+ });
+
+ it("keeps a card the catalog doesn't know as its full name", () => {
+ const result = migrateEditorState({ rig: { gpu: "amd|rx_9000|RX 9090 XT" } }, 18);
+ expect(result.rig.gpu).toBe("AMD Radeon RX 9090 XT");
+ });
+
+ it("survives a missing or malformed rig", () => {
+ expect(migrateEditorState({ rig: null }, 18).rig).toEqual({});
+ expect(migrateEditorState({}, 18).rig).toEqual({});
+ });
+
+ it("does not touch the rig of a v19 draft", () => {
+ const rig = { gpu: "gpu:amd-rx-7800-xt" };
+ expect(migrateEditorState({ rig }, 19).rig).toEqual(rig);
+ });
+});
diff --git a/tests/store/history-store.test.ts b/tests/store/history-store.test.ts
new file mode 100644
index 0000000..c49e1cf
--- /dev/null
+++ b/tests/store/history-store.test.ts
@@ -0,0 +1,66 @@
+import { beforeEach, describe, expect, it } from "vitest";
+import {
+ dedupeHistory,
+ historyKey,
+ useHistoryStore,
+ type HistoryEntry,
+} from "@store/history-store";
+
+const base = {
+ gameName: "Elden Ring",
+ videoType: "part" as const,
+ language: "en" as const,
+ genres: ["action" as const],
+ title: "Elden Ring Part 1 — Gameplay No Commentary",
+ description: "first",
+ tags: "a, b",
+};
+
+describe("history store (v1.0.0 dedupe)", () => {
+ beforeEach(() => useHistoryStore.setState({ entries: [] }));
+
+ it("records one entry per video however often it is generated", () => {
+ const { addEntry } = useHistoryStore.getState();
+ addEntry(base);
+ addEntry(base);
+ addEntry({ ...base, description: "second" });
+ const { entries } = useHistoryStore.getState();
+ expect(entries).toHaveLength(1);
+ expect(entries[0]?.description).toBe("second");
+ });
+
+ it("keeps the entry id and moves the video to the top", () => {
+ const { addEntry } = useHistoryStore.getState();
+ addEntry(base);
+ const id = useHistoryStore.getState().entries[0]?.id;
+ addEntry({ ...base, title: "Elden Ring Part 2 — Gameplay No Commentary" });
+ addEntry(base);
+ const { entries } = useHistoryStore.getState();
+ expect(entries.map((e) => e.title)).toEqual([
+ base.title,
+ "Elden Ring Part 2 — Gameplay No Commentary",
+ ]);
+ expect(entries[0]?.id).toBe(id);
+ });
+
+ it("clamps a bad limit instead of trusting it", () => {
+ const { addEntry } = useHistoryStore.getState();
+ for (let i = 0; i < 15; i++) addEntry({ ...base, title: `T${i}` }, 3);
+ expect(useHistoryStore.getState().entries).toHaveLength(10);
+ });
+
+ it("treats a different language or type as a different video", () => {
+ expect(historyKey(base)).not.toBe(historyKey({ ...base, language: "vi" }));
+ expect(historyKey(base)).not.toBe(historyKey({ ...base, videoType: "boss" }));
+ expect(historyKey(base)).toBe(historyKey({ ...base, gameName: " elden ring " }));
+ });
+
+ it("folds old duplicates keeping the newest", () => {
+ const entry = (id: string, createdAt: string): HistoryEntry => ({ ...base, id, createdAt });
+ const folded = dedupeHistory([
+ entry("new", "2026-09-30T00:00:00Z"),
+ entry("old", "2026-09-01T00:00:00Z"),
+ ]);
+ expect(folded.map((e) => e.id)).toEqual(["new"]);
+ });
+});
diff --git a/tests/store/settings-heal.test.ts b/tests/store/settings-heal.test.ts
index ddaff13..89263f1 100644
--- a/tests/store/settings-heal.test.ts
+++ b/tests/store/settings-heal.test.ts
@@ -287,3 +287,16 @@ describe("healSettings", () => {
expect(healSettings({ legalConsentVersion: 2.9 }).legalConsentVersion).toBe(2);
});
});
+
+describe("healSettings — historyLimit (v1.0.0)", () => {
+ it("clamps the history limit into 10–500", () => {
+ expect(healSettings({ historyLimit: 1 }).historyLimit).toBe(10);
+ expect(healSettings({ historyLimit: 1e9 }).historyLimit).toBe(500);
+ expect(healSettings({ historyLimit: 250.7 }).historyLimit).toBe(250);
+ });
+
+ it("falls back to the default for a non-number", () => {
+ expect(healSettings({ historyLimit: "many" }).historyLimit).toBe(100);
+ expect(healSettings({ historyLimit: Number.NaN }).historyLimit).toBe(100);
+ });
+});
diff --git a/tests/utils/rig-validation.test.ts b/tests/utils/rig-validation.test.ts
index 3dcfdd9..ef05cbd 100644
--- a/tests/utils/rig-validation.test.ts
+++ b/tests/utils/rig-validation.test.ts
@@ -1,5 +1,5 @@
import { describe, it, expect } from "vitest";
-import { validateRamValue, validateGpuValue, validateCompositeField } from "@utils/rig-validation";
+import { validateRamValue, validateCompositeField } from "@utils/rig-validation";
describe("validateRamValue", () => {
it("flags a size with no DDR generation", () => {
@@ -27,20 +27,6 @@ describe("validateRamValue", () => {
});
});
-describe("validateGpuValue", () => {
- it("flags a brand with no series", () => {
- expect(validateGpuValue("nvidia||")?.messageKey).toBe("editor.validation.gpuMissingSeries");
- });
-
- it("flags an empty custom GPU", () => {
- expect(validateGpuValue("custom||")?.messageKey).toBe("editor.validation.gpuCustomEmpty");
- });
-
- it("passes a complete brand + series + model", () => {
- expect(validateGpuValue("nvidia|rtx_40|RTX 4090")).toBeNull();
- });
-});
-
describe("validateCompositeField (v0.24.0 — per-field validator selection)", () => {
it("validates the RAM composite", () => {
expect(validateCompositeField("ram", "32|")?.messageKey).toBe(
diff --git a/tests/utils/validation.test.ts b/tests/utils/validation.test.ts
index d7e913b..decf5d8 100644
--- a/tests/utils/validation.test.ts
+++ b/tests/utils/validation.test.ts
@@ -2,6 +2,8 @@ import { describe, it, expect } from "vitest";
import {
validateUrlWithPattern,
validatePlaylistUrl,
+ normalizePlaylistUrl,
+ validateUrlWithPrefix,
validateMessengerUrl,
validateZaloGroupUrl,
validateSignalGroupUrl,
@@ -176,10 +178,29 @@ describe("validatePlaylistUrl", () => {
expect(result.errorParams?.expected).toBe("https://www.youtube.com/playlist?list=[id]");
});
- it("rejects a watch URL with both v= and list= params", () => {
- expect(
- validatePlaylistUrl("https://www.youtube.com/watch?v=abc&list=PLrAXtmRdnEQy6nuLMHj").valid,
- ).toBe(false);
+ it("accepts a video-in-playlist URL and normalises it to the playlist page (v1.0.0)", () => {
+ const url = "https://www.youtube.com/watch?v=abc&list=PLrAXtmRdnEQy6nuLMHj";
+ expect(validatePlaylistUrl(url).valid).toBe(true);
+ expect(normalizePlaylistUrl(url)).toBe(
+ "https://www.youtube.com/playlist?list=PLrAXtmRdnEQy6nuLMHj",
+ );
+ });
+
+ it("accepts phone and YouTube Music playlist links (v1.0.0)", () => {
+ for (const url of [
+ "https://m.youtube.com/playlist?list=PLabc",
+ "https://music.youtube.com/playlist?list=PLabc",
+ ]) {
+ expect(validatePlaylistUrl(url).valid, url).toBe(true);
+ expect(normalizePlaylistUrl(url)).toBe("https://www.youtube.com/playlist?list=PLabc");
+ }
+ });
+
+ it("still rejects a watch URL without a list", () => {
+ expect(validatePlaylistUrl("https://www.youtube.com/watch?v=abc").valid).toBe(false);
+ expect(normalizePlaylistUrl("https://www.youtube.com/watch?v=abc")).toBe(
+ "https://www.youtube.com/watch?v=abc",
+ );
});
it("rejects a youtu.be short URL", () => {
@@ -559,3 +580,25 @@ describe("validateEmails — the cap still applies to imported values", () => {
expect(result.error).toBe("validation.emailInvalid");
});
});
+
+describe("v1.0.0 validation changes", () => {
+ it("requires a dot and a real TLD in email domains", () => {
+ expect(validateEmails("me@gmail").valid).toBe(false);
+ expect(validateEmails("me@localhost").valid).toBe(false);
+ expect(validateEmails("me@gmail.com").valid).toBe(true);
+ expect(validateEmails("me@mail.co.uk").valid).toBe(true);
+ });
+
+ it("does not warn about www., m. or twitter.com against a social prefix", () => {
+ expect(
+ validateUrlWithPrefix("https://www.instagram.com/me", "https://instagram.com/").error,
+ ).toBeUndefined();
+ expect(
+ validateUrlWithPrefix("https://m.facebook.com/me", "https://facebook.com/").error,
+ ).toBeUndefined();
+ expect(validateUrlWithPrefix("https://twitter.com/me", "https://x.com/").error).toBeUndefined();
+ expect(validateUrlWithPrefix("https://example.com/me", "https://x.com/").error).toBe(
+ "validation.urlPrefixMismatch",
+ );
+ });
+});