feat: Phase 1 MVP scaffold — core engine, i18n, UI, CI/CD

Complete Phase 1 implementation of YTDescGen:
- Project setup: Vite 5 + React 18 + TypeScript strict + Tailwind CSS dark theme
- Config layer: 7 video types, 10 genres, 7 platforms, rig/social fields
- i18n: EN/VI/JA with separate UI and template namespaces + validation script
- Core engine: title-builder, description-builder, tag-generator (pure TS, zero React)
- 42 unit tests covering all engine functions
- Zustand stores: editor + settings with localStorage persistence
- UI: 6 primitives, 11 editor components, 4 output components, 3 layout components
- Pages: Editor (form + quick preview) and Output (title/desc/tags + copy)
- CI/CD: GitHub Actions for lint/typecheck/test/build + GitHub Pages deploy

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
poli0981andClaude Opus 4.6 committed 2026-04-07 21:46:59 +07:00
1 parent da7aa855bb
commit a763f7c78a
82 files changed
+11145 -1

No files matched your search

+23
View File
@@ -0,0 +1,23 @@
name: CI
on:
push:
branches: [main, dev]
pull_request:
branches: [main]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
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
+31
View File
@@ -0,0 +1,31 @@
name: Deploy to GitHub Pages
on:
push:
branches: [main]
permissions:
contents: read
pages: write
id-token: write
jobs:
deploy:
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run build
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
with:
path: dist
- id: deployment
uses: actions/deploy-pages@v4
+10
View File
@@ -0,0 +1,10 @@
node_modules/
dist/
.env
.env.*
*.local
coverage/
.DS_Store
*.tsbuildinfo
.idea/
.claude/
+8
View File
@@ -0,0 +1,8 @@
{
"semi": true,
"singleQuote": false,
"trailingComma": "all",
"tabWidth": 2,
"printWidth": 100,
"plugins": ["prettier-plugin-tailwindcss"]
}
+297
View File
@@ -0,0 +1,297 @@
# CLAUDE.md — YouTube Description Generator (YTDescGen)
## Project Overview
**YTDescGen** is a desktop-capable web application that generates YouTube video titles, descriptions, and tags for Gameplay No Commentary channels. It supports multiple languages, game genres, and video types with a profile/preset system to eliminate repetitive data entry.
- **Repository**: `github.com/poli0981/yt-desc-gen` (private)
- **License**: MIT
- **Primary Language**: TypeScript
- **Stack**: React 18 + Vite + Tailwind CSS + Zustand + Tauri (desktop)
- **Target Platforms**: Web (GitHub Pages), Desktop (Windows/macOS via Tauri)
## Tech Stack
| Layer | Technology | Why |
|-------|-----------|-----|
| Framework | React 18 | Familiar from F2P tracker dashboard |
| Build | Vite 5 | Fast HMR, clean config |
| Language | TypeScript (strict) | Type safety for template engine |
| Styling | Tailwind CSS 3 | Utility-first, fast iteration |
| State | Zustand + persist middleware | Simple, localStorage/file persistence |
| Router | React Router 6 (HashRouter) | GitHub Pages compatible |
| i18n | i18next + react-i18next | Industry standard, lazy-load locales |
| Desktop | Tauri 2 | Lightweight Rust-based, ~5MB binary |
| Testing | Vitest + React Testing Library | Vite-native, fast |
| Lint | ESLint + Prettier | Consistent code style |
| CI/CD | GitHub Actions | Familiar workflow |
## Project Structure
```
yt-desc-gen/
├── CLAUDE.md # ← You are here
├── README.md
├── LICENSE
├── package.json
├── tsconfig.json
├── vite.config.ts
├── tailwind.config.ts
├── index.html
│
├── docs/ # Project documentation
│ ├── PRD.md # Product Requirements Document
│ ├── ARCHITECTURE.md # Technical architecture
│ ├── FEATURES.md # Complete feature list
│ ├── ROADMAP.md # Development phases
│ ├── TECH-SPEC.md # Technical specifications
│ ├── I18N.md # Internationalization guide
│ └── PACKAGING.md # Desktop packaging guide
│
├── src/
│ ├── main.tsx # Entry point
│ ├── App.tsx # Root component + router
│ ├── vite-env.d.ts
│ │
│ ├── config/ # Static data & constants
│ │ ├── video-types.ts # VIDEO_TYPES array
│ │ ├── genres.ts # GENRES array (extensible)
│ │ ├── platforms.ts # Store platforms (Steam, Epic, etc.)
│ │ ├── rig-fields.ts # Hardware field definitions
│ │ ├── social-fields.ts # Social/donate link definitions
│ │ └── defaults.ts # Default state values
│ │
│ ├── i18n/ # Internationalization
│ │ ├── index.ts # i18next setup
│ │ └── locales/
│ │ ├── en/
│ │ │ ├── ui.json # UI strings (buttons, labels)
│ │ │ └── templates.json # Description templates
│ │ ├── vi/
│ │ ├── ja/
│ │ ├── es/ # Spanish (example extension)
│ │ ├── ko/ # Korean (future)
│ │ ├── zh/ # Chinese (future)
│ │ └── _schema.json # JSON schema for locale validation
│ │
│ ├── engine/ # Core template engine (pure functions, no React)
│ │ ├── title-builder.ts # Title generation logic
│ │ ├── description-builder.ts # Description generation logic
│ │ ├── tag-generator.ts # Tag generation + dedup + char limit
│ │ ├── template-renderer.ts # Orchestrator: combines title + desc + tags
│ │ └── types.ts # Shared types for engine
│ │
│ ├── store/ # State management (Zustand)
│ │ ├── editor-store.ts # Current editor form state
│ │ ├── profile-store.ts # Saved profiles (social, rig, channel)
│ │ ├── preset-store.ts # Game presets (name + store links)
│ │ ├── history-store.ts # Generated output history
│ │ └── settings-store.ts # App settings (theme, default language)
│ │
│ ├── hooks/ # Custom React hooks
│ │ ├── use-generated-output.ts # Memoized template rendering
│ │ ├── use-clipboard.ts # Copy-to-clipboard with feedback
│ │ ├── use-char-count.ts # Character count with limit warning
│ │ └── use-debounce.ts # Input debouncing
│ │
│ ├── components/ # Reusable UI components
│ │ ├── ui/ # Primitives
│ │ │ ├── Button.tsx
│ │ │ ├── Input.tsx
│ │ │ ├── Textarea.tsx
│ │ │ ├── Toggle.tsx
│ │ │ ├── ChipGroup.tsx
│ │ │ ├── Select.tsx
│ │ │ ├── Badge.tsx
│ │ │ ├── Tooltip.tsx
│ │ │ ├── Modal.tsx
│ │ │ └── Toast.tsx
│ │ │
│ │ ├── editor/ # Editor-specific components
│ │ │ ├── VideoTypeSelector.tsx
│ │ │ ├── LanguageSelector.tsx
│ │ │ ├── GenreSelector.tsx
│ │ │ ├── GameInfoForm.tsx
│ │ │ ├── VideoSettingsForm.tsx
│ │ │ ├── TimestampEditor.tsx
│ │ │ ├── StoreLinkEditor.tsx
│ │ │ ├── RigEditor.tsx
│ │ │ ├── SocialEditor.tsx
│ │ │ ├── WarningToggles.tsx
│ │ │ └── QuickPreview.tsx
│ │ │
│ │ ├── output/ # Output display components
│ │ │ ├── OutputPreview.tsx
│ │ │ ├── TitleOutput.tsx
│ │ │ ├── DescriptionOutput.tsx
│ │ │ ├── TagOutput.tsx
│ │ │ ├── CharCounter.tsx
│ │ │ ├── CopyButton.tsx
│ │ │ └── CopyAllBar.tsx
│ │ │
│ │ ├── profiles/ # Profile management
│ │ │ ├── ProfileList.tsx
│ │ │ ├── ProfileCard.tsx
│ │ │ ├── ProfileSaveForm.tsx
│ │ │ └── GamePresetManager.tsx
│ │ │
│ │ └── layout/ # App shell
│ │ ├── AppShell.tsx
│ │ ├── Sidebar.tsx
│ │ ├── Header.tsx
│ │ └── TabBar.tsx
│ │
│ ├── pages/ # Route pages
│ │ ├── EditorPage.tsx
│ │ ├── OutputPage.tsx
│ │ ├── ProfilesPage.tsx
│ │ ├── HistoryPage.tsx
│ │ ├── SettingsPage.tsx
│ │ └── BatchPage.tsx
│ │
│ ├── utils/ # Shared utilities
│ │ ├── clipboard.ts
│ │ ├── char-count.ts
│ │ ├── sanitize.ts
│ │ ├── export.ts # JSON/CSV export
│ │ └── import.ts # JSON import
│ │
│ └── styles/
│ └── globals.css # Tailwind directives + custom vars
│
├── src-tauri/ # Tauri desktop shell (Phase 4)
│ ├── Cargo.toml
│ ├── tauri.conf.json
│ ├── src/
│ │ └── main.rs
│ └── icons/
│
├── tests/
│ ├── engine/ # Unit tests for template engine
│ │ ├── title-builder.test.ts
│ │ ├── description-builder.test.ts
│ │ └── tag-generator.test.ts
│ ├── store/ # Store tests
│ └── components/ # Component tests
│
├── scripts/ # Build/dev scripts
│ ├── validate-locales.ts # Validate all locale files have same keys
│ └── generate-locale-template.ts # Generate empty locale from schema
│
└── .github/
└── workflows/
├── ci.yml # Lint + test + build
├── deploy-web.yml # Deploy to GitHub Pages
└── release-desktop.yml # Build Tauri binaries
```
## Coding Conventions
### TypeScript
- Strict mode enabled (`strict: true` in tsconfig)
- Prefer `interface` over `type` for object shapes
- Use `const` assertions for static config arrays
- No `any` — use `unknown` + type guards
- Barrel exports via `index.ts` per directory
### React
- Functional components only, no class components
- Custom hooks for shared logic — prefix with `use`
- Memoize expensive computations with `useMemo`
- Use `React.lazy()` for page-level code splitting
- No prop drilling beyond 2 levels — use Zustand store
### Naming
- Files: `kebab-case.ts` / `PascalCase.tsx` for components
- Variables/functions: `camelCase`
- Types/interfaces: `PascalCase`
- Constants: `UPPER_SNAKE_CASE`
- Store slices: `use[Name]Store`
### Styling
- Tailwind utility classes — no inline styles, no CSS modules
- Custom colors defined in `tailwind.config.ts`
- Dark theme by default, optional light theme via class toggle
- Responsive: mobile-first, breakpoints at `sm`, `md`, `lg`
### i18n
- All user-facing strings go through `t()` function
- Template strings (description/title) use dedicated locale file
- UI strings and template strings are separate namespace files
- Never hardcode user-visible text in components
### State Management
- Zustand stores with `persist` middleware for localStorage
- Separate stores by domain (editor, profiles, presets, settings)
- Keep stores flat — no deep nesting
- Actions defined inside the store, not externally
### Engine (template logic)
- Pure functions only — no React dependencies
- 100% unit test coverage for engine/
- Each function takes typed input, returns string
- No side effects — no clipboard, no storage, no DOM
## Key Design Decisions
1. **Engine is framework-agnostic**: `src/engine/` has zero React imports. This allows reuse if migrating to another framework, CLI tool, or VS Code extension.
2. **i18n covers both UI and templates**: UI labels (`ui.json`) and generated content (`templates.json`) are separate. Adding a language means adding 2 JSON files + registering in config.
3. **Profiles vs Presets**: Profile = user identity (channel, social, rig — rarely changes). Preset = game identity (name, store links — reused across parts). These are separate stores.
4. **Tags are generated, not hand-written**: Tag engine combines genre pool + core pool + platform + quality + multilingual + trending. User can edit the final output but doesn't build tags manually.
5. **Tauri for desktop**: Chosen over Electron for ~5MB binary vs ~150MB. Familiar Rust toolchain. Web version works independently without Tauri.
## Development Commands
```bash
# Install dependencies
npm install
# Development server
npm run dev
# Build for web
npm run build
# Preview production build
npm run preview
# Run tests
npm run test
# Lint
npm run lint
# Type check
npm run typecheck
# Validate locale files
npm run validate:locales
# Desktop dev (requires Tauri CLI)
npm run tauri dev
# Desktop build
npm run tauri build
```
## Git Workflow
- `main` — stable releases
- `dev` — integration branch
- Feature branches: `feat/feature-name`
- Commit format: `type(scope): message`
- Types: `feat`, `fix`, `refactor`, `docs`, `test`, `ci`, `chore`
- Example: `feat(engine): add Spanish template support`
## Important Notes for Claude Code
- Always run `npm run typecheck` before committing
- When adding a new language: follow docs/I18N.md checklist
- When adding a new genre: add to `src/config/genres.ts` + tag pool in `src/engine/tag-generator.ts`
- When adding a new video type: add to `src/config/video-types.ts` + update all template files in `src/i18n/locales/*/templates.json`
- Engine tests must pass before any PR merge
- Keep bundle size under 500KB (excluding Tauri)
+56 -1
View File
@@ -1 +1,56 @@
# youtube-generator # 🎮 YTDescGen
**YouTube Gameplay Description Generator** — A template engine for Gameplay No Commentary channels.
Generate YouTube video titles, descriptions, and tags in multiple languages with one click.
## Features
- **14 video types** — Full Gameplay, Part, Boss Fight, Speedrun, 100%, DLC, and more
- **12 languages** — English, Vietnamese, Japanese, Spanish, Korean, Chinese, and more
- **25 game genres** — Action, Horror, RPG, FPS, Open World, Souls-like, and more
- **Profile system** — Save social/rig/channel info once, reuse forever
- **Game presets** — Save game info once, reuse for multi-part series
- **Smart tags** — Auto-generated from genre + platform + quality + multilingual
- **Character counters** — Real-time limits for title (100), description (5000), tags (500)
- **Batch mode** — Generate descriptions for multiple parts at once
- **Desktop app** — Windows & macOS via Tauri (~8MB binary)
- **Offline** — Full functionality without internet
## Quick Start
```bash
# Clone
git clone https://github.com/poli0981/yt-desc-gen.git
cd yt-desc-gen
# Install
npm install
# Dev
npm run dev
# Build
npm run build
```
## Tech Stack
React 18 • TypeScript • Vite • Tailwind CSS • Zustand • i18next • Tauri 2
## Documentation
| Document | Description |
|----------|-------------|
| [CLAUDE.md](./CLAUDE.md) | Claude Code instructions & project overview |
| [PRD](./docs/PRD.md) | Product Requirements Document |
| [Architecture](./docs/ARCHITECTURE.md) | Technical architecture & data flow |
| [Features](./docs/FEATURES.md) | Complete feature list |
| [Roadmap](./docs/ROADMAP.md) | Development phases & timeline |
| [Tech Spec](./docs/TECH-SPEC.md) | Implementation details & configs |
| [i18n Guide](./docs/I18N.md) | How to add new languages |
| [Packaging](./docs/PACKAGING.md) | Desktop app build guide |
## License
MIT
+347
View File
@@ -0,0 +1,347 @@
# Architecture Document
## YTDescGen — Technical Architecture
---
## 1. High-Level Architecture
```
┌─────────────────────────────────────────────────────────────┐
│ Presentation Layer │
│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌───────────────┐ │
│ │ Editor │ │ Output │ │ Profiles │ │ Batch / History│ │
│ │ Page │ │ Page │ │ Page │ │ Pages │ │
│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └──────┬────────┘ │
│ │ │ │ │ │
│ ┌────┴─────────────┴────────────┴───────────────┴────────┐ │
│ │ Shared Components (ui/, editor/, output/) │ │
│ └────────────────────────────┬────────────────────────────┘ │
├───────────────────────────────┼──────────────────────────────┤
│ Application Layer │
│ ┌────────────┐ ┌───────────┴──────────┐ ┌──────────────┐ │
│ │ Hooks │ │ State (Zustand) │ │ i18next │ │
│ │ useGenerate │ │ editor / profile / │ │ locales/ │ │
│ │ useClipboard│ │ preset / history / │ │ en/vi/ja/ │ │
│ │ useCharCount│ │ settings │ │ es/ko/zh │ │
│ └──────┬─────┘ └───────────┬───────────┘ └──────┬───────┘ │
├─────────┼────────────────────┼──────────────────────┼────────┤
│ Core Engine Layer │
│ ┌──────┴────────────────────┴──────────────────────┴──────┐ │
│ │ engine/ (Pure TypeScript) │ │
│ │ ┌──────────────┐ ┌──────────────────┐ ┌──────────────┐ │ │
│ │ │ title-builder│ │description-builder│ │ tag-generator│ │ │
│ │ └──────┬───────┘ └────────┬─────────┘ └──────┬───────┘ │ │
│ │ └──────────────────┼───────────────────┘ │ │
│ │ ┌────────┴────────┐ │ │
│ │ │template-renderer│ │ │
│ │ └─────────────────┘ │ │
│ └──────────────────────────────────────────────────────────┘ │
├──────────────────────────────────────────────────────────────┤
│ Infrastructure Layer │
│ ┌────────────────┐ ┌───────────────┐ ┌─────────────────┐ │
│ │ localStorage │ │ File System │ │ Clipboard API │ │
│ │ (Web) │ │ (Tauri) │ │ │ │
│ └────────────────┘ └───────────────┘ └─────────────────┘ │
└──────────────────────────────────────────────────────────────┘
```
## 2. Core Engine Design
Engine module chứa toàn bộ logic generate — **zero framework dependency**. Mọi function đều pure: input → string.
### 2.1 Type Definitions (`engine/types.ts`)
```typescript
// ── Video Types ──
type VideoType =
| "full" // Full Gameplay
| "part" // Gameplay Part X
| "boss" // Boss Fight
| "boss_nohit" // Boss No Hit
| "ending" // Ending / All Endings
| "speedrun" // Speedrun
| "100percent" // 100% Completion
| "dlc" // DLC Content
| "newgame_plus" // New Game+
| "challenge" // Challenge Run
| "side_quest" // Side Quest / Optional Content
| "secret" // Secret / Hidden Content
| "comparison" // Graphics / Version Comparison
| "guide"; // Silent Guide / Walkthrough
// ── Genre ──
type Genre =
| "action" | "horror" | "rpg" | "fps" | "openworld"
| "indie" | "soulslike" | "racing" | "story" | "simulation"
| "fighting" | "stealth" | "survival_craft" | "mmo"
| "rhythm" | "puzzle" | "roguelike" | "metroidvania"
| "tower_defense" | "card_game" | "battle_royale"
| "crpg" | "tactical" | "space" | "farming";
// ── Supported Languages ──
type SupportedLanguage = "en" | "vi" | "ja" | "es" | "ko" | "zh"
| "fr" | "de" | "pt" | "ru" | "th" | "ar";
// ── Input State ──
interface GeneratorInput {
// Core
videoType: VideoType;
language: SupportedLanguage;
genre: Genre;
// Game info
gameName: string;
gameNameLocalized?: Record<SupportedLanguage, string>; // optional localized game name
channelName: string;
platform: string;
// Video type-specific
partNumber?: string;
bossName?: string;
dlcName?: string;
challengeName?: string;
// Video settings
resolution?: string;
fps?: string;
graphicsPreset?: string;
// Content
timestamps?: string;
playlistLink?: string;
contactEmail?: string;
// Warnings
spoilerWarning: boolean;
matureWarning: boolean;
// Links
storeLinks: Record<string, string>;
social: Record<string, string>;
rig: Record<string, string>;
}
// ── Output ──
interface GeneratorOutput {
title: string;
description: string;
tags: string[];
tagString: string;
charCounts: {
title: number;
description: number;
tags: number;
};
warnings: string[]; // e.g. "Tags exceed 500 character limit"
}
```
### 2.2 Template Architecture
Templates sử dụng **data-driven approach** thay vì hardcode string concatenation:
```typescript
// i18n/locales/en/templates.json
{
"title": {
"separator": " — ",
"suffix": "Gameplay No Commentary",
"videoType": {
"full": "",
"part": "Part {{partNumber}}",
"boss": "{{bossName}} Boss Fight",
"boss_nohit": "{{bossName}} Boss No Hit",
"ending": "Ending",
"speedrun": "Speedrun",
"100percent": "100% Completion",
"dlc": "{{dlcName}} DLC",
"newgame_plus": "New Game+",
"challenge": "{{challengeName}} Challenge"
}
},
"description": {
"intro": {
"full": "This video features the full gameplay of {{gameName}} on {{channelName}}.",
"part": "This video features Part {{partNumber}} of {{gameName}} on {{channelName}}."
},
"noCommentaryLine": "No Commentary — pure gameplay for your enjoyment.",
"sections": {
"timestamps": "⏱ TIMESTAMPS",
"storeLinks": "🎮 GET THE GAME",
"videoSettings": "🖥 VIDEO SETTINGS: {{settings}}",
"rig": "💻 MY RIG",
"spoilerWarning": "⚠️ SPOILER WARNING: This video contains spoilers.",
"matureWarning": "🔞 MATURE CONTENT (18+): Contains violence / strong language.",
"playlist": "▶️ Watch the full series: {{link}}",
"contact": "📧 Business inquiries: {{email}}",
"cta": "👍 Like | 🔔 Subscribe | ↗️ Share"
}
}
}
```
### 2.3 Tag Generator Architecture
```
TagGenerator Pipeline:
┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
│ Core Pool│───→│Genre Pool│───→│ Platform │───→│ Quality │
│ (always) │ │(by genre)│ │ Pool │ │ Pool │
└──────────┘ └──────────┘ └──────────┘ └──────────┘
│ │ │ │
└───────────────┴──────────────┴───────────────┘
│
┌─────────┴─────────┐
│ VideoType Pool │
│ (boss, speedrun…) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Multilingual Pool │
│ (JA, VI, ES…) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Trending Pool │
│ (year-based) │
└─────────┬─────────┘
│
┌─────────┴─────────┐
│ Dedup (Set) │
│ + Priority Sort │
│ + 500 char trim │
└───────────────────┘
```
Tag pools là registry pattern — thêm genre mới chỉ cần thêm 1 entry:
```typescript
// engine/tag-generator.ts
const TAG_REGISTRY: Record<Genre, (gameName: string) => string[]> = {
action: (g) => [`${g} action`, "action game no commentary", "action adventure gameplay"],
horror: (g) => [`${g} horror`, "horror game no commentary", "survival horror gameplay"],
// ... thêm genre ở đây
};
```
## 3. State Architecture
```
Zustand Stores:
┌───────────────────────────────────────────────┐
│ EditorStore │
│ - videoType, language, genre │
│ - gameName, channelName, platform │
│ - timestamps, storeLinks, rig, social │
│ - spoilerWarning, matureWarning │
│ Middleware: none (ephemeral per session) │
│ + persist: auto-save draft (debounced) │
├───────────────────────────────────────────────┤
│ ProfileStore │
│ - profiles: Profile[] │
│ - activeProfileId: string | null │
│ Middleware: persist (localStorage) │
├───────────────────────────────────────────────┤
│ PresetStore │
│ - gamePresets: GamePreset[] │
│ Middleware: persist (localStorage) │
├───────────────────────────────────────────────┤
│ HistoryStore │
│ - entries: HistoryEntry[] (max 100) │
│ Middleware: persist (localStorage, pruned) │
├───────────────────────────────────────────────┤
│ SettingsStore │
│ - theme: "dark" | "light" │
│ - defaultLanguage: SupportedLanguage │
│ - defaultGenre: Genre │
│ - autoSaveDraft: boolean │
│ Middleware: persist (localStorage) │
└───────────────────────────────────────────────┘
```
## 4. i18n Architecture
```
i18n/locales/
├── en/
│ ├── ui.json # UI strings: buttons, labels, tooltips, errors
│ └── templates.json # Generated content: title patterns, description sections
├── vi/
│ ├── ui.json
│ └── templates.json
├── ja/
│ ├── ui.json
│ └── templates.json
└── _schema.json # JSON Schema — validates all locale files have same keys
```
**Adding a new language** = 2 JSON files + 1 line registration. See docs/I18N.md.
**UI language vs Output language**: These are independent. User can browse the app in English but generate descriptions in Japanese. UI language follows `SettingsStore.defaultLanguage`, output language follows `EditorStore.language`.
## 5. Desktop Packaging (Tauri)
```
Web App (React + Vite)
│
▼
┌───────────────────┐
│ Tauri Shell │
│ ┌──────────────┐ │
│ │ WebView │ │ ← Renders the same React app
│ │ (system) │ │
│ └──────────────┘ │
│ ┌──────────────┐ │
│ │ Rust Core │ │ ← File system access, clipboard, tray
│ └──────────────┘ │
└───────────────────┘
│
▼
Binary output:
- Windows: .msi / .exe (~8MB)
- macOS: .dmg / .app (~10MB)
```
Tauri advantages over Electron:
- Binary size: ~8MB vs ~150MB
- Memory: ~30MB vs ~100MB+
- No bundled Chromium — uses system WebView
- Rust backend for native features
## 6. Extensibility Points
| What | How to Extend | Files to Touch |
|------|--------------|----------------|
| New language | Add `locales/{code}/ui.json` + `templates.json`, register in `i18n/index.ts` | 3 files |
| New genre | Add entry to `config/genres.ts`, add tag pool to `engine/tag-generator.ts` | 2 files |
| New video type | Add to `config/video-types.ts`, add patterns to all `templates.json` | 1 + N locale files |
| New platform/store | Add entry to `config/platforms.ts` | 1 file |
| New social link | Add entry to `config/social-fields.ts` | 1 file |
| New rig field | Add entry to `config/rig-fields.ts` | 1 file |
| Custom template | Edit `templates.json` for target language | 1 file |
| Desktop feature | Add Tauri command in `src-tauri/src/main.rs` | 1 file |
## 7. Data Flow
```
User Input (form)
│
▼
EditorStore (Zustand)
│
├──→ useGeneratedOutput hook
│ │
│ ├──→ titleBuilder(input, locale) → title string
│ ├──→ descriptionBuilder(input, locale) → description string
│ ├──→ tagGenerator(input) → tags string[]
│ │
│ └──→ GeneratorOutput (memoized)
│ │
│ ▼
│ OutputPage (display + copy)
│
├──→ ProfileStore.save() ──→ localStorage
├──→ PresetStore.save() ──→ localStorage
└──→ HistoryStore.add() ──→ localStorage
```
+280
View File
@@ -0,0 +1,280 @@
# Complete Feature List
## YTDescGen — All Features (Current + Planned)
---
## 🎬 Video Types (14 types)
| ID | Label (EN) | Label (VI) | Label (JA) | Extra Fields |
|----|-----------|------------|------------|--------------|
| `full` | Full Gameplay | Full Gameplay | フルゲームプレイ | — |
| `part` | Gameplay Part | Gameplay Phần | ゲームプレイ パート | `partNumber` |
| `boss` | Boss Fight | Boss Fight | ボス戦 | `bossName` |
| `boss_nohit` | Boss No Hit | Boss No Hit | ボス ノーヒット | `bossName` |
| `ending` | Ending / All Endings | Kết thúc | エンディング | — |
| `speedrun` | Speedrun | Speedrun | スピードラン | — |
| `100percent` | 100% Completion | 100% Completion | 100%クリア | — |
| `dlc` | DLC Content | Nội dung DLC | DLCコンテンツ | `dlcName` |
| `newgame_plus` | New Game+ | New Game+ | 強くてニューゲーム | — |
| `challenge` | Challenge Run | Challenge Run | チャレンジラン | `challengeName` |
| `side_quest` | Side Quests | Nhiệm vụ phụ | サブクエスト | — |
| `secret` | Secrets / Hidden | Bí mật | 隠し要素 | — |
| `comparison` | Graphics Comparison | So sánh đồ họa | グラフィック比較 | — |
| `guide` | Silent Guide | Hướng dẫn | 攻略ガイド | — |
## 🌐 Languages (12 languages)
### Launch (Phase 1)
| Code | Language | Native Name | Status |
|------|----------|-------------|--------|
| `en` | English | English | ✅ Ready |
| `vi` | Vietnamese | Tiếng Việt | ✅ Ready |
| `ja` | Japanese | 日本語 | ✅ Ready |
### Phase 2
| Code | Language | Native Name |
|------|----------|-------------|
| `es` | Spanish | Español |
| `ko` | Korean | 한국어 |
| `zh` | Chinese (Simplified) | 简体中文 |
### Phase 3+
| Code | Language | Native Name |
|------|----------|-------------|
| `fr` | French | Français |
| `de` | German | Deutsch |
| `pt` | Portuguese | Português |
| `ru` | Russian | Русский |
| `th` | Thai | ภาษาไทย |
| `ar` | Arabic | العربية |
Each language requires:
- `ui.json` — UI labels, buttons, placeholders, error messages
- `templates.json` — Title patterns, description sections, CTA text
## 🎮 Game Genres (25 genres)
| ID | Label | Icon | Tag Keywords (sample) |
|----|-------|------|-----------------------|
| `action` | Action / Adventure | ⚔️ | action game, hack and slash, action adventure |
| `horror` | Horror / Survival | 👻 | horror game, survival horror, scary game, psychological horror |
| `rpg` | RPG / JRPG | 🛡 | RPG, JRPG, action RPG, turn based RPG |
| `fps` | FPS / Shooter | 🔫 | FPS, shooter, tactical shooter, third person shooter |
| `openworld` | Open World / Sandbox | 🌍 | open world, sandbox, free roam, exploration |
| `indie` | Indie / Platformer | 🕹 | indie game, platformer, pixel art |
| `soulslike` | Souls-like | 💀 | souls like, soulsborne, boss fight, no death run |
| `racing` | Racing / Sports | 🏎 | racing game, driving sim, sports game |
| `story` | Story / Visual Novel | 📖 | story game, visual novel, narrative game, interactive drama |
| `simulation` | Simulation / Strategy | 🏗 | simulation, city builder, management, tycoon |
| `fighting` | Fighting | 🥊 | fighting game, combo, versus, arcade |
| `stealth` | Stealth / Espionage | 🥷 | stealth game, stealth gameplay, infiltration |
| `survival_craft` | Survival / Crafting | 🏕 | survival game, crafting, base building |
| `mmo` | MMO / Online | 🌐 | MMO, MMORPG, online game, multiplayer |
| `rhythm` | Rhythm / Music | 🎵 | rhythm game, music game, beat game |
| `puzzle` | Puzzle | 🧩 | puzzle game, brain teaser, logic game |
| `roguelike` | Roguelike / Roguelite | 🎲 | roguelike, roguelite, procedural, permadeath |
| `metroidvania` | Metroidvania | 🗺 | metroidvania, exploration, ability unlock |
| `tower_defense` | Tower Defense | 🏰 | tower defense, TD game, strategy |
| `card_game` | Card / Deck Builder | 🃏 | card game, deck builder, TCG |
| `battle_royale` | Battle Royale | 🏆 | battle royale, last man standing, BR |
| `crpg` | CRPG / Isometric | 📜 | CRPG, isometric RPG, classic RPG |
| `tactical` | Tactical / Turn-based | ♟ | tactical, turn based strategy, XCOM-like |
| `space` | Space / Sci-Fi | 🚀 | space game, sci-fi, space exploration |
| `farming` | Farming / Life Sim | 🌾 | farming sim, life sim, cozy game |
## 🛒 Store Platforms (9 platforms)
| ID | Label | URL Prefix |
|----|-------|-----------|
| `steam` | Steam | `https://store.steampowered.com/app/` |
| `epic` | Epic Games Store | `https://store.epicgames.com/` |
| `ps` | PlayStation Store | `https://store.playstation.com/` |
| `xbox` | Xbox / Microsoft Store | `https://www.xbox.com/games/` |
| `nintendo` | Nintendo eShop | `https://www.nintendo.com/store/` |
| `gog` | GOG | `https://www.gog.com/game/` |
| `itchio` | itch.io | `https://itch.io/` |
| `humble` | Humble Bundle | `https://www.humblebundle.com/store/` |
| `amazon` | Amazon Luna | `https://www.amazon.com/luna/` |
## ☕ Social & Donate Links (12 fields)
### Donate
| ID | Label | Prefix |
|----|-------|--------|
| `kofi` | Ko-fi | `https://ko-fi.com/` |
| `patreon` | Patreon | `https://patreon.com/` |
| `buymeacoffee` | Buy Me a Coffee | `https://buymeacoffee.com/` |
| `paypal` | PayPal | `https://paypal.me/` |
| `streamlabs` | Streamlabs | `https://streamlabs.com/` |
### Social
| ID | Label | Prefix |
|----|-------|--------|
| `github` | GitHub | `https://github.com/` |
| `twitter` | Twitter / X | `https://x.com/` |
| `discord` | Discord | `https://discord.gg/` |
| `twitch` | Twitch | `https://twitch.tv/` |
| `tiktok` | TikTok | `https://tiktok.com/@` |
| `instagram` | Instagram | `https://instagram.com/` |
| `website` | Website | — |
## 💻 Rig Fields (8 fields)
| ID | Label | Example |
|----|-------|---------|
| `cpu` | CPU | Intel i9-14900K / AMD Ryzen 9 7950X |
| `gpu` | GPU | NVIDIA RTX 4090 / AMD RX 7900 XTX |
| `ram` | RAM | 32GB DDR5-6000 |
| `storage` | Storage | 2TB Samsung 990 PRO NVMe |
| `motherboard` | Motherboard | ASUS ROG Maximus Z790 |
| `monitor` | Monitor | LG 27GP950 27" 4K 144Hz |
| `capture` | Capture Software | OBS Studio 30.x |
| `controller` | Controller | DualSense / Xbox Elite Series 2 |
## 📄 Output Sections (Description Structure)
Mỗi ngôn ngữ có description structure như sau (tất cả sections optional):
```
1. Intro line (auto-generated from video type + game name)
2. No Commentary tagline
3. ─── Timestamps ─── (if provided)
4. ─── Store Links ─── (if any platform link provided)
5. ─── Video Settings ─── (resolution / FPS / graphics)
6. ─── My Rig ─── (if any rig field provided)
7. ─── Spoiler Warning ─── (if toggled)
8. ─── 18+ Warning ─── (if toggled)
9. ─── Donate Links ─── (if any provided)
10. ─── Social Links ─── (if any provided)
11. ─── Playlist Link ─── (if provided)
12. ─── Contact Email ─── (if provided)
13. CTA line (Like / Subscribe / Share)
14. Hashtags (3 max, auto-generated)
```
## 🏷 Tag Generation
### Tag Pools by Category
| Pool | Triggered By | Sample Output |
|------|-------------|---------------|
| Core | Always | `[game] gameplay`, `[game] no commentary`, `gameplay no commentary` |
| Genre | Genre selection | `horror game no commentary`, `RPG gameplay no commentary` |
| VideoType | Video type | `[game] boss fight`, `[game] speedrun`, `[game] all endings` |
| Platform | Platform field | `[game] PC`, `PC gameplay`, `[game] Steam` |
| Quality | Resolution/FPS | `[game] 4K`, `4K gameplay no commentary`, `[game] 4K 60FPS` |
| Multilingual JA | Always | `[game] ゲームプレイ`, `[game] 実況なし` |
| Multilingual VI | Always | `[game] gameplay không bình luận` |
| Multilingual ES | If ES enabled | `[game] sin comentarios`, `juego de acción` |
| Trending | Always | `[game] 2026`, `best [genre] games 2026` |
### Tag Pipeline
1. Collect tags from all applicable pools
2. Deduplicate (Set-based)
3. Priority sort (core first, trending last)
4. Trim to 500 character limit (drop lowest priority first)
5. Output as comma-separated string
## 💾 Data Persistence
### Profile (saved once, reused always)
```typescript
interface Profile {
id: string; // uuid
name: string; // "Main Channel"
channelName: string;
contactEmail: string;
social: Record<string, string>;
rig: Record<string, string>;
resolution: string;
fps: string;
graphicsPreset: string;
createdAt: string;
updatedAt: string;
}
```
### Game Preset (saved per game, reused for all parts)
```typescript
interface GamePreset {
id: string;
gameName: string;
gameNameLocalized?: Record<string, string>;
genre: Genre;
platform: string;
storeLinks: Record<string, string>;
spoilerWarning: boolean;
matureWarning: boolean;
createdAt: string;
}
```
### History Entry (auto-saved per generation)
```typescript
interface HistoryEntry {
id: string;
gameName: string;
videoType: VideoType;
language: SupportedLanguage;
title: string;
description: string;
tags: string;
createdAt: string;
}
```
## ⌨️ Keyboard Shortcuts
| Shortcut | Action |
|----------|--------|
| `Ctrl+Enter` | Generate output (switch to Output tab) |
| `Ctrl+Shift+C` | Copy all (title + description + tags) |
| `Ctrl+Shift+T` | Copy title only |
| `Ctrl+Shift+D` | Copy description only |
| `Ctrl+Shift+G` | Copy tags only |
| `Ctrl+S` | Save current form as draft |
| `Ctrl+P` | Quick-switch profile |
| `Ctrl+/` | Show keyboard shortcuts |
| `Escape` | Close modal / clear selection |
## 🔧 Settings
| Setting | Type | Default | Description |
|---------|------|---------|-------------|
| Theme | dark / light | dark | App color theme |
| Default UI Language | SupportedLanguage | en | Language for app interface |
| Default Output Language | SupportedLanguage | en | Default language for generated output |
| Default Genre | Genre | action | Pre-selected genre on new session |
| Auto-save Draft | boolean | true | Auto-save form state to localStorage |
| Show Character Count | boolean | true | Display char counters on output |
| Compact Tag Display | boolean | false | Tags as comma list vs chip display |
| History Limit | number | 100 | Max history entries to keep |
| Include Multilingual Tags | boolean | true | Add JA/VI tags to tag output |
| Include Trending Tags | boolean | true | Add year-based trending tags |
| Hashtag Count | 1-3 | 3 | Number of hashtags to generate |
## 🖥 Desktop App Features (Tauri)
| Feature | Description |
|---------|-------------|
| System Tray | Minimize to tray, quick access |
| Native Clipboard | Direct clipboard write (no browser permission) |
| File Export | Save outputs as `.txt` / `.json` to file system |
| File Import | Import profiles/presets from JSON file |
| Auto-update | Tauri updater (check GitHub releases) |
| Offline | Full functionality without internet |
| Global Hotkey | System-wide hotkey to open app (optional) |
## 🔌 Future Extension Points
| Extension | Description | Effort |
|-----------|-------------|--------|
| VS Code Extension | Command palette → generate description | Medium |
| CLI Tool | `ytdesc generate --game "Elden Ring" --type full --lang en` | Low |
| Browser Extension | Right-click on YouTube Studio → auto-fill | High |
| YouTube API | Auto-apply description to video via API | High |
| Template Marketplace | Share/import community templates | Medium |
| AI Tag Suggestions | Use game name to suggest trending tags | Medium |
| Thumbnail Text | Generate text overlay suggestions for thumbnails | Low |
| Multi-channel | Support multiple YouTube channels per profile | Low |
+306
View File
@@ -0,0 +1,306 @@
# Internationalization Guide (i18n)
## YTDescGen — Adding & Managing Languages
---
## Overview
YTDescGen has **two independent language contexts**:
1. **UI Language** — The app interface (buttons, labels, tooltips). Controlled by `SettingsStore.defaultLanguage`. Affects how the app *looks*.
2. **Output Language** — The generated title/description/tags. Controlled by `EditorStore.language`. Affects what the app *produces*.
These are independent: a Vietnamese user can browse the app in Vietnamese (UI) while generating descriptions in Japanese (output).
## File Structure
```
src/i18n/
├── index.ts # i18next initialization + language registration
├── locales/
│ ├── _schema.json # JSON Schema defining all required keys
│ ├── en/
│ │ ├── ui.json # UI strings (buttons, labels, errors, tooltips)
│ │ └── templates.json # Generated content (title, description patterns)
│ ├── vi/
│ │ ├── ui.json
│ │ └── templates.json
│ ├── ja/
│ │ ├── ui.json
│ │ └── templates.json
│ └── es/ # Example: adding Spanish
│ ├── ui.json
│ └── templates.json
```
## Adding a New Language — Checklist
### Step 1: Create locale files
```bash
# Generate empty locale from schema
npm run generate:locale -- --lang es
# This creates:
# src/i18n/locales/es/ui.json (all keys, empty values)
# src/i18n/locales/es/templates.json (all keys, empty values)
```
Or copy from English and translate:
```bash
cp -r src/i18n/locales/en src/i18n/locales/es
```
### Step 2: Translate ui.json
```jsonc
// src/i18n/locales/es/ui.json
{
"app": {
"title": "Generador de Descripción YT",
"subtitle": "Motor de plantillas Gameplay No Commentary"
},
"tabs": {
"editor": "✏️ Editor",
"output": "📄 Resultado",
"profiles": "💾 Perfiles",
"history": "📜 Historial",
"settings": "⚙️ Ajustes",
"batch": "📦 Lote"
},
"editor": {
"videoType": "Tipo de Video",
"language": "Idioma",
"genre": "Género del Juego",
"gameName": "Nombre del Juego",
"channelName": "Nombre del Canal",
"platform": "Plataforma",
"resolution": "Resolución",
"fps": "FPS",
"graphics": "Gráficos",
"timestamps": "Marcas de Tiempo",
"storeLinks": "Enlaces de Tienda",
"rig": "Mi PC",
"social": "Redes Sociales y Donaciones",
"warnings": "Advertencias",
"spoilerWarning": "Advertencia de Spoiler",
"matureWarning": "Contenido para Adultos (18+)",
"playlistLink": "Enlace de Lista de Reproducción",
"contactEmail": "Correo de Contacto"
},
"output": {
"title": "📌 Título",
"description": "📝 Descripción",
"tags": "🏷 Etiquetas",
"copyTitle": "Copiar Título",
"copyDescription": "Copiar Descripción",
"copyTags": "Copiar Etiquetas",
"copyAll": "📋 Copiar Todo",
"copied": "✓ ¡Copiado!",
"charCount": "{{count}}/{{limit}}"
},
"profiles": {
"saveProfile": "Guardar Perfil",
"loadProfile": "Cargar",
"deleteProfile": "Eliminar",
"profileName": "Nombre del Perfil",
"noProfiles": "No hay perfiles guardados.",
"gamePresets": "Preajustes de Juegos"
},
"common": {
"save": "Guardar",
"cancel": "Cancelar",
"delete": "Eliminar",
"confirm": "Confirmar",
"export": "Exportar",
"import": "Importar",
"reset": "Restablecer",
"search": "Buscar"
},
"videoTypes": {
"full": "Gameplay Completo",
"part": "Gameplay Parte",
"boss": "Pelea de Jefe",
"boss_nohit": "Jefe Sin Golpes",
"ending": "Final / Todos los Finales",
"speedrun": "Speedrun",
"100percent": "100% Completado",
"dlc": "Contenido DLC",
"newgame_plus": "New Game+",
"challenge": "Desafío",
"side_quest": "Misiones Secundarias",
"secret": "Secretos / Ocultos",
"comparison": "Comparación de Gráficos",
"guide": "Guía Silenciosa"
}
}
```
### Step 3: Translate templates.json
```jsonc
// src/i18n/locales/es/templates.json
{
"title": {
"separator": " — ",
"suffix": "Gameplay No Commentary",
"videoType": {
"full": "",
"part": "Parte {{partNumber}}",
"boss": "{{bossName}} Pelea de Jefe",
"boss_nohit": "{{bossName}} Jefe Sin Golpes",
"ending": "Final",
"speedrun": "Speedrun",
"100percent": "100%",
"dlc": "{{dlcName}} DLC",
"newgame_plus": "New Game+",
"challenge": "Desafío {{challengeName}}",
"side_quest": "Misiones Secundarias",
"secret": "Secretos",
"comparison": "Comparación",
"guide": "Guía"
}
},
"description": {
"intro": {
"full": "Este video presenta el gameplay completo de {{gameName}} en {{channelName}}.",
"part": "Este video presenta la Parte {{partNumber}} de {{gameName}} en {{channelName}}.",
"boss": "Este video presenta la pelea de jefe {{bossName}} de {{gameName}} en {{channelName}}.",
"boss_nohit": "Este video presenta la pelea de jefe {{bossName}} (sin golpes) de {{gameName}} en {{channelName}}.",
"ending": "Este video presenta el final de {{gameName}} en {{channelName}}.",
"speedrun": "Este video presenta un speedrun de {{gameName}} en {{channelName}}.",
"100percent": "Este video presenta el 100% completado de {{gameName}} en {{channelName}}.",
"dlc": "Este video presenta el DLC {{dlcName}} de {{gameName}} en {{channelName}}.",
"newgame_plus": "Este video presenta el New Game+ de {{gameName}} en {{channelName}}.",
"challenge": "Este video presenta el desafío {{challengeName}} de {{gameName}} en {{channelName}}.",
"side_quest": "Este video presenta las misiones secundarias de {{gameName}} en {{channelName}}.",
"secret": "Este video presenta los secretos y contenido oculto de {{gameName}} en {{channelName}}.",
"comparison": "Este video compara los gráficos de {{gameName}} en {{channelName}}.",
"guide": "Este video es una guía silenciosa de {{gameName}} en {{channelName}}."
},
"noCommentaryLine": "Sin comentarios — gameplay puro para tu disfrute.",
"sections": {
"timestamps": "⏱ MARCAS DE TIEMPO",
"storeLinks": "🎮 OBTENER EL JUEGO",
"videoSettings": "🖥 AJUSTES DE VIDEO: {{settings}}",
"rig": "💻 MI PC",
"spoilerWarning": "⚠️ ADVERTENCIA DE SPOILER: Este video contiene spoilers. ¡Míralo bajo tu propio riesgo!",
"matureWarning": "🔞 CONTENIDO PARA ADULTOS (18+): Contiene violencia / lenguaje fuerte / contenido gráfico.",
"playlist": "▶️ Ver la serie completa: {{link}}",
"contact": "📧 Consultas comerciales: {{email}}",
"cta": "👍 Me gusta | 🔔 Suscríbete | ↗️ Comparte"
}
},
"tags": {
"multilingual": [
"{{gameName}} sin comentarios",
"{{gameName}} gameplay completo",
"juego de acción sin comentarios"
]
}
}
```
### Step 4: Register the language
```typescript
// src/i18n/index.ts — add to SUPPORTED_LANGUAGES
export const SUPPORTED_LANGUAGES = [
{ id: "en", label: "English", flag: "🇬🇧", nativeName: "English" },
{ id: "vi", label: "Vietnamese", flag: "🇻🇳", nativeName: "Tiếng Việt" },
{ id: "ja", label: "Japanese", flag: "🇯🇵", nativeName: "日本語" },
{ id: "es", label: "Spanish", flag: "🇪🇸", nativeName: "Español" }, // ← Add here
] as const;
// Add resource import
import esUI from "./locales/es/ui.json";
import esTemplates from "./locales/es/templates.json";
// Add to i18next resources
resources: {
// ...existing
es: { ui: esUI, templates: esTemplates },
}
```
### Step 5: Add multilingual tag pool
```typescript
// src/engine/tag-generator.ts — add to MULTILINGUAL_TAG_POOLS
multilingual_es: (gameName: string) => [
`${gameName} sin comentarios`,
`${gameName} gameplay completo`,
`juego sin comentarios`,
],
```
### Step 6: Validate
```bash
npm run validate:locales
# Checks all locale files have the same keys as _schema.json
# Reports missing/extra keys per language
```
### Step 7: Test
```bash
npm run test -- --grep "i18n"
# Runs i18n-related tests including new language
```
## Locale Validation Script
The `scripts/validate-locales.ts` script ensures all locale files are complete:
```
✓ en/ui.json — 47/47 keys
✓ en/templates.json — 32/32 keys
✓ vi/ui.json — 47/47 keys
✓ vi/templates.json — 32/32 keys
✓ ja/ui.json — 47/47 keys
✓ ja/templates.json — 32/32 keys
✗ es/ui.json — 45/47 keys (missing: editor.dlcName, editor.challengeName)
✓ es/templates.json — 32/32 keys
```
## Template Interpolation
Templates use `{{variable}}` syntax (i18next default):
```json
"intro": "This video features the full gameplay of {{gameName}} on {{channelName}}."
```
Engine passes variables:
```typescript
t("templates:description.intro.full", {
gameName: state.gameName,
channelName: state.channelName,
});
```
## RTL Language Support (Arabic)
For Arabic (`ar`), add RTL handling:
```typescript
// src/i18n/index.ts
export const RTL_LANGUAGES = ["ar"] as const;
// src/App.tsx — set dir attribute
const isRTL = RTL_LANGUAGES.includes(currentLanguage);
<div dir={isRTL ? "rtl" : "ltr"}>
```
## Contributing Translations
Community members can contribute translations by:
1. Fork the repository
2. Copy `src/i18n/locales/en/` to `src/i18n/locales/{code}/`
3. Translate all strings
4. Run `npm run validate:locales` to check completeness
5. Submit a PR with the new locale files
+312
View File
@@ -0,0 +1,312 @@
# Desktop Packaging Guide
## YTDescGen — Tauri Desktop App
---
## Why Tauri?
| Feature | Tauri 2 | Electron |
|---------|---------|----------|
| Binary size | ~8 MB | ~150 MB |
| Memory usage | ~30 MB | ~100 MB+ |
| Bundled runtime | System WebView | Chromium |
| Backend language | Rust | Node.js |
| Security | Strict CSP, no Node in renderer | Full Node access |
| Auto-update | Built-in updater | electron-updater |
| CI build time | ~5 min | ~10 min |
Kokone đã quen Rust (từ hệ sinh thái Tauri/build tooling). Binary nhỏ, tốn ít RAM, deploy đơn giản.
## Prerequisites
```bash
# Rust toolchain
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
# Tauri CLI
cargo install tauri-cli
# Node.js 20+
# npm already installed from web development
# Platform-specific
# Windows: Microsoft Visual Studio C++ Build Tools
# macOS: Xcode Command Line Tools
```
## Project Setup
### 1. Initialize Tauri in existing Vite project
```bash
npm run tauri init
```
This creates `src-tauri/` directory.
### 2. tauri.conf.json
```jsonc
{
"$schema": "https://raw.githubusercontent.com/nicedoc/tauri/dev/tooling/cli/schema.json",
"build": {
"beforeBuildCommand": "npm run build",
"beforeDevCommand": "npm run dev",
"devPath": "http://localhost:5173",
"distDir": "../dist"
},
"package": {
"productName": "YTDescGen",
"version": "0.1.0"
},
"tauri": {
"bundle": {
"active": true,
"identifier": "com.skullmute.ytdescgen",
"icon": [
"icons/32x32.png",
"icons/128x128.png",
"icons/128x128@2x.png",
"icons/icon.icns",
"icons/icon.ico"
],
"targets": ["msi", "nsis", "dmg", "app"],
"windows": {
"webviewInstallMode": {
"type": "downloadBootstrapper"
}
}
},
"windows": [
{
"title": "YTDescGen",
"width": 1100,
"height": 750,
"minWidth": 800,
"minHeight": 600,
"resizable": true,
"fullscreen": false,
"center": true
}
],
"security": {
"csp": "default-src 'self'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' https://fonts.gstatic.com"
},
"systemTray": {
"iconPath": "icons/icon.png",
"iconAsTemplate": true
},
"updater": {
"active": true,
"dialog": true,
"endpoints": [
"https://github.com/poli0981/yt-desc-gen/releases/latest/download/latest.json"
]
}
}
}
```
### 3. Rust Backend (src-tauri/src/main.rs)
```rust
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
use tauri::{Manager, SystemTray, SystemTrayMenu, SystemTrayMenuItem, SystemTrayEvent};
#[tauri::command]
fn save_to_file(path: String, content: String) -> Result<(), String> {
std::fs::write(&path, &content).map_err(|e| e.to_string())
}
#[tauri::command]
fn read_from_file(path: String) -> Result<String, String> {
std::fs::read_to_string(&path).map_err(|e| e.to_string())
}
fn main() {
let tray_menu = SystemTrayMenu::new()
.add_item(tauri::CustomMenuItem::new("show", "Show"))
.add_native_item(SystemTrayMenuItem::Separator)
.add_item(tauri::CustomMenuItem::new("quit", "Quit"));
let system_tray = SystemTray::new().with_menu(tray_menu);
tauri::Builder::default()
.system_tray(system_tray)
.on_system_tray_event(|app, event| match event {
SystemTrayEvent::LeftClick { .. } => {
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
SystemTrayEvent::MenuItemClick { id, .. } => match id.as_str() {
"show" => {
let window = app.get_window("main").unwrap();
window.show().unwrap();
window.set_focus().unwrap();
}
"quit" => {
std::process::exit(0);
}
_ => {}
},
_ => {}
})
.invoke_handler(tauri::generate_handler![save_to_file, read_from_file])
.run(tauri::generate_context!())
.expect("error while running tauri application");
}
```
### 4. Frontend Tauri Integration
```typescript
// src/utils/platform.ts
export const IS_TAURI = "__TAURI__" in window;
// src/utils/file-ops.ts
import { IS_TAURI } from "./platform";
export async function saveFile(content: string, filename: string): Promise<void> {
if (IS_TAURI) {
const { save } = await import("@tauri-apps/api/dialog");
const { invoke } = await import("@tauri-apps/api/tauri");
const path = await save({ defaultPath: filename });
if (path) await invoke("save_to_file", { path, content });
} else {
// Web fallback: download via blob
const blob = new Blob([content], { type: "text/plain" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
URL.revokeObjectURL(url);
}
}
export async function loadFile(): Promise<string | null> {
if (IS_TAURI) {
const { open } = await import("@tauri-apps/api/dialog");
const { invoke } = await import("@tauri-apps/api/tauri");
const path = await open({ filters: [{ name: "JSON", extensions: ["json"] }] });
if (typeof path === "string") return invoke("read_from_file", { path });
return null;
} else {
// Web fallback: file input
return new Promise((resolve) => {
const input = document.createElement("input");
input.type = "file";
input.accept = ".json";
input.onchange = async () => {
const file = input.files?.[0];
if (file) resolve(await file.text());
else resolve(null);
};
input.click();
});
}
}
```
## Build & Release
### Development
```bash
# Web only
npm run dev
# Desktop (opens native window with hot reload)
npm run tauri dev
```
### Production Build
```bash
# Web only → dist/
npm run build
# Desktop → src-tauri/target/release/bundle/
npm run tauri build
```
Output locations:
- Windows: `src-tauri/target/release/bundle/msi/YTDescGen_0.1.0_x64.msi`
- macOS: `src-tauri/target/release/bundle/dmg/YTDescGen_0.1.0_aarch64.dmg`
### GitHub Actions Release
```yaml
# .github/workflows/release-desktop.yml
name: Release Desktop
on:
push:
tags: ["v*"]
permissions:
contents: write
jobs:
build:
strategy:
matrix:
include:
- os: windows-latest
target: x86_64-pc-windows-msvc
- os: macos-latest
target: aarch64-apple-darwin
- os: macos-latest
target: x86_64-apple-darwin
runs-on: ${{ matrix.os }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- uses: dtolnay/rust-toolchain@stable
with:
targets: ${{ matrix.target }}
- run: npm ci
- uses: tauri-apps/tauri-action@v0
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tagName: v__VERSION__
releaseName: "YTDescGen v__VERSION__"
releaseBody: "See CHANGELOG.md for details."
releaseDraft: true
```
## Auto-Update Flow
```
App Start
│
▼
Check GitHub Releases endpoint
│
├─ No update → Continue normally
│
└─ Update available
│
▼
Show dialog: "Update v0.2.0 available. Install now?"
│
├─ Yes → Download + install + restart
└─ No → Dismiss, ask again next launch
```
## Offline Capability
The app is fully offline-capable because:
- All templates and configs are bundled
- State persists in localStorage (web) or app data directory (Tauri)
- No external API calls required
- Fonts can be bundled locally for desktop
Only auto-update requires internet connectivity.
+120
View File
@@ -0,0 +1,120 @@
# Product Requirements Document (PRD)
## YTDescGen — YouTube Gameplay Description Generator
**Version**: 1.0
**Author**: Kokone (skullmute)
**Last Updated**: 2026-04-07
---
## 1. Problem Statement
Kênh YouTube Gameplay No Commentary cần tạo title, description, và tags cho mỗi video upload. Quy trình hiện tại:
1. Mở file template → copy → paste vào YouTube Studio
2. Thay thế từng placeholder bằng thông tin game cụ thể
3. Tìm và thêm tags phù hợp thể loại
4. Lặp lại toàn bộ cho mỗi ngôn ngữ
5. Lặp lại toàn bộ cho mỗi video trong series
**Pain Points:**
- Lặp lại thao tác nhập Social/Rig/Channel info mỗi lần
- Dễ quên/sai khi thay placeholder
- Tags phải nhớ hoặc tra cứu từ file Excel
- Không có cách kiểm tra character limit trước khi paste
- Multi-language phải làm riêng từng bản
- Không tái sử dụng được game info cho multi-part series
## 2. Solution
Ứng dụng web (+ desktop) với form-based UI:
- Chọn video type, ngôn ngữ, thể loại game
- Nhập thông tin một lần → lưu Profile
- Nhập game info một lần → lưu Preset cho cả series
- Tự động generate title + description + tags
- Copy trực tiếp vào clipboard, paste vào YouTube Studio
- Hỗ trợ batch mode cho nhiều video cùng game
## 3. Target Users
- **Primary**: Bản thân Kokone — kênh Gameplay No Commentary
- **Secondary**: Các YouTuber gameplay nhỏ lẻ cùng niche
- **Future**: Mở rộng cho community qua GitHub release
## 4. Core User Stories
### Must Have (P0)
| ID | Story | Acceptance Criteria |
|----|-------|-------------------|
| US-01 | Chọn loại video (Full, Part, Boss, etc.) | UI hiển thị đúng form fields theo loại video đã chọn |
| US-02 | Chọn ngôn ngữ output (EN/VI/JA) | Toàn bộ generated output chuyển sang ngôn ngữ đã chọn |
| US-03 | Chọn thể loại game | Tags được generate phù hợp thể loại |
| US-04 | Nhập game info (tên, platform, store links) | Thông tin được đưa vào title + description đúng vị trí |
| US-05 | Nhập timestamps | Timestamps xuất hiện trong description với format YouTube chapters |
| US-06 | Nhập Social/Donate links | Links xuất hiện trong description section phù hợp |
| US-07 | Nhập Rig info | Rig xuất hiện dưới dạng compact format trong description |
| US-08 | Xem preview title + description + tags | Preview cập nhật real-time khi thay đổi input |
| US-09 | Copy từng phần (title / desc / tags) | Clipboard chứa đúng nội dung, toast confirm |
| US-10 | Copy tất cả | Clipboard chứa title + desc, tags riêng |
| US-11 | Hiển thị character count | Description ≤ 5000, Tags ≤ 500, warning khi gần/vượt limit |
| US-12 | Toggle Spoiler/18+ warning | Dòng warning xuất hiện/ẩn trong description |
### Should Have (P1)
| ID | Story | Acceptance Criteria |
|----|-------|-------------------|
| US-13 | Lưu Profile (social, rig, channel) | Profile persist qua sessions, load vào form |
| US-14 | Lưu Game Preset (tên + store links) | Preset persist, selectable khi tạo video mới |
| US-15 | Xem lịch sử generated outputs | Danh sách outputs đã tạo, có thể copy lại |
| US-16 | Thêm ngôn ngữ mới dễ dàng | Chỉ cần thêm locale JSON files + register |
| US-17 | Thêm thể loại game mới | Chỉ cần thêm entry trong config + tag pool |
| US-18 | Import/Export settings | JSON export/import cho profiles + presets |
| US-19 | Multi-language output đồng thời | Generate cả 3 ngôn ngữ cùng lúc, mỗi ngôn ngữ 1 tab |
### Nice to Have (P2)
| ID | Story | Acceptance Criteria |
|----|-------|-------------------|
| US-20 | Batch mode cho multi-part series | Nhập game info 1 lần, tạo N videos khác part/timestamps |
| US-21 | Desktop app (Windows/macOS) | Tauri binary, hoạt động offline |
| US-22 | Custom template editor | Người dùng tự sửa template structure |
| US-23 | Keyboard shortcuts | Ctrl+Enter = generate, Ctrl+Shift+C = copy all |
| US-24 | Dark/Light theme toggle | Theme persist qua sessions |
| US-25 | Auto-save draft | Form state tự lưu, recover khi reload |
| US-26 | Tag suggestions từ game name | Gợi ý tag dựa trên tên game + trending |
| US-27 | YouTube API integration | Auto-fill qua YouTube Data API (future) |
| US-28 | VS Code / IDE extension | Command palette → generate description |
## 5. Non-Functional Requirements
| Requirement | Target |
|------------|--------|
| First Contentful Paint | < 1.5s |
| Bundle size (web) | < 500KB gzipped |
| Desktop binary size | < 15MB (Tauri) |
| Offline support | Full functionality without internet |
| Browser support | Chrome 90+, Firefox 90+, Edge 90+ |
| Accessibility | WCAG 2.1 Level AA |
| Persistence | localStorage (web), file system (desktop) |
## 6. Out of Scope (v1)
- YouTube API auto-upload
- Thumbnail generation
- Video editing integration
- Multi-user / team features
- Cloud sync between devices
- Analytics / tracking
- Monetization
## 7. Success Metrics
| Metric | Target |
|--------|--------|
| Time to generate 1 video description | < 2 minutes (vs ~10 minutes manual) |
| Error rate (missing fields, wrong format) | 0% — form validates before generate |
| Languages supported at launch | 3 (EN, VI, JA) |
| Genres supported at launch | 10+ |
| Video types supported | 7+ |
+282
View File
@@ -0,0 +1,282 @@
# Development Roadmap
## YTDescGen — Phased Development Plan
---
## Phase 1 — MVP Core (Priority: P0)
**Goal**: Ứng dụng web chạy được, generate title + description + tags, copy to clipboard.
**Estimated**: 3-4 days
### Tasks
```
1.1 Project scaffold
- [x] Vite + React 18 + TypeScript setup
- [ ] Tailwind CSS configuration (dark theme default)
- [ ] ESLint + Prettier config
- [ ] Directory structure per CLAUDE.md
- [ ] Package.json scripts
1.2 Config layer
- [ ] src/config/video-types.ts (7 initial types)
- [ ] src/config/genres.ts (10 initial genres)
- [ ] src/config/platforms.ts (7 platforms)
- [ ] src/config/rig-fields.ts
- [ ] src/config/social-fields.ts
- [ ] src/config/defaults.ts
1.3 i18n setup
- [ ] i18next + react-i18next install & config
- [ ] locales/en/ui.json + templates.json
- [ ] locales/vi/ui.json + templates.json
- [ ] locales/ja/ui.json + templates.json
- [ ] Locale validation script
1.4 Core engine
- [ ] engine/types.ts
- [ ] engine/title-builder.ts + tests
- [ ] engine/description-builder.ts + tests
- [ ] engine/tag-generator.ts + tests
- [ ] engine/template-renderer.ts (orchestrator)
1.5 State management
- [ ] Zustand setup
- [ ] editor-store.ts (form state)
- [ ] settings-store.ts (theme, default language)
1.6 UI components
- [ ] ui/ primitives: Button, Input, Textarea, Toggle, ChipGroup, Select
- [ ] editor/ components: VideoTypeSelector, LanguageSelector, GenreSelector
- [ ] editor/ components: GameInfoForm, VideoSettingsForm, TimestampEditor
- [ ] editor/ components: StoreLinkEditor, RigEditor, SocialEditor, WarningToggles
- [ ] editor/ components: QuickPreview
- [ ] output/ components: OutputPreview, CopyButton, CharCounter, CopyAllBar
- [ ] layout/ components: AppShell, Header, TabBar
1.7 Pages
- [ ] EditorPage (form + quick preview)
- [ ] OutputPage (title + desc + tags + copy)
- [ ] React Router setup (HashRouter)
1.8 Testing
- [ ] Vitest config
- [ ] Engine unit tests (title, description, tags)
- [ ] Smoke tests for main pages
1.9 CI/CD
- [ ] GitHub Actions: lint + typecheck + test
- [ ] GitHub Actions: deploy to GitHub Pages
### Definition of Done
- [ ] User can select video type, language, genre
- [ ] User can enter game name, timestamps, store links, rig, social, warnings
- [ ] Title, description, and tags generate correctly in EN/VI/JA
- [ ] Copy buttons work for title, description, tags, and all
- [ ] Character counts displayed (5000 desc, 500 tags)
- [ ] CI passes, deploys to GitHub Pages
```
---
## Phase 2 — Profiles & Presets (Priority: P1)
**Goal**: Lưu thông tin tái sử dụng, không phải nhập lại mỗi lần.
**Estimated**: 2-3 days
### Tasks
```
2.1 Profile system
- [ ] profile-store.ts (Zustand + persist)
- [ ] ProfileSaveForm component
- [ ] ProfileList + ProfileCard components
- [ ] Load profile → populate editor form
- [ ] Delete profile with confirmation
- [ ] Multiple profiles support
2.2 Game preset system
- [ ] preset-store.ts (Zustand + persist)
- [ ] GamePresetManager component
- [ ] Save game (name + genre + platform + store links + warnings)
- [ ] Load preset → populate game fields
- [ ] Preset selector dropdown in editor
2.3 ProfilesPage
- [ ] Profile management tab
- [ ] Game preset management tab
- [ ] Import/Export JSON
2.4 Auto-save draft
- [ ] Debounced save of editor state to localStorage
- [ ] Restore on page load
- [ ] Clear draft button
2.5 Expand content
- [ ] Add video types: dlc, newgame_plus, challenge, side_quest, secret
- [ ] Add genres to 15+: fighting, stealth, survival_craft, roguelike, metroidvania
- [ ] Add social fields: twitch, tiktok, instagram, streamlabs
- [ ] Add rig fields: motherboard, controller
- [ ] Add store: humble, amazon
### Definition of Done
- [ ] User creates profile → social/rig/channel info saved
- [ ] User loads profile → form populated instantly
- [ ] User creates game preset → reused across parts
- [ ] Form state auto-saved, survives page reload
- [ ] Export/Import profiles as JSON works
```
---
## Phase 3 — Polish & Advanced Features (Priority: P1-P2)
**Goal**: Batch mode, history, keyboard shortcuts, theme.
**Estimated**: 2-3 days
### Tasks
```
3.1 History system
- [ ] history-store.ts (max 100 entries, auto-prune)
- [ ] HistoryPage with list view
- [ ] Copy from history
- [ ] Delete history entries
- [ ] Search/filter history
3.2 Batch mode
- [ ] BatchPage UI
- [ ] Same game, different parts/timestamps
- [ ] Generate N outputs at once
- [ ] Copy all as combined text or individual
3.3 Multi-language output
- [ ] Generate output in multiple languages simultaneously
- [ ] Tab-based display per language
- [ ] Copy per language or copy all languages
3.4 Settings page
- [ ] SettingsPage component
- [ ] Theme toggle (dark/light)
- [ ] Default language, genre preferences
- [ ] Tag generation options (multilingual, trending on/off)
- [ ] History limit setting
3.5 Keyboard shortcuts
- [ ] Shortcut handler (global keyboard listener)
- [ ] Ctrl+Enter, Ctrl+Shift+C, etc.
- [ ] Shortcut help modal (Ctrl+/)
3.6 UX Polish
- [ ] Toast notifications for copy/save/delete
- [ ] Form validation (required fields highlight)
- [ ] Responsive design (mobile-friendly)
- [ ] Loading states and transitions
- [ ] Empty states with illustrations
3.7 Expand languages
- [ ] Spanish (es) locale files
- [ ] Korean (ko) locale files
- [ ] Chinese Simplified (zh) locale files
3.8 Expand genres to 25
- [ ] Add remaining: mmo, rhythm, puzzle, tower_defense, card_game
- [ ] battle_royale, crpg, tactical, space, farming
- [ ] Tag pools for each new genre
### Definition of Done
- [ ] Batch generate 10 parts in under 30 seconds
- [ ] History page shows last 100 generated outputs
- [ ] Dark/Light theme works correctly
- [ ] Keyboard shortcuts functional
- [ ] 6 languages, 25 genres, 14 video types
```
---
## Phase 4 — Desktop App (Priority: P2)
**Goal**: Đóng gói thành ứng dụng desktop bằng Tauri.
**Estimated**: 2-3 days
### Tasks
```
4.1 Tauri setup
- [ ] Install Tauri CLI + dependencies
- [ ] src-tauri/ scaffold
- [ ] tauri.conf.json configuration
- [ ] App icons (all sizes)
4.2 Desktop features
- [ ] Native clipboard integration
- [ ] File export (save outputs as .txt/.json)
- [ ] File import (load profiles/presets from JSON)
- [ ] System tray with quick access
- [ ] Window state persistence (size, position)
4.3 Auto-update
- [ ] Tauri updater configuration
- [ ] GitHub Releases integration
- [ ] Update notification UI
4.4 Build pipeline
- [ ] GitHub Actions: build Windows .msi
- [ ] GitHub Actions: build macOS .dmg
- [ ] Release workflow (tag → build → publish)
4.5 Platform-specific
- [ ] Windows: installer, start menu shortcut
- [ ] macOS: .app bundle, code signing (if needed)
- [ ] Verify offline functionality
### Definition of Done
- [ ] Windows installer < 15MB, installs and runs
- [ ] macOS .app < 15MB, runs on Apple Silicon + Intel
- [ ] Auto-update from GitHub Releases works
- [ ] All web features work identically in desktop
- [ ] Offline mode fully functional
```
---
## Phase 5 — Extensions & Ecosystem (Priority: P2-P3)
**Goal**: IDE extension, CLI, community features.
**Estimated**: Ongoing
### Tasks
```
5.1 CLI tool
- [ ] Standalone Node.js CLI using engine/
- [ ] `npx ytdescgen generate --game "..." --type full --lang en`
- [ ] JSON output mode for scripting
- [ ] Config file support (.ytdescgen.json)
5.2 VS Code Extension
- [ ] Command palette: "YTDescGen: Generate Description"
- [ ] Webview panel with editor UI
- [ ] Output to new editor tab
- [ ] Settings sync with VS Code settings
5.3 Additional languages
- [ ] French, German, Portuguese, Russian, Thai, Arabic
- [ ] Community contribution guide for translations
- [ ] Locale validation CI check
5.4 Template customization
- [ ] Custom template editor in app
- [ ] Template import/export
- [ ] Template sharing (JSON format)
5.5 Quality of life
- [ ] YouTube API integration (auto-apply description)
- [ ] Tag trend analysis (what's trending for the genre)
- [ ] Multi-channel profile support
```
---
## Timeline Summary
| Phase | Scope | Days | Cumulative |
|-------|-------|------|------------|
| Phase 1 | MVP Core | 3-4 | 3-4 days |
| Phase 2 | Profiles & Presets | 2-3 | 5-7 days |
| Phase 3 | Polish & Advanced | 2-3 | 7-10 days |
| Phase 4 | Desktop App | 2-3 | 9-13 days |
| Phase 5 | Extensions | Ongoing | — |
**MVP usable after Phase 1** (~3-4 days). Full-featured after Phase 3 (~7-10 days).
+420
View File
@@ -0,0 +1,420 @@
# Technical Specifications
## YTDescGen — Implementation Details
---
## 1. Package Configuration
### package.json
```jsonc
{
"name": "yt-desc-gen",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "vitest",
"test:run": "vitest run",
"test:coverage": "vitest run --coverage",
"lint": "eslint src/ --ext .ts,.tsx",
"lint:fix": "eslint src/ --ext .ts,.tsx --fix",
"typecheck": "tsc --noEmit",
"format": "prettier --write \"src/**/*.{ts,tsx,json,css}\"",
"validate:locales": "tsx scripts/validate-locales.ts",
"generate:locale": "tsx scripts/generate-locale-template.ts",
"tauri": "tauri",
"tauri:dev": "tauri dev",
"tauri:build": "tauri build"
},
"dependencies": {
"react": "^18.3.0",
"react-dom": "^18.3.0",
"react-router-dom": "^6.26.0",
"zustand": "^4.5.0",
"i18next": "^23.15.0",
"react-i18next": "^15.0.0",
"react-hot-toast": "^2.4.0",
"lucide-react": "^0.400.0",
"clsx": "^2.1.0"
},
"devDependencies": {
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.0",
"typescript": "^5.5.0",
"vite": "^5.4.0",
"vitest": "^2.0.0",
"@testing-library/react": "^16.0.0",
"@testing-library/jest-dom": "^6.4.0",
"tailwindcss": "^3.4.0",
"postcss": "^8.4.0",
"autoprefixer": "^10.4.0",
"eslint": "^9.0.0",
"@eslint/js": "^9.0.0",
"typescript-eslint": "^8.0.0",
"eslint-plugin-react-hooks": "^4.6.0",
"prettier": "^3.3.0",
"prettier-plugin-tailwindcss": "^0.6.0",
"@tauri-apps/cli": "^2.0.0",
"@tauri-apps/api": "^2.0.0",
"tsx": "^4.16.0"
}
}
```
### tsconfig.json
```jsonc
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@config/*": ["./src/config/*"],
"@engine/*": ["./src/engine/*"],
"@store/*": ["./src/store/*"],
"@hooks/*": ["./src/hooks/*"],
"@components/*": ["./src/components/*"],
"@pages/*": ["./src/pages/*"],
"@utils/*": ["./src/utils/*"],
"@i18n/*": ["./src/i18n/*"]
}
},
"include": ["src"]
}
```
### vite.config.ts
```typescript
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
plugins: [react()],
base: "/yt-desc-gen/", // GitHub Pages
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"@config": path.resolve(__dirname, "./src/config"),
"@engine": path.resolve(__dirname, "./src/engine"),
"@store": path.resolve(__dirname, "./src/store"),
"@hooks": path.resolve(__dirname, "./src/hooks"),
"@components": path.resolve(__dirname, "./src/components"),
"@pages": path.resolve(__dirname, "./src/pages"),
"@utils": path.resolve(__dirname, "./src/utils"),
"@i18n": path.resolve(__dirname, "./src/i18n"),
},
},
build: {
rollupOptions: {
output: {
manualChunks: {
react: ["react", "react-dom"],
router: ["react-router-dom"],
i18n: ["i18next", "react-i18next"],
},
},
},
},
});
```
### tailwind.config.ts
```typescript
import type { Config } from "tailwindcss";
export default {
content: ["./index.html", "./src/**/*.{ts,tsx}"],
darkMode: "class",
theme: {
extend: {
colors: {
surface: {
0: "var(--surface-0)", // deepest background
1: "var(--surface-1)", // card background
2: "var(--surface-2)", // elevated surface
3: "var(--surface-3)", // hover/active state
},
border: {
DEFAULT: "var(--border)",
strong: "var(--border-strong)",
},
text: {
primary: "var(--text-primary)",
secondary: "var(--text-secondary)",
muted: "var(--text-muted)",
},
accent: {
DEFAULT: "var(--accent)",
hover: "var(--accent-hover)",
muted: "var(--accent-muted)",
},
success: "var(--success)",
warning: "var(--warning)",
danger: "var(--danger)",
},
fontFamily: {
sans: ["var(--font-sans)"],
mono: ["var(--font-mono)"],
},
},
},
plugins: [],
} satisfies Config;
```
## 2. Core Engine Interfaces
```typescript
// src/engine/types.ts
export interface GeneratorInput {
videoType: VideoType;
language: SupportedLanguage;
genre: Genre;
gameName: string;
gameNameLocalized?: Partial<Record<SupportedLanguage, string>>;
channelName: string;
platform: string;
partNumber?: string;
bossName?: string;
dlcName?: string;
challengeName?: string;
resolution?: string;
fps?: string;
graphicsPreset?: string;
timestamps?: string;
playlistLink?: string;
contactEmail?: string;
spoilerWarning: boolean;
matureWarning: boolean;
storeLinks: Partial<Record<string, string>>;
social: Partial<Record<string, string>>;
rig: Partial<Record<string, string>>;
}
export interface GeneratorOutput {
title: string;
description: string;
tags: string[];
tagString: string;
charCounts: {
title: number; // YouTube limit: 100
description: number; // YouTube limit: 5000
tags: number; // YouTube limit: 500
};
warnings: CharLimitWarning[];
}
export interface CharLimitWarning {
field: "title" | "description" | "tags";
current: number;
limit: number;
message: string;
}
// YouTube official limits
export const YT_LIMITS = {
TITLE_MAX: 100,
DESCRIPTION_MAX: 5000,
TAGS_MAX: 500,
SINGLE_TAG_MAX: 30, // single tag character limit
HASHTAG_MAX: 3,
} as const;
```
## 3. Zustand Store Pattern
```typescript
// src/store/editor-store.ts
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import type { GeneratorInput } from "@engine/types";
import { DEFAULTS } from "@config/defaults";
interface EditorState extends GeneratorInput {
// Actions
set: <K extends keyof GeneratorInput>(key: K, value: GeneratorInput[K]) => void;
setNested: <G extends "storeLinks" | "social" | "rig">(
group: G,
key: string,
value: string,
) => void;
loadProfile: (profile: Partial<GeneratorInput>) => void;
loadPreset: (preset: Partial<GeneratorInput>) => void;
reset: () => void;
}
export const useEditorStore = create<EditorState>()(
persist(
(set) => ({
...DEFAULTS.editor,
set: (key, value) => set({ [key]: value }),
setNested: (group, key, value) =>
set((state) => ({
[group]: { ...state[group], [key]: value },
})),
loadProfile: (profile) => set((state) => ({ ...state, ...profile })),
loadPreset: (preset) => set((state) => ({ ...state, ...preset })),
reset: () => set(DEFAULTS.editor),
}),
{
name: "ytdescgen-editor-draft",
storage: createJSONStorage(() => localStorage),
partialize: (state) => {
// Exclude actions from persistence
const { set: _s, setNested: _sn, loadProfile: _lp, loadPreset: _lpre, reset: _r, ...data } = state;
return data;
},
},
),
);
```
## 4. GitHub Actions CI
```yaml
# .github/workflows/ci.yml
name: CI
on:
push:
branches: [main, dev]
pull_request:
branches: [main]
jobs:
check:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
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
```
```yaml
# .github/workflows/deploy-web.yml
name: Deploy to GitHub Pages
on:
push:
branches: [main]
permissions:
contents: read
pages: write
id-token: write
jobs:
deploy:
runs-on: ubuntu-latest
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
cache: npm
- run: npm ci
- run: npm run build
- uses: actions/configure-pages@v5
- uses: actions/upload-pages-artifact@v3
with:
path: dist
- id: deployment
uses: actions/deploy-pages@v4
```
## 5. Testing Strategy
```typescript
// tests/engine/title-builder.test.ts
import { describe, it, expect } from "vitest";
import { buildTitle } from "@engine/title-builder";
describe("buildTitle", () => {
it("generates full gameplay title in English", () => {
const result = buildTitle({
gameName: "Elden Ring",
videoType: "full",
language: "en",
});
expect(result).toBe("Elden Ring — Gameplay No Commentary");
});
it("generates part title with number", () => {
const result = buildTitle({
gameName: "Elden Ring",
videoType: "part",
partNumber: "5",
language: "en",
});
expect(result).toBe("Elden Ring — Part 5 — Gameplay No Commentary");
});
it("generates boss title in Japanese", () => {
const result = buildTitle({
gameName: "エルデンリング",
videoType: "boss",
bossName: "マルギット",
language: "ja",
});
expect(result).toBe("エルデンリング — マルギット ボス戦 — Gameplay No Commentary");
});
it("warns when title exceeds 100 characters", () => {
// ... test char limit warning
});
});
```
## 6. YouTube Character Limits Reference
| Field | Limit | Behavior When Exceeded |
|-------|-------|----------------------|
| Title | 100 chars | YouTube truncates with "..." |
| Description | 5,000 chars | YouTube silently truncates |
| Tags (total) | 500 chars | YouTube rejects all tags |
| Single Tag | 30 chars | YouTube rejects that tag |
| Hashtags in description | 60 max, 3 shown | First 3 shown above title |
| Playlist title | 150 chars | Truncated |
+21
View File
@@ -0,0 +1,21 @@
import js from "@eslint/js";
import tseslint from "typescript-eslint";
import reactHooks from "eslint-plugin-react-hooks";
export default tseslint.config(
js.configs.recommended,
...tseslint.configs.strict,
{
plugins: {
"react-hooks": reactHooks,
},
rules: {
...reactHooks.configs.recommended.rules,
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/no-unused-vars": ["error", { argsIgnorePattern: "^_" }],
},
},
{
ignores: ["dist/", "node_modules/", "*.config.*"],
},
);
+12
View File
@@ -0,0 +1,12 @@
<!doctype html>
<html lang="en" class="dark">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>YTDescGen</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
+5520
View File
File diff suppressed because it is too large. Load diff
+51
View File
@@ -0,0 +1,51 @@
{
"name": "yt-desc-gen",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview",
"test": "vitest",
"test:run": "vitest run",
"test:coverage": "vitest run --coverage",
"lint": "eslint src/ --ext .ts,.tsx",
"lint:fix": "eslint src/ --ext .ts,.tsx --fix",
"typecheck": "tsc --noEmit",
"format": "prettier --write \"src/**/*.{ts,tsx,json,css}\"",
"validate:locales": "tsx scripts/validate-locales.ts",
"generate:locale": "tsx scripts/generate-locale-template.ts"
},
"dependencies": {
"react": "^18.3.0",
"react-dom": "^18.3.0",
"react-router-dom": "^6.26.0",
"zustand": "^4.5.0",
"i18next": "^23.15.0",
"react-i18next": "^15.0.0",
"react-hot-toast": "^2.4.0",
"lucide-react": "^0.400.0",
"clsx": "^2.1.0"
},
"devDependencies": {
"@types/react": "^18.3.0",
"@types/react-dom": "^18.3.0",
"@vitejs/plugin-react": "^4.3.0",
"typescript": "^5.5.0",
"vite": "^5.4.0",
"vitest": "^2.0.0",
"@testing-library/react": "^16.0.0",
"@testing-library/jest-dom": "^6.4.0",
"tailwindcss": "^3.4.0",
"postcss": "^8.4.0",
"autoprefixer": "^10.4.0",
"eslint": "^9.0.0",
"@eslint/js": "^9.0.0",
"typescript-eslint": "^8.0.0",
"eslint-plugin-react-hooks": "^5.0.0",
"prettier": "^3.3.0",
"prettier-plugin-tailwindcss": "^0.6.0",
"tsx": "^4.16.0"
}
}
+6
View File
@@ -0,0 +1,6 @@
export default {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
};
+97
View File
@@ -0,0 +1,97 @@
import { readFileSync, readdirSync, existsSync } from "fs";
import { join, resolve } from "path";
const LOCALES_DIR = resolve("src/i18n/locales");
const SCHEMA_PATH = join(LOCALES_DIR, "_schema.json");
interface Schema {
ui: Record<string, string[]>;
templates: Record<string, string[]>;
}
function getNestedKeys(obj: Record<string, unknown>, prefix = ""): string[] {
const keys: string[] = [];
for (const key of Object.keys(obj)) {
const fullKey = prefix ? `${prefix}.${key}` : key;
const value = obj[key];
if (typeof value === "object" && value !== null && !Array.isArray(value)) {
keys.push(...getNestedKeys(value as Record<string, unknown>, fullKey));
} else {
keys.push(fullKey);
}
}
return keys;
}
function getExpectedKeys(schema: Schema, namespace: "ui" | "templates"): string[] {
const section = schema[namespace];
const keys: string[] = [];
for (const [path, fields] of Object.entries(section)) {
for (const field of fields) {
keys.push(`${path}.${field}`);
}
}
return keys;
}
function validate(): void {
if (!existsSync(SCHEMA_PATH)) {
console.error("Schema file not found:", SCHEMA_PATH);
process.exit(1);
}
const schema: Schema = JSON.parse(readFileSync(SCHEMA_PATH, "utf-8"));
const expectedUIKeys = getExpectedKeys(schema, "ui");
const expectedTemplateKeys = getExpectedKeys(schema, "templates");
const localeDirs = readdirSync(LOCALES_DIR, { withFileTypes: true })
.filter((d) => d.isDirectory())
.map((d) => d.name);
let hasErrors = false;
for (const locale of localeDirs) {
const localeDir = join(LOCALES_DIR, locale);
for (const [filename, expectedKeys] of [
["ui.json", expectedUIKeys],
["templates.json", expectedTemplateKeys],
] as const) {
const filePath = join(localeDir, filename);
if (!existsSync(filePath)) {
console.error(`✗ ${locale}/${filename} — FILE MISSING`);
hasErrors = true;
continue;
}
const content: Record<string, unknown> = JSON.parse(readFileSync(filePath, "utf-8"));
const actualKeys = getNestedKeys(content);
const missing = expectedKeys.filter((k) => !actualKeys.includes(k));
const extra = actualKeys.filter((k) => !expectedKeys.includes(k));
if (missing.length === 0 && extra.length === 0) {
console.log(`✓ ${locale}/${filename} — ${actualKeys.length}/${expectedKeys.length} keys`);
} else {
hasErrors = true;
console.error(
`✗ ${locale}/${filename} — ${actualKeys.length}/${expectedKeys.length} keys`,
);
if (missing.length > 0) {
console.error(` Missing: ${missing.join(", ")}`);
}
if (extra.length > 0) {
console.error(` Extra: ${extra.join(", ")}`);
}
}
}
}
if (hasErrors) {
process.exit(1);
} else {
console.log("\nAll locale files are complete!");
}
}
validate();
+31
View File
@@ -0,0 +1,31 @@
import { HashRouter, Routes, Route } from "react-router-dom";
import { Toaster } from "react-hot-toast";
import { AppShell } from "@components/layout/AppShell";
import { EditorPage } from "@pages/EditorPage";
import { OutputPage } from "@pages/OutputPage";
import "@i18n/index";
export default function App() {
return (
<>
<HashRouter>
<Routes>
<Route element={<AppShell />}>
<Route index element={<EditorPage />} />
<Route path="output" element={<OutputPage />} />
</Route>
</Routes>
</HashRouter>
<Toaster
position="bottom-right"
toastOptions={{
style: {
background: "var(--surface-2)",
color: "var(--text-primary)",
border: "1px solid var(--border)",
},
}}
/>
</>
);
}
+55
View File
@@ -0,0 +1,55 @@
import { useTranslation } from "react-i18next";
import { Input } from "@components/ui/Input";
import { Select } from "@components/ui/Select";
import { PLATFORMS } from "@config/platforms";
import { VIDEO_TYPES } from "@config/video-types";
import { useEditorStore } from "@store/editor-store";
export function GameInfoForm() {
const { t } = useTranslation("ui");
const store = useEditorStore();
const currentVideoType = VIDEO_TYPES.find((vt) => vt.id === store.videoType);
const extraFields: readonly string[] = currentVideoType?.extraFields ?? [];
const platformOptions = PLATFORMS.map((p) => ({ value: p.id, label: p.label }));
return (
<div className="flex flex-col gap-3">
<Input
label={t("editor.gameName")}
placeholder={t("editor.gameNamePlaceholder")}
value={store.gameName}
onChange={(e) => store.set("gameName", e.target.value)}
/>
<Input
label={t("editor.channelName")}
placeholder={t("editor.channelNamePlaceholder")}
value={store.channelName}
onChange={(e) => store.set("channelName", e.target.value)}
/>
<Select
label={t("editor.platform")}
options={platformOptions}
value={store.platform}
onChange={(v) => store.set("platform", v)}
/>
{extraFields.includes("partNumber") && (
<Input
label={t("editor.partNumber")}
placeholder={t("editor.partNumberPlaceholder")}
value={store.partNumber ?? ""}
onChange={(e) => store.set("partNumber", e.target.value)}
/>
)}
{extraFields.includes("bossName") && (
<Input
label={t("editor.bossName")}
placeholder={t("editor.bossNamePlaceholder")}
value={store.bossName ?? ""}
onChange={(e) => store.set("bossName", e.target.value)}
/>
)}
</div>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { useTranslation } from "react-i18next";
import { ChipGroup } from "@components/ui/ChipGroup";
import { GENRES } from "@config/genres";
import { useEditorStore } from "@store/editor-store";
export function GenreSelector() {
const { t } = useTranslation("ui");
const genre = useEditorStore((s) => s.genre);
const set = useEditorStore((s) => s.set);
const options = GENRES.map((g) => ({
id: g.id,
label: t(g.labelKey),
icon: g.icon,
}));
return (
<ChipGroup
label={t("editor.genre")}
options={options}
value={genre}
onChange={(v) => set("genre", v as typeof genre)}
/>
);
}
@@ -0,0 +1,24 @@
import { useTranslation } from "react-i18next";
import { Select } from "@components/ui/Select";
import { SUPPORTED_LANGUAGES } from "@i18n/index";
import { useEditorStore } from "@store/editor-store";
export function LanguageSelector() {
const { t } = useTranslation("ui");
const language = useEditorStore((s) => s.language);
const set = useEditorStore((s) => s.set);
const options = SUPPORTED_LANGUAGES.map((lang) => ({
value: lang.id,
label: `${lang.flag} ${lang.nativeName}`,
}));
return (
<Select
label={t("editor.language")}
options={options}
value={language}
onChange={(v) => set("language", v as typeof language)}
/>
);
}
+42
View File
@@ -0,0 +1,42 @@
import { useTranslation } from "react-i18next";
import { useGeneratedOutput } from "@hooks/use-generated-output";
export function QuickPreview() {
const { t } = useTranslation("ui");
const output = useGeneratedOutput();
return (
<div className="flex flex-col gap-3 rounded-lg border border-border bg-surface-1 p-4">
<span className="text-sm font-medium text-text-secondary">{t("editor.quickPreview")}</span>
<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>
</div>
<div>
<span className="text-xs font-medium uppercase text-text-muted">
{t("output.description")}
</span>
<p className="mt-1 line-clamp-3 whitespace-pre-wrap text-xs text-text-secondary">
{output.description || "..."}
</p>
</div>
<div>
<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>
</div>
</div>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { useTranslation } from "react-i18next";
import { Input } from "@components/ui/Input";
import { RIG_FIELDS } from "@config/rig-fields";
import { useEditorStore } from "@store/editor-store";
export function RigEditor() {
const { t } = useTranslation("ui");
const rig = useEditorStore((s) => s.rig);
const setNested = useEditorStore((s) => s.setNested);
return (
<div className="flex flex-col gap-3">
<span className="text-sm font-medium text-text-secondary">{t("editor.rig")}</span>
<div className="grid grid-cols-2 gap-2">
{RIG_FIELDS.map((field) => (
<Input
key={field.id}
label={t(field.labelKey)}
placeholder={field.placeholder}
value={rig[field.id] ?? ""}
onChange={(e) => setNested("rig", field.id, e.target.value)}
/>
))}
</div>
</div>
);
}
+45
View File
@@ -0,0 +1,45 @@
import { useTranslation } from "react-i18next";
import { Input } from "@components/ui/Input";
import { SOCIAL_FIELDS } from "@config/social-fields";
import { useEditorStore } from "@store/editor-store";
export function SocialEditor() {
const { t } = useTranslation("ui");
const social = useEditorStore((s) => s.social);
const setNested = useEditorStore((s) => s.setNested);
const donateFields = SOCIAL_FIELDS.filter((f) => f.category === "donate");
const socialFields = SOCIAL_FIELDS.filter((f) => f.category === "social");
return (
<div className="flex flex-col gap-4">
<span className="text-sm font-medium text-text-secondary">{t("editor.social")}</span>
<div className="flex flex-col gap-2">
<span className="text-xs font-medium uppercase text-text-muted">Donate</span>
{donateFields.map((field) => (
<Input
key={field.id}
label={t(field.labelKey)}
placeholder={field.urlPrefix || "URL"}
value={social[field.id] ?? ""}
onChange={(e) => setNested("social", field.id, e.target.value)}
/>
))}
</div>
<div className="flex flex-col gap-2">
<span className="text-xs font-medium uppercase text-text-muted">Social</span>
{socialFields.map((field) => (
<Input
key={field.id}
label={t(field.labelKey)}
placeholder={field.urlPrefix || "URL"}
value={social[field.id] ?? ""}
onChange={(e) => setNested("social", field.id, e.target.value)}
/>
))}
</div>
</div>
);
}
+27
View File
@@ -0,0 +1,27 @@
import { useTranslation } from "react-i18next";
import { Input } from "@components/ui/Input";
import { PLATFORMS } from "@config/platforms";
import { useEditorStore } from "@store/editor-store";
export function StoreLinkEditor() {
const { t } = useTranslation("ui");
const storeLinks = useEditorStore((s) => s.storeLinks);
const setNested = useEditorStore((s) => s.setNested);
return (
<div className="flex flex-col gap-3">
<span className="text-sm font-medium text-text-secondary">{t("editor.storeLinks")}</span>
<div className="flex flex-col gap-2">
{PLATFORMS.map((platform) => (
<Input
key={platform.id}
label={platform.label}
placeholder={platform.urlPrefix}
value={storeLinks[platform.id] ?? ""}
onChange={(e) => setNested("storeLinks", platform.id, e.target.value)}
/>
))}
</div>
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { useTranslation } from "react-i18next";
import { Textarea } from "@components/ui/Textarea";
import { useEditorStore } from "@store/editor-store";
export function TimestampEditor() {
const { t } = useTranslation("ui");
const timestamps = useEditorStore((s) => s.timestamps);
const set = useEditorStore((s) => s.set);
return (
<Textarea
label={t("editor.timestamps")}
placeholder={t("editor.timestampsPlaceholder")}
value={timestamps ?? ""}
onChange={(e) => set("timestamps", e.target.value)}
rows={4}
/>
);
}
@@ -0,0 +1,49 @@
import { useTranslation } from "react-i18next";
import { Select } from "@components/ui/Select";
import { Input } from "@components/ui/Input";
import { useEditorStore } from "@store/editor-store";
const RESOLUTION_OPTIONS = [
{ value: "720p", label: "720p" },
{ value: "1080p", label: "1080p" },
{ value: "1440p", label: "1440p" },
{ value: "4K", label: "4K" },
];
const FPS_OPTIONS = [
{ value: "30", label: "30 FPS" },
{ value: "60", label: "60 FPS" },
{ value: "120", label: "120 FPS" },
{ value: "144", label: "144 FPS" },
];
export function VideoSettingsForm() {
const { t } = useTranslation("ui");
const store = useEditorStore();
return (
<div className="flex flex-col gap-3">
<span className="text-sm font-medium text-text-secondary">{t("editor.videoSettings")}</span>
<div className="grid grid-cols-3 gap-3">
<Select
label={t("editor.resolution")}
options={RESOLUTION_OPTIONS}
value={store.resolution ?? "1080p"}
onChange={(v) => store.set("resolution", v)}
/>
<Select
label={t("editor.fps")}
options={FPS_OPTIONS}
value={store.fps ?? "60"}
onChange={(v) => store.set("fps", v)}
/>
<Input
label={t("editor.graphicsPreset")}
placeholder="Ultra"
value={store.graphicsPreset ?? ""}
onChange={(e) => store.set("graphicsPreset", e.target.value)}
/>
</div>
</div>
);
}
@@ -0,0 +1,25 @@
import { useTranslation } from "react-i18next";
import { ChipGroup } from "@components/ui/ChipGroup";
import { VIDEO_TYPES } from "@config/video-types";
import { useEditorStore } from "@store/editor-store";
export function VideoTypeSelector() {
const { t } = useTranslation("ui");
const videoType = useEditorStore((s) => s.videoType);
const set = useEditorStore((s) => s.set);
const options = VIDEO_TYPES.map((vt) => ({
id: vt.id,
label: t(vt.labelKey),
icon: vt.icon,
}));
return (
<ChipGroup
label={t("editor.videoType")}
options={options}
value={videoType}
onChange={(v) => set("videoType", v as typeof videoType)}
/>
);
}
+26
View File
@@ -0,0 +1,26 @@
import { useTranslation } from "react-i18next";
import { Toggle } from "@components/ui/Toggle";
import { useEditorStore } from "@store/editor-store";
export function WarningToggles() {
const { t } = useTranslation("ui");
const spoilerWarning = useEditorStore((s) => s.spoilerWarning);
const matureWarning = useEditorStore((s) => s.matureWarning);
const set = useEditorStore((s) => s.set);
return (
<div className="flex flex-col gap-3">
<span className="text-sm font-medium text-text-secondary">{t("editor.warnings")}</span>
<Toggle
label={t("editor.spoilerWarning")}
checked={spoilerWarning}
onChange={(v) => set("spoilerWarning", v)}
/>
<Toggle
label={t("editor.matureWarning")}
checked={matureWarning}
onChange={(v) => set("matureWarning", v)}
/>
</div>
);
}
+15
View File
@@ -0,0 +1,15 @@
import { Outlet } from "react-router-dom";
import { Header } from "./Header";
import { TabBar } from "./TabBar";
export function AppShell() {
return (
<div className="flex min-h-screen flex-col bg-surface-0">
<Header />
<TabBar />
<main className="flex-1 overflow-y-auto">
<Outlet />
</main>
</div>
);
}
+28
View File
@@ -0,0 +1,28 @@
import { useTranslation } from "react-i18next";
import { Select } from "@components/ui/Select";
import { SUPPORTED_LANGUAGES } from "@i18n/index";
export function Header() {
const { t, i18n } = useTranslation("ui");
const langOptions = SUPPORTED_LANGUAGES.map((lang) => ({
value: lang.id,
label: `${lang.flag} ${lang.nativeName}`,
}));
return (
<header className="flex items-center justify-between border-b border-border bg-surface-1 px-6 py-3">
<div>
<h1 className="text-lg font-bold text-text-primary">{t("app.title")}</h1>
<p className="text-xs text-text-muted">{t("app.subtitle")}</p>
</div>
<div className="w-40">
<Select
options={langOptions}
value={i18n.language}
onChange={(v) => i18n.changeLanguage(v)}
/>
</div>
</header>
);
}
+36
View File
@@ -0,0 +1,36 @@
import { NavLink } from "react-router-dom";
import { useTranslation } from "react-i18next";
import { Pencil, FileText } from "lucide-react";
import clsx from "clsx";
const tabs = [
{ to: "/", labelKey: "tabs.editor", icon: Pencil },
{ to: "/output", labelKey: "tabs.output", icon: FileText },
] as const;
export function TabBar() {
const { t } = useTranslation("ui");
return (
<nav className="flex border-b border-border bg-surface-1 px-6">
{tabs.map((tab) => (
<NavLink
key={tab.to}
to={tab.to}
end={tab.to === "/"}
className={({ isActive }) =>
clsx(
"flex items-center gap-2 border-b-2 px-4 py-2.5 text-sm font-medium transition-colors",
isActive
? "border-accent text-accent"
: "border-transparent text-text-muted hover:text-text-secondary",
)
}
>
<tab.icon className="h-4 w-4" />
{t(tab.labelKey)}
</NavLink>
))}
</nav>
);
}
+22
View File
@@ -0,0 +1,22 @@
import clsx from "clsx";
import { useCharCount } from "@hooks/use-char-count";
interface CharCounterProps {
text: string;
limit: number;
}
export function CharCounter({ text, limit }: CharCounterProps) {
const { count, isOver, percentage } = useCharCount(text, limit);
return (
<span
className={clsx(
"text-xs font-mono",
isOver ? "text-danger" : percentage > 80 ? "text-warning" : "text-text-muted",
)}
>
{count}/{limit}
</span>
);
}
+25
View File
@@ -0,0 +1,25 @@
import { useTranslation } from "react-i18next";
import { ClipboardCopy } from "lucide-react";
import { Button } from "@components/ui/Button";
import { useGeneratedOutput } from "@hooks/use-generated-output";
import { useClipboard } from "@hooks/use-clipboard";
export function CopyAllBar() {
const { t } = useTranslation("ui");
const output = useGeneratedOutput();
const { copy } = useClipboard();
const handleCopyAll = () => {
const combined = `${output.title}\n\n${output.description}`;
copy(combined);
};
return (
<div className="sticky bottom-0 flex items-center justify-end border-t border-border bg-surface-0 px-4 py-3">
<Button onClick={handleCopyAll} size="lg">
<ClipboardCopy className="h-4 w-4" />
{t("output.copyAll")}
</Button>
</div>
);
}
+19
View File
@@ -0,0 +1,19 @@
import { Copy, Check } from "lucide-react";
import { Button } from "@components/ui/Button";
import { useClipboard } from "@hooks/use-clipboard";
interface CopyButtonProps {
text: string;
label: string;
}
export function CopyButton({ text, label }: CopyButtonProps) {
const { copy, copied } = useClipboard();
return (
<Button variant="ghost" size="sm" onClick={() => copy(text)} disabled={!text}>
{copied ? <Check className="h-4 w-4" /> : <Copy className="h-4 w-4" />}
{copied ? "Copied!" : label}
</Button>
);
}
+69
View File
@@ -0,0 +1,69 @@
import { useTranslation } from "react-i18next";
import { useGeneratedOutput } from "@hooks/use-generated-output";
import { CopyButton } from "./CopyButton";
import { CharCounter } from "./CharCounter";
import { YT_LIMITS } from "@engine/types";
export function OutputPreview() {
const { t } = useTranslation("ui");
const output = useGeneratedOutput();
return (
<div className="flex flex-col gap-6">
{/* Title */}
<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.title")}</h3>
<div className="flex items-center gap-3">
<CharCounter text={output.title} limit={YT_LIMITS.TITLE_MAX} />
<CopyButton text={output.title} label={t("output.copyTitle")} />
</div>
</div>
<div className="rounded-lg border border-border bg-surface-1 p-3">
<p className="text-sm font-medium text-text-primary">{output.title}</p>
</div>
</section>
{/* Description */}
<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.description")}</h3>
<div className="flex items-center gap-3">
<CharCounter text={output.description} limit={YT_LIMITS.DESCRIPTION_MAX} />
<CopyButton text={output.description} label={t("output.copyDescription")} />
</div>
</div>
<div className="max-h-[400px] overflow-y-auto rounded-lg border border-border bg-surface-1 p-3">
<pre className="whitespace-pre-wrap font-sans text-sm text-text-secondary">
{output.description}
</pre>
</div>
</section>
{/* Tags */}
<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.tags")} ({output.tags.length})
</h3>
<div className="flex items-center gap-3">
<CharCounter text={output.tagString} limit={YT_LIMITS.TAGS_MAX} />
<CopyButton text={output.tagString} label={t("output.copyTags")} />
</div>
</div>
<div className="rounded-lg border border-border bg-surface-1 p-3">
<div className="flex flex-wrap gap-1.5">
{output.tags.map((tag, i) => (
<span
key={i}
className="rounded-md bg-surface-2 px-2 py-0.5 text-xs text-text-secondary"
>
{tag}
</span>
))}
</div>
</div>
</section>
</div>
);
}
+38
View File
@@ -0,0 +1,38 @@
import { forwardRef, type ButtonHTMLAttributes } from "react";
import clsx from "clsx";
interface ButtonProps extends ButtonHTMLAttributes<HTMLButtonElement> {
variant?: "primary" | "secondary" | "ghost";
size?: "sm" | "md" | "lg";
}
const variantClasses = {
primary: "bg-accent text-white hover:bg-accent-hover",
secondary: "bg-surface-2 text-text-primary border border-border hover:bg-surface-3",
ghost: "text-text-secondary hover:text-text-primary hover:bg-surface-2",
};
const sizeClasses = {
sm: "px-2.5 py-1 text-xs",
md: "px-4 py-2 text-sm",
lg: "px-6 py-2.5 text-base",
};
export const Button = forwardRef<HTMLButtonElement, ButtonProps>(
({ variant = "primary", size = "md", className, children, ...props }, ref) => (
<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",
variantClasses[variant],
sizeClasses[size],
className,
)}
{...props}
>
{children}
</button>
),
);
Button.displayName = "Button";
+41
View File
@@ -0,0 +1,41 @@
import clsx from "clsx";
interface ChipOption {
id: string;
label: string;
icon?: string;
}
interface ChipGroupProps {
label?: string;
options: readonly ChipOption[];
value: string;
onChange: (value: string) => void;
className?: string;
}
export function ChipGroup({ label, options, value, onChange, className }: ChipGroupProps) {
return (
<div className={clsx("flex flex-col gap-2", className)}>
{label && <span className="text-sm font-medium text-text-secondary">{label}</span>}
<div className="flex flex-wrap gap-2">
{options.map((option) => (
<button
key={option.id}
type="button"
onClick={() => onChange(option.id)}
className={clsx(
"inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-sm font-medium transition-colors",
value === option.id
? "bg-accent text-white"
: "bg-surface-2 text-text-secondary hover:bg-surface-3 hover:text-text-primary",
)}
>
{option.icon && <span>{option.icon}</span>}
{option.label}
</button>
))}
</div>
</div>
);
}
+35
View File
@@ -0,0 +1,35 @@
import { forwardRef, type InputHTMLAttributes } from "react";
import clsx from "clsx";
interface InputProps extends InputHTMLAttributes<HTMLInputElement> {
label?: string;
error?: boolean;
}
export const Input = forwardRef<HTMLInputElement, InputProps>(
({ label, error, className, id, ...props }, ref) => {
const inputId = id ?? label?.toLowerCase().replace(/\s+/g, "-");
return (
<div className="flex flex-col gap-1">
{label && (
<label htmlFor={inputId} className="text-sm font-medium text-text-secondary">
{label}
</label>
)}
<input
ref={ref}
id={inputId}
className={clsx(
"rounded-lg border bg-surface-1 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-colors focus:outline-none focus:ring-2 focus:ring-accent/50",
error ? "border-danger" : "border-border focus:border-accent",
className,
)}
{...props}
/>
</div>
);
},
);
Input.displayName = "Input";
+48
View File
@@ -0,0 +1,48 @@
import { forwardRef, type SelectHTMLAttributes } from "react";
import clsx from "clsx";
interface SelectOption {
value: string;
label: string;
}
interface SelectProps extends Omit<SelectHTMLAttributes<HTMLSelectElement>, "onChange"> {
label?: string;
options: readonly SelectOption[];
onChange: (value: string) => void;
}
export const Select = forwardRef<HTMLSelectElement, SelectProps>(
({ label, options, value, onChange, className, id, ...props }, ref) => {
const selectId = id ?? label?.toLowerCase().replace(/\s+/g, "-");
return (
<div className="flex flex-col gap-1">
{label && (
<label htmlFor={selectId} className="text-sm font-medium text-text-secondary">
{label}
</label>
)}
<select
ref={ref}
id={selectId}
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",
className,
)}
{...props}
>
{options.map((opt) => (
<option key={opt.value} value={opt.value}>
{opt.label}
</option>
))}
</select>
</div>
);
},
);
Select.displayName = "Select";
+35
View File
@@ -0,0 +1,35 @@
import { forwardRef, type TextareaHTMLAttributes } from "react";
import clsx from "clsx";
interface TextareaProps extends TextareaHTMLAttributes<HTMLTextAreaElement> {
label?: string;
error?: boolean;
}
export const Textarea = forwardRef<HTMLTextAreaElement, TextareaProps>(
({ label, error, className, id, ...props }, ref) => {
const inputId = id ?? label?.toLowerCase().replace(/\s+/g, "-");
return (
<div className="flex flex-col gap-1">
{label && (
<label htmlFor={inputId} className="text-sm font-medium text-text-secondary">
{label}
</label>
)}
<textarea
ref={ref}
id={inputId}
className={clsx(
"min-h-[80px] rounded-lg border bg-surface-1 px-3 py-2 text-sm text-text-primary placeholder:text-text-muted transition-colors focus:outline-none focus:ring-2 focus:ring-accent/50 resize-y",
error ? "border-danger" : "border-border focus:border-accent",
className,
)}
{...props}
/>
</div>
);
},
);
Textarea.displayName = "Textarea";
+33
View File
@@ -0,0 +1,33 @@
import clsx from "clsx";
interface ToggleProps {
label: string;
checked: boolean;
onChange: (checked: boolean) => void;
className?: string;
}
export function Toggle({ label, checked, onChange, className }: ToggleProps) {
return (
<label className={clsx("flex cursor-pointer items-center gap-3", className)}>
<button
role="switch"
type="button"
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",
checked ? "bg-accent" : "bg-surface-3",
)}
>
<span
className={clsx(
"pointer-events-none inline-block h-5 w-5 rounded-full bg-white shadow-sm transition-transform",
checked ? "translate-x-5" : "translate-x-0",
)}
/>
</button>
<span className="text-sm text-text-primary">{label}</span>
</label>
);
}
+67
View File
@@ -0,0 +1,67 @@
import type { VideoTypeId } from "./video-types";
import type { GenreId } from "./genres";
import type { SupportedLanguage } from "@engine/types";
export interface EditorDefaults {
videoType: VideoTypeId;
language: SupportedLanguage;
genre: GenreId;
gameName: string;
gameNameLocalized: Record<string, string>;
channelName: string;
platform: string;
partNumber: string;
bossName: string;
dlcName: string;
challengeName: string;
resolution: string;
fps: string;
graphicsPreset: string;
timestamps: string;
playlistLink: string;
contactEmail: string;
spoilerWarning: boolean;
matureWarning: boolean;
storeLinks: Record<string, string>;
social: Record<string, string>;
rig: Record<string, string>;
}
export interface SettingsDefaults {
theme: "dark" | "light";
defaultLanguage: string;
defaultGenre: GenreId;
}
export const DEFAULTS = {
editor: {
videoType: "full",
language: "en",
genre: "action",
gameName: "",
gameNameLocalized: {},
channelName: "",
platform: "steam",
partNumber: "",
bossName: "",
dlcName: "",
challengeName: "",
resolution: "1080p",
fps: "60",
graphicsPreset: "Ultra",
timestamps: "",
playlistLink: "",
contactEmail: "",
spoilerWarning: false,
matureWarning: false,
storeLinks: {},
social: {},
rig: {},
} satisfies EditorDefaults,
settings: {
theme: "dark",
defaultLanguage: "en",
defaultGenre: "action",
} satisfies SettingsDefaults,
} as const;
+14
View File
@@ -0,0 +1,14 @@
export const GENRES = [
{ id: "action", labelKey: "genres.action", icon: "⚔️" },
{ id: "horror", labelKey: "genres.horror", icon: "👻" },
{ id: "rpg", labelKey: "genres.rpg", icon: "🛡" },
{ id: "fps", labelKey: "genres.fps", icon: "🔫" },
{ id: "openworld", labelKey: "genres.openworld", icon: "🌍" },
{ id: "indie", labelKey: "genres.indie", icon: "🕹" },
{ id: "soulslike", labelKey: "genres.soulslike", icon: "💀" },
{ id: "racing", labelKey: "genres.racing", icon: "🏎" },
{ id: "story", labelKey: "genres.story", icon: "📖" },
{ id: "simulation", labelKey: "genres.simulation", icon: "🏗" },
] as const;
export type GenreId = (typeof GENRES)[number]["id"];
+11
View File
@@ -0,0 +1,11 @@
export const PLATFORMS = [
{ id: "steam", label: "Steam", urlPrefix: "https://store.steampowered.com/app/" },
{ id: "epic", label: "Epic Games Store", urlPrefix: "https://store.epicgames.com/" },
{ id: "ps", label: "PlayStation Store", urlPrefix: "https://store.playstation.com/" },
{ id: "xbox", label: "Xbox / Microsoft Store", urlPrefix: "https://www.xbox.com/games/" },
{ id: "nintendo", label: "Nintendo eShop", urlPrefix: "https://www.nintendo.com/store/" },
{ id: "gog", label: "GOG", urlPrefix: "https://www.gog.com/game/" },
{ id: "itchio", label: "itch.io", urlPrefix: "https://itch.io/" },
] as const;
export type PlatformId = (typeof PLATFORMS)[number]["id"];
+10
View File
@@ -0,0 +1,10 @@
export const RIG_FIELDS = [
{ id: "cpu", labelKey: "rig.cpu", placeholder: "Intel i9-14900K / AMD Ryzen 9 7950X" },
{ id: "gpu", labelKey: "rig.gpu", placeholder: "NVIDIA RTX 4090 / AMD RX 7900 XTX" },
{ id: "ram", labelKey: "rig.ram", placeholder: "32GB DDR5-6000" },
{ id: "storage", labelKey: "rig.storage", placeholder: "2TB Samsung 990 PRO NVMe" },
{ id: "monitor", labelKey: "rig.monitor", placeholder: "LG 27GP950 27\" 4K 144Hz" },
{ id: "capture", labelKey: "rig.capture", placeholder: "OBS Studio 30.x" },
] as const;
export type RigFieldId = (typeof RIG_FIELDS)[number]["id"];
+28
View File
@@ -0,0 +1,28 @@
export const SOCIAL_FIELDS = [
{ id: "kofi", labelKey: "social.kofi", urlPrefix: "https://ko-fi.com/", category: "donate" },
{
id: "patreon",
labelKey: "social.patreon",
urlPrefix: "https://patreon.com/",
category: "donate",
},
{
id: "buymeacoffee",
labelKey: "social.buymeacoffee",
urlPrefix: "https://buymeacoffee.com/",
category: "donate",
},
{
id: "paypal",
labelKey: "social.paypal",
urlPrefix: "https://paypal.me/",
category: "donate",
},
{ id: "github", labelKey: "social.github", urlPrefix: "https://github.com/", category: "social" },
{ id: "twitter", labelKey: "social.twitter", urlPrefix: "https://x.com/", category: "social" },
{ id: "discord", labelKey: "social.discord", urlPrefix: "https://discord.gg/", category: "social" },
{ id: "website", labelKey: "social.website", urlPrefix: "", category: "social" },
] as const;
export type SocialFieldId = (typeof SOCIAL_FIELDS)[number]["id"];
export type SocialCategory = "donate" | "social";
+11
View File
@@ -0,0 +1,11 @@
export const VIDEO_TYPES = [
{ id: "full", labelKey: "videoTypes.full", icon: "🎮", extraFields: [] },
{ id: "part", labelKey: "videoTypes.part", icon: "📂", extraFields: ["partNumber"] },
{ id: "boss", labelKey: "videoTypes.boss", icon: "👹", extraFields: ["bossName"] },
{ id: "boss_nohit", labelKey: "videoTypes.boss_nohit", icon: "💀", extraFields: ["bossName"] },
{ id: "ending", labelKey: "videoTypes.ending", icon: "🏁", extraFields: [] },
{ id: "speedrun", labelKey: "videoTypes.speedrun", icon: "⚡", extraFields: [] },
{ id: "100percent", labelKey: "videoTypes.100percent", icon: "💯", extraFields: [] },
] as const;
export type VideoTypeId = (typeof VIDEO_TYPES)[number]["id"];
+129
View File
@@ -0,0 +1,129 @@
import type { GeneratorInput, TranslationFn, CharLimitWarning } from "./types";
import { YT_LIMITS } from "./types";
function hasEntries(obj: Partial<Record<string, string>>): boolean {
return Object.values(obj).some((v) => v && v.trim() !== "");
}
function formatKeyValueBlock(
obj: Partial<Record<string, string>>,
labelMap?: Record<string, string>,
): string {
return Object.entries(obj)
.filter(([, v]) => v && v.trim() !== "")
.map(([k, v]) => {
const label = labelMap?.[k] ?? k.toUpperCase();
return `${label}: ${v}`;
})
.join("\n");
}
export function buildDescription(input: GeneratorInput, t: TranslationFn): string {
const sections: string[] = [];
const gameName =
input.gameNameLocalized?.[input.language] ?? input.gameName;
// 1. Intro
const intro = t(`description.intro.${input.videoType}`, {
gameName,
channelName: input.channelName,
partNumber: input.partNumber ?? "",
bossName: input.bossName ?? "",
dlcName: input.dlcName ?? "",
challengeName: input.challengeName ?? "",
});
sections.push(intro);
// 2. No Commentary tagline
sections.push(t("description.noCommentaryLine"));
// 3. Timestamps
if (input.timestamps && input.timestamps.trim()) {
sections.push(`${t("description.sections.timestamps")}\n${input.timestamps.trim()}`);
}
// 4. Store Links
if (hasEntries(input.storeLinks)) {
const links = Object.entries(input.storeLinks)
.filter(([, v]) => v && v.trim() !== "")
.map(([platform, url]) => `${platform}: ${url}`)
.join("\n");
sections.push(`${t("description.sections.storeLinks")}\n${links}`);
}
// 5. Video Settings
const settings: string[] = [];
if (input.resolution) settings.push(input.resolution);
if (input.fps) settings.push(`${input.fps} FPS`);
if (input.graphicsPreset) settings.push(input.graphicsPreset);
if (settings.length > 0) {
sections.push(`${t("description.sections.videoSettings")}\n${settings.join(" | ")}`);
}
// 6. Rig
if (hasEntries(input.rig)) {
sections.push(`${t("description.sections.rig")}\n${formatKeyValueBlock(input.rig)}`);
}
// 7. Spoiler Warning
if (input.spoilerWarning) {
sections.push(t("description.sections.spoilerWarning"));
}
// 8. Mature Warning
if (input.matureWarning) {
sections.push(t("description.sections.matureWarning"));
}
// 9. Donate Links
const donateFields = ["kofi", "patreon", "buymeacoffee", "paypal", "streamlabs"];
const donateLinks = Object.entries(input.social)
.filter(([k, v]) => donateFields.includes(k) && v && v.trim() !== "")
.map(([k, v]) => `${k}: ${v}`)
.join("\n");
if (donateLinks) {
sections.push(`${t("description.sections.donate")}\n${donateLinks}`);
}
// 10. Social Links
const socialFields = ["github", "twitter", "discord", "twitch", "tiktok", "instagram", "website"];
const socialLinks = Object.entries(input.social)
.filter(([k, v]) => socialFields.includes(k) && v && v.trim() !== "")
.map(([k, v]) => `${k}: ${v}`)
.join("\n");
if (socialLinks) {
sections.push(`${t("description.sections.social")}\n${socialLinks}`);
}
// 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()) {
sections.push(t("description.sections.contact", { email: input.contactEmail }));
}
// 13. CTA
sections.push(t("description.sections.cta"));
// 14. Hashtags
const gameTag = `#${gameName.replace(/\s+/g, "")}`;
const genreTag = `#${input.genre}`;
sections.push(`${gameTag} #GameplayNoCommentary ${genreTag}`);
return sections.join("\n\n");
}
export function checkDescriptionWarning(description: string): CharLimitWarning | null {
if (description.length > YT_LIMITS.DESCRIPTION_MAX) {
return {
field: "description",
current: description.length,
limit: YT_LIMITS.DESCRIPTION_MAX,
message: `Description exceeds ${YT_LIMITS.DESCRIPTION_MAX} characters (${description.length}/${YT_LIMITS.DESCRIPTION_MAX})`,
};
}
return null;
}
+135
View File
@@ -0,0 +1,135 @@
import type { GeneratorInput } from "./types";
import { YT_LIMITS } from "./types";
const GENRE_TAG_REGISTRY: Record<string, (gameName: string) => string[]> = {
action: (g) => [`${g} action`, "action game no commentary", "action adventure gameplay"],
horror: (g) => [`${g} horror`, "horror game no commentary", "survival horror gameplay"],
rpg: (g) => [`${g} RPG`, "RPG no commentary", "RPG gameplay", "JRPG no commentary"],
fps: (g) => [`${g} FPS`, "FPS no commentary", "shooter gameplay no commentary"],
openworld: (g) => [`${g} open world`, "open world no commentary", "free roam gameplay"],
indie: (g) => [`${g} indie`, "indie game no commentary", "indie gameplay"],
soulslike: (g) => [`${g} souls like`, "soulsborne no commentary", "souls like gameplay"],
racing: (g) => [`${g} racing`, "racing game no commentary", "racing gameplay"],
story: (g) => [`${g} story`, "story game no commentary", "narrative gameplay"],
simulation: (g) => [`${g} simulation`, "simulation game no commentary", "strategy gameplay"],
};
const VIDEO_TYPE_TAGS: Record<string, (gameName: string) => string[]> = {
full: (g) => [`${g} full game`, `${g} full gameplay no commentary`, `${g} longplay`],
part: (g) => [`${g} walkthrough`, `${g} playthrough`, `${g} let's play no commentary`],
boss: (g) => [`${g} boss fight`, `${g} boss battle`, "boss fight no commentary"],
boss_nohit: (g) => [`${g} boss no hit`, `${g} no damage boss`, "no hit boss fight"],
ending: (g) => [`${g} ending`, `${g} all endings`, `${g} final boss`],
speedrun: (g) => [`${g} speedrun`, "speedrun no commentary", `${g} speed run`],
"100percent": (g) => [`${g} 100%`, `${g} 100 percent`, `${g} completionist`],
};
const MULTILINGUAL_TAGS: Record<string, (gameName: string) => string[]> = {
ja: (g) => [`${g} ゲームプレイ`, `${g} 実況なし`, "ゲームプレイ 実況なし"],
vi: (g) => [`${g} gameplay không bình luận`, `${g} không bình luận`],
};
function getCoreTags(gameName: string): string[] {
return [
`${gameName} gameplay`,
`${gameName} no commentary`,
"gameplay no commentary",
`${gameName} walkthrough`,
`${gameName} full game`,
`${gameName} gameplay no commentary`,
];
}
function getPlatformTags(gameName: string, platform: string): string[] {
if (!platform) return [];
const platformLabel = platform.toUpperCase();
return [`${gameName} ${platformLabel}`, `${platformLabel} gameplay`, `${gameName} ${platformLabel} gameplay`];
}
function getQualityTags(gameName: string, resolution?: string, fps?: string): string[] {
const tags: string[] = [];
if (resolution && resolution !== "1080p") {
tags.push(`${gameName} ${resolution}`, `${resolution} gameplay no commentary`);
}
if (fps && fps !== "60") {
tags.push(`${gameName} ${fps}fps`);
}
if (resolution && fps) {
tags.push(`${gameName} ${resolution} ${fps}fps`);
}
return tags;
}
function getTrendingTags(gameName: string, genre: string): string[] {
const year = new Date().getFullYear().toString();
return [`${gameName} ${year}`, `best ${genre} games ${year}`, `${genre} gameplay ${year}`];
}
export function generateTags(input: GeneratorInput): string[] {
const gameName =
input.gameNameLocalized?.[input.language] ?? input.gameName;
const allTags: string[] = [];
// Core tags (highest priority)
allTags.push(...getCoreTags(gameName));
// Genre tags
const genreFn = GENRE_TAG_REGISTRY[input.genre];
if (genreFn) {
allTags.push(...genreFn(gameName));
}
// Video type tags
const typeFn = VIDEO_TYPE_TAGS[input.videoType];
if (typeFn) {
allTags.push(...typeFn(gameName));
}
// Platform tags
allTags.push(...getPlatformTags(gameName, input.platform));
// Quality tags
allTags.push(...getQualityTags(gameName, input.resolution, input.fps));
// Multilingual tags (always include ja and vi)
for (const [, langFn] of Object.entries(MULTILINGUAL_TAGS)) {
allTags.push(...langFn(gameName));
}
// Trending tags (lowest priority)
allTags.push(...getTrendingTags(gameName, input.genre));
// Dedup (case-insensitive)
const seen = new Set<string>();
const deduped: string[] = [];
for (const tag of allTags) {
const lower = tag.toLowerCase().trim();
if (lower && !seen.has(lower) && lower.length <= YT_LIMITS.SINGLE_TAG_MAX) {
seen.add(lower);
deduped.push(tag.trim());
}
}
// Trim to 500 character limit
return trimToCharLimit(deduped, YT_LIMITS.TAGS_MAX);
}
function trimToCharLimit(tags: string[], maxChars: number): string[] {
const result: string[] = [];
let totalLength = 0;
for (const tag of tags) {
const separatorLength = result.length > 0 ? 2 : 0; // ", "
const newLength = totalLength + separatorLength + tag.length;
if (newLength > maxChars) break;
result.push(tag);
totalLength = newLength;
}
return result;
}
export function formatTagString(tags: string[]): string {
return tags.join(", ");
}
+44
View File
@@ -0,0 +1,44 @@
import type { GeneratorInput, GeneratorOutput, TranslationFn, CharLimitWarning } from "./types";
import { buildTitle, checkTitleWarning } from "./title-builder";
import { buildDescription, checkDescriptionWarning } from "./description-builder";
import { generateTags, formatTagString } from "./tag-generator";
import { YT_LIMITS } from "./types";
export function renderAll(input: GeneratorInput, t: TranslationFn): GeneratorOutput {
const title = buildTitle(input, t);
const description = buildDescription(input, t);
const tags = generateTags(input);
const tagString = formatTagString(tags);
const charCounts = {
title: title.length,
description: description.length,
tags: tagString.length,
};
const warnings: CharLimitWarning[] = [];
const titleWarning = checkTitleWarning(title);
if (titleWarning) warnings.push(titleWarning);
const descWarning = checkDescriptionWarning(description);
if (descWarning) warnings.push(descWarning);
if (tagString.length > YT_LIMITS.TAGS_MAX) {
warnings.push({
field: "tags",
current: tagString.length,
limit: YT_LIMITS.TAGS_MAX,
message: `Tags exceed ${YT_LIMITS.TAGS_MAX} characters (${tagString.length}/${YT_LIMITS.TAGS_MAX})`,
});
}
return {
title,
description,
tags,
tagString,
charCounts,
warnings,
};
}
+37
View File
@@ -0,0 +1,37 @@
import type { GeneratorInput, TranslationFn, CharLimitWarning } from "./types";
import { YT_LIMITS } from "./types";
export function buildTitle(input: GeneratorInput, t: TranslationFn): string {
const separator = t("title.separator");
const suffix = t("title.suffix");
const videoTypeLabel = t(`title.videoType.${input.videoType}`, {
partNumber: input.partNumber ?? "",
bossName: input.bossName ?? "",
dlcName: input.dlcName ?? "",
challengeName: input.challengeName ?? "",
});
const gameName =
input.gameNameLocalized?.[input.language] ?? input.gameName;
const parts = [gameName];
if (videoTypeLabel) {
parts.push(videoTypeLabel);
}
parts.push(suffix);
return parts.join(separator);
}
export function checkTitleWarning(title: string): CharLimitWarning | null {
if (title.length > YT_LIMITS.TITLE_MAX) {
return {
field: "title",
current: title.length,
limit: YT_LIMITS.TITLE_MAX,
message: `Title exceeds ${YT_LIMITS.TITLE_MAX} characters (${title.length}/${YT_LIMITS.TITLE_MAX})`,
};
}
return null;
}
+79
View File
@@ -0,0 +1,79 @@
export type VideoType =
| "full"
| "part"
| "boss"
| "boss_nohit"
| "ending"
| "speedrun"
| "100percent";
export type Genre =
| "action"
| "horror"
| "rpg"
| "fps"
| "openworld"
| "indie"
| "soulslike"
| "racing"
| "story"
| "simulation";
export type SupportedLanguage = "en" | "vi" | "ja";
export interface GeneratorInput {
videoType: VideoType;
language: SupportedLanguage;
genre: Genre;
gameName: string;
gameNameLocalized?: Partial<Record<SupportedLanguage, string>>;
channelName: string;
platform: string;
partNumber?: string;
bossName?: string;
dlcName?: string;
challengeName?: string;
resolution?: string;
fps?: string;
graphicsPreset?: string;
timestamps?: string;
playlistLink?: string;
contactEmail?: string;
spoilerWarning: boolean;
matureWarning: boolean;
storeLinks: Partial<Record<string, string>>;
social: Partial<Record<string, string>>;
rig: Partial<Record<string, string>>;
}
export interface GeneratorOutput {
title: string;
description: string;
tags: string[];
tagString: string;
charCounts: {
title: number;
description: number;
tags: number;
};
warnings: CharLimitWarning[];
}
export interface CharLimitWarning {
field: "title" | "description" | "tags";
current: number;
limit: number;
message: string;
}
export const YT_LIMITS = {
TITLE_MAX: 100,
DESCRIPTION_MAX: 5000,
TAGS_MAX: 500,
SINGLE_TAG_MAX: 30,
HASHTAG_MAX: 3,
} as const;
export interface TranslationFn {
(key: string, options?: Record<string, string>): string;
}
+20
View File
@@ -0,0 +1,20 @@
import { useMemo } from "react";
interface CharCountResult {
count: number;
limit: number;
isOver: boolean;
percentage: number;
}
export function useCharCount(text: string, limit: number): CharCountResult {
return useMemo(
() => ({
count: text.length,
limit,
isOver: text.length > limit,
percentage: Math.min((text.length / limit) * 100, 100),
}),
[text, limit],
);
}
+27
View File
@@ -0,0 +1,27 @@
import { useState, useCallback, useRef } from "react";
import toast from "react-hot-toast";
interface UseClipboardReturn {
copy: (text: string) => Promise<void>;
copied: boolean;
}
export function useClipboard(): UseClipboardReturn {
const [copied, setCopied] = useState(false);
const timeoutRef = useRef<ReturnType<typeof setTimeout> | null>(null);
const copy = useCallback(async (text: string) => {
try {
await navigator.clipboard.writeText(text);
setCopied(true);
toast.success("Copied!");
if (timeoutRef.current) clearTimeout(timeoutRef.current);
timeoutRef.current = setTimeout(() => setCopied(false), 2000);
} catch {
toast.error("Failed to copy");
}
}, []);
return { copy, copied };
}
+12
View File
@@ -0,0 +1,12 @@
import { useState, useEffect } from "react";
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState(value);
useEffect(() => {
const timer = setTimeout(() => setDebouncedValue(value), delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}
+63
View File
@@ -0,0 +1,63 @@
import { useMemo } from "react";
import { useTranslation } from "react-i18next";
import { useEditorStore } from "@store/editor-store";
import { renderAll } from "@engine/template-renderer";
import type { GeneratorOutput, GeneratorInput } from "@engine/types";
export function useGeneratedOutput(): GeneratorOutput {
const state = useEditorStore();
const { t } = useTranslation("templates");
const input: GeneratorInput = useMemo(
() => ({
videoType: state.videoType,
language: state.language,
genre: state.genre,
gameName: state.gameName,
gameNameLocalized: state.gameNameLocalized,
channelName: state.channelName,
platform: state.platform,
partNumber: state.partNumber,
bossName: state.bossName,
dlcName: state.dlcName,
challengeName: state.challengeName,
resolution: state.resolution,
fps: state.fps,
graphicsPreset: state.graphicsPreset,
timestamps: state.timestamps,
playlistLink: state.playlistLink,
contactEmail: state.contactEmail,
spoilerWarning: state.spoilerWarning,
matureWarning: state.matureWarning,
storeLinks: state.storeLinks,
social: state.social,
rig: state.rig,
}),
[
state.videoType,
state.language,
state.genre,
state.gameName,
state.gameNameLocalized,
state.channelName,
state.platform,
state.partNumber,
state.bossName,
state.dlcName,
state.challengeName,
state.resolution,
state.fps,
state.graphicsPreset,
state.timestamps,
state.playlistLink,
state.contactEmail,
state.spoilerWarning,
state.matureWarning,
state.storeLinks,
state.social,
state.rig,
],
);
return useMemo(() => renderAll(input, t), [input, t]);
}
+33
View File
@@ -0,0 +1,33 @@
import i18n from "i18next";
import { initReactI18next } from "react-i18next";
import enUI from "./locales/en/ui.json";
import enTemplates from "./locales/en/templates.json";
import viUI from "./locales/vi/ui.json";
import viTemplates from "./locales/vi/templates.json";
import jaUI from "./locales/ja/ui.json";
import jaTemplates from "./locales/ja/templates.json";
export const SUPPORTED_LANGUAGES = [
{ id: "en", label: "English", flag: "🇬🇧", nativeName: "English" },
{ id: "vi", label: "Vietnamese", flag: "🇻🇳", nativeName: "Tiếng Việt" },
{ id: "ja", label: "Japanese", flag: "🇯🇵", nativeName: "日本語" },
] as const;
export type SupportedLanguageId = (typeof SUPPORTED_LANGUAGES)[number]["id"];
i18n.use(initReactI18next).init({
resources: {
en: { ui: enUI, templates: enTemplates },
vi: { ui: viUI, templates: viTemplates },
ja: { ui: jaUI, templates: jaTemplates },
},
ns: ["ui", "templates"],
defaultNS: "ui",
fallbackLng: "en",
interpolation: {
escapeValue: false,
},
});
export default i18n;
+43
View File
@@ -0,0 +1,43 @@
{
"ui": {
"app": ["title", "subtitle"],
"tabs": ["editor", "output"],
"editor": [
"videoType", "language", "genre", "gameName", "gameNamePlaceholder",
"channelName", "channelNamePlaceholder", "platform",
"partNumber", "partNumberPlaceholder", "bossName", "bossNamePlaceholder",
"dlcName", "dlcNamePlaceholder", "challengeName", "challengeNamePlaceholder",
"resolution", "fps", "graphicsPreset",
"timestamps", "timestampsPlaceholder",
"storeLinks", "rig", "social", "warnings",
"spoilerWarning", "matureWarning",
"playlistLink", "playlistLinkPlaceholder",
"contactEmail", "contactEmailPlaceholder",
"videoSettings", "quickPreview"
],
"output": [
"title", "description", "tags",
"copyTitle", "copyDescription", "copyTags", "copyAll",
"copied", "charCount"
],
"common": ["save", "cancel", "delete", "confirm", "export", "import", "reset", "search", "generate"],
"videoTypes": ["full", "part", "boss", "boss_nohit", "ending", "speedrun", "100percent"],
"genres": ["action", "horror", "rpg", "fps", "openworld", "indie", "soulslike", "racing", "story", "simulation"],
"rig": ["cpu", "gpu", "ram", "storage", "monitor", "capture"],
"social": ["kofi", "patreon", "buymeacoffee", "paypal", "github", "twitter", "discord", "website"],
"resolutions": ["720p", "1080p", "1440p", "4K"],
"fpsOptions": ["30", "60", "120", "144"]
},
"templates": {
"title": ["separator", "suffix"],
"title.videoType": ["full", "part", "boss", "boss_nohit", "ending", "speedrun", "100percent"],
"description.intro": ["full", "part", "boss", "boss_nohit", "ending", "speedrun", "100percent"],
"description": ["noCommentaryLine"],
"description.sections": [
"timestamps", "storeLinks", "videoSettings", "rig",
"spoilerWarning", "matureWarning", "donate", "social",
"playlist", "contact", "cta"
],
"hashtags": ["gameplay", "noCommentary", "genre"]
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"title": {
"separator": " — ",
"suffix": "Gameplay No Commentary",
"videoType": {
"full": "",
"part": "Part {{partNumber}}",
"boss": "{{bossName}} Boss Fight",
"boss_nohit": "{{bossName}} Boss No Hit",
"ending": "Ending",
"speedrun": "Speedrun",
"100percent": "100% Completion"
}
},
"description": {
"intro": {
"full": "This video features the full gameplay of {{gameName}} on {{channelName}}.",
"part": "This video features Part {{partNumber}} of {{gameName}} on {{channelName}}.",
"boss": "This video features the {{bossName}} boss fight from {{gameName}} on {{channelName}}.",
"boss_nohit": "This video features the {{bossName}} boss fight (No Hit) from {{gameName}} on {{channelName}}.",
"ending": "This video features the ending of {{gameName}} on {{channelName}}.",
"speedrun": "This video features a speedrun of {{gameName}} on {{channelName}}.",
"100percent": "This video features the 100% completion of {{gameName}} on {{channelName}}."
},
"noCommentaryLine": "No Commentary — pure gameplay for your enjoyment.",
"sections": {
"timestamps": "⏱ TIMESTAMPS",
"storeLinks": "🎮 GET THE GAME",
"videoSettings": "🖥 VIDEO SETTINGS",
"rig": "💻 MY RIG",
"spoilerWarning": "⚠️ SPOILER WARNING: This video may contain spoilers. Watch at your own risk!",
"matureWarning": "🔞 MATURE CONTENT (18+): Contains violence / strong language / graphic content.",
"donate": "☕ SUPPORT THE CHANNEL",
"social": "🔗 FOLLOW ME",
"playlist": "▶️ Watch the full series: {{link}}",
"contact": "📧 Business inquiries: {{email}}",
"cta": "👍 Like | 🔔 Subscribe | ↗️ Share"
}
},
"hashtags": {
"gameplay": "#{{gameName}}",
"noCommentary": "#GameplayNoCommentary",
"genre": "#{{genre}}"
}
}
+118
View File
@@ -0,0 +1,118 @@
{
"app": {
"title": "YTDescGen",
"subtitle": "Gameplay No Commentary Template Engine"
},
"tabs": {
"editor": "Editor",
"output": "Output"
},
"editor": {
"videoType": "Video Type",
"language": "Output Language",
"genre": "Game Genre",
"gameName": "Game Name",
"gameNamePlaceholder": "e.g. Elden Ring",
"channelName": "Channel Name",
"channelNamePlaceholder": "e.g. MyChannel",
"platform": "Platform",
"partNumber": "Part Number",
"partNumberPlaceholder": "e.g. 5",
"bossName": "Boss Name",
"bossNamePlaceholder": "e.g. Margit, The Fell Omen",
"dlcName": "DLC Name",
"dlcNamePlaceholder": "e.g. Shadow of the Erdtree",
"challengeName": "Challenge Name",
"challengeNamePlaceholder": "e.g. No Hit Run",
"resolution": "Resolution",
"fps": "FPS",
"graphicsPreset": "Graphics Preset",
"timestamps": "Timestamps",
"timestampsPlaceholder": "0:00 Intro\n5:30 Chapter 1\n15:00 Boss Fight",
"storeLinks": "Store Links",
"rig": "My Rig",
"social": "Social & Donate Links",
"warnings": "Warnings",
"spoilerWarning": "Spoiler Warning",
"matureWarning": "Mature Content (18+)",
"playlistLink": "Playlist Link",
"playlistLinkPlaceholder": "https://youtube.com/playlist?list=...",
"contactEmail": "Contact Email",
"contactEmailPlaceholder": "business@example.com",
"videoSettings": "Video Settings",
"quickPreview": "Quick Preview"
},
"output": {
"title": "Title",
"description": "Description",
"tags": "Tags",
"copyTitle": "Copy Title",
"copyDescription": "Copy Description",
"copyTags": "Copy Tags",
"copyAll": "Copy All",
"copied": "Copied!",
"charCount": "{{count}}/{{limit}}"
},
"common": {
"save": "Save",
"cancel": "Cancel",
"delete": "Delete",
"confirm": "Confirm",
"export": "Export",
"import": "Import",
"reset": "Reset",
"search": "Search",
"generate": "Generate"
},
"videoTypes": {
"full": "Full Gameplay",
"part": "Gameplay Part",
"boss": "Boss Fight",
"boss_nohit": "Boss No Hit",
"ending": "Ending / All Endings",
"speedrun": "Speedrun",
"100percent": "100% Completion"
},
"genres": {
"action": "Action / Adventure",
"horror": "Horror / Survival",
"rpg": "RPG / JRPG",
"fps": "FPS / Shooter",
"openworld": "Open World / Sandbox",
"indie": "Indie / Platformer",
"soulslike": "Souls-like",
"racing": "Racing / Sports",
"story": "Story / Visual Novel",
"simulation": "Simulation / Strategy"
},
"rig": {
"cpu": "CPU",
"gpu": "GPU",
"ram": "RAM",
"storage": "Storage",
"monitor": "Monitor",
"capture": "Capture Software"
},
"social": {
"kofi": "Ko-fi",
"patreon": "Patreon",
"buymeacoffee": "Buy Me a Coffee",
"paypal": "PayPal",
"github": "GitHub",
"twitter": "Twitter / X",
"discord": "Discord",
"website": "Website"
},
"resolutions": {
"720p": "720p",
"1080p": "1080p",
"1440p": "1440p",
"4K": "4K"
},
"fpsOptions": {
"30": "30 FPS",
"60": "60 FPS",
"120": "120 FPS",
"144": "144 FPS"
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"title": {
"separator": " — ",
"suffix": "Gameplay No Commentary",
"videoType": {
"full": "",
"part": "パート{{partNumber}}",
"boss": "{{bossName}} ボス戦",
"boss_nohit": "{{bossName}} ボス ノーヒット",
"ending": "エンディング",
"speedrun": "スピードラン",
"100percent": "100%クリア"
}
},
"description": {
"intro": {
"full": "この動画は{{channelName}}による{{gameName}}のフルゲームプレイです。",
"part": "この動画は{{channelName}}による{{gameName}}のパート{{partNumber}}です。",
"boss": "この動画は{{channelName}}による{{gameName}}の{{bossName}}ボス戦です。",
"boss_nohit": "この動画は{{channelName}}による{{gameName}}の{{bossName}}ボス戦(ノーヒット)です。",
"ending": "この動画は{{channelName}}による{{gameName}}のエンディングです。",
"speedrun": "この動画は{{channelName}}による{{gameName}}のスピードランです。",
"100percent": "この動画は{{channelName}}による{{gameName}}の100%クリアです。"
},
"noCommentaryLine": "実況なし — 純粋なゲームプレイをお楽しみください。",
"sections": {
"timestamps": "⏱ タイムスタンプ",
"storeLinks": "🎮 ゲームを購入",
"videoSettings": "🖥 動画設定",
"rig": "💻 PC構成",
"spoilerWarning": "⚠️ ネタバレ注意:この動画にはネタバレが含まれている可能性があります。自己責任でご視聴ください!",
"matureWarning": "🔞 成人向けコンテンツ (18+):暴力 / 強い言葉 / グラフィックコンテンツを含みます。",
"donate": "☕ チャンネルを応援",
"social": "🔗 フォローする",
"playlist": "▶️ シリーズ全体を見る:{{link}}",
"contact": "📧 お仕事の依頼:{{email}}",
"cta": "👍 いいね | 🔔 チャンネル登録 | ↗️ シェア"
}
},
"hashtags": {
"gameplay": "#{{gameName}}",
"noCommentary": "#GameplayNoCommentary",
"genre": "#{{genre}}"
}
}
+118
View File
@@ -0,0 +1,118 @@
{
"app": {
"title": "YTDescGen",
"subtitle": "Gameplay No Commentary テンプレートエンジン"
},
"tabs": {
"editor": "エディター",
"output": "出力"
},
"editor": {
"videoType": "動画タイプ",
"language": "出力言語",
"genre": "ゲームジャンル",
"gameName": "ゲーム名",
"gameNamePlaceholder": "例:エルデンリング",
"channelName": "チャンネル名",
"channelNamePlaceholder": "例:MyChannel",
"platform": "プラットフォーム",
"partNumber": "パート番号",
"partNumberPlaceholder": "例:5",
"bossName": "ボス名",
"bossNamePlaceholder": "例:マルギット",
"dlcName": "DLC名",
"dlcNamePlaceholder": "例:Shadow of the Erdtree",
"challengeName": "チャレンジ名",
"challengeNamePlaceholder": "例:ノーヒットラン",
"resolution": "解像度",
"fps": "FPS",
"graphicsPreset": "グラフィック設定",
"timestamps": "タイムスタンプ",
"timestampsPlaceholder": "0:00 イントロ\n5:30 チャプター1\n15:00 ボス戦",
"storeLinks": "購入リンク",
"rig": "PC構成",
"social": "SNS・寄付リンク",
"warnings": "警告",
"spoilerWarning": "ネタバレ警告",
"matureWarning": "成人向けコンテンツ (18+)",
"playlistLink": "プレイリストリンク",
"playlistLinkPlaceholder": "https://youtube.com/playlist?list=...",
"contactEmail": "連絡先メール",
"contactEmailPlaceholder": "business@example.com",
"videoSettings": "動画設定",
"quickPreview": "クイックプレビュー"
},
"output": {
"title": "タイトル",
"description": "説明文",
"tags": "タグ",
"copyTitle": "タイトルをコピー",
"copyDescription": "説明文をコピー",
"copyTags": "タグをコピー",
"copyAll": "全てコピー",
"copied": "コピーしました!",
"charCount": "{{count}}/{{limit}}"
},
"common": {
"save": "保存",
"cancel": "キャンセル",
"delete": "削除",
"confirm": "確認",
"export": "エクスポート",
"import": "インポート",
"reset": "リセット",
"search": "検索",
"generate": "生成"
},
"videoTypes": {
"full": "フルゲームプレイ",
"part": "ゲームプレイ パート",
"boss": "ボス戦",
"boss_nohit": "ボス ノーヒット",
"ending": "エンディング",
"speedrun": "スピードラン",
"100percent": "100%クリア"
},
"genres": {
"action": "アクション / アドベンチャー",
"horror": "ホラー / サバイバル",
"rpg": "RPG / JRPG",
"fps": "FPS / シューター",
"openworld": "オープンワールド / サンドボックス",
"indie": "インディー / プラットフォーマー",
"soulslike": "ソウルライク",
"racing": "レーシング / スポーツ",
"story": "ストーリー / ビジュアルノベル",
"simulation": "シミュレーション / ストラテジー"
},
"rig": {
"cpu": "CPU",
"gpu": "GPU",
"ram": "RAM",
"storage": "ストレージ",
"monitor": "モニター",
"capture": "キャプチャソフト"
},
"social": {
"kofi": "Ko-fi",
"patreon": "Patreon",
"buymeacoffee": "Buy Me a Coffee",
"paypal": "PayPal",
"github": "GitHub",
"twitter": "Twitter / X",
"discord": "Discord",
"website": "ウェブサイト"
},
"resolutions": {
"720p": "720p",
"1080p": "1080p",
"1440p": "1440p",
"4K": "4K"
},
"fpsOptions": {
"30": "30 FPS",
"60": "60 FPS",
"120": "120 FPS",
"144": "144 FPS"
}
}
+45
View File
@@ -0,0 +1,45 @@
{
"title": {
"separator": " — ",
"suffix": "Gameplay No Commentary",
"videoType": {
"full": "",
"part": "Phần {{partNumber}}",
"boss": "{{bossName}} Boss Fight",
"boss_nohit": "{{bossName}} Boss No Hit",
"ending": "Kết thúc",
"speedrun": "Speedrun",
"100percent": "100% Completion"
}
},
"description": {
"intro": {
"full": "Video này là full gameplay của {{gameName}} trên kênh {{channelName}}.",
"part": "Video này là Phần {{partNumber}} của {{gameName}} trên kênh {{channelName}}.",
"boss": "Video này là trận đánh boss {{bossName}} trong {{gameName}} trên kênh {{channelName}}.",
"boss_nohit": "Video này là trận đánh boss {{bossName}} (No Hit) trong {{gameName}} trên kênh {{channelName}}.",
"ending": "Video này là phần kết thúc của {{gameName}} trên kênh {{channelName}}.",
"speedrun": "Video này là speedrun của {{gameName}} trên kênh {{channelName}}.",
"100percent": "Video này là 100% completion của {{gameName}} trên kênh {{channelName}}."
},
"noCommentaryLine": "Không bình luận — gameplay thuần túy để bạn thưởng thức.",
"sections": {
"timestamps": "⏱ MỐC THỜI GIAN",
"storeLinks": "🎮 MUA GAME",
"videoSettings": "🖥 CÀI ĐẶT VIDEO",
"rig": "💻 CẤU HÌNH MÁY",
"spoilerWarning": "⚠️ CẢNH BÁO SPOILER: Video này có thể chứa nội dung spoiler. Xem theo ý muốn của bạn!",
"matureWarning": "🔞 NỘI DUNG NGƯỜI LỚN (18+): Chứa bạo lực / ngôn ngữ mạnh / nội dung nhạy cảm.",
"donate": "☕ ỦNG HỘ KÊNH",
"social": "🔗 THEO DÕI MÌNH",
"playlist": "▶️ Xem toàn bộ series: {{link}}",
"contact": "📧 Liên hệ hợp tác: {{email}}",
"cta": "👍 Like | 🔔 Đăng ký | ↗️ Chia sẻ"
}
},
"hashtags": {
"gameplay": "#{{gameName}}",
"noCommentary": "#GameplayNoCommentary",
"genre": "#{{genre}}"
}
}
+118
View File
@@ -0,0 +1,118 @@
{
"app": {
"title": "YTDescGen",
"subtitle": "Công cụ tạo mô tả Gameplay No Commentary"
},
"tabs": {
"editor": "Chỉnh sửa",
"output": "Kết quả"
},
"editor": {
"videoType": "Loại Video",
"language": "Ngôn ngữ đầu ra",
"genre": "Thể loại Game",
"gameName": "Tên Game",
"gameNamePlaceholder": "VD: Elden Ring",
"channelName": "Tên Kênh",
"channelNamePlaceholder": "VD: MyChannel",
"platform": "Nền tảng",
"partNumber": "Số Phần",
"partNumberPlaceholder": "VD: 5",
"bossName": "Tên Boss",
"bossNamePlaceholder": "VD: Margit, The Fell Omen",
"dlcName": "Tên DLC",
"dlcNamePlaceholder": "VD: Shadow of the Erdtree",
"challengeName": "Tên Challenge",
"challengeNamePlaceholder": "VD: No Hit Run",
"resolution": "Độ phân giải",
"fps": "FPS",
"graphicsPreset": "Cài đặt đồ họa",
"timestamps": "Mốc thời gian",
"timestampsPlaceholder": "0:00 Giới thiệu\n5:30 Chương 1\n15:00 Đánh Boss",
"storeLinks": "Link mua game",
"rig": "Cấu hình máy",
"social": "Mạng xã hội & Donate",
"warnings": "Cảnh báo",
"spoilerWarning": "Cảnh báo Spoiler",
"matureWarning": "Nội dung người lớn (18+)",
"playlistLink": "Link Playlist",
"playlistLinkPlaceholder": "https://youtube.com/playlist?list=...",
"contactEmail": "Email liên hệ",
"contactEmailPlaceholder": "business@example.com",
"videoSettings": "Cài đặt Video",
"quickPreview": "Xem trước nhanh"
},
"output": {
"title": "Tiêu đề",
"description": "Mô tả",
"tags": "Tags",
"copyTitle": "Sao chép tiêu đề",
"copyDescription": "Sao chép mô tả",
"copyTags": "Sao chép tags",
"copyAll": "Sao chép tất cả",
"copied": "Đã sao chép!",
"charCount": "{{count}}/{{limit}}"
},
"common": {
"save": "Lưu",
"cancel": "Hủy",
"delete": "Xóa",
"confirm": "Xác nhận",
"export": "Xuất",
"import": "Nhập",
"reset": "Đặt lại",
"search": "Tìm kiếm",
"generate": "Tạo"
},
"videoTypes": {
"full": "Full Gameplay",
"part": "Gameplay Phần",
"boss": "Boss Fight",
"boss_nohit": "Boss No Hit",
"ending": "Kết thúc",
"speedrun": "Speedrun",
"100percent": "100% Completion"
},
"genres": {
"action": "Hành động / Phiêu lưu",
"horror": "Kinh dị / Sinh tồn",
"rpg": "RPG / JRPG",
"fps": "FPS / Bắn súng",
"openworld": "Thế giới mở / Sandbox",
"indie": "Indie / Platformer",
"soulslike": "Souls-like",
"racing": "Đua xe / Thể thao",
"story": "Cốt truyện / Visual Novel",
"simulation": "Mô phỏng / Chiến thuật"
},
"rig": {
"cpu": "CPU",
"gpu": "GPU",
"ram": "RAM",
"storage": "Ổ cứng",
"monitor": "Màn hình",
"capture": "Phần mềm quay"
},
"social": {
"kofi": "Ko-fi",
"patreon": "Patreon",
"buymeacoffee": "Buy Me a Coffee",
"paypal": "PayPal",
"github": "GitHub",
"twitter": "Twitter / X",
"discord": "Discord",
"website": "Website"
},
"resolutions": {
"720p": "720p",
"1080p": "1080p",
"1440p": "1440p",
"4K": "4K"
},
"fpsOptions": {
"30": "30 FPS",
"60": "60 FPS",
"120": "120 FPS",
"144": "144 FPS"
}
}
+13
View File
@@ -0,0 +1,13 @@
import { StrictMode } from "react";
import { createRoot } from "react-dom/client";
import App from "./App";
import "./styles/globals.css";
const root = document.getElementById("root");
if (!root) throw new Error("Root element not found");
createRoot(root).render(
<StrictMode>
<App />
</StrictMode>,
);
+61
View File
@@ -0,0 +1,61 @@
import { VideoTypeSelector } from "@components/editor/VideoTypeSelector";
import { LanguageSelector } from "@components/editor/LanguageSelector";
import { GenreSelector } from "@components/editor/GenreSelector";
import { GameInfoForm } from "@components/editor/GameInfoForm";
import { VideoSettingsForm } from "@components/editor/VideoSettingsForm";
import { TimestampEditor } from "@components/editor/TimestampEditor";
import { StoreLinkEditor } from "@components/editor/StoreLinkEditor";
import { RigEditor } from "@components/editor/RigEditor";
import { SocialEditor } from "@components/editor/SocialEditor";
import { WarningToggles } from "@components/editor/WarningToggles";
import { QuickPreview } from "@components/editor/QuickPreview";
import { Input } from "@components/ui/Input";
import { useEditorStore } from "@store/editor-store";
import { useTranslation } from "react-i18next";
export function EditorPage() {
const { t } = useTranslation("ui");
const store = useEditorStore();
return (
<div className="mx-auto flex max-w-6xl gap-6 p-6">
{/* Form */}
<div className="flex flex-1 flex-col gap-6">
<VideoTypeSelector />
<div className="grid grid-cols-2 gap-4">
<LanguageSelector />
<div />
</div>
<GenreSelector />
<GameInfoForm />
<VideoSettingsForm />
<TimestampEditor />
<Input
label={t("editor.playlistLink")}
placeholder={t("editor.playlistLinkPlaceholder")}
value={store.playlistLink ?? ""}
onChange={(e) => store.set("playlistLink", e.target.value)}
/>
<Input
label={t("editor.contactEmail")}
placeholder={t("editor.contactEmailPlaceholder")}
value={store.contactEmail ?? ""}
onChange={(e) => store.set("contactEmail", e.target.value)}
/>
<WarningToggles />
<StoreLinkEditor />
<RigEditor />
<SocialEditor />
</div>
{/* Sidebar: Quick Preview */}
<div className="w-80 shrink-0">
<div className="sticky top-6">
<QuickPreview />
</div>
</div>
</div>
);
}
+13
View File
@@ -0,0 +1,13 @@
import { OutputPreview } from "@components/output/OutputPreview";
import { CopyAllBar } from "@components/output/CopyAllBar";
export function OutputPage() {
return (
<div className="flex flex-1 flex-col">
<div className="mx-auto w-full max-w-4xl flex-1 p-6">
<OutputPreview />
</div>
<CopyAllBar />
</div>
);
}
+104
View File
@@ -0,0 +1,104 @@
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import type { VideoType, Genre, SupportedLanguage } from "@engine/types";
import { DEFAULTS } from "@config/defaults";
interface EditorData {
videoType: VideoType;
language: SupportedLanguage;
genre: Genre;
gameName: string;
gameNameLocalized: Record<string, string>;
channelName: string;
platform: string;
partNumber: string;
bossName: string;
dlcName: string;
challengeName: string;
resolution: string;
fps: string;
graphicsPreset: string;
timestamps: string;
playlistLink: string;
contactEmail: string;
spoilerWarning: boolean;
matureWarning: boolean;
storeLinks: Record<string, string>;
social: Record<string, string>;
rig: Record<string, string>;
}
interface EditorActions {
set: <K extends keyof EditorData>(key: K, value: EditorData[K]) => void;
setNested: <G extends "storeLinks" | "social" | "rig">(
group: G,
key: string,
value: string,
) => void;
loadProfile: (profile: Partial<EditorData>) => void;
loadPreset: (preset: Partial<EditorData>) => void;
reset: () => void;
}
type EditorState = EditorData & EditorActions;
const initialState: EditorData = {
videoType: DEFAULTS.editor.videoType as VideoType,
language: DEFAULTS.editor.language as SupportedLanguage,
genre: DEFAULTS.editor.genre as Genre,
gameName: DEFAULTS.editor.gameName,
gameNameLocalized: { ...DEFAULTS.editor.gameNameLocalized },
channelName: DEFAULTS.editor.channelName,
platform: DEFAULTS.editor.platform,
partNumber: DEFAULTS.editor.partNumber,
bossName: DEFAULTS.editor.bossName,
dlcName: DEFAULTS.editor.dlcName,
challengeName: DEFAULTS.editor.challengeName,
resolution: DEFAULTS.editor.resolution,
fps: DEFAULTS.editor.fps,
graphicsPreset: DEFAULTS.editor.graphicsPreset,
timestamps: DEFAULTS.editor.timestamps,
playlistLink: DEFAULTS.editor.playlistLink,
contactEmail: DEFAULTS.editor.contactEmail,
spoilerWarning: DEFAULTS.editor.spoilerWarning,
matureWarning: DEFAULTS.editor.matureWarning,
storeLinks: { ...DEFAULTS.editor.storeLinks },
social: { ...DEFAULTS.editor.social },
rig: { ...DEFAULTS.editor.rig },
};
export const useEditorStore = create<EditorState>()(
persist(
(set) => ({
...initialState,
set: (key, value) => set({ [key]: value }),
setNested: (group, key, value) =>
set((state) => ({
[group]: { ...state[group], [key]: value },
})),
loadProfile: (profile) => set((state) => ({ ...state, ...profile })),
loadPreset: (preset) => set((state) => ({ ...state, ...preset })),
reset: () => set(initialState),
}),
{
name: "ytdescgen-editor-draft",
storage: createJSONStorage(() => localStorage),
partialize: (state) => {
const {
set: _s,
setNested: _sn,
loadProfile: _lp,
loadPreset: _lpre,
reset: _r,
...data
} = state;
return data;
},
},
),
);
+44
View File
@@ -0,0 +1,44 @@
import { create } from "zustand";
import { persist, createJSONStorage } from "zustand/middleware";
import { DEFAULTS } from "@config/defaults";
import type { GenreId } from "@config/genres";
interface SettingsState {
theme: "dark" | "light";
defaultLanguage: string;
defaultGenre: GenreId;
setTheme: (theme: "dark" | "light") => void;
setDefaultLanguage: (lang: string) => void;
setDefaultGenre: (genre: GenreId) => void;
}
export const useSettingsStore = create<SettingsState>()(
persist(
(set) => ({
...DEFAULTS.settings,
setTheme: (theme) => {
document.documentElement.classList.toggle("dark", theme === "dark");
document.documentElement.classList.toggle("light", theme === "light");
set({ theme });
},
setDefaultLanguage: (lang) => set({ defaultLanguage: lang }),
setDefaultGenre: (genre) => set({ defaultGenre: genre }),
}),
{
name: "ytdescgen-settings",
storage: createJSONStorage(() => localStorage),
partialize: (state) => {
const {
setTheme: _st,
setDefaultLanguage: _sdl,
setDefaultGenre: _sdg,
...data
} = state;
return data;
},
},
),
);
+74
View File
@@ -0,0 +1,74 @@
@tailwind base;
@tailwind components;
@tailwind utilities;
:root {
/* Dark theme (default) */
--surface-0: #0a0a0b;
--surface-1: #141416;
--surface-2: #1e1e22;
--surface-3: #28282e;
--border: #2a2a30;
--border-strong: #3a3a42;
--text-primary: #e8e8ed;
--text-secondary: #a0a0ab;
--text-muted: #6b6b76;
--accent: #6366f1;
--accent-hover: #818cf8;
--accent-muted: rgba(99, 102, 241, 0.15);
--success: #22c55e;
--warning: #eab308;
--danger: #ef4444;
--font-sans: "Inter", ui-sans-serif, system-ui, -apple-system, sans-serif;
--font-mono: "JetBrains Mono", ui-monospace, "Cascadia Code", monospace;
}
.light {
--surface-0: #ffffff;
--surface-1: #f8f8fa;
--surface-2: #f0f0f4;
--surface-3: #e8e8ed;
--border: #d4d4db;
--border-strong: #b0b0bb;
--text-primary: #1a1a1f;
--text-secondary: #4a4a55;
--text-muted: #8a8a96;
--accent: #4f46e5;
--accent-hover: #6366f1;
--accent-muted: rgba(79, 70, 229, 0.1);
--success: #16a34a;
--warning: #ca8a04;
--danger: #dc2626;
}
body {
@apply bg-surface-0 font-sans text-text-primary;
margin: 0;
min-height: 100vh;
}
/* Scrollbar styling */
::-webkit-scrollbar {
width: 8px;
}
::-webkit-scrollbar-track {
@apply bg-surface-0;
}
::-webkit-scrollbar-thumb {
@apply rounded-full bg-surface-3;
}
::-webkit-scrollbar-thumb:hover {
@apply bg-border-strong;
}
+1
View File
@@ -0,0 +1 @@
/// <reference types="vite/client" />
+40
View File
@@ -0,0 +1,40 @@
import type { Config } from "tailwindcss";
export default {
content: ["./index.html", "./src/**/*.{ts,tsx}"],
darkMode: "class",
theme: {
extend: {
colors: {
surface: {
0: "var(--surface-0)",
1: "var(--surface-1)",
2: "var(--surface-2)",
3: "var(--surface-3)",
},
border: {
DEFAULT: "var(--border)",
strong: "var(--border-strong)",
},
text: {
primary: "var(--text-primary)",
secondary: "var(--text-secondary)",
muted: "var(--text-muted)",
},
accent: {
DEFAULT: "var(--accent)",
hover: "var(--accent-hover)",
muted: "var(--accent-muted)",
},
success: "var(--success)",
warning: "var(--warning)",
danger: "var(--danger)",
},
fontFamily: {
sans: ["var(--font-sans)"],
mono: ["var(--font-mono)"],
},
},
},
plugins: [],
} satisfies Config;
+154
View File
@@ -0,0 +1,154 @@
import { describe, it, expect } from "vitest";
import { buildDescription, checkDescriptionWarning } from "@engine/description-builder";
import { createMockT } from "../helpers/mock-t";
import type { GeneratorInput } from "@engine/types";
function makeInput(overrides: Partial<GeneratorInput> = {}): GeneratorInput {
return {
videoType: "full",
language: "en",
genre: "action",
gameName: "Elden Ring",
channelName: "TestChannel",
platform: "steam",
spoilerWarning: false,
matureWarning: false,
storeLinks: {},
social: {},
rig: {},
...overrides,
};
}
describe("buildDescription", () => {
it("generates minimal description with only required fields", () => {
const t = createMockT("en");
const result = buildDescription(makeInput(), t);
expect(result).toContain("full gameplay of Elden Ring on TestChannel");
expect(result).toContain("No Commentary");
expect(result).toContain("Like | 🔔 Subscribe");
expect(result).toContain("#EldenRing");
});
it("includes timestamps when provided", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({ timestamps: "0:00 Intro\n5:30 Boss" }),
t,
);
expect(result).toContain("TIMESTAMPS");
expect(result).toContain("0:00 Intro");
expect(result).toContain("5:30 Boss");
});
it("includes store links when provided", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({ storeLinks: { Steam: "https://store.steampowered.com/app/123" } }),
t,
);
expect(result).toContain("GET THE GAME");
expect(result).toContain("Steam: https://store.steampowered.com/app/123");
});
it("includes video settings", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({ resolution: "4K", fps: "60", graphicsPreset: "Ultra" }),
t,
);
expect(result).toContain("VIDEO SETTINGS");
expect(result).toContain("4K | 60 FPS | Ultra");
});
it("includes rig info when provided", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({ rig: { CPU: "i9-14900K", GPU: "RTX 4090" } }),
t,
);
expect(result).toContain("MY RIG");
expect(result).toContain("CPU: i9-14900K");
expect(result).toContain("GPU: RTX 4090");
});
it("includes spoiler warning when enabled", () => {
const t = createMockT("en");
const result = buildDescription(makeInput({ spoilerWarning: true }), t);
expect(result).toContain("SPOILER WARNING");
});
it("includes mature warning when enabled", () => {
const t = createMockT("en");
const result = buildDescription(makeInput({ matureWarning: true }), t);
expect(result).toContain("MATURE CONTENT");
});
it("includes social links when provided", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({ social: { twitter: "https://x.com/test", discord: "https://discord.gg/test" } }),
t,
);
expect(result).toContain("FOLLOW ME");
expect(result).toContain("twitter: https://x.com/test");
});
it("includes playlist link when provided", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({ playlistLink: "https://youtube.com/playlist?list=abc" }),
t,
);
expect(result).toContain("Watch the full series: https://youtube.com/playlist?list=abc");
});
it("includes contact email when provided", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({ contactEmail: "test@example.com" }),
t,
);
expect(result).toContain("Business inquiries: test@example.com");
});
it("generates part description correctly", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({ videoType: "part", partNumber: "5" }),
t,
);
expect(result).toContain("Part 5 of Elden Ring");
});
it("generates boss description correctly", () => {
const t = createMockT("en");
const result = buildDescription(
makeInput({ videoType: "boss", bossName: "Margit" }),
t,
);
expect(result).toContain("Margit boss fight");
});
it("generates description in Vietnamese", () => {
const t = createMockT("vi");
const result = buildDescription(makeInput({ language: "vi" }), t);
expect(result).toContain("full gameplay của Elden Ring");
expect(result).toContain("Không bình luận");
});
});
describe("checkDescriptionWarning", () => {
it("returns null for description under limit", () => {
expect(checkDescriptionWarning("Short description")).toBeNull();
});
it("returns warning for description exceeding 5000 chars", () => {
const longDesc = "A".repeat(5001);
const warning = checkDescriptionWarning(longDesc);
expect(warning).not.toBeNull();
expect(warning!.field).toBe("description");
expect(warning!.limit).toBe(5000);
});
});
+105
View File
@@ -0,0 +1,105 @@
import { describe, it, expect } from "vitest";
import { generateTags, formatTagString } from "@engine/tag-generator";
import type { GeneratorInput } from "@engine/types";
function makeInput(overrides: Partial<GeneratorInput> = {}): GeneratorInput {
return {
videoType: "full",
language: "en",
genre: "action",
gameName: "Elden Ring",
channelName: "TestChannel",
platform: "steam",
spoilerWarning: false,
matureWarning: false,
storeLinks: {},
social: {},
rig: {},
...overrides,
};
}
describe("generateTags", () => {
it("includes core tags", () => {
const tags = generateTags(makeInput());
expect(tags).toContain("Elden Ring gameplay");
expect(tags).toContain("Elden Ring no commentary");
expect(tags).toContain("gameplay no commentary");
});
it("includes genre-specific tags for action", () => {
const tags = generateTags(makeInput({ genre: "action" }));
expect(tags.some((t) => t.toLowerCase().includes("action"))).toBe(true);
});
it("includes genre-specific tags for horror", () => {
const tags = generateTags(makeInput({ genre: "horror" }));
expect(tags.some((t) => t.toLowerCase().includes("horror"))).toBe(true);
});
it("includes genre-specific tags for rpg", () => {
const tags = generateTags(makeInput({ genre: "rpg" }));
expect(tags.some((t) => t.toLowerCase().includes("rpg"))).toBe(true);
});
it("includes video type tags for boss", () => {
const tags = generateTags(makeInput({ videoType: "boss" }));
expect(tags.some((t) => t.toLowerCase().includes("boss"))).toBe(true);
});
it("includes video type tags for speedrun", () => {
const tags = generateTags(makeInput({ videoType: "speedrun" }));
expect(tags.some((t) => t.toLowerCase().includes("speedrun"))).toBe(true);
});
it("includes multilingual tags (Japanese)", () => {
const tags = generateTags(makeInput());
expect(tags.some((t) => t.includes("ゲームプレイ"))).toBe(true);
});
it("includes multilingual tags (Vietnamese)", () => {
const tags = generateTags(makeInput());
expect(tags.some((t) => t.includes("không bình luận"))).toBe(true);
});
it("has no duplicate tags (case-insensitive)", () => {
const tags = generateTags(makeInput());
const lowerTags = tags.map((t) => t.toLowerCase());
const unique = new Set(lowerTags);
expect(lowerTags.length).toBe(unique.size);
});
it("does not exceed 500 character limit for tag string", () => {
const tags = generateTags(makeInput());
const tagString = formatTagString(tags);
expect(tagString.length).toBeLessThanOrEqual(500);
});
it("each tag does not exceed 30 characters", () => {
const tags = generateTags(makeInput());
for (const tag of tags) {
expect(tag.length).toBeLessThanOrEqual(30);
}
});
it("includes trending tags with current year", () => {
const tags = generateTags(makeInput());
const year = new Date().getFullYear().toString();
expect(tags.some((t) => t.includes(year))).toBe(true);
});
it("includes platform tags", () => {
const tags = generateTags(makeInput({ platform: "steam" }));
expect(tags.some((t) => t.toLowerCase().includes("steam"))).toBe(true);
});
});
describe("formatTagString", () => {
it("joins tags with comma and space", () => {
expect(formatTagString(["a", "b", "c"])).toBe("a, b, c");
});
it("returns empty string for empty array", () => {
expect(formatTagString([])).toBe("");
});
});
+118
View File
@@ -0,0 +1,118 @@
import { describe, it, expect } from "vitest";
import { buildTitle, checkTitleWarning } from "@engine/title-builder";
import { createMockT } from "../helpers/mock-t";
import type { GeneratorInput } from "@engine/types";
function makeInput(overrides: Partial<GeneratorInput> = {}): GeneratorInput {
return {
videoType: "full",
language: "en",
genre: "action",
gameName: "Elden Ring",
channelName: "TestChannel",
platform: "steam",
spoilerWarning: false,
matureWarning: false,
storeLinks: {},
social: {},
rig: {},
...overrides,
};
}
describe("buildTitle", () => {
it("generates full gameplay title in English", () => {
const t = createMockT("en");
const result = buildTitle(makeInput(), t);
expect(result).toBe("Elden Ring — Gameplay No Commentary");
});
it("generates part title with number", () => {
const t = createMockT("en");
const result = buildTitle(makeInput({ videoType: "part", partNumber: "5" }), t);
expect(result).toBe("Elden Ring — Part 5 — Gameplay No Commentary");
});
it("generates boss title with boss name", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({ videoType: "boss", bossName: "Margit" }),
t,
);
expect(result).toBe("Elden Ring — Margit Boss Fight — Gameplay No Commentary");
});
it("generates boss no hit title", () => {
const t = createMockT("en");
const result = buildTitle(
makeInput({ videoType: "boss_nohit", bossName: "Margit" }),
t,
);
expect(result).toBe("Elden Ring — Margit Boss No Hit — Gameplay No Commentary");
});
it("generates ending title", () => {
const t = createMockT("en");
const result = buildTitle(makeInput({ videoType: "ending" }), t);
expect(result).toBe("Elden Ring — Ending — Gameplay No Commentary");
});
it("generates speedrun title", () => {
const t = createMockT("en");
const result = buildTitle(makeInput({ videoType: "speedrun" }), t);
expect(result).toBe("Elden Ring — Speedrun — Gameplay No Commentary");
});
it("generates 100% title", () => {
const t = createMockT("en");
const result = buildTitle(makeInput({ videoType: "100percent" }), t);
expect(result).toBe("Elden Ring — 100% Completion — Gameplay No Commentary");
});
it("generates boss title in Japanese", () => {
const t = createMockT("ja");
const input = makeInput({
videoType: "boss",
bossName: "マルギット",
gameName: "エルデンリング",
language: "ja",
});
const result = buildTitle(input, t);
expect(result).toBe("エルデンリング — マルギット ボス戦 — Gameplay No Commentary");
});
it("generates part title in Vietnamese", () => {
const t = createMockT("vi");
const result = buildTitle(
makeInput({ videoType: "part", partNumber: "3", language: "vi" }),
t,
);
expect(result).toBe("Elden Ring — Phần 3 — Gameplay No Commentary");
});
it("uses localized game name when available", () => {
const t = createMockT("ja");
const input = makeInput({
language: "ja",
gameName: "Elden Ring",
gameNameLocalized: { ja: "エルデンリング" },
});
const result = buildTitle(input, t);
expect(result).toBe("エルデンリング — Gameplay No Commentary");
});
});
describe("checkTitleWarning", () => {
it("returns null for title under limit", () => {
expect(checkTitleWarning("Short title")).toBeNull();
});
it("returns warning for title exceeding 100 chars", () => {
const longTitle = "A".repeat(101);
const warning = checkTitleWarning(longTitle);
expect(warning).not.toBeNull();
expect(warning!.field).toBe("title");
expect(warning!.current).toBe(101);
expect(warning!.limit).toBe(100);
});
});
+40
View File
@@ -0,0 +1,40 @@
import enTemplates from "../../src/i18n/locales/en/templates.json";
import viTemplates from "../../src/i18n/locales/vi/templates.json";
import jaTemplates from "../../src/i18n/locales/ja/templates.json";
import type { TranslationFn } from "../../src/engine/types";
type NestedRecord = Record<string, unknown>;
const templatesByLang: Record<string, NestedRecord> = {
en: enTemplates,
vi: viTemplates,
ja: jaTemplates,
};
function getNestedValue(obj: NestedRecord, path: string): unknown {
const keys = path.split(".");
let current: unknown = obj;
for (const key of keys) {
if (current === null || current === undefined || typeof current !== "object") {
return undefined;
}
current = (current as NestedRecord)[key];
}
return current;
}
function interpolate(template: string, vars: Record<string, string>): string {
return template.replace(/\{\{(\w+)\}\}/g, (_, key: string) => vars[key] ?? "");
}
export function createMockT(lang = "en"): TranslationFn {
const templates = templatesByLang[lang] ?? templatesByLang["en"]!;
return (key: string, options?: Record<string, string>): string => {
const value = getNestedValue(templates, key);
if (typeof value !== "string") {
return key;
}
return options ? interpolate(value, options) : value;
};
}
+34
View File
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2020",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "react-jsx",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedIndexedAccess": true,
"forceConsistentCasingInFileNames": true,
"resolveJsonModule": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"@config/*": ["./src/config/*"],
"@engine/*": ["./src/engine/*"],
"@store/*": ["./src/store/*"],
"@hooks/*": ["./src/hooks/*"],
"@components/*": ["./src/components/*"],
"@pages/*": ["./src/pages/*"],
"@utils/*": ["./src/utils/*"],
"@i18n/*": ["./src/i18n/*"]
}
},
"include": ["src"]
}
+32
View File
@@ -0,0 +1,32 @@
import { defineConfig } from "vite";
import react from "@vitejs/plugin-react";
import path from "path";
export default defineConfig({
plugins: [react()],
base: "/yt-desc-gen/",
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"@config": path.resolve(__dirname, "./src/config"),
"@engine": path.resolve(__dirname, "./src/engine"),
"@store": path.resolve(__dirname, "./src/store"),
"@hooks": path.resolve(__dirname, "./src/hooks"),
"@components": path.resolve(__dirname, "./src/components"),
"@pages": path.resolve(__dirname, "./src/pages"),
"@utils": path.resolve(__dirname, "./src/utils"),
"@i18n": path.resolve(__dirname, "./src/i18n"),
},
},
build: {
rollupOptions: {
output: {
manualChunks: {
react: ["react", "react-dom"],
router: ["react-router-dom"],
i18n: ["i18next", "react-i18next"],
},
},
},
},
});
+22
View File
@@ -0,0 +1,22 @@
import { defineConfig } from "vitest/config";
import path from "path";
export default defineConfig({
resolve: {
alias: {
"@": path.resolve(__dirname, "./src"),
"@config": path.resolve(__dirname, "./src/config"),
"@engine": path.resolve(__dirname, "./src/engine"),
"@store": path.resolve(__dirname, "./src/store"),
"@hooks": path.resolve(__dirname, "./src/hooks"),
"@components": path.resolve(__dirname, "./src/components"),
"@pages": path.resolve(__dirname, "./src/pages"),
"@utils": path.resolve(__dirname, "./src/utils"),
"@i18n": path.resolve(__dirname, "./src/i18n"),
},
},
test: {
globals: true,
include: ["tests/**/*.test.ts", "src/**/*.test.ts"],
},
});