Compare commits

...
32 Commits
Author SHA1 Message Date
poli0981 c9facc59ec Merge pull request #142 from poli0981/feat/v0.35.0-guardrails
feat: v0.35.0 — guardrails
2026-08-17 11:16:50 +07:00
poli0981andClaude Opus 5 b8f245dee4 chore(release): v0.35.0 — guardrails
Splits SettingsPage (544 → 347 lines), extracting the import/export IO and the
42-input Genre Playlists section — the two pieces with no reason to sit inside
a page component.

Bumps all six version manifests and adds the CHANGELOG entry. `npm run
check:version`, added earlier in this cycle, confirms they agree.

Deliberately NOT split: `description-builder.ts` (974) and `editor-store.ts`
(998). Both are large, but this release changes almost nothing in either, and
carving up a 20-section render pipeline or a migration ladder is a test-heavy
refactor with real regression surface and no connection to guardrails.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 11:15:08 +07:00
poli0981andClaude Opus 5 8c32435d8a fix(strict-mode): derive the gate from state, not from mounted inputs
The first cut had each input register its own error into a shared store as it
rendered, clearing on unmount. That read as reasonable and was quietly useless:
the fields live on the Editor page, the gates live on Batch / Social / Output /
Profiles, and unmounting the Editor took every issue with it. Verified in the
browser — typing a malformed Steam URL, navigating to Batch, and finding
Generate perfectly enabled with no banner.

Replaced with two sources that between them cover what the setting promises:

- `collectEditorIssues` (pure, `@utils/editor-issues`) walks the editor STATE
  against the same validators and the same `PLATFORMS` / `SOCIAL_FIELDS` config
  the inputs use — one rule set, two consumers, no duplicated regexes. This is
  what catches data that never passed through an input at all: an imported
  profile, a preset shared by someone else, a draft persisted before a
  validator got stricter. Since `ValidatedInput` refuses to commit invalid
  text, imports are in fact the main way bad data reaches the store.
- `pending-invalid-store` holds text that is invalid and therefore *not*
  committed. Without it, a field showing a red error would still be invisible
  to every gate, because the store behind it holds the last good value. It has
  no unmount cleanup — that was the original bug — so an entry lives until the
  field is valid again.

Both are filtered through one relevance check, so a field nobody can see never
blocks: `adEmail` / `gameKeyEmail` while the split toggle is off, `zaloGroupLink`
outside Vietnamese output. Without that, Strict Mode could become an
unresolvable dead end — blocked on a field with no visible input to fix it.

Dropping the registry also removes the render-loop hazard it carried: the
effect published on every render of every input, guarded only by a deep-equal
bail-out.

Verified end to end in the browser: a bad Steam URL now disables Generate on
Batch and names the field in the banner; fixing it re-enables; and a Ko-fi link
on a vanity domain shows its inline prefix warning without blocking anything.

Tests 687 → 696.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 11:11:20 +07:00
poli0981andClaude Opus 5 1f9621b5cd feat: enforce the field caps everywhere they can be reached
Completes the field-limit work: `maxLength` is now wired at 53 call sites
across every editor form, the Settings genre-playlist inputs, the save dialogs
and the Playlist notes — grouped by what the field holds rather than named one
by one, so a new input inherits a sensible cap instead of inventing a number.

Two gaps that a `maxLength` attribute alone cannot close:

- **Imports bypass it entirely.** `maxLength` constrains typing and pasting;
  a profile, preset or template — including one saved before the caps existed
  — never passes through an input at all. `normalizeEditorPatch` now clamps on
  the way in, covering the flat fields plus the nested `social` and
  `storeLinks` URL maps. Without this the cap was decorative for exactly the
  path most likely to violate it.
- **Strict Mode could not see any field.** The registry landed in the previous
  commit, but nothing registered with it. Every `ValidatedInput` now carries a
  stable `fieldId` (composed for loop-rendered fields: `editor.social.twitch`,
  `settings.genrePlaylists.horror`), so the banner can name the offending
  input rather than saying "something is wrong".

Also fixed: `liveUrl` was a plain `Input` with no validation at all — the only
URL field in the app that would accept anything and pass it straight into the
description.

Tests 681 → 687.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 11:00:51 +07:00
poli0981andClaude Opus 5 f69941aae3 feat: block copying over-limit output, and add an opt-in Strict Mode
**Over-limit output could always be copied.** `renderAll` has returned
`warnings: CharLimitWarning[]` since v0.5 and nothing in the UI ever read it.
Three ad-hoc checks had grown up in the components instead, each with a
different blind spot:

  - `CopyButton` turned red and stayed clickable.
  - `CopyAllBar` checked title and description but not tags — and bailed out of
    every check when its `extraText` prop was set. Exactly one caller set that
    prop: OutputPage, whenever more than one language was selected. So picking
    a second language silently disabled limit checking on the main copy path.
  - BatchPage passed no limits at all, so a 6000-character description copied
    without a word.

`src/engine/limits.ts` is now the single derivation, and the requested rule is
all-or-nothing per output: if any one of title / description / tags is over,
none of them can be copied. Copying two fields and silently leaving the third
is how a half-populated description gets published.

Scoping decisions worth stating:
  - Batch blocks the offending part's own buttons plus Copy All Batch, but not
    the other 99 parts. Freezing an entire batch because part 7 is three
    characters long would be useless.
  - On Output, per-field buttons use the ACTIVE TAB's status while Copy All
    uses the merge — an over-long Japanese title must not disable the English
    copy button the user is looking at, but it must block the blob containing it.
  - `OutputExtras` (thumbnail text, pinned comment) and Playlist stay ungated:
    different YouTube surfaces with different limits, so reusing YT_LIMITS
    there would be wrong.

Batch also gained the description and tag counters it never had — a row could
be 1500 characters over with nothing on screen saying so. Social bulk Copy All
now respects each platform's own cap (TikTok 4000, Reels 2200).

**Strict Mode** (Settings → Guardrails, default OFF). Blocks Generate, Copy and
Export while any field carries a hard error. This needed something that did not
exist: an app-wide view of which fields are invalid. Every error lived in the
private `useState` of the input that produced it, so no caller could ask the
question. `src/store/validation-store.ts` is that registry — ephemeral, not
persisted, since an error rehydrated from disk would describe text the user can
no longer see.

Errors only. `validateUrlWithPrefix` returns a soft warning for a link that
works but doesn't match a platform's usual prefix; blocking on that would
strand anyone on a vanity domain or a regional mirror.

Two exemptions: the log .txt/.json export stays ungated (a debugging export
must not be held hostage by an unrelated bad URL), and the Editor gets the
banner but no gate — it is where you go to FIX the fields, so disabling
anything there would be backwards. Unmounted fields deregister, so a hidden
`adEmail` or a swapped-out video-type field can never block.

**Settings sections are collapsible.** Genre Playlists renders one input per
genre — 42 of them — and was the tallest block on the page. It now ships
collapsed with a filled-count badge. The other eight sections became accordions
too (defaulting OPEN) because a page mixing bare headings with chevrons reads
as broken, and unknown ids default open so a section added later cannot vanish
for an existing user.

Settings persist v11 → v12 (`strictMode`, `settingsAccordionState`), with
`SCHEMA_VERSIONS.settings` bumped in lockstep. Both are coerced, not just
back-filled: a hand-edited `"strictMode": "yes"` is truthy in JS, and silently
switching a seatbelt on is the opposite of an opt-in. Also corrected
`SCHEMA_VERSIONS.profile` 1 → 2, left behind when profile-store bumped in v0.34.0.

16 UI keys across all six locales (validator 999 ui / 563 templates).
Tests 665 → 681.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 10:56:05 +07:00
poli0981andClaude Opus 5 6e0b02a050 feat: ask where to save exports, and cap what can be typed into a field
Two independent guardrails; both were missing outright rather than broken.

**Exports never asked where to save.** There were two writers that disagreed:
`saveFile` branched correctly per platform but had exactly one caller (the log
.txt export), while every JSON export went through a private blob-download
helper with no platform branch at all. So "Export" on Settings, Profiles,
Presets, Templates, Social and the log JSON dumped straight into Downloads —
even on desktop, where a native Save As dialog had been available and
capability-approved the whole time.

Now one writer, `saveTextFile`, with three branches:
  1. Tauri desktop — native Save As, then the existing `save_to_file` command.
     No Rust or capability change was needed; the permissions were already there.
  2. Web with the File System Access API — a real picker. It must be the FIRST
     await in a click handler because it needs transient user activation, so
     every call site now builds its payload synchronously first. A
     `NotAllowedError` from a spent activation degrades to (3) instead of
     losing the file.
  3. Everything else (Android WebView, Firefox, Safari) — blob download.

`exportTypedToJsonFile` is now async and returns the outcome, so **cancelling
is silent**: dismissing a save dialog is a decision, not a failure, and
toasting "Export failed" at someone who pressed Escape is how people learn to
ignore toasts. The shared `useFileExport` hook holds that rule in one place and
retires the hardcoded English "Exported!" / "Export failed" strings.

Settings Import/Export is no longer desktop-only. That gate was a leftover from
when export meant dumping the on-disk settings.json; import has always been a
plain <input type="file">, and export now offers a real dialog on the web too.

**No field had a length cap** — `maxLength` appeared nowhere in the codebase, so
a pasted novel in the game-name field produced a title YouTube would reject.
`FIELD_LIMITS` groups caps by what a field holds (URL 200, email 320, short
name 100, label 300, long text 2000, timestamps = the 5000 description budget)
so a new input inherits a sensible limit instead of inventing one. `clampField`
covers the paths `maxLength` cannot: profile/preset/template import and
paste-autofill.

**Emails hard-stop at three per field.** The cap is enforced on the increase,
not the absolute count, which buys two things: a field that already holds four
(legacy profile, hand-edited import) stays editable down to three instead of
freezing, and a half-typed `a@b.com,c@` is never punished. Per field rather
than across the split — each of the three renders its own labelled line, so
filling the advertising address must not retroactively invalidate the contact.

**`ValidatedInput` no longer destroys good input.** On an invalid value it used
to call `onChange("")`, wiping the stored value while the box still showed the
user's text — so backspacing one character out of a complete URL silently
emptied the field, and autosave then persisted the empty value with no signal.
It now simply doesn't commit, leaving the last valid value in place; bad input
is kept out just as effectively. Also fixed while here: `displayValue` never
re-synced when the prop changed, so applying a profile or preset left the box
showing stale text that disagreed with the store.

i18n keys for the new strings land in the following commit.

Tests 629 → 655.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 10:41:33 +07:00
poli0981andClaude Opus 5 6b6613cca0 fix(batch): render split contact emails in Batch, and make the drift impossible
Reported: with Settings → "Split contact email by purpose" ON, the Batch tab
showed only the old single "📧 Business inquiries:" line, while the Output tab
correctly showed the grouped 📧 BUSINESS / CONTACT block with all three
addresses.

Root cause is not in the engine. `renderAll` had three call sites, each
hand-copying the same twelve settings fields into an options object, and
BatchPage's copy was missing two: `splitContactEmail` and `showThirdPartyAds`
(plus `tEn`). An absent flag defaults to `false` inside `buildDescription`, so
the else-branch emitted the legacy single line — silently, with no type error
and no failing test, because the engine tests call `buildDescription` directly
with an explicit options object and never exercise the wiring.

Rather than add a third copy of the list, the mapping now lives in one place:

- `SettingsRenderOptions` (settings-derived) is split from
  `RenderOptionOverrides` (per-caller: `tEn`, `bilingualContentBlocks`), and
  `RenderOptions` is their intersection. Same shape as before for `renderAll`.
- New `useRenderOptions` / `buildRenderOptions` produce the settings half; all
  three call sites consume it and layer only their own overrides.

Two guards, both verified to fail when the original bug is reintroduced:

- Compile-time: `buildRenderOptions` builds a `Required<SettingsRenderOptions>`,
  so dropping a key is `TS2741: Property 'splitContactEmail' is missing`.
- Runtime: `tests/hooks/render-options-parity.test.ts` diffs the produced keys
  against `SETTINGS_DERIVED_RENDER_KEYS` in both directions and names the
  offending key in the failure message.

Also fixed by the same change, since Batch was dropping it too:
`showThirdPartyAds` — the SPONSORS & PARTNERS block now renders in Batch.

Batch deliberately still passes no `tEn`: its rows are one language each, so
the bilingual `EN · LOCAL` treatment would duplicate every content-warning line.

Note for the changelog: Batch descriptions get *longer* for anyone who had
either toggle on, because those blocks were being silently dropped.

Tests 621 → 629.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 10:41:33 +07:00
poli0981 31fa18627e Merge pull request #135 from poli0981/chore/security-and-format
ci: enforce existing checks, patch advisories, backfill CHANGELOG
2026-08-17 10:41:30 +07:00
poli0981andClaude Opus 5 7b0189a1f9 test: assert the (free) suffix by adjacency instead of a URL substring
The first attempt at this alert swapped the bare host substring for the full
URL, which CodeQL still flags — `js/incomplete-url-substring-sanitization`
fires on `.includes()` against any URL-shaped value, not on the needle's
length, so the change produced two alerts where there had been one.

A store line renders as `🎮 {label}{suffix}: {url}`, so asserting
`(free): <url>` against the whole description tests the actual adjacency the
case is about, drops `.includes()` entirely, and no longer needs to locate a
line by host at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 10:33:57 +07:00
poli0981andClaude Opus 5 d2100d2d40 ci: enforce the checks the repo already had, and close the CHANGELOG gap
CI ran typecheck/lint/locales/test/build. Everything else the repo owned was
configured but never executed — `knip` was installed and configured yet ran
nowhere, Prettier had a config and no gate, and the six version fields the
release ritual bumps by hand had nothing watching them. This wires all of it
into the pipeline.

Correctness gaps this immediately caught:

- `tsconfig.json` covers only `src`, so tests/ and scripts/ were NEVER
  type-checked. Adding `tsconfig.check.json` (+ `typecheck:all`) surfaced 53
  errors, including three fields silently missing from the editor→engine
  parity fixture: `videoStyleEra` (v0.22.0), `adEmail` + `gameKeyEmail`
  (v0.34.0), and the four `endings*` fields (v0.16.0/v0.17.1). The fixture is
  the guard against exactly that class of drift, and it had drifted itself.
- `vitest.config.ts` `include` matched only `*.test.ts`, so any `.test.tsx`
  would have been collected by nobody and "passed" silently. Now `{ts,tsx}`.

New gates in ci.yml: `typecheck:all`, `format:check`, `knip`, `check:version`,
and an advisory `npm audit --audit-level=high` (advisory so a fresh transitive
advisory cannot redden every unrelated PR before Dependabot opens its fix).
Plus least-privilege `permissions: contents: read` — which also clears the
`actions/missing-workflow-permissions` code-scanning alert — and a
concurrency group that cancels superseded runs everywhere except `main`.

New scripts:

- `scripts/check-version-sync.ts` — asserts all SIX version fields agree
  (package.json, package-lock root AND packages[""], tauri.conf.json,
  Cargo.toml, Cargo.lock self-entry). Nothing else notices a missed one, and a
  stale tauri.conf.json ships an installer that disagrees with its tag.
- `scripts/generate-locale-template.ts` — `npm run generate:locale` has been
  advertised in package.json and docs/I18N.md step 1 since v0.1, but the file
  was never committed, so the documented first step of adding a language
  failed outright. Blocks the planned pt-BR + id work.

Dead code removed: the Rust `ensure_dir` command and its two scoped `opener:`
capabilities. Its documented caller, `openSettingsFolder()`, no longer exists
in `src/` — `opener:default` (all `openExternal` needs) is untouched. Also
`@tauri-apps/plugin-opener` left knip's ignore list now that it is genuinely
imported, and `DroppedReasonId` went from unused export to typing
PlaylistPage's dropped-reason state.

Security: the `js/incomplete-url-substring-sanitization` alert in
description-builder.test.ts was a real (if low-stakes) weak assertion —
`includes("itch.io")` also matches `https://itch.io.example.com/`, so the
test could pass on the wrong line. Now matches the full URL.

CHANGELOG: v0.31.0, v0.32.0 and v0.32.1 shipped as tagged releases but were
never logged, leaving the file jumping v0.33.0 → v0.30.0. Reconstructed from
the release commits in the file's existing house style.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 10:28:00 +07:00
poli0981andClaude Opus 5 48d5bb035c style: apply Prettier across src, tests and scripts
`prettier --check` failed on 81 files: the repo had a Prettier config and a
`format` script from day one, but nothing ever enforced them, so formatting
drifted file by file. This is that pass, isolated in its own commit so the
CI gate added alongside it lands on an already-clean tree and no future
feature diff has to carry whitespace noise.

Formatting only — no behavioural change. Verified by `npm run test:run`
(621 passing, unchanged) and `npm run typecheck`.

Markdown, `_schema.json` and the workflow YAML are deliberately excluded:
Prettier reflows prose and expands the locale schema's compact arrays by
~1600 lines, which makes both harder to review for zero benefit. The
`format` script is scoped to `{src,tests,scripts}/**/*.{ts,tsx,css}` to
match.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 10:27:24 +07:00
poli0981andClaude Opus 5 86c5dec087 chore(deps): patch nanoid DoS advisory via npm audit fix
`nanoid` <3.3.18 (GHSA-2v37-7h3g-55p8 — custom generators can loop
indefinitely when size is zero) reached the tree transitively through
postcss. `npm audit` now reports 0 vulnerabilities; the brace-expansion
advisories were cleared separately by #134.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-17 10:16:56 +07:00
poli0981 216eabcec8 Merge pull request #134 from poli0981/dependabot/npm_and_yarn/brace-expansion-1.1.18
chore(deps-dev): bump brace-expansion from 1.1.13 to 1.1.18
2026-08-17 10:16:32 +07:00
poli0981 69f6e32ebf Merge pull request #126 from poli0981/dependabot/cargo/src-tauri/serde_with-3.21.0 2026-08-13 09:45:25 +07:00
poli0981 779aa1943e Merge pull request #131 from poli0981/dependabot/npm_and_yarn/postcss-8.5.25 2026-08-13 09:43:20 +07:00
poli0981 1a67dc6901 Merge pull request #133 from poli0981/dependabot/npm_and_yarn/multi-2181bdc769 2026-08-13 09:42:20 +07:00
dependabot[bot] 967c0c4024 chore(deps-dev): bump brace-expansion from 1.1.13 to 1.1.18
Bumps [brace-expansion](https://github.com/juliangruber/brace-expansion) from 1.1.13 to 1.1.18.
- [Release notes](https://github.com/juliangruber/brace-expansion/releases)
- [Commits](https://github.com/juliangruber/brace-expansion/compare/v1.1.13...v1.1.18)

---
updated-dependencies:
- dependency-name: brace-expansion
  dependency-version: 1.1.18
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-13 02:42:07 +00:00
dependabot[bot] 2408c40e50 chore(deps): bump react-router and react-router-dom
Bumps [react-router](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router) to 7.18.2 and updates ancestor dependency [react-router-dom](https://github.com/remix-run/react-router/tree/HEAD/packages/react-router-dom). These dependencies need to be updated together.


Updates `react-router` from 6.30.4 to 7.18.2
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router@7.18.2/packages/react-router/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router@7.18.2/packages/react-router)

Updates `react-router-dom` from 6.30.4 to 7.18.2
- [Release notes](https://github.com/remix-run/react-router/releases)
- [Changelog](https://github.com/remix-run/react-router/blob/react-router-dom@7.18.2/packages/react-router-dom/CHANGELOG.md)
- [Commits](https://github.com/remix-run/react-router/commits/react-router-dom@7.18.2/packages/react-router-dom)

---
updated-dependencies:
- dependency-name: react-router
  dependency-version: 7.18.2
  dependency-type: indirect
- dependency-name: react-router-dom
  dependency-version: 7.18.2
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-13 02:41:01 +00:00
poli0981 d955d045f0 Merge pull request #132 from poli0981/dependabot/npm_and_yarn/js-yaml-4.3.1 2026-08-13 09:39:45 +07:00
dependabot[bot] 8c064ebd98 chore(deps-dev): bump js-yaml from 4.2.0 to 4.3.1
Bumps [js-yaml](https://github.com/nodeca/js-yaml) from 4.2.0 to 4.3.1.
- [Changelog](https://github.com/nodeca/js-yaml/blob/4.3.1/CHANGELOG.md)
- [Commits](https://github.com/nodeca/js-yaml/compare/4.2.0...4.3.1)

---
updated-dependencies:
- dependency-name: js-yaml
  dependency-version: 4.3.1
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-12 00:51:36 +00:00
dependabot[bot] e138758656 chore(deps-dev): bump postcss from 8.5.15 to 8.5.25
Bumps [postcss](https://github.com/postcss/postcss) from 8.5.15 to 8.5.25.
- [Release notes](https://github.com/postcss/postcss/releases)
- [Changelog](https://github.com/postcss/postcss/blob/main/CHANGELOG.md)
- [Commits](https://github.com/postcss/postcss/compare/8.5.15...8.5.25)

---
updated-dependencies:
- dependency-name: postcss
  dependency-version: 8.5.25
  dependency-type: direct:development
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-02 02:38:44 +00:00
poli0981 9671bca9c4 Merge pull request #127 from poli0981/claude/email-customization-toggle-1afb33
feat: split contact email by purpose behind a toggle (v0.34.0)
2026-07-20 21:02:38 +07:00
poli0981andClaude Opus 4.8 633298c049 feat: split contact email by purpose behind a toggle (v0.34.0)
Add a Settings "Split contact email by purpose" toggle (off by default).
When on, the editor exposes three email fields — Contact, Advertising,
and Game keys & playtest — and the description renders a grouped
"BUSINESS / CONTACT" block with one labeled line per non-empty field.
Off keeps the single "Business inquiries" line unchanged.

- New editor fields adEmail/gameKeyEmail (persist v17->v18); contactEmail
  is reused as the Contact line, so no saved data moves. The
  splitContactEmail toggle mirrors showThirdPartyAds end-to-end
  (settings persist v10->v11). Profiles persist v1->v2. All migrations
  are additive back-fills.
- +8 ui / +4 templates i18n keys across all six locales (983/563).
- 621 tests pass (613 + 8), typecheck/lint/locale validation green.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-20 20:59:19 +07:00
dependabot[bot] 938d35b613 chore(deps): bump serde_with from 3.18.0 to 3.21.0 in /src-tauri
Bumps [serde_with](https://github.com/jonasbb/serde_with) from 3.18.0 to 3.21.0.
- [Release notes](https://github.com/jonasbb/serde_with/releases)
- [Commits](https://github.com/jonasbb/serde_with/compare/v3.18.0...v3.21.0)

---
updated-dependencies:
- dependency-name: serde_with
  dependency-version: 3.21.0
  dependency-type: indirect
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-07-15 23:29:04 +00:00
poli0981 43d850d1d4 Merge pull request #124 from poli0981/claude/community-social-links-7a51c1
feat: Community section — Signal + Instagram links, Facebook Group moved in (v0.33.0)
2026-07-13 19:19:46 +07:00
poli0981andClaude Opus 4.8 10ef68bfdc feat: add Signal + Instagram community links, move Facebook Group (v0.33.0)
Grow the description's COMMUNITY block into the channel's full "join the
chat" hub. Two new dedicated invite fields — Signal
(https://signal.group/#<id>) and the Instagram group chat
(https://www.instagram.com/j/<id> or https://ig.me/j/<id>) — plus
Facebook Group moved out of the generic Social list into its own
facebookGroupLink community field. All three render for every output
language (like Messenger); Zalo stays Vietnamese-only. Block order:
Messenger, Signal, Instagram, Facebook Group, Zalo.

Each new link hard-rejects off-format input via a strict validator
(validateSignalGroupUrl / validateInstagramInviteUrl /
validateFacebookGroupUrl). The three fields thread through defaults, the
store (persist v16 -> v17), GeneratorInput, the editor -> engine mapper,
and template snapshots. The v17 migration lifts a legacy social.fb_group
value into facebookGroupLink and drops the dead key; normalizeEditorPatch
does the same for profiles/presets/templates.

i18n: 9 keys added / 1 removed across all 6 locales + schema
(975 ui / 559 templates). 613 tests pass (was 583). Five manifests
bumped 0.32.1 -> 0.33.0.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-13 19:18:19 +07:00
poli0981 7e31791439 Merge pull request #122 from poli0981/claude/messenger-community-link-hotfix-f1b3c9
fix: correct Messenger community link format to m.me/ch/ (v0.32.1)
2026-07-12 23:13:51 +07:00
poli0981andClaude Opus 4.8 2d92d5ba81 fix: correct Messenger community link format to m.me/ch/ (v0.32.1)
v0.32.0 accepted `https://m.me/[id]` (a personal-page link) for the
Messenger Community field. A community/channel invite is actually
`https://m.me/ch/[id]` (e.g. https://m.me/ch/Abb1hmBhU_97UMCF/).

- Tighten MESSENGER_URL_REGEX to require the /ch/ segment (trailing
  slash optional) and hard-reject the old bare form.
- Update the shown example (MESSENGER_URL_EXPECTED) + the 6-locale
  placeholder to https://m.me/ch/yourid; refresh stale doc comments.
- Update validation/engine/migrate tests; add trailing-slash accept
  and bare-form reject cases.

Engine and store are unchanged (the link is printed verbatim, and the
field type/persist shape is untouched). Bump to v0.32.1.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-12 23:10:53 +07:00
poli0981 fdb55f3018 Merge pull request #120 from poli0981/claude/zalo-messenger-community-links-a6a29e
feat: add Messenger community + VN Zalo group links (v0.32.0)
2026-07-08 20:51:03 +07:00
poli0981andClaude Opus 4.8 12b0099238 feat: add Messenger community + VN Zalo group links (v0.32.0)
Add two "join the chat" community links that render into a single
"💬 COMMUNITY" description block:

- Messenger community (https://m.me/[id]) — shown for every language.
- Zalo group (https://zalo.me/g/<code>) — Zalo is a Vietnam-audience
  app, so the editor input only appears (and the description line only
  renders) when the output language is Vietnamese, mirroring the VN
  donate block. A value entered while in Vietnamese is preserved if the
  creator switches language.

Both links are hard-validated (validateMessengerUrl / validateZaloGroupUrl)
so a malformed URL never reaches the output. New editor-store fields
persist via a v15→v16 migration and round-trip through saved templates.

i18n across all 6 locales (967 ui / 559 templates). Tests 560→581.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-08 20:47:53 +07:00
poli0981 e5776fa38c Merge pull request #118 from poli0981/claude/wizardly-tesla-6f470f
feat: playlist pinned-comment + dropped reasons (v0.31.0)
2026-06-28 22:18:23 +07:00
poli0981andClaude Opus 4.8 fe7e89d57e feat: add playlist pinned-comment + dropped reasons (v0.31.0)
Playlist Generator now produces a status-adaptive pinned comment for the
latest video, and when a series is marked dropped, a multi-select of
reasons (predefined checklist + free-text) that render in both the
playlist description and the comment. Localized across all 6 locales.
New buildPlaylistComment engine fn + first tests for playlist-builder.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-28 22:15:14 +07:00
172 changed files with 6342 additions and 2159 deletions

No files matched your search

+47 -5
View File
@@ -1,10 +1,11 @@
# Dependabot configuration.
#
# This file exists only to configure SECURITY updates for cargo in /src-tauri.
# Version updates stay disabled (open-pull-requests-limit: 0); npm and
# GitHub Actions keep GitHub's default security-update behavior.
# Three ecosystems: npm (the app), cargo (the Tauri shell), and github-actions
# (the workflows). Security updates are on repo-wide by default; the entries
# below add scheduled VERSION updates so the tree does not silently rot between
# advisories, and carry the ignore rules that keep unfixable alerts quiet.
#
# Why the ignores: `rand` and `glib` are transitive dependencies of tauri,
# Why the cargo ignores: `rand` and `glib` are transitive dependencies of tauri,
# and their security fixes require semver-major bumps that the dependency
# tree does not allow, so every Dependabot security-update job for them
# fails with `security_update_not_possible` (runs 27387346373, 27387346324):
@@ -20,12 +21,53 @@
version: 2
updates:
- package-ecosystem: "npm"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 5
commit-message:
prefix: "chore(deps)"
prefix-development: "chore(deps-dev)"
groups:
# One PR per family instead of one per package. A split React or
# typescript-eslint bump is never independently mergeable anyway, and
# CI has to run for each PR.
react:
patterns: ["react", "react-dom", "@types/react", "@types/react-dom"]
i18n:
patterns: ["i18next*", "react-i18next"]
tauri:
patterns: ["@tauri-apps/*"]
lint-and-format:
patterns: ["eslint*", "@eslint/*", "typescript-eslint", "prettier*", "knip"]
build-tooling:
patterns: ["vite", "vitest", "@vitejs/*", "tailwindcss", "postcss", "autoprefixer", "tsx"]
ignore:
# Majors land in their own planned release (see docs/ROADMAP.md) because
# each one needs a real migration — React 19, Tailwind 4 and ESLint 10 all
# change APIs the app uses directly. Dependabot handles minor + patch.
- dependency-name: "*"
update-types: ["version-update:semver-major"]
- package-ecosystem: "cargo"
directory: "/src-tauri"
schedule:
interval: "weekly"
# No version-update PRs; this entry only feeds ignore rules to security updates.
# No version-update PRs; this entry only feeds ignore rules to security
# updates. The Rust side is pinned to whatever tauri's tree allows.
open-pull-requests-limit: 0
ignore:
- dependency-name: "rand"
- dependency-name: "glib"
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "weekly"
open-pull-requests-limit: 3
commit-message:
prefix: "ci"
groups:
actions:
patterns: ["*"]
+51 -5
View File
@@ -6,6 +6,20 @@ on:
pull_request:
branches: [main]
# Least privilege. The job only reads the repo — it publishes nothing, comments
# nowhere. Declaring it explicitly also silences CodeQL's
# `actions/missing-workflow-permissions`, which otherwise flags the implicit
# (and much wider) default token scope.
permissions:
contents: read
# A force-push or a quick follow-up commit makes the older run worthless. Cancel
# it instead of paying for both — except on `main`, where every commit's result
# is a historical record the release process reads back.
concurrency:
group: ci-${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
jobs:
check:
runs-on: ubuntu-latest
@@ -16,8 +30,40 @@ jobs:
node-version: 22
cache: npm
- run: npm ci
- run: npm run typecheck
- run: npm run lint
- run: npm run validate:locales
- run: npm run test:run
- run: npm run build
# --- correctness ------------------------------------------------------
# `typecheck` covers src/ (what Vite actually builds); `typecheck:all`
# adds tests/ and scripts/, which went unchecked until v0.35.0 and were
# hiding three silently-stale fixture fields.
- name: Type check (src)
run: npm run typecheck
- name: Type check (tests + scripts)
run: npm run typecheck:all
- name: Lint
run: npm run lint
- name: Validate locales
run: npm run validate:locales
- name: Test
run: npm run test:run
# --- consistency ------------------------------------------------------
- name: Check formatting
run: npm run format:check
- name: Check dead code
run: npm run knip
# The release ritual bumps SIX version fields by hand. This is the only
# thing that notices when one is missed — see scripts/check-version-sync.ts.
- name: Check version sync
run: npm run check:version
# --- security ---------------------------------------------------------
# Advisory-only: a fresh high-severity advisory in a transitive dep must
# not turn every unrelated PR red before Dependabot has had a chance to
# open its fix PR. The Dependabot alerts tab is the source of truth.
- name: Audit dependencies
run: npm audit --audit-level=high
continue-on-error: true
# --- build ------------------------------------------------------------
- name: Build
run: npm run build
+110
View File
@@ -2,6 +2,116 @@
All notable changes to YTDescGen ship as tagged releases on `main`.
## v0.35.0 — 2026-08-17
A **guardrails** release. Four things the app quietly let you do wrong — publish
a Batch description missing its contact block, copy output YouTube would reject,
paste a novel into a field, and export a file without being asked where to put
it — now can't happen.
### Fixed
- **Split contact emails now render in Batch** ([src/hooks/use-render-options.ts](src/hooks/use-render-options.ts), [src/pages/BatchPage.tsx](src/pages/BatchPage.tsx)) — with **Settings → Split contact email** on, the Batch tab showed only the legacy single `📧 Business inquiries:` line while the Output tab correctly showed the grouped `📧 BUSINESS / CONTACT` block. The engine was never at fault: `renderAll` had three call sites each hand-copying the same twelve settings fields, and BatchPage's copy was missing `splitContactEmail` and `showThirdPartyAds`. An absent flag defaults to `false`, so the wrong branch ran silently. The mapping now lives in one hook, guarded from both sides — a missing key is a compile error (`Required<SettingsRenderOptions>`) *and* a named test failure. **The SPONSORS & PARTNERS block was being dropped in Batch for the same reason and now renders too, so Batch descriptions get longer if you had either toggle on.**
- **Exports ask where to save** ([src/utils/file-ops.ts](src/utils/file-ops.ts)) — every JSON export (Settings, Profiles, Presets, Templates, Social, Log) bypassed the one writer that branched per platform and dumped straight into `Downloads`, even on desktop where a native Save As dialog was available the whole time. One writer now serves all seven: native **Save As** on Tauri desktop, the **file picker** on Chromium browsers, and the download fallback on Android / Firefox / Safari. Cancelling is silent — dismissing a dialog is a decision, not a failure. Settings Import/Export is also no longer desktop-only.
- **`ValidatedInput` no longer destroys good input** ([src/components/ui/ValidatedInput.tsx](src/components/ui/ValidatedInput.tsx)) — on an invalid value it called `onChange("")`, wiping the stored value while the box still showed your text. Backspacing one character out of a complete URL silently emptied the field, and autosave persisted the empty. It now simply doesn't commit, keeping the last valid value. Separately, the box never re-synced when the value changed underneath it, so applying a profile or preset left stale text on screen disagreeing with the store.
### Added
- **Over-limit output can't be copied** ([src/engine/limits.ts](src/engine/limits.ts)) — if any one of title / description / tags is over its YouTube limit, none of them can be copied, on **Output and Batch**. The engine has returned `warnings` since v0.5 and nothing ever read it; three ad-hoc checks had grown up instead, and the one in `CopyAllBar` skipped every check whenever more than one output language was selected. Batch also gained the description and tag counters it never had. Scoped sensibly: one over-limit part blocks itself and Copy All Batch, not the other 99.
- **Strict Mode** ([src/utils/editor-issues.ts](src/utils/editor-issues.ts)) — a **Settings → Guardrails** toggle, off by default. When on, Generate / Copy / Export are blocked while any field has a hard error, with a banner naming each one. Errors only: a working link that merely doesn't match a platform's usual prefix stays a warning, because blocking it would strand anyone on a vanity domain. Derived from state rather than from mounted inputs, so it works from any page and also catches bad data that arrived by import. The log export stays ungated — a debugging export shouldn't be held hostage by an unrelated bad URL.
- **Field length caps** ([src/config/field-limits.ts](src/config/field-limits.ts)) — `maxLength` appeared nowhere in the codebase before this release. Caps are grouped by what a field holds (URL 200, email 320, short name 100, label 300, long text 2000, timestamps 5000) and wired at 53 call sites. Imports are clamped too, since `maxLength` only constrains typing.
- **Emails hard-stop at three per field** ([src/utils/validation.ts](src/utils/validation.ts)) — typing a fourth is refused outright instead of wiping the field. Enforced on the *increase*, so a field that already holds four (from an older profile) stays editable down to three, and a half-typed `a@b.com,c@` is never punished.
- **Collapsible Settings sections** ([src/pages/settings/GenrePlaylistsSection.tsx](src/pages/settings/GenrePlaylistsSection.tsx)) — **Genre Playlists** renders one input per genre (42 of them) and was the tallest block on the page. It now ships collapsed with a filled-count badge. The other eight sections became accordions too, defaulting open.
### Under the hood
- Settings persist **v11 → v12** (`strictMode`, `settingsAccordionState`), with `SCHEMA_VERSIONS.settings` bumped in lockstep. Both are *coerced*, not merely back-filled — a hand-edited `"strictMode": "yes"` is truthy in JS, and switching a seatbelt on by accident is the opposite of an opt-in. `SCHEMA_VERSIONS.profile` corrected 1 → 2, left behind when profile-store bumped in v0.34.0.
- `SettingsPage` split 544 → 347 lines, extracting the import/export IO and the Genre Playlists section.
- 16 i18n keys per locale across all six locales (validator **999 ui / 563 templates**). typecheck, lint, locale validation, dead-code, formatting, version-sync and **692 tests** (621 + 71) pass; verified live in the browser — Batch renders all three contact lines, a bad Steam URL disables Batch generation and names the field, a fourth email is refused with the three intact, and Genre Playlists opens to 42 inputs behind a `0/42` badge.
- Six manifests bumped 0.34.0 → 0.35.0.
## v0.34.0 — 2026-07-20
A **feature** release that lets creators publish a different email per purpose instead of a
single catch-all address — so viewers, sponsors, and studios each reach the right inbox.
### Added
- **Split contact email by purpose** ([src/pages/SettingsPage.tsx](src/pages/SettingsPage.tsx), [src/components/editor/ContactEmailEditor.tsx](src/components/editor/ContactEmailEditor.tsx)) — a new **Settings → Description** toggle (off by default). Off keeps today's single `📧 Business inquiries:` line, unchanged. On splits the editor's Contact Email field into three: **Contact** (general), **Advertising / sponsorship**, and **Game keys & playtest** — each accepting up to 3 comma-separated addresses via the existing email validator.
- **Grouped contact block** ([src/engine/description-builder.ts](src/engine/description-builder.ts)) — when the toggle is on, the description renders a localized `📧 BUSINESS / CONTACT` block with one labeled line per non-empty field (`📧 Contact:`, `🤝 Advertising:`, `🎮 Game keys & playtest:`). Empty fields are skipped and the whole block drops when all three are empty — same skip logic as the Community block. The existing `contactEmail` is reused as the Contact line, so no saved data moves.
### Under the hood
- Two editor fields (`adEmail`, `gameKeyEmail`) thread through defaults, the store (persist **v17 → v18**), `GeneratorInput`, the editor → engine mapping, template snapshots, and Profiles (persist **v1 → v2**) — guarded by the existing parity test. The `splitContactEmail` toggle mirrors `showThirdPartyAds` end-to-end: the settings store (persist **v10 → v11**, `SCHEMA_VERSIONS.settings` in lockstep), both output hooks, and the render options. Both migrations are additive `""` / `false` back-fills, so existing drafts, profiles, and settings upgrade untouched.
- Twelve i18n keys per locale added (8 ui + 4 templates) across all six locales (validator **983 ui / 563 templates**). typecheck, lint, locale validation, and **621 tests** (613 + 8: split render on/off/partial/empty, v18 migration back-fill/coerce/preserve) pass; verified live.
- Five manifests bumped 0.33.0 → 0.34.0.
## v0.33.0 — 2026-07-13
A **feature** release that turns the description's Community block into the channel's
full "join the chat" hub: two new invite links (**Signal**, **Instagram group chat**)
and **Facebook Group** moved in from the generic Social list.
### Added
- **Signal + Instagram community invites** ([src/components/editor/CommunityEditor.tsx](src/components/editor/CommunityEditor.tsx), [src/utils/validation.ts](src/utils/validation.ts)) — two new inputs in the **Community** section that feed the `💬 COMMUNITY` description block for **every** output language (like Messenger). Signal expects `https://signal.group/#<id>`; Instagram expects the group-chat invite `https://www.instagram.com/j/<id>` or the short `https://ig.me/j/<id>` (distinct from the Instagram **profile** link, which stays in Social). Both hard-reject anything off-format via `ValidatedInput`, so a broken invite never reaches the description.
- **Facebook Group moved into Community** ([src/config/social-fields.ts](src/config/social-fields.ts), [src/engine/description-builder.ts](src/engine/description-builder.ts)) — the old generic `fb_group` Social entry is now a dedicated `facebookGroupLink` community field with its own strict `https://facebook.com/groups/<id>` validator (tolerating `www.` / `m.` / `web.` and a trailing slash). It renders in the Community block for all languages. The block order is Messenger → Signal → Instagram → Facebook Group → Zalo (Vietnamese-only).
### Under the hood
- Three editor fields (`signalGroupLink`, `instagramGroupLink`, `facebookGroupLink`) thread through defaults, the store (persist **v16 → v17**), `GeneratorInput`, the editor → engine mapping, and template snapshots — guarded by the existing parity test. The v17 migration **lifts** a legacy `social.fb_group` value into `facebookGroupLink` and drops the dead key; `normalizeEditorPatch` does the same when a pre-move profile / preset / template is applied. Consequence: like the other community links, Facebook Group is no longer stored inside Profiles.
- Nine i18n keys per locale added, one (`social.fb_group`) removed, across all six locales (validator **975 ui / 559 templates**). typecheck, lint, locale validation, and **613 tests** (583 + 30: three new validators, v17 migration incl. the fb_group lift, community render/order/all-language cases, mapping parity) pass; verified live — Vietnamese output shows all five lines in order with a localized heading, English output drops the Zalo line while keeping the rest, and a malformed Signal link surfaces an inline hard-reject error.
- Five manifests bumped 0.32.1 → 0.33.0.
## v0.32.1 — 2026-07-12
A **hotfix** to v0.32.0. The Messenger Community field accepted the wrong link
shape: `https://m.me/[id]` is a personal-page link, while a community/channel
invite is `https://m.me/ch/[id]` (e.g. `https://m.me/ch/Abb1hmBhU_97UMCF/`).
Creators following the in-app example published a link that did not open the
community.
### Fixed
- **Messenger community link format** ([src/utils/validation.ts](src/utils/validation.ts)) — `MESSENGER_URL_REGEX` now requires the `/ch/` segment (trailing slash optional) and hard-rejects the old bare form, so a wrong link can no longer reach the description. The shown example (`MESSENGER_URL_EXPECTED`) and the placeholder in all six locales moved to `https://m.me/ch/yourid`; stale doc comments were refreshed alongside.
### Under the hood
- Engine and store are untouched — the link is printed verbatim and the field's type and persist shape are unchanged, so no migration was needed. Validation, engine, and migration tests updated, with new trailing-slash-accept and bare-form-reject cases.
- Five manifests bumped 0.32.0 → 0.32.1.
## v0.32.0 — 2026-07-08
A **feature** release adding the first two "join the chat" community links, in a
single `💬 COMMUNITY` description block — the block that v0.33.0 later grew to
five entries.
### Added
- **Messenger community + Zalo group** ([src/components/editor/CommunityEditor.tsx](src/components/editor/CommunityEditor.tsx), [src/utils/validation.ts](src/utils/validation.ts)) — a new **Community** section feeding a localized `💬 COMMUNITY` block. Messenger renders for **every** output language. Zalo is a Vietnam-audience app, so its input only appears — and its line only renders — when the output language is Vietnamese, mirroring the existing VN donate block; a value entered while in Vietnamese survives a language switch. Both links are hard-validated (`validateMessengerUrl` / `validateZaloGroupUrl`) so a malformed URL never reaches the output.
### Under the hood
- Two editor fields (`messengerCommunityLink`, `zaloGroupLink`) thread through defaults, the store (persist **v15 → v16**, an additive back-fill), `GeneratorInput`, the editor → engine mapping, and template snapshots — guarded by the existing parity test.
- i18n across all six locales (validator **967 ui / 559 templates**). typecheck, lint, locale validation, and **581 tests** (560 + 21: two new validators, the v16 migration, and community render/language-gating cases) pass.
- Five manifests bumped 0.31.0 → 0.32.0.
## v0.31.0 — 2026-06-28
A **feature** release for the Playlist Generator: the pinned comment a series
needs on its latest video, and an honest answer to "why did this playlist stop?"
### Added
- **Status-adaptive playlist pinned comment** ([src/engine/playlist-builder.ts](src/engine/playlist-builder.ts)) — a new `buildPlaylistComment` engine function produces a pinned comment for the series' latest video whose wording follows the playlist status (completed / dropped / incomplete / in progress), rather than one generic template for all four.
- **Dropped reasons** ([src/config/dropped-reasons.ts](src/config/dropped-reasons.ts), [src/pages/PlaylistPage.tsx](src/pages/PlaylistPage.tsx)) — when a series is marked **dropped**, a multi-select of six predefined reasons (`😴 boring`, `🐌 performance`, `🐛 bugs`, `🗑️ delisted`, `📉 low views`, `⏳ time`) plus a free-text "other reason" field. Selected reasons render in **both** the playlist description and the pinned comment. Reason labels are localized in both namespaces — `ui` for the selection chips, `templates` for the rendered output — the same split content warnings use.
### Under the hood
- Playlist state stays local to the page; nothing was added to the editor store, so there is no migration in this release.
- i18n across all six locales (validator **959 ui / 558 templates**). `playlist-builder` gained its first test file — **197 lines** covering comment generation per status and dropped-reason rendering.
- Five manifests bumped 0.30.0 → 0.31.0.
## v0.30.0 — 2026-06-27
A **feature** release adding two things creators kept doing by hand: advertising a
+11
View File
@@ -15,6 +15,17 @@ export default tseslint.config(
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
},
},
{
// Tests index into fixture arrays constantly, and `noUncheckedIndexedAccess`
// makes every one of those reads `T | undefined`. A `!` there asserts the
// fixture the test itself just built — the alternative is a guard clause per
// lookup that can only ever fail if the test is already broken. Production
// code keeps the rule.
files: ["tests/**/*.ts", "tests/**/*.tsx"],
rules: {
"@typescript-eslint/no-non-null-assertion": "off",
},
},
{
ignores: ["dist/", "node_modules/", "*.config.*"],
},
-1
View File
@@ -5,7 +5,6 @@
"ignoreExportsUsedInFile": true,
"ignoreDependencies": [
"@tauri-apps/plugin-fs",
"@tauri-apps/plugin-opener",
"@tauri-apps/plugin-shell",
"@testing-library/jest-dom",
"@testing-library/react"
+78 -44
View File
@@ -1,12 +1,12 @@
{
"name": "yt-desc-gen",
"version": "0.30.0",
"version": "0.35.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "yt-desc-gen",
"version": "0.30.0",
"version": "0.35.0",
"license": "Apache-2.0",
"dependencies": {
"@tauri-apps/api": "^2.11.0",
@@ -22,13 +22,14 @@
"react-dom": "^18.3.0",
"react-hot-toast": "^2.4.0",
"react-i18next": "^15.0.0",
"react-router-dom": "^6.26.0",
"react-router-dom": "^7.18.2",
"zustand": "^4.5.0"
},
"devDependencies": {
"@eslint/js": "^9.0.0",
"@testing-library/jest-dom": "^6.4.0",
"@testing-library/react": "^16.0.0",
"@types/node": "^26.2.0",
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^5.2.0",
@@ -36,7 +37,7 @@
"eslint": "^9.0.0",
"eslint-plugin-react-hooks": "^5.0.0",
"knip": "^6.14.1",
"postcss": "^8.5.14",
"postcss": "^8.5.25",
"prettier": "^3.3.0",
"prettier-plugin-tailwindcss": "^0.6.0",
"tailwindcss": "^3.4.0",
@@ -1820,15 +1821,6 @@
"win32"
]
},
"node_modules/@remix-run/router": {
"version": "1.23.3",
"resolved": "https://registry.npmjs.org/@remix-run/router/-/router-1.23.3.tgz",
"integrity": "sha512-4An71tdz9X8+3sI4Qqqd2LWd9vS39J7sqd9EU4Scw7TJE/qB10Flv/UuqbPVgfQV9XoK8Np6jNquZitnZq5i+Q==",
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/@rolldown/binding-android-arm64": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz",
@@ -2336,6 +2328,16 @@
"dev": true,
"license": "MIT"
},
"node_modules/@types/node": {
"version": "26.2.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-26.2.0.tgz",
"integrity": "sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg==",
"dev": true,
"license": "MIT",
"dependencies": {
"undici-types": "~8.3.0"
}
},
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
@@ -2563,16 +2565,16 @@
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/brace-expansion": {
"version": "5.0.6",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz",
"integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==",
"version": "5.0.9",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.9.tgz",
"integrity": "sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==",
"dev": true,
"license": "MIT",
"dependencies": {
"balanced-match": "^4.0.2"
},
"engines": {
"node": "18 || 20 || >=22"
"node": "20 || >=22"
}
},
"node_modules/@typescript-eslint/typescript-estree/node_modules/minimatch": {
@@ -2986,9 +2988,9 @@
}
},
"node_modules/brace-expansion": {
"version": "1.1.13",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.13.tgz",
"integrity": "sha512-9ZLprWS6EENmhEOpjCYW2c8VkmOvckIJZfkr7rBW6dObmfgJ/L1GpSYW5Hpo9lDz4D1+n0Ckz8rU7FwHDQiG/w==",
"version": "1.1.18",
"resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz",
"integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==",
"dev": true,
"license": "MIT",
"dependencies": {
@@ -3202,6 +3204,19 @@
"dev": true,
"license": "MIT"
},
"node_modules/cookie": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
"license": "MIT",
"engines": {
"node": ">=18"
},
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/express"
}
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -4021,9 +4036,9 @@
"license": "MIT"
},
"node_modules/js-yaml": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.2.0.tgz",
"integrity": "sha512-ePWsvanv0DWuDRsW8dnt+R4jQ31SCRCQ7hhNcPXZPsoBZiemuZNYGf7adZdqX2D86j6rvKp3RpCxVTSb8WQlOw==",
"version": "4.3.1",
"resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.3.1.tgz",
"integrity": "sha512-CY6crGq313MX8GkwvB7tzgp99vjQxY1++5y10/BKN/GUfHqWaOGQMNZkBvqSzsZKWk/ijwHlWzzkLulsGHhjWQ==",
"dev": true,
"funding": [
{
@@ -4653,9 +4668,9 @@
}
},
"node_modules/nanoid": {
"version": "3.3.12",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
"version": "3.3.18",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.18.tgz",
"integrity": "sha512-DTg4MJbGMWkfi6VZFdNt2/caMbQy4Ou+Op/hJQvGEWcnVfoA1QA+xzRKAzw9jD6+GVOOeYr/mIcuDSdug6F6+w==",
"dev": true,
"funding": [
{
@@ -4937,9 +4952,9 @@
}
},
"node_modules/postcss": {
"version": "8.5.15",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz",
"integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==",
"version": "8.5.25",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.25.tgz",
"integrity": "sha512-DTPx3RWSSnWyzLxQnlH0rJP+EW5ekl16ZU4/psbIhA0e53kJfdgaN5vKM+xP7yJtXVu+nfdVFmlgFDEKAe4Pyw==",
"dev": true,
"funding": [
{
@@ -4957,7 +4972,7 @@
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.12",
"nanoid": "^3.3.16",
"picocolors": "^1.1.1",
"source-map-js": "^1.2.1"
},
@@ -5360,35 +5375,41 @@
}
},
"node_modules/react-router": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-6.30.4.tgz",
"integrity": "sha512-SVUsDe+DybHM/WmYKIVYhZh1o5Dcuf16yM6WjG02Q9XVFMZIJyHYhwrr6bFBXZkVP6z69kNkMyBCujt8FaFLJA==",
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/react-router/-/react-router-7.18.2.tgz",
"integrity": "sha512-aUVMjFm3GAPTTZL7oYr5E7ETiqfQCHRLH+B+5afnICvf0r7kkK4eR6SMuwbSTJw/7t+12khT/Kahij49fqOCIg==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3"
"cookie": "^1.0.1",
"set-cookie-parser": "^2.6.0"
},
"engines": {
"node": ">=14.0.0"
"node": ">=20.0.0"
},
"peerDependencies": {
"react": ">=16.8"
"react": ">=18",
"react-dom": ">=18"
},
"peerDependenciesMeta": {
"react-dom": {
"optional": true
}
}
},
"node_modules/react-router-dom": {
"version": "6.30.4",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-6.30.4.tgz",
"integrity": "sha512-q4HvNl+mmDdkS0g+MqiBZNteQJCuimWoOyHMy4T/RQLAn9Z29+E91QXRaxOujeMl2HTzRSS0KFPd7lxX3PjV0Q==",
"version": "7.18.2",
"resolved": "https://registry.npmjs.org/react-router-dom/-/react-router-dom-7.18.2.tgz",
"integrity": "sha512-AIKJ/jgGlFb3EbfCXk5Gzshiwt+l3mqbCrNjmEWMMjqQxNJ3svBa6bgzFyCC2Sw3RA0VWF1kg3uQf2OFhxb8hw==",
"license": "MIT",
"dependencies": {
"@remix-run/router": "1.23.3",
"react-router": "6.30.4"
"react-router": "7.18.2"
},
"engines": {
"node": ">=14.0.0"
"node": ">=20.0.0"
},
"peerDependencies": {
"react": ">=16.8",
"react-dom": ">=16.8"
"react": ">=18",
"react-dom": ">=18"
}
},
"node_modules/read-cache": {
@@ -5574,6 +5595,12 @@
"semver": "bin/semver.js"
}
},
"node_modules/set-cookie-parser": {
"version": "2.7.2",
"resolved": "https://registry.npmjs.org/set-cookie-parser/-/set-cookie-parser-2.7.2.tgz",
"integrity": "sha512-oeM1lpU/UvhTxw+g3cIfxXHyJRc/uidd3yK1P242gzHds0udQBYzs3y8j4gCCW+ZJ7ad0yctld8RYO+bdurlvw==",
"license": "MIT"
},
"node_modules/shebang-command": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
@@ -5973,6 +6000,13 @@
"node": ">=14"
}
},
"node_modules/undici-types": {
"version": "8.3.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz",
"integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==",
"dev": true,
"license": "MIT"
},
"node_modules/update-browserslist-db": {
"version": "1.2.3",
"resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz",
+10 -6
View File
@@ -1,6 +1,6 @@
{
"name": "yt-desc-gen",
"version": "0.30.0",
"version": "0.35.0",
"private": true,
"license": "Apache-2.0",
"type": "module",
@@ -11,11 +11,14 @@
"test": "vitest",
"test:run": "vitest run",
"test:coverage": "vitest run --coverage",
"lint": "eslint src/",
"lint:fix": "eslint src/ --fix",
"lint": "eslint src/ tests/ scripts/",
"lint:fix": "eslint src/ tests/ scripts/ --fix",
"knip": "knip",
"typecheck": "tsc --noEmit",
"format": "prettier --write \"src/**/*.{ts,tsx,json,css}\"",
"typecheck:all": "tsc --noEmit -p tsconfig.check.json",
"format": "prettier --write \"{src,tests,scripts}/**/*.{ts,tsx,css}\"",
"format:check": "prettier --check \"{src,tests,scripts}/**/*.{ts,tsx,css}\"",
"check:version": "tsx scripts/check-version-sync.ts",
"validate:locales": "tsx scripts/validate-locales.ts",
"generate:locale": "tsx scripts/generate-locale-template.ts",
"tauri": "tauri",
@@ -36,13 +39,14 @@
"react-dom": "^18.3.0",
"react-hot-toast": "^2.4.0",
"react-i18next": "^15.0.0",
"react-router-dom": "^6.26.0",
"react-router-dom": "^7.18.2",
"zustand": "^4.5.0"
},
"devDependencies": {
"@eslint/js": "^9.0.0",
"@testing-library/jest-dom": "^6.4.0",
"@testing-library/react": "^16.0.0",
"@types/node": "^26.2.0",
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^5.2.0",
@@ -50,7 +54,7 @@
"eslint": "^9.0.0",
"eslint-plugin-react-hooks": "^5.0.0",
"knip": "^6.14.1",
"postcss": "^8.5.14",
"postcss": "^8.5.25",
"prettier": "^3.3.0",
"prettier-plugin-tailwindcss": "^0.6.0",
"tailwindcss": "^3.4.0",
+113
View File
@@ -0,0 +1,113 @@
/**
* Verify that every manifest carrying the app version agrees.
*
* A release bumps SIX places, and nothing but this script notices when one is
* missed. A stale `tauri.conf.json` ships an installer whose About screen and
* updater metadata disagree with the tag; a stale `Cargo.lock` self-entry makes
* the next `cargo build` rewrite the lockfile mid-release.
*
* Run via `npm run check:version`. Exits non-zero (and prints every mismatch,
* not just the first) so CI fails the PR rather than the release.
*/
import { readFileSync } from "fs";
import { resolve } from "path";
interface VersionSource {
/** Human-readable location, printed on mismatch. */
label: string;
/** Repo-relative path. */
file: string;
/** Pull the version out of the file's raw text. */
extract: (raw: string) => string | null;
}
/** Read `version` from a top-level JSON object. */
function jsonVersion(raw: string): string | null {
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null) return null;
const version = (parsed as Record<string, unknown>).version;
return typeof version === "string" ? version : null;
}
const SOURCES: VersionSource[] = [
{
label: "package.json → version",
file: "package.json",
extract: jsonVersion,
},
{
label: "package-lock.json → version",
file: "package-lock.json",
extract: jsonVersion,
},
{
label: 'package-lock.json → packages[""].version',
file: "package-lock.json",
extract: (raw) => {
const parsed: unknown = JSON.parse(raw);
if (typeof parsed !== "object" || parsed === null) return null;
const packages = (parsed as Record<string, unknown>).packages;
if (typeof packages !== "object" || packages === null) return null;
const root = (packages as Record<string, unknown>)[""];
if (typeof root !== "object" || root === null) return null;
const version = (root as Record<string, unknown>).version;
return typeof version === "string" ? version : null;
},
},
{
label: "src-tauri/tauri.conf.json → version",
file: "src-tauri/tauri.conf.json",
extract: jsonVersion,
},
{
label: "src-tauri/Cargo.toml → [package] version",
file: "src-tauri/Cargo.toml",
// Anchor on the [package] table so a dependency's `version = "…"` in the
// same file can never be picked up instead.
extract: (raw) => /^\[package\][\s\S]*?^version\s*=\s*"([^"]+)"/m.exec(raw)?.[1] ?? null,
},
{
label: "src-tauri/Cargo.lock → yt-desc-gen entry",
file: "src-tauri/Cargo.lock",
extract: (raw) => /^name = "yt-desc-gen"\r?\nversion = "([^"]+)"/m.exec(raw)?.[1] ?? null,
},
];
function main(): void {
const found: { label: string; version: string | null }[] = SOURCES.map((source) => {
let raw: string;
try {
raw = readFileSync(resolve(source.file), "utf8");
} catch {
return { label: source.label, version: null };
}
let version: string | null = null;
try {
version = source.extract(raw);
} catch {
version = null;
}
return { label: source.label, version };
});
const missing = found.filter((entry) => entry.version === null);
const versions = [...new Set(found.map((entry) => entry.version).filter(Boolean))];
if (missing.length === 0 && versions.length === 1) {
console.log(`✓ All ${found.length} manifests agree on version ${versions[0]}`);
return;
}
console.error("✗ Version manifests are out of sync.\n");
for (const entry of found) {
const mark = entry.version === null ? "?" : entry.version === versions[0] ? " " : "!";
console.error(` ${mark} ${entry.version ?? "<not found>"} ${entry.label}`);
}
console.error(
"\nBump every manifest to the same version before tagging. `npm version --no-git-tag-version <v>`",
);
console.error("covers package.json + package-lock.json; the three Rust/Tauri files are manual.");
process.exit(1);
}
main();
+133
View File
@@ -0,0 +1,133 @@
/**
* Scaffold a new locale directory from the English source.
*
* `package.json` has advertised `npm run generate:locale` since v0.1, and
* `docs/I18N.md` step 1 tells contributors to run it — but the script was never
* committed, so the documented first step of adding a language failed outright.
* This is that script.
*
* Usage:
* npm run generate:locale -- --lang pt-BR # empty values to translate
* npm run generate:locale -- --lang id --copy-english # pre-fill with EN text
* npm run generate:locale -- --lang id --force # overwrite an existing dir
*
* Output mirrors `src/i18n/locales/en/{ui,templates}.json` key-for-key, so
* `npm run validate:locales` passes the moment the files are written (it checks
* key parity, not whether the values were actually translated).
*
* Registering the locale in code is NOT done here — see the checklist printed
* on success, and docs/I18N.md.
*/
import { readFileSync, writeFileSync, existsSync, mkdirSync } from "fs";
import { join, resolve } from "path";
const LOCALES_DIR = resolve("src/i18n/locales");
const SOURCE_LOCALE = "en";
const NAMESPACES = ["ui", "templates"] as const;
/** BCP-47-ish: `pt`, `pt-BR`, `zh-Hant`. Keeps a typo from creating a junk dir. */
const LANG_PATTERN = /^[a-z]{2,3}(-[A-Za-z]{2,8})*$/;
interface Options {
lang: string;
copyEnglish: boolean;
force: boolean;
}
function parseArgs(argv: string[]): Options {
let lang = "";
let copyEnglish = false;
let force = false;
for (let i = 0; i < argv.length; i++) {
const arg = argv[i];
if (arg === "--lang" || arg === "-l") {
lang = argv[++i] ?? "";
} else if (arg?.startsWith("--lang=")) {
lang = arg.slice("--lang=".length);
} else if (arg === "--copy-english") {
copyEnglish = true;
} else if (arg === "--force") {
force = true;
}
}
if (!lang) {
console.error("Missing --lang.\n\n npm run generate:locale -- --lang pt-BR\n");
process.exit(1);
}
if (!LANG_PATTERN.test(lang)) {
console.error(`Invalid language code "${lang}". Expected e.g. "id", "pt-BR", "zh-Hant".\n`);
process.exit(1);
}
return { lang, copyEnglish, force };
}
/**
* Rebuild the tree with every leaf replaced by `""`, preserving key order so
* the generated file diffs cleanly against the English source.
*/
function blankLeaves(value: unknown): unknown {
if (Array.isArray(value)) return value.map(blankLeaves);
if (typeof value === "object" && value !== null) {
const out: Record<string, unknown> = {};
for (const [key, child] of Object.entries(value as Record<string, unknown>)) {
out[key] = blankLeaves(child);
}
return out;
}
return "";
}
function countLeaves(value: unknown): number {
if (Array.isArray(value)) return value.reduce<number>((n, v) => n + countLeaves(v), 0);
if (typeof value === "object" && value !== null) {
return Object.values(value as Record<string, unknown>).reduce<number>(
(n, v) => n + countLeaves(v),
0,
);
}
return 1;
}
function main(): void {
const { lang, copyEnglish, force } = parseArgs(process.argv.slice(2));
const targetDir = join(LOCALES_DIR, lang);
if (existsSync(targetDir) && !force) {
console.error(`✗ ${targetDir} already exists. Pass --force to overwrite.\n`);
process.exit(1);
}
mkdirSync(targetDir, { recursive: true });
let total = 0;
for (const ns of NAMESPACES) {
const sourcePath = join(LOCALES_DIR, SOURCE_LOCALE, `${ns}.json`);
if (!existsSync(sourcePath)) {
console.error(`✗ Source locale missing: ${sourcePath}`);
process.exit(1);
}
const source: unknown = JSON.parse(readFileSync(sourcePath, "utf-8"));
const output = copyEnglish ? source : blankLeaves(source);
const outPath = join(targetDir, `${ns}.json`);
// Two-space indent + trailing newline matches the existing locale files.
writeFileSync(outPath, `${JSON.stringify(output, null, 2)}\n`, "utf-8");
const leaves = countLeaves(source);
total += leaves;
console.log(
`✓ ${lang}/${ns}.json — ${leaves} keys${copyEnglish ? " (English text)" : " (empty)"}`,
);
}
console.log(`\n${total} strings to translate. Remaining steps to register "${lang}":
1. src/i18n/index.ts — add to SUPPORTED_LANGUAGES (flag + nativeName)
2. src/engine/types.ts — add to the SupportedLanguage union
3. src/store/settings-heal.ts — add to detectBrowserLanguage's supported list
4. src/engine/tag-generator.ts— add a MULTILINGUAL_TAGS entry (TS enforces this)
5. npm run validate:locales — must pass before committing
See docs/I18N.md for the full checklist.`);
}
main();
+1 -3
View File
@@ -74,9 +74,7 @@ function validate(): void {
console.log(`✓ ${locale}/${filename} — ${actualKeys.length}/${expectedKeys.length} keys`);
} else {
hasErrors = true;
console.error(
`✗ ${locale}/${filename} — ${actualKeys.length}/${expectedKeys.length} keys`,
);
console.error(`✗ ${locale}/${filename} — ${actualKeys.length}/${expectedKeys.length} keys`);
if (missing.length > 0) {
console.error(` Missing: ${missing.join(", ")}`);
}
+41 -47
View File
@@ -307,6 +307,15 @@ dependencies = [
"alloc-stdlib",
]
[[package]]
name = "bs58"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"
dependencies = [
"tinyvec",
]
[[package]]
name = "bumpalo"
version = "3.20.2"
@@ -1629,7 +1638,7 @@ dependencies = [
"js-sys",
"log",
"wasm-bindgen",
"windows-core 0.62.2",
"windows-core",
]
[[package]]
@@ -3389,11 +3398,12 @@ dependencies = [
[[package]]
name = "serde_with"
version = "3.18.0"
version = "3.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd5414fad8e6907dbdd5bc441a50ae8d6e26151a03b1de04d89a5576de61d01f"
checksum = "76a5c54c7310e7b8b9577c286d7e399ddd876c3e12b3ed917a8aabc4b96e9e8c"
dependencies = [
"base64 0.22.1",
"bs58",
"chrono",
"hex",
"indexmap 1.9.3",
@@ -3408,9 +3418,9 @@ dependencies = [
[[package]]
name = "serde_with_macros"
version = "3.18.0"
version = "3.21.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3db8978e608f1fe7357e211969fd9abdcae80bac1ba7a3369bb7eb6b404eb65"
checksum = "84d57bc0c8b9a17920c178daa6bb924850d54a9c97ab45194bb8c17ad66bb660"
dependencies = [
"darling",
"proc-macro2",
@@ -3768,7 +3778,7 @@ dependencies = [
"unicode-segmentation",
"url",
"windows",
"windows-core 0.61.2",
"windows-core",
"windows-version",
"x11-dl",
]
@@ -4237,6 +4247,21 @@ dependencies = [
"zerovec",
]
[[package]]
name = "tinyvec"
version = "1.12.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f"
dependencies = [
"tinyvec_macros",
]
[[package]]
name = "tinyvec_macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
[[package]]
name = "tokio"
version = "1.51.0"
@@ -4862,7 +4887,7 @@ dependencies = [
"webview2-com-macros",
"webview2-com-sys",
"windows",
"windows-core 0.61.2",
"windows-core",
"windows-implement",
"windows-interface",
]
@@ -4886,7 +4911,7 @@ checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"
dependencies = [
"thiserror 2.0.18",
"windows",
"windows-core 0.61.2",
"windows-core",
]
[[package]]
@@ -4942,7 +4967,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893"
dependencies = [
"windows-collections",
"windows-core 0.61.2",
"windows-core",
"windows-future",
"windows-link 0.1.3",
"windows-numerics",
@@ -4954,7 +4979,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8"
dependencies = [
"windows-core 0.61.2",
"windows-core",
]
[[package]]
@@ -4966,21 +4991,8 @@ dependencies = [
"windows-implement",
"windows-interface",
"windows-link 0.1.3",
"windows-result 0.3.4",
"windows-strings 0.4.2",
]
[[package]]
name = "windows-core"
version = "0.62.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
dependencies = [
"windows-implement",
"windows-interface",
"windows-link 0.2.1",
"windows-result 0.4.1",
"windows-strings 0.5.1",
"windows-result",
"windows-strings",
]
[[package]]
@@ -4989,7 +5001,7 @@ version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e"
dependencies = [
"windows-core 0.61.2",
"windows-core",
"windows-link 0.1.3",
"windows-threading",
]
@@ -5034,7 +5046,7 @@ version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1"
dependencies = [
"windows-core 0.61.2",
"windows-core",
"windows-link 0.1.3",
]
@@ -5047,15 +5059,6 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-result"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-strings"
version = "0.4.2"
@@ -5065,15 +5068,6 @@ dependencies = [
"windows-link 0.1.3",
]
[[package]]
name = "windows-strings"
version = "0.5.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
dependencies = [
"windows-link 0.2.1",
]
[[package]]
name = "windows-sys"
version = "0.45.0"
@@ -5484,7 +5478,7 @@ dependencies = [
"webkit2gtk-sys",
"webview2-com",
"windows",
"windows-core 0.61.2",
"windows-core",
"windows-version",
"x11-dl",
]
@@ -5535,7 +5529,7 @@ dependencies = [
[[package]]
name = "yt-desc-gen"
version = "0.30.0"
version = "0.35.0"
dependencies = [
"tauri",
"tauri-build",
+1 -1
View File
@@ -1,6 +1,6 @@
[package]
name = "yt-desc-gen"
version = "0.30.0"
version = "0.35.0"
description = "YouTube Gameplay Description Generator"
authors = ["poli0981"]
edition = "2021"
+1 -9
View File
@@ -11,14 +11,6 @@
"fs:allow-read-text-file",
"fs:allow-write-text-file",
"shell:default",
"opener:default",
{
"identifier": "opener:allow-open-path",
"allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }]
},
{
"identifier": "opener:allow-reveal-item-in-dir",
"allow": [{ "path": "$APPDATA" }, { "path": "$APPDATA/**" }]
}
"opener:default"
]
}
+1 -1
View File
@@ -1 +1 @@
{"default":{"identifier":"default","description":"Default capabilities for YTDescGen","local":true,"windows":["main"],"permissions":["core:default","dialog:default","dialog:allow-save","dialog:allow-open","fs:default","fs:allow-read-text-file","fs:allow-write-text-file","shell:default","opener:default",{"identifier":"opener:allow-open-path","allow":[{"path":"$APPDATA"},{"path":"$APPDATA/**"}]},{"identifier":"opener:allow-reveal-item-in-dir","allow":[{"path":"$APPDATA"},{"path":"$APPDATA/**"}]}]}}
{"default":{"identifier":"default","description":"Default capabilities for YTDescGen","local":true,"windows":["main"],"permissions":["core:default","dialog:default","dialog:allow-save","dialog:allow-open","fs:default","fs:allow-read-text-file","fs:allow-write-text-file","shell:default","opener:default"]}}
-14
View File
@@ -27,19 +27,6 @@ fn read_from_file(path: String) -> Result<String, String> {
std::fs::read_to_string(&path).map_err(|e| e.to_string())
}
/// Ensure a directory exists on disk, creating it (and any missing
/// parents) if necessary. No-op when the path already exists as a
/// directory. Fixes the "Windows cannot find ... AppData\Roaming\
/// com.skullmute.ytdescgen" Explorer error on first launch — see
/// `openSettingsFolder()` in `SettingsPage.tsx`, where this is called
/// before `openPath(dir)` so the OS shell never sees a non-existent
/// path. Returns the OS error string on failure (e.g. permission
/// denied) so the caller can surface it via the in-app log.
#[tauri::command]
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,
@@ -111,7 +98,6 @@ pub fn run() {
.invoke_handler(tauri::generate_handler![
save_to_file,
read_from_file,
ensure_dir,
append_to_file,
list_dir,
delete_file
+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.30.0",
"version": "0.35.0",
"identifier": "com.skullmute.ytdescgen",
"build": {
"beforeBuildCommand": "npm run build",
+44 -20
View File
@@ -24,21 +24,13 @@ const HistoryPage = lazy(() =>
const SettingsPage = lazy(() =>
import("@pages/SettingsPage").then((m) => ({ default: m.SettingsPage })),
);
const BatchPage = lazy(() =>
import("@pages/BatchPage").then((m) => ({ default: m.BatchPage })),
);
const SocialPage = lazy(() =>
import("@pages/SocialPage").then((m) => ({ default: m.SocialPage })),
);
const BatchPage = lazy(() => import("@pages/BatchPage").then((m) => ({ default: m.BatchPage })));
const SocialPage = lazy(() => import("@pages/SocialPage").then((m) => ({ default: m.SocialPage })));
const PlaylistPage = lazy(() =>
import("@pages/PlaylistPage").then((m) => ({ default: m.PlaylistPage })),
);
const LogPage = lazy(() =>
import("@pages/LogPage").then((m) => ({ default: m.LogPage })),
);
const AboutPage = lazy(() =>
import("@pages/AboutPage").then((m) => ({ default: m.AboutPage })),
);
const LogPage = lazy(() => import("@pages/LogPage").then((m) => ({ default: m.LogPage })));
const AboutPage = lazy(() => import("@pages/AboutPage").then((m) => ({ default: m.AboutPage })));
function PageLoader() {
return <div className="flex items-center justify-center p-12 text-text-muted">Loading...</div>;
@@ -152,35 +144,67 @@ export default function App() {
/>
<Route
path="profiles"
element={<PageBoundary label="Profiles"><ProfilesPage /></PageBoundary>}
element={
<PageBoundary label="Profiles">
<ProfilesPage />
</PageBoundary>
}
/>
<Route
path="history"
element={<PageBoundary label="History"><HistoryPage /></PageBoundary>}
element={
<PageBoundary label="History">
<HistoryPage />
</PageBoundary>
}
/>
<Route
path="settings"
element={<PageBoundary label="Settings"><SettingsPage /></PageBoundary>}
element={
<PageBoundary label="Settings">
<SettingsPage />
</PageBoundary>
}
/>
<Route
path="batch"
element={<PageBoundary label="Batch"><BatchPage /></PageBoundary>}
element={
<PageBoundary label="Batch">
<BatchPage />
</PageBoundary>
}
/>
<Route
path="social"
element={<PageBoundary label="Social"><SocialPage /></PageBoundary>}
element={
<PageBoundary label="Social">
<SocialPage />
</PageBoundary>
}
/>
<Route
path="playlist"
element={<PageBoundary label="Playlist"><PlaylistPage /></PageBoundary>}
element={
<PageBoundary label="Playlist">
<PlaylistPage />
</PageBoundary>
}
/>
<Route
path="logs"
element={<PageBoundary label="Logs"><LogPage /></PageBoundary>}
element={
<PageBoundary label="Logs">
<LogPage />
</PageBoundary>
}
/>
<Route
path="about"
element={<PageBoundary label="About"><AboutPage /></PageBoundary>}
element={
<PageBoundary label="About">
<AboutPage />
</PageBoundary>
}
/>
</Route>
{/* Designed error pages — siblings of the AppShell group so they
+118
View File
@@ -0,0 +1,118 @@
import { useTranslation } from "react-i18next";
import { ValidatedInput } from "@components/ui/ValidatedInput";
import { useEditorStore } from "@store/editor-store";
import {
validateMessengerUrl,
validateZaloGroupUrl,
validateSignalGroupUrl,
validateInstagramInviteUrl,
validateFacebookGroupUrl,
} from "@utils/validation";
import { FIELD_LIMITS } from "@config/field-limits";
/**
* Community invite links. A single section for "join the chat" links that
* feed the description's "💬 COMMUNITY" block:
*
* - Messenger community (`https://m.me/ch/<id>`), Signal group
* (`https://signal.group/#<id>`), Instagram group chat
* (`https://www.instagram.com/j/<id>` or `https://ig.me/j/<id>`), and
* Facebook Group (`https://facebook.com/groups/<id>`) — all shown for
* every output language (v0.32.0 Messenger; v0.33.0 the rest, with
* Facebook Group moved here from the Social section).
* - Zalo group (`https://zalo.me/g/<code>`) — Zalo is a Vietnam-audience
* app, so the input only appears (and the description line only renders)
* when the output language is Vietnamese. A value entered while in
* Vietnamese is preserved if the creator later switches language.
*
* Every input hard-rejects malformed links via {@link ValidatedInput}, so a
* bad URL never reaches the generated description.
*/
export function CommunityEditor() {
const { t } = useTranslation("ui");
const messengerCommunityLink = useEditorStore((s) => s.messengerCommunityLink);
const signalGroupLink = useEditorStore((s) => s.signalGroupLink);
const instagramGroupLink = useEditorStore((s) => s.instagramGroupLink);
const facebookGroupLink = useEditorStore((s) => s.facebookGroupLink);
const zaloGroupLink = useEditorStore((s) => s.zaloGroupLink);
const language = useEditorStore((s) => s.language);
const setField = useEditorStore((s) => s.set);
const isVi = language === "vi";
return (
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium text-text-secondary">{t("editor.community")}</span>
<p className="text-xs text-text-muted">{t("editor.communityHelp")}</p>
</div>
<ValidatedInput
fieldId="messengerCommunityLink"
labelKey="editor.messengerCommunityLink"
label={t("editor.messengerCommunityLink")}
maxLength={FIELD_LIMITS.URL}
placeholder={t("editor.messengerCommunityLinkPlaceholder")}
value={messengerCommunityLink}
onChange={(v) => setField("messengerCommunityLink", v)}
validate={validateMessengerUrl}
inputMode="url"
autoComplete="off"
/>
<ValidatedInput
fieldId="signalGroupLink"
labelKey="editor.signalGroupLink"
label={t("editor.signalGroupLink")}
maxLength={FIELD_LIMITS.URL}
placeholder={t("editor.signalGroupLinkPlaceholder")}
value={signalGroupLink}
onChange={(v) => setField("signalGroupLink", v)}
validate={validateSignalGroupUrl}
inputMode="url"
autoComplete="off"
/>
<ValidatedInput
fieldId="instagramGroupLink"
labelKey="editor.instagramGroupLink"
label={t("editor.instagramGroupLink")}
maxLength={FIELD_LIMITS.URL}
placeholder={t("editor.instagramGroupLinkPlaceholder")}
value={instagramGroupLink}
onChange={(v) => setField("instagramGroupLink", v)}
validate={validateInstagramInviteUrl}
inputMode="url"
autoComplete="off"
/>
<ValidatedInput
fieldId="facebookGroupLink"
labelKey="editor.facebookGroupLink"
label={t("editor.facebookGroupLink")}
maxLength={FIELD_LIMITS.URL}
placeholder={t("editor.facebookGroupLinkPlaceholder")}
value={facebookGroupLink}
onChange={(v) => setField("facebookGroupLink", v)}
validate={validateFacebookGroupUrl}
inputMode="url"
autoComplete="off"
/>
{isVi && (
<ValidatedInput
fieldId="zaloGroupLink"
labelKey="editor.zaloGroupLink"
label={t("editor.zaloGroupLink")}
maxLength={FIELD_LIMITS.URL}
placeholder={t("editor.zaloGroupLinkPlaceholder")}
value={zaloGroupLink}
onChange={(v) => setField("zaloGroupLink", v)}
validate={validateZaloGroupUrl}
inputMode="url"
autoComplete="off"
/>
)}
</div>
);
}
@@ -0,0 +1,95 @@
import { useTranslation } from "react-i18next";
import { ValidatedInput } from "@components/ui/ValidatedInput";
import { useEditorStore } from "@store/editor-store";
import { useSettingsStore } from "@store/settings-store";
import { validateEmails, canAcceptEmailInput, MAX_EMAILS } from "@utils/validation";
import { FIELD_LIMITS } from "@config/field-limits";
/**
* Contact email input(s). Two modes, driven by the `splitContactEmail`
* settings toggle:
*
* - off (default) — a single "Contact Email" field, exactly as before.
* Feeds the description's single "📧 Business inquiries" line.
* - on — three purpose fields (general / advertising / game keys &
* playtest) that feed the grouped "📧 BUSINESS / CONTACT" block. The
* general field reuses the existing `contactEmail`, so a value entered
* before the toggle was flipped carries over as the Contact address.
*
* Every input allows up to 3 comma-separated addresses via
* {@link validateEmails}, and a malformed value never reaches the
* generated description ({@link ValidatedInput} clears it on error).
*/
export function ContactEmailEditor() {
const { t } = useTranslation("ui");
const contactEmail = useEditorStore((s) => s.contactEmail);
const adEmail = useEditorStore((s) => s.adEmail);
const gameKeyEmail = useEditorStore((s) => s.gameKeyEmail);
const setField = useEditorStore((s) => s.set);
const splitContactEmail = useSettingsStore((s) => s.splitContactEmail);
// Shared by all three fields. The cap is per field, not across the split:
// each one renders its own labelled description line, so filling the
// advertising address must not retroactively invalidate the contact one.
const emailGuard = {
validate: validateEmails,
// Accept the change verbatim, or reject the keystroke with `null` so the
// three addresses already typed survive untouched.
beforeChange: (next: string, prev: string): string | null =>
canAcceptEmailInput(next, prev) ? next : null,
blockedMessage: t("validation.emailMaxReached", { max: MAX_EMAILS }),
maxLength: FIELD_LIMITS.EMAIL_FIELD,
inputMode: "email" as const,
autoComplete: "email",
};
if (!splitContactEmail) {
return (
<ValidatedInput
fieldId="contactEmail"
labelKey="editor.contactEmail"
label={t("editor.contactEmail")}
placeholder={t("editor.contactEmailPlaceholder")}
value={contactEmail ?? ""}
onChange={(v) => setField("contactEmail", v)}
helpText={t("editor.contactEmailHelp")}
{...emailGuard}
/>
);
}
return (
<div className="flex flex-col gap-3">
<ValidatedInput
fieldId="contactEmail"
labelKey="editor.contactEmail"
label={t("editor.contactEmail")}
placeholder={t("editor.contactEmailPlaceholder")}
value={contactEmail ?? ""}
onChange={(v) => setField("contactEmail", v)}
helpText={t("editor.contactEmailHelp")}
{...emailGuard}
/>
<ValidatedInput
fieldId="adEmail"
labelKey="editor.adEmail"
label={t("editor.adEmail")}
placeholder={t("editor.adEmailPlaceholder")}
value={adEmail ?? ""}
onChange={(v) => setField("adEmail", v)}
helpText={t("editor.adEmailHelp")}
{...emailGuard}
/>
<ValidatedInput
fieldId="gameKeyEmail"
labelKey="editor.gameKeyEmail"
label={t("editor.gameKeyEmail")}
placeholder={t("editor.gameKeyEmailPlaceholder")}
value={gameKeyEmail ?? ""}
onChange={(v) => setField("gameKeyEmail", v)}
helpText={t("editor.gameKeyEmailHelp")}
{...emailGuard}
/>
</div>
);
}
@@ -3,10 +3,7 @@ import { useTranslation } from "react-i18next";
import { ChevronDown, ChevronRight, Search, X } from "lucide-react";
import clsx from "clsx";
import { useEditorStore } from "@store/editor-store";
import {
CONTENT_WARNING_GROUPS,
type ContentWarningGroup,
} from "@config/content-warning-groups";
import { CONTENT_WARNING_GROUPS, type ContentWarningGroup } from "@config/content-warning-groups";
import type { ContentWarning } from "@engine/types";
/**
@@ -69,13 +66,9 @@ export function ContentWarningChecklist() {
return (
<div className="flex flex-col gap-2">
<div className="flex items-baseline justify-between">
<span className="text-sm font-medium text-text-secondary">
{t("editor.warnings")}
</span>
<span className="text-sm font-medium text-text-secondary">{t("editor.warnings")}</span>
{selected.length > 0 && (
<span className="text-xs text-text-muted">
{selected.length} selected
</span>
<span className="text-xs text-text-muted">{selected.length} selected</span>
)}
</div>
@@ -108,9 +101,7 @@ export function ContentWarningChecklist() {
<div className="flex flex-col gap-1">
{filteredGroups.map((group) => {
const isOpen = isFiltering || openGroups[group.id];
const groupSelectedCount = group.items.filter((id) =>
selected.includes(id),
).length;
const groupSelectedCount = group.items.filter((id) => selected.includes(id)).length;
return (
<div
key={group.id}
@@ -131,7 +122,7 @@ export function ContentWarningChecklist() {
{t(group.labelKey)}
</span>
{groupSelectedCount > 0 && (
<span className="rounded-full bg-accent/15 px-2 py-0.5 text-[10px] font-medium text-accent">
<span className="bg-accent/15 rounded-full px-2 py-0.5 text-[10px] font-medium text-accent">
{groupSelectedCount}
</span>
)}
@@ -154,7 +145,7 @@ export function ContentWarningChecklist() {
type="checkbox"
checked={checked}
onChange={() => toggleItem(id)}
className="h-3.5 w-3.5 shrink-0 cursor-pointer rounded border-border text-accent focus:ring-1 focus:ring-accent/40"
className="focus:ring-accent/40 h-3.5 w-3.5 shrink-0 cursor-pointer rounded border-border text-accent focus:ring-1"
/>
<span>{t(`editor.contentWarningOptions.${id}`)}</span>
</label>
+17 -32
View File
@@ -4,13 +4,11 @@ import { Plus, Minus, AlertTriangle } from "lucide-react";
import { Input } from "@components/ui/Input";
import { Button } from "@components/ui/Button";
import { Select } from "@components/ui/Select";
import {
useEditorStore,
computeContiguousRanges,
} from "@store/editor-store";
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";
import { FIELD_LIMITS } from "@config/field-limits";
/** Editor cap, matching the original spec ("Giá trị từ 1 - 100"). */
const MAX_ENDINGS = 100;
@@ -78,7 +76,10 @@ export function EndingsEditor() {
const nextEndings: EndingEntry[] =
clamped <= count
? endings.slice(0, clamped)
: [...endings, ...Array.from({ length: clamped - count }, () => ({ number: null, name: "" }))];
: [
...endings,
...Array.from({ length: clamped - count }, () => ({ number: null, name: "" })),
];
set("endings", nextEndings);
// Re-derive endingVideoCount + ranges so the schema invariants
@@ -86,10 +87,7 @@ export function EndingsEditor() {
// 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),
);
set("endingVideoRanges", clamped === 0 ? [] : computeContiguousRanges(clamped, nextVideoCount));
};
/** Update one ending row's number / name. */
@@ -119,9 +117,7 @@ export function EndingsEditor() {
* 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,
);
const next = endingVideoRanges.map((r, idx) => (idx === i ? { ...r, ...patch } : r));
set("endingVideoRanges", next);
};
@@ -206,9 +202,7 @@ export function EndingsEditor() {
)}
</div>
{count === 0 && (
<p className="text-xs text-text-muted">{t("editor.endings.emptyHint")}</p>
)}
{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] && (
@@ -228,6 +222,7 @@ export function EndingsEditor() {
/>
<Input
label={t("editor.endings.nameLabel")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.endings.namePlaceholder")}
value={endings[0].name}
onChange={(e) => updateEnding(0, { name: e.target.value })}
@@ -297,7 +292,7 @@ export function EndingsEditor() {
{/* 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">
<p className="border-warning/40 bg-warning/10 flex items-start gap-1.5 rounded border 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", {
@@ -321,16 +316,12 @@ export function EndingsEditor() {
/>
{isMultiVideo && (
<>
<p className="text-xs text-text-muted">
{t("editor.endings.videoRangeHint")}
</p>
<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">{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>
@@ -345,9 +336,7 @@ export function EndingsEditor() {
min={1}
max={count}
value={String(r.from)}
onChange={(e) =>
updateRange(i, { from: Number(e.target.value) || 1 })
}
onChange={(e) => updateRange(i, { from: Number(e.target.value) || 1 })}
/>
</td>
<td className="px-2 py-1.5">
@@ -356,9 +345,7 @@ export function EndingsEditor() {
min={1}
max={count}
value={String(r.to)}
onChange={(e) =>
updateRange(i, { to: Number(e.target.value) || 1 })
}
onChange={(e) => updateRange(i, { to: Number(e.target.value) || 1 })}
/>
</td>
</tr>
@@ -367,7 +354,7 @@ export function EndingsEditor() {
</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">
<ul className="border-warning/40 bg-warning/10 flex flex-col gap-1 rounded border 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" />
@@ -394,9 +381,7 @@ export function EndingsEditor() {
value={String(Math.min(endingVideoIndex, endingVideoCount))}
onChange={(v) => set("endingVideoIndex", Number(v) || 1)}
/>
<p className="text-xs text-text-muted">
{t("editor.endings.videoIndexHint")}
</p>
<p className="text-xs text-text-muted">{t("editor.endings.videoIndexHint")}</p>
</>
)}
</div>
+21 -25
View File
@@ -10,6 +10,7 @@ import {
type GachaQuestType,
} from "@config/gacha-quest-types";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
const ANNIVERSARY_YEARS = Array.from({ length: 20 }, (_, i) => i + 1);
@@ -32,9 +33,7 @@ export function ExtraFieldsInput() {
const visibility = GACHA_QUEST_FIELD_VISIBILITY[questType];
const placeholders = GACHA_QUEST_PLACEHOLDERS[questType];
const placeholderFor = (
field: "chapterName" | "questName" | "partNumber",
): string => {
const placeholderFor = (field: "chapterName" | "questName" | "partNumber"): string => {
const key = `editor.placeholders.questType.${questType}.${field}`;
const localised = t(key);
if (localised && localised !== key) return localised;
@@ -57,25 +56,17 @@ export function ExtraFieldsInput() {
<div className="flex flex-col gap-3">
{extraFields.includes("gachaQuestType") && (
<div className="flex flex-col gap-1">
<label
htmlFor="gacha-quest-type"
className="text-sm font-medium text-text-secondary"
>
<label htmlFor="gacha-quest-type" className="text-sm font-medium text-text-secondary">
{t("editor.gachaQuestType")}
</label>
<select
id="gacha-quest-type"
value={store.gachaQuestType ?? "main_story"}
onChange={(e) =>
store.set("gachaQuestType", e.target.value as GachaQuestType)
}
className="rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/50"
onChange={(e) => store.set("gachaQuestType", e.target.value as GachaQuestType)}
className="focus:ring-accent/50 rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary transition-colors focus:border-accent focus:outline-none focus:ring-2"
>
{GACHA_QUEST_TYPE_GROUPS.map((g) => (
<optgroup
key={g.group}
label={t(`editor.gachaQuestTypeGroups.${g.group}`)}
>
<optgroup key={g.group} label={t(`editor.gachaQuestTypeGroups.${g.group}`)}>
{g.members.map((m) => (
<option key={m} value={m}>
{t(`editor.gachaQuestTypeOptions.${m}`)}
@@ -89,6 +80,7 @@ export function ExtraFieldsInput() {
{isGacha && visibility.characterName && (
<Input
label={t("editor.characterName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.characterNamePlaceholder")}
value={store.characterName ?? ""}
onChange={(e) => store.set("characterName", e.target.value)}
@@ -96,22 +88,16 @@ export function ExtraFieldsInput() {
)}
{isGacha && visibility.anniversaryYear && (
<div className="flex flex-col gap-1">
<label
htmlFor="anniversary-year"
className="text-sm font-medium text-text-secondary"
>
<label htmlFor="anniversary-year" className="text-sm font-medium text-text-secondary">
{t("editor.anniversaryYear")}
</label>
<select
id="anniversary-year"
value={store.anniversaryYear ?? ""}
onChange={(e) =>
store.set(
"anniversaryYear",
e.target.value === "" ? null : Number(e.target.value),
)
store.set("anniversaryYear", e.target.value === "" ? null : Number(e.target.value))
}
className="rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/50"
className="focus:ring-accent/50 rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary transition-colors focus:border-accent focus:outline-none focus:ring-2"
>
<option value="">—</option>
{ANNIVERSARY_YEARS.map((y) => (
@@ -125,6 +111,7 @@ export function ExtraFieldsInput() {
{showField("chapterName") && (
<Input
label={t("editor.chapterName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={isGacha ? placeholderFor("chapterName") : t("editor.chapterNamePlaceholder")}
value={store.chapterName ?? ""}
onChange={(e) => store.set("chapterName", e.target.value)}
@@ -133,6 +120,7 @@ export function ExtraFieldsInput() {
{showField("questName") && (
<Input
label={t("editor.questName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={isGacha ? placeholderFor("questName") : t("editor.questNamePlaceholder")}
value={store.questName ?? ""}
onChange={(e) => store.set("questName", e.target.value)}
@@ -141,6 +129,7 @@ export function ExtraFieldsInput() {
{showField("partNumber") && (
<Input
label={t("editor.partNumber")}
maxLength={FIELD_LIMITS.NUMERIC}
placeholder={isGacha ? placeholderFor("partNumber") : t("editor.partNumberPlaceholder")}
value={store.partNumber ?? ""}
onChange={(e) => store.set("partNumber", e.target.value)}
@@ -149,6 +138,7 @@ export function ExtraFieldsInput() {
{isGacha && (
<Input
label={t("editor.gachaVersion")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.gachaVersionPlaceholder")}
value={store.gachaVersion ?? ""}
onChange={(e) => store.set("gachaVersion", e.target.value)}
@@ -157,6 +147,7 @@ export function ExtraFieldsInput() {
{extraFields.includes("bossName") && (
<Input
label={t("editor.bossName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.bossNamePlaceholder")}
value={store.bossName ?? ""}
onChange={(e) => store.set("bossName", e.target.value)}
@@ -165,6 +156,7 @@ export function ExtraFieldsInput() {
{extraFields.includes("dlcName") && (
<Input
label={t("editor.dlcName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.dlcNamePlaceholder")}
value={store.dlcName ?? ""}
onChange={(e) => store.set("dlcName", e.target.value)}
@@ -173,6 +165,7 @@ export function ExtraFieldsInput() {
{extraFields.includes("challengeName") && (
<Input
label={t("editor.challengeName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.challengeNamePlaceholder")}
value={store.challengeName ?? ""}
onChange={(e) => store.set("challengeName", e.target.value)}
@@ -182,12 +175,14 @@ export function ExtraFieldsInput() {
<>
<Input
label={t("editor.modName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.modNamePlaceholder")}
value={store.modName ?? ""}
onChange={(e) => store.set("modName", e.target.value)}
/>
<Textarea
label={t("editor.modList")}
maxLength={FIELD_LIMITS.LONG_TEXT}
placeholder={t("editor.modListPlaceholder")}
value={store.modList ?? ""}
onChange={(e) => store.set("modList", e.target.value)}
@@ -198,6 +193,7 @@ export function ExtraFieldsInput() {
{extraFields.includes("liveUrl") && (
<Input
label={t("editor.liveUrl")}
maxLength={FIELD_LIMITS.URL}
placeholder={t("editor.liveUrlPlaceholder")}
value={store.liveUrl ?? ""}
onChange={(e) => store.set("liveUrl", e.target.value)}
@@ -212,7 +208,7 @@ export function ExtraFieldsInput() {
type="datetime-local"
value={store.scheduledTime ?? ""}
onChange={(e) => store.set("scheduledTime", e.target.value)}
className="rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/50"
className="focus:ring-accent/50 rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary transition-colors placeholder:text-text-muted focus:border-accent focus:outline-none focus:ring-2"
/>
</div>
)}
+4
View File
@@ -3,6 +3,7 @@ import { Input } from "@components/ui/Input";
import { Select } from "@components/ui/Select";
import { PLATFORMS } from "@config/platforms";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
/**
* Core identity fields for the video (game name, channel, platform).
@@ -19,6 +20,7 @@ export function GameInfoForm() {
<div className="flex flex-col gap-3">
<Input
label={t("editor.gameName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.gameNamePlaceholder")}
value={store.gameName}
onChange={(e) => store.set("gameName", e.target.value)}
@@ -27,6 +29,7 @@ export function GameInfoForm() {
/>
<Input
label={t("editor.channelName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.channelNamePlaceholder")}
value={store.channelName}
onChange={(e) => store.set("channelName", e.target.value)}
@@ -49,6 +52,7 @@ export function GameInfoForm() {
*/}
<Input
label={t("editor.pubDevName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.pubDevNamePlaceholder")}
value={store.pubDevName ?? ""}
onChange={(e) => store.set("pubDevName", e.target.value)}
+5 -14
View File
@@ -1,12 +1,7 @@
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import { ChipGroup } from "@components/ui/ChipGroup";
import {
GENRES,
GENRE_GROUPS,
GENRE_GROUP_IDS,
type GenreGroupId,
} from "@config/genres";
import { GENRES, GENRE_GROUPS, GENRE_GROUP_IDS, type GenreGroupId } from "@config/genres";
import { GENRES_WITHOUT_GRAPHICS_SETTINGS } from "@config/graphics-settings";
import { useEditorStore } from "@store/editor-store";
import { MAX_GENRES, type Genre } from "@engine/types";
@@ -55,9 +50,7 @@ export function GenreSelector() {
return (
<div className="flex flex-col gap-2">
<div className="flex flex-wrap items-center justify-between gap-2">
<span className="text-sm font-medium text-text-secondary">
{t("editor.genre")}
</span>
<span className="text-sm font-medium text-text-secondary">{t("editor.genre")}</span>
<span className="text-xs text-text-muted">
{genres.length}/{MAX_GENRES}
</span>
@@ -79,12 +72,10 @@ export function GenreSelector() {
value={filter}
onChange={(e) => setFilter(e.target.value)}
placeholder={t("editor.genreSearchPlaceholder")}
className="rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/50"
className="focus:ring-accent/50 rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary transition-colors placeholder:text-text-muted focus:border-accent focus:outline-none focus:ring-2"
/>
{visibleOptions.length === 0 ? (
<p className="py-2 text-sm text-text-muted">
{t("editor.genreSearchNoResults")}
</p>
<p className="py-2 text-sm text-text-muted">{t("editor.genreSearchNoResults")}</p>
) : (
<ChipGroup
multiple
@@ -95,7 +86,7 @@ export function GenreSelector() {
/>
)}
{showHint && (
<div className="flex items-center justify-between gap-3 rounded-lg border border-accent/40 bg-accent/5 px-3 py-2 text-xs text-text-secondary">
<div className="border-accent/40 bg-accent/5 flex items-center justify-between gap-3 rounded-lg border px-3 py-2 text-xs text-text-secondary">
<span>{t("editor.skipGraphicsHintLabel")}</span>
<div className="flex shrink-0 gap-2">
<button
@@ -1,6 +1,7 @@
import { useTranslation } from "react-i18next";
import { Textarea } from "@components/ui/Textarea";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
/**
* Music / sound attribution credit. When non-empty, the engine adds a
@@ -14,6 +15,7 @@ export function MusicAttributionEditor() {
return (
<Textarea
label={t("editor.musicAttribution")}
maxLength={FIELD_LIMITS.LONG_TEXT}
placeholder={t("editor.musicAttributionPlaceholder")}
value={musicAttribution ?? ""}
onChange={(e) => set("musicAttribution", e.target.value)}
@@ -1,6 +1,7 @@
import { useTranslation } from "react-i18next";
import { Textarea } from "@components/ui/Textarea";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
/**
* Template for the pinned comment a creator posts under their own
@@ -15,6 +16,7 @@ export function PinnedCommentEditor() {
return (
<Textarea
label={t("editor.pinnedComment")}
maxLength={FIELD_LIMITS.LONG_TEXT}
placeholder={t("editor.pinnedCommentPlaceholder")}
value={pinnedComment ?? ""}
onChange={(e) => set("pinnedComment", e.target.value)}
+6 -9
View File
@@ -4,15 +4,9 @@ import { ValidatedInput } from "@components/ui/ValidatedInput";
import { Input } from "@components/ui/Input";
import { Select } from "@components/ui/Select";
import { useEditorStore } from "@store/editor-store";
import {
validateUrl,
validateUrlWithPattern,
validateIntegerInRange,
} from "@utils/validation";
import {
PLAYTEST_PLATFORMS,
maxInvitesForPlatform,
} from "@config/playtest-platforms";
import { validateUrl, validateUrlWithPattern, validateIntegerInRange } from "@utils/validation";
import { PLAYTEST_PLATFORMS, maxInvitesForPlatform } from "@config/playtest-platforms";
import { FIELD_LIMITS } from "@config/field-limits";
/**
* Playtest section (v0.30.0). One signup link + the platform it lives on +
@@ -88,7 +82,10 @@ export function PlaytestEditor() {
</span>
<ValidatedInput
fieldId="playtestLink"
labelKey="editor.playtest.linkLabel"
label={t("editor.playtest.linkLabel")}
maxLength={FIELD_LIMITS.URL}
placeholder={platform?.urlPrefix ?? "https://"}
value={playtestLink}
onChange={(v) => setField("playtestLink", v)}
@@ -3,6 +3,7 @@ import { Select } from "@components/ui/Select";
import { Input } from "@components/ui/Input";
import { useEditorStore } from "@store/editor-store";
import { EndingsEditor } from "./EndingsEditor";
import { FIELD_LIMITS } from "@config/field-limits";
import {
PLAYTHROUGH_STATUSES,
DIFFICULTY_LEVELS,
@@ -83,6 +84,7 @@ export function PlaythroughNotesForm() {
{store.difficulty === "custom" && (
<Input
label={t("editor.difficultyCustomLabel")}
maxLength={FIELD_LIMITS.LABEL}
placeholder={t("editor.difficultyCustomPlaceholder")}
value={store.difficultyCustomLabel}
onChange={(e) => store.set("difficultyCustomLabel", e.target.value)}
@@ -105,6 +107,7 @@ export function PlaythroughNotesForm() {
{languagePatchHasCustomSlot(store.languagePatch) && (
<Input
label={t("editor.playthroughNotes.languagePatchCustomLabel")}
maxLength={FIELD_LIMITS.LABEL}
placeholder={t("editor.playthroughNotes.languagePatchCustomPlaceholder")}
value={store.languagePatchCustom}
onChange={(e) => store.set("languagePatchCustom", e.target.value)}
@@ -120,6 +123,7 @@ export function PlaythroughNotesForm() {
{gameVersionHasCustomSlot(store.gameVersion) && (
<Input
label={t("editor.playthroughNotes.gameVersionCustomLabel")}
maxLength={FIELD_LIMITS.LABEL}
placeholder={t("editor.playthroughNotes.gameVersionCustomPlaceholder")}
value={store.gameVersionCustom}
onChange={(e) => store.set("gameVersionCustom", e.target.value)}
+3 -9
View File
@@ -11,12 +11,8 @@ export function QuickPreview() {
<div className="flex flex-col gap-2">
<div>
<span className="text-xs font-medium uppercase text-text-muted">
{t("output.title")}
</span>
<p className="mt-1 text-sm font-medium text-text-primary">
{output.title || "..."}
</p>
<span className="text-xs font-medium uppercase text-text-muted">{t("output.title")}</span>
<p className="mt-1 text-sm font-medium text-text-primary">{output.title || "..."}</p>
</div>
<div>
@@ -32,9 +28,7 @@ export function QuickPreview() {
<span className="text-xs font-medium uppercase text-text-muted">
{t("output.tags")} ({output.tags.length})
</span>
<p className="mt-1 line-clamp-2 text-xs text-text-muted">
{output.tagString || "..."}
</p>
<p className="mt-1 line-clamp-2 text-xs text-text-muted">{output.tagString || "..."}</p>
</div>
</div>
</div>
+9 -17
View File
@@ -13,6 +13,7 @@ import {
} from "@config/rig-fields";
import { GPU_CUSTOM_BRAND_ID, findGpuBrand } from "@config/gpu-catalog";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
import {
validateGpuValue,
validateCompositeField,
@@ -66,10 +67,7 @@ export function RigEditor() {
: [{ value: "", label: "—" }];
const currentSeries = currentBrand?.series.find((s) => s.id === series);
const modelOptions = currentSeries
? [
{ value: "", label: "—" },
...currentSeries.models.map((m) => ({ value: m, label: m })),
]
? [{ value: "", label: "—" }, ...currentSeries.models.map((m) => ({ value: m, label: m }))]
: [{ value: "", label: "—" }];
const setBrand = (next: string) => {
@@ -84,11 +82,7 @@ export function RigEditor() {
setNested("rig", field.id, joinCascading(brand, series, next));
};
const setCustomText = (text: string) => {
setNested(
"rig",
field.id,
text ? joinCascading(GPU_CUSTOM_BRAND_ID, "", text) : "",
);
setNested("rig", field.id, text ? joinCascading(GPU_CUSTOM_BRAND_ID, "", text) : "");
};
return (
@@ -105,6 +99,7 @@ export function RigEditor() {
<div className="col-span-2">
<Input
label={t("editor.gpu_custom")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder="e.g. RTX 4090 (custom OC)"
value={model}
onChange={(e) => setCustomText(e.target.value)}
@@ -141,9 +136,7 @@ export function RigEditor() {
// Validate per field — only RAM has size/DDR semantics. Running the
// RAM validator on the OS composite mis-fired "Pick a DDR generation."
const issue = validateCompositeField(field.id, raw);
const partValues = field.composite.parts.map(
(_p, i) => storedParts[i] ?? "",
);
const partValues = field.composite.parts.map((_p, i) => storedParts[i] ?? "");
// v0.23.0: setting a part also resets all downstream parts to "" so
// a cascading parent change can't leave the form with a stale child
@@ -181,9 +174,7 @@ export function RigEditor() {
return (
<div key={field.id} className="col-span-2 flex flex-col gap-2">
<span className="text-sm font-medium text-text-secondary">{t(field.labelKey)}</span>
<div className="grid grid-cols-2 gap-2">
{renderedParts}
</div>
<div className="grid grid-cols-2 gap-2">{renderedParts}</div>
{renderValidationBadge(issue)}
</div>
);
@@ -247,8 +238,7 @@ export function RigEditor() {
const commit = (nextValue: string, nextVersion: string) => {
// Keep the stored form compact: drop the pipe when empty.
const next =
!nextValue && !nextVersion ? "" : `${nextValue}|${nextVersion}`;
const next = !nextValue && !nextVersion ? "" : `${nextValue}|${nextVersion}`;
setNested("rig", field.id, next);
};
@@ -262,6 +252,7 @@ export function RigEditor() {
/>
<Input
label={t("editor.version")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={field.versionPlaceholder}
value={version}
onChange={(e) => commit(value, e.target.value)}
@@ -282,6 +273,7 @@ export function RigEditor() {
<Input
key={field.id}
label={t(field.labelKey)}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={field.placeholder}
value={rig[field.id] ?? ""}
onChange={(e) => setNested("rig", field.id, e.target.value)}
+7
View File
@@ -3,6 +3,7 @@ import { ValidatedInput } from "@components/ui/ValidatedInput";
import { SOCIAL_FIELDS } from "@config/social-fields";
import { useEditorStore } from "@store/editor-store";
import { validateUrl, validateUrlWithPrefix } from "@utils/validation";
import { FIELD_LIMITS } from "@config/field-limits";
export function SocialEditor() {
const { t } = useTranslation("ui");
@@ -21,8 +22,11 @@ export function SocialEditor() {
{donateFields.map((field) => (
<ValidatedInput
key={field.id}
fieldId={`social.${field.id}`}
labelKey={field.labelKey}
label={t(field.labelKey)}
placeholder={field.urlPrefix || "URL"}
maxLength={FIELD_LIMITS.URL}
value={social[field.id] ?? ""}
onChange={(v) => setNested("social", field.id, v)}
validate={(v) =>
@@ -37,8 +41,11 @@ export function SocialEditor() {
{socialFields.map((field) => (
<ValidatedInput
key={field.id}
fieldId={`social.${field.id}`}
labelKey={field.labelKey}
label={t(field.labelKey)}
placeholder={field.urlPrefix || "URL"}
maxLength={FIELD_LIMITS.URL}
value={social[field.id] ?? ""}
onChange={(v) => setNested("social", field.id, v)}
validate={(v) =>
@@ -1,6 +1,7 @@
import { useTranslation } from "react-i18next";
import { Input } from "@components/ui/Input";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
/**
* Publisher/developer + platform pair for the "🎁 Thanks to …" credit
@@ -17,12 +18,14 @@ export function SponsorCreditEditor() {
<div className="flex flex-col gap-2">
<Input
label={t("editor.sponsorName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.sponsorNamePlaceholder")}
value={sponsorName ?? ""}
onChange={(e) => set("sponsorName", e.target.value)}
/>
<Input
label={t("editor.sponsorPlatform")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.sponsorPlatformPlaceholder")}
value={sponsorPlatform ?? ""}
onChange={(e) => set("sponsorPlatform", e.target.value)}
+8 -11
View File
@@ -7,11 +7,9 @@ import { Select } from "@components/ui/Select";
import { PLATFORMS } from "@config/platforms";
import { useEditorStore } from "@store/editor-store";
import { validateUrlWithPattern } from "@utils/validation";
import {
extractGameNameFromUrl,
isLinkNameMismatch,
} from "@utils/url-extractors";
import { extractGameNameFromUrl, isLinkNameMismatch } from "@utils/url-extractors";
import type { StoreLinkType } from "@engine/types";
import { FIELD_LIMITS } from "@config/field-limits";
const STORE_LINK_TYPE_VALUES: readonly StoreLinkType[] = ["paid", "free", "demo"];
@@ -30,9 +28,9 @@ export function StoreLinkEditor() {
const setNested = useEditorStore((s) => s.setNested);
const setStoreLinkType = useEditorStore((s) => s.setStoreLinkType);
const [dismissedFingerprints, setDismissedFingerprints] = useState<
ReadonlySet<string>
>(new Set());
const [dismissedFingerprints, setDismissedFingerprints] = useState<ReadonlySet<string>>(
new Set(),
);
const typeOptions = STORE_LINK_TYPE_VALUES.map((value) => ({
value,
@@ -135,13 +133,12 @@ export function StoreLinkEditor() {
// the optional game-copyright description line independently
// of whether the publisher URL is filled.
return (
<div
key={platform.id}
className="grid grid-cols-[1fr_9rem] items-end gap-2"
>
<div key={platform.id} className="grid grid-cols-[1fr_9rem] items-end gap-2">
<ValidatedInput
fieldId={`storeLinks.${platform.id}`}
label={platform.label}
placeholder={platform.urlPrefix}
maxLength={FIELD_LIMITS.URL}
value={url}
onChange={(v) => {
const final = v && platform.normalize ? platform.normalize(v) : v;
+7 -18
View File
@@ -3,10 +3,7 @@ import { useTranslation } from "react-i18next";
import { ChevronDown, ChevronRight, Search, X } from "lucide-react";
import clsx from "clsx";
import { useEditorStore } from "@store/editor-store";
import {
TECH_NOTE_GROUPS,
type TechNoteGroup,
} from "@config/tech-note-groups";
import { TECH_NOTE_GROUPS, type TechNoteGroup } from "@config/tech-note-groups";
import type { TechNote } from "@engine/types";
/**
@@ -70,13 +67,9 @@ export function TechNotesChecklist() {
return (
<div className="flex flex-col gap-2">
<div className="flex items-baseline justify-between">
<span className="text-sm font-medium text-text-secondary">
{t("editor.techNotes")}
</span>
<span className="text-sm font-medium text-text-secondary">{t("editor.techNotes")}</span>
{selected.length > 0 && (
<span className="text-xs text-text-muted">
{selected.length} selected
</span>
<span className="text-xs text-text-muted">{selected.length} selected</span>
)}
</div>
@@ -102,16 +95,12 @@ export function TechNotesChecklist() {
</div>
{isFiltering && totalMatching === 0 ? (
<p className="py-2 text-center text-xs text-text-muted">
{t("editor.techNoteEmpty")}
</p>
<p className="py-2 text-center text-xs text-text-muted">{t("editor.techNoteEmpty")}</p>
) : (
<div className="flex flex-col gap-1">
{filteredGroups.map((group) => {
const isOpen = isFiltering || openGroups[group.id];
const groupSelectedCount = group.items.filter((id) =>
selected.includes(id),
).length;
const groupSelectedCount = group.items.filter((id) => selected.includes(id)).length;
return (
<div
key={group.id}
@@ -132,7 +121,7 @@ export function TechNotesChecklist() {
{t(group.labelKey)}
</span>
{groupSelectedCount > 0 && (
<span className="rounded-full bg-accent/15 px-2 py-0.5 text-[10px] font-medium text-accent">
<span className="bg-accent/15 rounded-full px-2 py-0.5 text-[10px] font-medium text-accent">
{groupSelectedCount}
</span>
)}
@@ -155,7 +144,7 @@ export function TechNotesChecklist() {
type="checkbox"
checked={checked}
onChange={() => toggleItem(id)}
className="h-3.5 w-3.5 shrink-0 cursor-pointer rounded border-border text-accent focus:ring-1 focus:ring-accent/40"
className="focus:ring-accent/40 h-3.5 w-3.5 shrink-0 cursor-pointer rounded border-border text-accent focus:ring-1"
/>
<span>{t(`editor.techNoteOptions.${id}`)}</span>
</label>
@@ -1,6 +1,7 @@
import { useTranslation } from "react-i18next";
import { Textarea } from "@components/ui/Textarea";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
/**
* Free-form draft for the thumbnail text overlay. Never lands in the
@@ -15,6 +16,7 @@ export function ThumbnailHelper() {
return (
<Textarea
label={t("editor.thumbnailText")}
maxLength={FIELD_LIMITS.LONG_TEXT}
placeholder={t("editor.thumbnailTextPlaceholder")}
value={thumbnailText ?? ""}
onChange={(e) => set("thumbnailText", e.target.value)}
@@ -1,6 +1,7 @@
import { useTranslation } from "react-i18next";
import { Textarea } from "@components/ui/Textarea";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
export function TimestampEditor() {
const { t } = useTranslation("ui");
@@ -10,6 +11,7 @@ export function TimestampEditor() {
return (
<Textarea
label={t("editor.timestamps")}
maxLength={FIELD_LIMITS.TIMESTAMPS}
placeholder={t("editor.timestampsPlaceholder")}
value={timestamps ?? ""}
onChange={(e) => set("timestamps", e.target.value)}
@@ -23,6 +23,7 @@ import {
coerceFrameGenMultiplier,
} from "@engine/graphics-vendor";
import { VIDEO_STYLE_ERA_IDS, type VideoStyleEra } from "@config/video-styles";
import { FIELD_LIMITS } from "@config/field-limits";
const RESOLUTION_OPTIONS = [
{ value: "720p", label: "720p" },
@@ -137,6 +138,7 @@ export function VideoSettingsForm() {
{store.graphicsPreset === "custom" && (
<Input
label={t("editor.graphicsPresetCustom")}
maxLength={FIELD_LIMITS.LABEL}
placeholder={t("editor.graphicsPresetCustomPlaceholder")}
value={store.graphicsPresetCustom}
onChange={(e) => store.set("graphicsPresetCustom", e.target.value)}
@@ -200,6 +202,7 @@ export function VideoSettingsForm() {
<Input
label={t("editor.versionInfo")}
maxLength={FIELD_LIMITS.LABEL}
placeholder={t("editor.versionInfoPlaceholder")}
value={store.versionInfo}
onChange={(e) => store.set("versionInfo", e.target.value)}
@@ -3,6 +3,7 @@ import { useTranslation } from "react-i18next";
import { Input } from "@components/ui/Input";
import { Select } from "@components/ui/Select";
import { useEditorStore } from "@store/editor-store";
import { FIELD_LIMITS } from "@config/field-limits";
import {
VIETNAMESE_BANKS,
VIETNAMESE_BANK_OTHER,
@@ -48,11 +49,8 @@ export function VietnameseDonateEditor() {
() => isVi && isCustomVietnameseBank(vnBankName ?? ""),
);
const customMode =
isVi && (otherSticky || isCustomVietnameseBank(vnBankName ?? ""));
const selectValue = customMode
? VIETNAMESE_BANK_OTHER
: (vnBankName ?? "");
const customMode = isVi && (otherSticky || isCustomVietnameseBank(vnBankName ?? ""));
const selectValue = customMode ? VIETNAMESE_BANK_OTHER : (vnBankName ?? "");
const bankOptions = [
{ value: "", label: t("editor.vnBankNameSelectPlaceholder") },
@@ -63,9 +61,7 @@ export function VietnameseDonateEditor() {
return (
<div className="flex flex-col gap-3">
<div className="flex flex-col gap-1">
<span className="text-sm font-medium text-text-secondary">
{t("editor.vnDonate")}
</span>
<span className="text-sm font-medium text-text-secondary">{t("editor.vnDonate")}</span>
<p className="text-xs text-text-muted">{t("editor.vnDonateHelp")}</p>
</div>
@@ -98,6 +94,7 @@ export function VietnameseDonateEditor() {
) : (
<Input
label={t("editor.vnBankName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.vnBankNamePlaceholder")}
value={vnBankName ?? ""}
onChange={(e) => store.set("vnBankName", e.target.value)}
@@ -105,6 +102,7 @@ export function VietnameseDonateEditor() {
)}
<Input
label={t("editor.vnBankAccount")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.vnBankAccountPlaceholder")}
value={store.vnBankAccount ?? ""}
onChange={(e) => store.set("vnBankAccount", e.target.value)}
@@ -113,6 +111,7 @@ export function VietnameseDonateEditor() {
<Input
label={t("editor.vnBankHolder")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.vnBankHolderPlaceholder")}
value={store.vnBankHolder ?? ""}
onChange={(e) => store.set("vnBankHolder", e.target.value)}
@@ -121,12 +120,14 @@ export function VietnameseDonateEditor() {
<div className="grid grid-cols-2 gap-3">
<Input
label={t("editor.vnMomo")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.vnMomoPlaceholder")}
value={store.vnMomo ?? ""}
onChange={(e) => store.set("vnMomo", e.target.value)}
/>
<Input
label={t("editor.vnZalopay")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.vnZalopayPlaceholder")}
value={store.vnZalopay ?? ""}
onChange={(e) => store.set("vnZalopay", e.target.value)}
+3 -3
View File
@@ -55,7 +55,7 @@ function FullscreenError({ kind }: ErrorPageProps) {
<div className="flex min-h-screen flex-col items-center justify-center gap-6 bg-surface-0 px-6 py-12 text-center">
<Icon className={clsx("h-16 w-16", colour)} aria-hidden />
{meta.code !== null && (
<p className={clsx("font-mono text-6xl font-bold leading-none tabular-nums", colour)}>
<p className={clsx("font-mono text-6xl font-bold tabular-nums leading-none", colour)}>
{meta.code}
</p>
)}
@@ -99,7 +99,7 @@ function ContainedError({ kind, onReset, detail }: ErrorPageProps) {
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="border-danger/40 w-full max-w-md rounded-lg border bg-surface-2 p-5 shadow-md shadow-black/10">
<div className={clsx("mb-3 flex items-center gap-2", colour)}>
<Icon className="h-4 w-4" />
<h2 className="text-sm font-semibold">{title}</h2>
@@ -140,7 +140,7 @@ function ReportBugLink({ size = "md" }: { size?: "sm" | "md" }) {
target="_blank"
rel="noopener noreferrer"
className={clsx(
"inline-flex items-center justify-center gap-2 rounded-lg font-medium text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary focus:outline-none focus:ring-2 focus:ring-accent/50",
"focus:ring-accent/50 inline-flex items-center justify-center gap-2 rounded-lg font-medium text-text-secondary transition-colors hover:bg-surface-2 hover:text-text-primary focus:outline-none focus:ring-2",
sizeClass,
)}
>
+1 -1
View File
@@ -35,7 +35,7 @@ export function OfflineBanner() {
return (
<div
role="status"
className="fixed inset-x-0 bottom-0 z-50 flex items-center justify-center gap-3 border-t border-warning/40 bg-surface-2 px-4 py-2 text-sm text-text-primary shadow-md shadow-black/20"
className="border-warning/40 fixed inset-x-0 bottom-0 z-50 flex items-center justify-center gap-3 border-t bg-surface-2 px-4 py-2 text-sm text-text-primary shadow-md shadow-black/20"
>
<WifiOff className="h-4 w-4 shrink-0 text-warning" aria-hidden />
<span>{t("errorPages.offlineBanner.message")}</span>
+1 -1
View File
@@ -19,7 +19,7 @@ export function HistoryCard({ entry }: HistoryCardProps) {
const date = new Date(entry.createdAt).toLocaleDateString();
return (
<div className="rounded-lg border border-border-strong bg-surface-2 shadow-md shadow-black/10 transition-colors hover:border-accent/30">
<div className="hover:border-accent/30 rounded-lg border border-border-strong bg-surface-2 shadow-md shadow-black/10 transition-colors">
<div
className="flex cursor-pointer items-center justify-between p-3"
onClick={() => setExpanded(!expanded)}
+4 -12
View File
@@ -37,9 +37,7 @@ export function Header({ onOpenMobileNav }: HeaderProps) {
};
return (
<header
className="flex items-center justify-between gap-2 border-b border-border bg-surface-1 px-3 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] sm:px-6"
>
<header className="flex items-center justify-between gap-2 border-b border-border bg-surface-1 px-3 py-3 pt-[max(0.75rem,env(safe-area-inset-top))] sm:px-6">
<div className="flex min-w-0 items-center gap-2">
{onOpenMobileNav && (
<button
@@ -55,9 +53,7 @@ export function Header({ onOpenMobileNav }: HeaderProps) {
<h1 className="truncate text-base font-bold text-text-primary sm:text-lg">
{t("app.title")}
</h1>
<p className="hidden truncate text-xs text-text-muted sm:block">
{t("app.subtitle")}
</p>
<p className="hidden truncate text-xs text-text-muted sm:block">{t("app.subtitle")}</p>
</div>
</div>
<div className="flex shrink-0 items-center gap-2">
@@ -79,11 +75,7 @@ export function Header({ onOpenMobileNav }: HeaderProps) {
title={t("header.toggleTheme")}
aria-label={t("header.toggleTheme")}
>
{theme === "dark" ? (
<Moon className="h-4 w-4" />
) : (
<Sun className="h-4 w-4" />
)}
{theme === "dark" ? <Moon className="h-4 w-4" /> : <Sun className="h-4 w-4" />}
</button>
<div className="relative" ref={dropdownRef}>
<button
@@ -97,7 +89,7 @@ export function Header({ onOpenMobileNav }: HeaderProps) {
<ChevronDown className="h-3.5 w-3.5 text-text-muted" />
</button>
{open && (
<div className="absolute right-0 top-full z-50 mt-1 max-w-[calc(100vw-2rem)] min-w-[200px] rounded-lg border border-border bg-surface-1 py-1 shadow-xl">
<div className="absolute right-0 top-full z-50 mt-1 min-w-[200px] max-w-[calc(100vw-2rem)] rounded-lg border border-border bg-surface-1 py-1 shadow-xl">
{SUPPORTED_LANGUAGES.map((lang) => (
<button
key={lang.id}
+1 -3
View File
@@ -50,9 +50,7 @@ export function ScrollToTopButton({ scrollRef }: ScrollToTopButtonProps) {
function scrollToTop() {
const el = scrollRef.current;
if (!el) return;
const reduceMotion = window.matchMedia(
"(prefers-reduced-motion: reduce)",
).matches;
const reduceMotion = window.matchMedia("(prefers-reduced-motion: reduce)").matches;
el.scrollTo({ top: 0, behavior: reduceMotion ? "auto" : "smooth" });
}
+1 -5
View File
@@ -121,11 +121,7 @@ export function Sidebar() {
title={t(collapsed ? "sidebar.expand" : "sidebar.collapse")}
className="flex h-12 items-center justify-center border-b border-border text-text-muted transition-colors hover:bg-surface-2 hover:text-text-primary"
>
{collapsed ? (
<PanelLeftOpen className="h-5 w-5" />
) : (
<PanelLeftClose className="h-5 w-5" />
)}
{collapsed ? <PanelLeftOpen className="h-5 w-5" /> : <PanelLeftClose className="h-5 w-5" />}
</button>
<SidebarNavList collapsed={collapsed} />
</aside>
+2 -2
View File
@@ -19,10 +19,10 @@ export function CharCounter({ text, limit }: CharCounterProps) {
return (
<span
className={clsx(
"text-xs font-mono font-semibold transition-colors",
"font-mono text-xs font-semibold transition-colors",
isOver && "text-danger",
isWarning && "text-warning",
!isOver && !isWarning && "text-text-muted font-normal",
!isOver && !isWarning && "font-normal text-text-muted",
)}
>
{count}/{limit}
+33 -46
View File
@@ -1,61 +1,48 @@
import { useTranslation } from "react-i18next";
import toast from "react-hot-toast";
import { ClipboardCopy } from "lucide-react";
import { Button } from "@components/ui/Button";
import { useGeneratedOutput } from "@hooks/use-generated-output";
import { useClipboard } from "@hooks/use-clipboard";
import { YT_LIMITS } from "@engine/types";
import { LimitBlockBanner } from "./LimitBlockBanner";
import type { OutputLimitStatus } from "@engine/limits";
interface CopyAllBarProps {
extraText?: string;
/** Exactly what gets copied — the caller decides single vs multi-language. */
text: string;
/**
* Over-limit status of every output contributing to `text`. The bar copies a
* concatenation, so one offending language blocks the blob.
*/
status: OutputLimitStatus;
}
export function CopyAllBar({ extraText }: CopyAllBarProps) {
/**
* Sticky "copy everything" bar.
*
* Before v0.35.0 this owned its own over-limit check — which skipped tags, and
* more importantly bailed out entirely when an `extraText` prop was present.
* That prop was set by exactly one caller: OutputPage, whenever more than one
* language was selected. So selecting a second language silently turned off
* every limit check on the primary copy path. The bar no longer decides
* anything; it renders the status the page computes.
*/
export function CopyAllBar({ text, status }: CopyAllBarProps) {
const { t } = useTranslation("ui");
const output = useGeneratedOutput();
const { copy } = useClipboard();
const handleCopyAll = () => {
if (extraText) {
copy(extraText);
return;
}
const overflows: string[] = [];
if (output.title.length > YT_LIMITS.TITLE_MAX) {
overflows.push(
t("output.copy.overLimit", {
field: t("output.title"),
count: output.title.length,
limit: YT_LIMITS.TITLE_MAX,
}),
);
}
if (output.description.length > YT_LIMITS.DESCRIPTION_MAX) {
overflows.push(
t("output.copy.overLimit", {
field: t("output.description"),
count: output.description.length,
limit: YT_LIMITS.DESCRIPTION_MAX,
}),
);
}
if (overflows.length > 0) {
toast.error(overflows.join("\n"));
return;
}
copy(`${output.title}\n\n${output.description}`);
};
return (
<div className="sticky bottom-0 flex items-center justify-end border-t border-border bg-surface-0 px-3 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-4">
<Button
onClick={handleCopyAll}
size="lg"
className="text-sm sm:text-base"
>
<ClipboardCopy className="h-4 w-4" />
{t("output.copyAll")}
</Button>
<div className="sticky bottom-0 flex flex-col gap-2 border-t border-border bg-surface-0 px-3 py-3 pb-[max(0.75rem,env(safe-area-inset-bottom))] sm:px-4">
<LimitBlockBanner status={status} />
<div className="flex items-center justify-end">
<Button
onClick={() => void copy(text)}
disabled={status.blocked || !text}
size="lg"
className="text-sm sm:text-base"
>
<ClipboardCopy className="h-4 w-4" />
{t("output.copyAll")}
</Button>
</div>
</div>
);
}
+24 -7
View File
@@ -1,4 +1,5 @@
import { Copy, Check, AlertTriangle } from "lucide-react";
import { useTranslation } from "react-i18next";
import clsx from "clsx";
import { Button } from "@components/ui/Button";
import { useClipboard } from "@hooks/use-clipboard";
@@ -8,29 +9,45 @@ interface CopyButtonProps {
label: string;
limit?: number;
fieldLabel?: string;
/**
* Disable the button because *some* field in this output is over its limit —
* not necessarily this one.
*
* The rule is all-or-nothing per output: if the description is 200 characters
* too long, copying the title is blocked too. Copying two of three fields and
* silently leaving the third behind is how a half-populated video description
* gets published.
*/
blocked?: boolean;
}
export function CopyButton({ text, label, limit, fieldLabel }: CopyButtonProps) {
export function CopyButton({ text, label, limit, fieldLabel, blocked }: CopyButtonProps) {
const { t } = useTranslation("ui");
const { copy, copied } = useClipboard();
const isOver = limit !== undefined && text.length > limit;
const disabled = !text || blocked;
return (
<Button
variant="ghost"
size="sm"
onClick={() => copy(text, { limit, fieldLabel })}
disabled={!text}
className={clsx(isOver && "text-danger hover:bg-surface-2 hover:text-danger")}
title={isOver ? `${text.length}/${limit}` : undefined}
// `useClipboard` still re-checks `limit` as a backstop, for any call site
// that passes a limit without wiring `blocked`.
onClick={() => void copy(text, { limit, fieldLabel })}
disabled={disabled}
className={clsx((isOver || blocked) && "text-danger hover:bg-surface-2 hover:text-danger")}
title={
blocked ? t("output.limits.copyBlocked") : isOver ? `${text.length}/${limit}` : undefined
}
>
{isOver ? (
{isOver || blocked ? (
<AlertTriangle className="h-4 w-4" />
) : copied ? (
<Check className="h-4 w-4" />
) : (
<Copy className="h-4 w-4" />
)}
{copied ? "Copied!" : label}
{copied ? t("output.copied") : label}
</Button>
);
}
@@ -0,0 +1,45 @@
import { AlertTriangle } from "lucide-react";
import { useTranslation } from "react-i18next";
import type { OutputLimitStatus } from "@engine/limits";
interface LimitBlockBannerProps {
status: OutputLimitStatus;
/** Optional override for the heading — Batch uses a Copy-All-specific one. */
titleKey?: string;
}
/**
* Explains why copying is disabled, naming each offending field with its count.
*
* Without this, a disabled Copy button is just a dead control. The counts come
* from the engine's warnings rather than `CharLimitWarning.message`, which is a
* hardcoded English string.
*/
export function LimitBlockBanner({ status, titleKey }: LimitBlockBannerProps) {
const { t } = useTranslation("ui");
if (!status.blocked) return null;
return (
<div
role="alert"
className="border-danger/40 bg-danger/10 flex flex-col gap-1 rounded-lg border px-3 py-2 text-xs text-danger"
>
<span className="flex items-center gap-1.5 font-semibold">
<AlertTriangle className="h-3.5 w-3.5 shrink-0" />
{t(titleKey ?? "output.limits.bannerTitle")}
</span>
<ul className="flex flex-col gap-0.5 pl-5">
{status.overflows.map((o) => (
<li key={o.field}>
{t("output.limits.fieldLine", {
field: t(`output.${o.field}`),
count: o.current,
limit: o.limit,
})}
</li>
))}
</ul>
<span className="text-text-muted">{t("output.limits.bannerHint")}</span>
</div>
);
}
+3 -9
View File
@@ -27,9 +27,7 @@ export function OutputExtras() {
const pinnedComment = useEditorStore((s) => s.pinnedComment);
const showPinnedCommentTemplate = useSettingsStore((s) => s.showPinnedCommentTemplate);
const includeAskNextGame = useSettingsStore((s) => s.pinnedCommentIncludeAskNextGame);
const includeGenrePlaylist = useSettingsStore(
(s) => s.pinnedCommentIncludeGenrePlaylist,
);
const includeGenrePlaylist = useSettingsStore((s) => s.pinnedCommentIncludeGenrePlaylist);
const genrePlaylists = useSettingsStore((s) => s.genrePlaylists);
const input = useCurrentGeneratorInput();
@@ -75,9 +73,7 @@ export function OutputExtras() {
{hasThumbnail && (
<section className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-text-primary">
{t("output.thumbnailText")}
</h3>
<h3 className="text-sm font-semibold text-text-primary">{t("output.thumbnailText")}</h3>
<CopyButton text={thumbnailText} label={t("output.copyThumbnailText")} />
</div>
<div className="rounded-lg border border-border bg-surface-1 p-3">
@@ -91,9 +87,7 @@ export function OutputExtras() {
{hasPinned && (
<section className="flex flex-col gap-2">
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-text-primary">
{t("output.pinnedComment")}
</h3>
<h3 className="text-sm font-semibold text-text-primary">{t("output.pinnedComment")}</h3>
<CopyButton text={pinnedComment} label={t("output.copyPinnedComment")} />
</div>
<div className="rounded-lg border border-border bg-surface-1 p-3">
+14 -2
View File
@@ -5,12 +5,19 @@ import { CopyButton } from "./CopyButton";
import { CharCounter } from "./CharCounter";
import { YT_LIMITS } from "@engine/types";
import type { GeneratorOutput } from "@engine/types";
import type { OutputLimitStatus } from "@engine/limits";
interface OutputPreviewProps {
output?: GeneratorOutput;
/**
* Over-limit status of the output actually shown. All three copy buttons are
* gated on it together — see `CopyButton.blocked` for why it is
* all-or-nothing rather than per field.
*/
status: OutputLimitStatus;
}
export function OutputPreview({ output: outputProp }: OutputPreviewProps) {
export function OutputPreview({ output: outputProp, status }: OutputPreviewProps) {
const { t } = useTranslation("ui");
const defaultOutput = useGeneratedOutput();
const { showCharCount, compactTagDisplay } = useSettingsStore();
@@ -29,6 +36,7 @@ export function OutputPreview({ output: outputProp }: OutputPreviewProps) {
label={t("output.copyTitle")}
limit={YT_LIMITS.TITLE_MAX}
fieldLabel={t("output.title")}
blocked={status.blocked}
/>
</div>
</div>
@@ -42,12 +50,15 @@ export function OutputPreview({ output: outputProp }: OutputPreviewProps) {
<div className="flex items-center justify-between">
<h3 className="text-sm font-semibold text-text-primary">{t("output.description")}</h3>
<div className="flex items-center gap-3">
{showCharCount && <CharCounter text={output.description} limit={YT_LIMITS.DESCRIPTION_MAX} />}
{showCharCount && (
<CharCounter text={output.description} limit={YT_LIMITS.DESCRIPTION_MAX} />
)}
<CopyButton
text={output.description}
label={t("output.copyDescription")}
limit={YT_LIMITS.DESCRIPTION_MAX}
fieldLabel={t("output.description")}
blocked={status.blocked}
/>
</div>
</div>
@@ -71,6 +82,7 @@ export function OutputPreview({ output: outputProp }: OutputPreviewProps) {
label={t("output.copyTags")}
limit={YT_LIMITS.TAGS_MAX}
fieldLabel={t("output.tags")}
blocked={status.blocked}
/>
</div>
</div>
+6 -1
View File
@@ -82,7 +82,12 @@ export function VariantPicker({ open, onClose }: VariantPickerProps) {
]);
return (
<Modal open={open} onClose={onClose} title={t("output.generateAlternatives")} className="max-w-2xl">
<Modal
open={open}
onClose={onClose}
title={t("output.generateAlternatives")}
className="max-w-2xl"
>
<div className="flex flex-col gap-4">
{variants.map((variant) => (
<section key={variant.id} className="flex flex-col gap-2">
+2 -6
View File
@@ -46,7 +46,7 @@ export function PresetCard({ preset }: PresetCardProps) {
return (
<>
<div className="flex flex-col gap-3 rounded-lg border border-border-strong bg-surface-2 p-4 shadow-md shadow-black/10 transition-colors hover:border-accent/30 sm:flex-row sm:items-center sm:justify-between">
<div className="hover:border-accent/30 flex flex-col gap-3 rounded-lg border border-border-strong bg-surface-2 p-4 shadow-md shadow-black/10 transition-colors sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 flex-1">
<h3 className="text-sm font-semibold text-text-primary">{preset.gameName}</h3>
<div className="mt-1.5 flex flex-wrap items-center gap-1.5 text-xs text-text-muted">
@@ -85,11 +85,7 @@ export function PresetCard({ preset }: PresetCardProps) {
variant="danger"
/>
<PresetSaveForm
open={showEdit}
onClose={() => setShowEdit(false)}
editPreset={preset}
/>
<PresetSaveForm open={showEdit} onClose={() => setShowEdit(false)} editPreset={preset} />
</>
);
}
@@ -6,6 +6,7 @@ import { Input } from "@components/ui/Input";
import { useEditorStore } from "@store/editor-store";
import { useSettingsStore } from "@store/settings-store";
import { usePresetStore, type GamePreset } from "@store/preset-store";
import { FIELD_LIMITS } from "@config/field-limits";
interface PresetSaveFormProps {
open: boolean;
@@ -59,6 +60,7 @@ export function PresetSaveForm({ open, onClose, editPreset }: PresetSaveFormProp
<div className="flex flex-col gap-3">
<Input
label={t("editor.gameName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("editor.gameNamePlaceholder")}
value={gameName}
onChange={(e) => setGameName(e.target.value)}
+3 -1
View File
@@ -40,5 +40,7 @@ export function PresetSelector() {
}
};
return <Select label={t("presets.selectPreset")} options={options} value="" onChange={handleSelect} />;
return (
<Select label={t("presets.selectPreset")} options={options} value="" onChange={handleSelect} />
);
}
+7 -7
View File
@@ -27,6 +27,8 @@ export function ProfileCard({ profile }: ProfileCardProps) {
loadProfile({
channelName: profile.channelName,
contactEmail: profile.contactEmail,
adEmail: profile.adEmail ?? "",
gameKeyEmail: profile.gameKeyEmail ?? "",
social: { ...(profile.social ?? {}) },
rig: { ...(profile.rig ?? {}) },
resolution: profile.resolution,
@@ -43,10 +45,12 @@ export function ProfileCard({ profile }: ProfileCardProps) {
return (
<>
<div className="flex flex-col gap-3 rounded-lg border border-border-strong bg-surface-2 p-4 shadow-md shadow-black/10 transition-colors hover:border-accent/30 sm:flex-row sm:items-center sm:justify-between">
<div className="hover:border-accent/30 flex flex-col gap-3 rounded-lg border border-border-strong bg-surface-2 p-4 shadow-md shadow-black/10 transition-colors sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 flex-1">
<h3 className="text-sm font-semibold text-text-primary">{profile.name}</h3>
<p className="mt-0.5 text-xs text-text-secondary">{profile.channelName || "No channel"}</p>
<p className="mt-0.5 text-xs text-text-secondary">
{profile.channelName || "No channel"}
</p>
<div className="mt-1.5 flex flex-wrap gap-3 text-xs text-text-muted">
{socialCount > 0 && <span>{socialCount} social links</span>}
{rigCount > 0 && <span>{rigCount} rig fields</span>}
@@ -79,11 +83,7 @@ export function ProfileCard({ profile }: ProfileCardProps) {
variant="danger"
/>
<ProfileSaveForm
open={showEdit}
onClose={() => setShowEdit(false)}
editProfile={profile}
/>
<ProfileSaveForm open={showEdit} onClose={() => setShowEdit(false)} editProfile={profile} />
</>
);
}
@@ -6,6 +6,7 @@ import { Input } from "@components/ui/Input";
import { Textarea } from "@components/ui/Textarea";
import { useEditorStore } from "@store/editor-store";
import { useProfileStore, type Profile } from "@store/profile-store";
import { FIELD_LIMITS } from "@config/field-limits";
interface ProfileSaveFormProps {
open: boolean;
@@ -34,6 +35,8 @@ export function ProfileSaveForm({ open, onClose, editProfile }: ProfileSaveFormP
name: name.trim() || "Unnamed Profile",
channelName: editProfile?.channelName ?? editor.channelName,
contactEmail: editProfile?.contactEmail ?? editor.contactEmail,
adEmail: editProfile?.adEmail ?? editor.adEmail,
gameKeyEmail: editProfile?.gameKeyEmail ?? editor.gameKeyEmail,
social: editProfile?.social ?? { ...editor.social },
rig: editProfile?.rig ?? { ...editor.rig },
resolution: editProfile?.resolution ?? editor.resolution,
@@ -67,6 +70,7 @@ export function ProfileSaveForm({ open, onClose, editProfile }: ProfileSaveFormP
<div className="flex flex-col gap-3">
<Input
label={t("profiles.profileName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("profiles.profileNamePlaceholder")}
value={name}
onChange={(e) => setName(e.target.value)}
@@ -74,6 +78,7 @@ export function ProfileSaveForm({ open, onClose, editProfile }: ProfileSaveFormP
/>
<Textarea
label={t("profiles.thirdPartyAdText")}
maxLength={FIELD_LIMITS.LONG_TEXT}
placeholder={t("profiles.thirdPartyAdTextPlaceholder")}
value={adText}
onChange={(e) => setAdText(e.target.value)}
+4 -2
View File
@@ -24,7 +24,9 @@ export function TemplateCard({ template }: TemplateCardProps) {
// 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" }));
toast.error(
t("templates.applyFailed", { defaultValue: "Template is corrupt — cannot apply" }),
);
return;
}
loadProfile(template.snapshot);
@@ -35,7 +37,7 @@ export function TemplateCard({ template }: TemplateCardProps) {
return (
<>
<div className="flex flex-col gap-3 rounded-lg border border-border-strong bg-surface-2 p-4 shadow-md shadow-black/10 transition-colors hover:border-accent/30 sm:flex-row sm:items-center sm:justify-between">
<div className="hover:border-accent/30 flex flex-col gap-3 rounded-lg border border-border-strong bg-surface-2 p-4 shadow-md shadow-black/10 transition-colors sm:flex-row sm:items-center sm:justify-between">
<div className="min-w-0 flex-1">
<h3 className="text-sm font-semibold text-text-primary">{template.name}</h3>
<div className="mt-1.5 flex flex-wrap items-center gap-2 text-xs text-text-muted">
@@ -6,6 +6,7 @@ import { Input } from "@components/ui/Input";
import { useEditorStore } from "@store/editor-store";
import { useTemplateStore, type TemplateSnapshot } from "@store/template-store";
import toast from "react-hot-toast";
import { FIELD_LIMITS } from "@config/field-limits";
interface TemplateSaveFormProps {
open: boolean;
@@ -56,6 +57,8 @@ export function TemplateSaveForm({ open, onClose }: TemplateSaveFormProps) {
timestamps: editor.timestamps,
playlistLink: editor.playlistLink,
contactEmail: editor.contactEmail,
adEmail: editor.adEmail,
gameKeyEmail: editor.gameKeyEmail,
musicAttribution: editor.musicAttribution,
thumbnailText: editor.thumbnailText,
pinnedComment: editor.pinnedComment,
@@ -80,6 +83,11 @@ export function TemplateSaveForm({ open, onClose }: TemplateSaveFormProps) {
vnBankHolder: editor.vnBankHolder,
vnMomo: editor.vnMomo,
vnZalopay: editor.vnZalopay,
messengerCommunityLink: editor.messengerCommunityLink,
zaloGroupLink: editor.zaloGroupLink,
signalGroupLink: editor.signalGroupLink,
instagramGroupLink: editor.instagramGroupLink,
facebookGroupLink: editor.facebookGroupLink,
};
addTemplate(name, snapshot);
toast.success(t("templates.savedAs", { name: name.trim() || "Untitled" }));
@@ -104,6 +112,7 @@ export function TemplateSaveForm({ open, onClose }: TemplateSaveFormProps) {
<div className="flex flex-col gap-3">
<Input
label={t("templates.templateName")}
maxLength={FIELD_LIMITS.SHORT_NAME}
placeholder={t("templates.templateNamePlaceholder")}
value={name}
onChange={(e) => setName(e.target.value)}
+2 -12
View File
@@ -23,15 +23,7 @@ interface AccordionProps {
* sections are open and persists that choice. Height animates via a
* grid-rows trick so content can be any height without measurement.
*/
export function Accordion({
id,
title,
icon,
badge,
open,
onToggle,
children,
}: AccordionProps) {
export function Accordion({ id, title, icon, badge, open, onToggle, children }: AccordionProps) {
return (
<section
data-accordion-id={id}
@@ -62,9 +54,7 @@ export function Accordion({
)}
>
<div className="overflow-hidden">
<div className="flex flex-col gap-3 border-t border-border px-4 py-4">
{children}
</div>
<div className="flex flex-col gap-3 border-t border-border px-4 py-4">{children}</div>
</div>
</div>
</section>
+1 -1
View File
@@ -23,7 +23,7 @@ export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
<button
ref={ref}
className={clsx(
"inline-flex items-center justify-center gap-2 rounded-lg font-medium transition-colors focus:outline-none focus:ring-2 focus:ring-accent/50 disabled:cursor-not-allowed disabled:opacity-50",
"focus:ring-accent/50 inline-flex items-center justify-center gap-2 rounded-lg font-medium transition-colors focus:outline-none focus:ring-2 disabled:cursor-not-allowed disabled:opacity-50",
variantClasses[variant],
sizeClasses[size],
className,
+5 -2
View File
@@ -25,7 +25,10 @@ export function Checkbox({ checked, onChange, label, className, id }: CheckboxPr
return (
<label
htmlFor={inputId}
className={clsx("group flex min-h-touch cursor-pointer items-start gap-3 text-left", className)}
className={clsx(
"group flex min-h-touch cursor-pointer items-start gap-3 text-left",
className,
)}
>
<input
id={inputId}
@@ -38,7 +41,7 @@ export function Checkbox({ checked, onChange, label, className, id }: CheckboxPr
aria-hidden
className={clsx(
"mt-0.5 flex h-5 w-5 shrink-0 items-center justify-center rounded border transition-colors",
"peer-focus-visible:ring-2 peer-focus-visible:ring-accent/50",
"peer-focus-visible:ring-accent/50 peer-focus-visible:ring-2",
checked
? "border-accent bg-accent text-white"
: "border-border bg-surface-1 text-transparent group-hover:border-border-strong",
+1 -2
View File
@@ -52,8 +52,7 @@ export function ChipGroup(props: ChipGroupProps) {
}
};
const counter =
props.multiple && props.max != null ? `${props.value.length}/${props.max}` : null;
const counter = props.multiple && props.max != null ? `${props.value.length}/${props.max}` : null;
return (
<div className={clsx("flex flex-col gap-2", className)}>
+1 -1
View File
@@ -36,7 +36,7 @@ export function ConfirmDialog({
<Button
variant="primary"
onClick={onConfirm}
className={variant === "danger" ? "bg-danger hover:bg-danger/80" : ""}
className={variant === "danger" ? "hover:bg-danger/80 bg-danger" : ""}
>
{confirmLabel ?? t("common.confirm")}
</Button>
+2 -10
View File
@@ -43,11 +43,7 @@ export function Drawer({
)}
aria-hidden={!open}
>
<div
className="absolute inset-0 bg-black/60"
onClick={onClose}
aria-hidden="true"
/>
<div className="absolute inset-0 bg-black/60" onClick={onClose} aria-hidden="true" />
<div
role="dialog"
aria-modal="true"
@@ -55,11 +51,7 @@ export function Drawer({
className={clsx(
"absolute bottom-0 top-0 flex w-64 max-w-[85vw] flex-col bg-surface-1 shadow-2xl transition-transform duration-200",
side === "left" ? "left-0 border-r border-border" : "right-0 border-l border-border",
open
? "translate-x-0"
: side === "left"
? "-translate-x-full"
: "translate-x-full",
open ? "translate-x-0" : side === "left" ? "-translate-x-full" : "translate-x-full",
className,
)}
style={{
+1 -1
View File
@@ -27,7 +27,7 @@ export const Input = forwardRef<HTMLInputElement, InputProps>(
id={inputId}
aria-invalid={isError || undefined}
className={clsx(
"min-h-touch rounded-lg border bg-surface-1 px-3 py-2.5 text-base text-text-primary placeholder:text-text-muted transition-colors focus:outline-none focus:ring-2 focus:ring-accent/50 sm:text-sm",
"focus:ring-accent/50 min-h-touch rounded-lg border bg-surface-1 px-3 py-2.5 text-base text-text-primary transition-colors placeholder:text-text-muted focus:outline-none focus:ring-2 sm:text-sm",
isError ? "border-danger" : "border-border focus:border-accent",
className,
)}
+1 -1
View File
@@ -29,7 +29,7 @@ export const Select = forwardRef<HTMLSelectElement, SelectProps>(
value={value}
onChange={(e) => onChange(e.target.value)}
className={clsx(
"rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary transition-colors focus:outline-none focus:ring-2 focus:ring-accent/50 focus:border-accent",
"focus:ring-accent/50 rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary transition-colors focus:border-accent focus:outline-none focus:ring-2",
className,
)}
{...props}
+3 -7
View File
@@ -45,13 +45,11 @@ export function ShortcutHelpModal({ open, onClose }: ShortcutHelpModalProps) {
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder={t("shortcuts.searchPlaceholder")}
className="rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-colors focus:border-accent focus:outline-none focus:ring-2 focus:ring-accent/50"
className="focus:ring-accent/50 rounded-lg border border-border bg-surface-1 px-3 py-2 text-sm text-text-primary transition-colors placeholder:text-text-muted focus:border-accent focus:outline-none focus:ring-2"
autoFocus
/>
{filtered.length === 0 ? (
<p className="py-2 text-sm text-text-muted">
{t("shortcuts.noResults")}
</p>
<p className="py-2 text-sm text-text-muted">{t("shortcuts.noResults")}</p>
) : (
<div className="flex flex-col gap-2">
{filtered.map((s) => (
@@ -59,9 +57,7 @@ export function ShortcutHelpModal({ open, onClose }: ShortcutHelpModalProps) {
key={`${s.keys}-${s.labelKey}`}
className="flex items-center justify-between py-1"
>
<span className="text-sm text-text-secondary">
{t(s.labelKey)}
</span>
<span className="text-sm text-text-secondary">{t(s.labelKey)}</span>
<kbd className="rounded bg-surface-2 px-2 py-0.5 font-mono text-xs text-text-primary">
{s.keys}
</kbd>
+42
View File
@@ -0,0 +1,42 @@
import { ShieldAlert } from "lucide-react";
import { useTranslation } from "react-i18next";
import { useSettingsStore } from "@store/settings-store";
import { useEditorIssues } from "@hooks/use-strict-block";
/**
* Lists the fields Strict Mode is blocking on.
*
* A disabled Generate button with no explanation is worse than no gate at all,
* so this always names the offending field and its error. Renders nothing when
* Strict Mode is off or nothing is wrong.
*/
export function StrictModeBanner() {
const { t } = useTranslation("ui");
const strictMode = useSettingsStore((s) => s.strictMode);
const issues = useEditorIssues();
const errors = issues.filter((i) => i.severity === "error");
if (!strictMode || errors.length === 0) return null;
return (
<div
role="alert"
className="border-danger/40 bg-danger/10 flex flex-col gap-1 rounded-lg border px-3 py-2 text-xs text-danger"
>
<span className="flex items-center gap-1.5 font-semibold">
<ShieldAlert className="h-3.5 w-3.5 shrink-0" />
{t("strict.blockedTitle", { count: errors.length })}
</span>
<ul className="flex flex-col gap-0.5 pl-5">
{errors.map((issue) => (
<li key={issue.id}>
<span className="font-medium">{t(issue.labelKey)}</span>
{" — "}
{t(issue.messageKey, issue.params as Record<string, string>)}
</li>
))}
</ul>
<span className="text-text-muted">{t("strict.fixHint")}</span>
</div>
);
}
+1 -1
View File
@@ -21,7 +21,7 @@ export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
ref={ref}
id={inputId}
className={clsx(
"min-h-[96px] rounded-lg border bg-surface-1 px-3 py-2.5 text-base text-text-primary placeholder:text-text-muted transition-colors focus:outline-none focus:ring-2 focus:ring-accent/50 resize-y sm:text-sm",
"focus:ring-accent/50 min-h-[96px] resize-y rounded-lg border bg-surface-1 px-3 py-2.5 text-base text-text-primary transition-colors placeholder:text-text-muted focus:outline-none focus:ring-2 sm:text-sm",
error ? "border-danger" : "border-border focus:border-accent",
className,
)}
+1 -1
View File
@@ -16,7 +16,7 @@ export function Toggle({ label, checked, onChange, className }: ToggleProps) {
aria-checked={checked}
onClick={() => onChange(!checked)}
className={clsx(
"relative inline-flex h-6 w-11 shrink-0 rounded-full border-2 border-transparent transition-colors focus:outline-none focus:ring-2 focus:ring-accent/50",
"focus:ring-accent/50 relative inline-flex h-6 w-11 shrink-0 rounded-full border-2 border-transparent transition-colors focus:outline-none focus:ring-2",
checked ? "bg-accent" : "bg-surface-3",
)}
>
+115 -15
View File
@@ -1,10 +1,20 @@
import { useState, useCallback, type ClipboardEvent } from "react";
import { useState, useCallback, useEffect, useRef, type ClipboardEvent } from "react";
import { useTranslation } from "react-i18next";
import type { ValidationResult } from "@utils/validation";
import { usePendingInvalidStore } from "@store/pending-invalid-store";
import clsx from "clsx";
interface ValidatedInputProps {
label: string;
/**
* Stable id matching the one `collectEditorIssues` uses for the same field
* (`storeLinks.steam`, `contactEmail`). Supplying it lets Strict Mode see
* text that is invalid *and therefore never committed to the editor store* —
* without it, such a field is invisible to every gate outside this page.
*/
fieldId?: string;
/** i18n key naming the field in the Strict Mode banner. */
labelKey?: string;
value: string;
onChange: (value: string) => void;
validate: (value: string) => ValidationResult;
@@ -13,6 +23,24 @@ interface ValidatedInputProps {
inputMode?: "text" | "email" | "url" | "numeric" | "tel" | "search" | "decimal";
autoComplete?: string;
enterKeyHint?: "enter" | "done" | "go" | "next" | "previous" | "search" | "send";
/**
* Hard cap on typed/pasted length — see `src/config/field-limits.ts`. This
* component does not spread props onto the input, so unlike `Input` it needs
* the prop declared explicitly.
*/
maxLength?: number;
/**
* Veto or rewrite a change before it is validated or committed. Return the
* (possibly adjusted) next value to accept it, or `null` to reject the
* keystroke outright, leaving the field exactly as it was.
*
* Used for constraints a validator cannot express without destroying data —
* the three-address email cap, where rejecting the 4th address must not
* disturb the three already typed.
*/
beforeChange?: (next: string, prev: string) => string | null;
/** Shown instead of `helpText` when `beforeChange` rejects a change. */
blockedMessage?: string;
/**
* Forwarded to the inner `<input>`. Used by StoreLinkEditor to sniff a
* pasted URL and auto-fill the Game Name field — see
@@ -24,6 +52,8 @@ interface ValidatedInputProps {
export function ValidatedInput({
label,
fieldId,
labelKey,
value,
onChange,
validate,
@@ -32,38 +62,106 @@ export function ValidatedInput({
inputMode,
autoComplete,
enterKeyHint,
maxLength,
beforeChange,
blockedMessage,
onPaste,
}: ValidatedInputProps) {
const { t } = useTranslation("ui");
const [displayValue, setDisplayValue] = useState(value);
const [error, setError] = useState<string | null>(null);
const [touched, setTouched] = useState(false);
const [blocked, setBlocked] = useState(false);
// Re-sync when the value changes underneath us — applying a profile, preset
// or template, or resetting the editor. Without this the box kept showing
// whatever was typed first and silently disagreed with the store, because
// `useState(value)` only reads the prop on mount.
//
// Guarded on `displayValue` so it never fights the user's own typing: while
// they type, `value` and `displayValue` already agree (or `value` is the last
// valid one, in which case an external change is what we want to adopt).
const lastExternalValue = useRef(value);
useEffect(() => {
if (value !== lastExternalValue.current) {
lastExternalValue.current = value;
setDisplayValue(value);
setError(null);
setBlocked(false);
}
}, [value]);
const handleChange = useCallback(
(newValue: string) => {
setDisplayValue(newValue);
const result = validate(newValue);
(rawValue: string) => {
const next = beforeChange ? beforeChange(rawValue, displayValue) : rawValue;
if (next === null) {
// Rejected outright — leave both the display and the committed value
// untouched so nothing already entered is lost.
setBlocked(true);
setTouched(true);
return;
}
setBlocked(false);
setDisplayValue(next);
lastExternalValue.current = next;
const result = validate(next);
if (result.valid && !result.error) {
// Fully valid: commit the value to the store.
setError(null);
onChange(newValue);
onChange(next);
} else if (result.valid && result.error) {
// Warning (e.g. prefix mismatch from validateUrlWithPrefix).
// Surface the warning but still commit so the user can decide.
setError(t(result.error, result.errorParams as Record<string, string>));
onChange(newValue);
onChange(next);
} else {
// Invalid: show the error and CLEAR the committed value so the
// bad input never reaches the generated description/tags. The
// local displayValue is preserved so the user can keep editing.
// Invalid: surface the error and DON'T commit, so the bad input never
// reaches the generated description/tags.
//
// Before v0.35.0 this branch called `onChange("")`, which wiped the
// stored value while the box still showed the user's text — so
// backspacing one character out of a complete URL silently emptied the
// field, and autosave/profile-save then persisted the empty value with
// no visible signal. Leaving the last valid value in place keeps bad
// input out just as effectively without destroying good input.
setError(t(result.error ?? "", result.errorParams as Record<string, string>));
onChange("");
}
setTouched(true);
},
[validate, onChange, t],
[validate, onChange, t, beforeChange, displayValue],
);
const message = blocked ? (blockedMessage ?? error) : error;
// Publish "this field currently holds text that will not be saved" so gates
// on other pages can see it. Keyed on the raw validation result rather than
// the rendered message, which is already translated and would re-publish on
// every UI-language change.
const liveResult = validate(displayValue);
const isInvalid = blocked || (!liveResult.valid && displayValue.trim() !== "");
const invalidKey = blocked ? "validation.emailMaxReached" : (liveResult.error ?? "");
const invalidParams = JSON.stringify(liveResult.errorParams ?? null);
useEffect(() => {
if (!fieldId) return;
const { markInvalid, clearInvalid } = usePendingInvalidStore.getState();
if (isInvalid) {
const parsed = JSON.parse(invalidParams) as Record<string, string | number> | null;
markInvalid({
id: fieldId,
labelKey: labelKey ?? label,
messageKey: invalidKey,
...(parsed ? { params: parsed } : {}),
});
} else {
clearInvalid(fieldId);
}
// Deliberately NO cleanup on unmount — see the store's doc comment. An
// entry lives until the field is valid again, so navigating to Batch does
// not silently clear the very thing Strict Mode is supposed to catch.
}, [fieldId, labelKey, label, isInvalid, invalidKey, invalidParams]);
return (
<div className="flex flex-col gap-1">
<label className="text-sm font-medium text-text-secondary">{label}</label>
@@ -77,13 +175,15 @@ export function ValidatedInput({
inputMode={inputMode}
autoComplete={autoComplete}
enterKeyHint={enterKeyHint}
maxLength={maxLength}
aria-invalid={touched && Boolean(message) ? true : undefined}
className={clsx(
"min-h-touch rounded-lg border bg-surface-1 px-3 py-2.5 text-base text-text-primary placeholder:text-text-muted transition-colors focus:outline-none focus:ring-2 focus:ring-accent/50 sm:text-sm",
touched && error ? "border-danger" : "border-border focus:border-accent",
"focus:ring-accent/50 min-h-touch rounded-lg border bg-surface-1 px-3 py-2.5 text-base text-text-primary transition-colors placeholder:text-text-muted focus:outline-none focus:ring-2 sm:text-sm",
touched && message ? "border-danger" : "border-border focus:border-accent",
)}
/>
{touched && error && <p className="text-xs text-danger">{error}</p>}
{helpText && !error && <p className="text-xs text-text-muted">{helpText}</p>}
{touched && message && <p className="text-xs text-danger">{message}</p>}
{helpText && !message && <p className="text-xs text-text-muted">{helpText}</p>}
</div>
);
}
+28
View File
@@ -71,6 +71,17 @@ export interface EditorDefaults {
timestamps: string;
playlistLink: string;
contactEmail: string;
/**
* v0.34.0 email-split fields. When the `splitContactEmail` settings
* toggle is on, the description's contact block renders a labeled line
* per purpose: `contactEmail` (general), `adEmail` (advertising /
* sponsorship inquiries — distinct from the video-sponsor-credit
* fields `sponsorName` / `sponsorPlatform`), and `gameKeyEmail` (game
* keys & playtest invites). Each holds up to 3 comma-separated emails
* (same `validateEmails` cap as `contactEmail`). Empty by default.
*/
adEmail: string;
gameKeyEmail: string;
musicAttribution: string;
sponsorName: string;
sponsorPlatform: string;
@@ -138,6 +149,16 @@ export interface EditorDefaults {
playtestPlatform: string;
/** Playtest invites available, 0..platform max (≤100). 0 = unset. */
playtestInvites: number;
/** Messenger community invite link (v0.32.0). `https://m.me/ch/<id>`. Empty = no community line. */
messengerCommunityLink: string;
/** Zalo group invite link (v0.32.0). `https://zalo.me/g/<code>`. Rendered only for Vietnamese output. */
zaloGroupLink: string;
/** Signal group invite link (v0.33.0). `https://signal.group/#<id>`. Rendered for all languages. Empty = no line. */
signalGroupLink: string;
/** Instagram group-chat invite link (v0.33.0). `https://www.instagram.com/j/<id>` or `https://ig.me/j/<id>`. All languages. */
instagramGroupLink: string;
/** Facebook group invite link (v0.33.0). `https://facebook.com/groups/<id>`. Moved from the generic Social list; all languages. */
facebookGroupLink: string;
}
export interface SettingsDefaults {
@@ -183,6 +204,8 @@ export const DEFAULTS = {
timestamps: "",
playlistLink: "",
contactEmail: "",
adEmail: "",
gameKeyEmail: "",
musicAttribution: "",
sponsorName: "",
sponsorPlatform: "",
@@ -218,6 +241,11 @@ export const DEFAULTS = {
playtestLink: "",
playtestPlatform: DEFAULT_PLAYTEST_PLATFORM,
playtestInvites: 0,
messengerCommunityLink: "",
zaloGroupLink: "",
signalGroupLink: "",
instagramGroupLink: "",
facebookGroupLink: "",
} satisfies EditorDefaults,
settings: {
+21
View File
@@ -0,0 +1,21 @@
/**
* Predefined "why was this playlist dropped" reasons (v0.31.0).
*
* Drives the Playlist Generator's dropped-reason multi-select, shown only
* when the playlist status is "dropped". Each id maps to a localized label
* under `playlist.droppedReasons.<id>` in BOTH the `ui` namespace (the
* selection chips) and the `templates` namespace (the rendered output) —
* the same split used by content warnings. The list is a starting point,
* just plain constants free to tune; the editor's free-text "other reason"
* field covers anything not listed here.
*/
export const DROPPED_REASONS = [
{ id: "boring", icon: "😴" },
{ id: "performance", icon: "🐌" },
{ id: "bugs", icon: "🐛" },
{ id: "delisted", icon: "🗑️" },
{ id: "low_views", icon: "📉" },
{ id: "time", icon: "⏳" },
] as const;
export type DroppedReasonId = (typeof DROPPED_REASONS)[number]["id"];
+74
View File
@@ -0,0 +1,74 @@
import { YT_LIMITS } from "@engine/types";
/**
* Maximum length of every free-text field in the editor.
*
* Until v0.35.0 no input in the app had a cap at all: `maxLength` appeared
* nowhere in the codebase. A pasted novel in the game-name field produced a
* title YouTube would reject, and a 4 KB "URL" silently rode along into the
* description.
*
* Caps are grouped by the *kind* of thing a field holds, not per field, so a
* new input inherits a sensible limit by picking the closest category instead
* of inventing a number. All values are UTF-16 code units, matching the DOM
* `maxLength` attribute — an emoji costs 2 and a flag emoji 4. That is a
* deliberate simplification: grapheme counting would be more "correct" but
* cannot be enforced by the browser, and these are generous ceilings meant to
* stop absurd input, not to budget characters precisely.
*/
export const FIELD_LIMITS = {
/**
* Store pages, social profiles, playlists, community invites. The longest
* realistic value in the app's own inventory is a Signal group invite
* (`https://signal.group/#<base64>`) at roughly 120 characters.
*/
URL: 200,
/**
* Up to three comma-separated addresses. RFC 5321 caps a single address at
* 254, so 200 would be too tight for even one worst-case address; 320 fits
* three ordinary ones with room to spare while still rejecting a paste of
* an entire contact list.
*/
EMAIL_FIELD: 320,
/**
* Game names, channel names, boss / chapter / DLC names, sponsor names,
* hardware model strings, profile and preset names. The longest real game
* titles run to roughly 50 characters.
*/
SHORT_NAME: 100,
/** Custom labels and version strings — a phrase, not a sentence. */
LABEL: 300,
/**
* Music attribution, mod lists, pinned comments, thumbnail text, sponsor
* blurbs, playlist notes. Long enough for a real credits block, short
* enough that no single field can consume the whole description budget.
*/
LONG_TEXT: 2000,
/**
* The timestamps field is the one input that legitimately holds a whole
* chapter list. Capped at the YouTube description limit because a longer
* value could only ever produce a description that is already over budget
* and blocked from copying.
*/
TIMESTAMPS: YT_LIMITS.DESCRIPTION_MAX,
/** Part numbers, years, counts. Ten digits is already absurd for these. */
NUMERIC: 10,
} as const;
/**
* Truncate a value to `max`.
*
* The DOM `maxLength` attribute only constrains *typing and pasting*. Values
* arriving programmatically — a profile / preset / template import, a
* store-link paste that auto-fills the game name, a hand-edited settings JSON
* — bypass it entirely. Run those through here, or the cap is decorative.
*/
export function clampField(value: string, max: number): string {
return value.length > max ? value.slice(0, max) : value;
}
+1 -4
View File
@@ -140,10 +140,7 @@ const DEFAULT_FIELD_VISIBILITY: GachaQuestFieldVisibility = {
anniversaryYear: false,
};
export const GACHA_QUEST_FIELD_VISIBILITY: Record<
GachaQuestType,
GachaQuestFieldVisibility
> = {
export const GACHA_QUEST_FIELD_VISIBILITY: Record<GachaQuestType, GachaQuestFieldVisibility> = {
main_story: { ...DEFAULT_FIELD_VISIBILITY, questName: false },
world_quest: { ...DEFAULT_FIELD_VISIBILITY, chapterName: false, partNumber: false },
side_quest: { ...DEFAULT_FIELD_VISIBILITY, chapterName: false, partNumber: false },
+32 -4
View File
@@ -44,7 +44,15 @@ const NVIDIA_SERIES: readonly GpuSeries[] = [
{
id: "rtx_50",
label: "RTX 50 Series",
models: ["RTX 5050", "RTX 5060", "RTX 5060 Ti", "RTX 5070", "RTX 5070 Ti", "RTX 5080", "RTX 5090"],
models: [
"RTX 5050",
"RTX 5060",
"RTX 5060 Ti",
"RTX 5070",
"RTX 5070 Ti",
"RTX 5080",
"RTX 5090",
],
},
{
id: "rtx_40",
@@ -185,12 +193,32 @@ const AMD_SERIES: readonly GpuSeries[] = [
{
id: "r9_300",
label: "Radeon R7/R9 300",
models: ["R7 360", "R7 370", "R9 380", "R9 380X", "R9 390", "R9 390X", "R9 Fury", "R9 Fury X", "R9 Nano"],
models: [
"R7 360",
"R7 370",
"R9 380",
"R9 380X",
"R9 390",
"R9 390X",
"R9 Fury",
"R9 Fury X",
"R9 Nano",
],
},
{
id: "r9_200",
label: "Radeon R7/R9 200",
models: ["R7 250", "R7 260", "R7 260X", "R9 270", "R9 270X", "R9 280", "R9 280X", "R9 290", "R9 290X"],
models: [
"R7 250",
"R7 260",
"R7 260X",
"R9 270",
"R9 270X",
"R9 280",
"R9 280X",
"R9 290",
"R9 290X",
],
},
{
id: "hd_7000",
@@ -253,4 +281,4 @@ export const GPU_CUSTOM_BRAND_ID = "custom";
*/
export function findGpuBrand(brandId: string): GpuBrand | undefined {
return GPU_CATALOG.find((b) => b.id === brandId);
}
}
+1 -6
View File
@@ -26,12 +26,7 @@ export type GraphicsPreset = (typeof GRAPHICS_PRESETS)[number];
* of these layered (e.g. Path Tracing + Ray Reconstruction + Frame
* Generation). Empty array → no RT clause in the description.
*/
export const RT_MODES = [
"ray_tracing",
"full_rt",
"path_tracing",
"ray_reconstruction",
] as const;
export const RT_MODES = ["ray_tracing", "full_rt", "path_tracing", "ray_reconstruction"] as const;
export type RTMode = (typeof RT_MODES)[number];
/**
+2 -5
View File
@@ -21,9 +21,7 @@ export interface PlatformConfig {
* numeric id, yielding the canonical `.../app/<id>` form.
*/
function normalizeSteamUrl(url: string): string {
const match = url.match(
/^(https:\/\/store\.steampowered\.com\/app\/\d+)(?:\/.*)?$/i,
);
const match = url.match(/^(https:\/\/store\.steampowered\.com\/app\/\d+)(?:\/.*)?$/i);
return match?.[1] ?? url;
}
@@ -72,8 +70,7 @@ export const PLATFORMS: readonly PlatformConfig[] = [
urlPrefix: "https://<dev>.itch.io/<game>",
// itch.io games live at https://<dev>.itch.io/<game>, where <dev>
// is a user subdomain. Reject the bare https://itch.io/... host.
urlPattern:
/^https:\/\/[a-z0-9][a-z0-9-]*\.itch\.io\/[a-z0-9][a-z0-9_-]*\/?$/i,
urlPattern: /^https:\/\/[a-z0-9][a-z0-9-]*\.itch\.io\/[a-z0-9][a-z0-9_-]*\/?$/i,
},
{
id: "humble",
+1 -2
View File
@@ -50,8 +50,7 @@ export const PLAYTEST_PLATFORMS: readonly PlaytestPlatformConfig[] = [
id: "itchio",
label: "itch.io",
urlPrefix: "https://<dev>.itch.io/<game>",
urlPattern:
/^https:\/\/[a-z0-9][a-z0-9-]*\.itch\.io\/[a-z0-9][a-z0-9_-]*\/?$/i,
urlPattern: /^https:\/\/[a-z0-9][a-z0-9-]*\.itch\.io\/[a-z0-9][a-z0-9_-]*\/?$/i,
maxInvites: 50,
},
{
+21 -15
View File
@@ -1,9 +1,4 @@
import {
GPU_CATALOG,
GPU_CUSTOM_BRAND_ID,
findGpuBrand,
type GpuCatalog,
} from "./gpu-catalog";
import { GPU_CATALOG, GPU_CUSTOM_BRAND_ID, findGpuBrand, type GpuCatalog } from "./gpu-catalog";
/**
* Supported rig field input types.
@@ -25,11 +20,7 @@ import {
* may opt into a free-text "Custom" override; the stored format is
* pipe-delimited in the order parts are declared.
*/
type RigFieldType =
| "text"
| "dropdown_with_version"
| "cascading_dropdown"
| "composite_dropdown";
type RigFieldType = "text" | "dropdown_with_version" | "cascading_dropdown" | "composite_dropdown";
interface RigFieldOption {
readonly value: string;
@@ -344,7 +335,12 @@ const OS_COMPOSITE: CompositeFieldSpec = {
export const RIG_FIELDS: readonly RigField[] = [
{ id: "os", labelKey: "rig.os", type: "composite_dropdown", composite: OS_COMPOSITE },
{ id: "cpu", labelKey: "rig.cpu", type: "text", placeholder: "Intel i9-14900K / AMD Ryzen 9 7950X" },
{
id: "cpu",
labelKey: "rig.cpu",
type: "text",
placeholder: "Intel i9-14900K / AMD Ryzen 9 7950X",
},
{
id: "gpu",
labelKey: "rig.gpu",
@@ -358,10 +354,20 @@ export const RIG_FIELDS: readonly RigField[] = [
composite: RAM_COMPOSITE,
},
{ id: "storage", labelKey: "rig.storage", type: "text", placeholder: "2TB Samsung 990 PRO NVMe" },
{ id: "monitor", labelKey: "rig.monitor", type: "text", placeholder: "LG 27GP950 27\" 4K 144Hz" },
{ id: "monitor", labelKey: "rig.monitor", type: "text", placeholder: 'LG 27GP950 27" 4K 144Hz' },
{ id: "capture", labelKey: "rig.capture", type: "text", placeholder: "OBS Studio 30.x" },
{ id: "motherboard", labelKey: "rig.motherboard", type: "text", placeholder: "ASUS ROG Maximus Z790 Hero" },
{ id: "controller", labelKey: "rig.controller", type: "text", placeholder: "DualSense / Xbox Elite Series 2" },
{
id: "motherboard",
labelKey: "rig.motherboard",
type: "text",
placeholder: "ASUS ROG Maximus Z790 Hero",
},
{
id: "controller",
labelKey: "rig.controller",
type: "text",
placeholder: "DualSense / Xbox Elite Series 2",
},
{
id: "video_editor",
labelKey: "rig.video_editor",
+121 -18
View File
@@ -1,22 +1,125 @@
export const SOCIAL_FIELDS = [
// Donate
{ id: "kofi", label: "Ko-fi", labelKey: "social.kofi", urlPrefix: "https://ko-fi.com/", category: "donate" },
{ id: "patreon", label: "Patreon", labelKey: "social.patreon", urlPrefix: "https://patreon.com/", category: "donate" },
{ id: "buymeacoffee", label: "Buy Me a Coffee", labelKey: "social.buymeacoffee", urlPrefix: "https://buymeacoffee.com/", category: "donate" },
{ id: "paypal", label: "PayPal", labelKey: "social.paypal", urlPrefix: "https://paypal.me/", category: "donate" },
{ id: "streamlabs", label: "Streamlabs", labelKey: "social.streamlabs", urlPrefix: "https://streamlabs.com/", category: "donate" },
{
id: "kofi",
label: "Ko-fi",
labelKey: "social.kofi",
urlPrefix: "https://ko-fi.com/",
category: "donate",
},
{
id: "patreon",
label: "Patreon",
labelKey: "social.patreon",
urlPrefix: "https://patreon.com/",
category: "donate",
},
{
id: "buymeacoffee",
label: "Buy Me a Coffee",
labelKey: "social.buymeacoffee",
urlPrefix: "https://buymeacoffee.com/",
category: "donate",
},
{
id: "paypal",
label: "PayPal",
labelKey: "social.paypal",
urlPrefix: "https://paypal.me/",
category: "donate",
},
{
id: "streamlabs",
label: "Streamlabs",
labelKey: "social.streamlabs",
urlPrefix: "https://streamlabs.com/",
category: "donate",
},
// Social
{ id: "github", label: "GitHub", labelKey: "social.github", urlPrefix: "https://github.com/", category: "social" },
{ id: "twitter", label: "Twitter / X", labelKey: "social.twitter", urlPrefix: "https://x.com/", category: "social" },
{ id: "discord", label: "Discord", labelKey: "social.discord", urlPrefix: "https://discord.gg/", category: "social" },
{ id: "twitch", label: "Twitch", labelKey: "social.twitch", urlPrefix: "https://twitch.tv/", category: "social" },
{ id: "tiktok", label: "TikTok", labelKey: "social.tiktok", urlPrefix: "https://tiktok.com/@", category: "social" },
{ id: "instagram", label: "Instagram", labelKey: "social.instagram", urlPrefix: "https://instagram.com/", category: "social" },
{ id: "bluesky", label: "Bluesky", labelKey: "social.bluesky", urlPrefix: "https://bsky.app/profile/", category: "social" },
{ id: "mastodon", label: "Mastodon", labelKey: "social.mastodon", urlPrefix: "", category: "social" },
{ id: "facebook", label: "Facebook", labelKey: "social.facebook", urlPrefix: "https://facebook.com/", category: "social" },
{ id: "fb_page", label: "Facebook Page", labelKey: "social.fb_page", urlPrefix: "https://facebook.com/", category: "social" },
{ id: "fb_group", label: "Facebook Group", labelKey: "social.fb_group", urlPrefix: "https://facebook.com/groups/", category: "social" },
{ id: "telegram", label: "Telegram", labelKey: "social.telegram", urlPrefix: "https://t.me/", category: "social" },
{ id: "website", label: "Website", labelKey: "social.website", urlPrefix: "", category: "social" },
{
id: "github",
label: "GitHub",
labelKey: "social.github",
urlPrefix: "https://github.com/",
category: "social",
},
{
id: "twitter",
label: "Twitter / X",
labelKey: "social.twitter",
urlPrefix: "https://x.com/",
category: "social",
},
{
id: "discord",
label: "Discord",
labelKey: "social.discord",
urlPrefix: "https://discord.gg/",
category: "social",
},
{
id: "twitch",
label: "Twitch",
labelKey: "social.twitch",
urlPrefix: "https://twitch.tv/",
category: "social",
},
{
id: "tiktok",
label: "TikTok",
labelKey: "social.tiktok",
urlPrefix: "https://tiktok.com/@",
category: "social",
},
{
id: "instagram",
label: "Instagram",
labelKey: "social.instagram",
urlPrefix: "https://instagram.com/",
category: "social",
},
{
id: "bluesky",
label: "Bluesky",
labelKey: "social.bluesky",
urlPrefix: "https://bsky.app/profile/",
category: "social",
},
{
id: "mastodon",
label: "Mastodon",
labelKey: "social.mastodon",
urlPrefix: "",
category: "social",
},
{
id: "facebook",
label: "Facebook",
labelKey: "social.facebook",
urlPrefix: "https://facebook.com/",
category: "social",
},
{
id: "fb_page",
label: "Facebook Page",
labelKey: "social.fb_page",
urlPrefix: "https://facebook.com/",
category: "social",
},
// Facebook Group moved to the Community section in v0.33.0 — it's now a
// dedicated `facebookGroupLink` editor field (see CommunityEditor).
{
id: "telegram",
label: "Telegram",
labelKey: "social.telegram",
urlPrefix: "https://t.me/",
category: "social",
},
{
id: "website",
label: "Website",
labelKey: "social.website",
urlPrefix: "",
category: "social",
},
] as const;
+2 -11
View File
@@ -34,21 +34,12 @@ export const TECH_NOTE_GROUPS: readonly TechNoteGroup[] = [
{
id: "video_quality",
labelKey: "editor.techNoteGroups.video_quality",
items: [
"low_resolution_hardware",
"low_graphics_performance",
"fps_drops_hardware",
],
items: ["low_resolution_hardware", "low_graphics_performance", "fps_drops_hardware"],
},
{
id: "recording_issues",
labelKey: "editor.techNoteGroups.recording_issues",
items: [
"bug_from_game",
"crash_kept_transparency",
"loading_cut",
"obs_artifacts_possible",
],
items: ["bug_from_game", "crash_kept_transparency", "loading_cut", "obs_artifacts_possible"],
},
{
id: "playstyle",
+4 -7
View File
@@ -32,9 +32,9 @@ export const VIDEO_STYLE_ERAS = [
export type VideoStyleEra = (typeof VIDEO_STYLE_ERAS)[number];
/** Subset minus the empty sentinel — used by the form to render options. */
export const VIDEO_STYLE_ERA_IDS = VIDEO_STYLE_ERAS.filter(
(id) => id !== "",
) as ReadonlyArray<Exclude<VideoStyleEra, "">>;
export const VIDEO_STYLE_ERA_IDS = VIDEO_STYLE_ERAS.filter((id) => id !== "") as ReadonlyArray<
Exclude<VideoStyleEra, "">
>;
/**
* Type guard so the engine + migration can coerce unrecognised values
@@ -42,8 +42,5 @@ export const VIDEO_STYLE_ERA_IDS = VIDEO_STYLE_ERAS.filter(
* eras) back to the empty sentinel without crashing.
*/
export function isVideoStyleEra(value: unknown): value is VideoStyleEra {
return (
typeof value === "string" &&
(VIDEO_STYLE_ERAS as readonly string[]).includes(value)
);
return typeof value === "string" && (VIDEO_STYLE_ERAS as readonly string[]).includes(value);
}
+80 -100
View File
@@ -26,7 +26,6 @@ const SOCIAL_ICONS: Record<string, string> = {
mastodon: "🐘",
facebook: "👤",
fb_page: "📄",
fb_group: "👥",
telegram: "✈️",
website: "🌐",
};
@@ -41,12 +40,7 @@ const TRANSLATION_TRUSTED: readonly string[] = ["vi", "en"];
/** Caveat bullet ids for the Translation Quality section, resolved against
* `description.translationQuality.items.<id>` (v0.24.0). */
const TRANSLATION_QUALITY_ITEMS = [
"accuracy",
"phrasing",
"localStyle",
"corrections",
] as const;
const TRANSLATION_QUALITY_ITEMS = ["accuracy", "phrasing", "localStyle", "corrections"] as const;
function hasEntries(obj: Partial<Record<string, string>>): boolean {
return Object.values(obj).some((v) => v && v.trim() !== "");
@@ -88,14 +82,12 @@ function formatScheduledTime(iso: string, language: string): string {
* is similarly fixed: "Frame Generation" (NVIDIA), "Fluid Motion Frames"
* (AMD's official term), "XeFG" (Intel's announced FG tech).
*/
const VENDOR_GFX_BRANDS: Record<
"nvidia" | "amd" | "intel",
{ upscale: string; framegen: string }
> = {
nvidia: { upscale: "NVIDIA DLSS", framegen: "NVIDIA Frame Generation" },
amd: { upscale: "AMD FSR", framegen: "AMD Fluid Motion Frames" },
intel: { upscale: "Intel XeSS", framegen: "Intel XeFG" },
};
const VENDOR_GFX_BRANDS: Record<"nvidia" | "amd" | "intel", { upscale: string; framegen: string }> =
{
nvidia: { upscale: "NVIDIA DLSS", framegen: "NVIDIA Frame Generation" },
amd: { upscale: "AMD FSR", framegen: "AMD Fluid Motion Frames" },
intel: { upscale: "Intel XeSS", framegen: "Intel XeFG" },
};
/**
* Compose the value half of the "In-game Setting:" line — e.g.
@@ -126,13 +118,9 @@ function composeGraphicsPart(input: GeneratorInput, t: TranslationFn): string {
// 2. Modifier (upscale + frame-gen). Vendor gates the whole clause —
// upscaling/frame-gen quality without a vendor is meaningless.
const vendor =
input.frameGenVendor && input.frameGenVendor !== "none"
? input.frameGenVendor
: null;
input.frameGenVendor && input.frameGenVendor !== "none" ? input.frameGenVendor : null;
const upscaleQ =
input.upscaleQuality && input.upscaleQuality !== "none"
? input.upscaleQuality
: null;
input.upscaleQuality && input.upscaleQuality !== "none" ? input.upscaleQuality : null;
const fgMul =
input.frameGenMultiplier && input.frameGenMultiplier !== "none"
? input.frameGenMultiplier
@@ -220,10 +208,7 @@ function composeVideoStyleLine(input: GeneratorInput, t: TranslationFn): string
const eraLabel = t(eraKey);
if (!eraLabel || eraLabel === eraKey) return "";
const editor = formatRigValue(
"video_editor",
input.rig?.video_editor ?? "",
).trim();
const editor = formatRigValue("video_editor", input.rig?.video_editor ?? "").trim();
if (editor) {
return t("description.videoSettings.styleLine", { era: eraLabel, editor });
@@ -252,6 +237,11 @@ export interface BuildDescriptionOptions {
/** When true and the active profile's `thirdPartyAdText` is non-empty,
* emits a "🤝 SPONSORS & PARTNERS" block (v0.11). */
showThirdPartyAds?: boolean;
/** When true, the contact block (§12) splits into a grouped
* "📧 BUSINESS / CONTACT" block with one labeled line per non-empty
* purpose field (`contactEmail` / `adEmail` / `gameKeyEmail`) instead
* of the single "📧 Business inquiries" line. v0.34.0. */
splitContactEmail?: boolean;
/** When true, appends an AI-translation disclaimer block for output
* languages outside the trusted set ({@link TRANSLATION_TRUSTED} —
* English / Vietnamese, which are human-reviewed). v0.24.0. */
@@ -280,6 +270,7 @@ export function buildDescription(
showUsagePolicy = false,
showSponsorCredit = false,
showThirdPartyAds = false,
splitContactEmail = false,
showGameCopyright = false,
showTranslationQuality = false,
tEn,
@@ -290,8 +281,7 @@ export function buildDescription(
// The translation-quality disclaimer keeps the raw `tEn` and stays bilingual.
const contentBlockTEn = bilingualContentBlocks ? tEn : undefined;
const sections: string[] = [];
const gameName =
input.gameNameLocalized?.[input.language] ?? input.gameName;
const gameName = input.gameNameLocalized?.[input.language] ?? input.gameName;
// 1. Intro. Gacha videos dispatch on `gachaQuestType` so each of the
// 17 patterns can frame the description with its own opening line
@@ -318,8 +308,7 @@ export function buildDescription(
questName: input.questName ?? "",
characterName: input.characterName ?? "",
anniversaryYear: input.anniversaryYear != null ? String(input.anniversaryYear) : "",
ordinalSuffix:
input.anniversaryYear != null ? ordinalSuffix(input.anniversaryYear) : "",
ordinalSuffix: input.anniversaryYear != null ? ordinalSuffix(input.anniversaryYear) : "",
gachaVersion: input.gachaVersion ?? "",
versionLabel,
});
@@ -367,8 +356,9 @@ export function buildDescription(
// 4. Store Links (heading + per-link suffix by pricing category)
if (hasEntries(input.storeLinks)) {
const entries = Object.entries(input.storeLinks)
.filter((entry): entry is [string, string] =>
typeof entry[1] === "string" && entry[1].trim() !== "",
.filter(
(entry): entry is [string, string] =>
typeof entry[1] === "string" && entry[1].trim() !== "",
)
.map(([id, url]) => ({
id,
@@ -424,16 +414,11 @@ export function buildDescription(
// produce a broken line.
if (input.playtestLink && input.playtestLink.trim()) {
const link = input.playtestLink.trim();
const platformLabel = getLabelForId(
input.playtestPlatform ?? "",
PLAYTEST_PLATFORMS,
);
const platformLabel = getLabelForId(input.playtestPlatform ?? "", PLAYTEST_PLATFORMS);
const lines = [`🧪 ${platformLabel}: ${link}`];
const invites = input.playtestInvites ?? 0;
if (Number.isInteger(invites) && invites > 0) {
lines.push(
t("description.sections.playtestInvites", { count: String(invites) }),
);
lines.push(t("description.sections.playtestInvites", { count: String(invites) }));
}
sections.push(`${t("description.sections.playtest")}\n${lines.join("\n")}`);
}
@@ -522,14 +507,8 @@ export function buildDescription(
// Vortex, Mod Organizer…). The single-line `modName` field stays in the
// title / intro for short identification; this block lists the full
// load order for the description.
if (
input.videoType === "mods" &&
input.modList &&
input.modList.trim()
) {
sections.push(
`${t("description.sections.modList")}\n${input.modList.trim()}`,
);
if (input.videoType === "mods" && input.modList && input.modList.trim()) {
sections.push(`${t("description.sections.modList")}\n${input.modList.trim()}`);
}
// 7. Content warnings — unified bilingual checklist (v0.11). Header +
@@ -601,22 +580,14 @@ export function buildDescription(
// verbatim. Gated on settings toggle AND profile field non-empty;
// partial state is a no-op so flipping the toggle without filling
// the profile doesn't sneak an empty section into the description.
if (
showThirdPartyAds &&
input.thirdPartyAdText &&
input.thirdPartyAdText.trim()
) {
sections.push(
`${t("description.sections.thirdPartyAds")}\n${input.thirdPartyAdText.trim()}`,
);
if (showThirdPartyAds && input.thirdPartyAdText && input.thirdPartyAdText.trim()) {
sections.push(`${t("description.sections.thirdPartyAds")}\n${input.thirdPartyAdText.trim()}`);
}
// 8.5. Music / sound attribution — sits right before the donate
// block because both are "credits"-adjacent sections.
if (input.musicAttribution && input.musicAttribution.trim()) {
sections.push(
`${t("description.sections.music")}\n${input.musicAttribution.trim()}`,
);
sections.push(`${t("description.sections.music")}\n${input.musicAttribution.trim()}`);
}
// 9. Donate Links (use proper labels + icons)
@@ -667,13 +638,54 @@ export function buildDescription(
sections.push(`${t("description.sections.social")}\n${socialEntries.join("\n")}`);
}
// 10.5 Community — a single "💬 COMMUNITY" block for "join the chat"
// invites. Messenger, Signal, Instagram (group chat) and Facebook Group
// render for every language; the Zalo group is a Vietnam-audience app so
// its line is gated on Vietnamese output (same rationale as the VN donate
// block above). Line labels are fixed brand names (not localized), like
// the rest of this block. The whole block is skipped when no eligible
// link is present.
const communityLines: string[] = [];
const messenger = input.messengerCommunityLink?.trim() ?? "";
if (messenger) communityLines.push(`💬 Messenger: ${messenger}`);
const signal = input.signalGroupLink?.trim() ?? "";
if (signal) communityLines.push(`🔒 Signal: ${signal}`);
const instagram = input.instagramGroupLink?.trim() ?? "";
if (instagram) communityLines.push(`📸 Instagram: ${instagram}`);
const facebookGroup = input.facebookGroupLink?.trim() ?? "";
if (facebookGroup) communityLines.push(`👥 Facebook Group: ${facebookGroup}`);
const zalo = input.zaloGroupLink?.trim() ?? "";
if (zalo && input.language === "vi") communityLines.push(`💙 Zalo: ${zalo}`);
if (communityLines.length > 0) {
sections.push(`${t("description.sections.community")}\n${communityLines.join("\n")}`);
}
// 11. Playlist
if (input.playlistLink && input.playlistLink.trim()) {
sections.push(t("description.sections.playlist", { link: input.playlistLink }));
}
// 12. Contact
if (input.contactEmail && input.contactEmail.trim()) {
// 12. Contact. Two modes, gated by the `splitContactEmail` toggle:
// • off (default) — a single "📧 Business inquiries" line, unchanged.
// • on — a grouped "📧 BUSINESS / CONTACT" block with one labeled line
// per non-empty purpose field. Each line is skipped when its field
// is empty, and the whole block is skipped when all three are empty
// (same skip logic as the Community block above).
if (splitContactEmail) {
const emailLines: string[] = [];
if (input.contactEmail?.trim()) {
emailLines.push(t("description.sections.emailContact", { email: input.contactEmail }));
}
if (input.adEmail?.trim()) {
emailLines.push(t("description.sections.emailAd", { email: input.adEmail }));
}
if (input.gameKeyEmail?.trim()) {
emailLines.push(t("description.sections.emailGameKeys", { email: input.gameKeyEmail }));
}
if (emailLines.length > 0) {
sections.push(`${t("description.sections.contactHeader")}\n${emailLines.join("\n")}`);
}
} else if (input.contactEmail && input.contactEmail.trim()) {
sections.push(t("description.sections.contact", { email: input.contactEmail }));
}
@@ -743,19 +755,13 @@ function buildPlaythroughNotesSection(
* in bilingual mode and `Label: Value` otherwise. Returns null when the
* value is empty (caller filters these out).
*/
function bullet(
labelKey: string,
valueEn: string,
valueLocal: string,
): string | null {
function bullet(labelKey: string, valueEn: string, valueLocal: string): string | null {
const trimmedEn = valueEn.trim();
const trimmedLocal = valueLocal.trim();
if (!trimmedEn && !trimmedLocal) return null;
const labelEn = tEnUse(labelKey);
const labelLocal = t(labelKey);
const labelLine = renderBilingual
? `${labelEn} · ${labelLocal}`
: labelEn;
const labelLine = renderBilingual ? `${labelEn} · ${labelLocal}` : labelEn;
const valueLine = renderBilingual
? `${trimmedEn || trimmedLocal} · ${trimmedLocal || trimmedEn}`
: trimmedEn || trimmedLocal;
@@ -817,11 +823,7 @@ function buildPlaythroughNotesSection(
valueEn = en === key ? input.difficulty : en;
valueLocal = local === key ? input.difficulty : local;
}
const b = bullet(
"description.playthroughNotes.labels.difficulty",
valueEn,
valueLocal,
);
const b = bullet("description.playthroughNotes.labels.difficulty", valueEn, valueLocal);
if (b) bullets.push(b);
}
@@ -842,26 +844,16 @@ function buildPlaythroughNotesSection(
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);
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,
);
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,
);
const b = bullet("description.playthroughNotes.labels.endings", legacy, legacy);
if (b) bullets.push(b);
}
}
@@ -881,11 +873,7 @@ function buildPlaythroughNotesSection(
valueEn = resolved.en;
valueLocal = resolved.local;
}
const b = bullet(
"description.playthroughNotes.labels.languagePatch",
valueEn,
valueLocal,
);
const b = bullet("description.playthroughNotes.labels.languagePatch", valueEn, valueLocal);
if (b) bullets.push(b);
}
@@ -899,19 +887,11 @@ function buildPlaythroughNotesSection(
valueEn = custom;
valueLocal = custom;
} else {
const resolved = resolveEnum(
"gameVersionOptions",
input.gameVersion,
"full_release",
);
const resolved = resolveEnum("gameVersionOptions", input.gameVersion, "full_release");
valueEn = resolved.en;
valueLocal = resolved.local;
}
const b = bullet(
"description.playthroughNotes.labels.gameVersion",
valueEn,
valueLocal,
);
const b = bullet("description.playthroughNotes.labels.gameVersion", valueEn, valueLocal);
if (b) bullets.push(b);
}
+3 -7
View File
@@ -19,9 +19,8 @@ import type { EndingEntry, EndingVideoRange, GeneratorInput } from "./types";
* 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 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}`;
@@ -66,10 +65,7 @@ export function sliceEndingsForVideo(
* 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 {
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 };
+4 -19
View File
@@ -1,8 +1,4 @@
import type {
FrameGenVendor,
FrameGenMultiplier,
UpscaleQuality,
} from "@config/graphics-settings";
import type { FrameGenVendor, FrameGenMultiplier, UpscaleQuality } from "@config/graphics-settings";
/**
* Vendor-aware filtering for upscaling-quality and frame-generation
@@ -21,19 +17,10 @@ import type {
* and by description-builder / editor-store / template-store to coerce
* invalid vendor×quality combos back to `"none"` on rehydrate.
*/
export function getValidUpscaleQualities(
vendor: FrameGenVendor,
): readonly UpscaleQuality[] {
export function getValidUpscaleQualities(vendor: FrameGenVendor): readonly UpscaleQuality[] {
switch (vendor) {
case "nvidia":
return [
"none",
"dlaa",
"quality",
"balanced",
"performance",
"ultra_performance",
] as const;
return ["none", "dlaa", "quality", "balanced", "performance", "ultra_performance"] as const;
case "amd":
return [
"none",
@@ -65,9 +52,7 @@ export function getValidUpscaleQualities(
}
}
export function getValidFrameGenMultipliers(
vendor: FrameGenVendor,
): readonly FrameGenMultiplier[] {
export function getValidFrameGenMultipliers(vendor: FrameGenVendor): readonly FrameGenMultiplier[] {
switch (vendor) {
case "nvidia":
return ["none", "x2", "x3", "x4"] as const;
+83
View File
@@ -0,0 +1,83 @@
import type { GeneratorOutput, CharLimitWarning } from "./types";
/**
* Whether a generated output may be copied, derived from the engine's own
* over-limit warnings.
*
* `renderAll` has always returned `warnings: CharLimitWarning[]` — and until
* v0.35.0 **nothing in the UI read it.** Instead, three separate ad-hoc
* over-limit checks had grown up in the components, each with a different
* blind spot: `CopyButton` coloured itself red but stayed clickable,
* `CopyAllBar` checked title and description but not tags *and* skipped every
* check on the multi-language path, and BatchPage passed no limits at all, so
* a 6000-character description copied silently.
*
* This module is the single derivation. Pure, no React — the same rule applies
* on the Output tab and in Batch.
*
* Note the engine's `checkTitleWarning` / `checkDescriptionWarning` only fire
* when a field is *strictly over* its limit, never at the 80% "getting close"
* threshold the character counter colours yellow. So a non-empty `warnings`
* array is an exact "YouTube will reject this" signal, safe to block on.
*/
export type LimitedField = CharLimitWarning["field"];
export interface LimitOverflow {
field: LimitedField;
current: number;
limit: number;
}
export interface OutputLimitStatus {
/** True when at least one field is over its limit. */
blocked: boolean;
/** One entry per offending field, deduped, in title → description → tags order. */
overflows: readonly LimitOverflow[];
}
export const EMPTY_LIMIT_STATUS: OutputLimitStatus = { blocked: false, overflows: [] };
/** Stable display order, independent of the order warnings were pushed. */
const FIELD_ORDER: readonly LimitedField[] = ["title", "description", "tags"];
function byFieldOrder(a: LimitOverflow, b: LimitOverflow): number {
return FIELD_ORDER.indexOf(a.field) - FIELD_ORDER.indexOf(b.field);
}
/**
* Read one output's over-limit state.
*
* Deliberately ignores `CharLimitWarning.message`, which is a hardcoded
* English sentence built inside the engine and therefore unusable in a
* localized UI. The UI renders `output.limits.*` keys from the numbers instead.
*/
export function getOutputLimitStatus(output: Pick<GeneratorOutput, "warnings">): OutputLimitStatus {
if (output.warnings.length === 0) return EMPTY_LIMIT_STATUS;
const overflows = output.warnings
.map(({ field, current, limit }) => ({ field, current, limit }))
.sort(byFieldOrder);
return { blocked: true, overflows };
}
/**
* Combine several outputs into one status — the multi-language Output tabs and
* the Copy-All-Batch blob, both of which concatenate text that may come from
* any of them.
*
* Deduped by field, keeping the worst offender, so five Batch rows all over on
* description produce one banner line rather than five.
*/
export function mergeLimitStatus(statuses: readonly OutputLimitStatus[]): OutputLimitStatus {
const worst = new Map<LimitedField, LimitOverflow>();
for (const status of statuses) {
for (const overflow of status.overflows) {
const existing = worst.get(overflow.field);
if (!existing || overflow.current > existing.current) {
worst.set(overflow.field, overflow);
}
}
}
if (worst.size === 0) return EMPTY_LIMIT_STATUS;
return { blocked: true, overflows: [...worst.values()].sort(byFieldOrder) };
}
+80
View File
@@ -21,6 +21,38 @@ export interface PlaylistInput {
totalVideos?: number;
storeLinks?: Partial<Record<string, string>>;
playlistNote?: string;
/**
* Selected dropped-reason ids (see `@config/dropped-reasons`). Only
* rendered when {@link status} is "dropped". v0.31.0
*/
droppedReasons?: string[];
/** Free-text custom dropped reason, appended after the predefined ones. v0.31.0 */
droppedReasonCustom?: string;
/**
* Playlist URL, reused from the editor store — drives the pinned-comment
* "watch the full playlist" line. Empty/absent omits the line. v0.31.0
*/
playlistLink?: string;
}
/**
* Dropped-reason bullet lines, shared by the description and the comment.
* Empty unless the playlist is actually dropped. Each predefined id resolves
* via `playlist.droppedReasons.<id>`; an unresolved key (missing translation)
* is skipped rather than printed raw. The free-text custom reason, when set,
* is appended last.
*/
function buildDroppedReasonBullets(input: PlaylistInput, t: TranslationFn): string[] {
if (input.status !== "dropped") return [];
const bullets: string[] = [];
for (const id of input.droppedReasons ?? []) {
const key = `playlist.droppedReasons.${id}`;
const label = t(key);
if (label && label !== key) bullets.push(`• ${label}`);
}
const custom = input.droppedReasonCustom?.trim();
if (custom) bullets.push(`• ${custom}`);
return bullets;
}
export function buildPlaylistTitle(input: PlaylistInput, t: TranslationFn): string {
@@ -43,6 +75,15 @@ export function buildPlaylistDescription(input: PlaylistInput, t: TranslationFn)
lines.push("");
// Dropped reasons (v0.31.0) — only when the series is marked dropped and
// at least one reason (predefined or custom) is present.
const droppedBullets = buildDroppedReasonBullets(input, t);
if (droppedBullets.length > 0) {
lines.push(t("playlist.droppedHeading"));
lines.push(...droppedBullets);
lines.push("");
}
if (input.totalVideos && input.totalVideos > 0) {
lines.push(t("playlist.videoCount", { count: String(input.totalVideos) }));
lines.push("");
@@ -71,3 +112,42 @@ export function buildPlaylistDescription(input: PlaylistInput, t: TranslationFn)
return lines.join("\n");
}
/**
* Pinned-comment template for the playlist's most-recent video (v0.31.0).
* Status-adaptive: the opening line changes per status, and a dropped
* playlist appends its reasons. Mirrors {@link buildPinnedComment}'s idioms
* — sub-key composition, `t(key) === key` missing-key fallback, blocks
* joined by a blank line, "" when nothing renders. Pure.
*/
export function buildPlaylistComment(input: PlaylistInput, t: TranslationFn): string {
const blocks: string[] = [];
const openingKey = `playlist.comment.opening.${input.status}`;
const opening = t(openingKey, { gameName: input.gameName });
if (opening && opening !== openingKey) blocks.push(opening);
if (input.totalVideos && input.totalVideos > 0) {
const count = t("playlist.videoCount", { count: String(input.totalVideos) });
if (count && count !== "playlist.videoCount") blocks.push(count);
}
const link = input.playlistLink?.trim();
if (link) {
const linkLine = t("playlist.comment.playlistPrompt", { link });
if (linkLine && linkLine !== "playlist.comment.playlistPrompt") blocks.push(linkLine);
}
const droppedBullets = buildDroppedReasonBullets(input, t);
if (droppedBullets.length > 0) {
const introKey = "playlist.comment.droppedReasonsIntro";
const intro = t(introKey);
const introLine = intro && intro !== introKey ? `${intro}\n` : "";
blocks.push(`${introLine}${droppedBullets.join("\n")}`);
}
const engagement = t("playlist.comment.engagement");
if (engagement && engagement !== "playlist.comment.engagement") blocks.push(engagement);
return blocks.filter((b) => b.trim() !== "").join("\n\n");
}
+4 -12
View File
@@ -75,10 +75,7 @@ function dedupeHashtags(tags: readonly string[]): string[] {
return out;
}
function buildHashtagLine(
input: GeneratorInput,
popular: readonly string[],
): string {
function buildHashtagLine(input: GeneratorInput, popular: readonly string[]): string {
const gameName = input.gameNameLocalized?.[input.language] ?? input.gameName;
const primaryGenre = input.genres[0];
const derived = [
@@ -94,8 +91,7 @@ export function buildSocialPost(
t: TranslationFn,
options: SocialPostOptions,
): SocialPostOutput {
const { charLimit, popularHashtags, showCopyright, showSponsorCredit, tEn } =
options;
const { charLimit, popularHashtags, showCopyright, showSponsorCredit, tEn } = options;
// Title — short-form, so the `[2K 60FPS]` badge is suppressed.
const title = buildTitle(input, t, { showQualityBadge: false });
@@ -111,9 +107,7 @@ export function buildSocialPost(
tEn,
) ?? "",
thanks:
showSponsorCredit &&
input.sponsorName?.trim() &&
input.sponsorPlatform?.trim()
showSponsorCredit && input.sponsorName?.trim() && input.sponsorPlatform?.trim()
? t("description.sections.sponsorCredit", {
sponsor: input.sponsorName.trim(),
platform: input.sponsorPlatform.trim(),
@@ -132,9 +126,7 @@ export function buildSocialPost(
// Track which optional blocks are still present; drop in priority order
// until the caption fits. Title + hashtags are always kept.
const present = new Set<BlockId>(
DISPLAY_ORDER.filter((id) => blocks[id].trim() !== ""),
);
const present = new Set<BlockId>(DISPLAY_ORDER.filter((id) => blocks[id].trim() !== ""));
const assemble = (): string => {
const parts: string[] = [title];
+112 -44
View File
@@ -23,11 +23,7 @@ const QUALIFIER_SUFFIX_RE =
* Pure — exported for testing.
*/
export function sanitizeForTag(name: string): string {
return name
.replace(/[™®©]/g, "")
.replace(/[,;|]/g, " ")
.replace(/\s+/g, " ")
.trim();
return name.replace(/[™®©]/g, "").replace(/[,;|]/g, " ").replace(/\s+/g, " ").trim();
}
/**
@@ -79,13 +75,45 @@ export function tagFriendlyGameName(name: string, budget: number): string {
* MULTILINGUAL_TAGS.
*/
const GENRE_TAG_REGISTRY: Record<string, (gameName: string) => string[]> = {
action: (g) => [`${g} action`, "action game no commentary", "action adventure gameplay", `${g} combat`],
horror: (g) => [`${g} horror`, "horror game no commentary", "survival horror gameplay", `${g} scary`],
rpg: (g) => [`${g} RPG`, "RPG no commentary", "RPG gameplay", "JRPG no commentary", `${g} role playing`],
action: (g) => [
`${g} action`,
"action game no commentary",
"action adventure gameplay",
`${g} combat`,
],
horror: (g) => [
`${g} horror`,
"horror game no commentary",
"survival horror gameplay",
`${g} scary`,
],
rpg: (g) => [
`${g} RPG`,
"RPG no commentary",
"RPG gameplay",
"JRPG no commentary",
`${g} role playing`,
],
fps: (g) => [`${g} FPS`, "FPS no commentary", "shooter gameplay no commentary", `${g} shooter`],
openworld: (g) => [`${g} open world`, "open world no commentary", "free roam gameplay", `${g} exploration`],
indie: (g) => [`${g} indie`, `${g} indie game`, "indie game no commentary", "indie gameplay", "best indie games"],
soulslike: (g) => [`${g} souls like`, "soulsborne no commentary", "souls like gameplay", `${g} hardcore`],
openworld: (g) => [
`${g} open world`,
"open world no commentary",
"free roam gameplay",
`${g} exploration`,
],
indie: (g) => [
`${g} indie`,
`${g} indie game`,
"indie game no commentary",
"indie gameplay",
"best indie games",
],
soulslike: (g) => [
`${g} souls like`,
"soulsborne no commentary",
"souls like gameplay",
`${g} hardcore`,
],
racing: (g) => [`${g} racing`, "racing game no commentary", "racing gameplay", `${g} cars`],
story: (g) => [
`${g} story`,
@@ -94,9 +122,19 @@ const GENRE_TAG_REGISTRY: Record<string, (gameName: string) => string[]> = {
"narrative gameplay",
"cinematic adventure no commentary",
],
simulation: (g) => [`${g} simulation`, "simulation game no commentary", "strategy gameplay", `${g} sim`],
simulation: (g) => [
`${g} simulation`,
"simulation game no commentary",
"strategy gameplay",
`${g} sim`,
],
fighting: (g) => [`${g} fighting`, "fighting game no commentary", "combo gameplay", `${g} fight`],
stealth: (g) => [`${g} stealth`, "stealth game no commentary", "stealth gameplay", `${g} ghost run`],
stealth: (g) => [
`${g} stealth`,
"stealth game no commentary",
"stealth gameplay",
`${g} ghost run`,
],
survival_craft: (g) => [
`${g} survival`,
"survival crafting no commentary",
@@ -112,15 +150,45 @@ const GENRE_TAG_REGISTRY: Record<string, (gameName: string) => string[]> = {
],
mmo: (g) => [`${g} MMO`, "MMO no commentary", "MMORPG gameplay", `${g} online`],
rhythm: (g) => [`${g} rhythm`, "rhythm game no commentary", "music game gameplay", `${g} music`],
puzzle: (g) => [`${g} puzzle`, "puzzle game no commentary", "brain teaser gameplay", `${g} logic`],
tower_defense: (g) => [`${g} tower defense`, "tower defense no commentary", "TD gameplay", `${g} strategy`],
card_game: (g) => [`${g} card game`, "deck builder no commentary", "card game gameplay", `${g} TCG`],
battle_royale: (g) => [`${g} battle royale`, "battle royale no commentary", "BR gameplay", `${g} solo`],
puzzle: (g) => [
`${g} puzzle`,
"puzzle game no commentary",
"brain teaser gameplay",
`${g} logic`,
],
tower_defense: (g) => [
`${g} tower defense`,
"tower defense no commentary",
"TD gameplay",
`${g} strategy`,
],
card_game: (g) => [
`${g} card game`,
"deck builder no commentary",
"card game gameplay",
`${g} TCG`,
],
battle_royale: (g) => [
`${g} battle royale`,
"battle royale no commentary",
"BR gameplay",
`${g} solo`,
],
crpg: (g) => [`${g} CRPG`, "CRPG no commentary", "isometric RPG gameplay", `${g} party`],
tactical: (g) => [`${g} tactical`, "tactical game no commentary", "turn based strategy", `${g} tactics`],
tactical: (g) => [
`${g} tactical`,
"tactical game no commentary",
"turn based strategy",
`${g} tactics`,
],
space: (g) => [`${g} space`, "space game no commentary", "sci-fi gameplay", `${g} sci fi`],
farming: (g) => [`${g} farming`, "farming sim no commentary", "cozy game gameplay", `${g} cozy`],
fmv: (g) => [`${g} FMV`, "FMV game no commentary", "interactive movie gameplay", `${g} live action`],
fmv: (g) => [
`${g} FMV`,
"FMV game no commentary",
"interactive movie gameplay",
`${g} live action`,
],
visual_novel: (g) => [
`${g} visual novel`,
`${g} VN no commentary`,
@@ -158,12 +226,7 @@ const GENRE_TAG_REGISTRY: Record<string, (gameName: string) => string[]> = {
`${g} atmospheric horror`,
"mind bending horror gameplay",
],
jrpg: (g) => [
`${g} JRPG`,
"JRPG no commentary",
`${g} japanese RPG`,
"turn based JRPG gameplay",
],
jrpg: (g) => [`${g} JRPG`, "JRPG no commentary", `${g} japanese RPG`, "turn based JRPG gameplay"],
action_rpg: (g) => [
`${g} action RPG`,
"action RPG no commentary",
@@ -194,12 +257,7 @@ const GENRE_TAG_REGISTRY: Record<string, (gameName: string) => string[]> = {
`${g} loot and extract`,
"extraction FPS gameplay",
],
shmup: (g) => [
`${g} shmup`,
`${g} bullet hell`,
"shoot em up no commentary",
"danmaku gameplay",
],
shmup: (g) => [`${g} shmup`, `${g} bullet hell`, "shoot em up no commentary", "danmaku gameplay"],
city_builder: (g) => [
`${g} city builder`,
"city builder no commentary",
@@ -259,13 +317,7 @@ const VIDEO_TYPE_TAGS: Record<string, (gameName: string) => string[]> = {
`${g} completionist no commentary`,
`${g} achievement guide`,
],
livestream: (g) => [
"livestream",
"live gameplay",
`${g} live`,
`${g} stream`,
`${g} livestream`,
],
livestream: (g) => ["livestream", "live gameplay", `${g} live`, `${g} stream`, `${g} livestream`],
// One pool for the whole gacha bucket — quest-type-specific tags
// would balloon the pool and rarely surface in YouTube search anyway.
// The intro / title / hashtags already carry the per-quest framing.
@@ -317,8 +369,22 @@ const CORE_TAGS_BY_LANG: Record<SupportedLanguage, (gameName: string) => string[
`${g} guía`,
`${g} español`,
],
ko: (g) => [`${g} 게임플레이`, `${g} 무편집`, "게임플레이 무편집", `${g} 공략`, `${g} 플레이`, `${g} 한국어`],
zh: (g) => [`${g} 游戏实况`, `${g} 无解说`, "游戏实况 无解说", `${g} 攻略`, `${g} 流程`, `${g} 通关`],
ko: (g) => [
`${g} 게임플레이`,
`${g} 무편집`,
"게임플레이 무편집",
`${g} 공략`,
`${g} 플레이`,
`${g} 한국어`,
],
zh: (g) => [
`${g} 游戏实况`,
`${g} 无解说`,
"游戏实况 无解说",
`${g} 攻略`,
`${g} 流程`,
`${g} 通关`,
],
};
/**
@@ -362,7 +428,11 @@ function getQualityTags(gameName: string, resolution?: string, fps?: string): st
function getTrendingTags(gameName: string, genre: string): string[] {
const year = new Date().getFullYear().toString();
const genreLabel = humanizeId(genre);
return [`${gameName} ${year}`, `best ${genreLabel} games ${year}`, `${genreLabel} gameplay ${year}`];
return [
`${gameName} ${year}`,
`best ${genreLabel} games ${year}`,
`${genreLabel} gameplay ${year}`,
];
}
export interface TagOptions {
@@ -372,9 +442,7 @@ export interface TagOptions {
export function generateTags(input: GeneratorInput, options?: TagOptions): string[] {
const { includeMultilingualTags = true, includeTrendingTags = true } = options ?? {};
const rawName = sanitizeForTag(
input.gameNameLocalized?.[input.language] ?? input.gameName,
);
const rawName = sanitizeForTag(input.gameNameLocalized?.[input.language] ?? input.gameName);
// Two friendly forms of the game name:
// • bareNameTag — fits the per-tag 30-char limit; always added so the
+32 -1
View File
@@ -10,7 +10,20 @@ import { buildDescription, checkDescriptionWarning } from "./description-builder
import { generateTags, formatTagString, type TagOptions } from "./tag-generator";
import { YT_LIMITS } from "./types";
export interface RenderOptions extends TagOptions {
/**
* Every {@link RenderOptions} knob that comes from the user's Settings.
*
* Split out from the per-caller knobs deliberately. Before v0.35.0 each of the
* three `renderAll` call sites hand-copied this list out of the settings store,
* and BatchPage's copy was missing `splitContactEmail` and `showThirdPartyAds`
* — so a creator with the split-email toggle on saw all three contact lines on
* the Output tab and only the old single "Business inquiries" line in Batch.
*
* Naming the set lets `buildRenderOptions` return `Required<SettingsRenderOptions>`,
* which makes a forgotten key a compile error rather than a silent omission.
* See `src/hooks/use-render-options.ts` and its parity test.
*/
export interface SettingsRenderOptions extends TagOptions {
hashtagCount?: number;
/**
* When true, buildTitle appends a `[2K 60FPS]`-style badge to the
@@ -47,6 +60,12 @@ export interface RenderOptions extends TagOptions {
* music section (v0.11).
*/
showThirdPartyAds?: boolean;
/**
* When true, the description's contact block splits into up to three
* labeled lines by purpose (general / advertising / game keys &
* playtest) instead of the single "📧 Business inquiries" line. v0.34.0.
*/
splitContactEmail?: boolean;
/**
* When true and the editor's `pubDevName` is non-empty, the description
* emits a `© {publisher}. All rights reserved.` line right after the
@@ -60,6 +79,15 @@ export interface RenderOptions extends TagOptions {
* v0.24.0.
*/
showTranslationQuality?: boolean;
}
/**
* The knobs a *caller* decides, not the user. These vary by render surface —
* the Output tab wants bilingual content blocks, the multi-language tabs and
* Batch do not — so they are supplied per call site rather than read from
* Settings.
*/
export interface RenderOptionOverrides {
/**
* Optional English-fixed translation function. Used by the v0.11
* unified content-warnings block to render bilingual lines
@@ -77,6 +105,8 @@ export interface RenderOptions extends TagOptions {
bilingualContentBlocks?: boolean;
}
export interface RenderOptions extends SettingsRenderOptions, RenderOptionOverrides {}
export function renderAll(
input: GeneratorInput,
t: TranslationFn,
@@ -94,6 +124,7 @@ export function renderAll(
showUsagePolicy: options?.showUsagePolicy,
showSponsorCredit: options?.showSponsorCredit,
showThirdPartyAds: options?.showThirdPartyAds,
splitContactEmail: options?.splitContactEmail,
showGameCopyright: options?.showGameCopyright,
showTranslationQuality: options?.showTranslationQuality,
tEn: options?.tEn,
+4 -11
View File
@@ -198,10 +198,7 @@ export function buildGachaPartSuffix(
* endings. The Output page passes the index when looping over
* `endingVideoCount`; bare generation (no index) sees the union.
*/
function buildStructuredEndingLabel(
input: GeneratorInput,
t: TranslationFn,
): string | null {
function buildStructuredEndingLabel(input: GeneratorInput, t: TranslationFn): string | null {
const endings: EndingEntry[] = input.endings ?? [];
if (endings.length === 0) return null;
@@ -209,8 +206,7 @@ function buildStructuredEndingLabel(
// 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 hasNumber = typeof e.number === "number" && Number.isFinite(e.number);
const hasName = (e.name ?? "").trim().length > 0;
return hasNumber || hasName;
});
@@ -235,9 +231,7 @@ function buildStructuredEndingLabel(
.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,
);
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;
@@ -271,8 +265,7 @@ export function buildTitle(
const suffix = t("title.suffix");
const gameName =
input.gameNameLocalized?.[input.language] ?? input.gameName;
const gameName = input.gameNameLocalized?.[input.language] ?? input.gameName;
let badge = opts.showQualityBadge ? buildQualityBadge(input.resolution, input.fps) : "";
if (badge && opts.badgeCase === "lower") badge = badge.toLowerCase();
+44 -8
View File
@@ -8,6 +8,20 @@ import type {
} from "@config/graphics-settings";
import type { GachaQuestType } from "@config/gacha-quest-types";
// `GeneratorInput` exposes all of these on its own fields, so anyone typing a
// value to hand to the engine needs them too. Re-exported here so `@engine/types`
// is a complete public surface and callers don't have to reach into `@config/*`
// for a type the engine already speaks.
export type {
GraphicsPreset,
RTMode,
FrameGenVendor,
FrameGenMultiplier,
UpscaleQuality,
ArtStyle,
GachaQuestType,
};
export type VideoType =
| "full"
| "part"
@@ -114,14 +128,7 @@ export type PlaythroughStatus = (typeof PLAYTHROUGH_STATUSES)[number];
* difficulty names don't fit (e.g. "Lethal", "Fromsoft default").
* `"none"` → skip the section.
*/
export const DIFFICULTY_LEVELS = [
"none",
"easy",
"normal",
"hard",
"nightmare",
"custom",
] as const;
export const DIFFICULTY_LEVELS = ["none", "easy", "normal", "hard", "nightmare", "custom"] as const;
export type DifficultyLevel = (typeof DIFFICULTY_LEVELS)[number];
/**
@@ -656,6 +663,15 @@ export interface GeneratorInput {
timestamps?: string;
playlistLink?: string;
contactEmail?: string;
/**
* v0.34.0 email-split fields. Rendered as labeled lines inside the
* contact block when the `splitContactEmail` render option is on:
* `adEmail` (advertising / sponsorship inquiries — distinct from
* {@link sponsorName}) and `gameKeyEmail` (game keys & playtest
* invites). Each holds up to 3 comma-separated emails.
*/
adEmail?: string;
gameKeyEmail?: string;
/**
* Music / sound attribution credit. Free-form multiline string.
* When set, adds a "🎵 MUSIC / SOUND" section to the description
@@ -833,6 +849,26 @@ export interface GeneratorInput {
playtestLink?: string;
playtestPlatform?: string;
playtestInvites?: number;
/**
* Community invite links (v0.32.0). {@link messengerCommunityLink}
* (`https://m.me/ch/<id>`) renders for every language; {@link zaloGroupLink}
* (`https://zalo.me/g/<code>`) is gated on {@link language} === `"vi"`
* (Zalo is a Vietnam-audience app). Both feed a single "💬 COMMUNITY"
* block, which is omitted when it would be empty.
*/
messengerCommunityLink?: string;
zaloGroupLink?: string;
/**
* More community invite links (v0.33.0), all rendered for every output
* language into the same "💬 COMMUNITY" block. {@link signalGroupLink}
* (`https://signal.group/#<id>`), {@link instagramGroupLink} (the IG
* group-chat invite `https://www.instagram.com/j/<id>` or
* `https://ig.me/j/<id>`), and {@link facebookGroupLink}
* (`https://facebook.com/groups/<id>`, moved here from the Social block).
*/
signalGroupLink?: string;
instagramGroupLink?: string;
facebookGroupLink?: string;
}
export interface GeneratorOutput {
+8 -2
View File
@@ -58,6 +58,8 @@ export function buildGeneratorInputFromEditor(
timestamps: state.timestamps,
playlistLink: state.playlistLink,
contactEmail: state.contactEmail,
adEmail: state.adEmail,
gameKeyEmail: state.gameKeyEmail,
musicAttribution: state.musicAttribution,
sponsorName: state.sponsorName,
sponsorPlatform: state.sponsorPlatform,
@@ -77,8 +79,7 @@ export function buildGeneratorInputFromEditor(
// means the engine should see the union (the slice helpers
// already short-circuit on `videoCount <= 1`, but skipping the
// pass-through here keeps the input cleaner for tests).
endingVideoIndex:
state.endingVideoCount > 1 ? state.endingVideoIndex : undefined,
endingVideoIndex: state.endingVideoCount > 1 ? state.endingVideoIndex : undefined,
languagePatch: state.languagePatch,
languagePatchCustom: state.languagePatchCustom,
gameVersion: state.gameVersion,
@@ -97,6 +98,11 @@ export function buildGeneratorInputFromEditor(
playtestLink: state.playtestLink,
playtestPlatform: state.playtestPlatform,
playtestInvites: state.playtestInvites,
messengerCommunityLink: state.messengerCommunityLink,
zaloGroupLink: state.zaloGroupLink,
signalGroupLink: state.signalGroupLink,
instagramGroupLink: state.instagramGroupLink,
facebookGroupLink: state.facebookGroupLink,
};
}
+31
View File
@@ -0,0 +1,31 @@
import { useCallback } from "react";
import toast from "react-hot-toast";
import { useTranslation } from "react-i18next";
import type { SaveOutcome } from "@utils/file-ops";
/**
* Turn a {@link SaveOutcome} into the right user feedback, in one place.
*
* The rule that matters: **"cancelled" is silent.** Dismissing a save dialog is
* a decision, not a failure, and toasting "Export failed" at someone who
* pressed Escape is exactly the kind of thing that trains people to ignore
* toasts. Only a genuine write error says anything red.
*
* Six export buttons across five pages share this, which also retires the
* hardcoded English "Exported!" / "Export failed" strings those handlers
* carried before v0.35.0.
*/
export function useFileExport(): { report: (outcome: SaveOutcome) => void } {
const { t } = useTranslation("ui");
const report = useCallback(
(outcome: SaveOutcome) => {
if (outcome === "saved") toast.success(t("common.exported"));
else if (outcome === "failed") toast.error(t("common.exportFailed"));
// "cancelled" — deliberately nothing.
},
[t],
);
return { report };
}
+7 -48
View File
@@ -1,26 +1,13 @@
import { useMemo } from "react";
import i18n from "i18next";
import { useSettingsStore } from "@store/settings-store";
import { renderAll } from "@engine/template-renderer";
import { EMPTY_GENERATOR_OUTPUT, type GeneratorOutput } from "@engine/types";
import { useCurrentGeneratorInput } from "./use-current-generator-input";
import { useLanguagesReady } from "./use-languages-ready";
import { useRenderOptions } from "./use-render-options";
export function useGeneratedOutput(): GeneratorOutput {
const input = useCurrentGeneratorInput();
const {
includeMultilingualTags,
includeTrendingTags,
hashtagCount,
showQualityBadge,
showCopyright,
showUsagePolicy,
showSponsorCredit,
showGameCopyright,
showThirdPartyAds,
showTranslationQuality,
titleFormat,
} = useSettingsStore();
// Lazy-loaded locales (v0.26): block generation until the output
// language's bundle is in memory — getFixedT would otherwise silently
@@ -34,40 +21,12 @@ export function useGeneratedOutput(): GeneratorOutput {
// bundled, so it never needs the readiness gate.
const tEn = useMemo(() => i18n.getFixedT("en", "templates"), []);
// Every settings-derived option in one place — see use-render-options.ts for
// why this is a shared hook rather than a per-call-site destructure.
const options = useRenderOptions(tEn);
return useMemo(
() =>
!ready
? EMPTY_GENERATOR_OUTPUT
: renderAll(input, t, {
includeMultilingualTags,
includeTrendingTags,
hashtagCount,
showQualityBadge,
showCopyright,
showUsagePolicy,
showSponsorCredit,
showGameCopyright,
showThirdPartyAds,
showTranslationQuality,
titleFormat,
tEn,
}),
[
ready,
input,
t,
tEn,
includeMultilingualTags,
includeTrendingTags,
hashtagCount,
showQualityBadge,
showCopyright,
showUsagePolicy,
showSponsorCredit,
showGameCopyright,
showThirdPartyAds,
showTranslationQuality,
titleFormat,
],
() => (!ready ? EMPTY_GENERATOR_OUTPUT : renderAll(input, t, options)),
[ready, input, t, options],
);
}
+2 -12
View File
@@ -9,10 +9,7 @@ interface ShortcutOptions {
onToggleSidebar: () => void;
}
export function useKeyboardShortcuts({
onToggleHelp,
onToggleSidebar,
}: ShortcutOptions) {
export function useKeyboardShortcuts({ onToggleHelp, onToggleSidebar }: ShortcutOptions) {
const navigate = useNavigate();
const output = useGeneratedOutput();
const { copy } = useClipboard();
@@ -52,14 +49,7 @@ export function useKeyboardShortcuts({
window.addEventListener("keydown", handleKeyDown);
return () => window.removeEventListener("keydown", handleKeyDown);
}, [
navigate,
output.title,
output.description,
copy,
onToggleHelp,
onToggleSidebar,
]);
}, [navigate, output.title, output.description, copy, onToggleHelp, onToggleSidebar]);
}
/**
+1 -3
View File
@@ -12,9 +12,7 @@ import type { SupportedLanguage } from "@engine/types";
* deploy): `ensureLanguagesLoaded` logs the failure and the app degrades
* to English rather than hanging the UI.
*/
export function useLanguagesReady(
langs: readonly SupportedLanguage[],
): boolean {
export function useLanguagesReady(langs: readonly SupportedLanguage[]): boolean {
const joined = langs.join(",");
// Stable identity for the requested set — callers pass fresh array
// literals on every render.
+4 -46
View File
@@ -1,10 +1,10 @@
import { useMemo } from "react";
import i18n from "i18next";
import { useSettingsStore } from "@store/settings-store";
import { renderAll } from "@engine/template-renderer";
import type { GeneratorOutput, SupportedLanguage } from "@engine/types";
import { useCurrentGeneratorInput } from "./use-current-generator-input";
import { useLanguagesReady } from "./use-languages-ready";
import { useRenderOptions } from "./use-render-options";
export function useMultilangOutput(
languages: SupportedLanguage[],
@@ -14,19 +14,6 @@ export function useMultilangOutput(
// renders nothing for an absent tab entry, and the per-language chunks
// load in parallel, so partial results aren't worth the complexity.
const ready = useLanguagesReady(languages);
const {
includeMultilingualTags,
includeTrendingTags,
hashtagCount,
showQualityBadge,
showCopyright,
showUsagePolicy,
showSponsorCredit,
showGameCopyright,
showThirdPartyAds,
showTranslationQuality,
titleFormat,
} = useSettingsStore();
// Always-English `t` for the bilingual translation-quality disclaimer.
// In multi-language tabs each tab is already a single target language, so
@@ -36,6 +23,7 @@ export function useMultilangOutput(
// where `tEn` also makes those blocks bilingual `EN · LOCAL`. v0.29.3.
// `en` is eagerly bundled, so it never needs the readiness gate.
const tEn = useMemo(() => i18n.getFixedT("en", "templates"), []);
const options = useRenderOptions(tEn, false);
return useMemo(() => {
const results: Record<string, GeneratorOutput> = {};
@@ -43,38 +31,8 @@ export function useMultilangOutput(
for (const lang of languages) {
const tFn = i18n.getFixedT(lang, "templates");
const input = { ...baseInput, language: lang };
results[lang] = renderAll(input, tFn, {
includeMultilingualTags,
includeTrendingTags,
hashtagCount,
showQualityBadge,
showCopyright,
showUsagePolicy,
showSponsorCredit,
showGameCopyright,
showThirdPartyAds,
showTranslationQuality,
titleFormat,
tEn,
bilingualContentBlocks: false,
});
results[lang] = renderAll(input, tFn, options);
}
return results;
}, [
ready,
languages,
baseInput,
includeMultilingualTags,
includeTrendingTags,
hashtagCount,
showQualityBadge,
showCopyright,
showUsagePolicy,
showSponsorCredit,
showGameCopyright,
showThirdPartyAds,
showTranslationQuality,
titleFormat,
tEn,
]);
}, [ready, languages, baseInput, options]);
}
+15
View File
@@ -0,0 +1,15 @@
import { useMemo } from "react";
import { getOutputLimitStatus, mergeLimitStatus, type OutputLimitStatus } from "@engine/limits";
import type { GeneratorOutput } from "@engine/types";
/**
* Over-limit status for one output, or the merge of several.
*
* Pass a memoized array — an inline `[a, b]` literal changes identity every
* render and defeats the memo. Several outputs are merged when the copy target
* concatenates them (multi-language Copy All, Copy All Batch), because the
* resulting blob contains the offending text either way.
*/
export function useOutputLimits(outputs: readonly GeneratorOutput[]): OutputLimitStatus {
return useMemo(() => mergeLimitStatus(outputs.map(getOutputLimitStatus)), [outputs]);
}
Loaded 100 of 172 files, more files were not shown because too many files have changed in this diff. Show more