Compare commits

...
6 Commits
Author SHA1 Message Date
poli0981 b8e8e476f5 Merge pull request #66 from poli0981/feat/v0.17.0-logging-and-ending-titles
v0.17.0: structured ending titles + log persistence + session UI
2026-05-14 23:49:08 +07:00
poli0981andClaude Opus 4.7 d0dd6bad12 feat(v0.17.0): structured ending titles + log persistence + session UI
Combined release: the deferred ending-title piece from v0.16.0 lands
alongside a full logging overhaul. Output titles now reflect the
filled-in endings; logs survive app restarts with session-grouped
navigation and JSON/TXT export.

## Structured ending titles

Title-builder reads `endings[]` + `endingVideoIndex` and picks the
video-type label from a four-tier resolver:

  1. Single entry         → formatEndingEntry()
                             ("Ending 3: Best End", "Ending 3", "Best End")
  2. Multi-entry, named   → comma-joined names
                             ("True End, Bad End, Hidden")
  3. Multi-entry, numbers → contiguous range via title.endingLabel.range
                             ("Endings 1–3" / "Kết thúc 1–3")
  4. Mixed / sparse       → title.endingLabel.count ("3 Endings")

Falls back to the legacy locale "Ending" label when no usable entries,
so pre-v0.16 single-ending creators see byte-identical output.

## Logging overhaul

* Persistence: new `src/utils/log-storage.ts`. Tauri writes
  append-only JSONL `{appData}/logs/ytdescgen-YYYYMMDD.jsonl` (daily
  rotation). Web caps localStorage at 5000 FIFO entries. Three new
  Tauri commands: `append_to_file`, `list_dir`, `delete_file`.
* Session grouping: `LogEntry.sessionId` (one per app boot). LogPage
  renders one collapsible block per session — current expanded,
  prior collapsed — with per-session "Clear" action.
* Export JSON (envelope) + TXT (one line per entry, chronological).
* Boot hydration via `hydrateLogStore(retentionDays)` in App.tsx.
* New setting `logRetentionDays` (default 7, clamped [1, 90]).
  Persist-store v9 → v10 additive.

## Locale & test churn

* 12 new locale keys × 6 locales; 715/715 ui, 370/370 templates.
* 14 new tests (408 → 422).

## Bundle

* index 470.51 KB (+7 KB), LogPage 8.37 KB (+3 KB). Under 500 KB cap.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:46:57 +07:00
poli0981 a685b050d9 Merge pull request #65 from poli0981/feat/v0.16.0-ending-redesign
v0.16.0: structured endings editor + multi-video split
2026-05-14 23:24:15 +07:00
poli0981andClaude Opus 4.7 25d4e9e148 feat(editor): structured endings + multi-video split (v0.16.0)
Replaces the freeform "Endings shown" Input in Playthrough Notes
with a structured editor that knows about ending numbers, names,
multi-video splits, and timeline cross-validation. The output
description bullet renders comma-joined structured entries with
fallback to the legacy freeform for migrated drafts.

Key changes:

* New `EndingsEditor` component with three logical cases:
  - 1 ending  → Number + Name pair with live preview
  - 2+ endings, 1 video → table row per ending + timeline gate
    (warns when timeline lacks `ending` markers for each row)
  - 2+ endings, 2+ videos → endings table + per-video range table
    with auto-contiguous balanced split (extras spill into the
    LAST video — climactic-final convention) and override support
    + inline overlap/gap/out-of-bounds warnings.

* Schema additions to `EditorData`:
  - `endings: EndingEntry[]` ({number, name})
  - `endingVideoCount: number`
  - `endingVideoRanges: EndingVideoRange[]` (1-indexed inclusive)
  - `endingsShown` kept on the type for migration round-trip but
    no longer surfaces in the UI.

* Engine `endings-format.ts` — pure helpers used by description
  builder + editor preview:
  - `formatEndingEntry` (4 cases: both / number-only / name-only
    / neither → null drop signal)
  - `sliceEndingsForVideo` (whole-array fallback when not multi-
    video / index out of range; targeted slice otherwise)
  - `clampRange`

* Timeline parser ending pattern now captures an optional ordinal
  so `Ending 3: Best End` parses into `{keyword: "ending",
  number: 3, rest: ": Best End"}`. Unblocks the case-B timeline
  gate. Renderer collapses trailing whitespace so a bare `Boss`
  no longer becomes `Boss `.

* Description builder reads structured `endings[]` first, falls
  back to legacy `endingsShown` only when the array is empty.
  Multi-row entries render comma-joined; sliced by
  `endingVideoIndex` when supplied.

* Migration `migrateEditorState` v11 → v12:
  - `liftLegacyEndingString` parses "Ending 3: Best End" /
    "Ending 3" / localised "Kết thúc N" / "エンディングN" / etc.
    into a single structured row. Unparseable strings fall
    through to a name-only row.
  - `computeContiguousRanges` builds the default video split.
  - Clamps `endingVideoCount` to `[1, endings.length]`.

* 19 new locale keys × 6 locales under `editor.endings.*`
  (705/705 keys, up from 686/686). Schema updated.

* 42 new tests (367 → 409): endings-format, editor-store
  migration, description-builder structured render, timeline-
  parser ending ordinal capture.

* Bundle: index 463.08 KB (+62 KB for new UI + engine). Under
  the 500 KB cap.

Migration notes:

* Persisted v0.12–v0.15 drafts auto-lift their `endingsShown`
  string into a single structured row on first rehydrate. The
  rendered description bullet is byte-identical for the common
  case ("True ending only" → "True ending only"). Numbered
  legacy strings ("Ending 3: Best End") gain structure so future
  edits via the new UI work seamlessly.

* Pre-v0.16 templates with `endings` missing still load — the
  TemplateSnapshot type makes all three new fields optional.

* Case C (multi-video) currently renders the union of all
  endings in the Output preview. Per-video output rendering is
  wired into the engine via `endingVideoIndex` but the UI
  selector for it lands in a follow-up patch.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:23:16 +07:00
poli0981 df7d734c74 Merge pull request #64 from poli0981/claude/ecstatic-blackwell-457818
v0.14.1 + v0.15.0: Windows AppData fix, Import Settings, ErrorBoundary, envelope import/export
2026-05-14 23:02:47 +07:00
poli0981andClaude Opus 4.7 8af06c425a feat(stability): ErrorBoundary + envelope import/export overhaul (v0.15.0)
Closes the "black-screen on bad file" class of bugs and gives every
JSON export an auto-detect header so users can no longer confuse
profile / preset / template files with each other.

Key changes:

* `ErrorBoundary` (new) wraps every <Route> in App.tsx plus a
  top-level boundary in main.tsx. Catches render-time exceptions
  that previously black-screened the app, surfaces a fallback UI
  with `Try again` + `Reload page` actions, and copies the error
  to the in-app Logs tab via the logger. Per-route boundaries mean
  a crash on Profiles cannot take down the Editor.

* File envelope format (`src/utils/file-schema.ts`) — every JSON
  export now writes `{ _app: "ytdescgen", _type, _schemaVersion,
  _exportedAt, data }`. The `_type` discriminator lets imports
  detect "you opened a Template file in Profiles importer" and
  offer to auto-switch tabs instead of failing silently. Legacy
  bare-array exports still import via shape detection.

* `importTypedFromJsonFile(expected)` returns a discriminated union
  with five distinct failure kinds (cancelled / read-failed / empty
  / parse-error / wrong-shape / newer-schema) so every error gets a
  targeted toast instead of a generic "Import failed".

* Black-screen root cause fix: null-guard the three-spread chain
  `TemplateCard.snapshot` → `editor-store.normalizeEditorPatch` →
  `ProfileCard.Object.values(profile.social)`. All three now treat
  null/undefined as no-ops. Store-level import validators in
  profile/preset/template stores filter rows with missing `id`
  before they hit the store, so a malformed file can't even reach
  the render path.

* 17 new unit tests in `tests/utils/file-schema.test.ts` cover the
  envelope round-trip plus every detection branch. Total 367/367
  pass.

Migration notes:

* No store schema bump. v0.14.x persisted state loads unchanged.
* Legacy bare-array export files still import via shape-detector.
  Re-export to get the envelope header + tab-switch hints.
* Envelope versions: profile=1, preset=2, template=1, settings=9,
  history=2. Bump per-type on a non-additive shape change.

Bundle: index 401 KB, ProfilesPage chunk 18.44 KB. Well under the
500 KB cap.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 23:01:37 +07:00
54 changed files with 3530 additions and 187 deletions

No files matched your search

+139
View File
@@ -2,6 +2,145 @@
All notable changes to YTDescGen ship as tagged releases on `main`.
## v0.17.0 — 2026-05-14
Combined release: logging overhaul + the deferred ending title piece
from v0.16.0. The Output title now reflects the structured endings
the creator filled in (case-A/B/C aware), and the Logs tab persists
entries across app restarts with session-grouped navigation and
JSON/TXT export.
### Added
- **Structured ending titles** ([src/engine/title-builder.ts](src/engine/title-builder.ts)). When `videoType === "ending"` AND `endings[]` is filled, the title's video-type segment swaps from the static `"Ending"` to a context-aware label, picked by a four-tier resolver:
1. Single entry → `formatEndingEntry()` (e.g. `"Ending 3: Best End"`, `"Ending 3"`, or `"Best End"` depending on which fields are filled).
2. Multi-entry, every entry named → comma-joined names (`"True End, Bad End, Hidden"`).
3. Multi-entry, every entry numbered + contiguous run → `title.endingLabel.range` (`"Endings 1–3"` / `"Kết thúc 1–3"`).
4. Mixed / non-contiguous → `title.endingLabel.count` (`"3 Endings"`).
Falls back to the legacy locale label when no usable entries — pre-v0.16 single-ending creators see byte-identical output. Slicing respects `endingVideoIndex` + `endingVideoRanges` so a per-video title renders only that video's slice (foundation for the v0.17.1 per-video Output selector).
- **Persistent log storage** ([src/utils/log-storage.ts](src/utils/log-storage.ts)). Logs now survive app restarts:
- Tauri: append-only JSONL file `{appData}/logs/ytdescgen-YYYYMMDD.jsonl`. Daily rotation; cleanup deletes whole files older than `logRetentionDays` so retention sweeps are O(files) not O(entries). Three new Tauri commands feed this: `append_to_file`, `list_dir`, `delete_file`.
- Web: localStorage key `ytdescgen-logs`, FIFO-capped at 5000 entries.
- Best-effort: persistence failures never throw, so a disk hiccup can't recurse into a log loop.
- **Session-grouped LogPage** ([src/pages/LogPage.tsx](src/pages/LogPage.tsx)). Each entry now carries a `sessionId` (one per app boot). The page renders one collapsible block per session — current session expanded, prior sessions collapsed — with a per-session "Clear this session" affordance. Header shows entry count + error/warning counts + time range per session.
- **Log export buttons**:
- **JSON** — envelope-wrapped via the v0.15 `exportTypedToJsonFile` (currently keyed `_type: "history"`; promote to a dedicated `log` type later when re-import becomes a use case).
- **TXT** — `[ISO time] [LEVEL] [source] message — details` one line per entry, chronological. Pastes cleanly into bug reports.
- **`logRetentionDays` setting** ([src/store/settings-store.ts](src/store/settings-store.ts), [src/store/settings-heal.ts](src/store/settings-heal.ts)). Default 7 days; clamped to `[1, 90]` by `healSettings`. New section in Settings → Logs with inline hint. Persist-store version bumped 9 → 10.
- **Boot-time log hydration** ([src/App.tsx](src/App.tsx)). `hydrateLogStore(retentionDays)` runs in the root `useEffect`, loads recent persisted entries before the UI mounts, then schedules `pruneOldLogs` so the AppData folder stays trim.
- **Locale keys (10 new × 6 locales)**: `title.endingLabel.{range,count}` (2 templates keys), `settings.{logSettings,logRetentionDays,logRetentionHint}` + `logs.{clearPersistedConfirm,clearSession,exportJson,exportTxt,sessionCurrent,sessionLabel,entriesShort}` (10 ui keys). All 715 ui + 370 templates keys per locale.
### Changed
- **`log-store` schema** — `LogEntry` gained a `sessionId` field; in-memory cap raised from 500 → 2000 with persistence in play so a current session can fully populate the accordion without pagination. New actions: `clearAllPersisted` (in-memory + disk), `clearSession(id)`.
- **LogPage "Clear All"** now clears in-memory state AND deletes persisted JSONL files / localStorage. Two-step confirm via `clearPersistedConfirm` toast.
- **File envelope** — `SCHEMA_VERSIONS.settings` bumped 9 → 10 to match the persist version. v0.15+ settings exports still import unchanged via the `healSettings` defensive merge.
### Tests
- 11 new title-builder tests covering all four ending-label tiers + Vietnamese localisation + slice + fallback. 422/422 pass overall.
- 3 new settings-heal tests for the `logRetentionDays` default and `[1, 90]` clamp.
### Under the hood
- Tauri command surface gained 3 entries (`append_to_file`, `list_dir`, `delete_file`). All stdlib — no new crates.
- `pruneOldLogs` runs *after* `loadRecentLogs` at boot, so an entry on the retention edge is read into memory before being deleted from disk (last-chance access).
- Bundle: index 470.51 KB (+7 KB for title-builder ending logic), LogPage chunk 8.37 KB (+3 KB for session accordion + export buttons). Still under the 500 KB cap.
### Migration notes
- **Settings persist version 9 → 10**. Additive — `logRetentionDays` back-fills to 7 on first rehydrate, no user action required.
- **First-run on Tauri**: app creates `%APPDATA%\com.skullmute.ytdescgen\logs\` on the first log entry. The new `append_to_file` command auto-creates the parent dir via `std::fs::create_dir_all`.
- **Web users**: persisted entries live in `localStorage["ytdescgen-logs"]`; nothing to migrate.
- **Pre-v0.16 ending creators**: title behaviour unchanged unless they fill the new structured fields. Filling triggers the new resolver immediately.
## v0.16.0 — 2026-05-14
Structured ending editor + multi-video split. The Playthrough Notes
section's free-form "Endings shown" Input is replaced with a
structured row table that knows about ending numbers, names,
multi-video splits, and timeline cross-validation.
### Added
- **`EndingsEditor` component ([src/components/editor/EndingsEditor.tsx](src/components/editor/EndingsEditor.tsx))** — three logical cases driven by ending count + video count:
- **Case A** (1 ending) — `Number` + `Name` pair with live preview. At least one of the two must be filled; otherwise an inline warning explains the bullet will be dropped.
- **Case B** (≥2 endings, 1 video) — full table row per ending. A gate inspects the Timestamps textarea — if it doesn't contain at least `endings.length` lines tagged with the `ending` keyword, a warning banner surfaces ("Timeline needs N markers; only M found").
- **Case C** (≥2 endings, ≥2 videos) — endings table + per-video range table. Default ranges are contiguous and balanced via the new `computeContiguousRanges` helper (extras spill into the *last* video for the climactic-final convention); the creator can override per-row. Overlap / gap / out-of-bounds errors surface inline.
- **Structured `endings: EndingEntry[]` schema** in `EditorData` (v0.16.0). Each entry pairs an optional `number` (1–100) with an optional `name`. Empty entries are dropped silently. Companions: `endingVideoCount`, `endingVideoRanges: EndingVideoRange[]`, `endingVideoIndex?` (engine-only — picks which video's slice to render).
- **Engine `endings-format.ts`** — pure helpers `formatEndingEntry`, `sliceEndingsForVideo`, `clampRange`. Used by both the description builder and the editor's live preview so creators see exactly what will render.
- **Ending ordinal capture in `timeline-parser.ts`** — the `ending` keyword pattern now captures an optional trailing number, so timeline lines like `1:23:45 Ending 3: Best End` parse into `{ keyword: "ending", number: 3, rest: ": Best End" }`. Unblocks the case-B timeline gate.
- **Locale keys (19 new × 6 locales)** under `editor.endings.*` covering count / video-count labels, per-row labels, the preview line, warnings (`singleEmpty`, `timelineShort`, `rangeInvalid`, `rangeGap`, `rangeOverlap`, `rangeShort`), and helper hints. Schema bumped from 686 to 705 ui keys.
- **Tests** — 42 new tests (367 → 409): `endings-format.test.ts` (15), `editor-store.endings.test.ts` (16), `description-builder.test.ts` (5 added inline), `timeline-parser.test.ts` (6 added inline).
### Changed
- **`PlaythroughNotesForm`** — the old single `<Input label="Endings shown">` is replaced by `<EndingsEditor />`. The legacy `endingsShown` freeform is kept on the editor type for migration round-trip but no longer surfaces in the UI.
- **`description-builder` endings bullet** — reads from structured `endings[]` first, falls back to legacy `endingsShown` only when the array is empty (covers migrated drafts that still carry both). Multi-row entries render as comma-joined: `Ending 1: True End, Ending 3: Bad End, Hidden`. When `endingVideoIndex` is supplied, only that video's slice renders.
- **`timeline-parser` keyword templates** — every locale's `timeline.keywords.ending` is now `"Ending {{n}}"` instead of `"Ending"`. The renderer collapses trailing whitespace so a bare `Boss` (no ordinal) still renders cleanly as `Boss` instead of `Boss `.
- **`TemplateSnapshot`** in `template-store.ts` — gained `endings?`, `endingVideoCount?`, `endingVideoRanges?` (all optional for back-compat with pre-v0.16 templates).
### Migration
- **`migrateEditorState` v11 → v12** — `liftLegacyEndingString` parses the freeform `endingsShown` into a single-row structured entry:
- `"Ending 3: Best End"` → `{ number: 3, name: "Best End" }`
- `"Ending 3"` → `{ number: 3, name: "" }`
- `"True ending only"` → `{ number: null, name: "True ending only" }`
- `""` → `[]` (no entry)
Localised "Kết thúc N", "エンディングN", etc. are also recognised. After lifting, `endingVideoCount` defaults to 1, `endingVideoRanges` to a single span; the existing `endingsShown` string is left in place but unused.
### Under the hood
- `EndingEntry` and `EndingVideoRange` types live in `src/engine/types.ts`. The 1-indexed inclusive `from/to` convention matches the user-facing "Video 1, Video 2…" labels.
- The Output preview for case C currently renders the *union* of all endings (same as case B) — per-video output rendering is wired into the engine via `endingVideoIndex` but the UI selector for it lands in a follow-up patch. Documented inline in `EndingsEditor` as `multiVideoOutputNote`.
- Bundle: index 463.08 KB (+62 KB for EndingsEditor + endings-format + table-row UI). Still under the 500 KB cap.
- 409/409 tests pass. Lint + typecheck + locale-validate all clean.
## v0.15.0 — 2026-05-14
Import / export overhaul + stability hardening. Closes the "black
screen on bad file" class of bugs and gives every JSON export an
auto-detect header so users can no longer confuse profile / preset /
template files with each other.
### Added
- **`ErrorBoundary` ([src/components/ErrorBoundary.tsx](src/components/ErrorBoundary.tsx))** wrapping every `<Route>` plus a top-level boundary in `main.tsx`. Catches render-time errors that previously black-screened the app, surfaces a fallback UI with `Try again` (remount the subtree) + `Reload page` actions, and copies the error into the Logs tab via the in-app `logger`. Per-route boundaries mean a crash on the Profiles tab doesn't take down the Editor — the user can navigate elsewhere and recover.
- **File envelope format ([src/utils/file-schema.ts](src/utils/file-schema.ts))** — every `.json` export written from this version onwards is wrapped in `{ _app: "ytdescgen", _type, _schemaVersion, _exportedAt, data }`. The `_type` discriminator (`"profile" | "preset" | "template" | "settings" | "history"`) lets imports detect "you opened a Template file in the Profiles importer" and offer to switch tabs instead of silently failing.
- **`detectShape` / `resolveForType`** — shape inspector handles envelope files (authoritative `_type`), legacy bare arrays (best-effort guess from `snapshot` / `channelName` + `social` + `rig` / `gameName` + `storeLinks` / `createdAt` + title), and the multi-store settings dump (recognised by the `ytdescgen-settings` key). 17 new unit tests in `tests/utils/file-schema.test.ts` cover the round-trip + every detection branch.
- **`importTypedFromJsonFile(expectedType)`** — high-level reader that resolves to a tagged-union `ImportResult`: either `{ ok: true; data; sourceVersion? }` or `{ ok: false; failure }` with one of five kinds (`cancelled`, `read-failed`, `empty`, `parse-error`, `wrong-shape`, `newer-schema`). Replaces the throw/catch-and-show-generic-toast pattern.
- **Auto tab-switch on wrong-type import** — when the user clicks Import on the Profiles tab but the file is detected as a Templates export, the toast says "This file looks like a Templates export. Switching tabs…" and `setTab("templates")` runs immediately. One click instead of three.
- **Import-result summary** in toasts — `Imported 5 of 7 profiles (some skipped).` when the store-level validator drops malformed rows. Previously a partial success surfaced as a plain "Imported!" even when half the file got rejected.
### Fixed
- **Black-screen crash** on loading a corrupt profile or template ("Cannot convert undefined or null to object"). Root cause was three unguarded spreads/`Object.values` chained together:
- [src/components/profiles/TemplateCard.tsx:21](src/components/profiles/TemplateCard.tsx) `loadProfile(template.snapshot)` with `snapshot: null` →
- [src/store/editor-store.ts:149](src/store/editor-store.ts) `normalizeEditorPatch` spread of `null` patch →
- [src/components/profiles/ProfileCard.tsx:34](src/components/profiles/ProfileCard.tsx) `Object.values(profile.social)` with `social: null`.
All three now null-guard. `normalizeEditorPatch` returns `{}` for a falsy patch; `loadProfile`-chain spreads degrade to a no-op; `Object.values(profile.social ?? {})` returns 0 instead of throwing. The new ErrorBoundary catches anything that still slips through.
- **Store-level import validators** in [profile-store.ts](src/store/profile-store.ts), [preset-store.ts](src/store/preset-store.ts), [template-store.ts](src/store/template-store.ts) now filter incoming arrays for rows with a string `id` of non-zero length; templates additionally require a non-null `snapshot` object. Bad rows are silently dropped (count surfaces in the import toast).
### Changed
- **`exportToJsonFile` → `exportTypedToJsonFile`** at every ProfilesPage call site. The legacy bare-value exporter is retained for back-compat but unused.
- **`importFromJsonFile<T>` → `importTypedFromJsonFile`** at every ProfilesPage handler. Legacy bare reader retained for the same reason — callers outside Profiles can migrate later.
- **`detectShape` is forward-compatible**: an envelope from a future version (whose `_schemaVersion` exceeds `SCHEMA_VERSIONS[expected]`) returns `newer-schema` instead of importing silently. Tells the user to upgrade the app.
### Under the hood
- Two layers of validation by design: `detectShape` confirms the file *kind*; per-store `importX` rejects malformed *rows*. A future tab-specific quirk in one validator can't corrupt other stores' data.
- `normalizeEditorPatch` signature widened to `Partial<EditorData> | null | undefined` so TS forces null-handling at call sites. Existing callers still work — `Partial<T>` is assignable to the new union.
- Vite reports one dynamic-import-also-statically-imported warning for `logger.ts`. Intentional: the boundary uses a dynamic import so logger init failures during the *primary* render error don't escalate into a secondary boundary crash. Bundle is not split.
- Bundle: index 401.06 KB (+2.49 KB), ProfilesPage chunk 18.44 KB (+4.38 KB for envelope + failure-toast rendering). Total still well under the 500 KB cap.
- 367/367 tests pass (350 + 17 new for file-schema).
### Migration notes
- **No store schema bump**. v0.14.x persisted state loads unchanged in v0.15.0; new envelope only affects on-disk JSON export files.
- **Legacy export files still import** via the shape-detector path. Re-export to get the envelope header + tab-switch hints.
- **Envelope schema versions**: profile=1, preset=2, template=1, settings=9, history=2. Bump per-type when introducing a non-additive change to that store's shape.
## v0.14.1 — 2026-05-14
Same-day patch on v0.14.0. Two desktop-only items closing user-reported
+2 -2
View File
@@ -1,12 +1,12 @@
{
"name": "yt-desc-gen",
"version": "0.14.1",
"version": "0.17.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "yt-desc-gen",
"version": "0.14.1",
"version": "0.17.0",
"license": "Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.11.0",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "yt-desc-gen",
"version": "0.14.1",
"version": "0.17.0",
"private": true,
"license": "Apache-2.0",
"type": "module",
+1 -1
View File
@@ -5535,7 +5535,7 @@ dependencies = [
[[package]]
name = "yt-desc-gen"
version = "0.14.1"
version = "0.17.0"
dependencies = [
"serde",
"serde_json",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "yt-desc-gen"
version = "0.14.1"
version = "0.17.0"
description = "YouTube Gameplay Description Generator"
authors = ["poli0981"]
edition = "2021"
+64 -1
View File
@@ -33,6 +33,62 @@ fn ensure_dir(path: String) -> Result<(), String> {
std::fs::create_dir_all(&path).map_err(|e| e.to_string())
}
/// Append `content` to the file at `path`, creating the file (and any
/// missing parent directories) if necessary. Used by the v0.17.0 log
/// persistence pipeline to write JSONL entries one line at a time,
/// rather than rewriting the whole file on every log call. Cheap
/// enough that we can call it on every `addEntry` without batching.
/// The caller is responsible for newline termination — this is a raw
/// byte append, not a line writer.
#[tauri::command]
fn append_to_file(path: String, content: String) -> Result<(), String> {
use std::fs::OpenOptions;
use std::io::Write;
if let Some(parent) = std::path::Path::new(&path).parent() {
std::fs::create_dir_all(parent).map_err(|e| e.to_string())?;
}
let mut file = OpenOptions::new()
.append(true)
.create(true)
.open(&path)
.map_err(|e| e.to_string())?;
file.write_all(content.as_bytes()).map_err(|e| e.to_string())
}
/// List entries in a directory, returning their file names (not full
/// paths). Used by the v0.17.0 log retention sweep to find
/// `ytdescgen-*.jsonl` files older than the configured retention
/// window. Returns an empty vec if the directory doesn't exist
/// (i.e. no logs have been written yet) — first-run safe.
#[tauri::command]
fn list_dir(path: String) -> Result<Vec<String>, String> {
let dir = std::path::Path::new(&path);
if !dir.exists() {
return Ok(Vec::new());
}
let entries = std::fs::read_dir(dir).map_err(|e| e.to_string())?;
let mut names = Vec::new();
for entry in entries.flatten() {
if let Some(name) = entry.file_name().to_str() {
names.push(name.to_string());
}
}
Ok(names)
}
/// Delete a file at `path` if it exists. No-op when the file is
/// missing (used by log retention sweep — racing with another sweep
/// or a manual cleanup shouldn't error). Returns the OS error string
/// on permission failures.
#[tauri::command]
fn delete_file(path: String) -> Result<(), String> {
let p = std::path::Path::new(&path);
if !p.exists() {
return Ok(());
}
std::fs::remove_file(p).map_err(|e| e.to_string())
}
#[cfg_attr(mobile, tauri::mobile_entry_point)]
pub fn run() {
// Flag that signals the user has requested a full quit (via tray menu).
@@ -112,7 +168,14 @@ pub fn run() {
}
}
})
.invoke_handler(tauri::generate_handler![save_to_file, read_from_file, ensure_dir])
.invoke_handler(tauri::generate_handler![
save_to_file,
read_from_file,
ensure_dir,
append_to_file,
list_dir,
delete_file
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
.run(move |_app_handle, event| {
+1 -1
View File
@@ -1,7 +1,7 @@
{
"$schema": "https://raw.githubusercontent.com/tauri-apps/tauri/dev/crates/tauri-cli/schema.json",
"productName": "YTDescGen",
"version": "0.14.1",
"version": "0.17.0",
"identifier": "com.skullmute.ytdescgen",
"build": {
"beforeBuildCommand": "npm run build",
+51 -38
View File
@@ -1,11 +1,14 @@
import { lazy, Suspense, useEffect } from "react";
import { lazy, Suspense, useEffect, type ReactNode } from "react";
import { HashRouter, Routes, Route } from "react-router-dom";
import { Toaster } from "react-hot-toast";
import toast from "react-hot-toast";
import { AppShell } from "@components/layout/AppShell";
import { ErrorBoundary } from "@components/ErrorBoundary";
import { EditorPage } from "@pages/EditorPage";
import { OutputPage } from "@pages/OutputPage";
import { checkDataFileHealth } from "@utils/storage-adapter";
import { hydrateLogStore } from "@store/log-store";
import { useSettingsStore } from "@store/settings-store";
import "@i18n/index";
const ProfilesPage = lazy(() =>
@@ -34,11 +37,35 @@ function PageLoader() {
return <div className="flex items-center justify-center p-12 text-text-muted">Loading...</div>;
}
/**
* Wrap a lazy-loaded page in both a {@link Suspense} (for the dynamic
* import) and an {@link ErrorBoundary} (for render errors). The
* boundary sits *outside* Suspense so a thrown error during lazy
* resolution also gets caught, not just errors from rendered children.
* Each route gets its own boundary instance so a crash on one tab
* cannot black-screen the whole app — the user can navigate elsewhere
* and recover.
*/
function PageBoundary({ label, children }: { label: string; children: ReactNode }) {
return (
<ErrorBoundary label={label}>
<Suspense fallback={<PageLoader />}>{children}</Suspense>
</ErrorBoundary>
);
}
export default function App() {
useEffect(() => {
checkDataFileHealth().then((msg) => {
if (msg) toast(msg, { icon: "⚠️", duration: 5000 });
});
// v0.17.0: hydrate the log store from persisted JSONL files /
// localStorage so prior-session entries surface in the Logs tab
// accordion. Uses the current `logRetentionDays` setting — read
// directly off the store at mount time so we don't rerun on
// every settings tweak.
const retentionDays = useSettingsStore.getState().logRetentionDays;
void hydrateLogStore(retentionDays);
}, []);
return (
@@ -46,63 +73,49 @@ export default function App() {
<HashRouter>
<Routes>
<Route element={<AppShell />}>
<Route index element={<EditorPage />} />
<Route path="output" element={<OutputPage />} />
<Route
index
element={
<ErrorBoundary label="Editor">
<EditorPage />
</ErrorBoundary>
}
/>
<Route
path="output"
element={
<ErrorBoundary label="Output">
<OutputPage />
</ErrorBoundary>
}
/>
<Route
path="profiles"
element={
<Suspense fallback={<PageLoader />}>
<ProfilesPage />
</Suspense>
}
element={<PageBoundary label="Profiles"><ProfilesPage /></PageBoundary>}
/>
<Route
path="history"
element={
<Suspense fallback={<PageLoader />}>
<HistoryPage />
</Suspense>
}
element={<PageBoundary label="History"><HistoryPage /></PageBoundary>}
/>
<Route
path="settings"
element={
<Suspense fallback={<PageLoader />}>
<SettingsPage />
</Suspense>
}
element={<PageBoundary label="Settings"><SettingsPage /></PageBoundary>}
/>
<Route
path="batch"
element={
<Suspense fallback={<PageLoader />}>
<BatchPage />
</Suspense>
}
element={<PageBoundary label="Batch"><BatchPage /></PageBoundary>}
/>
<Route
path="playlist"
element={
<Suspense fallback={<PageLoader />}>
<PlaylistPage />
</Suspense>
}
element={<PageBoundary label="Playlist"><PlaylistPage /></PageBoundary>}
/>
<Route
path="logs"
element={
<Suspense fallback={<PageLoader />}>
<LogPage />
</Suspense>
}
element={<PageBoundary label="Logs"><LogPage /></PageBoundary>}
/>
<Route
path="about"
element={
<Suspense fallback={<PageLoader />}>
<AboutPage />
</Suspense>
}
element={<PageBoundary label="About"><AboutPage /></PageBoundary>}
/>
</Route>
</Routes>
+127
View File
@@ -0,0 +1,127 @@
import { Component, type ErrorInfo, type ReactNode } from "react";
import { AlertTriangle, RotateCcw } from "lucide-react";
interface ErrorBoundaryProps {
/** Children to render normally. The boundary only kicks in on render
* errors thrown inside this subtree. */
children: ReactNode;
/** Human label that appears in the fallback UI to tell the user
* *what* crashed (e.g. "Profiles tab", "Editor"). Defaults to a
* generic "this section" copy so the boundary still degrades nicely
* if a caller forgets the prop. */
label?: string;
/** Optional callback fired on every catch — useful in tests, or to
* funnel boundary errors into a centralised reporter. The component
* also logs to `useLogStore` directly so the in-app Log tab gets a
* copy regardless. */
onError?: (error: Error, info: ErrorInfo) => void;
}
interface ErrorBoundaryState {
error: Error | null;
}
/**
* Class-based React error boundary — there is still no hook equivalent
* in React 18 (and as of React 19 only `useErrorBoundary` from external
* libraries cover the gap). Catches *render-time* exceptions from any
* descendant component and swaps in a fallback UI so the rest of the
* app keeps working.
*
* Motivation: v0.13.x had no boundary anywhere, so any render error —
* most commonly `Cannot convert undefined or null to object` when a
* malformed profile / template was loaded via Object spread — escalated
* into a black-screen crash. The boundary nets those errors at the
* route level, surfaces a recovery affordance, and writes a structured
* entry to the in-app log tab so the user can copy it into a bug
* report.
*
* Per-route boundaries (one per `<Route>`) mean a crash on the Profiles
* tab does not take down the Editor — the user can navigate away,
* adjust state, and click "Try again" to remount the broken subtree.
*
* Does NOT catch: async errors (Promise rejections), event-handler
* errors, SSR errors. For those use try/catch + the in-app logger
* directly (see `SettingsPage.importSettingsFromFile`).
*/
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
state: ErrorBoundaryState = { error: null };
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { error };
}
componentDidCatch(error: Error, info: ErrorInfo): void {
// Best-effort: pull the in-app logger lazily so the boundary stays
// importable from non-React entry points. We never let the logger
// itself throw a secondary error — if the log store is missing we
// fall back to the browser console.
try {
// Dynamic import dodges a circular dep with files that themselves
// import ErrorBoundary, e.g. when the boundary is mounted in
// main.tsx before the store has registered.
void import("@utils/logger").then(({ logger }) => {
logger.error(
"errorBoundary",
`[${this.props.label ?? "app"}] ${error.message}`,
info.componentStack ?? error.stack ?? "",
);
});
} catch {
console.error("ErrorBoundary caught:", error, info);
}
this.props.onError?.(error, info);
}
private handleReset = (): void => {
this.setState({ error: null });
};
private handleReload = (): void => {
window.location.reload();
};
render(): ReactNode {
if (!this.state.error) return this.props.children;
const label = this.props.label ?? "this section";
return (
<div className="flex min-h-[200px] items-center justify-center p-6">
<div className="w-full max-w-md rounded-lg border border-danger/40 bg-surface-2 p-5 shadow-md shadow-black/10">
<div className="mb-3 flex items-center gap-2 text-danger">
<AlertTriangle className="h-4 w-4" />
<h2 className="text-sm font-semibold">
Something went wrong in {label}
</h2>
</div>
<p className="mb-3 text-xs text-text-secondary">
The app caught a render error before it could crash the page.
Your data is safe — the error has been logged to the Logs
tab.
</p>
<pre className="mb-4 max-h-32 overflow-auto whitespace-pre-wrap rounded bg-surface-3 p-2 text-[11px] text-text-muted">
{this.state.error.message}
</pre>
<div className="flex flex-wrap gap-2">
<button
type="button"
onClick={this.handleReset}
className="inline-flex items-center gap-1.5 rounded bg-accent px-3 py-1.5 text-xs font-semibold text-white hover:bg-accent-hover"
>
<RotateCcw className="h-3.5 w-3.5" />
Try again
</button>
<button
type="button"
onClick={this.handleReload}
className="inline-flex items-center gap-1.5 rounded border border-border bg-surface-2 px-3 py-1.5 text-xs font-semibold text-text-primary hover:bg-surface-3"
>
Reload page
</button>
</div>
</div>
</div>
);
}
}
+381
View File
@@ -0,0 +1,381 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { Plus, Minus, AlertTriangle } from "lucide-react";
import { Input } from "@components/ui/Input";
import { Button } from "@components/ui/Button";
import {
useEditorStore,
computeContiguousRanges,
} from "@store/editor-store";
import { parseTimeline } from "@engine/timeline-parser";
import { formatEndingEntry } from "@engine/endings-format";
import type { EndingEntry, EndingVideoRange } from "@engine/types";
/** Editor cap, matching the original spec ("Giá trị từ 1 - 100"). */
const MAX_ENDINGS = 100;
/**
* Structured ending editor (v0.16.0). Replaces the freeform
* "Endings shown" single Input that used to live in
* `PlaythroughNotesForm`.
*
* Three logical cases drive the layout:
*
* • Case A — `endings.length <= 1`:
* Single Number + Name pair. At least one of the two must be
* filled; otherwise a banner explains that the entry will be
* dropped from the description bullet.
*
* • Case B — `endings.length >= 2` AND `endingVideoCount === 1`:
* Table with one row per ending. A gate inspects the
* Timestamps textarea — if it doesn't contain at least
* `endings.length` lines matching the `ending` keyword, a
* warning banner surfaces. (The actual copy-blocking is wired
* in CopyAllBar; this component just renders the banner so the
* creator sees the problem inline with the field that caused
* it.)
*
* • Case C — `endings.length >= 2` AND `endingVideoCount >= 2`:
* Endings table + a per-video range table. Default ranges are
* contiguous and balanced (extras spill into the last video);
* the creator can override per-row. Invalid overlaps /
* coverage gaps surface as inline warnings.
*
* The "Ending shown" preview line under each entry mirrors the
* formatter used by the description builder so creators see exactly
* what will land in the rendered bullet.
*/
export function EndingsEditor() {
const { t } = useTranslation("ui");
const endings = useEditorStore((s) => s.endings);
const endingVideoCount = useEditorStore((s) => s.endingVideoCount);
const endingVideoRanges = useEditorStore((s) => s.endingVideoRanges);
const timestamps = useEditorStore((s) => s.timestamps);
const set = useEditorStore((s) => s.set);
const count = endings.length;
const isMultiEnding = count >= 2;
const isMultiVideo = isMultiEnding && endingVideoCount >= 2;
/**
* Count timeline lines tagged as the "ending" keyword. Used by case
* B as a copy-time validity gate — the creator must declare at
* least as many timeline markers as the structured array claims.
*/
const timelineEndingCount = useMemo(() => {
if (!isMultiEnding || isMultiVideo) return 0;
const parsed = parseTimeline(timestamps);
return parsed.filter((e) => e.keyword === "ending").length;
}, [timestamps, isMultiEnding, isMultiVideo]);
/** Resize the structured `endings[]` array to a new length, padding
* with empty entries or truncating. Triggers a range recompute so
* case C stays in sync when going from 6→4 endings etc. */
const setEndingCount = (next: number) => {
const clamped = Math.max(0, Math.min(MAX_ENDINGS, Math.floor(next)));
const nextEndings: EndingEntry[] =
clamped <= count
? endings.slice(0, clamped)
: [...endings, ...Array.from({ length: clamped - count }, () => ({ number: null, name: "" }))];
set("endings", nextEndings);
// Re-derive endingVideoCount + ranges so the schema invariants
// (videoCount <= endings.length, ranges.length === videoCount)
// stay true after a shrink/grow.
const nextVideoCount = clamped === 0 ? 1 : Math.min(endingVideoCount, clamped);
set("endingVideoCount", nextVideoCount);
set(
"endingVideoRanges",
clamped === 0 ? [] : computeContiguousRanges(clamped, nextVideoCount),
);
};
/** Update one ending row's number / name. */
const updateEnding = (i: number, patch: Partial<EndingEntry>) => {
const next = endings.map((e, idx) => (idx === i ? { ...e, ...patch } : e));
set("endings", next);
};
/** Update the multi-video count (case C). Recomputes default ranges
* on change unless the creator has already customised them — we
* always reset on count change because a manual override at the old
* count is unlikely to make sense at the new one. */
const setVideoCount = (next: number) => {
if (count === 0) return;
const clamped = Math.max(1, Math.min(count, Math.floor(next)));
set("endingVideoCount", clamped);
set("endingVideoRanges", computeContiguousRanges(count, clamped));
};
/** Update one video's `from` / `to` bound (case C). Doesn't enforce
* non-overlap inline — the warning banner surfaces invalid
* configurations after the fact, since mid-edit overlaps are
* expected. */
const updateRange = (i: number, patch: Partial<EndingVideoRange>) => {
const next = endingVideoRanges.map((r, idx) =>
idx === i ? { ...r, ...patch } : r,
);
set("endingVideoRanges", next);
};
/**
* Inspect the current ranges array for overlap / gap / out-of-bounds
* errors. Returns a translation-key list that the warning banner
* iterates. Pure-ish — closes over `endingVideoRanges` + `count`.
*/
const rangeWarnings: string[] = useMemo(() => {
if (!isMultiVideo) return [];
const warnings: string[] = [];
const sorted = [...endingVideoRanges]
.map((r, idx) => ({ idx, ...r }))
.sort((a, b) => a.from - b.from);
for (const r of sorted) {
if (r.from < 1 || r.to > count || r.from > r.to) {
warnings.push(
t("editor.endings.warnings.rangeInvalid", {
video: r.idx + 1,
from: r.from,
to: r.to,
}),
);
}
}
// Coverage + overlap pass.
let covered = 0;
for (let i = 0; i < sorted.length; i++) {
const r = sorted[i];
if (!r) continue;
if (r.from > covered + 1) {
warnings.push(t("editor.endings.warnings.rangeGap", { at: covered + 1 }));
}
if (r.from <= covered) {
warnings.push(t("editor.endings.warnings.rangeOverlap", { at: r.from }));
}
if (r.to > covered) covered = r.to;
}
if (covered < count) {
warnings.push(t("editor.endings.warnings.rangeShort", { at: covered + 1, total: count }));
}
return warnings;
}, [endingVideoRanges, count, isMultiVideo, t]);
/** Build the "Ending shown" preview string for a single entry. */
const previewFor = (entry: EndingEntry): string =>
formatEndingEntry(entry) ?? t("editor.endings.previewEmpty");
return (
<div className="flex flex-col gap-3">
<div className="flex items-end gap-2">
<div className="flex-1">
<Input
label={t("editor.endings.countLabel")}
type="number"
min={0}
max={MAX_ENDINGS}
value={String(count)}
onChange={(e) => setEndingCount(Number(e.target.value) || 0)}
/>
</div>
{count > 0 && (
<div className="flex gap-1">
<Button
variant="ghost"
size="sm"
onClick={() => setEndingCount(count - 1)}
aria-label={t("editor.endings.removeLast")}
>
<Minus className="h-3.5 w-3.5" />
</Button>
<Button
variant="ghost"
size="sm"
onClick={() => setEndingCount(count + 1)}
aria-label={t("editor.endings.addOne")}
disabled={count >= MAX_ENDINGS}
>
<Plus className="h-3.5 w-3.5" />
</Button>
</div>
)}
</div>
{count === 0 && (
<p className="text-xs text-text-muted">{t("editor.endings.emptyHint")}</p>
)}
{/* CASE A: single ending — number + name pair, with preview. */}
{count === 1 && endings[0] && (
<div className="flex flex-col gap-2 rounded-lg border border-border bg-surface-1 p-3">
<div className="grid grid-cols-[100px_1fr] gap-2">
<Input
label={t("editor.endings.numberLabel")}
type="number"
min={1}
max={MAX_ENDINGS}
value={endings[0].number?.toString() ?? ""}
placeholder="3"
onChange={(e) => {
const v = e.target.value.trim();
updateEnding(0, { number: v === "" ? null : Number(v) });
}}
/>
<Input
label={t("editor.endings.nameLabel")}
placeholder={t("editor.endings.namePlaceholder")}
value={endings[0].name}
onChange={(e) => updateEnding(0, { name: e.target.value })}
/>
</div>
<p className="text-xs text-text-muted">
{t("editor.endings.previewLabel")}:{" "}
<span className="font-mono text-text-secondary">{previewFor(endings[0])}</span>
</p>
{!endings[0].number && !endings[0].name.trim() && (
<p className="flex items-center gap-1.5 text-xs text-warning">
<AlertTriangle className="h-3 w-3" />
{t("editor.endings.warnings.singleEmpty")}
</p>
)}
</div>
)}
{/* CASE B / C: multi-ending table. */}
{count >= 2 && (
<div className="flex flex-col gap-2">
<div className="overflow-hidden rounded-lg border border-border">
<table className="w-full text-sm">
<thead className="bg-surface-1 text-xs uppercase text-text-muted">
<tr>
<th className="px-2 py-1.5 text-left">#</th>
<th className="w-[100px] px-2 py-1.5 text-left">
{t("editor.endings.numberLabel")}
</th>
<th className="px-2 py-1.5 text-left">{t("editor.endings.nameLabel")}</th>
<th className="px-2 py-1.5 text-left">{t("editor.endings.previewLabel")}</th>
</tr>
</thead>
<tbody>
{endings.map((entry, i) => (
<tr key={i} className="border-t border-border">
<td className="px-2 py-1.5 text-text-muted">{i + 1}</td>
<td className="px-2 py-1.5">
<Input
type="number"
min={1}
max={MAX_ENDINGS}
value={entry.number?.toString() ?? ""}
onChange={(e) => {
const v = e.target.value.trim();
updateEnding(i, { number: v === "" ? null : Number(v) });
}}
/>
</td>
<td className="px-2 py-1.5">
<Input
placeholder={t("editor.endings.namePlaceholder")}
value={entry.name}
onChange={(e) => updateEnding(i, { name: e.target.value })}
/>
</td>
<td className="px-2 py-1.5 font-mono text-xs text-text-muted">
{previewFor(entry)}
</td>
</tr>
))}
</tbody>
</table>
</div>
</div>
)}
{/* Case B: timeline gate banner. */}
{isMultiEnding && !isMultiVideo && timelineEndingCount < count && (
<p className="flex items-start gap-1.5 rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning">
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span>
{t("editor.endings.warnings.timelineShort", {
needed: count,
found: timelineEndingCount,
})}
</span>
</p>
)}
{/* CASE C: video-count input + per-video ranges. */}
{isMultiEnding && (
<div className="flex flex-col gap-2 rounded-lg border border-border bg-surface-1 p-3">
<Input
label={t("editor.endings.videoCountLabel")}
type="number"
min={1}
max={count}
value={String(endingVideoCount)}
onChange={(e) => setVideoCount(Number(e.target.value) || 1)}
/>
{isMultiVideo && (
<>
<p className="text-xs text-text-muted">
{t("editor.endings.videoRangeHint")}
</p>
<div className="overflow-hidden rounded border border-border">
<table className="w-full text-sm">
<thead className="bg-surface-2 text-xs uppercase text-text-muted">
<tr>
<th className="px-2 py-1.5 text-left">
{t("editor.endings.videoLabel")}
</th>
<th className="px-2 py-1.5 text-left">From</th>
<th className="px-2 py-1.5 text-left">To</th>
</tr>
</thead>
<tbody>
{endingVideoRanges.map((r, i) => (
<tr key={i} className="border-t border-border">
<td className="px-2 py-1.5">{i + 1}</td>
<td className="px-2 py-1.5">
<Input
type="number"
min={1}
max={count}
value={String(r.from)}
onChange={(e) =>
updateRange(i, { from: Number(e.target.value) || 1 })
}
/>
</td>
<td className="px-2 py-1.5">
<Input
type="number"
min={1}
max={count}
value={String(r.to)}
onChange={(e) =>
updateRange(i, { to: Number(e.target.value) || 1 })
}
/>
</td>
</tr>
))}
</tbody>
</table>
</div>
{rangeWarnings.length > 0 && (
<ul className="flex flex-col gap-1 rounded border border-warning/40 bg-warning/10 p-2 text-xs text-warning">
{rangeWarnings.map((w, i) => (
<li key={i} className="flex items-start gap-1.5">
<AlertTriangle className="mt-0.5 h-3.5 w-3.5 shrink-0" />
<span>{w}</span>
</li>
))}
</ul>
)}
<p className="text-xs text-text-muted">
{t("editor.endings.multiVideoOutputNote")}
</p>
</>
)}
</div>
)}
</div>
);
}
@@ -2,6 +2,7 @@ import { useTranslation } from "react-i18next";
import { Select } from "@components/ui/Select";
import { Input } from "@components/ui/Input";
import { useEditorStore } from "@store/editor-store";
import { EndingsEditor } from "./EndingsEditor";
import {
PLAYTHROUGH_STATUSES,
DIFFICULTY_LEVELS,
@@ -88,12 +89,12 @@ export function PlaythroughNotesForm() {
/>
)}
<Input
label={t("editor.playthroughNotes.endingsLabel")}
placeholder={t("editor.playthroughNotes.endingsPlaceholder")}
value={store.endingsShown}
onChange={(e) => store.set("endingsShown", e.target.value)}
/>
{/* v0.16.0: free-form `endingsShown` Input replaced by the
* structured EndingsEditor — number + name pairs, optional
* multi-video split with auto-contiguous range, timeline
* cross-validation. Legacy persisted string is migrated to a
* single-row entry by editor-store v11→12 migrate. */}
<EndingsEditor />
<Select
label={t("editor.playthroughNotes.languagePatchLabel")}
+11 -4
View File
@@ -19,11 +19,16 @@ export function ProfileCard({ profile }: ProfileCardProps) {
const [showEdit, setShowEdit] = useState(false);
const handleLoad = () => {
// v0.15.0: defensive nullish-coalesce on the two nested record
// fields. A malformed imported profile may carry `social: null` /
// `rig: null` — spreading null throws "Cannot convert undefined or
// null to object", which used to black-screen the app. `?? {}`
// turns the bad import into a partial load instead of a crash.
loadProfile({
channelName: profile.channelName,
contactEmail: profile.contactEmail,
social: { ...profile.social },
rig: { ...profile.rig },
social: { ...(profile.social ?? {}) },
rig: { ...(profile.rig ?? {}) },
resolution: profile.resolution,
fps: profile.fps,
graphicsPreset: profile.graphicsPreset,
@@ -31,8 +36,10 @@ export function ProfileCard({ profile }: ProfileCardProps) {
});
};
const socialCount = Object.values(profile.social).filter((v) => v).length;
const rigCount = Object.values(profile.rig).filter((v) => v).length;
// Same defence on render: `Object.values(null)` throws. With the
// coalesce the count falls back to 0 and the chip just hides.
const socialCount = Object.values(profile.social ?? {}).filter((v) => v).length;
const rigCount = Object.values(profile.rig ?? {}).filter((v) => v).length;
return (
<>
@@ -18,6 +18,15 @@ export function TemplateCard({ template }: TemplateCardProps) {
const [showDelete, setShowDelete] = useState(false);
const handleApply = () => {
// v0.15.0: defend against a template whose `snapshot` field is
// null/undefined — most commonly when the template was imported
// from a malformed JSON. `loadProfile` itself now ignores a null
// patch via `normalizeEditorPatch`, but checking here lets us
// surface a clearer toast and skip the no-op success message.
if (!template.snapshot || typeof template.snapshot !== "object") {
toast.error(t("templates.applyFailed", { defaultValue: "Template is corrupt — cannot apply" }));
return;
}
loadProfile(template.snapshot);
toast.success(t("templates.appliedToast", { name: template.name }));
};
+13 -1
View File
@@ -18,6 +18,8 @@ import type {
LanguagePatch,
GameVersion,
TechNote,
EndingEntry,
EndingVideoRange,
} from "@engine/types";
export interface EditorDefaults {
@@ -93,8 +95,15 @@ export interface EditorDefaults {
playthroughStatus: PlaythroughStatus;
difficulty: DifficultyLevel;
difficultyCustomLabel: string;
/** Free-text endings descriptor for Playthrough Notes section (v0.12). */
/** Free-text endings descriptor for Playthrough Notes section (v0.12).
* @deprecated v0.16.0 — superseded by structured {@link endings}. */
endingsShown: string;
/** Structured ending list (v0.16.0). */
endings: EndingEntry[];
/** Number of videos the playthrough is split across (v0.16.0). */
endingVideoCount: number;
/** Per-video ending range (v0.16.0). */
endingVideoRanges: EndingVideoRange[];
/** Language-patch enum for Playthrough Notes section (v0.12). */
languagePatch: LanguagePatch;
/** Free-form label when `languagePatch` is `"official_other"` or `"custom"`. */
@@ -175,6 +184,9 @@ export const DEFAULTS = {
difficulty: "none",
difficultyCustomLabel: "",
endingsShown: "",
endings: [],
endingVideoCount: 1,
endingVideoRanges: [],
languagePatch: "none",
languagePatchCustom: "",
gameVersion: "full_release",
+40 -10
View File
@@ -6,6 +6,7 @@ import { formatRigValue } from "@config/rig-fields";
import { DEFAULT_GACHA_QUEST_TYPE } from "@config/gacha-quest-types";
import { ordinalSuffix } from "./title-builder";
import { parseTimeline, renderTimeline } from "./timeline-parser";
import { formatEndingEntry, sliceEndingsForVideo } from "./endings-format";
import { sanitizeHashtag } from "@utils/sanitize";
const SOCIAL_ICONS: Record<string, string> = {
@@ -698,16 +699,45 @@ function buildPlaythroughNotesSection(
if (b) bullets.push(b);
}
// Endings shown — free text, identical on both sides of the bilingual
// separator (it's a creator-typed label, not localised content).
const endings = (input.endingsShown ?? "").trim();
if (endings) {
const b = bullet(
"description.playthroughNotes.labels.endings",
endings,
endings,
);
if (b) bullets.push(b);
// Endings shown — v0.16.0 reads from the structured `endings[]` array
// first; falls back to the legacy `endingsShown` freeform when the
// array is empty (covers migrated drafts that still carry the legacy
// string). The structured renderer collapses 1-row "name only"
// entries to the bare name so the v0.12-era output ("True Ending")
// is preserved byte-for-byte for single-ending creators.
//
// Multi-video slicing: when `endingVideoIndex` is set AND the
// matching range covers a sub-slice of `endings[]`, only that slice
// is rendered. Used by the per-video generator pass in Output (one
// pass per video, each producing its own slice's bullet). When the
// index is missing / out-of-range, the union of all endings renders
// — covers case A (single ending) and case B (multi-ending single
// video) without a special branch.
const structured = Array.isArray(input.endings) ? input.endings : [];
const sliced = sliceEndingsForVideo(structured, input);
if (sliced.length > 0) {
const formatted = sliced
.map(formatEndingEntry)
.filter((s): s is string => !!s);
if (formatted.length > 0) {
const joined = formatted.join(", ");
const b = bullet(
"description.playthroughNotes.labels.endings",
joined,
joined,
);
if (b) bullets.push(b);
}
} else {
const legacy = (input.endingsShown ?? "").trim();
if (legacy) {
const b = bullet(
"description.playthroughNotes.labels.endings",
legacy,
legacy,
);
if (b) bullets.push(b);
}
}
// Language patch — enum + custom slot. `official_other` and `custom`
+92
View File
@@ -0,0 +1,92 @@
import type { EndingEntry, EndingVideoRange, GeneratorInput } from "./types";
/**
* Render a single {@link EndingEntry} into its display string.
*
* - both number + name → `"Ending {{number}}: {{name}}"`
* - number only → `"Ending {{number}}"`
* - name only → `"{{name}}"`
* - neither → `null` (entry should be dropped)
*
* The English literal "Ending" is hard-coded here intentionally: the
* label feeds into both the description bullet *and* the
* preview-in-editor live formatter, where localising "Ending" would
* require routing through i18next from a pure module. Templates can
* still override the surrounding bullet label via
* `description.playthroughNotes.labels.endings` — only the per-entry
* "Ending N" prefix stays in English. (Title interpolation runs in
* the same module via {@link formatSingleEndingForTitle} for the same
* reason.)
*
* Pure — exported for unit tests + direct use from React components.
*/
export function formatEndingEntry(entry: EndingEntry): string | null {
const num = typeof entry.number === "number" && Number.isFinite(entry.number)
? entry.number
: null;
const name = (entry.name ?? "").trim();
if (num !== null && name) return `Ending ${num}: ${name}`;
if (num !== null) return `Ending ${num}`;
if (name) return name;
return null;
}
/**
* Compute the slice of an `endings[]` array that should render for a
* given video index. Used by description-builder + title-builder when
* a multi-video playthrough is being generated.
*
* - `endingVideoCount` undefined / ≤ 1 → whole array (case A / B).
* - `endingVideoIndex` undefined / out-of-range → whole array. Lets
* a caller request the "union" view without knowing whether the
* creator is in single- or multi-video mode.
* - Otherwise pull the matching {@link EndingVideoRange} (1-indexed,
* inclusive) and slice. Missing range → fall through to "whole
* array" so a half-migrated draft still renders something.
*
* Pure — exported for unit tests.
*/
export function sliceEndingsForVideo(
endings: EndingEntry[],
input: Pick<GeneratorInput, "endingVideoCount" | "endingVideoIndex" | "endingVideoRanges">,
): EndingEntry[] {
if (endings.length === 0) return [];
const videoCount = input.endingVideoCount ?? 1;
const index = input.endingVideoIndex;
if (videoCount <= 1 || typeof index !== "number" || index < 1 || index > videoCount) {
return endings;
}
const ranges = input.endingVideoRanges ?? [];
const range = ranges[index - 1];
if (!range) return endings;
const { from, to } = clampRange(range, endings.length);
return endings.slice(from - 1, to);
}
/**
* Clamp a possibly-stale {@link EndingVideoRange} to `[1, length]` so
* a creator who shrank `endings[]` without re-deriving ranges still
* gets a sane slice instead of an empty / over-shot one. Pure.
*/
export function clampRange(
range: EndingVideoRange,
length: number,
): EndingVideoRange {
const from = Math.max(1, Math.min(range.from, length));
const to = Math.max(from, Math.min(range.to, length));
return { from, to };
}
/**
* Return a single string suitable for interpolation into a video
* title's `{{endingLabel}}` slot. Currently identical to
* {@link formatEndingEntry} for a single entry; defined separately so
* future per-locale title-formatting tweaks (e.g. Vietnamese "Kết thúc
* 3" instead of "Ending 3") have a single chokepoint.
*
* Returns `null` when no usable label can be produced — callers
* should fall back to the unbranded ending title in that case.
*/
export function formatSingleEndingForTitle(entry: EndingEntry): string | null {
return formatEndingEntry(entry);
}
+14 -4
View File
@@ -69,11 +69,15 @@ const KEYWORD_PATTERNS: KeywordPattern[] = [
keyword: "intro",
hasNumber: false,
},
// Ending
// Ending — v0.16.0 now captures an optional ordinal so timeline
// entries like "Ending 1" / "Ending 3: Best End" can be matched
// back to the structured `endings[]` array in the editor. The "rest"
// tail keeps any trailing label so the renderer still emits the
// creator's exact text on round-trip.
{
re: /^(ending|kết\s+thúc|ket\s+thuc|エンディング|final|엔딩|结局|结尾)(.*)$/i,
re: /^(?:ending|kết\s+thúc|ket\s+thuc|エンディング|final|엔딩|结局|结尾)\s*(\d+)?(.*)$/i,
keyword: "ending",
hasNumber: false,
hasNumber: true,
},
// Tutorial
{
@@ -172,7 +176,13 @@ export function renderTimeline(
}
const numberVar = entry.number != null ? String(entry.number) : "";
const translated = t(`timeline.keywords.${entry.keyword}`, { n: numberVar });
// v0.16.0: collapse the trailing whitespace that creeps in when a
// numbered keyword pattern (`"Boss {{n}}"`) interpolates with an
// empty `n` (e.g. a bare "boss" line with no ordinal). Without
// this, the renderer emits "0:42 Boss rest" with a double space.
const translated = t(`timeline.keywords.${entry.keyword}`, { n: numberVar })
.replace(/\s+$/u, "")
.replace(/\s{2,}/gu, " ");
const withRest = entry.rest ? `${translated} ${entry.rest}` : translated;
rendered.push(`${entry.time} ${withRest}`);
}
+106 -7
View File
@@ -12,6 +12,8 @@ import {
GACHA_PART_SUFFIX_STYLES,
type GachaQuestType,
} from "@config/gacha-quest-types";
import { formatEndingEntry, sliceEndingsForVideo } from "./endings-format";
import type { EndingEntry } from "./types";
/**
* Compact "[2K 60FPS]" badge appended to the video-type segment when the
@@ -169,6 +171,91 @@ export function buildGachaPartSuffix(
return resolved && resolved !== key ? resolved : "";
}
/**
* Build the video-type segment of the title when `videoType === "ending"`
* AND the creator has filled at least one structured {@link EndingEntry}
* (v0.17.0). Three tiers, picked by what's available:
*
* 1. Single entry → `formatEndingEntry()` (e.g. `"Ending 3: Best End"`,
* `"Ending 3"`, or `"Best End"`).
* 2. Multiple entries, every entry has a non-empty `name` → comma-join
* the names. Plays well with multi-route VN-style endings where
* the creator cares more about the named routes than the ordinals.
* 3. Multiple entries, every entry has a `number` AND they form a
* contiguous run → `"Endings {from}–{to}"` via locale key
* `title.endingLabel.range`. Tightest visible label for batched
* ending playthroughs ("Endings 1–3" / "Kết thúc 1–3").
* 4. Mixed / non-contiguous fallback → `"{count} Endings"` via
* `title.endingLabel.count`.
*
* Returns `null` when no structured data is usable, signalling the
* caller to fall back to the legacy locale-string label
* (`title.videoType.ending` = "Ending"). This keeps existing single-
* ending creators byte-identical post-migration.
*
* Slicing: respects `endingVideoIndex` + `endingVideoRanges` so a
* per-video title for case C renders only that video's slice of
* endings. The Output page passes the index when looping over
* `endingVideoCount`; bare generation (no index) sees the union.
*/
export function buildStructuredEndingLabel(
input: GeneratorInput,
t: TranslationFn,
): string | null {
const endings: EndingEntry[] = input.endings ?? [];
if (endings.length === 0) return null;
const sliced = sliceEndingsForVideo(endings, input);
// Drop entries that have neither number nor a non-empty name — they
// produce no visible label and would dilute the comma-join / count.
const usable = sliced.filter((e) => {
const hasNumber =
typeof e.number === "number" && Number.isFinite(e.number);
const hasName = (e.name ?? "").trim().length > 0;
return hasNumber || hasName;
});
if (usable.length === 0) return null;
if (usable.length === 1) {
const only = usable[0];
return only ? formatEndingEntry(only) : null;
}
// Multi-entry: prefer named comma-join when every entry has a name.
const allHaveNames = usable.every((e) => (e.name ?? "").trim().length > 0);
if (allHaveNames) {
return usable.map((e) => e.name.trim()).join(", ");
}
// Numbered + contiguous → range form. Sort + scan adjacent diffs to
// detect contiguity so an out-of-order entry list ([3, 1, 2]) still
// collapses to "Endings 1–3".
const numbers = usable
.map((e) => e.number)
.filter((n): n is number => typeof n === "number" && Number.isFinite(n));
if (numbers.length === usable.length) {
const sorted = [...numbers].sort((a, b) => a - b);
const isContiguous = sorted.every(
(n, i) => i === 0 || n === (sorted[i - 1] as number) + 1,
);
if (isContiguous) {
const from = sorted[0] as number;
const to = sorted[sorted.length - 1] as number;
const key = "title.endingLabel.range";
const resolved = t(key, { from: String(from), to: String(to) });
if (resolved && resolved !== key) return resolved;
// Fallback if the locale hasn't migrated yet — keep behaviour sane.
return `Endings ${from}–${to}`;
}
}
// Mixed / non-contiguous: report count.
const key = "title.endingLabel.count";
const resolved = t(key, { count: String(usable.length) });
if (resolved && resolved !== key) return resolved;
return `${usable.length} Endings`;
}
export function buildTitle(
input: GeneratorInput,
t: TranslationFn,
@@ -220,13 +307,25 @@ export function buildTitle(
});
}
const videoTypeLabel = t(`title.videoType.${input.videoType}`, {
partNumber: input.partNumber ?? "",
bossName: input.bossName ?? "",
dlcName: input.dlcName ?? "",
challengeName: input.challengeName ?? "",
modName: input.modName ?? "",
});
// v0.17.0: when the creator has filled structured endings, replace
// the static "Ending" label with a context-aware one (single entry
// surfaces the ending's name, multi-entry collapses to a name list /
// contiguous range / count). Falls back to the locale string when no
// structured data is usable, so the legacy single-ending creators
// who haven't migrated see byte-identical output.
let videoTypeLabel: string;
if (input.videoType === "ending") {
const structured = buildStructuredEndingLabel(input, t);
videoTypeLabel = structured ?? t("title.videoType.ending");
} else {
videoTypeLabel = t(`title.videoType.${input.videoType}`, {
partNumber: input.partNumber ?? "",
bossName: input.bossName ?? "",
dlcName: input.dlcName ?? "",
challengeName: input.challengeName ?? "",
modName: input.modName ?? "",
});
}
return composeTitle({
gameName,
+82
View File
@@ -160,6 +160,40 @@ export const GAME_VERSION_OPTIONS = [
] as const;
export type GameVersion = (typeof GAME_VERSION_OPTIONS)[number];
/**
* One ending in the structured `endings[]` array (v0.16.0). Both
* `number` and `name` are independently optional, but at least one
* must be filled for the entry to surface in the description bullet
* list — empty rows are dropped silently. The 1–100 bound on
* `number` mirrors the editor's max-endings cap and is purely
* advisory (no engine validation rejects out-of-range numbers, but
* the editor input clamps).
*/
export interface EndingEntry {
/** Ordinal in the game's ending list (e.g. 3 of 5). Null when the
* creator only wants to name endings, not number them. */
number: number | null;
/** Free-form ending label ("Best Ending", "True End", …). */
name: string;
}
/**
* Per-video ending range (v0.16.0). Used when a multi-ending
* playthrough is split across multiple videos — each video covers a
* contiguous slice of {@link EndingEntry} indices, expressed as
* 1-indexed `from`/`to` (both inclusive).
*
* Default auto-split is contiguous and balanced via `ending-split.ts`,
* but the creator can override per-video, so the array is persisted
* rather than recomputed at every render.
*/
export interface EndingVideoRange {
/** First ending index covered by this video (1-indexed, inclusive). */
from: number;
/** Last ending index covered by this video (1-indexed, inclusive). */
to: number;
}
/**
* Tech / production / playstyle disclaimer items (v0.12). One unified
* checklist that consolidates "Technical issue", "Gameplay", and
@@ -498,8 +532,56 @@ export interface GeneratorInput {
* block (v0.12). Examples: "1 of 3", "True ending only", "All routes
* 100%". Empty → bullet is skipped. Free-form on purpose: the natural
* value space is too varied for an enum.
*
* @deprecated v0.16.0 — superseded by the structured {@link endings}
* array. Reader path still falls back to this string when `endings`
* is empty, so persisted v0.12–v0.15 drafts render identically. The
* editor migration (`migrateEditorState` v11 → v12) lifts the
* freeform string into a single-row `endings` entry on rehydrate.
*/
endingsShown?: string;
/**
* Structured ending list (v0.16.0). Each entry pairs an optional
* ordinal `number` (1–100) with an optional free-form `name`
* ("Best Ending", "True Ending"…). At least one of the two must be
* filled for the entry to be rendered — entries with neither are
* dropped silently.
*
* Display format per entry:
*
* - both filled → "Ending {{number}}: {{name}}"
* - number only → "Ending {{number}}"
* - name only → "{{name}}"
*
* Length should match {@link endingVideoCount} × video coverage; the
* range split is held in {@link endingVideoRanges} when multi-video.
* Empty array → falls back to the legacy `endingsShown` freeform.
*/
endings?: EndingEntry[];
/**
* How many separate videos this gameplay run will be split into
* (v0.16.0). Always `1` when `endings.length <= 1`. When >1, each
* video covers a contiguous range of `endings[]` declared in
* {@link endingVideoRanges}; the description builder renders the
* slice belonging to the requested video index (defaults to slice
* covering the whole array when no index is supplied).
*/
endingVideoCount?: number;
/**
* Per-video ending range (1-indexed, inclusive). Length must equal
* {@link endingVideoCount}; auto-computed as a contiguous split by
* `ending-split.ts` whenever `endingVideoCount` or
* `endings.length` changes, but persisted so the creator can
* override.
*/
endingVideoRanges?: EndingVideoRange[];
/**
* Which video's slice this generator pass should render, when
* `endingVideoCount > 1`. 1-indexed to match the user-facing
* "Video 1, Video 2…" labels in the editor. Out-of-range / missing
* → render the union of all endings (legacy / case A / case B).
*/
endingVideoIndex?: number;
/**
* Language-patch state for the `▸ 🎮 PLAYTHROUGH NOTES` block (v0.12).
* `"none"` → skip the bullet. `"official_other"` and `"custom"` pair
+3
View File
@@ -68,6 +68,9 @@ export function buildGeneratorInputFromEditor(
difficulty: state.difficulty,
difficultyCustomLabel: state.difficultyCustomLabel,
endingsShown: state.endingsShown,
endings: state.endings,
endingVideoCount: state.endingVideoCount,
endingVideoRanges: state.endingVideoRanges,
languagePatch: state.languagePatch,
languagePatchCustom: state.languagePatchCustom,
gameVersion: state.gameVersion,
+14 -2
View File
@@ -91,6 +91,17 @@
],
"editor.playthroughNotes.languagePatchOptions": ["none", "official_en", "official_other", "fan_translation", "mtl", "custom"],
"editor.playthroughNotes.gameVersionOptions": ["full_release", "demo", "early_access", "beta", "prologue", "pre_release", "custom"],
"editor.endings": [
"countLabel", "videoCountLabel", "videoLabel",
"numberLabel", "nameLabel", "namePlaceholder",
"previewLabel", "previewEmpty",
"emptyHint", "addOne", "removeLast",
"videoRangeHint", "multiVideoOutputNote"
],
"editor.endings.warnings": [
"singleEmpty", "timelineShort",
"rangeInvalid", "rangeGap", "rangeOverlap", "rangeShort"
],
"editor.techNoteGroups": ["audio", "video_quality", "recording_issues", "playstyle", "production"],
"editor.techNoteOptions": [
"copyright_muted_sections", "volume_reduced_copyright", "music_replaced_copyright", "cutscene_audio_muted_only", "original_audio_kept",
@@ -144,17 +155,18 @@
"presets": ["title", "createNew", "editPreset", "loadPreset", "deleteConfirm", "emptyState", "selectPreset", "noPresets", "exportPresets", "importPresets"],
"templates": ["title", "createNew", "saveAsTemplate", "templateName", "templateNamePlaceholder", "loadTemplate", "deleteConfirm", "emptyState", "saveHint", "savedAs", "appliedToast", "exportTemplates", "importTemplates"],
"history": ["title", "emptyState", "clearAll", "clearConfirm", "searchPlaceholder"],
"settings": ["title", "appearance", "defaults", "editorSettings", "tagSettings", "historySettings", "theme", "appLanguage", "defaultOutputLanguage", "defaultGenre", "showCharCount", "compactTagDisplay", "historyLimit", "multilingualTags", "trendingTags", "hashtagCount", "showQualityBadge", "showCopyright", "showUsagePolicy", "showSponsorCredit", "showThirdPartyAds", "thirdPartyAdsHint", "titleFormatTitle", "descriptionSettingsTitle", "badgePosition", "badgePositionPrefix", "badgePositionMiddle", "badgePositionSuffix", "titleSeparator", "titleSeparatorEmDash", "titleSeparatorHyphen", "titleSeparatorColon", "titleSeparatorPipe", "badgeCase", "badgeCaseUpper", "badgeCaseLower", "showPinnedCommentTemplate", "pinnedCommentIncludeAskNextGame", "pinnedCommentIncludeGenrePlaylist", "genrePlaylistsTitle", "genrePlaylistsHelp", "genrePlaylistsEmptyHint"],
"settings": ["title", "appearance", "defaults", "editorSettings", "tagSettings", "historySettings", "theme", "appLanguage", "defaultOutputLanguage", "defaultGenre", "showCharCount", "compactTagDisplay", "historyLimit", "multilingualTags", "trendingTags", "hashtagCount", "showQualityBadge", "showCopyright", "showUsagePolicy", "showSponsorCredit", "showThirdPartyAds", "thirdPartyAdsHint", "titleFormatTitle", "descriptionSettingsTitle", "badgePosition", "badgePositionPrefix", "badgePositionMiddle", "badgePositionSuffix", "titleSeparator", "titleSeparatorEmDash", "titleSeparatorHyphen", "titleSeparatorColon", "titleSeparatorPipe", "badgeCase", "badgeCaseUpper", "badgeCaseLower", "showPinnedCommentTemplate", "pinnedCommentIncludeAskNextGame", "pinnedCommentIncludeGenrePlaylist", "genrePlaylistsTitle", "genrePlaylistsHelp", "genrePlaylistsEmptyHint", "logSettings", "logRetentionDays", "logRetentionHint"],
"batch": ["title", "startPart", "endPart", "generateBatch", "copyAllBatch", "emptyState"],
"shortcuts": ["title", "generate", "copyAll", "saveDraft", "toggleSidebar", "help", "close", "searchPlaceholder", "noResults"],
"validation": ["emailInvalid", "emailMaxExceeded", "urlInvalid", "urlPrefixMismatch", "playlistUrlInvalid"],
"logs": ["title", "emptyState", "clearAll", "clearConfirm", "searchPlaceholder"],
"logs": ["title", "emptyState", "clearAll", "clearConfirm", "clearPersistedConfirm", "clearSession", "searchPlaceholder", "exportJson", "exportTxt", "sessionCurrent", "sessionLabel", "entriesShort"],
"playlist": ["title", "status", "contentType", "totalVideos", "customNote", "generatePlaylist"]
},
"templates": {
"title": ["separator", "suffix"],
"title.separators": ["emDash", "hyphen", "colon", "pipe"],
"title.videoType": ["full", "part", "full_demo", "demo_part", "boss", "boss_nohit", "ending", "speedrun", "100percent", "dlc", "newgame_plus", "challenge", "side_quest", "secret", "comparison", "guide", "mods", "collectibles", "livestream", "gacha_quest"],
"title.endingLabel": ["range", "count"],
"title.gachaQuestType": [
"main_story", "world_quest", "side_quest", "spinoff_quest", "companion_quest", "bond_quest",
"event", "anniversary", "crossover", "dating_event",
+5 -1
View File
@@ -30,6 +30,10 @@
"livestream": "🔴 LIVE",
"gacha_quest": ""
},
"endingLabel": {
"range": "Endings {{from}}–{{to}}",
"count": "{{count}} Endings"
},
"gachaQuestType": {
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
"world_quest": "{{gameName}} — World Quest: {{questName}}",
@@ -444,7 +448,7 @@
"boss": "Boss {{n}}",
"final_boss": "Final Boss",
"intro": "Intro",
"ending": "Ending",
"ending": "Ending {{n}}",
"tutorial": "Tutorial",
"credits": "Credits"
}
+35 -2
View File
@@ -446,6 +446,29 @@
"custom": "Custom…"
}
},
"endings": {
"countLabel": "Number of endings",
"videoCountLabel": "Number of videos",
"videoLabel": "Video",
"numberLabel": "Number",
"nameLabel": "Name",
"namePlaceholder": "e.g. Best Ending",
"previewLabel": "Ending shown",
"previewEmpty": "(empty — fill number or name)",
"emptyHint": "Add at least one ending entry — leave at 0 to skip this bullet entirely.",
"addOne": "Add ending",
"removeLast": "Remove last ending",
"videoRangeHint": "Each video covers a contiguous slice of endings. Default split is balanced; adjust per row to override.",
"multiVideoOutputNote": "Each video's description renders that video's ending slice. Generate from the editor as usual — the Output preview shows video 1 by default.",
"warnings": {
"singleEmpty": "Fill at least the number or the name — empty entries are dropped from the description.",
"timelineShort": "Timeline needs {{needed}} ending markers; only {{found}} found. Add the missing rows before copying.",
"rangeInvalid": "Video {{video}}: range {{from}}–{{to}} is invalid (out of bounds or reversed).",
"rangeGap": "Endings {{at}}+ are not covered by any video — extend a range or add a video.",
"rangeOverlap": "Multiple videos cover ending {{at}} — adjust ranges to avoid overlap.",
"rangeShort": "Last covered ending is {{at}} but there are {{total}} endings — final video range is too short."
}
},
"techNotes": "Tech notes",
"techNoteSearchPlaceholder": "Search tech notes…",
"techNoteEmpty": "No matching notes",
@@ -753,7 +776,10 @@
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
"genrePlaylistsTitle": "Genre Playlists",
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
"logSettings": "Logs",
"logRetentionDays": "Log retention (days)",
"logRetentionHint": "Logs older than this are deleted at app start. Range: 1–90 days."
},
"batch": {
"title": "Batch Mode",
@@ -799,6 +825,13 @@
"emptyState": "No log entries yet.",
"clearAll": "Clear All",
"clearConfirm": "Are you sure you want to clear all logs?",
"searchPlaceholder": "Search logs..."
"clearPersistedConfirm": "Clear all logs from memory AND delete persisted log files? This cannot be undone.",
"clearSession": "Clear this session",
"searchPlaceholder": "Search logs...",
"exportJson": "Export JSON",
"exportTxt": "Export TXT",
"sessionCurrent": "Current session",
"sessionLabel": "Session {{n}}",
"entriesShort": "entries"
}
}
+5 -1
View File
@@ -30,6 +30,10 @@
"livestream": "🔴 EN VIVO",
"gacha_quest": ""
},
"endingLabel": {
"range": "Finales {{from}}–{{to}}",
"count": "{{count}} Finales"
},
"gachaQuestType": {
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
"world_quest": "{{gameName}} — World Quest: {{questName}}",
@@ -444,7 +448,7 @@
"boss": "Jefe {{n}}",
"final_boss": "Jefe Final",
"intro": "Introducción",
"ending": "Final",
"ending": "Final {{n}}",
"tutorial": "Tutorial",
"credits": "Créditos"
}
+35 -2
View File
@@ -446,6 +446,29 @@
"custom": "Personalizada…"
}
},
"endings": {
"countLabel": "Número de finales",
"videoCountLabel": "Número de videos",
"videoLabel": "Video",
"numberLabel": "Número",
"nameLabel": "Nombre",
"namePlaceholder": "ej. Mejor Final",
"previewLabel": "Final mostrado",
"previewEmpty": "(vacío — completa número o nombre)",
"emptyHint": "Añade al menos una entrada — déjalo en 0 para omitir este punto.",
"addOne": "Añadir final",
"removeLast": "Eliminar último",
"videoRangeHint": "Cada video cubre un tramo contiguo de finales. La división por defecto es equilibrada; ajusta por fila para sobrescribir.",
"multiVideoOutputNote": "La descripción de cada video renderiza su tramo. Genera desde el editor como siempre — la vista previa muestra el video 1 por defecto.",
"warnings": {
"singleEmpty": "Completa al menos número o nombre — las entradas vacías se omiten de la descripción.",
"timelineShort": "La línea de tiempo necesita {{needed}} marcadores de final; solo se encontraron {{found}}. Añade los faltantes antes de copiar.",
"rangeInvalid": "Video {{video}}: rango {{from}}–{{to}} no válido (fuera de límites o invertido).",
"rangeGap": "Los finales {{at}}+ no están cubiertos — extiende un rango o añade un video.",
"rangeOverlap": "Varios videos cubren el final {{at}} — ajusta los rangos para evitar solapamiento.",
"rangeShort": "El último final cubierto es {{at}} pero hay {{total}} finales — el rango del video final es demasiado corto."
}
},
"techNotes": "Notas técnicas",
"techNoteSearchPlaceholder": "Buscar notas…",
"techNoteEmpty": "No hay notas que coincidan",
@@ -753,7 +776,10 @@
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
"genrePlaylistsTitle": "Genre Playlists",
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
"logSettings": "Registros",
"logRetentionDays": "Retención de logs (días)",
"logRetentionHint": "Los logs más antiguos se eliminan al iniciar. Rango: 1–90 días."
},
"batch": {
"title": "Generación por Lote",
@@ -799,6 +825,13 @@
"emptyState": "No hay registros.",
"clearAll": "Borrar Todo",
"clearConfirm": "¿Estás seguro de borrar todos los registros?",
"searchPlaceholder": "Buscar registros..."
"clearPersistedConfirm": "¿Borrar logs en memoria Y eliminar archivos persistidos? No se puede deshacer.",
"clearSession": "Borrar esta sesión",
"searchPlaceholder": "Buscar registros...",
"exportJson": "Exportar JSON",
"exportTxt": "Exportar TXT",
"sessionCurrent": "Sesión actual",
"sessionLabel": "Sesión {{n}}",
"entriesShort": "entradas"
}
}
+5 -1
View File
@@ -30,6 +30,10 @@
"livestream": "🔴 LIVE",
"gacha_quest": ""
},
"endingLabel": {
"range": "エンディング {{from}}–{{to}}",
"count": "エンディング {{count}}個"
},
"gachaQuestType": {
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
"world_quest": "{{gameName}} — World Quest: {{questName}}",
@@ -444,7 +448,7 @@
"boss": "ボス{{n}}",
"final_boss": "ラスボス",
"intro": "オープニング",
"ending": "エンディング",
"ending": "エンディング{{n}}",
"tutorial": "チュートリアル",
"credits": "クレジット"
}
+35 -2
View File
@@ -446,6 +446,29 @@
"custom": "カスタム…"
}
},
"endings": {
"countLabel": "エンディング数",
"videoCountLabel": "動画数",
"videoLabel": "動画",
"numberLabel": "番号",
"nameLabel": "名前",
"namePlaceholder": "例: ベストエンド",
"previewLabel": "表示",
"previewEmpty": "(空 — 番号か名前を入力)",
"emptyHint": "エンディングを 1 件以上追加してください — 0 のままだとこの項目はスキップされます。",
"addOne": "エンディング追加",
"removeLast": "最後を削除",
"videoRangeHint": "各動画はエンディングの連続したスライスを担当します。デフォルトでは均等に分割されますが、行ごとに上書きできます。",
"multiVideoOutputNote": "各動画の説明はそのスライスを描画します。通常どおりエディタから生成 — プレビューはデフォルトで動画 1 を表示します。",
"warnings": {
"singleEmpty": "番号か名前のいずれかを入力してください — 空欄のエントリは説明から除外されます。",
"timelineShort": "タイムラインに {{needed}} 件のエンディングマーカーが必要ですが、{{found}} 件のみ。コピー前に不足分を追加してください。",
"rangeInvalid": "動画 {{video}}: 範囲 {{from}}–{{to}} は無効です(境界外または反転)。",
"rangeGap": "エンディング {{at}}+ はどの動画にも含まれません — 範囲を拡張するか動画を追加してください。",
"rangeOverlap": "複数の動画がエンディング {{at}} を含みます — 重複を避けるよう調整してください。",
"rangeShort": "最後にカバーされたエンディングは {{at}} ですが、全部で {{total}} 件 — 最終動画の範囲が短すぎます。"
}
},
"techNotes": "技術メモ",
"techNoteSearchPlaceholder": "メモを検索…",
"techNoteEmpty": "該当するメモはありません",
@@ -753,7 +776,10 @@
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
"genrePlaylistsTitle": "Genre Playlists",
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
"logSettings": "ログ",
"logRetentionDays": "ログ保持期間 (日)",
"logRetentionHint": "この日数より古いログは起動時に削除されます。範囲: 1–90 日。"
},
"batch": {
"title": "一括モード",
@@ -799,6 +825,13 @@
"emptyState": "ログはありません。",
"clearAll": "すべて削除",
"clearConfirm": "すべてのログを削除しますか?",
"searchPlaceholder": "ログを検索..."
"clearPersistedConfirm": "メモリ上のログ AND 保存済みログファイルを削除しますか?取り消せません。",
"clearSession": "このセッションを削除",
"searchPlaceholder": "ログを検索...",
"exportJson": "JSON でエクスポート",
"exportTxt": "TXT でエクスポート",
"sessionCurrent": "現在のセッション",
"sessionLabel": "セッション {{n}}",
"entriesShort": "件"
}
}
+5 -1
View File
@@ -30,6 +30,10 @@
"livestream": "🔴 LIVE",
"gacha_quest": ""
},
"endingLabel": {
"range": "엔딩 {{from}}–{{to}}",
"count": "엔딩 {{count}}개"
},
"gachaQuestType": {
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
"world_quest": "{{gameName}} — World Quest: {{questName}}",
@@ -444,7 +448,7 @@
"boss": "보스 {{n}}",
"final_boss": "최종 보스",
"intro": "인트로",
"ending": "엔딩",
"ending": "엔딩 {{n}}",
"tutorial": "튜토리얼",
"credits": "크레딧"
}
+35 -2
View File
@@ -446,6 +446,29 @@
"custom": "사용자 지정…"
}
},
"endings": {
"countLabel": "엔딩 개수",
"videoCountLabel": "영상 개수",
"videoLabel": "영상",
"numberLabel": "번호",
"nameLabel": "이름",
"namePlaceholder": "예: 베스트 엔딩",
"previewLabel": "표시",
"previewEmpty": "(비어 있음 — 번호 또는 이름 입력)",
"emptyHint": "엔딩 항목을 하나 이상 추가하세요 — 0이면 이 항목은 건너뜁니다.",
"addOne": "엔딩 추가",
"removeLast": "마지막 항목 삭제",
"videoRangeHint": "각 영상은 연속된 엔딩 구간을 담당합니다. 기본은 균등 분할이며 행 단위로 수정 가능합니다.",
"multiVideoOutputNote": "각 영상의 설명은 해당 구간을 렌더링합니다. 평소대로 생성 — 미리보기는 기본적으로 영상 1을 표시합니다.",
"warnings": {
"singleEmpty": "번호 또는 이름 중 하나는 입력해야 합니다 — 빈 항목은 설명에서 제외됩니다.",
"timelineShort": "타임라인에 엔딩 마커가 {{needed}}개 필요하지만 {{found}}개만 있습니다. 복사 전에 누락분을 추가하세요.",
"rangeInvalid": "영상 {{video}}: 범위 {{from}}–{{to}}가 잘못되었습니다 (범위 초과 또는 역순).",
"rangeGap": "엔딩 {{at}}+ 가 어떤 영상에도 포함되지 않음 — 범위를 확장하거나 영상을 추가하세요.",
"rangeOverlap": "여러 영상이 엔딩 {{at}}을 포함합니다 — 중복을 피하도록 조정하세요.",
"rangeShort": "마지막으로 포함된 엔딩은 {{at}}이지만 총 {{total}}개 — 마지막 영상 범위가 너무 짧습니다."
}
},
"techNotes": "기술 노트",
"techNoteSearchPlaceholder": "노트 검색…",
"techNoteEmpty": "일치하는 노트 없음",
@@ -753,7 +776,10 @@
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
"genrePlaylistsTitle": "Genre Playlists",
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
"logSettings": "로그",
"logRetentionDays": "로그 보관 기간 (일)",
"logRetentionHint": "이 일수보다 오래된 로그는 앱 시작 시 삭제됩니다. 범위: 1–90일."
},
"batch": {
"title": "일괄 생성",
@@ -799,6 +825,13 @@
"emptyState": "로그가 없습니다.",
"clearAll": "모두 삭제",
"clearConfirm": "모든 로그를 삭제하시겠습니까?",
"searchPlaceholder": "로그 검색..."
"clearPersistedConfirm": "메모리 내 로그와 저장된 로그 파일을 모두 삭제하시겠습니까? 되돌릴 수 없습니다.",
"clearSession": "이 세션 삭제",
"searchPlaceholder": "로그 검색...",
"exportJson": "JSON 내보내기",
"exportTxt": "TXT 내보내기",
"sessionCurrent": "현재 세션",
"sessionLabel": "세션 {{n}}",
"entriesShort": "건"
}
}
+5 -1
View File
@@ -30,6 +30,10 @@
"livestream": "🔴 LIVE",
"gacha_quest": ""
},
"endingLabel": {
"range": "Kết thúc {{from}}–{{to}}",
"count": "{{count}} Kết thúc"
},
"gachaQuestType": {
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
"world_quest": "{{gameName}} — Nhiệm vụ thế giới: {{questName}}",
@@ -444,7 +448,7 @@
"boss": "Boss {{n}}",
"final_boss": "Boss cuối",
"intro": "Mở đầu",
"ending": "Kết thúc",
"ending": "Kết thúc {{n}}",
"tutorial": "Hướng dẫn",
"credits": "Credits"
}
+35 -2
View File
@@ -446,6 +446,29 @@
"custom": "Tuỳ chỉnh…"
}
},
"endings": {
"countLabel": "Số lượng ending",
"videoCountLabel": "Số video",
"videoLabel": "Video",
"numberLabel": "Số",
"nameLabel": "Tên",
"namePlaceholder": "ví dụ: Best Ending",
"previewLabel": "Hiển thị",
"previewEmpty": "(trống — nhập số hoặc tên)",
"emptyHint": "Thêm ít nhất một ending — để 0 để bỏ qua mục này.",
"addOne": "Thêm ending",
"removeLast": "Xoá ending cuối",
"videoRangeHint": "Mỗi video chứa một dải ending liên tiếp. Chia mặc định cân đối; sửa theo hàng để tuỳ chỉnh.",
"multiVideoOutputNote": "Mỗi video xuất một dải ending riêng. Bấm Generate như bình thường — bản preview hiển thị video 1.",
"warnings": {
"singleEmpty": "Hãy điền ít nhất số hoặc tên — entry rỗng sẽ bị bỏ khỏi mô tả.",
"timelineShort": "Timeline cần {{needed}} mốc ending; hiện chỉ có {{found}}. Thêm các mốc còn thiếu trước khi copy.",
"rangeInvalid": "Video {{video}}: dải {{from}}–{{to}} không hợp lệ (vượt giới hạn hoặc đảo ngược).",
"rangeGap": "Ending {{at}}+ không thuộc video nào — mở rộng dải hoặc thêm video.",
"rangeOverlap": "Nhiều video phủ ending {{at}} — điều chỉnh dải để tránh chồng lấp.",
"rangeShort": "Ending cuối được phủ là {{at}} nhưng có {{total}} ending — dải video cuối quá ngắn."
}
},
"techNotes": "Ghi chú kỹ thuật",
"techNoteSearchPlaceholder": "Tìm ghi chú…",
"techNoteEmpty": "Không có ghi chú phù hợp",
@@ -753,7 +776,10 @@
"pinnedCommentIncludeGenrePlaylist": "Kèm gợi ý playlist theo thể loại trong pinned comment",
"genrePlaylistsTitle": "Playlist theo thể loại",
"genrePlaylistsHelp": "Cấu hình URL YouTube playlist cho từng thể loại. Pinned comment sẽ tự động gợi ý playlist phù hợp với thể loại chính của video.",
"genrePlaylistsEmptyHint": "Bỏ trống nếu chưa có playlist cho thể loại đó."
"genrePlaylistsEmptyHint": "Bỏ trống nếu chưa có playlist cho thể loại đó.",
"logSettings": "Nhật ký",
"logRetentionDays": "Giữ log (ngày)",
"logRetentionHint": "Log cũ hơn số ngày này sẽ tự xoá khi mở app. Phạm vi: 1–90 ngày."
},
"batch": {
"title": "Chế độ hàng loạt",
@@ -799,6 +825,13 @@
"emptyState": "Chưa có nhật ký.",
"clearAll": "Xóa tất cả",
"clearConfirm": "Bạn có chắc muốn xóa toàn bộ nhật ký?",
"searchPlaceholder": "Tìm kiếm nhật ký..."
"clearPersistedConfirm": "Xóa nhật ký trong bộ nhớ VÀ xoá file log đã lưu? Hành động này không thể hoàn tác.",
"clearSession": "Xoá phiên này",
"searchPlaceholder": "Tìm kiếm nhật ký...",
"exportJson": "Xuất JSON",
"exportTxt": "Xuất TXT",
"sessionCurrent": "Phiên hiện tại",
"sessionLabel": "Phiên {{n}}",
"entriesShort": "bản ghi"
}
}
+5 -1
View File
@@ -30,6 +30,10 @@
"livestream": "🔴 直播",
"gacha_quest": ""
},
"endingLabel": {
"range": "结局 {{from}}–{{to}}",
"count": "{{count}} 个结局"
},
"gachaQuestType": {
"main_story": "{{gameName}} — {{chapterName}}{{partSuffix}}",
"world_quest": "{{gameName}} — World Quest: {{questName}}",
@@ -444,7 +448,7 @@
"boss": "Boss {{n}}",
"final_boss": "最终Boss",
"intro": "开场",
"ending": "结局",
"ending": "结局 {{n}}",
"tutorial": "教程",
"credits": "片尾"
}
+35 -2
View File
@@ -446,6 +446,29 @@
"custom": "自定义…"
}
},
"endings": {
"countLabel": "结局数量",
"videoCountLabel": "视频数量",
"videoLabel": "视频",
"numberLabel": "编号",
"nameLabel": "名称",
"namePlaceholder": "如:最佳结局",
"previewLabel": "显示",
"previewEmpty": "(为空 — 请填写编号或名称)",
"emptyHint": "至少添加一个结局 — 留空为 0 将跳过此项。",
"addOne": "添加结局",
"removeLast": "删除最后一个",
"videoRangeHint": "每个视频覆盖一段连续的结局。默认均匀分配,可按行覆盖。",
"multiVideoOutputNote": "每个视频的描述渲染对应结局段。从编辑器照常生成 — 预览默认显示视频 1。",
"warnings": {
"singleEmpty": "至少填写编号或名称 — 空白条目将从描述中排除。",
"timelineShort": "时间线需要 {{needed}} 个结局标记,但只有 {{found}} 个。复制前请补齐。",
"rangeInvalid": "视频 {{video}}:范围 {{from}}–{{to}} 无效(超出范围或反向)。",
"rangeGap": "结局 {{at}}+ 未被任何视频覆盖 — 扩展某个范围或添加视频。",
"rangeOverlap": "多个视频覆盖结局 {{at}} — 请调整范围以避免重叠。",
"rangeShort": "最后覆盖的结局是 {{at}},但共有 {{total}} 个 — 最后一个视频范围过短。"
}
},
"techNotes": "技术说明",
"techNoteSearchPlaceholder": "搜索说明…",
"techNoteEmpty": "无匹配的说明",
@@ -753,7 +776,10 @@
"pinnedCommentIncludeGenrePlaylist": "Include genre-playlist suggestion in pinned comment",
"genrePlaylistsTitle": "Genre Playlists",
"genrePlaylistsHelp": "Configure a YouTube playlist URL per genre. The pinned-comment template will auto-suggest the matching playlist when the video's primary genre is selected.",
"genrePlaylistsEmptyHint": "Leave empty to skip a genre."
"genrePlaylistsEmptyHint": "Leave empty to skip a genre.",
"logSettings": "日志",
"logRetentionDays": "日志保留 (天)",
"logRetentionHint": "早于此天数的日志会在启动时删除。范围:1–90 天。"
},
"batch": {
"title": "批量生成",
@@ -799,6 +825,13 @@
"emptyState": "暂无日志。",
"clearAll": "清除全部",
"clearConfirm": "确定要清除所有日志吗?",
"searchPlaceholder": "搜索日志..."
"clearPersistedConfirm": "清除内存中的日志并删除已保存的日志文件?此操作无法撤销。",
"clearSession": "清除此会话",
"searchPlaceholder": "搜索日志...",
"exportJson": "导出 JSON",
"exportTxt": "导出 TXT",
"sessionCurrent": "当前会话",
"sessionLabel": "会话 {{n}}",
"entriesShort": "条"
}
}
+9 -1
View File
@@ -1,13 +1,21 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import { ErrorBoundary } from "./components/ErrorBoundary";
import "./styles/globals.css";
const root = document.getElementById("root");
if (!root) throw new Error("Root element not found");
// Top-level safety net. Per-route boundaries in App.tsx catch most
// errors with route-specific labels; this outer one only fires if
// something explodes *before* the router mounts (e.g. i18n init, store
// rehydrate). Without it, a top-level crash still produces a black
// page — defeating the point of per-route boundaries.
createRoot(root).render(
<StrictMode>
<App />
<ErrorBoundary label="app">
<App />
</ErrorBoundary>
</StrictMode>,
);
+217 -50
View File
@@ -1,12 +1,14 @@
import { useState, useRef, useEffect } from "react";
import { useState, useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useDocumentTitle } from "@hooks/use-document-title";
import { Trash2 } from "lucide-react";
import { Trash2, ChevronDown, ChevronRight, FileJson, FileText } from "lucide-react";
import { Input } from "@components/ui/Input";
import { Button } from "@components/ui/Button";
import { ConfirmDialog } from "@components/ui/ConfirmDialog";
import { LogEntryCard } from "@components/logs/LogEntry";
import { useLogStore, type LogLevel } from "@store/log-store";
import { useLogStore, type LogEntry, type LogLevel } from "@store/log-store";
import { exportTypedToJsonFile } from "@utils/import-export";
import { saveFile } from "@utils/file-ops";
import clsx from "clsx";
const LEVEL_FILTERS: Array<{ value: LogLevel | "all"; label: string; color: string }> = [
@@ -17,37 +19,99 @@ const LEVEL_FILTERS: Array<{ value: LogLevel | "all"; label: string; color: stri
{ value: "debug", label: "Debug", color: "text-gray-400" },
];
/**
* v0.17.0 LogPage. Three new concerns over the v0.16.x version:
*
* 1. **Session-grouped accordion**. The store now tags each entry
* with a `sessionId` (one per app boot). The page collects
* consecutive entries by id and renders one collapsible block
* per session. The *current* session expands by default; prior
* sessions collapse so the page opens fast even after a week of
* persisted history.
*
* 2. **Export buttons**. Two flavours:
* - JSON (envelope-wrapped) — feeds back into the v0.15 import
* pipeline (`_type: "history"` for now; eventually a dedicated
* `log` type when there's a use case to re-import).
* - Plaintext (.txt) — one line per entry, formatted as
* `[ISO time] [LEVEL] [source] message — details`. Most useful
* for pasting into a bug report.
*
* 3. **Session-scoped clear**. The existing `Clear All` confirms
* via the same dialog; a new "Clear this session" inline action
* on each session header lets a creator drop one bad debug run
* without losing prior history.
*/
export function LogPage() {
const { t } = useTranslation("ui");
useDocumentTitle(t("tabs.logs"));
const { entries, clearAll } = useLogStore();
// `clearAll` (in-memory only) intentionally omitted — the page uses
// `clearAllPersisted` so the on-disk JSONL files don't drift out of
// sync with the in-memory tail when the user hits the toolbar trash.
const { entries, currentSessionId, clearSession, clearAllPersisted } = useLogStore();
const [search, setSearch] = useState("");
const [levelFilter, setLevelFilter] = useState<LogLevel | "all">("all");
const [showClearAll, setShowClearAll] = useState(false);
const [autoScroll, setAutoScroll] = useState(true);
const listRef = useRef<HTMLDivElement>(null);
const [collapsedSessions, setCollapsedSessions] = useState<Set<string>>(new Set());
const filtered = entries.filter((e) => {
if (levelFilter !== "all" && e.level !== levelFilter) return false;
if (search) {
const q = search.toLowerCase();
return (
e.message.toLowerCase().includes(q) ||
e.source.toLowerCase().includes(q) ||
(e.details?.toLowerCase().includes(q) ?? false)
);
/** Apply level + search filters before grouping so empty sessions
* (whose only entries got filtered out) disappear entirely. */
const filtered = useMemo<LogEntry[]>(() => {
return entries.filter((e) => {
if (levelFilter !== "all" && e.level !== levelFilter) return false;
if (search) {
const q = search.toLowerCase();
return (
e.message.toLowerCase().includes(q) ||
e.source.toLowerCase().includes(q) ||
(e.details?.toLowerCase().includes(q) ?? false)
);
}
return true;
});
}, [entries, levelFilter, search]);
/** Group filtered entries by sessionId, preserving the descending-time
* order the store maintains. Each session carries summary counts
* rendered in the header. */
const sessions = useMemo(() => {
const map = new Map<string, LogEntry[]>();
for (const entry of filtered) {
const existing = map.get(entry.sessionId);
if (existing) {
existing.push(entry);
} else {
map.set(entry.sessionId, [entry]);
}
}
return true;
});
return Array.from(map.entries()).map(([id, sessionEntries]) => ({
id,
entries: sessionEntries,
isCurrent: id === currentSessionId,
// First entry is newest (entries are prepended); last is oldest
// — used for the time range label.
firstAt: sessionEntries[sessionEntries.length - 1]?.timestamp ?? "",
lastAt: sessionEntries[0]?.timestamp ?? "",
errorCount: sessionEntries.filter((e) => e.level === "error").length,
warnCount: sessionEntries.filter((e) => e.level === "warn").length,
}));
}, [filtered, currentSessionId]);
const errorCount = entries.filter((e) => e.level === "error").length;
const warnCount = entries.filter((e) => e.level === "warn").length;
const totalErrorCount = entries.filter((e) => e.level === "error").length;
const totalWarnCount = entries.filter((e) => e.level === "warn").length;
useEffect(() => {
if (autoScroll && listRef.current) {
listRef.current.scrollTop = 0;
}
}, [entries.length, autoScroll]);
const handleExportJson = () => {
exportTypedToJsonFile("history", entries, `ytdescgen-logs-${todayStamp()}.json`);
};
const handleExportTxt = async () => {
const text = entries
.slice()
.reverse() // chronological order in the export
.map(formatPlaintextLine)
.join("\n");
await saveFile(text, `ytdescgen-logs-${todayStamp()}.txt`);
};
return (
<div className="mx-auto max-w-4xl p-6">
@@ -55,30 +119,31 @@ export function LogPage() {
<div className="flex items-center gap-3">
<h1 className="text-lg font-bold text-text-primary">{t("logs.title")}</h1>
<span className="text-xs text-text-muted">
{entries.length} entries
{errorCount > 0 && (
<span className="ml-1 text-red-400">({errorCount} errors)</span>
{entries.length} entries · {sessions.length} sessions
{totalErrorCount > 0 && (
<span className="ml-1 text-red-400">({totalErrorCount} errors)</span>
)}
{warnCount > 0 && (
<span className="ml-1 text-yellow-400">({warnCount} warnings)</span>
{totalWarnCount > 0 && (
<span className="ml-1 text-yellow-400">({totalWarnCount} warnings)</span>
)}
</span>
</div>
<div className="flex items-center gap-2">
<label className="flex items-center gap-1.5 text-xs text-text-muted">
<input
type="checkbox"
checked={autoScroll}
onChange={(e) => setAutoScroll(e.target.checked)}
className="rounded"
/>
Auto-scroll
</label>
{entries.length > 0 && (
<Button variant="ghost" size="sm" onClick={() => setShowClearAll(true)}>
<Trash2 className="h-3.5 w-3.5" />
{t("logs.clearAll")}
</Button>
<>
<Button variant="ghost" size="sm" onClick={handleExportJson}>
<FileJson className="h-3.5 w-3.5" />
{t("logs.exportJson")}
</Button>
<Button variant="ghost" size="sm" onClick={handleExportTxt}>
<FileText className="h-3.5 w-3.5" />
{t("logs.exportTxt")}
</Button>
<Button variant="ghost" size="sm" onClick={() => setShowClearAll(true)}>
<Trash2 className="h-3.5 w-3.5" />
{t("logs.clearAll")}
</Button>
</>
)}
</div>
</div>
@@ -110,30 +175,132 @@ export function LogPage() {
</div>
</div>
{/* Log entries */}
{filtered.length === 0 ? (
{/* Session-grouped entries */}
{sessions.length === 0 ? (
<p className="rounded-lg border border-dashed border-border py-12 text-center text-sm text-text-muted">
{t("logs.emptyState")}
</p>
) : (
<div ref={listRef} className="flex max-h-[65vh] flex-col gap-1.5 overflow-y-auto">
{filtered.map((entry) => (
<LogEntryCard key={entry.id} entry={entry} />
))}
<div className="flex max-h-[65vh] flex-col gap-2 overflow-y-auto">
{sessions.map((session, idx) => {
const isCollapsed = collapsedSessions.has(session.id);
// Auto-collapse non-current sessions on first render — we
// store the inverse (collapsed-set) so this defaults to
// expanded for the current session.
const effectivelyCollapsed = session.isCurrent
? isCollapsed
: !collapsedSessions.has(`__expanded__${session.id}`);
return (
<div
key={session.id}
className="rounded-lg border border-border bg-surface-1"
>
<div
className="flex cursor-pointer items-center gap-2 px-3 py-2"
onClick={() => {
// Two different toggle keys depending on default
// state — keeps the "current expanded, others
// collapsed" semantic from leaking into the set.
setCollapsedSessions((prev) => {
const next = new Set(prev);
const key = session.isCurrent
? session.id
: `__expanded__${session.id}`;
if (next.has(key)) next.delete(key);
else next.add(key);
return next;
});
}}
>
{effectivelyCollapsed ? (
<ChevronRight className="h-4 w-4 text-text-muted" />
) : (
<ChevronDown className="h-4 w-4 text-text-muted" />
)}
<span className="text-sm font-semibold text-text-primary">
{session.isCurrent
? t("logs.sessionCurrent")
: t("logs.sessionLabel", { n: sessions.length - idx })}
</span>
<span className="text-xs text-text-muted">
{formatRange(session.firstAt, session.lastAt)}
</span>
<span className="text-xs text-text-muted">
· {session.entries.length} {t("logs.entriesShort")}
</span>
{session.errorCount > 0 && (
<span className="text-xs text-red-400">
· {session.errorCount} errors
</span>
)}
{session.warnCount > 0 && (
<span className="text-xs text-yellow-400">
· {session.warnCount} warnings
</span>
)}
<div className="flex-1" />
<button
onClick={(e) => {
e.stopPropagation();
clearSession(session.id);
}}
className="rounded p-1 text-text-muted hover:bg-surface-3 hover:text-danger"
title={t("logs.clearSession")}
>
<Trash2 className="h-3 w-3" />
</button>
</div>
{!effectivelyCollapsed && (
<div className="flex flex-col gap-1 border-t border-border p-2">
{session.entries.map((entry) => (
<LogEntryCard key={entry.id} entry={entry} />
))}
</div>
)}
</div>
);
})}
</div>
)}
<ConfirmDialog
open={showClearAll}
onConfirm={() => {
clearAll();
void clearAllPersisted();
setShowClearAll(false);
}}
onCancel={() => setShowClearAll(false)}
title={t("logs.clearAll")}
message={t("logs.clearConfirm")}
message={t("logs.clearPersistedConfirm")}
variant="danger"
/>
</div>
);
}
/** Format an ISO timestamp pair as `HH:MM:SS → HH:MM:SS`. Falls back
* to a single point when both ends match (single-entry session). */
function formatRange(firstIso: string, lastIso: string): string {
const first = firstIso ? new Date(firstIso).toLocaleTimeString() : "";
const last = lastIso ? new Date(lastIso).toLocaleTimeString() : "";
if (!first) return last;
if (!last || first === last) return first;
return `${first} → ${last}`;
}
/** Build today's date stamp for export filenames. */
function todayStamp(): string {
const now = new Date();
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, "0");
const d = String(now.getDate()).padStart(2, "0");
return `${y}${m}${d}`;
}
/** One-line text formatter for the plaintext export. */
function formatPlaintextLine(entry: LogEntry): string {
const time = entry.timestamp;
const head = `[${time}] [${entry.level.toUpperCase()}] [${entry.source}] ${entry.message}`;
return entry.details ? `${head} — ${entry.details}` : head;
}
+134 -25
View File
@@ -9,12 +9,35 @@ import { TemplateList } from "@components/templates/TemplateList";
import { useProfileStore, type Profile } from "@store/profile-store";
import { usePresetStore, type GamePreset } from "@store/preset-store";
import { useTemplateStore, type EditorTemplate } from "@store/template-store";
import { exportToJsonFile, importFromJsonFile } from "@utils/import-export";
import {
exportTypedToJsonFile,
importTypedFromJsonFile,
type ImportFailure,
} from "@utils/import-export";
import type { ExportType } from "@utils/file-schema";
import { logger } from "@utils/logger";
import toast from "react-hot-toast";
import clsx from "clsx";
type Tab = "profiles" | "presets" | "templates";
/** Map a tab id to the envelope `_type` discriminator. The tab labels
* are plural for UI; the envelope type is singular ("profile" not
* "profiles") so it reads as the *kind* of each row, not the file. */
const TAB_TO_TYPE: Record<Tab, ExportType> = {
profiles: "profile",
presets: "preset",
templates: "template",
};
/** Reverse map for the tab-switch suggestion when an import lands in
* the wrong tab — see `renderFailureToast`. */
const TYPE_TO_TAB: Partial<Record<ExportType, Tab>> = {
profile: "profiles",
preset: "presets",
template: "templates",
};
export function ProfilesPage() {
const { t } = useTranslation("ui");
useDocumentTitle(t("tabs.profiles"));
@@ -23,52 +46,133 @@ export function ProfilesPage() {
const { presets, importPresets } = usePresetStore();
const { templates, importTemplates } = useTemplateStore();
/**
* Render a tab-specific toast for an import failure. Each failure
* kind gets its own copy so the user can actually fix the problem
* (the old "Import failed" toast was almost useless for debugging).
* "wrong-shape" with a known actual type also offers a one-click
* fix via the toast action (`onClick` on the toast itself wouldn't
* work — react-hot-toast doesn't surface actions on the default
* `toast.error`, so we surface a follow-up `toast(`…`)` with the
* switch hint instead).
*/
function renderFailureToast(failure: ImportFailure, expected: ExportType): void {
switch (failure.kind) {
case "cancelled":
return; // silent
case "read-failed":
toast.error(`Could not read file: ${failure.message}`);
logger.error("import", `read-failed for ${expected}`, failure.message);
return;
case "empty":
toast.error("File is empty");
logger.warn("import", `empty file for ${expected}`);
return;
case "parse-error":
toast.error(`Invalid JSON: ${failure.message}`);
logger.error("import", `parse-error for ${expected}`, failure.message);
return;
case "wrong-shape": {
if (failure.actual) {
const suggestedTab = TYPE_TO_TAB[failure.actual];
const label = failure.actual.charAt(0).toUpperCase() + failure.actual.slice(1);
if (suggestedTab) {
toast.error(
`This file looks like a ${label} export. Switching tabs…`,
{ duration: 4000 },
);
setTab(suggestedTab);
logger.info(
"import",
`auto-switched tab from ${expected} to ${failure.actual}`,
);
return;
}
toast.error(`This file is a ${label} export, not ${expected}.`);
return;
}
toast.error("File shape is not recognised — choose a YTDescGen export.");
logger.warn("import", `unknown-shape for ${expected}`);
return;
}
case "newer-schema":
toast.error(
`File was exported by a newer version (schema v${failure.actual}; this build supports up to v${failure.supported}). Update YTDescGen.`,
);
logger.warn(
"import",
`newer-schema for ${expected}: file=v${failure.actual} supported=v${failure.supported}`,
);
return;
}
}
const handleExportProfiles = () => {
exportToJsonFile(profiles, "ytdescgen-profiles.json");
exportTypedToJsonFile("profile", profiles, "ytdescgen-profiles.json");
toast.success("Exported!");
};
const handleImportProfiles = async () => {
try {
const data = await importFromJsonFile<Profile[]>();
if (!Array.isArray(data)) throw new Error("Invalid format");
importProfiles(data);
toast.success("Imported!");
} catch {
toast.error("Import failed");
const result = await importTypedFromJsonFile("profile");
if (!result.ok) {
renderFailureToast(result.failure, "profile");
return;
}
// The detector only confirms the *shape* matches profile-ness; the
// store-level `importProfiles` filters individual rows that fail
// per-field validation (missing id, etc.). Two layers of validation
// is intentional — keeps callers' contracts clean and prevents a
// future tab-specific quirk from corrupting unrelated stores.
const incoming = Array.isArray(result.data) ? (result.data as Profile[]) : [];
importProfiles(incoming);
const accepted = useProfileStore.getState().profiles.length - profiles.length;
toast.success(
accepted === incoming.length
? `Imported ${accepted} profile${accepted === 1 ? "" : "s"}.`
: `Imported ${accepted} of ${incoming.length} profiles (some skipped).`,
);
};
const handleExportPresets = () => {
exportToJsonFile(presets, "ytdescgen-presets.json");
exportTypedToJsonFile("preset", presets, "ytdescgen-presets.json");
toast.success("Exported!");
};
const handleImportPresets = async () => {
try {
const data = await importFromJsonFile<GamePreset[]>();
if (!Array.isArray(data)) throw new Error("Invalid format");
importPresets(data);
toast.success("Imported!");
} catch {
toast.error("Import failed");
const result = await importTypedFromJsonFile("preset");
if (!result.ok) {
renderFailureToast(result.failure, "preset");
return;
}
const incoming = Array.isArray(result.data) ? (result.data as GamePreset[]) : [];
importPresets(incoming);
const accepted = usePresetStore.getState().presets.length - presets.length;
toast.success(
accepted === incoming.length
? `Imported ${accepted} preset${accepted === 1 ? "" : "s"}.`
: `Imported ${accepted} of ${incoming.length} presets (some skipped).`,
);
};
const handleExportTemplates = () => {
exportToJsonFile(templates, "ytdescgen-templates.json");
exportTypedToJsonFile("template", templates, "ytdescgen-templates.json");
toast.success("Exported!");
};
const handleImportTemplates = async () => {
try {
const data = await importFromJsonFile<EditorTemplate[]>();
if (!Array.isArray(data)) throw new Error("Invalid format");
importTemplates(data);
toast.success("Imported!");
} catch {
toast.error("Import failed");
const result = await importTypedFromJsonFile("template");
if (!result.ok) {
renderFailureToast(result.failure, "template");
return;
}
const incoming = Array.isArray(result.data) ? (result.data as EditorTemplate[]) : [];
importTemplates(incoming);
const accepted = useTemplateStore.getState().templates.length - templates.length;
toast.success(
accepted === incoming.length
? `Imported ${accepted} template${accepted === 1 ? "" : "s"}.`
: `Imported ${accepted} of ${incoming.length} templates (some skipped).`,
);
};
return (
@@ -136,3 +240,8 @@ export function ProfilesPage() {
</div>
);
}
// `TAB_TO_TYPE` kept exported-shaped (not exported) for now — currently
// only this file maps tabs to types. Promote to an export if a future
// page (e.g. a "Backup all" button on Settings) reuses the mapping.
void TAB_TO_TYPE;
+19
View File
@@ -425,6 +425,25 @@ export function SettingsPage() {
}}
/>
</section>
{/* 8. Logs — v0.17.0 retention. */}
<section className="flex flex-col gap-3">
<h2 className="text-sm font-semibold text-text-secondary">{t("settings.logSettings")}</h2>
<Input
label={t("settings.logRetentionDays")}
type="number"
min={1}
max={90}
value={String(settings.logRetentionDays)}
onChange={(e) => {
// Same clamp as `healSettings` so the in-memory value
// never goes out of bounds before persistence runs.
const val = Math.max(1, Math.min(90, Number(e.target.value) || 7));
settings.setSetting("logRetentionDays", val);
}}
/>
<p className="text-xs text-text-muted">{t("settings.logRetentionHint")}</p>
</section>
</div>
</div>
);
+158 -3
View File
@@ -11,6 +11,8 @@ import type {
LanguagePatch,
GameVersion,
TechNote,
EndingEntry,
EndingVideoRange,
} from "@engine/types";
import {
LANGUAGE_PATCH_OPTIONS,
@@ -93,8 +95,35 @@ export interface EditorData {
playthroughStatus: PlaythroughStatus;
difficulty: DifficultyLevel;
difficultyCustomLabel: string;
/** Free-text endings descriptor for Playthrough Notes (v0.12). */
/**
* Free-text endings descriptor for Playthrough Notes (v0.12).
* @deprecated v0.16.0 — kept on the type for migration round-trip,
* but the editor UI no longer reads or writes this field. Persisted
* v0.12–v0.15 drafts get lifted into a single-row `endings` entry
* by `migrateEditorState` v11 → v12.
*/
endingsShown: string;
/**
* Structured ending list (v0.16.0). Empty array = "no endings to
* declare"; the description renderer falls back to the legacy
* `endingsShown` freeform only when this array is empty AND the
* legacy string is non-empty (covers post-migration drafts that
* still carry both). Editor cap is 100 rows.
*/
endings: EndingEntry[];
/**
* Number of separate videos the playthrough is split across
* (v0.16.0). Always 1 when `endings.length <= 1`. Editor input
* clamps to `[1, endings.length]`.
*/
endingVideoCount: number;
/**
* Per-video ending range (v0.16.0). 1-indexed inclusive bounds into
* `endings[]`. Length always equals `endingVideoCount`; auto-derived
* as a contiguous balanced split on edit, persisted so the creator
* can override.
*/
endingVideoRanges: EndingVideoRange[];
/** Language-patch enum for Playthrough Notes (v0.12). */
languagePatch: LanguagePatch;
/** Free-form label paired with `languagePatch === "official_other" | "custom"`. */
@@ -146,7 +175,17 @@ export function legacyGraphicsPresetToEnum(legacy: string): {
* accepts via structural compatibility — we sniff the runtime value here
* via an `unknown` cast.
*/
function normalizeEditorPatch(patch: Partial<EditorData>): Partial<EditorData> {
function normalizeEditorPatch(
patch: Partial<EditorData> | null | undefined,
): Partial<EditorData> {
// v0.15.0: guard against malformed input. Previously a `null` patch
// — typically from an imported template whose `snapshot` field was
// null/undefined — reached the spread on the next line and threw
// "Cannot convert undefined or null to object", which bubbled out of
// `set()` as an unhandled render error and black-screened the app.
// Returning an empty patch lets the caller's `{ ...state, ...patch }`
// become a no-op instead of crashing.
if (!patch || typeof patch !== "object") return {};
const out: Partial<EditorData> = { ...patch };
const raw: unknown = (patch as { graphicsPreset?: unknown }).graphicsPreset;
if (typeof raw === "string" && !(GRAPHICS_PRESETS as readonly string[]).includes(raw)) {
@@ -265,6 +304,9 @@ const initialState: EditorData = {
difficulty: DEFAULTS.editor.difficulty as DifficultyLevel,
difficultyCustomLabel: DEFAULTS.editor.difficultyCustomLabel,
endingsShown: DEFAULTS.editor.endingsShown,
endings: [...DEFAULTS.editor.endings] as EndingEntry[],
endingVideoCount: DEFAULTS.editor.endingVideoCount,
endingVideoRanges: [...DEFAULTS.editor.endingVideoRanges] as EndingVideoRange[],
languagePatch: DEFAULTS.editor.languagePatch,
languagePatchCustom: DEFAULTS.editor.languagePatchCustom,
gameVersion: DEFAULTS.editor.gameVersion,
@@ -299,6 +341,11 @@ export const useEditorStore = create<EditorState>()(
storeLinkTypes: { ...state.storeLinkTypes, [platformId]: type },
})),
// `normalizeEditorPatch` now null-guards internally (v0.15.0) so
// a malformed profile / template snapshot is treated as a no-op
// rather than crashing the render. The action signature still
// requires a non-null patch in TypeScript — runtime safety covers
// the persisted-blob case where types lie.
loadProfile: (profile) =>
set((state) => ({ ...state, ...normalizeEditorPatch(profile) })),
@@ -365,13 +412,22 @@ export const useEditorStore = create<EditorState>()(
// existing `playthroughStatus` / `difficulty` /
// `difficultyCustomLabel` values are preserved; only the
// description-builder render path changed.
// v11 → v12: v0.16.0. Free-form `endingsShown` string is being
// superseded by a structured `endings` array of
// {number, name} entries plus `endingVideoCount` +
// `endingVideoRanges` for multi-video splits. Migration
// lifts the legacy string into a single-row
// `endings` entry so the renderer (which now reads
// the array first, falls back to the freeform when the
// array is empty) produces identical output for
// existing drafts.
// v10 → v11: v0.13. Gacha-quest gained three new structured fields:
// `characterName` (used for the Showcase quest type, replacing
// chapter/quest in templates), `anniversaryYear` (1–20 number
// used by the Anniversary quest type), and `gachaVersion`
// (free-form game version like "1.2"). All additive — empty
// / null defaults round-trip cleanly.
version: 11,
version: 12,
migrate: (persistedState, version) =>
migrateEditorState(persistedState, version),
partialize: (state) => ({
@@ -423,6 +479,9 @@ export const useEditorStore = create<EditorState>()(
difficulty: state.difficulty,
difficultyCustomLabel: state.difficultyCustomLabel,
endingsShown: state.endingsShown,
endings: state.endings,
endingVideoCount: state.endingVideoCount,
endingVideoRanges: state.endingVideoRanges,
languagePatch: state.languagePatch,
languagePatchCustom: state.languagePatchCustom,
gameVersion: state.gameVersion,
@@ -608,5 +667,101 @@ export function migrateEditorState(
state.anniversaryYear = null;
}
}
if (version < 12) {
// v0.16.0 ending redesign. Two concerns:
//
// 1. Lift the legacy `endingsShown` freeform into the structured
// `endings` array if no array is already present. The string is
// kept in place (the deprecated field still exists on
// EditorData) so a render path that's mid-migration won't lose
// data, but the structured renderer reads the array first.
//
// 2. Initialise the multi-video split fields. Default
// endingVideoCount = 1, ranges = single span covering all
// endings (or empty when endings.length === 0).
if (!Array.isArray(state.endings)) {
const legacy = typeof state.endingsShown === "string" ? state.endingsShown.trim() : "";
state.endings = liftLegacyEndingString(legacy);
}
if (typeof state.endingVideoCount !== "number" || state.endingVideoCount < 1) {
state.endingVideoCount = 1;
}
const endingsLen = (state.endings as EndingEntry[]).length;
// Clamp video count to [1, endings.length || 1].
state.endingVideoCount = Math.min(
Math.max(1, state.endingVideoCount as number),
endingsLen > 0 ? endingsLen : 1,
);
if (
!Array.isArray(state.endingVideoRanges) ||
(state.endingVideoRanges as EndingVideoRange[]).length !== state.endingVideoCount
) {
state.endingVideoRanges =
endingsLen === 0
? []
: computeContiguousRanges(endingsLen, state.endingVideoCount as number);
}
}
return { ...initialState, ...state } as EditorData;
}
/**
* Parse a legacy `endingsShown` freeform string into one structured
* {@link EndingEntry} row. Recognises a handful of common shapes so
* persisted v0.12–v0.15 drafts surface the same value after migration:
*
* - "Ending 3: Best End" → { number: 3, name: "Best End" }
* - "Ending 3" → { number: 3, name: "" }
* - "True Ending" → { number: null, name: "True Ending" }
* - "" → [] (no row)
*
* Anything that doesn't match the "Ending {N}: …" pattern falls
* through to a single name-only row. Pure — exported for unit tests.
*/
export function liftLegacyEndingString(raw: string): EndingEntry[] {
const trimmed = raw.trim();
if (!trimmed) return [];
// Match optional "Ending" prefix + number + optional ": rest" tail.
// Case-insensitive on the keyword; localised variants ("kết thúc",
// "エンディング", "结局") are accepted too. Anything else → name-only.
const m = trimmed.match(
/^(?:ending|kết\s+thúc|エンディング|final|엔딩|结局)\s*(\d+)\s*(?::\s*(.+))?\s*$/i,
);
if (m) {
const num = parseInt(m[1] ?? "", 10);
const name = (m[2] ?? "").trim();
if (Number.isFinite(num)) {
return [{ number: num, name }];
}
}
return [{ number: null, name: trimmed }];
}
/**
* Split an `endings.length` integer into `videoCount` contiguous
* balanced 1-indexed inclusive ranges. Extra endings spill into the
* tail videos: e.g. 7 endings / 3 videos → [[1,2],[3,4],[5,7]].
*
* Used by both the persist migration (initial range) and the
* `ending-split.ts` UI utility (on user-driven count changes). Pure.
*/
export function computeContiguousRanges(
endingsLength: number,
videoCount: number,
): EndingVideoRange[] {
if (endingsLength <= 0 || videoCount <= 0) return [];
const safeCount = Math.min(videoCount, endingsLength);
const base = Math.floor(endingsLength / safeCount);
const rem = endingsLength % safeCount;
const ranges: EndingVideoRange[] = [];
let cursor = 1;
for (let i = 0; i < safeCount; i++) {
// Spill the remainder onto the *last* video, not the first — most
// creators expect the early-ending videos to feel "lighter" than
// the climactic final video, which justifies the convention.
const size = base + (i === safeCount - 1 ? rem : 0);
ranges.push({ from: cursor, to: cursor + size - 1 });
cursor += size;
}
return ranges;
}
+91 -2
View File
@@ -1,5 +1,11 @@
import { create } from "zustand";
import { generateId } from "@utils/uuid";
import {
persistLogEntry,
loadRecentLogs,
pruneOldLogs,
clearAllPersistedLogs,
} from "@utils/log-storage";
export type LogLevel = "error" | "warn" | "info" | "debug";
@@ -10,29 +16,63 @@ export interface LogEntry {
source: string;
message: string;
details?: string;
/**
* Session identifier (v0.17.0). One per app boot, attached to
* every entry the store records during that lifetime. Lets the
* LogPage group entries into per-session accordion sections so
* "what happened since I opened the app" is readable at a glance,
* and prior-session history doesn't smear into the current run.
*/
sessionId: string;
}
interface LogState {
entries: LogEntry[];
addEntry: (data: Omit<LogEntry, "id" | "timestamp">) => void;
/** Session id of the *current* app boot. Stable for the lifetime
* of the store; entries from prior runs carry their own id. */
currentSessionId: string;
addEntry: (data: Omit<LogEntry, "id" | "timestamp" | "sessionId">) => void;
deleteEntry: (id: string) => void;
clearAll: () => void;
/** Clear in-memory state AND wipe persisted log files / localStorage.
* Used by the "Clear all persisted logs" action. */
clearAllPersisted: () => Promise<void>;
/** Clear all entries from a single session (current or historical). */
clearSession: (sessionId: string) => void;
}
const MAX_ENTRIES = 500;
/**
* In-memory cap. The previous limit (500) covered ~a few hours of
* heavy debug logging; raised to 2000 with persistence in play so
* the in-memory tail can fully represent a session for the LogPage
* accordion to render without paging.
*/
const MAX_ENTRIES = 2000;
/**
* Session id for THIS app boot. Module-scoped (not store-scoped) so
* every entry recorded during this process lifetime shares the same
* value regardless of which call site lands first.
*/
const CURRENT_SESSION_ID = generateId();
export const useLogStore = create<LogState>()((set) => ({
entries: [],
currentSessionId: CURRENT_SESSION_ID,
addEntry: (data) => {
const entry: LogEntry = {
...data,
id: generateId(),
timestamp: new Date().toISOString(),
sessionId: CURRENT_SESSION_ID,
};
set((state) => ({
entries: [entry, ...state.entries].slice(0, MAX_ENTRIES),
}));
// Fire-and-forget persistence. `persistLogEntry` swallows failures
// — we don't want a disk hiccup to escalate into a log loop.
void persistLogEntry(entry);
},
deleteEntry: (id) => {
@@ -40,4 +80,53 @@ export const useLogStore = create<LogState>()((set) => ({
},
clearAll: () => set({ entries: [] }),
clearAllPersisted: async () => {
set({ entries: [] });
await clearAllPersistedLogs();
},
clearSession: (sessionId) =>
set((state) => ({
entries: state.entries.filter((e) => e.sessionId !== sessionId),
})),
}));
/**
* Boot-time hydration. Reads recent persisted entries from disk /
* localStorage and folds them into the in-memory store before the
* UI mounts. Idempotent — re-running just produces the same merge
* (entries are deduped by id).
*
* Async and best-effort: if persistence fails or the platform layer
* isn't ready yet, the store just starts empty and accumulates from
* the current session forward. Called once from `App.tsx`.
*/
export async function hydrateLogStore(retentionDays: number): Promise<void> {
try {
const prior = await loadRecentLogs(retentionDays);
if (prior.length === 0) {
// No-op — first run / nothing in the retention window.
} else {
// Sort by timestamp descending so the newest is first
// (matches `addEntry`'s prepend semantics). Filter out anything
// already in memory by id to keep hydration idempotent.
const sorted = [...prior].sort(
(a, b) => Date.parse(b.timestamp) - Date.parse(a.timestamp),
);
useLogStore.setState((state) => {
const existing = new Set(state.entries.map((e) => e.id));
const fresh = sorted.filter((e) => !existing.has(e.id));
// Place fresh prior entries AFTER current session's entries
// (which were added between boot and this call) so the
// accordion still opens with the current session at top.
return { entries: [...state.entries, ...fresh].slice(0, MAX_ENTRIES) };
});
}
// Run retention sweep AFTER hydrate so the load can pick up
// entries that are about to be pruned (last-chance access).
void pruneOldLogs(retentionDays);
} catch {
// Hydration failure → store stays empty + per-session forward.
}
}
+10 -1
View File
@@ -63,9 +63,18 @@ export const usePresetStore = create<PresetState>()(
},
importPresets: (presets) => {
// v0.15.0: shape-check incoming rows before they hit the
// store. See profile-store.importProfiles for the rationale —
// a hand-edited / malformed file used to slip in rows with
// missing fields that then crashed downstream consumers.
if (!Array.isArray(presets)) return;
const valid = presets.filter(
(p): p is GamePreset =>
!!p && typeof p === "object" && typeof (p as GamePreset).id === "string",
);
set((state) => {
const existingIds = new Set(state.presets.map((p) => p.id));
const normalised = presets.map((p) => normalisePreset(p as LegacyPreset));
const normalised = valid.map((p) => normalisePreset(p as LegacyPreset));
const newPresets = normalised.filter((p) => !existingIds.has(p.id));
return { presets: [...state.presets, ...newPresets] };
});
+16 -1
View File
@@ -70,9 +70,24 @@ export const useProfileStore = create<ProfileState>()(
},
importProfiles: (profiles) => {
// v0.15.0: defensive shape check on each incoming row. A
// malformed import previously silently injected entries with
// `id: null` / `social: null` etc.; the next render then
// exploded on `Object.values(null)` and black-screened the
// app. Filter to objects with a non-empty string `id` before
// merging — anything that fails the check is dropped and
// logged via the caller's toast (ProfilesPage).
if (!Array.isArray(profiles)) return;
set((state) => {
const existingIds = new Set(state.profiles.map((p) => p.id));
const newProfiles = profiles.filter((p) => !existingIds.has(p.id));
const newProfiles = profiles.filter(
(p): p is Profile =>
!!p &&
typeof p === "object" &&
typeof p.id === "string" &&
p.id.length > 0 &&
!existingIds.has(p.id),
);
return { profiles: [...state.profiles, ...newProfiles] };
});
},
+19
View File
@@ -79,6 +79,14 @@ export interface SettingsData {
* narrow-screen users don't keep collapsing on every visit.
*/
sidebarCollapsed: boolean;
/**
* How many days of log history to keep on disk / in localStorage
* (v0.17.0). Files older than this are deleted at app boot.
* Default 7 — long enough to investigate week-ago issues, short
* enough to keep the AppData folder small. Clamped to `[1, 90]`
* by `healSettings`.
*/
logRetentionDays: number;
}
export function detectBrowserLanguage(): SupportedLanguage {
@@ -128,6 +136,7 @@ export const initialSettings: SettingsData = {
storeAndSocial: false,
},
sidebarCollapsed: false,
logRetentionDays: 7,
};
/**
@@ -172,5 +181,15 @@ export function healSettings(raw: unknown): SettingsData {
: {};
incoming.genrePlaylists = { ...initialSettings.genrePlaylists, ...incomingGp };
// v9 → v10: v0.17.0. `logRetentionDays` added (default 7). Clamp
// to [1, 90] so an extreme value can't either spam the disk or
// wipe everything on boot.
if (typeof incoming.logRetentionDays === "number") {
incoming.logRetentionDays = Math.max(
1,
Math.min(90, Math.floor(incoming.logRetentionDays)),
);
}
return { ...initialSettings, ...incoming } as SettingsData;
}
+4 -1
View File
@@ -69,7 +69,9 @@ export const useSettingsStore = create<SettingsState>()(
// explicit per-version migration step is required here.
// v8 → v9: v0.11 added `showThirdPartyAds`. Additive — same back-fill
// path as v8.
version: 9,
// v9 → v10: v0.17.0 added `logRetentionDays`. Additive — defaults to
// 7 days; `healSettings` clamps incoming values to [1, 90].
version: 10,
migrate: (persistedState: unknown): SettingsData => healSettings(persistedState),
partialize: (state) => extractData(state),
onRehydrateStorage: () => {
@@ -112,6 +114,7 @@ function extractData(state: SettingsData): SettingsData {
titleFormat: { ...state.titleFormat },
editorAccordionState: state.editorAccordionState,
sidebarCollapsed: state.sidebarCollapsed,
logRetentionDays: state.logRetentionDays,
};
}
+27 -2
View File
@@ -13,6 +13,8 @@ import type {
LanguagePatch,
GameVersion,
TechNote,
EndingEntry,
EndingVideoRange,
} from "@engine/types";
import type {
GraphicsPreset,
@@ -93,8 +95,15 @@ export interface TemplateSnapshot {
contentWarnings?: ContentWarning[];
/** v0.12 Playthrough Notes structured fields. Optional for back-compat
* with pre-v0.12 templates — `loadProfile` spreads `...patch` so
* missing keys keep the editor's existing values. */
* missing keys keep the editor's existing values.
* @deprecated v0.16.0 — superseded by structured `endings` array. */
endingsShown?: string;
/** v0.16.0 structured ending list — optional for back-compat with
* pre-v0.16 templates. The editor's `normalizeEditorPatch` will run
* `liftLegacyEndingString` on `endingsShown` if `endings` is absent. */
endings?: EndingEntry[];
endingVideoCount?: number;
endingVideoRanges?: EndingVideoRange[];
languagePatch?: LanguagePatch;
languagePatchCustom?: string;
gameVersion?: GameVersion;
@@ -166,9 +175,25 @@ export const useTemplateStore = create<TemplateState>()(
getTemplate: (id) => get().templates.find((tpl) => tpl.id === id),
importTemplates: (templates) => {
// v0.15.0: shape-check rows + require `snapshot` to be a
// non-null object. Previously a template with `snapshot:
// null` made it into the store, and clicking "Apply" on the
// resulting card crashed the editor on the next render via
// `Object.values(null)`. The boundary now catches that, but
// it's a worse UX than rejecting the bad row up front.
if (!Array.isArray(templates)) return;
set((state) => {
const existing = new Set(state.templates.map((tpl) => tpl.id));
const incoming = templates.filter((tpl) => !existing.has(tpl.id));
const incoming = templates.filter(
(tpl): tpl is EditorTemplate =>
!!tpl &&
typeof tpl === "object" &&
typeof tpl.id === "string" &&
tpl.id.length > 0 &&
!!tpl.snapshot &&
typeof tpl.snapshot === "object" &&
!existing.has(tpl.id),
);
return { templates: [...state.templates, ...incoming] };
});
},
+247
View File
@@ -0,0 +1,247 @@
/**
* Export-file envelope + shape detection.
*
* Motivation: prior to v0.15.0 every export was a bare JSON value
* (`Profile[]`, `GamePreset[]`, `EditorTemplate[]`, …) with no
* type marker. Users routinely confused the files — importing a
* templates dump into the Profiles tab silently injected entries
* with `social: undefined` that later crashed the editor render.
*
* The envelope adds a discriminator (`_type`) + version metadata so
* imports can:
*
* 1. Detect "you opened a Template file in the Profiles importer"
* and offer to switch tabs, rather than silently failing.
* 2. Migrate older shapes forward via per-type `healX` hooks.
* 3. Stay forward-compatible — files exported by future versions
* carry their `_schemaVersion`, so older builds can warn instead
* of corrupting state.
*
* Backward compatibility: legacy files (pre-v0.15 bare arrays /
* objects) are detected by {@link detectShape} and routed through the
* same import pipeline. Nothing breaks; users just lose the
* "wrong-tab" warning until they re-export.
*/
export const APP_MARKER = "ytdescgen" as const;
/** Kinds of payload the app can round-trip via JSON files. The string
* literal IS the on-disk discriminator — don't rename without writing
* a back-compat alias. */
export type ExportType =
| "profile"
| "preset"
| "template"
| "settings"
| "history";
/** Versioned wrapper written by every v0.15+ export. */
export interface ExportEnvelope<T = unknown> {
/** Static marker so a foreign JSON file (e.g. some other tool's
* export) can be rejected before we even look at `_type`. */
_app: typeof APP_MARKER;
_type: ExportType;
/** Per-type schema version — bumped when the inner shape changes
* in a non-additive way. Allows targeted migrations without
* touching the rest of the envelope. */
_schemaVersion: number;
_exportedAt: string;
/** App version that wrote the file. Informational only — never
* used as a migration key (the per-type `_schemaVersion` is). */
_appVersion?: string;
data: T;
}
/** Schema-version map. Bump the entry when you make a breaking change
* to the corresponding store's persisted shape AND want imports to
* branch on it. Additive changes (new optional fields) don't need a
* bump — `healX` functions back-fill them on load. */
export const SCHEMA_VERSIONS: Record<ExportType, number> = {
profile: 1, // v0.11 added `thirdPartyAdText`
preset: 2, // v0.5 added `genres[]` (was `genre`)
template: 1, // v0.11 vendor-coercion
settings: 10, // matches settings-store persist version
history: 2, // v0.5 added `genres[]` to HistoryEntry
};
/**
* Wrap `data` in an {@link ExportEnvelope}. Use this on the writer
* side — every v0.15+ export funnels through here so the envelope
* stays consistent.
*/
export function wrapEnvelope<T>(type: ExportType, data: T): ExportEnvelope<T> {
return {
_app: APP_MARKER,
_type: type,
_schemaVersion: SCHEMA_VERSIONS[type],
_exportedAt: new Date().toISOString(),
data,
};
}
/** Result of inspecting an imported JSON payload. */
export type DetectedShape =
| { kind: "envelope"; type: ExportType; schemaVersion: number; data: unknown }
| { kind: "legacy"; guessedType: ExportType | null; data: unknown }
| { kind: "unknown"; data: unknown };
/**
* Inspect a parsed JSON payload and classify it.
*
* Order of preference:
*
* 1. Envelope (`_app === "ytdescgen"` + valid `_type`) — authoritative,
* skip shape-sniffing.
* 2. Legacy shape detection on a bare array / object — best-effort
* guess by characteristic fields (e.g. `social` + `rig` on an
* array element → profiles).
* 3. Unknown — give up; caller surfaces a "wrong shape" toast.
*
* Pure — exported for unit tests.
*/
export function detectShape(parsed: unknown): DetectedShape {
if (!parsed || typeof parsed !== "object") {
return { kind: "unknown", data: parsed };
}
// 1. Envelope path.
const maybe = parsed as Partial<ExportEnvelope>;
if (
maybe._app === APP_MARKER &&
typeof maybe._type === "string" &&
isExportType(maybe._type)
) {
return {
kind: "envelope",
type: maybe._type,
schemaVersion:
typeof maybe._schemaVersion === "number" ? maybe._schemaVersion : 0,
data: maybe.data,
};
}
// 2. Legacy shape detection.
if (Array.isArray(parsed)) {
return { kind: "legacy", guessedType: guessArrayType(parsed), data: parsed };
}
if (typeof parsed === "object") {
// `Record<string, unknown>` — could be a bare SettingsData or the
// multi-store dump the Tauri settings.json writer produces (the
// latter is keyed by `ytdescgen-settings` / `ytdescgen-profiles`).
const asRecord = parsed as Record<string, unknown>;
if ("ytdescgen-settings" in asRecord || "appLanguage" in asRecord) {
return { kind: "legacy", guessedType: "settings", data: parsed };
}
}
return { kind: "unknown", data: parsed };
}
/** Type-guard helper so the `ExportType` literal stays the source of
* truth (don't duplicate the list). */
function isExportType(value: string): value is ExportType {
return (
value === "profile" ||
value === "preset" ||
value === "template" ||
value === "settings" ||
value === "history"
);
}
/**
* Best-effort: peek at the first non-null array element and guess its
* type by characteristic fields. Returns `null` if the array is empty
* or the first element doesn't match any known shape — callers should
* treat that as "wrong shape" and ask the user to choose the type.
*/
function guessArrayType(arr: unknown[]): ExportType | null {
const sample = arr.find((x) => !!x && typeof x === "object") as
| Record<string, unknown>
| undefined;
if (!sample) return null;
// Templates have a top-level `snapshot` object — most distinctive
// field.
if (typeof sample.snapshot === "object" && sample.snapshot !== null) {
return "template";
}
// Profiles carry channel-level data (channelName / social / rig).
if (
typeof sample.channelName === "string" ||
(typeof sample.social === "object" && typeof sample.rig === "object")
) {
return "profile";
}
// Presets carry game-level data (gameName + storeLinks).
if (
typeof sample.gameName === "string" &&
typeof sample.storeLinks === "object"
) {
return "preset";
}
// History entries always have a `createdAt` + (title|description|tags).
if (
typeof sample.createdAt === "string" &&
(typeof sample.title === "string" || typeof sample.tags === "string")
) {
return "history";
}
return null;
}
/**
* Resolve a detection result to the actual payload, given the type the
* caller expects to import.
*
* Returns `{ ok: true, data }` when the payload is usable, or
* `{ ok: false, reason }` when the import should be rejected and the
* caller should surface a toast. The `reason` field carries enough
* context for the UI to suggest a fix (e.g. switch tabs).
*/
export function resolveForType(
shape: DetectedShape,
expected: ExportType,
):
| { ok: true; data: unknown; sourceVersion?: number }
| {
ok: false;
reason:
| { kind: "wrong-type"; actual: ExportType }
| { kind: "unknown-shape" }
| { kind: "newer-schema"; actual: number; supported: number };
} {
switch (shape.kind) {
case "envelope": {
if (shape.type === expected) {
if (shape.schemaVersion > SCHEMA_VERSIONS[expected]) {
return {
ok: false,
reason: {
kind: "newer-schema",
actual: shape.schemaVersion,
supported: SCHEMA_VERSIONS[expected],
},
};
}
return { ok: true, data: shape.data, sourceVersion: shape.schemaVersion };
}
return { ok: false, reason: { kind: "wrong-type", actual: shape.type } };
}
case "legacy": {
if (shape.guessedType === expected || shape.guessedType === null) {
// Either the guess matches, or we couldn't guess and have to
// trust the user's tab choice. Both paths fall through to the
// existing import validator in the per-store importX function,
// which will skip any rows that don't have the right fields.
return { ok: true, data: shape.data };
}
return {
ok: false,
reason: { kind: "wrong-type", actual: shape.guessedType },
};
}
case "unknown":
return { ok: false, reason: { kind: "unknown-shape" } };
}
}
+201 -1
View File
@@ -1,6 +1,73 @@
import {
wrapEnvelope,
detectShape,
resolveForType,
type ExportType,
type DetectedShape,
} from "./file-schema";
/**
* Distinct failure modes the import pipeline surfaces to callers.
* Lets the UI render targeted toasts (and i18n keys, when we wire
* those up in a future release) instead of a single "Import failed"
* for every problem.
*
* - `cancelled`: user dismissed the file picker — handle silently.
* - `read-failed`: file picker resolved but reading raised (rare on
* web, more common on Tauri when the dialog cancellation race
* condition hits).
* - `empty`: file existed but was zero bytes / whitespace only.
* - `parse-error`: JSON parse threw — `message` carries the parser's
* line/col so the user can fix the file.
* - `wrong-shape`: parsed JSON is structurally invalid (not an
* object/array, or `_type` mismatch for the caller's expected
* type). `actual` is the detected type when known so the UI can
* suggest switching tabs.
* - `newer-schema`: file was exported by a future app version with
* an incompatible schema — refuse rather than risk silent data
* corruption.
*/
export type ImportFailure =
| { kind: "cancelled" }
| { kind: "read-failed"; message: string }
| { kind: "empty" }
| { kind: "parse-error"; message: string }
| { kind: "wrong-shape"; expected: ExportType; actual: ExportType | null }
| { kind: "newer-schema"; expected: ExportType; actual: number; supported: number };
export type ImportResult<T> =
| { ok: true; data: T; sourceVersion?: number }
| { ok: false; failure: ImportFailure };
/**
* Write `data` to a download as a typed envelope JSON file. The
* envelope marker lets a later import auto-detect the file's type
* (see {@link importTypedFromJsonFile}). Existing pre-v0.15 export
* call sites still work via {@link exportToJsonFile} below, which
* forwards here with no `type`.
*/
export function exportTypedToJsonFile<T>(
type: ExportType,
data: T,
filename: string,
): void {
const envelope = wrapEnvelope(type, data);
const json = JSON.stringify(envelope, null, 2);
triggerDownload(json, filename);
}
/**
* Legacy: untyped export (bare value, no envelope). Kept for the few
* call sites that aren't ready to migrate — anything new should use
* {@link exportTypedToJsonFile} so the import side gets auto-detect.
*/
export function exportToJsonFile(data: unknown, filename: string): void {
const json = JSON.stringify(data, null, 2);
const blob = new Blob([json], { type: "application/json" });
triggerDownload(json, filename);
}
function triggerDownload(content: string, filename: string): void {
const blob = new Blob([content], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
@@ -9,6 +76,139 @@ export function exportToJsonFile(data: unknown, filename: string): void {
URL.revokeObjectURL(url);
}
/**
* Read a JSON file from the user's disk and resolve to its parsed
* payload, classified by {@link detectShape}. Splits the "failure"
* paths so callers can render targeted toasts.
*
* This is the low-level reader — the typed wrapper
* {@link importTypedFromJsonFile} layers `resolveForType` on top so
* callers get a `{ ok: true; data: T }` discriminated union.
*
* Why not throw? Because every callsite had to swallow the throw and
* convert it back to a toast anyway — making failures values keeps
* the contract honest and forces handling at the call site.
*/
export function importParsedFromJsonFile(): Promise<
{ ok: true; shape: DetectedShape; rawText: string } | { ok: false; failure: ImportFailure }
> {
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json";
let settled = false;
const settle = (
result:
| { ok: true; shape: DetectedShape; rawText: string }
| { ok: false; failure: ImportFailure },
) => {
if (settled) return;
settled = true;
resolve(result);
};
// Browsers don't expose a reliable "user pressed cancel" event on
// <input type=file>. Fall back to focus-on-window heuristic: when
// the picker closes (either via OK or cancel), the window regains
// focus. If `onchange` hasn't fired by the next tick, treat as
// cancelled. The 250 ms wait covers slow desktops.
const onFocus = () => {
window.removeEventListener("focus", onFocus);
setTimeout(() => settle({ ok: false, failure: { kind: "cancelled" } }), 250);
};
window.addEventListener("focus", onFocus, { once: true });
input.onchange = () => {
window.removeEventListener("focus", onFocus);
const file = input.files?.[0];
if (!file) {
settle({ ok: false, failure: { kind: "cancelled" } });
return;
}
const reader = new FileReader();
reader.onload = () => {
const text = String(reader.result ?? "");
if (!text.trim()) {
settle({ ok: false, failure: { kind: "empty" } });
return;
}
let parsed: unknown;
try {
parsed = JSON.parse(text);
} catch (e) {
settle({
ok: false,
failure: { kind: "parse-error", message: String(e) },
});
return;
}
settle({ ok: true, shape: detectShape(parsed), rawText: text });
};
reader.onerror = () =>
settle({
ok: false,
failure: { kind: "read-failed", message: String(reader.error ?? "unknown") },
});
reader.readAsText(file);
};
input.click();
});
}
/**
* High-level typed import. Wraps {@link importParsedFromJsonFile} with
* {@link resolveForType} so the caller specifies the expected file
* type ("profile" / "preset" / "template" / …) and gets back either
* the validated payload or a structured failure.
*
* The returned `data` field is `unknown` because the underlying JSON
* may carry rows that fail per-field validation — narrow it via the
* per-store import function (each of which now filters malformed
* rows). This keeps the contract honest: passing the typing burden
* to a single validator instead of trusting the call site.
*/
export async function importTypedFromJsonFile(
expectedType: ExportType,
): Promise<ImportResult<unknown>> {
const read = await importParsedFromJsonFile();
if (!read.ok) return { ok: false, failure: read.failure };
const resolved = resolveForType(read.shape, expectedType);
if (!resolved.ok) {
switch (resolved.reason.kind) {
case "wrong-type":
return {
ok: false,
failure: {
kind: "wrong-shape",
expected: expectedType,
actual: resolved.reason.actual,
},
};
case "unknown-shape":
return {
ok: false,
failure: { kind: "wrong-shape", expected: expectedType, actual: null },
};
case "newer-schema":
return {
ok: false,
failure: {
kind: "newer-schema",
expected: expectedType,
actual: resolved.reason.actual,
supported: resolved.reason.supported,
},
};
}
}
return { ok: true, data: resolved.data, sourceVersion: resolved.sourceVersion };
}
/**
* Legacy: bare-value JSON import. Some call sites still need this
* (LogPage's eventual log-import, ad-hoc tooling). Throws on parse /
* empty errors — the new contract is {@link importTypedFromJsonFile}
* for everything user-facing.
*/
export function importFromJsonFile<T>(): Promise<T> {
return new Promise((resolve, reject) => {
const input = document.createElement("input");
+222
View File
@@ -0,0 +1,222 @@
import { IS_TAURI } from "./platform";
import type { LogEntry } from "@store/log-store";
/**
* Log persistence (v0.17.0). Bridges the in-memory log store to
* disk (Tauri JSONL files) / localStorage (web) so creators get a
* persistent trail across app restarts.
*
* Design choices:
*
* - **JSONL on disk**, one entry per line. Lets us append on every
* `addEntry` without re-serialising the whole tail, and a corrupt
* line never breaks the rest of the file (parse failures are
* filtered, not propagated).
* - **Daily file rotation** (`ytdescgen-YYYYMMDD.jsonl`). Cleanup
* sweeps just delete whole files older than `logRetentionDays`,
* which is dramatically faster than scanning every line.
* - **localStorage cap on web** (5000 entries). When the cap is
* exceeded, oldest entries drop. Roughly matches a week of
* moderate use; users who need more should use the desktop build.
* - **Best-effort writes**: persistence failures never throw — the
* in-memory store stays the source of truth even if disk writes
* fail. Errors get logged to the *previous* log entry's source so
* we don't recurse into an infinite write loop.
*/
const LOG_DIR_SUBPATH = "logs";
const FILE_PREFIX = "ytdescgen-";
const FILE_SUFFIX = ".jsonl";
const WEB_STORAGE_KEY = "ytdescgen-logs";
const WEB_MAX_ENTRIES = 5000;
/** Build today's log file name (`ytdescgen-YYYYMMDD.jsonl`). */
function todayFileName(now = new Date()): string {
const y = now.getFullYear();
const m = String(now.getMonth() + 1).padStart(2, "0");
const d = String(now.getDate()).padStart(2, "0");
return `${FILE_PREFIX}${y}${m}${d}${FILE_SUFFIX}`;
}
/** Extract the YYYYMMDD date from a log file name. Returns null when
* the name doesn't match the prefix/suffix shape — defensive against
* hand-edited files in the same directory. */
function parseFileDate(name: string): Date | null {
if (!name.startsWith(FILE_PREFIX) || !name.endsWith(FILE_SUFFIX)) {
return null;
}
const datePart = name.slice(FILE_PREFIX.length, name.length - FILE_SUFFIX.length);
if (!/^\d{8}$/.test(datePart)) return null;
const y = parseInt(datePart.slice(0, 4), 10);
const m = parseInt(datePart.slice(4, 6), 10) - 1;
const d = parseInt(datePart.slice(6, 8), 10);
return new Date(y, m, d);
}
/** Compute the absolute path to today's log file on the Tauri side. */
async function getTodayLogPath(): Promise<string> {
const { appDataDir } = await import("@tauri-apps/api/path");
const dir = await appDataDir();
return `${dir}${LOG_DIR_SUBPATH}/${todayFileName()}`;
}
async function getLogDirPath(): Promise<string> {
const { appDataDir } = await import("@tauri-apps/api/path");
const dir = await appDataDir();
return `${dir}${LOG_DIR_SUBPATH}`;
}
/**
* Append a single {@link LogEntry} to durable storage. On Tauri this
* writes one JSONL line to the daily file; on web it appends to the
* `ytdescgen-logs` localStorage key (with FIFO eviction when the cap
* is hit). Failures are swallowed — the in-memory store remains the
* canonical view.
*/
export async function persistLogEntry(entry: LogEntry): Promise<void> {
try {
if (IS_TAURI) {
const { invoke } = await import("@tauri-apps/api/core");
const path = await getTodayLogPath();
const line = `${JSON.stringify(entry)}\n`;
await invoke("append_to_file", { path, content: line });
} else {
const raw = localStorage.getItem(WEB_STORAGE_KEY);
const existing: LogEntry[] = raw ? safeParseArray(raw) : [];
existing.push(entry);
const trimmed =
existing.length > WEB_MAX_ENTRIES
? existing.slice(existing.length - WEB_MAX_ENTRIES)
: existing;
localStorage.setItem(WEB_STORAGE_KEY, JSON.stringify(trimmed));
}
} catch {
// Swallow — see top-of-file comment. We can't even log the failure
// because that would recurse here. The in-memory store still has
// the entry, so the user sees it for the current session.
}
}
/**
* Load persisted log entries from durable storage, filtered to the
* last `maxAgeDays` days. Used at app boot to seed the in-memory
* store with prior-session history.
*
* Web: one localStorage read + filter by `timestamp`.
*
* Tauri: lists files in `{appData}/logs/`, picks each `ytdescgen-*.jsonl`
* with a parsed date within the retention window, reads + parses
* JSONL line-by-line. Corrupt lines are skipped silently so a single
* bad write can't poison the whole tail.
*/
export async function loadRecentLogs(maxAgeDays: number): Promise<LogEntry[]> {
const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
try {
if (IS_TAURI) {
return await loadRecentTauriLogs(cutoff);
}
const raw = localStorage.getItem(WEB_STORAGE_KEY);
if (!raw) return [];
return safeParseArray(raw).filter((e) => Date.parse(e.timestamp) >= cutoff);
} catch {
return [];
}
}
async function loadRecentTauriLogs(cutoffMs: number): Promise<LogEntry[]> {
const { invoke } = await import("@tauri-apps/api/core");
const dirPath = await getLogDirPath();
const names = await invoke<string[]>("list_dir", { path: dirPath });
// Only consider files whose parsed date is within the window. Saves
// a full read of files we'd just throw away.
const candidates = names
.map((name) => ({ name, date: parseFileDate(name) }))
.filter(
(x): x is { name: string; date: Date } =>
x.date !== null && x.date.getTime() >= cutoffMs - 24 * 60 * 60 * 1000,
);
const entries: LogEntry[] = [];
for (const { name } of candidates) {
try {
const content: string = await invoke("read_from_file", {
path: `${dirPath}/${name}`,
});
for (const line of content.split("\n")) {
if (!line.trim()) continue;
try {
const parsed = JSON.parse(line) as LogEntry;
if (Date.parse(parsed.timestamp) >= cutoffMs) {
entries.push(parsed);
}
} catch {
// Corrupt line — skip without failing the whole sweep.
}
}
} catch {
// Couldn't read this file — skip it.
}
}
return entries;
}
/**
* Delete log files older than `maxAgeDays`. Runs at app boot after
* `loadRecentLogs` so a long-idle install doesn't keep months of old
* JSONL around. Web path is a no-op — the localStorage cap already
* handles eviction by FIFO.
*/
export async function pruneOldLogs(maxAgeDays: number): Promise<void> {
if (!IS_TAURI) return;
const cutoff = Date.now() - maxAgeDays * 24 * 60 * 60 * 1000;
try {
const { invoke } = await import("@tauri-apps/api/core");
const dirPath = await getLogDirPath();
const names = await invoke<string[]>("list_dir", { path: dirPath });
for (const name of names) {
const date = parseFileDate(name);
if (date && date.getTime() < cutoff) {
try {
await invoke("delete_file", { path: `${dirPath}/${name}` });
} catch {
// Permission denied / already gone → skip.
}
}
}
} catch {
// Directory listing failed — non-fatal.
}
}
/**
* Hard-clear ALL persisted logs (Tauri files + web localStorage).
* Used by the LogPage "Clear all persisted logs" action. The
* in-memory store is reset separately by the caller.
*/
export async function clearAllPersistedLogs(): Promise<void> {
try {
if (IS_TAURI) {
const { invoke } = await import("@tauri-apps/api/core");
const dirPath = await getLogDirPath();
const names = await invoke<string[]>("list_dir", { path: dirPath });
for (const name of names) {
if (name.startsWith(FILE_PREFIX) && name.endsWith(FILE_SUFFIX)) {
await invoke("delete_file", { path: `${dirPath}/${name}` });
}
}
} else {
localStorage.removeItem(WEB_STORAGE_KEY);
}
} catch {
// Best-effort; caller already cleared the in-memory store.
}
}
/** Parse a JSON array string safely; returns [] on any failure. */
function safeParseArray(raw: string): LogEntry[] {
try {
const parsed = JSON.parse(raw);
return Array.isArray(parsed) ? (parsed as LogEntry[]) : [];
} catch {
return [];
}
}
+82
View File
@@ -892,6 +892,88 @@ describe("buildDescription — v0.12 Playthrough Notes consolidation", () => {
expect(result).toContain("• Game version: Early Access");
});
it("renders structured endings[] as a comma-joined bullet (v0.16.0)", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({
endings: [
{ number: 1, name: "True End" },
{ number: 3, name: "Bad End" },
{ number: null, name: "Hidden" },
],
}),
t,
);
expect(result).toContain(
"• Endings shown: Ending 1: True End, Ending 3: Bad End, Hidden",
);
});
it("falls back to legacy endingsShown when endings[] is empty (v0.16.0)", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({
endings: [],
endingsShown: "Legacy freeform value",
}),
t,
);
expect(result).toContain("• Endings shown: Legacy freeform value");
});
it("prefers structured endings over legacy endingsShown when both are set", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({
endings: [{ number: 5, name: "Best End" }],
endingsShown: "Should be ignored",
}),
t,
);
expect(result).toContain("• Endings shown: Ending 5: Best End");
expect(result).not.toContain("Should be ignored");
});
it("slices endings[] to the requested video index when multi-video (v0.16.0)", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({
endings: [
{ number: 1, name: "A" },
{ number: 2, name: "B" },
{ number: 3, name: "C" },
{ number: 4, name: "D" },
],
endingVideoCount: 2,
endingVideoIndex: 2,
endingVideoRanges: [
{ from: 1, to: 2 },
{ from: 3, to: 4 },
],
}),
t,
);
// Video 2 covers endings 3 & 4 only.
expect(result).toContain("• Endings shown: Ending 3: C, Ending 4: D");
expect(result).not.toContain("Ending 1");
expect(result).not.toContain("Ending 2");
});
it("drops empty entries from the structured render", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({
endings: [
{ number: 1, name: "True End" },
{ number: null, name: "" }, // empty — should be dropped
{ number: 2, name: "Bad End" },
],
}),
t,
);
expect(result).toContain("• Endings shown: Ending 1: True End, Ending 2: Bad End");
});
it("uses the custom slot for languagePatch='official_other'", () => {
const t = createMockT("en");
const result = buildDescription(
+125
View File
@@ -0,0 +1,125 @@
import { describe, it, expect } from "vitest";
import {
formatEndingEntry,
sliceEndingsForVideo,
clampRange,
} from "@engine/endings-format";
import type { EndingEntry } from "@engine/types";
describe("formatEndingEntry", () => {
it("renders 'Ending {n}: {name}' when both are filled", () => {
expect(formatEndingEntry({ number: 3, name: "Best End" })).toBe(
"Ending 3: Best End",
);
});
it("renders 'Ending {n}' when only the number is filled", () => {
expect(formatEndingEntry({ number: 7, name: "" })).toBe("Ending 7");
});
it("renders just the name when only the name is filled", () => {
expect(formatEndingEntry({ number: null, name: "True Ending" })).toBe(
"True Ending",
);
});
it("returns null when neither is filled (drop signal)", () => {
expect(formatEndingEntry({ number: null, name: "" })).toBeNull();
expect(formatEndingEntry({ number: null, name: " " })).toBeNull();
});
it("trims whitespace from the name", () => {
expect(formatEndingEntry({ number: 2, name: " Bad End " })).toBe(
"Ending 2: Bad End",
);
});
it("rejects NaN / Infinity numbers as if missing", () => {
expect(formatEndingEntry({ number: NaN, name: "True End" })).toBe("True End");
expect(
formatEndingEntry({ number: Infinity, name: "X" }),
).toBe("X");
});
});
describe("sliceEndingsForVideo", () => {
const endings: EndingEntry[] = [
{ number: 1, name: "A" },
{ number: 2, name: "B" },
{ number: 3, name: "C" },
{ number: 4, name: "D" },
];
it("returns the whole array when videoCount <= 1", () => {
expect(sliceEndingsForVideo(endings, { endingVideoCount: 1 })).toEqual(endings);
expect(sliceEndingsForVideo(endings, { endingVideoCount: 0 })).toEqual(endings);
expect(sliceEndingsForVideo(endings, {})).toEqual(endings);
});
it("returns the whole array when videoIndex is missing or out of range", () => {
const input = {
endingVideoCount: 2,
endingVideoRanges: [
{ from: 1, to: 2 },
{ from: 3, to: 4 },
],
};
expect(sliceEndingsForVideo(endings, input)).toEqual(endings);
expect(
sliceEndingsForVideo(endings, { ...input, endingVideoIndex: 99 }),
).toEqual(endings);
});
it("returns the slice for video 1 when indexed", () => {
const sliced = sliceEndingsForVideo(endings, {
endingVideoCount: 2,
endingVideoIndex: 1,
endingVideoRanges: [
{ from: 1, to: 2 },
{ from: 3, to: 4 },
],
});
expect(sliced).toEqual([endings[0], endings[1]]);
});
it("returns the slice for video 2 when indexed", () => {
const sliced = sliceEndingsForVideo(endings, {
endingVideoCount: 2,
endingVideoIndex: 2,
endingVideoRanges: [
{ from: 1, to: 2 },
{ from: 3, to: 4 },
],
});
expect(sliced).toEqual([endings[2], endings[3]]);
});
it("returns empty when endings is empty", () => {
expect(sliceEndingsForVideo([], { endingVideoCount: 2, endingVideoIndex: 1 })).toEqual([]);
});
it("falls back to whole array when the matching range is missing", () => {
expect(
sliceEndingsForVideo(endings, {
endingVideoCount: 2,
endingVideoIndex: 1,
endingVideoRanges: [],
}),
).toEqual(endings);
});
});
describe("clampRange", () => {
it("clamps from below to 1 and to above to length", () => {
expect(clampRange({ from: 0, to: 100 }, 5)).toEqual({ from: 1, to: 5 });
});
it("ensures from <= to (clamps to single index when reversed)", () => {
// from=4, to=2 → clamp from to length=3 (4 > 3 → from=3), to becomes max(from, ...) = 3
expect(clampRange({ from: 4, to: 2 }, 3)).toEqual({ from: 3, to: 3 });
});
it("passes valid ranges through unchanged", () => {
expect(clampRange({ from: 2, to: 4 }, 5)).toEqual({ from: 2, to: 4 });
});
});
+52 -3
View File
@@ -11,7 +11,9 @@ const DICT: Record<string, Record<string, string>> = {
boss: "Boss {{n}}",
final_boss: "Final Boss",
intro: "Intro",
ending: "Ending",
// v0.16.0: ending keyword now interpolates {{n}} like chapter/part/boss
// so "Ending 1" / "Ending 2" survive the parse → render round-trip.
ending: "Ending {{n}}",
tutorial: "Tutorial",
credits: "Credits",
},
@@ -21,7 +23,7 @@ const DICT: Record<string, Record<string, string>> = {
boss: "Boss {{n}}",
final_boss: "Boss cuối",
intro: "Mở đầu",
ending: "Kết thúc",
ending: "Kết thúc {{n}}",
tutorial: "Hướng dẫn",
credits: "Credits",
},
@@ -31,7 +33,7 @@ const DICT: Record<string, Record<string, string>> = {
boss: "ボス{{n}}",
final_boss: "ラスボス",
intro: "オープニング",
ending: "エンディング",
ending: "エンディング{{n}}",
tutorial: "チュートリアル",
credits: "クレジット",
},
@@ -103,6 +105,35 @@ describe("parseTimeline", () => {
const entries = parseTimeline("\n0:00 Intro\n\n5:00 Chapter 1\n");
expect(entries).toHaveLength(2);
});
// v0.16.0: ending keyword now captures an optional ordinal so
// structured `endings[]` rows can be matched to timeline markers.
it("captures the ending ordinal when present", () => {
const entries = parseTimeline("1:00:00 Ending 1\n2:00:00 Ending 3");
expect(entries[0].keyword).toBe("ending");
expect(entries[0].number).toBe(1);
expect(entries[1].keyword).toBe("ending");
expect(entries[1].number).toBe(3);
});
it("recognises a bare 'Ending' line as ending without a number", () => {
const entries = parseTimeline("1:00:00 Ending");
expect(entries[0].keyword).toBe("ending");
expect(entries[0].number).toBeUndefined();
});
it("captures the trailing label after 'Ending N: ...' as `rest`", () => {
const entries = parseTimeline("1:00:00 Ending 3: Best End");
expect(entries[0].keyword).toBe("ending");
expect(entries[0].number).toBe(3);
expect(entries[0].rest).toBe(": Best End");
});
it("recognises Vietnamese 'Kết thúc 2'", () => {
const entries = parseTimeline("1:30:00 Kết thúc 2");
expect(entries[0].keyword).toBe("ending");
expect(entries[0].number).toBe(2);
});
});
describe("renderTimeline", () => {
@@ -129,4 +160,22 @@ describe("renderTimeline", () => {
const out = renderTimeline(entries, "en", makeT("en"));
expect(out).toBe("0:00 Intro\n5:30 Chapter 1\n10:00 Boss 2");
});
// v0.16.0: when a numbered keyword has no captured ordinal (rare —
// e.g. a "boss" line without an N), the renderer used to emit a
// trailing space ("Boss "). Now it collapses internal/trailing
// whitespace so output stays clean.
it("collapses trailing space when a numbered keyword has no ordinal", () => {
const entries = parseTimeline("0:00 Boss");
const out = renderTimeline(entries, "en", makeT("en"));
expect(out).toBe("0:00 Boss");
});
it("renders 'Ending N' bilingually when the ordinal is present", () => {
const entries = parseTimeline("1:00:00 Ending 2");
const enOut = renderTimeline(entries, "en", makeT("en"));
expect(enOut).toBe("1:00:00 Ending 2");
const viOut = renderTimeline(entries, "vi", makeT("vi"));
expect(viOut).toBe("1:00:00 Kết thúc 2");
});
});
+172
View File
@@ -68,6 +68,178 @@ describe("buildTitle", () => {
expect(result).toBe("Elden Ring — Ending — Gameplay No Commentary");
});
// v0.17.0: when the creator fills structured endings, the title's
// video-type segment swaps from the static "Ending" to a label
// built off the entries themselves.
it("renders a single structured ending with both number + name (v0.17.0)", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({
videoType: "ending",
endings: [{ number: 3, name: "Best End" }],
}),
t,
);
expect(result).toBe(
"Elden Ring — Ending 3: Best End — Gameplay No Commentary",
);
});
it("renders a single structured ending with number only (v0.17.0)", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({
videoType: "ending",
endings: [{ number: 7, name: "" }],
}),
t,
);
expect(result).toBe("Elden Ring — Ending 7 — Gameplay No Commentary");
});
it("renders a single structured ending with name only (v0.17.0)", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({
videoType: "ending",
endings: [{ number: null, name: "True End" }],
}),
t,
);
expect(result).toBe("Elden Ring — True End — Gameplay No Commentary");
});
it("collapses multi-ending to comma-joined names when all named (v0.17.0)", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({
videoType: "ending",
endings: [
{ number: 1, name: "True End" },
{ number: 2, name: "Bad End" },
{ number: 3, name: "Hidden" },
],
}),
t,
);
expect(result).toBe(
"Elden Ring — True End, Bad End, Hidden — Gameplay No Commentary",
);
});
it("renders contiguous numbered endings as a range (v0.17.0)", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({
videoType: "ending",
// Numbers only, contiguous.
endings: [
{ number: 1, name: "" },
{ number: 2, name: "" },
{ number: 3, name: "" },
],
}),
t,
);
expect(result).toBe(
"Elden Ring — Endings 1–3 — Gameplay No Commentary",
);
});
it("handles out-of-order numbered endings by sorting for the range (v0.17.0)", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({
videoType: "ending",
endings: [
{ number: 3, name: "" },
{ number: 1, name: "" },
{ number: 2, name: "" },
],
}),
t,
);
expect(result).toBe("Elden Ring — Endings 1–3 — Gameplay No Commentary");
});
it("falls back to count form when non-contiguous numbers (v0.17.0)", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({
videoType: "ending",
endings: [
{ number: 1, name: "" },
{ number: 4, name: "" }, // gap → non-contiguous
],
}),
t,
);
expect(result).toBe("Elden Ring — 2 Endings — Gameplay No Commentary");
});
it("respects endingVideoIndex when slicing for per-video title (v0.17.0)", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({
videoType: "ending",
endings: [
{ number: 1, name: "True" },
{ number: 2, name: "Bad" },
{ number: 3, name: "Best" },
{ number: 4, name: "Hidden" },
],
endingVideoCount: 2,
endingVideoIndex: 2,
endingVideoRanges: [
{ from: 1, to: 2 },
{ from: 3, to: 4 },
],
}),
t,
);
// Video 2 covers endings 3 & 4 — joined names.
expect(result).toBe("Elden Ring — Best, Hidden — Gameplay No Commentary");
});
it("falls back to the legacy 'Ending' label when no usable entries (v0.17.0)", () => {
const t = createMockT("en");
// All entries empty → drop signal → fall back.
const result = buildTitle(
makeInput({
videoType: "ending",
endings: [{ number: null, name: "" }],
}),
t,
);
expect(result).toBe("Elden Ring — Ending — Gameplay No Commentary");
});
it("falls back when endings array is undefined (legacy creator)", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({ videoType: "ending", endings: undefined }),
t,
);
expect(result).toBe("Elden Ring — Ending — Gameplay No Commentary");
});
it("renders Vietnamese ending range with localised label (v0.17.0)", () => {
const t = createMockT("vi");
const result = buildTitle(
makeInput({
videoType: "ending",
language: "vi",
gameName: "Elden Ring",
endings: [
{ number: 1, name: "" },
{ number: 2, name: "" },
],
}),
t,
);
expect(result).toContain("Kết thúc 1–2");
});
it("generates speedrun title", () => {
const t = createMockT("en");
const result = buildTitle(makeInput({ videoType: "speedrun" }), t);
+147
View File
@@ -0,0 +1,147 @@
import { describe, it, expect } from "vitest";
import {
liftLegacyEndingString,
computeContiguousRanges,
migrateEditorState,
} from "@store/editor-store";
describe("liftLegacyEndingString", () => {
it("returns an empty array for empty / whitespace input", () => {
expect(liftLegacyEndingString("")).toEqual([]);
expect(liftLegacyEndingString(" ")).toEqual([]);
});
it("parses 'Ending N: Name' into a structured entry", () => {
expect(liftLegacyEndingString("Ending 3: Best End")).toEqual([
{ number: 3, name: "Best End" },
]);
});
it("parses 'Ending N' (number only) into a structured entry", () => {
expect(liftLegacyEndingString("Ending 7")).toEqual([
{ number: 7, name: "" },
]);
});
it("recognises localised 'Kết thúc N' (Vietnamese)", () => {
expect(liftLegacyEndingString("Kết thúc 2: Hậu trung dung")).toEqual([
{ number: 2, name: "Hậu trung dung" },
]);
});
it("recognises Japanese 'エンディング3'", () => {
expect(liftLegacyEndingString("エンディング3: 真エンド")).toEqual([
{ number: 3, name: "真エンド" },
]);
});
it("falls through to a name-only row for unparseable input", () => {
expect(liftLegacyEndingString("True ending only")).toEqual([
{ number: null, name: "True ending only" },
]);
expect(liftLegacyEndingString("1 of 3")).toEqual([
{ number: null, name: "1 of 3" },
]);
});
});
describe("computeContiguousRanges", () => {
it("returns empty when either input is non-positive", () => {
expect(computeContiguousRanges(0, 2)).toEqual([]);
expect(computeContiguousRanges(5, 0)).toEqual([]);
});
it("returns a single full-range row for videoCount = 1", () => {
expect(computeContiguousRanges(5, 1)).toEqual([{ from: 1, to: 5 }]);
});
it("splits 6 endings into 2 even videos", () => {
expect(computeContiguousRanges(6, 2)).toEqual([
{ from: 1, to: 3 },
{ from: 4, to: 6 },
]);
});
it("spills the remainder into the LAST video (climactic-final convention)", () => {
// 7 / 3 = 2 remainder 1; last video gets size 3.
expect(computeContiguousRanges(7, 3)).toEqual([
{ from: 1, to: 2 },
{ from: 3, to: 4 },
{ from: 5, to: 7 },
]);
});
it("clamps videoCount to endings.length when over-asked", () => {
// Asking for more videos than endings → only `endings.length` rows.
expect(computeContiguousRanges(3, 5)).toEqual([
{ from: 1, to: 1 },
{ from: 2, to: 2 },
{ from: 3, to: 3 },
]);
});
});
describe("migrateEditorState v11 → v12 (endings)", () => {
it("lifts a legacy endingsShown freeform into a single-row endings entry", () => {
const persisted = { endingsShown: "Ending 5: Bad End" };
const result = migrateEditorState(persisted, 11);
expect(result.endings).toEqual([{ number: 5, name: "Bad End" }]);
expect(result.endingVideoCount).toBe(1);
expect(result.endingVideoRanges).toEqual([{ from: 1, to: 1 }]);
});
it("leaves endings empty when legacy string is empty", () => {
const result = migrateEditorState({ endingsShown: "" }, 11);
expect(result.endings).toEqual([]);
expect(result.endingVideoCount).toBe(1);
expect(result.endingVideoRanges).toEqual([]);
});
it("preserves an already-structured endings array on later migration runs", () => {
const persisted = {
endingsShown: "irrelevant — should not be re-lifted",
endings: [
{ number: 1, name: "A" },
{ number: 2, name: "B" },
],
endingVideoCount: 2,
endingVideoRanges: [
{ from: 1, to: 1 },
{ from: 2, to: 2 },
],
};
const result = migrateEditorState(persisted, 11);
expect(result.endings).toHaveLength(2);
expect(result.endings[0]).toEqual({ number: 1, name: "A" });
});
it("clamps endingVideoCount > endings.length down on rehydrate", () => {
const persisted = {
endings: [{ number: 1, name: "A" }],
endingVideoCount: 5,
};
const result = migrateEditorState(persisted, 11);
// Single ending → videoCount cannot exceed 1.
expect(result.endingVideoCount).toBe(1);
expect(result.endingVideoRanges).toEqual([{ from: 1, to: 1 }]);
});
it("re-derives ranges when count doesn't match", () => {
const persisted = {
endings: [
{ number: 1, name: "A" },
{ number: 2, name: "B" },
{ number: 3, name: "C" },
],
endingVideoCount: 2,
// Bogus 1-row ranges array — should be recomputed because length
// !== endingVideoCount.
endingVideoRanges: [{ from: 1, to: 3 }],
};
const result = migrateEditorState(persisted, 11);
expect(result.endingVideoRanges).toEqual([
{ from: 1, to: 1 },
{ from: 2, to: 3 },
]);
});
});
+13
View File
@@ -97,11 +97,24 @@ describe("healSettings", () => {
genrePlaylists: { horror: "https://www.youtube.com/playlist?list=abc" },
editorAccordionState: { gameInfo: false, videoSettings: true },
sidebarCollapsed: true,
logRetentionDays: 14,
};
const healed = healSettings(complete);
expect(healed).toEqual(complete);
});
it("back-fills logRetentionDays to 7 when absent (pre-v0.17 payload)", () => {
const healed = healSettings({ theme: "dark" as const });
expect(healed.logRetentionDays).toBe(7);
});
it("clamps logRetentionDays to [1, 90]", () => {
expect(healSettings({ logRetentionDays: 0 } as unknown).logRetentionDays).toBe(1);
expect(healSettings({ logRetentionDays: -5 } as unknown).logRetentionDays).toBe(1);
expect(healSettings({ logRetentionDays: 1000 } as unknown).logRetentionDays).toBe(90);
expect(healSettings({ logRetentionDays: 30.7 } as unknown).logRetentionDays).toBe(30);
});
it("back-fills showSponsorCredit default when the key is absent (v3 → v4 payload)", () => {
// Simulates a settings file written in v0.6 phase 1 where the new
// sponsor toggle hadn't been introduced yet.
+166
View File
@@ -0,0 +1,166 @@
import { describe, it, expect } from "vitest";
import {
APP_MARKER,
SCHEMA_VERSIONS,
detectShape,
resolveForType,
wrapEnvelope,
} from "@utils/file-schema";
describe("wrapEnvelope", () => {
it("produces an envelope with the marker, type, and per-type schema version", () => {
const env = wrapEnvelope("profile", [{ id: "p1", name: "Test" }]);
expect(env._app).toBe(APP_MARKER);
expect(env._type).toBe("profile");
expect(env._schemaVersion).toBe(SCHEMA_VERSIONS.profile);
expect(typeof env._exportedAt).toBe("string");
expect(env.data).toEqual([{ id: "p1", name: "Test" }]);
});
it("round-trips data unchanged", () => {
const data = { foo: 1, bar: [2, 3] };
expect(wrapEnvelope("settings", data).data).toBe(data);
});
});
describe("detectShape", () => {
it("classifies a well-formed envelope by its _type", () => {
const env = wrapEnvelope("template", [{ id: "t1", snapshot: {} }]);
const shape = detectShape(env);
expect(shape.kind).toBe("envelope");
if (shape.kind !== "envelope") return;
expect(shape.type).toBe("template");
expect(shape.schemaVersion).toBe(SCHEMA_VERSIONS.template);
});
it("rejects an envelope with a foreign _app marker", () => {
const shape = detectShape({
_app: "some-other-tool",
_type: "profile",
_schemaVersion: 1,
data: [],
});
expect(shape.kind).not.toBe("envelope");
});
it("guesses profile from an array with channelName/social/rig sample", () => {
const shape = detectShape([
{ id: "p1", channelName: "Skullmute", social: {}, rig: {} },
]);
expect(shape.kind).toBe("legacy");
if (shape.kind !== "legacy") return;
expect(shape.guessedType).toBe("profile");
});
it("guesses template by snapshot field on the array sample", () => {
const shape = detectShape([{ id: "t1", name: "X", snapshot: { gameName: "G" } }]);
expect(shape.kind).toBe("legacy");
if (shape.kind !== "legacy") return;
expect(shape.guessedType).toBe("template");
});
it("guesses preset by gameName + storeLinks combo", () => {
const shape = detectShape([
{ id: "g1", gameName: "Doom", storeLinks: { steam: "https://example" } },
]);
expect(shape.kind).toBe("legacy");
if (shape.kind !== "legacy") return;
expect(shape.guessedType).toBe("preset");
});
it("guesses settings when the object has the multi-store dump key", () => {
const shape = detectShape({ "ytdescgen-settings": { theme: "dark" } });
expect(shape.kind).toBe("legacy");
if (shape.kind !== "legacy") return;
expect(shape.guessedType).toBe("settings");
});
it("returns unknown for null / primitive / unrecognised shapes", () => {
expect(detectShape(null).kind).toBe("unknown");
expect(detectShape("foo").kind).toBe("unknown");
expect(detectShape(42).kind).toBe("unknown");
expect(detectShape([{ weird: "field" }]).kind).toBe("legacy");
// Empty array → legacy with guessedType null (no sample to inspect).
const empty = detectShape([]);
if (empty.kind === "legacy") expect(empty.guessedType).toBeNull();
});
});
describe("resolveForType", () => {
it("accepts an envelope whose type matches the expected type", () => {
const env = wrapEnvelope("profile", [{ id: "p1" }]);
const shape = detectShape(env);
const result = resolveForType(shape, "profile");
expect(result.ok).toBe(true);
if (!result.ok) return;
expect(result.data).toEqual([{ id: "p1" }]);
expect(result.sourceVersion).toBe(SCHEMA_VERSIONS.profile);
});
it("returns wrong-type when the envelope type does not match", () => {
const env = wrapEnvelope("template", [{ id: "t1", snapshot: {} }]);
const shape = detectShape(env);
const result = resolveForType(shape, "profile");
expect(result.ok).toBe(false);
if (result.ok) return;
if (result.reason.kind !== "wrong-type") throw new Error("expected wrong-type");
expect(result.reason.actual).toBe("template");
});
it("returns newer-schema when the envelope's schema version is too high", () => {
const env = {
_app: APP_MARKER,
_type: "profile" as const,
_schemaVersion: 999,
_exportedAt: "2099-01-01",
data: [],
};
const shape = detectShape(env);
const result = resolveForType(shape, "profile");
expect(result.ok).toBe(false);
if (result.ok) return;
if (result.reason.kind !== "newer-schema") throw new Error("expected newer-schema");
expect(result.reason.actual).toBe(999);
expect(result.reason.supported).toBe(SCHEMA_VERSIONS.profile);
});
it("accepts legacy data with a guess matching the expected type", () => {
const shape = detectShape([{ id: "p1", channelName: "X", social: {}, rig: {} }]);
const result = resolveForType(shape, "profile");
expect(result.ok).toBe(true);
});
it("accepts legacy data with no guess (trusts the user's tab choice)", () => {
const shape = detectShape([]); // empty array → guessedType null
const result = resolveForType(shape, "preset");
expect(result.ok).toBe(true);
});
it("rejects legacy data whose guess contradicts the expected type", () => {
const shape = detectShape([{ id: "t1", snapshot: {} }]); // looks like a template
const result = resolveForType(shape, "profile");
expect(result.ok).toBe(false);
if (result.ok) return;
if (result.reason.kind !== "wrong-type") throw new Error("expected wrong-type");
expect(result.reason.actual).toBe("template");
});
it("rejects unknown-shape payloads", () => {
const shape = detectShape(42);
const result = resolveForType(shape, "settings");
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.reason.kind).toBe("unknown-shape");
});
});
describe("envelope round-trip", () => {
it("survives JSON.stringify / parse and is recognised by detectShape", () => {
const env = wrapEnvelope("preset", [{ id: "g1", gameName: "Doom" }]);
const reparsed = JSON.parse(JSON.stringify(env));
const shape = detectShape(reparsed);
expect(shape.kind).toBe("envelope");
if (shape.kind !== "envelope") return;
expect(shape.type).toBe("preset");
});
});