Skip to content

Create polished demo videos without editing skills. Mac/Windows/Linux

feat: ui overhaul — Phosphor icons, redesigned launcher, editor layout, and component refresh

webadderalla84b83f91b86
diff --git a/.eslintrc.cjs b/.eslintrc.cjs
index dc6ce092..f63fe7dc 100644
--- a/.eslintrc.cjs
+++ b/.eslintrc.cjs
@@ -1,19 +1,15 @@
-module.exports = {
- root: true,
- env: { browser: true, es2020: true },
- extends: [
- 'eslint:recommended',
- 'plugin:@typescript-eslint/recommended',
- 'plugin:react-hooks/recommended',
- ],
- ignorePatterns: ['dist', '.eslintrc.cjs'],
- parser: '@typescript-eslint/parser',
- plugins: ['react-refresh'],
- rules: {
- 'react-refresh/only-export-components': [
- 'warn',
- { allowConstantExport: true },
- ],
- },
-}
-
+module.exports = {
+ root: true,
+ env: { browser: true, es2020: true },
+ extends: [
+ "eslint:recommended",
+ "plugin:@typescript-eslint/recommended",
+ "plugin:react-hooks/recommended",
+ ],
+ ignorePatterns: ["dist", ".eslintrc.cjs"],
+ parser: "@typescript-eslint/parser",
+ plugins: ["react-refresh"],
+ rules: {
+ "react-refresh/only-export-components": ["warn", { allowConstantExport: true }],
+ },
+};
diff --git a/README.md b/README.md
index 1c4ec204..f9ae83d9 100644
--- a/README.md
+++ b/README.md
@@ -26,7 +26,7 @@ Recordly is a desktop app for recording and editing screen captures with motion-
Recordly runs on:
-- **macOS** 13.0+
+- **macOS** 14.0+
- **Windows** 10 Build 19041+
- **Linux** on modern distros
@@ -61,6 +61,12 @@ Use drag-and-drop timeline tools for zooms, trims, speed regions, annotations, e
<img src="./feature3.png" width="450" alt="Recordly timeline editor screenshot">
</p>
+## Extensions & Marketplace
+
+Recordly has a community-driven extension system. Anyone can build and publish extensions that add new capabilities to Recordly — cursor click sounds, device frames, browser mockups, wallpapers, render hooks, settings panels, and more.
+
+Browse and install community extensions from the [Recordly Marketplace](https://marketplace.recordly.dev/extensions).
+
---
## All Features
@@ -233,7 +239,7 @@ xattr -rd com.apple.quarantine /Applications/Recordly.app
| Platform | Minimum version | Notes |
|---|---|---|
-| **macOS** | macOS 13.0 (Ventura) | Required for ScreenCaptureKit audio capture. |
+| **macOS** | macOS 14.0 (Sonoma) | Required for ScreenCaptureKit audio and microphone capture. |
| **Windows** | Windows 10 20H1 (Build 19041, May 2020) | Required for the native Windows Graphics Capture (WGC) helper and best cursor-hiding behavior. |
| **Linux** | Any modern distro | Recording works through Electron capture. System audio generally requires PipeWire. |
@@ -304,7 +310,7 @@ System audio support varies by platform.
- Usually requires PipeWire
**macOS**
-- Requires macOS 13.0+ and the ScreenCaptureKit-based workflow
+- Requires macOS 14.0+ and the ScreenCaptureKit-based workflow
---
@@ -382,14 +388,6 @@ Recordly is licensed under the **AGPL 3.0**.
---
-## Extensions
-
-Recordly has an extension system for adding device frames, click effects, render hooks, sounds, and settings panels. Built-in extensions ship under `public/builtin-extensions/`.
-
-See [EXTENSIONS.md](./EXTENSIONS.md) for the full API reference and examples.
-
----
-
# Credits
## Acknowledgements
diff --git a/README.zh-CN.md b/README.zh-CN.md
index b3e04f24..28b3f59b 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -26,7 +26,7 @@ Recordly 是一款桌面应用,用于录制并编辑屏幕内容,内置面
Recordly 运行于:
-- **macOS** 13.0+
+- **macOS** 14.0+
- **Windows** 10 Build 19041+
- **Linux** 现代发行版
@@ -61,6 +61,12 @@ Recordly 可以根据操作自动强调重点区域,平滑光标运动,添
<img src="./feature3.png" width="450" alt="Recordly timeline editor screenshot">
</p>
+## 扩展与市场
+
+Recordly 拥有一个社区驱动的扩展系统。任何人都可以构建和发布扩展来为 Recordly 添加新功能——光标点击音效、设备边框、浏览器模拟外壳、壁纸、渲染钩子、设置面板等等。
+
+浏览并安装社区扩展:[Recordly 扩展市场](https://marketplace.recordly.dev/extensions)。
+
---
## 全部功能
@@ -234,8 +240,8 @@ xattr -rd com.apple.quarantine /Applications/Recordly.app
| 平台 | 最低版本 | 说明 |
|---|---|---|
-| **macOS** | macOS 13.0 (Ventura) | 使用 ScreenCaptureKit 音频捕获所必需。 |
-| **Windows** | Windows 10 20H1(Build 19041,2020 年 5 月) | 原生 Windows Graphics Capture(WGC)辅助程序以及最佳光标隐藏行为所必需。 |
+| **macOS** | macOS 14.0 (Sonoma) | 使用 ScreenCaptureKit 捕获音频和麦克风所必需。 |
+| **Windows** | Windows 10 20H1(Build 19041,2020 年 5 月) | 原生 Windows Graphics Capture(WGC)辅助程序及最佳光标隐藏行为所必需。 |
| **Linux** | 任意现代发行版 | 通过 Electron 捕获录制。系统音频通常需要 PipeWire。 |
> [!IMPORTANT]
@@ -305,7 +311,7 @@ Recordly 会在录制画面上渲染一个经过美化的光标叠加层,但
- 通常需要 PipeWire
**macOS**
-- 需要 macOS 13.0+ 以及基于 ScreenCaptureKit 的工作流
+- 需要 macOS 14.0+ 和基于 ScreenCaptureKit 的工作流
---
diff --git a/biome.json b/biome.json
index 98c88e9a..798cd272 100644
--- a/biome.json
+++ b/biome.json
@@ -44,7 +44,7 @@
"noUnsafeOptionalChaining": "error",
"noUnusedLabels": "error",
"noUnusedVariables": "error",
- "useExhaustiveDependencies": "warn",
+ "useExhaustiveDependencies": "off",
"useHookAtTopLevel": "error",
"useIsNan": "error",
"useValidForDirection": "error",
@@ -55,7 +55,7 @@
"noNamespace": "error",
"useArrayLiterals": "error",
"useAsConstAssertion": "error",
- "useComponentExportOnlyModules": "warn"
+ "useComponentExportOnlyModules": "off"
},
"suspicious": {
"noAssignInExpressions": "error",
@@ -96,6 +96,7 @@
"includes": ["**", "**/dist", "**/.eslintrc.cjs", "**", "**/dist", "**/.eslintrc.cjs"]
},
"javascript": { "formatter": { "quoteStyle": "double" } },
+ "css": { "parser": { "tailwindDirectives": true } },
"overrides": [
{
"includes": ["*.ts", "*.tsx", "*.mts", "*.cts"],
@@ -156,6 +157,31 @@
}
}
}
+ },
+ {
+ "includes": ["src/components/ui/**/*.tsx"],
+ "linter": {
+ "rules": {
+ "style": {
+ "useComponentExportOnlyModules": "off"
+ }
+ }
+ }
+ },
+ {
+ "includes": ["**/*.test.ts", "**/*.test.tsx"],
+ "linter": {
+ "rules": {
+ "correctness": {
+ "noEmptyPattern": "off",
+ "noUnusedVariables": "off"
+ },
+ "suspicious": {
+ "noEmptyBlockStatements": "off",
+ "noExplicitAny": "off"
+ }
+ }
+ }
}
],
"assist": {
diff --git a/package-lock.json b/package-lock.json
index 46d2bfe7..8367a4c0 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -9,6 +9,7 @@
"version": "1.1.23",
"hasInstallScript": true,
"dependencies": {
+ "@phosphor-icons/react": "^2.1.10",
"capturekit": "^1.0.13",
"electron-updater": "^6.8.3",
"ffmpeg-static": "^5.3.0",
@@ -2843,6 +2844,19 @@
"node": "^12.13.0 || ^14.15.0 || >=16.0.0"
}
},
+ "node_modules/@phosphor-icons/react": {
+ "version": "2.1.10",
+ "resolved": "https://registry.npmjs.org/@phosphor-icons/react/-/react-2.1.10.tgz",
+ "integrity": "sha512-vt8Tvq8GLjheAZZYa+YG/pW7HDbov8El/MANW8pOAz4eGxrwhnbfrQZq0Cp4q8zBEu8NIhHdnr+r8thnfRSNYA==",
+ "license": "MIT",
+ "engines": {
+ "node": ">=10"
+ },
+ "peerDependencies": {
+ "react": ">= 16.8",
+ "react-dom": ">= 16.8"
+ }
+ },
"node_modules/@pixi/color": {
"version": "7.4.3",
"resolved": "https://registry.npmjs.org/@pixi/color/-/color-7.4.3.tgz",
@@ -9046,7 +9060,6 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
- "dev": true,
"license": "MIT"
},
"node_modules/js-yaml": {
@@ -9361,7 +9374,6 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
- "dev": true,
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
@@ -11227,7 +11239,6 @@
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
@@ -11240,7 +11251,6 @@
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
- "dev": true,
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
@@ -11948,7 +11958,6 @@
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
- "dev": true,
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
diff --git a/package.json b/package.json
index 68af12b7..d9e99cb9 100644
--- a/package.json
+++ b/package.json
@@ -37,6 +37,7 @@
"test:watch": "vitest"
},
"dependencies": {
+ "@phosphor-icons/react": "^2.1.10",
"capturekit": "^1.0.13",
"electron-updater": "^6.8.3",
"ffmpeg-static": "^5.3.0",
diff --git a/postcss.config.cjs b/postcss.config.cjs
index 33ad091d..e873f1a4 100644
--- a/postcss.config.cjs
+++ b/postcss.config.cjs
@@ -1,6 +1,6 @@
module.exports = {
- plugins: {
- tailwindcss: {},
- autoprefixer: {},
- },
-}
+ plugins: {
+ tailwindcss: {},
+ autoprefixer: {},
+ },
+};
diff --git a/scripts/benchmark-export-queues.mjs b/scripts/benchmark-export-queues.mjs
index db6902c0..3028ab12 100644
--- a/scripts/benchmark-export-queues.mjs
+++ b/scripts/benchmark-export-queues.mjs
@@ -17,8 +17,14 @@ const rendererEntry = path.join(repoRoot, "dist", "index.html");
const width = parseEvenInteger(process.env.RECORDLY_BENCH_EXPORT_WIDTH ?? "1280", "Width");
const height = parseEvenInteger(process.env.RECORDLY_BENCH_EXPORT_HEIGHT ?? "720", "Height");
const frameRate = parsePositiveInteger(process.env.RECORDLY_BENCH_EXPORT_FPS ?? "60", "Frame rate");
-const durationSeconds = parsePositiveInteger(process.env.RECORDLY_BENCH_EXPORT_DURATION ?? "15", "Duration");
-const timeoutMs = parsePositiveInteger(process.env.RECORDLY_BENCH_EXPORT_TIMEOUT_MS ?? "180000", "Timeout");
+const durationSeconds = parsePositiveInteger(
+ process.env.RECORDLY_BENCH_EXPORT_DURATION ?? "15",
+ "Duration",
+);
+const timeoutMs = parsePositiveInteger(
+ process.env.RECORDLY_BENCH_EXPORT_TIMEOUT_MS ?? "180000",
+ "Timeout",
+);
const runsPerVariant = parsePositiveInteger(process.env.RECORDLY_BENCH_EXPORT_RUNS ?? "2", "Runs");
const useNativeExport = process.env.RECORDLY_BENCH_EXPORT_USE_NATIVE === "1";
const useWebcamOverlay = process.env.RECORDLY_BENCH_EXPORT_ENABLE_WEBCAM === "1";
@@ -39,9 +45,7 @@ const webcamHeight = parseEvenInteger(
const webcamShadowIntensity = parseExportShadowIntensity(
process.env.RECORDLY_BENCH_EXPORT_WEBCAM_SHADOW ?? null,
);
-const webcamSize = parseExportWebcamSize(
- process.env.RECORDLY_BENCH_EXPORT_WEBCAM_SIZE ?? null,
-);
+const webcamSize = parseExportWebcamSize(process.env.RECORDLY_BENCH_EXPORT_WEBCAM_SIZE ?? null);
const MODERN_BACKEND_SWEEP = ["auto", "webcodecs", "breeze"];
const exportPipeline = parseExportPipeline(process.env.RECORDLY_BENCH_EXPORT_PIPELINE ?? null);
const exportBackend = parseExportBackend(process.env.RECORDLY_BENCH_EXPORT_BACKEND ?? null);
@@ -106,9 +110,7 @@ function parseExportBackend(rawValue) {
return rawValue;
}
- throw new Error(
- "RECORDLY_BENCH_EXPORT_BACKEND must be 'auto', 'webcodecs', or 'breeze'",
- );
+ throw new Error("RECORDLY_BENCH_EXPORT_BACKEND must be 'auto', 'webcodecs', or 'breeze'");
}
function parseExportBackendList(rawValue) {
@@ -172,9 +174,7 @@ function parseExportEncodingMode(rawValue) {
return rawValue;
}
- throw new Error(
- "RECORDLY_BENCH_EXPORT_ENCODING_MODE must be 'fast', 'balanced', or 'quality'",
- );
+ throw new Error("RECORDLY_BENCH_EXPORT_ENCODING_MODE must be 'fast', 'balanced', or 'quality'");
}
function parseExportShadowIntensity(rawValue) {
@@ -209,7 +209,10 @@ function summarizeSmokeProgress(progressSamples) {
}
const extractingSamples = progressSamples.filter(
- (sample) => sample?.phase === "extracting" && typeof sample?.currentFrame === "number" && sample.currentFrame > 1,
+ (sample) =>
+ sample?.phase === "extracting" &&
+ typeof sample?.currentFrame === "number" &&
+ sample.currentFrame > 1,
);
const fpsSource = extractingSamples.length > 0 ? extractingSamples : progressSamples;
const renderFpsSamples = fpsSource
@@ -245,7 +248,6 @@ async function ensureBuildArtifacts() {
await fs.access(rendererEntry);
}
-
async function createFixtureVideo(
ffmpegPath,
targetPath,
@@ -256,16 +258,7 @@ async function createFixtureVideo(
videoFilter = `testsrc2=size=${fixtureWidth}x${fixtureHeight}:rate=${frameRate}`,
} = {},
) {
- const args = [
- "-y",
- "-hide_banner",
- "-loglevel",
- "error",
- "-f",
- "lavfi",
- "-i",
- videoFilter,
- ];
+ const args = ["-y", "-hide_banner", "-loglevel", "error", "-f", "lavfi", "-i", videoFilter];
if (includeAudio) {
args.push(
@@ -421,9 +414,7 @@ function printTable(title, columns, rows) {
console.log(divider);
for (const row of formattedRows) {
console.log(
- `| ${row
- .map((value, columnIndex) => value.padEnd(widths[columnIndex]))
- .join(" | ")} |`,
+ `| ${row.map((value, columnIndex) => value.padEnd(widths[columnIndex])).join(" | ")} |`,
);
}
}
@@ -471,7 +462,8 @@ function calculateDelta(referenceValue, nextValue) {
return {
deltaMs: nextValue - referenceValue,
- deltaPercent: referenceValue > 0 ? ((nextValue - referenceValue) / referenceValue) * 100 : 0,
+ deltaPercent:
+ referenceValue > 0 ? ((nextValue - referenceValue) / referenceValue) * 100 : 0,
};
}
@@ -545,7 +537,10 @@ function printTimingSummaryTable(benchmarkResults) {
{ header: "Avg export", getValue: (row) => formatMs(row.averageSmokeElapsedMs) },
{ header: "Min", getValue: (row) => formatMs(row.minElapsedMs) },
{ header: "Max", getValue: (row) => formatMs(row.maxElapsedMs) },
- { header: "Avg output", getValue: (row) => formatSeconds(row.averageOutputDurationSeconds) },
+ {
+ header: "Avg output",
+ getValue: (row) => formatSeconds(row.averageOutputDurationSeconds),
+ },
{ header: "Avg size", getValue: (row) => formatMegabytes(row.averageSizeBytes) },
{ header: "Webcam", getValue: (row) => formatBoolean(row.webcamEnabled) },
],
@@ -590,7 +585,9 @@ function printBackendDetailTable(benchmarkResults) {
function buildDeltaTableRows(benchmarkResults) {
return benchmarkResults
.map((result) => {
- const baseline = result.summaries.find((summary) => summary.variant.name === "baseline");
+ const baseline = result.summaries.find(
+ (summary) => summary.variant.name === "baseline",
+ );
const tuned = result.summaries.find((summary) => summary.variant.name === "tuned");
if (!baseline || !tuned) {
return null;
@@ -623,9 +620,21 @@ function printDeltaTable(benchmarkResults) {
[
{ header: "Pipeline", getValue: (row) => row.pipeline },
{ header: "Backend", getValue: (row) => row.backend },
- { header: "Avg delta", getValue: (row) => `${formatDeltaMs(row.averageDeltaMs)} (${formatPercent(row.averageDeltaPercent)})` },
- { header: "Median delta", getValue: (row) => `${formatDeltaMs(row.medianDeltaMs)} (${formatPercent(row.medianDeltaPercent)})` },
- { header: "Export delta", getValue: (row) => `${formatDeltaMs(row.exportDeltaMs)} (${formatPercent(row.exportDeltaPercent)})` },
+ {
+ header: "Avg delta",
+ getValue: (row) =>
+ `${formatDeltaMs(row.averageDeltaMs)} (${formatPercent(row.averageDeltaPercent)})`,
+ },
+ {
+ header: "Median delta",
+ getValue: (row) =>
+ `${formatDeltaMs(row.medianDeltaMs)} (${formatPercent(row.medianDeltaPercent)})`,
+ },
+ {
+ header: "Export delta",
+ getValue: (row) =>
+ `${formatDeltaMs(row.exportDeltaMs)} (${formatPercent(row.exportDeltaPercent)})`,
+ },
],
buildDeltaTableRows(benchmarkResults),
);
@@ -659,9 +668,7 @@ async function runVariant(
...(exportShadowIntensity !== null
? { RECORDLY_SMOKE_EXPORT_SHADOW_INTENSITY: String(exportShadowIntensity) }
: {}),
- ...(webcamInputPath
- ? { RECORDLY_SMOKE_EXPORT_WEBCAM_INPUT: webcamInputPath }
- : {}),
+ ...(webcamInputPath ? { RECORDLY_SMOKE_EXPORT_WEBCAM_INPUT: webcamInputPath } : {}),
...(webcamShadowIntensity !== null
? { RECORDLY_SMOKE_EXPORT_WEBCAM_SHADOW: String(webcamShadowIntensity) }
: {}),
@@ -744,9 +751,7 @@ async function runVariant(
outputDuration,
webcamEnabled: !!webcamInputPath,
smokeExportReport: smokeExportReport?.report ?? null,
- smokeProgressSummary: summarizeSmokeProgress(
- smokeExportReport?.report?.progressSamples,
- ),
+ smokeProgressSummary: summarizeSmokeProgress(smokeExportReport?.report?.progressSamples),
};
}
@@ -877,7 +882,9 @@ async function main() {
console.log(`[benchmark-export-queues] Generating fixture video: ${inputPath}`);
await createFixtureVideo(ffmpegStatic, inputPath);
if (webcamInputPath) {
- console.log(`[benchmark-export-queues] Generating webcam fixture video: ${webcamInputPath}`);
+ console.log(
+ `[benchmark-export-queues] Generating webcam fixture video: ${webcamInputPath}`,
+ );
await createFixtureVideo(ffmpegStatic, webcamInputPath, {
fixtureWidth: webcamWidth,
fixtureHeight: webcamHeight,
@@ -945,12 +952,11 @@ async function main() {
const baseline = result.summaries[0];
const tuned = result.summaries[1];
const deltaMs = tuned.averageElapsedMs - baseline.averageElapsedMs;
- const percent = baseline.averageElapsedMs > 0 ? (deltaMs / baseline.averageElapsedMs) * 100 : 0;
+ const percent =
+ baseline.averageElapsedMs > 0 ? (deltaMs / baseline.averageElapsedMs) * 100 : 0;
const medianDeltaMs = tuned.medianElapsedMs - baseline.medianElapsedMs;
const medianPercent =
- baseline.medianElapsedMs > 0
- ? (medianDeltaMs / baseline.medianElapsedMs) * 100
- : 0;
+ baseline.medianElapsedMs > 0 ? (medianDeltaMs / baseline.medianElapsedMs) * 100 : 0;
const backendLabel = result.request.backend ?? "default";
console.log(
`[benchmark-export-queues] ${backendLabel} tuned vs baseline: ${deltaMs}ms (${percent.toFixed(1)}%)`,
@@ -969,4 +975,4 @@ main().catch((error) => {
`[benchmark-export-queues] ${error instanceof Error ? error.message : String(error)}`,
);
process.exitCode = 1;
-});
\ No newline at end of file
+});
diff --git a/scripts/build-native-helpers.mjs b/scripts/build-native-helpers.mjs
index 8cf67c4a..778b19b8 100644
--- a/scripts/build-native-helpers.mjs
+++ b/scripts/build-native-helpers.mjs
@@ -14,11 +14,11 @@ function getTargetConfigs() {
return [
{
archTag: "darwin-arm64",
- swiftTarget: "arm64-apple-macos13.0",
+ swiftTarget: "arm64-apple-macos14.0",
},
{
archTag: "darwin-x64",
- swiftTarget: "x86_64-apple-macos13.0",
+ swiftTarget: "x86_64-apple-macos14.0",
},
];
}
@@ -26,19 +26,19 @@ function getTargetConfigs() {
const helpers = [
{
source: "ScreenCaptureKitRecorder.swift",
- output: "openscreen-screencapturekit-helper",
+ output: "recordly-screencapturekit-helper",
},
{
source: "ScreenCaptureKitWindowList.swift",
- output: "openscreen-window-list",
+ output: "recordly-window-list",
},
{
source: "SystemCursorAssets.swift",
- output: "openscreen-system-cursors",
+ output: "recordly-system-cursors",
},
{
source: "NativeCursorMonitor.swift",
- output: "openscreen-native-cursor-monitor",
+ output: "recordly-native-cursor-monitor",
},
];
diff --git a/scripts/build-whisper-runtime.mjs b/scripts/build-whisper-runtime.mjs
index 0bdf9dd8..13c944e6 100644
--- a/scripts/build-whisper-runtime.mjs
+++ b/scripts/build-whisper-runtime.mjs
@@ -101,7 +101,12 @@ function getTargetConfigs() {
archTag,
buildRoot: path.join(cacheRoot, `build-${archTag}`),
outputDir: path.join(nativeRoot, "bin", archTag),
- configureArgs: ["-G", "Visual Studio 17 2022", "-A", arch === "arm64" ? "ARM64" : "x64"],
+ configureArgs: [
+ "-G",
+ "Visual Studio 17 2022",
+ "-A",
+ arch === "arm64" ? "ARM64" : "x64",
+ ],
},
];
}
@@ -258,7 +263,9 @@ async function shouldSkipBuild(target) {
const binaryName = target.platform === "win32" ? "whisper-cli.exe" : "whisper-cli";
const binaryPath = path.join(target.outputDir, binaryName);
return (
- manifest.version === whisperVersion && manifest.arch === target.arch && existsSync(binaryPath)
+ manifest.version === whisperVersion &&
+ manifest.arch === target.arch &&
+ existsSync(binaryPath)
);
} catch {
return false;
diff --git a/scripts/build-windows-capture.mjs b/scripts/build-windows-capture.mjs
index 18f5ca36..3ae981b2 100644
--- a/scripts/build-windows-capture.mjs
+++ b/scripts/build-windows-capture.mjs
@@ -1,11 +1,11 @@
import { execSync } from "node:child_process";
-import { copyFileSync, mkdirSync, existsSync, rmSync } from "node:fs";
+import { copyFileSync, existsSync, mkdirSync, rmSync } from "node:fs";
import path from "node:path";
import {
- formatNativeHelperManifestWarning,
- updateNativeHelperManifest,
- verifyNativeHelperManifest,
+ formatNativeHelperManifestWarning,
+ updateNativeHelperManifest,
+ verifyNativeHelperManifest,
} from "./native-helper-manifest.mjs";
const projectRoot = process.cwd();
@@ -21,81 +21,83 @@ const bundledDir = path.join(
const bundledExePath = path.join(bundledDir, "wgc-capture.exe");
const helperId = "wgc-capture";
-if (process.platform !== 'win32') {
- console.log('[build-windows-capture] Skipping native Windows capture build: host platform is not Windows.');
- process.exit(0);
+if (process.platform !== "win32") {
+ console.log(
+ "[build-windows-capture] Skipping native Windows capture build: host platform is not Windows.",
+ );
+ process.exit(0);
}
-if (!existsSync(path.join(sourceDir, 'CMakeLists.txt'))) {
- console.error('[build-windows-capture] CMakeLists.txt not found at', sourceDir);
- process.exit(1);
+if (!existsSync(path.join(sourceDir, "CMakeLists.txt"))) {
+ console.error("[build-windows-capture] CMakeLists.txt not found at", sourceDir);
+ process.exit(1);
}
function findCmake() {
- // Check PATH first
- try {
- execSync('cmake --version', { stdio: 'pipe' });
- return 'cmake';
- } catch {
- // not on PATH
- }
+ // Check PATH first
+ try {
+ execSync("cmake --version", { stdio: "pipe" });
+ return "cmake";
+ } catch {
+ // not on PATH
+ }
- const standaloneCmakePaths = [
- path.join('C:', 'Program Files', 'CMake', 'bin', 'cmake.exe'),
- path.join('C:', 'Program Files (x86)', 'CMake', 'bin', 'cmake.exe'),
- ];
- for (const cmakePath of standaloneCmakePaths) {
- if (existsSync(cmakePath)) {
- return `"${cmakePath}"`;
- }
- }
+ const standaloneCmakePaths = [
+ path.join("C:", "Program Files", "CMake", "bin", "cmake.exe"),
+ path.join("C:", "Program Files (x86)", "CMake", "bin", "cmake.exe"),
+ ];
+ for (const cmakePath of standaloneCmakePaths) {
+ if (existsSync(cmakePath)) {
+ return `"${cmakePath}"`;
+ }
+ }
- // VS 2022 bundled CMake
- const vsRoots = [
- path.join('C:', 'Program Files', 'Microsoft Visual Studio'),
- path.join('C:', 'Program Files (x86)', 'Microsoft Visual Studio'),
- ];
- const vsEditions = ['Community', 'Professional', 'Enterprise', 'BuildTools'];
- const vsVersions = ['2022', '2019'];
- for (const root of vsRoots) {
- for (const version of vsVersions) {
- for (const edition of vsEditions) {
- const cmakePath = path.join(
- root,
- version,
- edition,
- 'Common7',
- 'IDE',
- 'CommonExtensions',
- 'Microsoft',
- 'CMake',
- 'CMake',
- 'bin',
- 'cmake.exe'
- );
- if (existsSync(cmakePath)) {
- return `"${cmakePath}"`;
- }
- }
- }
- }
+ // VS 2022 bundled CMake
+ const vsRoots = [
+ path.join("C:", "Program Files", "Microsoft Visual Studio"),
+ path.join("C:", "Program Files (x86)", "Microsoft Visual Studio"),
+ ];
+ const vsEditions = ["Community", "Professional", "Enterprise", "BuildTools"];
+ const vsVersions = ["2022", "2019"];
+ for (const root of vsRoots) {
+ for (const version of vsVersions) {
+ for (const edition of vsEditions) {
+ const cmakePath = path.join(
+ root,
+ version,
+ edition,
+ "Common7",
+ "IDE",
+ "CommonExtensions",
+ "Microsoft",
+ "CMake",
+ "CMake",
+ "bin",
+ "cmake.exe",
+ );
+ if (existsSync(cmakePath)) {
+ return `"${cmakePath}"`;
+ }
+ }
+ }
+ }
- return null;
+ return null;
}
const cmake = findCmake();
if (!cmake) {
if (existsSync(bundledExePath)) {
- const verification = verifyNativeHelperManifest({
- projectRoot,
- helperId,
- sourceDir,
- binaryPath: bundledExePath,
- binaryName: "wgc-capture.exe",
- });
- if (!verification.ok) {
- console.warn(formatNativeHelperManifestWarning("build-windows-capture", verification));
- }
+ const verification = verifyNativeHelperManifest({
+ projectRoot,
+ helperId,
+ sourceDir,
+ binaryPath: bundledExePath,
+ binaryName: "wgc-capture.exe",
+ });
+ if (!verification.ok) {
+ console.warn(formatNativeHelperManifestWarning("build-windows-capture", verification));
+ }
console.log(`[build-windows-capture] Using bundled helper: ${bundledExePath}`);
process.exit(0);
}
@@ -107,64 +109,64 @@ if (!cmake) {
}
mkdirSync(buildDir, { recursive: true });
-const cacheFile = path.join(buildDir, 'CMakeCache.txt');
-const cacheDir = path.join(buildDir, 'CMakeFiles');
+const cacheFile = path.join(buildDir, "CMakeCache.txt");
+const cacheDir = path.join(buildDir, "CMakeFiles");
function clearCmakeCache() {
- rmSync(cacheFile, { force: true });
- rmSync(cacheDir, { recursive: true, force: true });
+ rmSync(cacheFile, { force: true });
+ rmSync(cacheDir, { recursive: true, force: true });
}
-console.log('[build-windows-capture] Configuring CMake...');
+console.log("[build-windows-capture] Configuring CMake...");
try {
- clearCmakeCache();
- execSync(`${cmake} .. -G "Visual Studio 17 2022" -A x64`, {
- cwd: buildDir,
- stdio: 'inherit',
- timeout: 120000,
- });
+ clearCmakeCache();
+ execSync(`${cmake} .. -G "Visual Studio 17 2022" -A x64`, {
+ cwd: buildDir,
+ stdio: "inherit",
+ timeout: 120000,
+ });
} catch {
- console.log('[build-windows-capture] VS 2022 generator not found, trying VS 2019...');
- try {
- clearCmakeCache();
- execSync(`${cmake} .. -G "Visual Studio 16 2019" -A x64`, {
- cwd: buildDir,
- stdio: 'inherit',
- timeout: 120000,
- });
- } catch (innerError) {
- console.error('[build-windows-capture] CMake configure failed:', innerError.message);
- process.exit(1);
- }
+ console.log("[build-windows-capture] VS 2022 generator not found, trying VS 2019...");
+ try {
+ clearCmakeCache();
+ execSync(`${cmake} .. -G "Visual Studio 16 2019" -A x64`, {
+ cwd: buildDir,
+ stdio: "inherit",
+ timeout: 120000,
+ });
+ } catch (innerError) {
+ console.error("[build-windows-capture] CMake configure failed:", innerError.message);
+ process.exit(1);
+ }
}
-console.log('[build-windows-capture] Building native Windows capture helper...');
+console.log("[build-windows-capture] Building native Windows capture helper...");
try {
- execSync(`${cmake} --build . --config Release`, {
- cwd: buildDir,
- stdio: 'inherit',
- timeout: 300000,
- });
+ execSync(`${cmake} --build . --config Release`, {
+ cwd: buildDir,
+ stdio: "inherit",
+ timeout: 300000,
+ });
} catch (error) {
- console.error('[build-windows-capture] Build failed:', error.message);
- process.exit(1);
+ console.error("[build-windows-capture] Build failed:", error.message);
+ process.exit(1);
}
-const exePath = path.join(buildDir, 'Release', 'wgc-capture.exe');
+const exePath = path.join(buildDir, "Release", "wgc-capture.exe");
if (existsSync(exePath)) {
console.log(`[build-windows-capture] Built successfully: ${exePath}`);
mkdirSync(bundledDir, { recursive: true });
copyFileSync(exePath, bundledExePath);
console.log(`[build-windows-capture] Staged bundled helper: ${bundledExePath}`);
- const manifestPath = updateNativeHelperManifest({
- projectRoot,
- helperId,
- sourceDir,
- binaryPath: bundledExePath,
- binaryName: "wgc-capture.exe",
- });
- console.log(`[build-windows-capture] Updated helper manifest: ${manifestPath}`);
+ const manifestPath = updateNativeHelperManifest({
+ projectRoot,
+ helperId,
+ sourceDir,
+ binaryPath: bundledExePath,
+ binaryName: "wgc-capture.exe",
+ });
+ console.log(`[build-windows-capture] Updated helper manifest: ${manifestPath}`);
} else {
- console.error('[build-windows-capture] Expected exe not found at', exePath);
- process.exit(1);
+ console.error("[build-windows-capture] Expected exe not found at", exePath);
+ process.exit(1);
}
diff --git a/scripts/i18n-check.mjs b/scripts/i18n-check.mjs
index 19535bda..cff56c29 100644
--- a/scripts/i18n-check.mjs
+++ b/scripts/i18n-check.mjs
@@ -1,86 +1,86 @@
-import fs from 'node:fs'
-import path from 'node:path'
+import fs from "node:fs";
+import path from "node:path";
-const root = process.cwd()
-const localesDir = path.join(root, 'src', 'i18n', 'locales')
+const root = process.cwd();
+const localesDir = path.join(root, "src", "i18n", "locales");
const locales = fs.readdirSync(localesDir).filter((entry) => {
- const fullPath = path.join(localesDir, entry)
- return fs.statSync(fullPath).isDirectory()
-})
+ const fullPath = path.join(localesDir, entry);
+ return fs.statSync(fullPath).isDirectory();
+});
-if (!locales.includes('en')) {
- console.error('i18n-check: expected base locale directory "en"')
- process.exit(1)
+if (!locales.includes("en")) {
+ console.error('i18n-check: expected base locale directory "en"');
+ process.exit(1);
}
function loadJson(filePath) {
- return JSON.parse(fs.readFileSync(filePath, 'utf8'))
+ return JSON.parse(fs.readFileSync(filePath, "utf8"));
}
-function collectKeyPaths(obj, prefix = '') {
- if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
- return prefix ? [prefix] : []
- }
-
- const keys = Object.keys(obj)
- if (keys.length === 0) {
- return prefix ? [prefix] : []
- }
-
- const paths = []
- for (const key of keys) {
- const nextPrefix = prefix ? `${prefix}.${key}` : key
- const value = obj[key]
- if (value && typeof value === 'object' && !Array.isArray(value)) {
- paths.push(...collectKeyPaths(value, nextPrefix))
- } else {
- paths.push(nextPrefix)
- }
- }
- return paths
+function collectKeyPaths(obj, prefix = "") {
+ if (!obj || typeof obj !== "object" || Array.isArray(obj)) {
+ return prefix ? [prefix] : [];
+ }
+
+ const keys = Object.keys(obj);
+ if (keys.length === 0) {
+ return prefix ? [prefix] : [];
+ }
+
+ const paths = [];
+ for (const key of keys) {
+ const nextPrefix = prefix ? `${prefix}.${key}` : key;
+ const value = obj[key];
+ if (value && typeof value === "object" && !Array.isArray(value)) {
+ paths.push(...collectKeyPaths(value, nextPrefix));
+ } else {
+ paths.push(nextPrefix);
+ }
+ }
+ return paths;
}
-const baseLocaleDir = path.join(localesDir, 'en')
-const namespaceFiles = fs.readdirSync(baseLocaleDir).filter((file) => file.endsWith('.json'))
+const baseLocaleDir = path.join(localesDir, "en");
+const namespaceFiles = fs.readdirSync(baseLocaleDir).filter((file) => file.endsWith(".json"));
-let hasErrors = false
+let hasErrors = false;
for (const namespaceFile of namespaceFiles) {
- const baseData = loadJson(path.join(baseLocaleDir, namespaceFile))
- const baseKeys = new Set(collectKeyPaths(baseData))
-
- for (const locale of locales) {
- if (locale === 'en') continue
-
- const localeFile = path.join(localesDir, locale, namespaceFile)
- if (!fs.existsSync(localeFile)) {
- console.error(`i18n-check: missing namespace file ${locale}/${namespaceFile}`)
- hasErrors = true
- continue
- }
-
- const localeData = loadJson(localeFile)
- const localeKeys = new Set(collectKeyPaths(localeData))
-
- for (const key of baseKeys) {
- if (!localeKeys.has(key)) {
- console.error(`i18n-check: missing key ${locale}/${namespaceFile}:${key}`)
- hasErrors = true
- }
- }
-
- for (const key of localeKeys) {
- if (!baseKeys.has(key)) {
- console.error(`i18n-check: extra key ${locale}/${namespaceFile}:${key}`)
- hasErrors = true
- }
- }
- }
+ const baseData = loadJson(path.join(baseLocaleDir, namespaceFile));
+ const baseKeys = new Set(collectKeyPaths(baseData));
+
+ for (const locale of locales) {
+ if (locale === "en") continue;
+
+ const localeFile = path.join(localesDir, locale, namespaceFile);
+ if (!fs.existsSync(localeFile)) {
+ console.error(`i18n-check: missing namespace file ${locale}/${namespaceFile}`);
+ hasErrors = true;
+ continue;
+ }
+
+ const localeData = loadJson(localeFile);
+ const localeKeys = new Set(collectKeyPaths(localeData));
+
+ for (const key of baseKeys) {
+ if (!localeKeys.has(key)) {
+ console.error(`i18n-check: missing key ${locale}/${namespaceFile}:${key}`);
+ hasErrors = true;
+ }
+ }
+
+ for (const key of localeKeys) {
+ if (!baseKeys.has(key)) {
+ console.error(`i18n-check: extra key ${locale}/${namespaceFile}:${key}`);
+ hasErrors = true;
+ }
+ }
+ }
}
if (hasErrors) {
- process.exit(1)
+ process.exit(1);
}
-console.log('i18n-check: locale files are structurally consistent')
\ No newline at end of file
+console.log("i18n-check: locale files are structurally consistent");
diff --git a/scripts/native-helper-manifest.mjs b/scripts/native-helper-manifest.mjs
index 5c13996e..0cf96e0f 100644
--- a/scripts/native-helper-manifest.mjs
+++ b/scripts/native-helper-manifest.mjs
@@ -1,12 +1,5 @@
import { createHash } from "node:crypto";
-import {
- existsSync,
- mkdirSync,
- readFileSync,
- readdirSync,
- statSync,
- writeFileSync,
-} from "node:fs";
+import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
import path from "node:path";
const MANIFEST_FILE_NAME = "helpers-manifest.json";
@@ -66,7 +59,11 @@ function hashFile(filePath) {
return hashBuffer(readFileSync(filePath));
}
-export function getNativeHelperManifestPath({ projectRoot, platform = process.platform, arch = process.arch }) {
+export function getNativeHelperManifestPath({
+ projectRoot,
+ platform = process.platform,
+ arch = process.arch,
+}) {
return path.join(
projectRoot,
"electron",
@@ -161,7 +158,9 @@ export function verifyNativeHelperManifest({
const reasons = [];
if (helperManifest.binaryName !== binaryName) {
- reasons.push(`expected binary ${binaryName}, found ${helperManifest.binaryName ?? "unknown"}`);
+ reasons.push(
+ `expected binary ${binaryName}, found ${helperManifest.binaryName ?? "unknown"}`,
+ );
}
const expectedBinaryHash = helperManifest.binarySha256;
@@ -186,4 +185,4 @@ export function verifyNativeHelperManifest({
export function formatNativeHelperManifestWarning(helperLabel, verificationResult) {
const reasonText = verificationResult.reasons.join(", ");
return `[${helperLabel}] Bundled helper provenance check failed (${reasonText}). Rebuild the helper to refresh ${path.basename(verificationResult.manifestPath)}.`;
-}
\ No newline at end of file
+}
diff --git a/scripts/postinstall.mjs b/scripts/postinstall.mjs
index 3a35d3db..b0715a83 100644
--- a/scripts/postinstall.mjs
+++ b/scripts/postinstall.mjs
@@ -23,9 +23,7 @@ function runScript(scriptName) {
});
if (result.error) {
- console.error(
- `[postinstall] Failed to start "${scriptName}" (${result.error.message}).`,
- );
+ console.error(`[postinstall] Failed to start "${scriptName}" (${result.error.message}).`);
return false;
}
@@ -35,9 +33,7 @@ function runScript(scriptName) {
}
if (result.status !== 0) {
- console.error(
- `[postinstall] "${scriptName}" exited with code ${result.status}.`,
- );
+ console.error(`[postinstall] "${scriptName}" exited with code ${result.status}.`);
return false;
}
diff --git a/src/App.css b/src/App.css
index d936c2c5..df674c0d 100644
--- a/src/App.css
+++ b/src/App.css
@@ -1,43 +1,42 @@
-#root {
- max-width: 1280px;
- margin: 0 auto;
- padding: 2rem;
- text-align: center;
-}
-
-.logo {
- height: 6em;
- padding: 1.5em;
- will-change: filter;
- transition: filter 300ms;
-}
-.logo:hover {
- filter: drop-shadow(0 0 2em #646cffaa);
-}
-.logo.react:hover {
- filter: drop-shadow(0 0 2em #61dafbaa);
-}
-
-@keyframes logo-spin {
- from {
- transform: rotate(0deg);
- }
- to {
- transform: rotate(360deg);
- }
-}
-
-@media (prefers-reduced-motion: no-preference) {
- a:nth-of-type(2) .logo {
- animation: logo-spin infinite 20s linear;
- }
-}
-
-.card {
- padding: 2em;
-}
-
-.read-the-docs {
- color: #888;
-}
+#root {
+ max-width: 1280px;
+ margin: 0 auto;
+ padding: 2rem;
+ text-align: center;
+}
+.logo {
+ height: 6em;
+ padding: 1.5em;
+ will-change: filter;
+ transition: filter 300ms;
+}
+.logo:hover {
+ filter: drop-shadow(0 0 2em #646cffaa);
+}
+.logo.react:hover {
+ filter: drop-shadow(0 0 2em #61dafbaa);
+}
+
+@keyframes logo-spin {
+ from {
+ transform: rotate(0deg);
+ }
+ to {
+ transform: rotate(360deg);
+ }
+}
+
+@media (prefers-reduced-motion: no-preference) {
+ a:nth-of-type(2) .logo {
+ animation: logo-spin infinite 20s linear;
+ }
+}
+
+.card {
+ padding: 2em;
+}
+
+.read-the-docs {
+ color: #888;
+}
diff --git a/src/App.tsx b/src/App.tsx
index 4622bdda..3ba05874 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -1,90 +1,94 @@
-import { useEffect, useState } from "react";
-import { CountdownOverlay } from "./components/countdown/CountdownOverlay";
-import { LaunchWindow } from "./components/launch/LaunchWindow";
-import { SourceSelector } from "./components/launch/SourceSelector";
-import { UpdateToastWindow } from "./components/launch/UpdateToastWindow";
-import { Toaster } from "./components/ui/sonner";
-import { ShortcutsConfigDialog } from "./components/video-editor/ShortcutsConfigDialog";
-import VideoEditor from "./components/video-editor/VideoEditor";
-import { useI18n } from "./contexts/I18nContext";
-import { ShortcutsProvider } from "./contexts/ShortcutsContext";
-import { loadAllCustomFonts } from "./lib/customFonts";
-
-export default function App() {
- const [windowType, setWindowType] = useState("");
- const { locale, t } = useI18n();
-
- useEffect(() => {
- const params = new URLSearchParams(window.location.search);
- const type = params.get("windowType") || "";
- const isMacOS = /mac/i.test(navigator.platform);
- setWindowType(type);
-
- if (
- type === "hud-overlay" ||
- type === "source-selector" ||
- type === "countdown" ||
- (type === "update-toast" && isMacOS)
- ) {
- document.body.style.background = "transparent";
- document.documentElement.style.background = "transparent";
- document.getElementById("root")?.style.setProperty("background", "transparent");
- }
-
- if (type === "hud-overlay" || type === "update-toast") {
- document.documentElement.style.overflow = "visible";
- document.body.style.overflow = "visible";
- document.getElementById("root")?.style.setProperty("overflow", "visible");
- }
-
- loadAllCustomFonts().catch((error) => {
- console.error("Failed to load custom fonts:", error);
- });
- }, []);
-
- useEffect(() => {
- document.title =
- windowType === "editor" ? t("app.editorTitle", "Recordly Editor") : t("app.name", "Recordly");
- }, [windowType, locale, t]);
-
- switch (windowType) {
- case "hud-overlay":
- return (
- <>
- <LaunchWindow />
- <Toaster theme="dark" className="pointer-events-auto" />
- </>
- );
- case "source-selector":
- return <SourceSelector />;
- case "countdown":
- return <CountdownOverlay />;
- case "update-toast":
- return <UpdateToastWindow />;
- case "editor":
- return (
- <ShortcutsProvider>
- <VideoEditor />
- <ShortcutsConfigDialog />
- </ShortcutsProvider>
- );
- default:
- return (
- <div className="flex h-full w-full items-center justify-center bg-slate-950 text-white">
- <div className="flex items-center gap-4 rounded-2xl border border-white/10 bg-white/5 px-6 py-5 shadow-2xl shadow-black/30 backdrop-blur-xl">
- <img
- src="/app-icons/recordly-128.png"
- alt={t("app.name", "Recordly")}
- className="h-12 w-12 rounded-xl"
- />
- <div>
- <h1 className="text-xl font-semibold tracking-tight">{t("app.name", "Recordly")}</h1>
- <p className="text-sm text-white/65">
- {t("app.subtitle", "Screen recording and editing")}
- </p>
- </div>
- </div>
- </div>
- );
- }
-}
+import { useEffect, useState } from "react";
+import { CountdownOverlay } from "./components/countdown/CountdownOverlay";
+import { LaunchWindow } from "./components/launch/LaunchWindow";
+import { SourceSelector } from "./components/launch/SourceSelector";
+import { UpdateToastWindow } from "./components/launch/UpdateToastWindow";
+import { Toaster } from "./components/ui/sonner";
+import { ShortcutsConfigDialog } from "./components/video-editor/ShortcutsConfigDialog";
+import VideoEditor from "./components/video-editor/VideoEditor";
+import { useI18n } from "./contexts/I18nContext";
+import { ShortcutsProvider } from "./contexts/ShortcutsContext";
+import { loadAllCustomFonts } from "./lib/customFonts";
+
+export default function App() {
+ const [windowType, setWindowType] = useState("");
+ const { t } = useI18n();
+
+ useEffect(() => {
+ const params = new URLSearchParams(window.location.search);
+ const type = params.get("windowType") || "";
+ const isMacOS = /mac/i.test(navigator.platform);
+ setWindowType(type);
+
+ if (
+ type === "hud-overlay" ||
+ type === "source-selector" ||
+ type === "countdown" ||
+ (type === "update-toast" && isMacOS)
+ ) {
+ document.body.style.background = "transparent";
+ document.documentElement.style.background = "transparent";
+ document.getElementById("root")?.style.setProperty("background", "transparent");
+ }
+
+ if (type === "hud-overlay" || type === "update-toast") {
+ document.documentElement.style.overflow = "visible";
+ document.body.style.overflow = "visible";
+ document.getElementById("root")?.style.setProperty("overflow", "visible");
+ }
+
+ loadAllCustomFonts().catch((error) => {
+ console.error("Failed to load custom fonts:", error);
+ });
+ }, []);
+
+ useEffect(() => {
+ document.title =
+ windowType === "editor"
+ ? t("app.editorTitle", "Recordly Editor")
+ : t("app.name", "Recordly");
+ }, [windowType, t]);
+
+ switch (windowType) {
+ case "hud-overlay":
+ return (
+ <>
+ <LaunchWindow />
+ <Toaster theme="dark" className="pointer-events-auto" />
+ </>
+ );
+ case "source-selector":
+ return <SourceSelector />;
+ case "countdown":
+ return <CountdownOverlay />;
+ case "update-toast":
+ return <UpdateToastWindow />;
+ case "editor":
+ return (
+ <ShortcutsProvider>
+ <VideoEditor />
+ <ShortcutsConfigDialog />
+ </ShortcutsProvider>
+ );
+ default:
+ return (
+ <div className="flex h-full w-full items-center justify-center bg-slate-950 text-white">
+ <div className="flex items-center gap-4 rounded-2xl border border-white/10 bg-white/5 px-6 py-5 shadow-2xl shadow-black/30 backdrop-blur-xl">
+ <img
+ src="/app-icons/recordly-128.png"
+ alt={t("app.name", "Recordly")}
+ className="h-12 w-12 rounded-xl"
+ />
+ <div>
+ <h1 className="text-xl font-semibold tracking-tight">
+ {t("app.name", "Recordly")}
+ </h1>
+ <p className="text-sm text-white/65">
+ {t("app.subtitle", "Screen recording and editing")}
+ </p>
+ </div>
+ </div>
+ </div>
+ );
+ }
+}
diff --git a/src/components/launch/LaunchWindow.tsx b/src/components/launch/LaunchWindow.tsx
index 5e182e78..2b12ea29 100644
--- a/src/components/launch/LaunchWindow.tsx
+++ b/src/components/launch/LaunchWindow.tsx
@@ -1,29 +1,29 @@
import {
AppWindow,
- ArrowUpCircle,
- ChevronUp,
- CheckCircle2,
+ ArrowCircleUp as ArrowUpCircle,
+ ArrowClockwise as RefreshCw,
+ CaretUp as ChevronUp,
+ CheckCircle as CheckCircle2,
+ DotsThreeVertical as MoreVertical,
Eye,
- EyeOff,
+ EyeSlash as EyeOff,
FolderOpen,
- Languages,
- Mic,
- MicOff,
+ Microphone as Mic,
+ MicrophoneSlash as MicOff,
Minus,
Monitor,
- MoreVertical,
Pause,
Play,
- RefreshCw,
- Square,
+ SpeakerHigh as Volume2,
+ SpeakerX as VolumeX,
+ Stop as Square,
Timer,
- Video,
- VideoIcon,
- VideoOff,
- Volume2,
- VolumeX,
+ Translate as Languages,
+ VideoCamera as Video,
+ VideoCamera as VideoIcon,
+ VideoCameraSlash as VideoOff,
X,
-} from "lucide-react";
+} from "@phosphor-icons/react";
import { AnimatePresence, motion } from "motion/react";
import type { ReactNode } from "react";
import { useCallback, useEffect, useRef, useState } from "react";
@@ -143,9 +143,7 @@ function MicDeviceRow({
className={`${styles.ddItem} ${selected ? styles.ddItemSelected : ""}`}
onClick={onSelect}
>
- <span className="shrink-0">
- {selected ? <Mic size={16} /> : <MicOff size={16} />}
- </span>
+ <span className="shrink-0">{selected ? <Mic size={16} /> : <MicOff size={16} />}</span>
<span className="truncate flex-1">{device.label}</span>
<AudioLevelMeter level={level} className="w-16 shrink-0" />
</button>
@@ -189,21 +187,14 @@ export function LaunchWindow() {
const [activeDropdown, setActiveDropdown] = useState<
"none" | "sources" | "more" | "mic" | "countdown" | "webcam"
>("none");
- const [projectLibraryEntries, setProjectLibraryEntries] = useState<
- ProjectLibraryEntry[]
- >([]);
+ const [projectLibraryEntries, setProjectLibraryEntries] = useState<ProjectLibraryEntry[]>([]);
const [projectBrowserOpen, setProjectBrowserOpen] = useState(false);
const [sources, setSources] = useState<DesktopSource[]>([]);
const [sourcesLoading, setSourcesLoading] = useState(false);
const [hideHudFromCapture, setHideHudFromCapture] = useState(true);
- const [showFloatingWebcamPreview, setShowFloatingWebcamPreview] =
- useState(true);
- const [webcamPreviewOffset, setWebcamPreviewOffset] = useState(
- DEFAULT_WEBCAM_PREVIEW_OFFSET,
- );
- const [recordingHudOffset, setRecordingHudOffset] = useState(
- DEFAULT_RECORDING_HUD_OFFSET,
- );
+ const [showFloatingWebcamPreview, setShowFloatingWebcamPreview] = useState(true);
+ const [webcamPreviewOffset, setWebcamPreviewOffset] = useState(DEFAULT_WEBCAM_PREVIEW_OFFSET);
+ const [recordingHudOffset, setRecordingHudOffset] = useState(DEFAULT_RECORDING_HUD_OFFSET);
const [platform, setPlatform] = useState<string | null>(null);
const [appVersion, setAppVersion] = useState<string | null>(null);
const [updateStatus, setUpdateStatus] = useState<{
@@ -230,9 +221,7 @@ export function LaunchWindow() {
const moreButtonRef = useRef<HTMLButtonElement | null>(null);
const webcamPreviewRef = useRef<HTMLVideoElement | null>(null);
const recordingWebcamPreviewRef = useRef<HTMLVideoElement | null>(null);
- const recordingWebcamPreviewContainerRef = useRef<HTMLDivElement | null>(
- null,
- );
+ const recordingWebcamPreviewContainerRef = useRef<HTMLDivElement | null>(null);
const previewStreamRef = useRef<MediaStream | null>(null);
const webcamPreviewDragStartRef = useRef<{
pointerId: number;
@@ -271,17 +260,13 @@ export function LaunchWindow() {
const micDropdownOpen = activeDropdown === "mic";
const webcamDropdownOpen = activeDropdown === "webcam";
const showWebcamControls = webcamEnabled && !recording;
- const showRecordingWebcamPreview =
- webcamEnabled && showFloatingWebcamPreview;
+ const showRecordingWebcamPreview = webcamEnabled && showFloatingWebcamPreview;
const shouldStreamWebcamPreview =
- webcamEnabled &&
- (showFloatingWebcamPreview ||
- (showWebcamControls && webcamDropdownOpen));
- const { devices, selectedDeviceId, setSelectedDeviceId } =
- useMicrophoneDevices(
- microphoneEnabled || micDropdownOpen,
- microphoneDeviceId,
- );
+ webcamEnabled && (showFloatingWebcamPreview || (showWebcamControls && webcamDropdownOpen));
+ const { devices, selectedDeviceId, setSelectedDeviceId } = useMicrophoneDevices(
+ microphoneEnabled || micDropdownOpen,
+ microphoneDeviceId,
+ );
const {
devices: videoDevices,
selectedDeviceId: selectedVideoDeviceId,
@@ -295,9 +280,7 @@ export function LaunchWindow() {
return;
}
- setMicrophoneDeviceId(
- selectedDeviceId === "default" ? undefined : selectedDeviceId,
- );
+ setMicrophoneDeviceId(selectedDeviceId === "default" ? undefined : selectedDeviceId);
}, [selectedDeviceId, setMicrophoneDeviceId]);
useEffect(() => {
@@ -322,9 +305,7 @@ export function LaunchWindow() {
}
}, [showRecordingWebcamPreview]);
- const handleWebcamPreviewPointerDown = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
+ const handleWebcamPreviewPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
if (event.button !== 0) {
return;
}
@@ -348,9 +329,7 @@ export function LaunchWindow() {
event.currentTarget.setPointerCapture(event.pointerId);
};
- const handleWebcamPreviewPointerMove = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
+ const handleWebcamPreviewPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
const dragState = webcamPreviewDragStartRef.current;
if (!dragState || dragState.pointerId !== event.pointerId) {
return;
@@ -359,10 +338,7 @@ export function LaunchWindow() {
const deltaX = event.clientX - dragState.startX;
const deltaY = event.clientY - dragState.startY;
- if (
- !dragState.dragging &&
- Math.hypot(deltaX, deltaY) < WEBCAM_PREVIEW_DRAG_THRESHOLD
- ) {
+ if (!dragState.dragging && Math.hypot(deltaX, deltaY) < WEBCAM_PREVIEW_DRAG_THRESHOLD) {
return;
}
@@ -371,14 +347,8 @@ export function LaunchWindow() {
isWebcamPreviewDraggingRef.current = true;
}
- const viewportWidth = Math.max(
- window.innerWidth,
- window.screen?.width ?? 0,
- );
- const viewportHeight = Math.max(
- window.innerHeight,
- window.screen?.height ?? 0,
- );
+ const viewportWidth = Math.max(window.innerWidth, window.screen?.width ?? 0);
+ const viewportHeight = Math.max(window.innerHeight, window.screen?.height ?? 0);
const unclampedLeft = dragState.initialLeft + deltaX;
const unclampedTop = dragState.initialTop + deltaY;
const clampedLeft = Math.min(
@@ -396,9 +366,7 @@ export function LaunchWindow() {
});
};
- const handleWebcamPreviewPointerUp = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
+ const handleWebcamPreviewPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
const dragState = webcamPreviewDragStartRef.current;
if (!dragState || dragState.pointerId !== event.pointerId) {
return;
@@ -415,9 +383,7 @@ export function LaunchWindow() {
}
};
- const handleHudBarPointerDown = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
+ const handleHudBarPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
if (event.button !== 0) {
return;
}
@@ -448,16 +414,10 @@ export function LaunchWindow() {
pointerId: event.pointerId,
mode: "overlay",
};
- window.electronAPI?.hudOverlayDrag?.(
- "start",
- event.screenX,
- event.screenY,
- );
+ window.electronAPI?.hudOverlayDrag?.("start", event.screenX, event.screenY);
};
- const handleHudBarPointerMove = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
+ const handleHudBarPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
const dragState = hudDragStartRef.current;
if (!dragState || dragState.pointerId !== event.pointerId) {
return;
@@ -466,14 +426,8 @@ export function LaunchWindow() {
if (dragState.mode === "webcam-preview") {
const deltaX = event.clientX - dragState.startX;
const deltaY = event.clientY - dragState.startY;
- const viewportWidth = Math.max(
- window.innerWidth,
- window.screen?.width ?? 0,
- );
- const viewportHeight = Math.max(
- window.innerHeight,
- window.screen?.height ?? 0,
- );
+ const viewportWidth = Math.max(window.innerWidth, window.screen?.width ?? 0);
+ const viewportHeight = Math.max(window.innerHeight, window.screen?.height ?? 0);
const unclampedLeft = dragState.initialLeft + deltaX;
const unclampedTop = dragState.initialTop + deltaY;
const clampedLeft = Math.min(
@@ -492,16 +446,10 @@ export function LaunchWindow() {
return;
}
- window.electronAPI?.hudOverlayDrag?.(
- "move",
- event.screenX,
- event.screenY,
- );
+ window.electronAPI?.hudOverlayDrag?.("move", event.screenX, event.screenY);
};
- const handleHudBarPointerUp = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
+ const handleHudBarPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
const dragState = hudDragStartRef.current;
if (!dragState || dragState.pointerId !== event.pointerId) {
return;
@@ -522,27 +470,20 @@ export function LaunchWindow() {
}
};
- const attachPreviewStreamToNode = useCallback(
- (videoElement: HTMLVideoElement | null) => {
- const previewStream = previewStreamRef.current;
- if (
- !videoElement ||
- !previewStream ||
- videoElement.srcObject === previewStream
- ) {
- return;
- }
+ const attachPreviewStreamToNode = useCallback((videoElement: HTMLVideoElement | null) => {
+ const previewStream = previewStreamRef.current;
+ if (!videoElement || !previewStream || videoElement.srcObject === previewStream) {
+ return;
+ }
- videoElement.srcObject = previewStream;
- const playPromise = videoElement.play();
- if (playPromise) {
- playPromise.catch(() => {
- // Ignore autoplay interruptions while the preview element mounts.
- });
- }
- },
- [],
- );
+ videoElement.srcObject = previewStream;
+ const playPromise = videoElement.play();
+ if (playPromise) {
+ playPromise.catch(() => {
+ // Ignore autoplay interruptions while the preview element mounts.
+ });
+ }
+ }, []);
const setWebcamPreviewNode = useCallback(
(node: HTMLVideoElement | null) => {
@@ -569,23 +510,21 @@ export function LaunchWindow() {
}
try {
- const previewStream = await navigator.mediaDevices.getUserMedia(
- {
- video: webcamDeviceId
- ? {
- deviceId: { exact: webcamDeviceId },
- width: { ideal: 320 },
- height: { ideal: 320 },
- frameRate: { ideal: 24, max: 30 },
- }
- : {
- width: { ideal: 320 },
- height: { ideal: 320 },
- frameRate: { ideal: 24, max: 30 },
- },
- audio: false,
- },
- );
+ const previewStream = await navigator.mediaDevices.getUserMedia({
+ video: webcamDeviceId
+ ? {
+ deviceId: { exact: webcamDeviceId },
+ width: { ideal: 320 },
+ height: { ideal: 320 },
+ frameRate: { ideal: 24, max: 30 },
+ }
+ : {
+ width: { ideal: 320 },
+ height: { ideal: 320 },
+ frameRate: { ideal: 24, max: 30 },
+ },
+ audio: false,
+ });
if (!mounted) {
previewStream.getTracks().forEach((track) => track.stop());
@@ -638,12 +577,7 @@ export function LaunchWindow() {
}
timer = setInterval(() => {
if (recordingStart) {
- setElapsed(
- Math.floor(
- (Date.now() - recordingStart - pausedTotal) /
- 1000,
- ),
- );
+ setElapsed(Math.floor((Date.now() - recordingStart - pausedTotal) / 1000));
}
}, 1000);
}
@@ -670,9 +604,7 @@ export function LaunchWindow() {
useEffect(() => {
let mounted = true;
- const applySelectedSource = (
- source: { name?: string } | null | undefined,
- ) => {
+ const applySelectedSource = (source: { name?: string } | null | undefined) => {
if (!mounted) {
return;
}
@@ -734,8 +666,7 @@ export function LaunchWindow() {
const refreshUpdateStatus = async () => {
try {
- const summary =
- await window.electronAPI.getUpdateStatusSummary();
+ const summary = await window.electronAPI.getUpdateStatusSummary();
if (mounted) {
setUpdateStatus(summary);
}
@@ -775,16 +706,12 @@ export function LaunchWindow() {
let cancelled = false;
const loadHudCaptureProtection = async () => {
try {
- const result =
- await window.electronAPI.getHudOverlayCaptureProtection();
+ const result = await window.electronAPI.getHudOverlayCaptureProtection();
if (!cancelled && result.success) {
setHideHudFromCapture(result.enabled);
}
} catch (error) {
- console.error(
- "Failed to load HUD capture protection state:",
- error,
- );
+ console.error("Failed to load HUD capture protection state:", error);
}
};
void loadHudCaptureProtection();
@@ -795,9 +722,7 @@ export function LaunchWindow() {
useEffect(() => {
const expanded =
- activeDropdown !== "none" ||
- projectBrowserOpen ||
- showRecordingWebcamPreview;
+ activeDropdown !== "none" || projectBrowserOpen || showRecordingWebcamPreview;
window.electronAPI.setHudOverlayExpanded(expanded);
return () => {
@@ -813,21 +738,10 @@ export function LaunchWindow() {
}
if (showRecordingWebcamPreview) {
- const viewportWidth = Math.max(
- window.innerWidth,
- window.screen?.width ?? 0,
- );
- const viewportHeight = Math.max(
- window.innerHeight,
- window.screen?.height ?? 0,
- );
- window.electronAPI.setHudOverlayCompactWidth(
- Math.ceil(viewportWidth),
- );
- window.electronAPI.setHudOverlayMeasuredHeight(
- Math.ceil(viewportHeight),
- true,
- );
+ const viewportWidth = Math.max(window.innerWidth, window.screen?.width ?? 0);
+ const viewportHeight = Math.max(window.innerHeight, window.screen?.height ?? 0);
+ window.electronAPI.setHudOverlayCompactWidth(Math.ceil(viewportWidth));
+ window.electronAPI.setHudOverlayMeasuredHeight(Math.ceil(viewportHeight), true);
return;
}
@@ -839,14 +753,9 @@ export function LaunchWindow() {
hudContentRect.width,
hudContent.scrollWidth,
);
- const standardHeight = Math.max(
- hudContentRect.height,
- hudContent.scrollHeight,
- );
+ const standardHeight = Math.max(hudContentRect.height, hudContent.scrollHeight);
- window.electronAPI.setHudOverlayCompactWidth(
- Math.ceil(standardWidth + 24),
- );
+ window.electronAPI.setHudOverlayCompactWidth(Math.ceil(standardWidth + 24));
window.electronAPI.setHudOverlayMeasuredHeight(
Math.ceil(standardHeight + 24),
activeDropdown !== "none" || projectBrowserOpen,
@@ -893,10 +802,7 @@ export function LaunchWindow() {
useEffect(() => {
const handleClick = (e: MouseEvent) => {
- if (
- dropdownRef.current &&
- !dropdownRef.current.contains(e.target as Node)
- ) {
+ if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
setActiveDropdown("none");
setProjectBrowserOpen(false);
}
@@ -917,15 +823,13 @@ export function LaunchWindow() {
setSources(
rawSources.map((s) => {
const isWindow = s.id.startsWith("window:");
- const type =
- s.sourceType ?? (isWindow ? "window" : "screen");
+ const type = s.sourceType ?? (isWindow ? "window" : "screen");
let displayName = s.name;
let appName = s.appName;
if (isWindow && !appName && s.name.includes(" — ")) {
const parts = s.name.split(" — ");
appName = parts[0]?.trim();
- displayName =
- parts.slice(1).join(" — ").trim() || s.name;
+ displayName = parts.slice(1).join(" — ").trim() || s.name;
} else if (isWindow && s.windowTitle) {
displayName = s.windowTitle;
}
@@ -948,9 +852,7 @@ export function LaunchWindow() {
}
}, []);
- const toggleDropdown = (
- which: "sources" | "more" | "mic" | "countdown" | "webcam",
- ) => {
+ const toggleDropdown = (which: "sources" | "more" | "mic" | "countdown" | "webcam") => {
setProjectBrowserOpen(false);
setActiveDropdown(activeDropdown === which ? "none" : which);
if (activeDropdown !== which && which === "sources") fetchSources();
@@ -963,9 +865,7 @@ export function LaunchWindow() {
setActiveDropdown("none");
window.electronAPI.showSourceHighlight?.({
...source,
- name: source.appName
- ? `${source.appName} — ${source.name}`
- : source.name,
+ name: source.appName ? `${source.appName} — ${source.name}` : source.name,
appName: source.appName,
});
};
@@ -1004,8 +904,7 @@ export function LaunchWindow() {
const openProjectFromLibrary = useCallback(async (projectPath: string) => {
try {
- const result =
- await window.electronAPI.openProjectFileAtPath(projectPath);
+ const result = await window.electronAPI.openProjectFileAtPath(projectPath);
if (result.canceled || !result.success) {
return;
}
@@ -1033,10 +932,7 @@ export function LaunchWindow() {
const nextValue = !hideHudFromCapture;
setHideHudFromCapture(nextValue);
try {
- const result =
- await window.electronAPI.setHudOverlayCaptureProtection(
- nextValue,
- );
+ const result = await window.electronAPI.setHudOverlayCaptureProtection(nextValue);
if (!result.success) {
setHideHudFromCapture(!nextValue);
return;
@@ -1067,29 +963,18 @@ export function LaunchWindow() {
const updateButtonTitle = (() => {
switch (updateStatus.status) {
case "up-to-date":
- return t(
- "recording.update.upToDateTitle",
- "Recordly {{version}} is up to date.",
- {
- version: updateStatus.currentVersion,
- },
- );
+ return t("recording.update.upToDateTitle", "Recordly {{version}} is up to date.", {
+ version: updateStatus.currentVersion,
+ });
case "available":
case "ready":
return updateStatus.availableVersion
- ? t(
- "recording.update.availableTitle",
- "Recordly {{version}} is available.",
- {
- version: updateStatus.availableVersion,
- },
- )
+ ? t("recording.update.availableTitle", "Recordly {{version}} is available.", {
+ version: updateStatus.availableVersion,
+ })
: t("recording.update.availableGenericTitle");
case "downloading":
- return (
- updateStatus.detail ??
- t("recording.update.downloadingTitle")
- );
+ return updateStatus.detail ?? t("recording.update.downloadingTitle");
case "checking":
return t("recording.update.checkingTitle");
case "error":
@@ -1105,9 +990,7 @@ export function LaunchWindow() {
return <CheckCircle2 size={14} />;
case "checking":
case "downloading":
- return (
- <RefreshCw size={14} className={styles.updateBadgeSpin} />
- );
+ return <RefreshCw size={14} className={styles.updateBadgeSpin} />;
default:
return <ArrowUpCircle size={14} />;
}
@@ -1217,10 +1100,7 @@ export function LaunchWindow() {
title={selectedSource}
>
<Monitor size={16} />
- <ContentClamp
- className={styles.sourceLabel}
- truncateLength={36}
- >
+ <ContentClamp className={styles.sourceLabel} truncateLength={36}>
{selectedSource}
</ContentClamp>
<ChevronUp
@@ -1245,11 +1125,7 @@ export function LaunchWindow() {
<IconButton
onClick={toggleWebcam}
- title={
- webcamEnabled
- ? t("recording.disableWebcam")
- : t("recording.enableWebcam")
- }
+ title={webcamEnabled ? t("recording.disableWebcam") : t("recording.enableWebcam")}
className={webcamEnabled ? styles.ibActive : ""}
>
{webcamEnabled ? <Video size={18} /> : <VideoOff size={18} />}
@@ -1268,11 +1144,7 @@ export function LaunchWindow() {
<button
type="button"
className={`${styles.recBtn} ${styles.electronNoDrag}`}
- onClick={
- hasSelectedSource
- ? toggleRecording
- : () => toggleDropdown("sources")
- }
+ onClick={hasSelectedSource ? toggleRecording : () => toggleDropdown("sources")}
disabled={countdownActive}
title={t("recording.record")}
>
@@ -1313,9 +1185,7 @@ export function LaunchWindow() {
<div
ref={hudContentRef}
className="flex flex-col items-center overflow-visible"
- onMouseEnter={() =>
- window.electronAPI?.hudOverlaySetIgnoreMouse?.(false)
- }
+ onMouseEnter={() => window.electronAPI?.hudOverlaySetIgnoreMouse?.(false)}
onMouseLeave={() => {
if (
!isHudDraggingRef.current &&
@@ -1348,9 +1218,7 @@ export function LaunchWindow() {
</div>
) : null}
{activeDropdown !== "none" && (
- <div
- className={`${styles.menuCard} ${styles.electronNoDrag}`}
- >
+ <div className={`${styles.menuCard} ${styles.electronNoDrag}`}>
{activeDropdown === "sources" && (
<>
{sourcesLoading ? (
@@ -1361,49 +1229,31 @@ export function LaunchWindow() {
<>
{screenSources.length > 0 && (
<>
- <div
- className={
- styles.ddLabel
- }
- >
+ <div className={styles.ddLabel}>
{t("recording.screens")}
</div>
- {screenSources.map(
- (source) => (
- <DropdownItem
- key={source.id}
- icon={
- <Monitor
- size={
- 16
- }
- />
- }
- selected={
- selectedSource ===
- source.name
- }
- onClick={() =>
- handleSourceSelect(
- source,
- )
- }
- >
- {source.name}
- </DropdownItem>
- ),
- )}
+ {screenSources.map((source) => (
+ <DropdownItem
+ key={source.id}
+ icon={<Monitor size={16} />}
+ selected={
+ selectedSource === source.name
+ }
+ onClick={() =>
+ handleSourceSelect(source)
+ }
+ >
+ {source.name}
+ </DropdownItem>
+ ))}
</>
)}
{windowSources.length > 0 && (
<>
<div
- className={
- styles.ddLabel
- }
+ className={styles.ddLabel}
style={
- screenSources.length >
- 0
+ screenSources.length > 0
? {
marginTop: 4,
}
@@ -1412,43 +1262,29 @@ export function LaunchWindow() {
>
{t("recording.windows")}
</div>
- {windowSources.map(
- (source) => (
- <DropdownItem
- key={source.id}
- icon={
- <AppWindow
- size={
- 16
- }
- />
- }
- selected={
- selectedSource ===
- source.name
- }
- onClick={() =>
- handleSourceSelect(
- source,
- )
- }
- >
- {source.appName &&
- source.appName !==
- source.name
- ? `${source.appName} — ${source.name}`
- : source.name}
- </DropdownItem>
- ),
- )}
+ {windowSources.map((source) => (
+ <DropdownItem
+ key={source.id}
+ icon={<AppWindow size={16} />}
+ selected={
+ selectedSource === source.name
+ }
+ onClick={() =>
+ handleSourceSelect(source)
+ }
+ >
+ {source.appName &&
+ source.appName !== source.name
+ ? `${source.appName} — ${source.name}`
+ : source.name}
+ </DropdownItem>
+ ))}
</>
)}
{screenSources.length === 0 &&
windowSources.length === 0 && (
<div className="text-center text-xs text-[#6b6b78] py-4">
- {t(
- "recording.noSourcesFound",
- )}
+ {t("recording.noSourcesFound")}
</div>
)}
</>
@@ -1471,9 +1307,7 @@ export function LaunchWindow() {
}
selected={systemAudioEnabled}
onClick={() => {
- setSystemAudioEnabled(
- !systemAudioEnabled,
- );
+ setSystemAudioEnabled(!systemAudioEnabled);
}}
>
{systemAudioEnabled
@@ -1502,19 +1336,14 @@ export function LaunchWindow() {
device={device}
selected={
microphoneEnabled &&
- (microphoneDeviceId ===
- device.deviceId ||
- selectedDeviceId ===
- device.deviceId)
+ (microphoneDeviceId === device.deviceId ||
+ selectedDeviceId === device.deviceId)
}
onSelect={() => {
setMicrophoneEnabled(true);
- setSelectedDeviceId(
- device.deviceId,
- );
+ setSelectedDeviceId(device.deviceId);
setMicrophoneDeviceId(
- device.deviceId ===
- "default"
+ device.deviceId === "default"
? undefined
: device.deviceId,
);
@@ -1531,9 +1360,7 @@ export function LaunchWindow() {
{activeDropdown === "webcam" && (
<>
- <div className={styles.ddLabel}>
- {t("recording.webcam")}
- </div>
+ <div className={styles.ddLabel}>{t("recording.webcam")}</div>
{webcamEnabled && (
<>
<DropdownItem
@@ -1553,9 +1380,7 @@ export function LaunchWindow() {
<Eye size={16} />
)
}
- selected={
- showFloatingWebcamPreview
- }
+ selected={showFloatingWebcamPreview}
onClick={() => {
setShowFloatingWebcamPreview(
(current) => !current,
@@ -1563,20 +1388,14 @@ export function LaunchWindow() {
}}
>
{showFloatingWebcamPreview
- ? t(
- "recording.hideFloatingWebcamPreview",
- )
- : t(
- "recording.showFloatingWebcamPreview",
- )}
+ ? t("recording.hideFloatingWebcamPreview")
+ : t("recording.showFloatingWebcamPreview")}
</DropdownItem>
</>
)}
{!webcamEnabled && (
<div className="px-3 py-2 text-xs text-[#6b6b78]">
- {t(
- "recording.selectWebcamToEnable",
- )}
+ {t("recording.selectWebcamToEnable")}
</div>
)}
{showWebcamControls && (
@@ -1599,10 +1418,8 @@ export function LaunchWindow() {
key={device.deviceId}
icon={
webcamEnabled &&
- (webcamDeviceId ===
- device.deviceId ||
- selectedVideoDeviceId ===
- device.deviceId) ? (
+ (webcamDeviceId === device.deviceId ||
+ selectedVideoDeviceId === device.deviceId) ? (
<Video size={16} />
) : (
<VideoOff size={16} />
@@ -1610,19 +1427,13 @@ export function LaunchWindow() {
}
selected={
webcamEnabled &&
- (webcamDeviceId ===
- device.deviceId ||
- selectedVideoDeviceId ===
- device.deviceId)
+ (webcamDeviceId === device.deviceId ||
+ selectedVideoDeviceId === device.deviceId)
}
onClick={() => {
setWebcamEnabled(true);
- setSelectedVideoDeviceId(
- device.deviceId,
- );
- setWebcamDeviceId(
- device.deviceId,
- );
+ setSelectedVideoDeviceId(device.deviceId);
+ setWebcamDeviceId(device.deviceId);
}}
>
{device.label}
@@ -1651,9 +1462,7 @@ export function LaunchWindow() {
setActiveDropdown("none");
}}
>
- {delay === 0
- ? t("recording.noDelay")
- : `${delay}s`}
+ {delay === 0 ? t("recording.noDelay") : `${delay}s`}
</DropdownItem>
))}
</>
@@ -1676,9 +1485,7 @@ export function LaunchWindow() {
}}
>
{hideHudFromCapture
- ? t(
- "recording.hideHudFromVideo",
- )
+ ? t("recording.hideHudFromVideo")
: t("recording.showHudInVideo")}
</DropdownItem>
)}
@@ -1696,16 +1503,11 @@ export function LaunchWindow() {
</DropdownItem>
<DropdownItem
icon={<FolderOpen size={16} />}
- onClick={() =>
- void openProjectBrowser()
- }
+ onClick={() => void openProjectBrowser()}
>
{t("recording.openProject")}
</DropdownItem>
- <div
- className={styles.ddLabel}
- style={{ marginTop: 4 }}
- >
+ <div className={styles.ddLabel} style={{ marginTop: 4 }}>
{t("recording.language")}
</div>
{SUPPORTED_LOCALES.map((code) => (
@@ -1760,10 +1562,7 @@ export function LaunchWindow() {
onPointerUp={handleHudBarPointerUp}
onPointerCancel={handleHudBarPointerUp}
>
- <RxDragHandleDots2
- size={14}
- className="text-[#6b6b78]"
- />
+ <RxDragHandleDots2 size={14} className="text-[#6b6b78]" />
</div>
<button
@@ -1805,9 +1604,7 @@ export function LaunchWindow() {
}}
transition={hudStateTransition}
>
- {recording
- ? recordingControls
- : idleControls}
+ {recording ? recordingControls : idleControls}
</motion.div>
</AnimatePresence>
</div>
diff --git a/src/components/launch/SourceSelector.module.css b/src/components/launch/SourceSelector.module.css
index d817be6e..79cf7853 100644
--- a/src/components/launch/SourceSelector.module.css
+++ b/src/components/launch/SourceSelector.module.css
@@ -1,71 +1,74 @@
-
.glassContainer {
- background: linear-gradient(135deg, rgba(28,28,34,0.92) 0%, rgba(18,18,22,0.88) 100%);
- backdrop-filter: blur(20px) saturate(160%);
- -webkit-backdrop-filter: blur(20px) saturate(160%);
- border-radius: 14px;
- box-shadow: 0 4px 16px 0 rgba(0,0,0,0.32), 0 1px 3px 0 rgba(0,0,0,0.18) inset;
- border: 1px solid rgba(60,60,80,0.18);
+ background: linear-gradient(135deg, rgba(28, 28, 34, 0.92) 0%, rgba(18, 18, 22, 0.88) 100%);
+ backdrop-filter: blur(20px) saturate(160%);
+ -webkit-backdrop-filter: blur(20px) saturate(160%);
+ border-radius: 14px;
+ box-shadow:
+ 0 4px 16px 0 rgba(0, 0, 0, 0.32),
+ 0 1px 3px 0 rgba(0, 0, 0, 0.18) inset;
+ border: 1px solid rgba(60, 60, 80, 0.18);
}
.sourceCard {
- border-radius: 10px;
- background: linear-gradient(120deg, rgba(38,38,48,0.98) 0%, rgba(24,24,32,0.96) 100%);
- border: 1px solid rgba(60,60,80,0.22);
- box-shadow: 0 2px 8px 0 rgba(0,0,0,0.18);
- transition: box-shadow 0.2s, border 0.2s, background 0.2s;
+ border-radius: 10px;
+ background: linear-gradient(120deg, rgba(38, 38, 48, 0.98) 0%, rgba(24, 24, 32, 0.96) 100%);
+ border: 1px solid rgba(60, 60, 80, 0.22);
+ box-shadow: 0 2px 8px 0 rgba(0, 0, 0, 0.18);
+ transition:
+ box-shadow 0.2s,
+ border 0.2s,
+ background 0.2s;
}
.selected {
- border: 2px solid #2563EB;
- background: linear-gradient(120deg, rgba(91,33,182,0.18) 0%, rgba(38,38,48,0.98) 100%);
- box-shadow: 0 0 0 2px #2563EB33;
+ border: 2px solid #2563eb;
+ background: linear-gradient(120deg, rgba(91, 33, 182, 0.18) 0%, rgba(38, 38, 48, 0.98) 100%);
+ box-shadow: 0 0 0 2px #2563eb33;
}
.icon {
- width: 13px;
- height: 13px;
- color: #c7d2fe;
+ width: 13px;
+ height: 13px;
+ color: #c7d2fe;
}
.name {
- font-size: 0.85rem;
- color: #f3f4f6;
- font-weight: 500;
- letter-spacing: 0.01em;
+ font-size: 0.85rem;
+ color: #f3f4f6;
+ font-weight: 500;
+ letter-spacing: 0.01em;
}
.cardText {
- color: #a1a1aa;
- font-size: 0.75rem;
+ color: #a1a1aa;
+ font-size: 0.75rem;
}
/* scrollbar */
.sourceGridScroll {
- scrollbar-width: thin;
- scrollbar-color: rgba(37, 99, 235, 0.5) rgba(40, 40, 50, 0.6);
+ scrollbar-width: thin;
+ scrollbar-color: rgba(37, 99, 235, 0.5) rgba(40, 40, 50, 0.6);
}
.sourceGridScroll::-webkit-scrollbar {
- width: 8px;
+ width: 8px;
}
.sourceGridScroll::-webkit-scrollbar-track {
- background: rgba(30, 30, 38, 0.5);
- border-radius: 4px;
- margin: 4px 0;
+ background: rgba(30, 30, 38, 0.5);
+ border-radius: 4px;
+ margin: 4px 0;
}
.sourceGridScroll::-webkit-scrollbar-thumb {
- background: rgba(80, 80, 100, 0.6);
- border-radius: 4px;
+ background: rgba(80, 80, 100, 0.6);
+ border-radius: 4px;
}
.sourceGridScroll::-webkit-scrollbar-thumb:hover {
- background: rgba(37, 99, 235, 0.6);
+ background: rgba(37, 99, 235, 0.6);
}
.sourceGridScroll::-webkit-scrollbar-thumb:active {
- background: rgba(37, 99, 235, 0.8);
+ background: rgba(37, 99, 235, 0.8);
}
-
diff --git a/src/components/launch/SourceSelector.tsx b/src/components/launch/SourceSelector.tsx
index 9b98e329..b9929695 100644
--- a/src/components/launch/SourceSelector.tsx
+++ b/src/components/launch/SourceSelector.tsx
@@ -1,245 +1,286 @@
-import { useState, useEffect } from "react";
-import { Button } from "../ui/button";
+import { useEffect, useState } from "react";
import { MdCheck } from "react-icons/md";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
-import { Card } from "../ui/card";
import { useScopedT } from "../../contexts/I18nContext";
+import { Button } from "../ui/button";
+import { Card } from "../ui/card";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
import styles from "./SourceSelector.module.css";
interface DesktopSource {
- id: string;
- name: string;
- thumbnail: string | null;
- display_id: string;
- appIcon: string | null;
- originalName: string;
- sourceType: 'screen' | 'window';
- appName?: string;
- windowTitle?: string;
+ id: string;
+ name: string;
+ thumbnail: string | null;
+ display_id: string;
+ appIcon: string | null;
+ originalName: string;
+ sourceType: "screen" | "window";
+ appName?: string;
+ windowTitle?: string;
}
function parseSourceMetadata(source: ProcessedDesktopSource) {
- if (source.sourceType === 'window' && (source.appName || source.windowTitle)) {
- return {
- sourceType: 'window' as const,
- appName: source.appName,
- windowTitle: source.windowTitle ?? source.name,
- displayName: source.windowTitle ?? source.name,
- };
- }
+ if (source.sourceType === "window" && (source.appName || source.windowTitle)) {
+ return {
+ sourceType: "window" as const,
+ appName: source.appName,
+ windowTitle: source.windowTitle ?? source.name,
+ displayName: source.windowTitle ?? source.name,
+ };
+ }
- const sourceType: 'screen' | 'window' = source.id.startsWith('window:') ? 'window' : 'screen';
- if (sourceType === 'window') {
- const [appNamePart, ...windowTitleParts] = source.name.split(' — ');
- const appName = appNamePart?.trim() || undefined;
- const windowTitle = windowTitleParts.join(' — ').trim() || source.name.trim();
+ const sourceType: "screen" | "window" = source.id.startsWith("window:") ? "window" : "screen";
+ if (sourceType === "window") {
+ const [appNamePart, ...windowTitleParts] = source.name.split(" — ");
+ const appName = appNamePart?.trim() || undefined;
+ const windowTitle = windowTitleParts.join(" — ").trim() || source.name.trim();
- return {
- sourceType,
- appName,
- windowTitle,
- displayName: windowTitle,
- };
- }
+ return {
+ sourceType,
+ appName,
+ windowTitle,
+ displayName: windowTitle,
+ };
+ }
- return {
- sourceType,
- appName: undefined,
- windowTitle: undefined,
- displayName: source.name,
- };
+ return {
+ sourceType,
+ appName: undefined,
+ windowTitle: undefined,
+ displayName: source.name,
+ };
}
export function SourceSelector() {
- const t = useScopedT('launch');
- const [sources, setSources] = useState<DesktopSource[]>([]);
- const [selectedSource, setSelectedSource] = useState<DesktopSource | null>(null);
- const [activeTab, setActiveTab] = useState<'screens' | 'windows'>('screens');
- const [loading, setLoading] = useState(true);
+ const t = useScopedT("launch");
+ const [sources, setSources] = useState<DesktopSource[]>([]);
+ const [selectedSource, setSelectedSource] = useState<DesktopSource | null>(null);
+ const [activeTab, setActiveTab] = useState<"screens" | "windows">("screens");
+ const [loading, setLoading] = useState(true);
- useEffect(() => {
- async function fetchSources() {
- setLoading(true);
- try {
- const rawSources = await window.electronAPI.getSources({
- types: ['screen', 'window'],
- thumbnailSize: { width: 320, height: 180 },
- fetchWindowIcons: true
- });
- setSources(
- rawSources.map(source => {
- const metadata = parseSourceMetadata(source);
+ useEffect(() => {
+ async function fetchSources() {
+ setLoading(true);
+ try {
+ const rawSources = await window.electronAPI.getSources({
+ types: ["screen", "window"],
+ thumbnailSize: { width: 320, height: 180 },
+ fetchWindowIcons: true,
+ });
+ setSources(
+ rawSources.map((source) => {
+ const metadata = parseSourceMetadata(source);
- return {
- id: source.id,
- name: metadata.displayName,
- thumbnail: source.thumbnail,
- display_id: source.display_id,
- appIcon: source.appIcon,
- originalName: source.name,
- sourceType: metadata.sourceType,
- appName: metadata.appName,
- windowTitle: metadata.windowTitle,
- };
- })
- );
- } catch (error) {
- console.error('Error loading sources:', error);
- } finally {
- setLoading(false);
- }
- }
- fetchSources();
- }, []);
+ return {
+ id: source.id,
+ name: metadata.displayName,
+ thumbnail: source.thumbnail,
+ display_id: source.display_id,
+ appIcon: source.appIcon,
+ originalName: source.name,
+ sourceType: metadata.sourceType,
+ appName: metadata.appName,
+ windowTitle: metadata.windowTitle,
+ };
+ }),
+ );
+ } catch (error) {
+ console.error("Error loading sources:", error);
+ } finally {
+ setLoading(false);
+ }
+ }
+ fetchSources();
+ }, []);
- const screenSources = sources.filter(s => s.id.startsWith('screen:'));
- const windowSources = sources.filter(s => s.id.startsWith('window:'));
+ const screenSources = sources.filter((s) => s.id.startsWith("screen:"));
+ const windowSources = sources.filter((s) => s.id.startsWith("window:"));
- useEffect(() => {
- if (loading) {
- return;
- }
+ useEffect(() => {
+ if (loading) {
+ return;
+ }
- if (screenSources.length === 0 && windowSources.length > 0) {
- setActiveTab('windows');
- return;
- }
+ if (screenSources.length === 0 && windowSources.length > 0) {
+ setActiveTab("windows");
+ return;
+ }
- if (windowSources.length === 0 && screenSources.length > 0) {
- setActiveTab('screens');
- }
- }, [loading, screenSources.length, windowSources.length]);
+ if (windowSources.length === 0 && screenSources.length > 0) {
+ setActiveTab("screens");
+ }
+ }, [loading, screenSources.length, windowSources.length]);
- const handleSourceSelect = (source: DesktopSource) => setSelectedSource(source);
- const handleShare = async () => {
- if (selectedSource) await window.electronAPI.selectSource(selectedSource);
- };
+ const handleSourceSelect = (source: DesktopSource) => setSelectedSource(source);
+ const handleShare = async () => {
+ if (selectedSource) await window.electronAPI.selectSource(selectedSource);
+ };
- if (loading) {
- return (
- <div className={`h-full flex items-center justify-center ${styles.glassContainer}`} style={{ minHeight: '100vh' }}>
- <div className="text-center">
- <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-zinc-600 mx-auto mb-2" />
- <p className="text-xs text-zinc-300">{t('sourceSelector.loadingSources')}</p>
- </div>
- </div>
- );
- }
+ if (loading) {
+ return (
+ <div
+ className={`h-full flex items-center justify-center ${styles.glassContainer}`}
+ style={{ minHeight: "100vh" }}
+ >
+ <div className="text-center">
+ <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-zinc-600 mx-auto mb-2" />
+ <p className="text-xs text-zinc-300">{t("sourceSelector.loadingSources")}</p>
+ </div>
+ </div>
+ );
+ }
- return (
- <div className={`min-h-screen flex flex-col items-center justify-center ${styles.glassContainer}`}>
- <div className="flex-1 flex flex-col w-full max-w-xl" style={{ padding: 0 }}>
- <Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'screens' | 'windows')}>
- <TabsList className="grid grid-cols-2 mb-3 bg-zinc-900/40 rounded-full">
- <TabsTrigger value="screens" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-zinc-200 rounded-full text-xs py-1">
- {t('sourceSelector.screens')} ({screenSources.length})
- </TabsTrigger>
- <TabsTrigger value="windows" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-zinc-200 rounded-full text-xs py-1">
- {t('sourceSelector.windows')} ({windowSources.length})
- </TabsTrigger>
- </TabsList>
- <div className="h-72 flex flex-col justify-stretch">
- <TabsContent value="screens" className="h-full">
- <div className={`grid grid-cols-2 gap-2 h-full overflow-y-auto pr-1 relative ${styles.sourceGridScroll}`}>
- {screenSources.length === 0 && (
- <div className="col-span-2 text-center text-xs text-zinc-500 py-8">No screens available</div>
- )}
- {screenSources.map(source => (
- <Card
- key={source.id}
- className={`${styles.sourceCard} ${selectedSource?.id === source.id ? styles.selected : ''} cursor-pointer h-fit p-2 scale-95`}
- style={{ margin: 8, width: '90%', maxWidth: 220 }}
- onClick={() => handleSourceSelect(source)}
- >
- <div className="p-1">
- <div className="relative mb-1">
- <img
- src={source.thumbnail || ''}
- alt={source.name}
- className="w-full aspect-video object-cover rounded border border-zinc-800"
- />
- {selectedSource?.id === source.id && (
- <div className="absolute -top-1 -right-1">
- <div className="w-4 h-4 bg-[#2563EB] rounded-full flex items-center justify-center shadow-md">
- <MdCheck className={styles.icon} />
- </div>
- </div>
- )}
- </div>
- <div className={styles.name + " truncate"}>{source.name}</div>
- </div>
- </Card>
- ))}
- </div>
- </TabsContent>
- <TabsContent value="windows" className="h-full">
- <p className="text-[10px] text-zinc-500 mb-1 px-1">{t('sourceSelector.windowsNote')}</p>
- <div className={`grid grid-cols-2 gap-2 h-full overflow-y-auto pr-1 relative ${styles.sourceGridScroll}`}>
- {windowSources.length === 0 && (
- <div className="col-span-2 text-center text-xs text-zinc-500 py-8">No windows available</div>
- )}
- {windowSources.map(source => (
- <Card
- key={source.id}
- className={`${styles.sourceCard} ${selectedSource?.id === source.id ? styles.selected : ''} cursor-pointer h-fit p-2 scale-95`}
- style={{ margin: 8, width: '90%', maxWidth: 220 }}
- onClick={() => handleSourceSelect(source)}
- >
- <div className="p-1">
- <div className="relative mb-1">
- {source.thumbnail ? (
- <img
- src={source.thumbnail}
- alt={source.name}
- className="w-full aspect-video object-cover rounded border border-gray-700"
- />
- ) : (
- <div className="w-full aspect-video rounded border border-gray-700 bg-zinc-900/80 flex flex-col items-center justify-center text-zinc-400 gap-2">
- {source.appIcon ? (
- <img
- src={source.appIcon}
- alt="App icon"
- className="w-8 h-8 rounded-md"
- />
- ) : (
- <div className="w-8 h-8 rounded-md bg-zinc-800 border border-zinc-700" />
- )}
- <div className="text-[10px] uppercase tracking-[0.2em] text-zinc-500">{t('sourceSelector.windowPlaceholder')}</div>
- </div>
- )}
- {selectedSource?.id === source.id && (
- <div className="absolute -top-1 -right-1">
- <div className="w-4 h-4 bg-blue-600 rounded-full flex items-center justify-center shadow-md">
- <MdCheck className={styles.icon} />
- </div>
- </div>
- )}
- </div>
- <div className="flex items-center gap-1">
- {source.appIcon && (
- <img
- src={source.appIcon}
- alt="App icon"
- className={styles.icon + " flex-shrink-0"}
- />
- )}
- <div className={styles.name + " truncate"}>{source.name}</div>
- </div>
- </div>
- </Card>
- ))}
- </div>
- </TabsContent>
- </div>
- </Tabs>
- </div>
- <div className="border-t border-zinc-800 p-2 w-full max-w-xl">
- <div className="flex justify-center gap-2">
- <Button variant="outline" onClick={() => window.close()} className="px-4 py-1 text-xs bg-zinc-800 border-zinc-700 text-zinc-200 hover:bg-zinc-700">{t('sourceSelector.cancel')}</Button>
- <Button onClick={handleShare} disabled={!selectedSource} className="px-4 py-1 text-xs bg-[#2563EB] text-white hover:bg-[#2563EB]/80 disabled:opacity-50 disabled:bg-zinc-700">{t('sourceSelector.share')}</Button>
- </div>
- </div>
- </div>
- );
+ return (
+ <div
+ className={`min-h-screen flex flex-col items-center justify-center ${styles.glassContainer}`}
+ >
+ <div className="flex-1 flex flex-col w-full max-w-xl" style={{ padding: 0 }}>
+ <Tabs
+ value={activeTab}
+ onValueChange={(value) => setActiveTab(value as "screens" | "windows")}
+ >
+ <TabsList className="grid grid-cols-2 mb-3 bg-zinc-900/40 rounded-full">
+ <TabsTrigger
+ value="screens"
+ className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-zinc-200 rounded-full text-xs py-1"
+ >
+ {t("sourceSelector.screens")} ({screenSources.length})
+ </TabsTrigger>
+ <TabsTrigger
+ value="windows"
+ className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-zinc-200 rounded-full text-xs py-1"
+ >
+ {t("sourceSelector.windows")} ({windowSources.length})
+ </TabsTrigger>
+ </TabsList>
+ <div className="h-72 flex flex-col justify-stretch">
+ <TabsContent value="screens" className="h-full">
+ <div
+ className={`grid grid-cols-2 gap-2 h-full overflow-y-auto pr-1 relative ${styles.sourceGridScroll}`}
+ >
+ {screenSources.length === 0 && (
+ <div className="col-span-2 text-center text-xs text-zinc-500 py-8">
+ No screens available
+ </div>
+ )}
+ {screenSources.map((source) => (
+ <Card
+ key={source.id}
+ className={`${styles.sourceCard} ${selectedSource?.id === source.id ? styles.selected : ""} cursor-pointer h-fit p-2 scale-95`}
+ style={{ margin: 8, width: "90%", maxWidth: 220 }}
+ onClick={() => handleSourceSelect(source)}
+ >
+ <div className="p-1">
+ <div className="relative mb-1">
+ <img
+ src={source.thumbnail || ""}
+ alt={source.name}
+ className="w-full aspect-video object-cover rounded border border-zinc-800"
+ />
+ {selectedSource?.id === source.id && (
+ <div className="absolute -top-1 -right-1">
+ <div className="w-4 h-4 bg-[#2563EB] rounded-full flex items-center justify-center shadow-md">
+ <MdCheck className={styles.icon} />
+ </div>
+ </div>
+ )}
+ </div>
+ <div className={styles.name + " truncate"}>
+ {source.name}
+ </div>
+ </div>
+ </Card>
+ ))}
+ </div>
+ </TabsContent>
+ <TabsContent value="windows" className="h-full">
+ <p className="text-[10px] text-zinc-500 mb-1 px-1">
+ {t("sourceSelector.windowsNote")}
+ </p>
+ <div
+ className={`grid grid-cols-2 gap-2 h-full overflow-y-auto pr-1 relative ${styles.sourceGridScroll}`}
+ >
+ {windowSources.length === 0 && (
+ <div className="col-span-2 text-center text-xs text-zinc-500 py-8">
+ No windows available
+ </div>
+ )}
+ {windowSources.map((source) => (
+ <Card
+ key={source.id}
+ className={`${styles.sourceCard} ${selectedSource?.id === source.id ? styles.selected : ""} cursor-pointer h-fit p-2 scale-95`}
+ style={{ margin: 8, width: "90%", maxWidth: 220 }}
+ onClick={() => handleSourceSelect(source)}
+ >
+ <div className="p-1">
+ <div className="relative mb-1">
+ {source.thumbnail ? (
+ <img
+ src={source.thumbnail}
+ alt={source.name}
+ className="w-full aspect-video object-cover rounded border border-gray-700"
+ />
+ ) : (
+ <div className="w-full aspect-video rounded border border-gray-700 bg-zinc-900/80 flex flex-col items-center justify-center text-zinc-400 gap-2">
+ {source.appIcon ? (
+ <img
+ src={source.appIcon}
+ alt="App icon"
+ className="w-8 h-8 rounded-md"
+ />
+ ) : (
+ <div className="w-8 h-8 rounded-md bg-zinc-800 border border-zinc-700" />
+ )}
+ <div className="text-[10px] uppercase tracking-[0.2em] text-zinc-500">
+ {t("sourceSelector.windowPlaceholder")}
+ </div>
+ </div>
+ )}
+ {selectedSource?.id === source.id && (
+ <div className="absolute -top-1 -right-1">
+ <div className="w-4 h-4 bg-blue-600 rounded-full flex items-center justify-center shadow-md">
+ <MdCheck className={styles.icon} />
+ </div>
+ </div>
+ )}
+ </div>
+ <div className="flex items-center gap-1">
+ {source.appIcon && (
+ <img
+ src={source.appIcon}
+ alt="App icon"
+ className={styles.icon + " flex-shrink-0"}
+ />
+ )}
+ <div className={styles.name + " truncate"}>
+ {source.name}
+ </div>
+ </div>
+ </div>
+ </Card>
+ ))}
+ </div>
+ </TabsContent>
+ </div>
+ </Tabs>
+ </div>
+ <div className="border-t border-zinc-800 p-2 w-full max-w-xl">
+ <div className="flex justify-center gap-2">
+ <Button
+ variant="outline"
+ onClick={() => window.close()}
+ className="px-4 py-1 text-xs bg-zinc-800 border-zinc-700 text-zinc-200 hover:bg-zinc-700"
+ >
+ {t("sourceSelector.cancel")}
+ </Button>
+ <Button
+ onClick={handleShare}
+ disabled={!selectedSource}
+ className="px-4 py-1 text-xs bg-[#2563EB] text-white hover:bg-[#2563EB]/80 disabled:opacity-50 disabled:bg-zinc-700"
+ >
+ {t("sourceSelector.share")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ );
}
-
diff --git a/src/components/launch/UpdateToastWindow.tsx b/src/components/launch/UpdateToastWindow.tsx
index 100a2339..cb293129 100644
--- a/src/components/launch/UpdateToastWindow.tsx
+++ b/src/components/launch/UpdateToastWindow.tsx
@@ -1,4 +1,9 @@
-import { AlertCircle, Download, LoaderCircle, Rocket } from "lucide-react";
+import {
+ DownloadSimple as Download,
+ Rocket,
+ Spinner as LoaderCircle,
+ WarningCircle as AlertCircle,
+} from "@phosphor-icons/react";
import { useEffect, useRef, useState } from "react";
type UpdateToastPayload = {
@@ -95,13 +100,19 @@ export function UpdateToastWindow() {
}, []);
useEffect(() => {
+ if (payload) {
+ void payload.phase;
+ void payload.version;
+ void payload.progressPercent;
+ }
+
setDragOffsetX(0);
dragState.current = {
pointerId: null,
startX: 0,
active: false,
};
- }, [payload?.phase, payload?.version, payload?.progressPercent]);
+ }, [payload]);
const cardStyle = {
background: "#0d1117",
@@ -251,14 +262,20 @@ export function UpdateToastWindow() {
event.currentTarget.setPointerCapture(event.pointerId);
}}
onPointerMove={(event) => {
- if (!dragState.current.active || dragState.current.pointerId !== event.pointerId) {
+ if (
+ !dragState.current.active ||
+ dragState.current.pointerId !== event.pointerId
+ ) {
return;
}
setDragOffsetX(event.clientX - dragState.current.startX);
}}
onPointerUp={async (event) => {
- if (!dragState.current.active || dragState.current.pointerId !== event.pointerId) {
+ if (
+ !dragState.current.active ||
+ dragState.current.pointerId !== event.pointerId
+ ) {
return;
}
@@ -287,7 +304,9 @@ export function UpdateToastWindow() {
>
<div style={iconBoxStyle}>
{payload.phase === "available" ? <Download size={20} /> : null}
- {payload.phase === "downloading" ? <LoaderCircle size={20} className="animate-spin" /> : null}
+ {payload.phase === "downloading" ? (
+ <LoaderCircle size={20} className="animate-spin" />
+ ) : null}
{payload.phase === "ready" ? <Rocket size={20} /> : null}
{payload.phase === "error" ? <AlertCircle size={20} /> : null}
</div>
@@ -295,7 +314,19 @@ export function UpdateToastWindow() {
<div style={{ display: "flex", alignItems: "center", gap: 8 }}>
<p style={titleStyle}>{getToastTitle(payload)}</p>
{payload.isPreview ? (
- <span style={{ borderRadius: 999, border: "1px solid rgba(125, 211, 252, 0.2)", background: "rgba(125, 211, 252, 0.1)", padding: "2px 8px", fontSize: 10, fontWeight: 700, letterSpacing: "0.18em", textTransform: "uppercase", color: "#bae6fd" }}>
+ <span
+ style={{
+ borderRadius: 999,
+ border: "1px solid rgba(125, 211, 252, 0.2)",
+ background: "rgba(125, 211, 252, 0.1)",
+ padding: "2px 8px",
+ fontSize: 10,
+ fontWeight: 700,
+ letterSpacing: "0.18em",
+ textTransform: "uppercase",
+ color: "#bae6fd",
+ }}
+ >
Dev
</span>
) : null}
@@ -304,12 +335,33 @@ export function UpdateToastWindow() {
{payload.phase === "downloading" ? (
<div style={{ marginTop: 12 }}>
- <div style={{ height: 8, overflow: "hidden", borderRadius: 999, background: "rgba(255, 255, 255, 0.1)" }}>
+ <div
+ style={{
+ height: 8,
+ overflow: "hidden",
+ borderRadius: 999,
+ background: "rgba(255, 255, 255, 0.1)",
+ }}
+ >
<div
- style={{ height: "100%", borderRadius: 999, background: "#7dd3fc", width: `${normalizedProgress}%` }}
+ style={{
+ height: "100%",
+ borderRadius: 999,
+ background: "#7dd3fc",
+ width: `${normalizedProgress}%`,
+ }}
/>
</div>
- <p style={{ margin: "8px 0 0 0", color: "rgba(224, 242, 254, 0.9)", fontSize: 12, fontWeight: 600 }}>{normalizedProgress}% downloaded</p>
+ <p
+ style={{
+ margin: "8px 0 0 0",
+ color: "rgba(224, 242, 254, 0.9)",
+ fontSize: 12,
+ fontWeight: 600,
+ }}
+ >
+ {normalizedProgress}% downloaded
+ </p>
</div>
) : null}
@@ -386,4 +438,4 @@ export function UpdateToastWindow() {
</div>
</div>
);
-}
\ No newline at end of file
+}
diff --git a/src/components/ui/accordion.tsx b/src/components/ui/accordion.tsx
index 8c106859..3ac6a39f 100644
--- a/src/components/ui/accordion.tsx
+++ b/src/components/ui/accordion.tsx
@@ -1,56 +1,55 @@
-import * as React from "react"
-import * as AccordionPrimitive from "@radix-ui/react-accordion"
-import { ChevronDown } from "lucide-react"
+import * as AccordionPrimitive from "@radix-ui/react-accordion";
+import { CaretDown as ChevronDown } from "@phosphor-icons/react";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
-const Accordion = AccordionPrimitive.Root
+const Accordion = AccordionPrimitive.Root;
const AccordionItem = React.forwardRef<
- React.ElementRef<typeof AccordionPrimitive.Item>,
- React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
+ React.ElementRef<typeof AccordionPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Item>
>(({ className, ...props }, ref) => (
- <AccordionPrimitive.Item
- ref={ref}
- className={cn("border-b border-white/5", className)}
- {...props}
- />
-))
-AccordionItem.displayName = "AccordionItem"
+ <AccordionPrimitive.Item
+ ref={ref}
+ className={cn("border-b border-white/5", className)}
+ {...props}
+ />
+));
+AccordionItem.displayName = "AccordionItem";
const AccordionTrigger = React.forwardRef<
- React.ElementRef<typeof AccordionPrimitive.Trigger>,
- React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
+ React.ElementRef<typeof AccordionPrimitive.Trigger>,
+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
- <AccordionPrimitive.Header className="flex">
- <AccordionPrimitive.Trigger
- ref={ref}
- className={cn(
- "flex flex-1 items-center justify-between py-3 text-sm font-medium text-slate-200 transition-all hover:text-white [&[data-state=open]>svg]:rotate-180",
- className
- )}
- {...props}
- >
- {children}
- <ChevronDown className="h-4 w-4 shrink-0 text-slate-400 transition-transform duration-200" />
- </AccordionPrimitive.Trigger>
- </AccordionPrimitive.Header>
-))
-AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName
+ <AccordionPrimitive.Header className="flex">
+ <AccordionPrimitive.Trigger
+ ref={ref}
+ className={cn(
+ "flex flex-1 items-center justify-between py-3 text-sm font-medium text-slate-200 transition-all hover:text-white [&[data-state=open]>svg]:rotate-180",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronDown className="h-4 w-4 shrink-0 text-slate-400 transition-transform duration-200" />
+ </AccordionPrimitive.Trigger>
+ </AccordionPrimitive.Header>
+));
+AccordionTrigger.displayName = AccordionPrimitive.Trigger.displayName;
const AccordionContent = React.forwardRef<
- React.ElementRef<typeof AccordionPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
+ React.ElementRef<typeof AccordionPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof AccordionPrimitive.Content>
>(({ className, children, ...props }, ref) => (
- <AccordionPrimitive.Content
- ref={ref}
- className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
- {...props}
- >
- <div className={cn("pb-4 pt-0", className)}>{children}</div>
- </AccordionPrimitive.Content>
-))
-AccordionContent.displayName = AccordionPrimitive.Content.displayName
-
-export { Accordion, AccordionItem, AccordionTrigger, AccordionContent }
+ <AccordionPrimitive.Content
+ ref={ref}
+ className="overflow-hidden text-sm data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down"
+ {...props}
+ >
+ <div className={cn("pb-4 pt-0", className)}>{children}</div>
+ </AccordionPrimitive.Content>
+));
+AccordionContent.displayName = AccordionPrimitive.Content.displayName;
+export { Accordion, AccordionItem, AccordionTrigger, AccordionContent };
diff --git a/src/components/ui/audio-level-meter.tsx b/src/components/ui/audio-level-meter.tsx
index d5b209d2..55e4bd1e 100644
--- a/src/components/ui/audio-level-meter.tsx
+++ b/src/components/ui/audio-level-meter.tsx
@@ -1,37 +1,37 @@
interface AudioLevelMeterProps {
- level: number;
- className?: string;
+ level: number;
+ className?: string;
}
const bars = [
- { threshold: 10, height: '30%' },
- { threshold: 25, height: '45%' },
- { threshold: 45, height: '60%' },
- { threshold: 65, height: '75%' },
- { threshold: 85, height: '90%' },
-]
+ { threshold: 10, height: "30%" },
+ { threshold: 25, height: "45%" },
+ { threshold: 45, height: "60%" },
+ { threshold: 65, height: "75%" },
+ { threshold: 85, height: "90%" },
+];
function getBarColor(level: number, threshold: number) {
- if (!level || level < threshold) return 'bg-slate-700'
- if (threshold > 80) return 'bg-red-500'
- if (threshold > 60) return 'bg-yellow-500'
- if (threshold > 40) return 'bg-blue-500'
- return 'bg-blue-400'
+ if (!level || level < threshold) return "bg-slate-700";
+ if (threshold > 80) return "bg-red-500";
+ if (threshold > 60) return "bg-yellow-500";
+ if (threshold > 40) return "bg-blue-500";
+ return "bg-blue-400";
}
-export function AudioLevelMeter({ level, className = '' }: AudioLevelMeterProps) {
- return (
- <div className={`flex items-end justify-between gap-1.5 h-6 ${className}`}>
- {bars.map((bar, index) => (
- <div
- key={index}
- className={`flex-1 rounded-sm transition-all duration-100 ease-out ${getBarColor(level, bar.threshold)}`}
- style={{
- height: level >= bar.threshold ? bar.height : '15%',
- opacity: level >= bar.threshold ? 1 : 0.4,
- }}
- />
- ))}
- </div>
- )
+export function AudioLevelMeter({ level, className = "" }: AudioLevelMeterProps) {
+ return (
+ <div className={`flex items-end justify-between gap-1.5 h-6 ${className}`}>
+ {bars.map((bar, index) => (
+ <div
+ key={index}
+ className={`flex-1 rounded-sm transition-all duration-100 ease-out ${getBarColor(level, bar.threshold)}`}
+ style={{
+ height: level >= bar.threshold ? bar.height : "15%",
+ opacity: level >= bar.threshold ? 1 : 0.4,
+ }}
+ />
+ ))}
+ </div>
+ );
}
diff --git a/src/components/ui/button.tsx b/src/components/ui/button.tsx
index 266f0e09..8dc9d07c 100644
--- a/src/components/ui/button.tsx
+++ b/src/components/ui/button.tsx
@@ -1,58 +1,55 @@
-import * as React from "react"
-import { Slot } from "@radix-ui/react-slot"
-import { cva, type VariantProps } from "class-variance-authority"
+import { Slot } from "@radix-ui/react-slot";
+import { cva, type VariantProps } from "class-variance-authority";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
const buttonVariants = cva(
- "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
- {
- variants: {
- variant: {
- default:
- "bg-primary text-primary-foreground shadow hover:bg-primary/90",
- destructive:
- "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
- outline:
- "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
- secondary:
- "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
- ghost: "hover:bg-accent hover:text-accent-foreground",
- link: "text-primary underline-offset-4 hover:underline",
- },
- size: {
- default: "h-9 px-4 py-2",
- sm: "h-8 rounded-md px-3 text-xs",
- lg: "h-10 rounded-md px-8",
- icon: "h-9 w-9",
- },
- },
- defaultVariants: {
- variant: "default",
- size: "default",
- },
- }
-)
+ "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
+ {
+ variants: {
+ variant: {
+ default: "bg-primary text-primary-foreground shadow hover:bg-primary/90",
+ destructive:
+ "bg-destructive text-destructive-foreground shadow-sm hover:bg-destructive/90",
+ outline:
+ "border border-input bg-background shadow-sm hover:bg-accent hover:text-accent-foreground",
+ secondary: "bg-secondary text-secondary-foreground shadow-sm hover:bg-secondary/80",
+ ghost: "hover:bg-accent hover:text-accent-foreground",
+ link: "text-primary underline-offset-4 hover:underline",
+ },
+ size: {
+ default: "h-9 px-4 py-2",
+ sm: "h-8 rounded-md px-3 text-xs",
+ lg: "h-10 rounded-md px-8",
+ icon: "h-9 w-9",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
export interface ButtonProps
- extends React.ButtonHTMLAttributes<HTMLButtonElement>,
- VariantProps<typeof buttonVariants> {
- asChild?: boolean
+ extends React.ButtonHTMLAttributes<HTMLButtonElement>,
+ VariantProps<typeof buttonVariants> {
+ asChild?: boolean;
}
const Button = React.forwardRef<HTMLButtonElement, ButtonProps>(
- ({ className, variant, size, asChild = false, ...props }, ref) => {
- const Comp = asChild ? Slot : "button"
- return (
- <Comp
- className={cn(buttonVariants({ variant, size, className }))}
- ref={ref}
- {...props}
- />
- )
- }
-)
-Button.displayName = "Button"
-
-export { Button, buttonVariants }
+ ({ className, variant, size, asChild = false, ...props }, ref) => {
+ const Comp = asChild ? Slot : "button";
+ return (
+ <Comp
+ className={cn(buttonVariants({ variant, size, className }))}
+ ref={ref}
+ {...props}
+ />
+ );
+ },
+);
+Button.displayName = "Button";
+export { Button, buttonVariants };
diff --git a/src/components/ui/card.tsx b/src/components/ui/card.tsx
index d7ca9454..2935ed46 100644
--- a/src/components/ui/card.tsx
+++ b/src/components/ui/card.tsx
@@ -1,77 +1,55 @@
-import * as React from "react"
-
-import { cn } from "@/lib/utils"
-
-const Card = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div
- ref={ref}
- className={cn(
- "rounded-xl border bg-card text-card-foreground shadow",
- className
- )}
- {...props}
- />
-))
-Card.displayName = "Card"
-
-const CardHeader = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div
- ref={ref}
- className={cn("flex flex-col space-y-1.5 p-6", className)}
- {...props}
- />
-))
-CardHeader.displayName = "CardHeader"
-
-const CardTitle = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div
- ref={ref}
- className={cn("font-semibold leading-none tracking-tight", className)}
- {...props}
- />
-))
-CardTitle.displayName = "CardTitle"
-
-const CardDescription = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div
- ref={ref}
- className={cn("text-sm text-muted-foreground", className)}
- {...props}
- />
-))
-CardDescription.displayName = "CardDescription"
-
-const CardContent = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
-))
-CardContent.displayName = "CardContent"
-
-const CardFooter = React.forwardRef<
- HTMLDivElement,
- React.HTMLAttributes<HTMLDivElement>
->(({ className, ...props }, ref) => (
- <div
- ref={ref}
- className={cn("flex items-center p-6 pt-0", className)}
- {...props}
- />
-))
-CardFooter.displayName = "CardFooter"
-
-export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent }
-
+import * as React from "react";
+
+import { cn } from "@/lib/utils";
+
+const Card = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ className={cn("rounded-xl border bg-card text-card-foreground shadow", className)}
+ {...props}
+ />
+ ),
+);
+Card.displayName = "Card";
+
+const CardHeader = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div ref={ref} className={cn("flex flex-col space-y-1.5 p-6", className)} {...props} />
+ ),
+);
+CardHeader.displayName = "CardHeader";
+
+const CardTitle = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div
+ ref={ref}
+ className={cn("font-semibold leading-none tracking-tight", className)}
+ {...props}
+ />
+ ),
+);
+CardTitle.displayName = "CardTitle";
+
+const CardDescription = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div ref={ref} className={cn("text-sm text-muted-foreground", className)} {...props} />
+ ),
+);
+CardDescription.displayName = "CardDescription";
+
+const CardContent = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div ref={ref} className={cn("p-6 pt-0", className)} {...props} />
+ ),
+);
+CardContent.displayName = "CardContent";
+
+const CardFooter = React.forwardRef<HTMLDivElement, React.HTMLAttributes<HTMLDivElement>>(
+ ({ className, ...props }, ref) => (
+ <div ref={ref} className={cn("flex items-center p-6 pt-0", className)} {...props} />
+ ),
+);
+CardFooter.displayName = "CardFooter";
+
+export { Card, CardHeader, CardFooter, CardTitle, CardDescription, CardContent };
diff --git a/src/components/ui/content-clamp.tsx b/src/components/ui/content-clamp.tsx
index 4435e9ec..c0600c19 100644
--- a/src/components/ui/content-clamp.tsx
+++ b/src/components/ui/content-clamp.tsx
@@ -1,87 +1,81 @@
-"use client"
-
-import * as React from "react"
-
-import { cn } from "@/lib/utils"
-import { Popover, PopoverArrow, PopoverContent, PopoverTrigger } from "./popover"
-
-interface ContentClampProps extends React.HTMLAttributes<HTMLDivElement> {
- children: React.ReactNode
- truncateLength?: number
-}
-
-function ContentClamp({
- children,
- className,
- truncateLength = 50,
- ...props
-}: ContentClampProps) {
- const text = typeof children === "string" ? children : String(children ?? "")
- const isTruncated = text.length > truncateLength
-
- const [open, setOpen] = React.useState(false)
- const timeoutRef = React.useRef<NodeJS.Timeout | null>(null)
-
- const handleMouseEnter = () => {
- if (timeoutRef.current) {
- clearTimeout(timeoutRef.current)
- timeoutRef.current = null
- }
- setOpen(true)
- }
-
- const handleMouseLeave = () => {
- timeoutRef.current = setTimeout(() => {
- setOpen(false)
- }, 100)
- }
-
- React.useEffect(() => {
- return () => {
- if (timeoutRef.current) {
- clearTimeout(timeoutRef.current)
- }
- }
- }, [])
-
- if (!isTruncated) {
- return (
- <div className={cn("inline", className)} {...props}>
- {children}
- </div>
- )
- }
-
- const truncatedText = text.slice(0, truncateLength) + "..."
-
- return (
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <span
- className={className}
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- onClick={(e) => e.preventDefault()}
- {...props}
- >
- {truncatedText}
- </span>
- </PopoverTrigger>
- <PopoverContent
- className="w-auto max-w-sm rounded-lg border border-white bg-popover p-3 text-sm text-popover-foreground"
- sideOffset={8}
- animated={false}
- onMouseEnter={handleMouseEnter}
- onMouseLeave={handleMouseLeave}
- onPointerDownOutside={(e) => e.preventDefault()}
- onClick={(e) => e.stopPropagation()}
- >
- <PopoverArrow className="fill-white" />
- {children}
- </PopoverContent>
- </Popover>
- )
-}
-
-export { ContentClamp }
+"use client";
+import * as React from "react";
+
+import { cn } from "@/lib/utils";
+import { Popover, PopoverArrow, PopoverContent, PopoverTrigger } from "./popover";
+
+interface ContentClampProps extends React.HTMLAttributes<HTMLDivElement> {
+ children: React.ReactNode;
+ truncateLength?: number;
+}
+
+function ContentClamp({ children, className, truncateLength = 50, ...props }: ContentClampProps) {
+ const text = typeof children === "string" ? children : String(children ?? "");
+ const isTruncated = text.length > truncateLength;
+
+ const [open, setOpen] = React.useState(false);
+ const timeoutRef = React.useRef<NodeJS.Timeout | null>(null);
+
+ const handleMouseEnter = () => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ timeoutRef.current = null;
+ }
+ setOpen(true);
+ };
+
+ const handleMouseLeave = () => {
+ timeoutRef.current = setTimeout(() => {
+ setOpen(false);
+ }, 100);
+ };
+
+ React.useEffect(() => {
+ return () => {
+ if (timeoutRef.current) {
+ clearTimeout(timeoutRef.current);
+ }
+ };
+ }, []);
+
+ if (!isTruncated) {
+ return (
+ <div className={cn("inline", className)} {...props}>
+ {children}
+ </div>
+ );
+ }
+
+ const truncatedText = text.slice(0, truncateLength) + "...";
+
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <span
+ className={className}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ onClick={(e) => e.preventDefault()}
+ {...props}
+ >
+ {truncatedText}
+ </span>
+ </PopoverTrigger>
+ <PopoverContent
+ className="w-auto max-w-sm rounded-lg border border-white bg-popover p-3 text-sm text-popover-foreground"
+ sideOffset={8}
+ animated={false}
+ onMouseEnter={handleMouseEnter}
+ onMouseLeave={handleMouseLeave}
+ onPointerDownOutside={(e) => e.preventDefault()}
+ onClick={(e) => e.stopPropagation()}
+ >
+ <PopoverArrow className="fill-white" />
+ {children}
+ </PopoverContent>
+ </Popover>
+ );
+}
+
+export { ContentClamp };
diff --git a/src/components/ui/dialog.tsx b/src/components/ui/dialog.tsx
index 697b3b88..fa1ff0c6 100644
--- a/src/components/ui/dialog.tsx
+++ b/src/components/ui/dialog.tsx
@@ -1,121 +1,105 @@
-import * as React from "react"
-import * as DialogPrimitive from "@radix-ui/react-dialog"
-import { X } from "lucide-react"
+import * as DialogPrimitive from "@radix-ui/react-dialog";
+import { X } from "@phosphor-icons/react";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
-const Dialog = DialogPrimitive.Root
+const Dialog = DialogPrimitive.Root;
-const DialogTrigger = DialogPrimitive.Trigger
+const DialogTrigger = DialogPrimitive.Trigger;
-const DialogPortal = DialogPrimitive.Portal
+const DialogPortal = DialogPrimitive.Portal;
-const DialogClose = DialogPrimitive.Close
+const DialogClose = DialogPrimitive.Close;
const DialogOverlay = React.forwardRef<
- React.ElementRef<typeof DialogPrimitive.Overlay>,
- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
+ React.ElementRef<typeof DialogPrimitive.Overlay>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Overlay>
>(({ className, ...props }, ref) => (
- <DialogPrimitive.Overlay
- ref={ref}
- className={cn(
- "fixed inset-0 z-[9999] bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
- className
- )}
- {...props}
- />
-))
-DialogOverlay.displayName = DialogPrimitive.Overlay.displayName
+ <DialogPrimitive.Overlay
+ ref={ref}
+ className={cn(
+ "fixed inset-0 z-[9999] bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
+ className,
+ )}
+ {...props}
+ />
+));
+DialogOverlay.displayName = DialogPrimitive.Overlay.displayName;
const DialogContent = React.forwardRef<
- React.ElementRef<typeof DialogPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
+ React.ElementRef<typeof DialogPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Content>
>(({ className, children, ...props }, ref) => (
- <DialogPortal>
- <DialogOverlay />
- <DialogPrimitive.Content
- ref={ref}
- className={cn(
- "fixed left-[50%] top-[50%] z-[10000] grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
- className
- )}
- {...props}
- >
- {children}
- <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
- <X className="h-4 w-4" />
- <span className="sr-only">Close</span>
- </DialogPrimitive.Close>
- </DialogPrimitive.Content>
- </DialogPortal>
-))
-DialogContent.displayName = DialogPrimitive.Content.displayName
+ <DialogPortal>
+ <DialogOverlay />
+ <DialogPrimitive.Content
+ ref={ref}
+ className={cn(
+ "fixed left-[50%] top-[50%] z-[10000] grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <DialogPrimitive.Close className="absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-accent data-[state=open]:text-muted-foreground">
+ <X className="h-4 w-4" />
+ <span className="sr-only">Close</span>
+ </DialogPrimitive.Close>
+ </DialogPrimitive.Content>
+ </DialogPortal>
+));
+DialogContent.displayName = DialogPrimitive.Content.displayName;
-const DialogHeader = ({
- className,
- ...props
-}: React.HTMLAttributes<HTMLDivElement>) => (
- <div
- className={cn(
- "flex flex-col space-y-1.5 text-center sm:text-left",
- className
- )}
- {...props}
- />
-)
-DialogHeader.displayName = "DialogHeader"
+const DialogHeader = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn("flex flex-col space-y-1.5 text-center sm:text-left", className)}
+ {...props}
+ />
+);
+DialogHeader.displayName = "DialogHeader";
-const DialogFooter = ({
- className,
- ...props
-}: React.HTMLAttributes<HTMLDivElement>) => (
- <div
- className={cn(
- "flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",
- className
- )}
- {...props}
- />
-)
-DialogFooter.displayName = "DialogFooter"
+const DialogFooter = ({ className, ...props }: React.HTMLAttributes<HTMLDivElement>) => (
+ <div
+ className={cn("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2", className)}
+ {...props}
+ />
+);
+DialogFooter.displayName = "DialogFooter";
const DialogTitle = React.forwardRef<
- React.ElementRef<typeof DialogPrimitive.Title>,
- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
+ React.ElementRef<typeof DialogPrimitive.Title>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Title>
>(({ className, ...props }, ref) => (
- <DialogPrimitive.Title
- ref={ref}
- className={cn(
- "text-lg font-semibold leading-none tracking-tight",
- className
- )}
- {...props}
- />
-))
-DialogTitle.displayName = DialogPrimitive.Title.displayName
+ <DialogPrimitive.Title
+ ref={ref}
+ className={cn("text-lg font-semibold leading-none tracking-tight", className)}
+ {...props}
+ />
+));
+DialogTitle.displayName = DialogPrimitive.Title.displayName;
const DialogDescription = React.forwardRef<
- React.ElementRef<typeof DialogPrimitive.Description>,
- React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
+ React.ElementRef<typeof DialogPrimitive.Description>,
+ React.ComponentPropsWithoutRef<typeof DialogPrimitive.Description>
>(({ className, ...props }, ref) => (
- <DialogPrimitive.Description
- ref={ref}
- className={cn("text-sm text-muted-foreground", className)}
- {...props}
- />
-))
-DialogDescription.displayName = DialogPrimitive.Description.displayName
+ <DialogPrimitive.Description
+ ref={ref}
+ className={cn("text-sm text-muted-foreground", className)}
+ {...props}
+ />
+));
+DialogDescription.displayName = DialogPrimitive.Description.displayName;
export {
- Dialog,
- DialogPortal,
- DialogOverlay,
- DialogTrigger,
- DialogClose,
- DialogContent,
- DialogHeader,
- DialogFooter,
- DialogTitle,
- DialogDescription,
-}
-
+ Dialog,
+ DialogPortal,
+ DialogOverlay,
+ DialogTrigger,
+ DialogClose,
+ DialogContent,
+ DialogHeader,
+ DialogFooter,
+ DialogTitle,
+ DialogDescription,
+};
diff --git a/src/components/ui/dropdown-menu.tsx b/src/components/ui/dropdown-menu.tsx
index d8ce2db3..079b5251 100644
--- a/src/components/ui/dropdown-menu.tsx
+++ b/src/components/ui/dropdown-menu.tsx
@@ -1,200 +1,186 @@
-import * as React from "react"
-import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu"
-import { Check, ChevronRight, Circle } from "lucide-react"
+import * as DropdownMenuPrimitive from "@radix-ui/react-dropdown-menu";
+import { CaretRight as ChevronRight, Check, Circle } from "@phosphor-icons/react";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
-const DropdownMenu = DropdownMenuPrimitive.Root
+const DropdownMenu = DropdownMenuPrimitive.Root;
-const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger
+const DropdownMenuTrigger = DropdownMenuPrimitive.Trigger;
-const DropdownMenuGroup = DropdownMenuPrimitive.Group
+const DropdownMenuGroup = DropdownMenuPrimitive.Group;
-const DropdownMenuPortal = DropdownMenuPrimitive.Portal
+const DropdownMenuPortal = DropdownMenuPrimitive.Portal;
-const DropdownMenuSub = DropdownMenuPrimitive.Sub
+const DropdownMenuSub = DropdownMenuPrimitive.Sub;
-const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup
+const DropdownMenuRadioGroup = DropdownMenuPrimitive.RadioGroup;
const DropdownMenuSubTrigger = React.forwardRef<
- React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
- inset?: boolean
- }
+ React.ElementRef<typeof DropdownMenuPrimitive.SubTrigger>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubTrigger> & {
+ inset?: boolean;
+ }
>(({ className, inset, children, ...props }, ref) => (
- <DropdownMenuPrimitive.SubTrigger
- ref={ref}
- className={cn(
- "flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
- inset && "pl-8",
- className
- )}
- {...props}
- >
- {children}
- <ChevronRight className="ml-auto" />
- </DropdownMenuPrimitive.SubTrigger>
-))
-DropdownMenuSubTrigger.displayName =
- DropdownMenuPrimitive.SubTrigger.displayName
+ <DropdownMenuPrimitive.SubTrigger
+ ref={ref}
+ className={cn(
+ "flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none focus:bg-accent data-[state=open]:bg-accent [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",
+ inset && "pl-8",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <ChevronRight className="ml-auto" />
+ </DropdownMenuPrimitive.SubTrigger>
+));
+DropdownMenuSubTrigger.displayName = DropdownMenuPrimitive.SubTrigger.displayName;
const DropdownMenuSubContent = React.forwardRef<
- React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
+ React.ElementRef<typeof DropdownMenuPrimitive.SubContent>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.SubContent>
>(({ className, ...props }, ref) => (
- <DropdownMenuPrimitive.SubContent
- ref={ref}
- className={cn(
- "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
- className
- )}
- {...props}
- />
-))
-DropdownMenuSubContent.displayName =
- DropdownMenuPrimitive.SubContent.displayName
+ <DropdownMenuPrimitive.SubContent
+ ref={ref}
+ className={cn(
+ "z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-lg data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
+ className,
+ )}
+ {...props}
+ />
+));
+DropdownMenuSubContent.displayName = DropdownMenuPrimitive.SubContent.displayName;
const DropdownMenuContent = React.forwardRef<
- React.ElementRef<typeof DropdownMenuPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
+ React.ElementRef<typeof DropdownMenuPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Content>
>(({ className, sideOffset = 4, ...props }, ref) => (
- <DropdownMenuPrimitive.Portal>
- <DropdownMenuPrimitive.Content
- ref={ref}
- sideOffset={sideOffset}
- className={cn(
- "z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
- className
- )}
- {...props}
- />
- </DropdownMenuPrimitive.Portal>
-))
-DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName
+ <DropdownMenuPrimitive.Portal>
+ <DropdownMenuPrimitive.Content
+ ref={ref}
+ sideOffset={sideOffset}
+ className={cn(
+ "z-50 max-h-[var(--radix-dropdown-menu-content-available-height)] min-w-[8rem] overflow-y-auto overflow-x-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md",
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-dropdown-menu-content-transform-origin]",
+ className,
+ )}
+ {...props}
+ />
+ </DropdownMenuPrimitive.Portal>
+));
+DropdownMenuContent.displayName = DropdownMenuPrimitive.Content.displayName;
const DropdownMenuItem = React.forwardRef<
- React.ElementRef<typeof DropdownMenuPrimitive.Item>,
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
- inset?: boolean
- }
+ React.ElementRef<typeof DropdownMenuPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Item> & {
+ inset?: boolean;
+ }
>(({ className, inset, ...props }, ref) => (
- <DropdownMenuPrimitive.Item
- ref={ref}
- className={cn(
- "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
- inset && "pl-8",
- className
- )}
- {...props}
- />
-))
-DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName
+ <DropdownMenuPrimitive.Item
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50 [&>svg]:size-4 [&>svg]:shrink-0",
+ inset && "pl-8",
+ className,
+ )}
+ {...props}
+ />
+));
+DropdownMenuItem.displayName = DropdownMenuPrimitive.Item.displayName;
const DropdownMenuCheckboxItem = React.forwardRef<
- React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
+ React.ElementRef<typeof DropdownMenuPrimitive.CheckboxItem>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.CheckboxItem>
>(({ className, children, checked, ...props }, ref) => (
- <DropdownMenuPrimitive.CheckboxItem
- ref={ref}
- className={cn(
- "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
- className
- )}
- checked={checked}
- {...props}
- >
- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
- <DropdownMenuPrimitive.ItemIndicator>
- <Check className="h-4 w-4" />
- </DropdownMenuPrimitive.ItemIndicator>
- </span>
- {children}
- </DropdownMenuPrimitive.CheckboxItem>
-))
-DropdownMenuCheckboxItem.displayName =
- DropdownMenuPrimitive.CheckboxItem.displayName
+ <DropdownMenuPrimitive.CheckboxItem
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className,
+ )}
+ checked={checked}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <DropdownMenuPrimitive.ItemIndicator>
+ <Check className="h-4 w-4" />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.CheckboxItem>
+));
+DropdownMenuCheckboxItem.displayName = DropdownMenuPrimitive.CheckboxItem.displayName;
const DropdownMenuRadioItem = React.forwardRef<
- React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
+ React.ElementRef<typeof DropdownMenuPrimitive.RadioItem>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.RadioItem>
>(({ className, children, ...props }, ref) => (
- <DropdownMenuPrimitive.RadioItem
- ref={ref}
- className={cn(
- "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
- className
- )}
- {...props}
- >
- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
- <DropdownMenuPrimitive.ItemIndicator>
- <Circle className="h-2 w-2 fill-current" />
- </DropdownMenuPrimitive.ItemIndicator>
- </span>
- {children}
- </DropdownMenuPrimitive.RadioItem>
-))
-DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName
+ <DropdownMenuPrimitive.RadioItem
+ ref={ref}
+ className={cn(
+ "relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className,
+ )}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <DropdownMenuPrimitive.ItemIndicator>
+ <Circle className="h-2 w-2 fill-current" />
+ </DropdownMenuPrimitive.ItemIndicator>
+ </span>
+ {children}
+ </DropdownMenuPrimitive.RadioItem>
+));
+DropdownMenuRadioItem.displayName = DropdownMenuPrimitive.RadioItem.displayName;
const DropdownMenuLabel = React.forwardRef<
- React.ElementRef<typeof DropdownMenuPrimitive.Label>,
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
- inset?: boolean
- }
+ React.ElementRef<typeof DropdownMenuPrimitive.Label>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Label> & {
+ inset?: boolean;
+ }
>(({ className, inset, ...props }, ref) => (
- <DropdownMenuPrimitive.Label
- ref={ref}
- className={cn(
- "px-2 py-1.5 text-sm font-semibold",
- inset && "pl-8",
- className
- )}
- {...props}
- />
-))
-DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName
+ <DropdownMenuPrimitive.Label
+ ref={ref}
+ className={cn("px-2 py-1.5 text-sm font-semibold", inset && "pl-8", className)}
+ {...props}
+ />
+));
+DropdownMenuLabel.displayName = DropdownMenuPrimitive.Label.displayName;
const DropdownMenuSeparator = React.forwardRef<
- React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
- React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
+ React.ElementRef<typeof DropdownMenuPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof DropdownMenuPrimitive.Separator>
>(({ className, ...props }, ref) => (
- <DropdownMenuPrimitive.Separator
- ref={ref}
- className={cn("-mx-1 my-1 h-px bg-muted", className)}
- {...props}
- />
-))
-DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName
-
-const DropdownMenuShortcut = ({
- className,
- ...props
-}: React.HTMLAttributes<HTMLSpanElement>) => {
- return (
- <span
- className={cn("ml-auto text-xs tracking-widest opacity-60", className)}
- {...props}
- />
- )
-}
-DropdownMenuShortcut.displayName = "DropdownMenuShortcut"
+ <DropdownMenuPrimitive.Separator
+ ref={ref}
+ className={cn("-mx-1 my-1 h-px bg-muted", className)}
+ {...props}
+ />
+));
+DropdownMenuSeparator.displayName = DropdownMenuPrimitive.Separator.displayName;
+
+const DropdownMenuShortcut = ({ className, ...props }: React.HTMLAttributes<HTMLSpanElement>) => {
+ return (
+ <span className={cn("ml-auto text-xs tracking-widest opacity-60", className)} {...props} />
+ );
+};
+DropdownMenuShortcut.displayName = "DropdownMenuShortcut";
export {
- DropdownMenu,
- DropdownMenuTrigger,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuCheckboxItem,
- DropdownMenuRadioItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuShortcut,
- DropdownMenuGroup,
- DropdownMenuPortal,
- DropdownMenuSub,
- DropdownMenuSubContent,
- DropdownMenuSubTrigger,
- DropdownMenuRadioGroup,
-}
-
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuCheckboxItem,
+ DropdownMenuRadioItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuShortcut,
+ DropdownMenuGroup,
+ DropdownMenuPortal,
+ DropdownMenuSub,
+ DropdownMenuSubContent,
+ DropdownMenuSubTrigger,
+ DropdownMenuRadioGroup,
+};
diff --git a/src/components/ui/input.tsx b/src/components/ui/input.tsx
index 7ba03f87..68ac869e 100644
--- a/src/components/ui/input.tsx
+++ b/src/components/ui/input.tsx
@@ -1,25 +1,23 @@
-import * as React from "react"
-import { cn } from "@/lib/utils"
-
-export interface InputProps
- extends React.InputHTMLAttributes<HTMLInputElement> {}
-
-const Input = React.forwardRef<HTMLInputElement, InputProps>(
- ({ className, type, ...props }, ref) => {
- return (
- <input
- type={type}
- className={cn(
- "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
- className
- )}
- ref={ref}
- {...props}
- />
- )
- }
-)
-Input.displayName = "Input"
-
-export { Input }
+import * as React from "react";
+import { cn } from "@/lib/utils";
+export interface InputProps extends React.InputHTMLAttributes<HTMLInputElement> {}
+
+const Input = React.forwardRef<HTMLInputElement, InputProps>(
+ ({ className, type, ...props }, ref) => {
+ return (
+ <input
+ type={type}
+ className={cn(
+ "flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",
+ className,
+ )}
+ ref={ref}
+ {...props}
+ />
+ );
+ },
+);
+Input.displayName = "Input";
+
+export { Input };
diff --git a/src/components/ui/label.tsx b/src/components/ui/label.tsx
index 67784787..fd6cbcc8 100644
--- a/src/components/ui/label.tsx
+++ b/src/components/ui/label.tsx
@@ -1,24 +1,20 @@
-import * as React from "react"
-import { cn } from "@/lib/utils"
-
-export interface LabelProps
- extends React.LabelHTMLAttributes<HTMLLabelElement> {}
-
-const Label = React.forwardRef<HTMLLabelElement, LabelProps>(
- ({ className, ...props }, ref) => {
- return (
- <label
- ref={ref}
- className={cn(
- "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
- className
- )}
- {...props}
- />
- )
- }
-)
-Label.displayName = "Label"
-
-export { Label }
+import * as React from "react";
+import { cn } from "@/lib/utils";
+export interface LabelProps extends React.LabelHTMLAttributes<HTMLLabelElement> {}
+
+const Label = React.forwardRef<HTMLLabelElement, LabelProps>(({ className, ...props }, ref) => {
+ return (
+ <label
+ ref={ref}
+ className={cn(
+ "text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70",
+ className,
+ )}
+ {...props}
+ />
+ );
+});
+Label.displayName = "Label";
+
+export { Label };
diff --git a/src/components/ui/popover.tsx b/src/components/ui/popover.tsx
index 21e94b01..8d723908 100644
--- a/src/components/ui/popover.tsx
+++ b/src/components/ui/popover.tsx
@@ -1,67 +1,60 @@
-"use client"
+"use client";
-import * as React from "react"
-import * as PopoverPrimitive from "@radix-ui/react-popover"
+import * as PopoverPrimitive from "@radix-ui/react-popover";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
-function Popover({
- ...props
-}: React.ComponentProps<typeof PopoverPrimitive.Root>) {
- return <PopoverPrimitive.Root data-slot="popover" {...props} />
+function Popover({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Root>) {
+ return <PopoverPrimitive.Root data-slot="popover" {...props} />;
}
-function PopoverTrigger({
- ...props
-}: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
- return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />
+function PopoverTrigger({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Trigger>) {
+ return <PopoverPrimitive.Trigger data-slot="popover-trigger" {...props} />;
}
function PopoverContent({
- className,
- align = "center",
- sideOffset = 4,
- animated = true,
- ...props
+ className,
+ align = "center",
+ sideOffset = 4,
+ animated = true,
+ ...props
}: React.ComponentProps<typeof PopoverPrimitive.Content> & {
- animated?: boolean
+ animated?: boolean;
}) {
- return (
- <PopoverPrimitive.Portal>
- <PopoverPrimitive.Content
- data-slot="popover-content"
- align={align}
- sideOffset={sideOffset}
- className={cn(
- "bg-popover text-popover-foreground z-50 w-72 rounded-md border p-4 shadow-md outline-hidden",
- animated &&
- "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-popover-content-transform-origin)",
- className
- )}
- {...props}
- />
- </PopoverPrimitive.Portal>
- )
+ return (
+ <PopoverPrimitive.Portal>
+ <PopoverPrimitive.Content
+ data-slot="popover-content"
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ "bg-popover text-popover-foreground z-50 w-72 rounded-md border p-4 shadow-md outline-hidden",
+ animated &&
+ "data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-(--radix-popover-content-transform-origin)",
+ className,
+ )}
+ {...props}
+ />
+ </PopoverPrimitive.Portal>
+ );
}
-function PopoverAnchor({
- ...props
-}: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
- return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />
+function PopoverAnchor({ ...props }: React.ComponentProps<typeof PopoverPrimitive.Anchor>) {
+ return <PopoverPrimitive.Anchor data-slot="popover-anchor" {...props} />;
}
function PopoverArrow({
- className,
- ...props
+ className,
+ ...props
}: React.ComponentProps<typeof PopoverPrimitive.Arrow>) {
- return (
- <PopoverPrimitive.Arrow
- data-slot="popover-arrow"
- className={cn("fill-popover", className)}
- {...props}
- />
- )
+ return (
+ <PopoverPrimitive.Arrow
+ data-slot="popover-arrow"
+ className={cn("fill-popover", className)}
+ {...props}
+ />
+ );
}
-export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor, PopoverArrow }
-
+export { Popover, PopoverTrigger, PopoverContent, PopoverAnchor, PopoverArrow };
diff --git a/src/components/ui/select.tsx b/src/components/ui/select.tsx
index aeeee0ce..55597aeb 100644
--- a/src/components/ui/select.tsx
+++ b/src/components/ui/select.tsx
@@ -1,161 +1,153 @@
-"use client"
+"use client";
-import * as React from "react"
-import * as SelectPrimitive from "@radix-ui/react-select"
-import { Check, ChevronDown, ChevronUp } from "lucide-react"
+import * as SelectPrimitive from "@radix-ui/react-select";
+import { CaretDown as ChevronDown, CaretUp as ChevronUp, Check } from "@phosphor-icons/react";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
-const Select = SelectPrimitive.Root
+const Select = SelectPrimitive.Root;
-const SelectGroup = SelectPrimitive.Group
+const SelectGroup = SelectPrimitive.Group;
-const SelectValue = SelectPrimitive.Value
+const SelectValue = SelectPrimitive.Value;
const SelectTrigger = React.forwardRef<
- React.ElementRef<typeof SelectPrimitive.Trigger>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
+ React.ElementRef<typeof SelectPrimitive.Trigger>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Trigger>
>(({ className, children, ...props }, ref) => (
- <SelectPrimitive.Trigger
- ref={ref}
- className={cn(
- "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
- className
- )}
- {...props}
- >
- {children}
- <SelectPrimitive.Icon asChild>
- <ChevronDown className="h-4 w-4 opacity-50" />
- </SelectPrimitive.Icon>
- </SelectPrimitive.Trigger>
-))
-SelectTrigger.displayName = SelectPrimitive.Trigger.displayName
+ <SelectPrimitive.Trigger
+ ref={ref}
+ className={cn(
+ "flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ <SelectPrimitive.Icon asChild>
+ <ChevronDown className="h-4 w-4 opacity-50" />
+ </SelectPrimitive.Icon>
+ </SelectPrimitive.Trigger>
+));
+SelectTrigger.displayName = SelectPrimitive.Trigger.displayName;
const SelectScrollUpButton = React.forwardRef<
- React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
+ React.ElementRef<typeof SelectPrimitive.ScrollUpButton>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollUpButton>
>(({ className, ...props }, ref) => (
- <SelectPrimitive.ScrollUpButton
- ref={ref}
- className={cn(
- "flex cursor-default items-center justify-center py-1",
- className
- )}
- {...props}
- >
- <ChevronUp className="h-4 w-4" />
- </SelectPrimitive.ScrollUpButton>
-))
-SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName
+ <SelectPrimitive.ScrollUpButton
+ ref={ref}
+ className={cn("flex cursor-default items-center justify-center py-1", className)}
+ {...props}
+ >
+ <ChevronUp className="h-4 w-4" />
+ </SelectPrimitive.ScrollUpButton>
+));
+SelectScrollUpButton.displayName = SelectPrimitive.ScrollUpButton.displayName;
const SelectScrollDownButton = React.forwardRef<
- React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
+ React.ElementRef<typeof SelectPrimitive.ScrollDownButton>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.ScrollDownButton>
>(({ className, ...props }, ref) => (
- <SelectPrimitive.ScrollDownButton
- ref={ref}
- className={cn(
- "flex cursor-default items-center justify-center py-1",
- className
- )}
- {...props}
- >
- <ChevronDown className="h-4 w-4" />
- </SelectPrimitive.ScrollDownButton>
-))
-SelectScrollDownButton.displayName =
- SelectPrimitive.ScrollDownButton.displayName
+ <SelectPrimitive.ScrollDownButton
+ ref={ref}
+ className={cn("flex cursor-default items-center justify-center py-1", className)}
+ {...props}
+ >
+ <ChevronDown className="h-4 w-4" />
+ </SelectPrimitive.ScrollDownButton>
+));
+SelectScrollDownButton.displayName = SelectPrimitive.ScrollDownButton.displayName;
const SelectContent = React.forwardRef<
- React.ElementRef<typeof SelectPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
+ React.ElementRef<typeof SelectPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Content>
>(({ className, children, position = "popper", ...props }, ref) => (
- <SelectPrimitive.Portal>
- <SelectPrimitive.Content
- ref={ref}
- className={cn(
- "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
- position === "popper" &&
- "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
- className
- )}
- position={position}
- {...props}
- >
- <SelectScrollUpButton />
- <SelectPrimitive.Viewport
- className={cn(
- "p-1",
- position === "popper" &&
- "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"
- )}
- >
- {children}
- </SelectPrimitive.Viewport>
- <SelectScrollDownButton />
- </SelectPrimitive.Content>
- </SelectPrimitive.Portal>
-))
-SelectContent.displayName = SelectPrimitive.Content.displayName
+ <SelectPrimitive.Portal>
+ <SelectPrimitive.Content
+ ref={ref}
+ className={cn(
+ "relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",
+ position === "popper" &&
+ "data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",
+ className,
+ )}
+ position={position}
+ {...props}
+ >
+ <SelectScrollUpButton />
+ <SelectPrimitive.Viewport
+ className={cn(
+ "p-1",
+ position === "popper" &&
+ "h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]",
+ )}
+ >
+ {children}
+ </SelectPrimitive.Viewport>
+ <SelectScrollDownButton />
+ </SelectPrimitive.Content>
+ </SelectPrimitive.Portal>
+));
+SelectContent.displayName = SelectPrimitive.Content.displayName;
const SelectLabel = React.forwardRef<
- React.ElementRef<typeof SelectPrimitive.Label>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
+ React.ElementRef<typeof SelectPrimitive.Label>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Label>
>(({ className, ...props }, ref) => (
- <SelectPrimitive.Label
- ref={ref}
- className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
- {...props}
- />
-))
-SelectLabel.displayName = SelectPrimitive.Label.displayName
+ <SelectPrimitive.Label
+ ref={ref}
+ className={cn("py-1.5 pl-8 pr-2 text-sm font-semibold", className)}
+ {...props}
+ />
+));
+SelectLabel.displayName = SelectPrimitive.Label.displayName;
const SelectItem = React.forwardRef<
- React.ElementRef<typeof SelectPrimitive.Item>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
+ React.ElementRef<typeof SelectPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Item>
>(({ className, children, ...props }, ref) => (
- <SelectPrimitive.Item
- ref={ref}
- className={cn(
- "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
- className
- )}
- {...props}
- >
- <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
- <SelectPrimitive.ItemIndicator>
- <Check className="h-4 w-4" />
- </SelectPrimitive.ItemIndicator>
- </span>
+ <SelectPrimitive.Item
+ ref={ref}
+ className={cn(
+ "relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",
+ className,
+ )}
+ {...props}
+ >
+ <span className="absolute left-2 flex h-3.5 w-3.5 items-center justify-center">
+ <SelectPrimitive.ItemIndicator>
+ <Check className="h-4 w-4" />
+ </SelectPrimitive.ItemIndicator>
+ </span>
- <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
- </SelectPrimitive.Item>
-))
-SelectItem.displayName = SelectPrimitive.Item.displayName
+ <SelectPrimitive.ItemText>{children}</SelectPrimitive.ItemText>
+ </SelectPrimitive.Item>
+));
+SelectItem.displayName = SelectPrimitive.Item.displayName;
const SelectSeparator = React.forwardRef<
- React.ElementRef<typeof SelectPrimitive.Separator>,
- React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
+ React.ElementRef<typeof SelectPrimitive.Separator>,
+ React.ComponentPropsWithoutRef<typeof SelectPrimitive.Separator>
>(({ className, ...props }, ref) => (
- <SelectPrimitive.Separator
- ref={ref}
- className={cn("-mx-1 my-1 h-px bg-muted", className)}
- {...props}
- />
-))
-SelectSeparator.displayName = SelectPrimitive.Separator.displayName
+ <SelectPrimitive.Separator
+ ref={ref}
+ className={cn("-mx-1 my-1 h-px bg-muted", className)}
+ {...props}
+ />
+));
+SelectSeparator.displayName = SelectPrimitive.Separator.displayName;
export {
- Select,
- SelectGroup,
- SelectValue,
- SelectTrigger,
- SelectContent,
- SelectLabel,
- SelectItem,
- SelectSeparator,
- SelectScrollUpButton,
- SelectScrollDownButton,
-}
-
+ Select,
+ SelectGroup,
+ SelectValue,
+ SelectTrigger,
+ SelectContent,
+ SelectLabel,
+ SelectItem,
+ SelectSeparator,
+ SelectScrollUpButton,
+ SelectScrollDownButton,
+};
diff --git a/src/components/ui/slider.tsx b/src/components/ui/slider.tsx
index 587f73f6..63933ee3 100644
--- a/src/components/ui/slider.tsx
+++ b/src/components/ui/slider.tsx
@@ -1,27 +1,23 @@
-import * as React from "react"
-import * as SliderPrimitive from "@radix-ui/react-slider"
+import * as SliderPrimitive from "@radix-ui/react-slider";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
const Slider = React.forwardRef<
- React.ElementRef<typeof SliderPrimitive.Root>,
- React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
+ React.ElementRef<typeof SliderPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof SliderPrimitive.Root>
>(({ className, ...props }, ref) => (
- <SliderPrimitive.Root
- ref={ref}
- className={cn(
- "relative flex w-full touch-none select-none items-center",
- className
- )}
- {...props}
- >
- <SliderPrimitive.Track className="relative h-2.5 w-full grow overflow-hidden rounded-full bg-white/10">
- <SliderPrimitive.Range className="absolute h-full bg-[#2563EB]" />
- </SliderPrimitive.Track>
- <SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-[#2563EB] bg-[#2563EB] shadow transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#2563EB]/50 disabled:pointer-events-none disabled:opacity-50" />
- </SliderPrimitive.Root>
-))
-Slider.displayName = SliderPrimitive.Root.displayName
-
-export { Slider }
+ <SliderPrimitive.Root
+ ref={ref}
+ className={cn("relative flex w-full touch-none select-none items-center", className)}
+ {...props}
+ >
+ <SliderPrimitive.Track className="relative h-2.5 w-full grow overflow-hidden rounded-full bg-white/10">
+ <SliderPrimitive.Range className="absolute h-full bg-[#2563EB]" />
+ </SliderPrimitive.Track>
+ <SliderPrimitive.Thumb className="block h-5 w-5 rounded-full border-2 border-[#2563EB] bg-[#2563EB] shadow transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[#2563EB]/50 disabled:pointer-events-none disabled:opacity-50" />
+ </SliderPrimitive.Root>
+));
+Slider.displayName = SliderPrimitive.Root.displayName;
+export { Slider };
diff --git a/src/components/ui/sonner.tsx b/src/components/ui/sonner.tsx
index be4c09db..9afe95db 100644
--- a/src/components/ui/sonner.tsx
+++ b/src/components/ui/sonner.tsx
@@ -3,26 +3,23 @@ import { Toaster as Sonner } from "sonner";
type ToasterProps = React.ComponentProps<typeof Sonner>;
const Toaster = ({ ...props }: ToasterProps) => {
- return (
- <Sonner
- theme="light"
- className="toaster group"
- duration={3000}
- toastOptions={{
- classNames: {
- toast:
- "group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
- description: "group-[.toast]:text-muted-foreground",
- actionButton:
- "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
- cancelButton:
- "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
- },
- }}
- {...props}
- />
- );
+ return (
+ <Sonner
+ theme="light"
+ className="toaster group"
+ duration={3000}
+ toastOptions={{
+ classNames: {
+ toast: "group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",
+ description: "group-[.toast]:text-muted-foreground",
+ actionButton:
+ "group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",
+ cancelButton: "group-[.toast]:bg-muted group-[.toast]:text-muted-foreground",
+ },
+ }}
+ {...props}
+ />
+ );
};
export { Toaster };
-
diff --git a/src/components/ui/switch.tsx b/src/components/ui/switch.tsx
index 9977d7be..fae3ca44 100644
--- a/src/components/ui/switch.tsx
+++ b/src/components/ui/switch.tsx
@@ -1,31 +1,30 @@
-import * as React from "react"
-import * as SwitchPrimitives from "@radix-ui/react-switch"
+import * as SwitchPrimitives from "@radix-ui/react-switch";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
const Switch = React.forwardRef<
- React.ElementRef<typeof SwitchPrimitives.Root>,
- React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
+ React.ElementRef<typeof SwitchPrimitives.Root>,
+ React.ComponentPropsWithoutRef<typeof SwitchPrimitives.Root>
>(({ className, ...props }, ref) => (
- <SwitchPrimitives.Root
- className={cn(
- "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",
- "data-[state=checked]:bg-[#2563EB] data-[state=unchecked]:bg-[#23232a]",
- className
- )}
- {...props}
- ref={ref}
- >
- <SwitchPrimitives.Thumb
- className={cn(
- "pointer-events-none block h-4 w-4 rounded-full shadow-lg ring-0 transition-transform",
- "bg-[#f5f5f7] dark:bg-[#23232a]",
- "data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0"
- )}
- />
- </SwitchPrimitives.Root>
-))
-Switch.displayName = SwitchPrimitives.Root.displayName
-
-export { Switch }
+ <SwitchPrimitives.Root
+ className={cn(
+ "peer inline-flex h-5 w-9 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent shadow-sm transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",
+ "data-[state=checked]:bg-[#2563EB] data-[state=unchecked]:bg-[#23232a]",
+ className,
+ )}
+ {...props}
+ ref={ref}
+ >
+ <SwitchPrimitives.Thumb
+ className={cn(
+ "pointer-events-none block h-4 w-4 rounded-full shadow-lg ring-0 transition-transform",
+ "bg-[#f5f5f7] dark:bg-[#23232a]",
+ "data-[state=checked]:translate-x-4 data-[state=unchecked]:translate-x-0",
+ )}
+ />
+ </SwitchPrimitives.Root>
+));
+Switch.displayName = SwitchPrimitives.Root.displayName;
+export { Switch };
diff --git a/src/components/ui/tabs.tsx b/src/components/ui/tabs.tsx
index 51b8e001..dbee684c 100644
--- a/src/components/ui/tabs.tsx
+++ b/src/components/ui/tabs.tsx
@@ -1,54 +1,53 @@
-import * as React from "react"
-import * as TabsPrimitive from "@radix-ui/react-tabs"
+import * as TabsPrimitive from "@radix-ui/react-tabs";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
-const Tabs = TabsPrimitive.Root
+const Tabs = TabsPrimitive.Root;
const TabsList = React.forwardRef<
- React.ElementRef<typeof TabsPrimitive.List>,
- React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
+ React.ElementRef<typeof TabsPrimitive.List>,
+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.List>
>(({ className, ...props }, ref) => (
- <TabsPrimitive.List
- ref={ref}
- className={cn(
- "inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",
- className
- )}
- {...props}
- />
-))
-TabsList.displayName = TabsPrimitive.List.displayName
+ <TabsPrimitive.List
+ ref={ref}
+ className={cn(
+ "inline-flex h-9 items-center justify-center rounded-lg bg-muted p-1 text-muted-foreground",
+ className,
+ )}
+ {...props}
+ />
+));
+TabsList.displayName = TabsPrimitive.List.displayName;
const TabsTrigger = React.forwardRef<
- React.ElementRef<typeof TabsPrimitive.Trigger>,
- React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
+ React.ElementRef<typeof TabsPrimitive.Trigger>,
+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.Trigger>
>(({ className, ...props }, ref) => (
- <TabsPrimitive.Trigger
- ref={ref}
- className={cn(
- "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
- className
- )}
- {...props}
- />
-))
-TabsTrigger.displayName = TabsPrimitive.Trigger.displayName
+ <TabsPrimitive.Trigger
+ ref={ref}
+ className={cn(
+ "inline-flex items-center justify-center whitespace-nowrap rounded-md px-3 py-1 text-sm font-medium ring-offset-background transition-all focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=active]:bg-background data-[state=active]:text-foreground data-[state=active]:shadow",
+ className,
+ )}
+ {...props}
+ />
+));
+TabsTrigger.displayName = TabsPrimitive.Trigger.displayName;
const TabsContent = React.forwardRef<
- React.ElementRef<typeof TabsPrimitive.Content>,
- React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
+ React.ElementRef<typeof TabsPrimitive.Content>,
+ React.ComponentPropsWithoutRef<typeof TabsPrimitive.Content>
>(({ className, ...props }, ref) => (
- <TabsPrimitive.Content
- ref={ref}
- className={cn(
- "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
- className
- )}
- {...props}
- />
-))
-TabsContent.displayName = TabsPrimitive.Content.displayName
-
-export { Tabs, TabsList, TabsTrigger, TabsContent }
+ <TabsPrimitive.Content
+ ref={ref}
+ className={cn(
+ "mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",
+ className,
+ )}
+ {...props}
+ />
+));
+TabsContent.displayName = TabsPrimitive.Content.displayName;
+export { Tabs, TabsList, TabsTrigger, TabsContent };
diff --git a/src/components/ui/toggle-group.tsx b/src/components/ui/toggle-group.tsx
index 5a8b121f..9077e473 100644
--- a/src/components/ui/toggle-group.tsx
+++ b/src/components/ui/toggle-group.tsx
@@ -1,62 +1,58 @@
-"use client"
+"use client";
-import * as React from "react"
-import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group"
-import { type VariantProps } from "class-variance-authority"
+import * as ToggleGroupPrimitive from "@radix-ui/react-toggle-group";
+import { type VariantProps } from "class-variance-authority";
+import * as React from "react";
+import { toggleVariants } from "@/components/ui/toggle";
+import { cn } from "@/lib/utils";
-import { cn } from "@/lib/utils"
-import { toggleVariants } from "@/components/ui/toggle"
-
-const ToggleGroupContext = React.createContext<
- VariantProps<typeof toggleVariants>
->({
- size: "default",
- variant: "default",
-})
+const ToggleGroupContext = React.createContext<VariantProps<typeof toggleVariants>>({
+ size: "default",
+ variant: "default",
+});
const ToggleGroup = React.forwardRef<
- React.ElementRef<typeof ToggleGroupPrimitive.Root>,
- React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &
- VariantProps<typeof toggleVariants>
+ React.ElementRef<typeof ToggleGroupPrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Root> &
+ VariantProps<typeof toggleVariants>
>(({ className, variant, size, children, ...props }, ref) => (
- <ToggleGroupPrimitive.Root
- ref={ref}
- className={cn("flex items-center justify-center gap-1", className)}
- {...props}
- >
- <ToggleGroupContext.Provider value={{ variant, size }}>
- {children}
- </ToggleGroupContext.Provider>
- </ToggleGroupPrimitive.Root>
-))
-
-ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName
+ <ToggleGroupPrimitive.Root
+ ref={ref}
+ className={cn("flex items-center justify-center gap-1", className)}
+ {...props}
+ >
+ <ToggleGroupContext.Provider value={{ variant, size }}>
+ {children}
+ </ToggleGroupContext.Provider>
+ </ToggleGroupPrimitive.Root>
+));
+
+ToggleGroup.displayName = ToggleGroupPrimitive.Root.displayName;
const ToggleGroupItem = React.forwardRef<
- React.ElementRef<typeof ToggleGroupPrimitive.Item>,
- React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &
- VariantProps<typeof toggleVariants>
+ React.ElementRef<typeof ToggleGroupPrimitive.Item>,
+ React.ComponentPropsWithoutRef<typeof ToggleGroupPrimitive.Item> &
+ VariantProps<typeof toggleVariants>
>(({ className, children, variant, size, ...props }, ref) => {
- const context = React.useContext(ToggleGroupContext)
-
- return (
- <ToggleGroupPrimitive.Item
- ref={ref}
- className={cn(
- toggleVariants({
- variant: context.variant || variant,
- size: context.size || size,
- }),
- className
- )}
- {...props}
- >
- {children}
- </ToggleGroupPrimitive.Item>
- )
-})
-
-ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName
-
-export { ToggleGroup, ToggleGroupItem }
-
+ const context = React.useContext(ToggleGroupContext);
+
+ return (
+ <ToggleGroupPrimitive.Item
+ ref={ref}
+ className={cn(
+ toggleVariants({
+ variant: context.variant || variant,
+ size: context.size || size,
+ }),
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </ToggleGroupPrimitive.Item>
+ );
+});
+
+ToggleGroupItem.displayName = ToggleGroupPrimitive.Item.displayName;
+
+export { ToggleGroup, ToggleGroupItem };
diff --git a/src/components/ui/toggle.tsx b/src/components/ui/toggle.tsx
index 4290d6ea..4a2cc68c 100644
--- a/src/components/ui/toggle.tsx
+++ b/src/components/ui/toggle.tsx
@@ -1,46 +1,45 @@
-"use client"
+"use client";
-import * as React from "react"
-import * as TogglePrimitive from "@radix-ui/react-toggle"
-import { cva, type VariantProps } from "class-variance-authority"
+import * as TogglePrimitive from "@radix-ui/react-toggle";
+import { cva, type VariantProps } from "class-variance-authority";
+import * as React from "react";
-import { cn } from "@/lib/utils"
+import { cn } from "@/lib/utils";
const toggleVariants = cva(
- "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
- {
- variants: {
- variant: {
- default: "bg-transparent",
- outline:
- "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
- },
- size: {
- default: "h-10 px-3",
- sm: "h-9 px-2.5",
- lg: "h-11 px-5",
- },
- },
- defaultVariants: {
- variant: "default",
- size: "default",
- },
- }
-)
+ "inline-flex items-center justify-center rounded-md text-sm font-medium ring-offset-background transition-colors hover:bg-muted hover:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 data-[state=on]:bg-accent data-[state=on]:text-accent-foreground",
+ {
+ variants: {
+ variant: {
+ default: "bg-transparent",
+ outline:
+ "border border-input bg-transparent hover:bg-accent hover:text-accent-foreground",
+ },
+ size: {
+ default: "h-10 px-3",
+ sm: "h-9 px-2.5",
+ lg: "h-11 px-5",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ size: "default",
+ },
+ },
+);
const Toggle = React.forwardRef<
- React.ElementRef<typeof TogglePrimitive.Root>,
- React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &
- VariantProps<typeof toggleVariants>
+ React.ElementRef<typeof TogglePrimitive.Root>,
+ React.ComponentPropsWithoutRef<typeof TogglePrimitive.Root> &
+ VariantProps<typeof toggleVariants>
>(({ className, variant, size, ...props }, ref) => (
- <TogglePrimitive.Root
- ref={ref}
- className={cn(toggleVariants({ variant, size, className }))}
- {...props}
- />
-))
+ <TogglePrimitive.Root
+ ref={ref}
+ className={cn(toggleVariants({ variant, size, className }))}
+ {...props}
+ />
+));
-Toggle.displayName = TogglePrimitive.Root.displayName
-
-export { Toggle, toggleVariants }
+Toggle.displayName = TogglePrimitive.Root.displayName;
+export { Toggle, toggleVariants };
diff --git a/src/components/video-editor/AddCustomFontDialog.tsx b/src/components/video-editor/AddCustomFontDialog.tsx
index f0054a7f..1ecbc629 100644
--- a/src/components/video-editor/AddCustomFontDialog.tsx
+++ b/src/components/video-editor/AddCustomFontDialog.tsx
@@ -1,184 +1,179 @@
-import { useState } from 'react';
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from '@/components/ui/dialog';
-import { Button } from '@/components/ui/button';
-import { Input } from '@/components/ui/input';
-import { Label } from '@/components/ui/label';
-import { Plus } from 'lucide-react';
-import { toast } from 'sonner';
-import {
- addCustomFont,
- generateFontId,
- parseFontFamilyFromImport,
- isValidGoogleFontsUrl,
- type CustomFont,
-} from '@/lib/customFonts';
-import { useScopedT } from '../../contexts/I18nContext';
-
-interface AddCustomFontDialogProps {
- onFontAdded?: (font: CustomFont) => void;
-}
-
-export function AddCustomFontDialog({ onFontAdded }: AddCustomFontDialogProps) {
- const t = useScopedT('dialogs');
- const [open, setOpen] = useState(false);
- const [importUrl, setImportUrl] = useState('');
- const [fontName, setFontName] = useState('');
- const [loading, setLoading] = useState(false);
-
- const handleImportUrlChange = (url: string) => {
- setImportUrl(url);
-
- // Auto-extract font name if valid Google Fonts URL
- if (isValidGoogleFontsUrl(url)) {
- const extracted = parseFontFamilyFromImport(url);
- if (extracted && !fontName) {
- setFontName(extracted);
- }
- }
- };
-
- const handleAdd = async () => {
- // Validate inputs
- if (!importUrl.trim()) {
- toast.error(t('addFont.enterUrl'));
- return;
- }
-
- if (!isValidGoogleFontsUrl(importUrl)) {
- toast.error(t('addFont.invalidUrl'));
- return;
- }
-
- if (!fontName.trim()) {
- toast.error(t('addFont.enterName'));
- return;
- }
-
- setLoading(true);
-
- try {
- // Extract font family from URL
- const fontFamily = parseFontFamilyFromImport(importUrl);
- if (!fontFamily) {
- toast.error(t('addFont.extractFailed'));
- setLoading(false);
- return;
- }
-
- // Create custom font object
- const newFont: CustomFont = {
- id: generateFontId(fontName),
- name: fontName.trim(),
- fontFamily: fontFamily,
- importUrl: importUrl.trim(),
- };
-
- // Add font (this will load and verify it) - throws if it fails
- await addCustomFont(newFont);
-
- // Notify parent
- if (onFontAdded) {
- onFontAdded(newFont);
- }
-
- toast.success(t('addFont.addSuccess', undefined, { name: fontName }));
-
- // Reset and close
- setImportUrl('');
- setFontName('');
- setOpen(false);
- } catch (error) {
- console.error('Failed to add custom font:', error);
- const errorMessage = error instanceof Error ? error.message : 'Failed to load font';
- toast.error(t('addFont.addFailed'), {
- description: errorMessage.includes('timeout')
- ? t('addFont.loadTimeout')
- : t('addFont.loadFailed'),
- });
- } finally {
- setLoading(false);
- }
- };
-
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogTrigger asChild>
- <Button
- variant="outline"
- size="sm"
- className="w-full bg-white/5 border-white/10 text-slate-200 hover:bg-white/10 h-9 text-xs"
- >
- <Plus className="w-3 h-3 mr-1" />
- {t('addFont.title')}
- </Button>
- </DialogTrigger>
- <DialogContent className="bg-[#1a1a1c] border-white/10 text-slate-200">
- <DialogHeader>
- <DialogTitle>{t('addFont.heading')}</DialogTitle>
- <DialogDescription className="text-slate-400">
- {t('addFont.description')}
- </DialogDescription>
- </DialogHeader>
-
- <div className="space-y-4 mt-4">
- <div className="space-y-2">
- <Label htmlFor="import-url" className="text-slate-200">
- {t('addFont.urlLabel')}
- </Label>
- <Input
- id="import-url"
- placeholder={t('addFont.urlPlaceholder')}
- value={importUrl}
- onChange={(e) => handleImportUrlChange(e.target.value)}
- className="bg-white/5 border-white/10 text-slate-200"
- />
- <p className="text-xs text-slate-400">
- {t('addFont.urlHelp')}
- </p>
- </div>
-
- <div className="space-y-2">
- <Label htmlFor="font-name" className="text-slate-200">
- {t('addFont.nameLabel')}
- </Label>
- <Input
- id="font-name"
- placeholder={t('addFont.namePlaceholder')}
- value={fontName}
- onChange={(e) => setFontName(e.target.value)}
- className="bg-white/5 border-white/10 text-slate-200"
- />
- <p className="text-xs text-slate-400">
- {t('addFont.nameHelp')}
- </p>
- </div>
-
- <div className="flex justify-end gap-2 mt-6">
- <Button
- variant="outline"
- onClick={() => setOpen(false)}
- className="bg-white/5 border-white/10 text-slate-200 hover:bg-white/10"
- >
- {t('addFont.cancel')}
- </Button>
- <Button
- onClick={handleAdd}
- disabled={loading}
- className="bg-blue-600 hover:bg-blue-700 text-white"
- >
- {loading ? t('addFont.adding') : t('addFont.addFont')}
- </Button>
- </div>
- </div>
- </DialogContent>
- </Dialog>
- );
-}
-
+import { Plus } from "@phosphor-icons/react";
+import { useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogDescription,
+ DialogHeader,
+ DialogTitle,
+ DialogTrigger,
+} from "@/components/ui/dialog";
+import { Input } from "@/components/ui/input";
+import { Label } from "@/components/ui/label";
+import {
+ addCustomFont,
+ type CustomFont,
+ generateFontId,
+ isValidGoogleFontsUrl,
+ parseFontFamilyFromImport,
+} from "@/lib/customFonts";
+import { useScopedT } from "../../contexts/I18nContext";
+
+interface AddCustomFontDialogProps {
+ onFontAdded?: (font: CustomFont) => void;
+}
+
+export function AddCustomFontDialog({ onFontAdded }: AddCustomFontDialogProps) {
+ const t = useScopedT("dialogs");
+ const [open, setOpen] = useState(false);
+ const [importUrl, setImportUrl] = useState("");
+ const [fontName, setFontName] = useState("");
+ const [loading, setLoading] = useState(false);
+
+ const handleImportUrlChange = (url: string) => {
+ setImportUrl(url);
+
+ // Auto-extract font name if valid Google Fonts URL
+ if (isValidGoogleFontsUrl(url)) {
+ const extracted = parseFontFamilyFromImport(url);
+ if (extracted && !fontName) {
+ setFontName(extracted);
+ }
+ }
+ };
+
+ const handleAdd = async () => {
+ // Validate inputs
+ if (!importUrl.trim()) {
+ toast.error(t("addFont.enterUrl"));
+ return;
+ }
+
+ if (!isValidGoogleFontsUrl(importUrl)) {
+ toast.error(t("addFont.invalidUrl"));
+ return;
+ }
+
+ if (!fontName.trim()) {
+ toast.error(t("addFont.enterName"));
+ return;
+ }
+
+ setLoading(true);
+
+ try {
+ // Extract font family from URL
+ const fontFamily = parseFontFamilyFromImport(importUrl);
+ if (!fontFamily) {
+ toast.error(t("addFont.extractFailed"));
+ setLoading(false);
+ return;
+ }
+
+ // Create custom font object
+ const newFont: CustomFont = {
+ id: generateFontId(fontName),
+ name: fontName.trim(),
+ fontFamily: fontFamily,
+ importUrl: importUrl.trim(),
+ };
+
+ // Add font (this will load and verify it) - throws if it fails
+ await addCustomFont(newFont);
+
+ // Notify parent
+ if (onFontAdded) {
+ onFontAdded(newFont);
+ }
+
+ toast.success(t("addFont.addSuccess", undefined, { name: fontName }));
+
+ // Reset and close
+ setImportUrl("");
+ setFontName("");
+ setOpen(false);
+ } catch (error) {
+ console.error("Failed to add custom font:", error);
+ const errorMessage = error instanceof Error ? error.message : "Failed to load font";
+ toast.error(t("addFont.addFailed"), {
+ description: errorMessage.includes("timeout")
+ ? t("addFont.loadTimeout")
+ : t("addFont.loadFailed"),
+ });
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogTrigger asChild>
+ <Button
+ variant="outline"
+ size="sm"
+ className="w-full bg-white/5 border-white/10 text-slate-200 hover:bg-white/10 h-9 text-xs"
+ >
+ <Plus className="w-3 h-3 mr-1" />
+ {t("addFont.title")}
+ </Button>
+ </DialogTrigger>
+ <DialogContent className="bg-[#1a1a1c] border-white/10 text-slate-200">
+ <DialogHeader>
+ <DialogTitle>{t("addFont.heading")}</DialogTitle>
+ <DialogDescription className="text-slate-400">
+ {t("addFont.description")}
+ </DialogDescription>
+ </DialogHeader>
+
+ <div className="space-y-4 mt-4">
+ <div className="space-y-2">
+ <Label htmlFor="import-url" className="text-slate-200">
+ {t("addFont.urlLabel")}
+ </Label>
+ <Input
+ id="import-url"
+ placeholder={t("addFont.urlPlaceholder")}
+ value={importUrl}
+ onChange={(e) => handleImportUrlChange(e.target.value)}
+ className="bg-white/5 border-white/10 text-slate-200"
+ />
+ <p className="text-xs text-slate-400">{t("addFont.urlHelp")}</p>
+ </div>
+
+ <div className="space-y-2">
+ <Label htmlFor="font-name" className="text-slate-200">
+ {t("addFont.nameLabel")}
+ </Label>
+ <Input
+ id="font-name"
+ placeholder={t("addFont.namePlaceholder")}
+ value={fontName}
+ onChange={(e) => setFontName(e.target.value)}
+ className="bg-white/5 border-white/10 text-slate-200"
+ />
+ <p className="text-xs text-slate-400">{t("addFont.nameHelp")}</p>
+ </div>
+
+ <div className="flex justify-end gap-2 mt-6">
+ <Button
+ variant="outline"
+ onClick={() => setOpen(false)}
+ className="bg-white/5 border-white/10 text-slate-200 hover:bg-white/10"
+ >
+ {t("addFont.cancel")}
+ </Button>
+ <Button
+ onClick={handleAdd}
+ disabled={loading}
+ className="bg-blue-600 hover:bg-blue-700 text-white"
+ >
+ {loading ? t("addFont.adding") : t("addFont.addFont")}
+ </Button>
+ </div>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/src/components/video-editor/AnnotationOverlay.tsx b/src/components/video-editor/AnnotationOverlay.tsx
index 60413aaf..8d219327 100644
--- a/src/components/video-editor/AnnotationOverlay.tsx
+++ b/src/components/video-editor/AnnotationOverlay.tsx
@@ -1,239 +1,241 @@
import { useRef } from "react";
import { Rnd } from "react-rnd";
-import { BLUR_ANNOTATION_STRENGTH, BASE_PREVIEW_WIDTH, type AnnotationRegion } from "./types";
-
import { cn } from "@/lib/utils";
import { getArrowComponent } from "./ArrowSvgs";
+import { type AnnotationRegion, BASE_PREVIEW_WIDTH, BLUR_ANNOTATION_STRENGTH } from "./types";
interface AnnotationOverlayProps {
- annotation: AnnotationRegion;
- isSelected: boolean;
- containerWidth: number;
- containerHeight: number;
- onPositionChange: (id: string, position: { x: number; y: number }) => void;
- onSizeChange: (id: string, size: { width: number; height: number }) => void;
- onClick: (id: string) => void;
- zIndex: number;
- isSelectedBoost: boolean; // Boost z-index when selected for easy editing
+ annotation: AnnotationRegion;
+ isSelected: boolean;
+ containerWidth: number;
+ containerHeight: number;
+ onPositionChange: (id: string, position: { x: number; y: number }) => void;
+ onSizeChange: (id: string, size: { width: number; height: number }) => void;
+ onClick: (id: string) => void;
+ zIndex: number;
+ isSelectedBoost: boolean; // Boost z-index when selected for easy editing
}
export function AnnotationOverlay({
- annotation,
- isSelected,
- containerWidth,
- containerHeight,
- onPositionChange,
- onSizeChange,
- onClick,
- zIndex,
- isSelectedBoost,
+ annotation,
+ isSelected,
+ containerWidth,
+ containerHeight,
+ onPositionChange,
+ onSizeChange,
+ onClick,
+ zIndex,
+ isSelectedBoost,
}: AnnotationOverlayProps) {
- const x = (annotation.position.x / 100) * containerWidth;
- const y = (annotation.position.y / 100) * containerHeight;
- const width = (annotation.size.width / 100) * containerWidth;
- const height = (annotation.size.height / 100) * containerHeight;
+ const x = (annotation.position.x / 100) * containerWidth;
+ const y = (annotation.position.y / 100) * containerHeight;
+ const width = (annotation.size.width / 100) * containerWidth;
+ const height = (annotation.size.height / 100) * containerHeight;
- const isDraggingRef = useRef(false);
+ const isDraggingRef = useRef(false);
- const renderArrow = () => {
- const direction = annotation.figureData?.arrowDirection || 'right';
- const color = annotation.figureData?.color || '#2563EB';
- const strokeWidth = annotation.figureData?.strokeWidth || 4;
+ const renderArrow = () => {
+ const direction = annotation.figureData?.arrowDirection || "right";
+ const color = annotation.figureData?.color || "#2563EB";
+ const strokeWidth = annotation.figureData?.strokeWidth || 4;
- const ArrowComponent = getArrowComponent(direction);
- return <ArrowComponent color={color} strokeWidth={strokeWidth} />;
- };
+ const ArrowComponent = getArrowComponent(direction);
+ return <ArrowComponent color={color} strokeWidth={strokeWidth} />;
+ };
- const renderContent = () => {
- switch (annotation.type) {
- case 'text':
- return (
- <div
- className="w-full h-full flex items-center p-2 overflow-hidden"
- style={{
- justifyContent: annotation.style.textAlign === 'left' ? 'flex-start' :
- annotation.style.textAlign === 'right' ? 'flex-end' : 'center',
- alignItems: 'center',
- }}
- >
- <span
- style={{
- color: annotation.style.color,
- backgroundColor: annotation.style.backgroundColor,
- fontSize: `${annotation.style.fontSize}px`,
- fontFamily: annotation.style.fontFamily,
- fontWeight: annotation.style.fontWeight,
- fontStyle: annotation.style.fontStyle,
- textDecoration: annotation.style.textDecoration,
- textAlign: annotation.style.textAlign,
- wordBreak: 'break-word',
- whiteSpace: 'pre-wrap',
- boxDecorationBreak: 'clone',
- WebkitBoxDecorationBreak: 'clone',
- padding: '0.1em 0.2em',
- borderRadius: '4px',
- lineHeight: '1.4',
- }}
- >
- {annotation.content}
- </span>
- </div>
- );
+ const renderContent = () => {
+ switch (annotation.type) {
+ case "text":
+ return (
+ <div
+ className="w-full h-full flex items-center p-2 overflow-hidden"
+ style={{
+ justifyContent:
+ annotation.style.textAlign === "left"
+ ? "flex-start"
+ : annotation.style.textAlign === "right"
+ ? "flex-end"
+ : "center",
+ alignItems: "center",
+ }}
+ >
+ <span
+ style={{
+ color: annotation.style.color,
+ backgroundColor: annotation.style.backgroundColor,
+ fontSize: `${annotation.style.fontSize}px`,
+ fontFamily: annotation.style.fontFamily,
+ fontWeight: annotation.style.fontWeight,
+ fontStyle: annotation.style.fontStyle,
+ textDecoration: annotation.style.textDecoration,
+ textAlign: annotation.style.textAlign,
+ wordBreak: "break-word",
+ whiteSpace: "pre-wrap",
+ boxDecorationBreak: "clone",
+ WebkitBoxDecorationBreak: "clone",
+ padding: "0.1em 0.2em",
+ borderRadius: "4px",
+ lineHeight: "1.4",
+ }}
+ >
+ {annotation.content}
+ </span>
+ </div>
+ );
- case 'image':
- if (annotation.content && annotation.content.startsWith('data:image')) {
- return (
- <img
- src={annotation.content}
- alt="Annotation"
- className="w-full h-full object-contain"
- draggable={false}
- />
- );
- }
- return (
- <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">
- No image
- </div>
- );
+ case "image":
+ if (annotation.content && annotation.content.startsWith("data:image")) {
+ return (
+ <img
+ src={annotation.content}
+ alt="Annotation"
+ className="w-full h-full object-contain"
+ draggable={false}
+ />
+ );
+ }
+ return (
+ <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">
+ No image
+ </div>
+ );
- case 'figure':
- if (!annotation.figureData) {
- return (
- <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">
- No arrow data
- </div>
- );
- }
+ case "figure":
+ if (!annotation.figureData) {
+ return (
+ <div className="w-full h-full flex items-center justify-center text-slate-400 text-sm">
+ No arrow data
+ </div>
+ );
+ }
- return (
- <div className="w-full h-full flex items-center justify-center p-2">
- {renderArrow()}
- </div>
- );
+ return (
+ <div className="w-full h-full flex items-center justify-center p-2">
+ {renderArrow()}
+ </div>
+ );
- case "blur": {
- const previewScaleFactor = containerWidth / BASE_PREVIEW_WIDTH;
- const currentBlurStrength = annotation.blurIntensity ?? BLUR_ANNOTATION_STRENGTH;
- const blurPx = currentBlurStrength * previewScaleFactor;
- const blurStyle = `blur(${blurPx}px)`;
+ case "blur": {
+ const previewScaleFactor = containerWidth / BASE_PREVIEW_WIDTH;
+ const currentBlurStrength = annotation.blurIntensity ?? BLUR_ANNOTATION_STRENGTH;
+ const blurPx = currentBlurStrength * previewScaleFactor;
+ const blurStyle = `blur(${blurPx}px)`;
- return (
- <div
- className="h-full w-full bg-slate-400/10"
- style={{
- backdropFilter: blurStyle,
- WebkitBackdropFilter: blurStyle,
- backgroundColor: annotation.blurColor || "transparent",
- borderRadius: `${(annotation.style.borderRadius ?? 0) * previewScaleFactor}px`,
- }}
- />
- );
- }
+ return (
+ <div
+ className="h-full w-full bg-slate-400/10"
+ style={{
+ backdropFilter: blurStyle,
+ WebkitBackdropFilter: blurStyle,
+ backgroundColor: annotation.blurColor || "transparent",
+ borderRadius: `${(annotation.style.borderRadius ?? 0) * previewScaleFactor}px`,
+ }}
+ />
+ );
+ }
- default:
- return null;
- }
- };
+ default:
+ return null;
+ }
+ };
- return (
- <Rnd
- position={{ x, y }}
- size={{ width, height }}
- onDragStart={() => {
- isDraggingRef.current = true;
- }}
- onDragStop={(_e, d) => {
- const xPercent = (d.x / containerWidth) * 100;
- const yPercent = (d.y / containerHeight) * 100;
- onPositionChange(annotation.id, { x: xPercent, y: yPercent });
-
- // Reset dragging flag after a short delay to prevent click event
- setTimeout(() => {
- isDraggingRef.current = false;
- }, 100);
- }}
- onResizeStop={(_e, _direction, ref, _delta, position) => {
- const xPercent = (position.x / containerWidth) * 100;
- const yPercent = (position.y / containerHeight) * 100;
- const widthPercent = (ref.offsetWidth / containerWidth) * 100;
- const heightPercent = (ref.offsetHeight / containerHeight) * 100;
- onPositionChange(annotation.id, { x: xPercent, y: yPercent });
- onSizeChange(annotation.id, { width: widthPercent, height: heightPercent });
- }}
- onClick={() => {
- if (isDraggingRef.current) return;
- onClick(annotation.id);
- }}
- bounds="parent"
- className={cn(
- "cursor-move transition-all",
- isSelected && "ring-2 ring-[#2563EB] ring-offset-2 ring-offset-transparent"
- )}
- style={{
- zIndex: isSelectedBoost ? zIndex + 1000 : zIndex, // Boost selected annotation to ensure it's on top
- pointerEvents: isSelected ? 'auto' : 'none',
- border: isSelected ? '2px solid rgba(37, 99, 235, 0.8)' : 'none',
- backgroundColor: isSelected ? 'rgba(37, 99, 235, 0.1)' : 'transparent',
- boxShadow: isSelected ? '0 0 0 1px rgba(37, 99, 235, 0.35)' : 'none',
- }}
- enableResizing={isSelected}
- disableDragging={!isSelected}
- resizeHandleStyles={{
- topLeft: {
- width: '12px',
- height: '12px',
- backgroundColor: isSelected ? 'white' : 'transparent',
- border: isSelected ? '2px solid #2563EB' : 'none',
- borderRadius: '50%',
- left: '-6px',
- top: '-6px',
- cursor: 'nwse-resize',
- },
- topRight: {
- width: '12px',
- height: '12px',
- backgroundColor: isSelected ? 'white' : 'transparent',
- border: isSelected ? '2px solid #2563EB' : 'none',
- borderRadius: '50%',
- right: '-6px',
- top: '-6px',
- cursor: 'nesw-resize',
- },
- bottomLeft: {
- width: '12px',
- height: '12px',
- backgroundColor: isSelected ? 'white' : 'transparent',
- border: isSelected ? '2px solid #2563EB' : 'none',
- borderRadius: '50%',
- left: '-6px',
- bottom: '-6px',
- cursor: 'nesw-resize',
- },
- bottomRight: {
- width: '12px',
- height: '12px',
- backgroundColor: isSelected ? 'white' : 'transparent',
- border: isSelected ? '2px solid #2563EB' : 'none',
- borderRadius: '50%',
- right: '-6px',
- bottom: '-6px',
- cursor: 'nwse-resize',
- },
- }}
- >
- <div
- className={cn(
- "w-full h-full rounded-lg",
- annotation.type === 'text' && "bg-transparent",
- annotation.type === 'image' && "bg-transparent",
- annotation.type === 'figure' && "bg-transparent",
- isSelected && "shadow-lg"
- )}
- >
- {renderContent()}
- </div>
- </Rnd>
- );
-}
+ return (
+ <Rnd
+ position={{ x, y }}
+ size={{ width, height }}
+ onDragStart={() => {
+ isDraggingRef.current = true;
+ }}
+ onDragStop={(_e, d) => {
+ const xPercent = (d.x / containerWidth) * 100;
+ const yPercent = (d.y / containerHeight) * 100;
+ onPositionChange(annotation.id, { x: xPercent, y: yPercent });
+ // Reset dragging flag after a short delay to prevent click event
+ setTimeout(() => {
+ isDraggingRef.current = false;
+ }, 100);
+ }}
+ onResizeStop={(_e, _direction, ref, _delta, position) => {
+ const xPercent = (position.x / containerWidth) * 100;
+ const yPercent = (position.y / containerHeight) * 100;
+ const widthPercent = (ref.offsetWidth / containerWidth) * 100;
+ const heightPercent = (ref.offsetHeight / containerHeight) * 100;
+ onPositionChange(annotation.id, { x: xPercent, y: yPercent });
+ onSizeChange(annotation.id, { width: widthPercent, height: heightPercent });
+ }}
+ onClick={() => {
+ if (isDraggingRef.current) return;
+ onClick(annotation.id);
+ }}
+ bounds="parent"
+ className={cn(
+ "cursor-move transition-all",
+ isSelected && "ring-2 ring-[#2563EB] ring-offset-2 ring-offset-transparent",
+ )}
+ style={{
+ zIndex: isSelectedBoost ? zIndex + 1000 : zIndex, // Boost selected annotation to ensure it's on top
+ pointerEvents: isSelected ? "auto" : "none",
+ border: isSelected ? "2px solid rgba(37, 99, 235, 0.8)" : "none",
+ backgroundColor: isSelected ? "rgba(37, 99, 235, 0.1)" : "transparent",
+ boxShadow: isSelected ? "0 0 0 1px rgba(37, 99, 235, 0.35)" : "none",
+ }}
+ enableResizing={isSelected}
+ disableDragging={!isSelected}
+ resizeHandleStyles={{
+ topLeft: {
+ width: "12px",
+ height: "12px",
+ backgroundColor: isSelected ? "white" : "transparent",
+ border: isSelected ? "2px solid #2563EB" : "none",
+ borderRadius: "50%",
+ left: "-6px",
+ top: "-6px",
+ cursor: "nwse-resize",
+ },
+ topRight: {
+ width: "12px",
+ height: "12px",
+ backgroundColor: isSelected ? "white" : "transparent",
+ border: isSelected ? "2px solid #2563EB" : "none",
+ borderRadius: "50%",
+ right: "-6px",
+ top: "-6px",
+ cursor: "nesw-resize",
+ },
+ bottomLeft: {
+ width: "12px",
+ height: "12px",
+ backgroundColor: isSelected ? "white" : "transparent",
+ border: isSelected ? "2px solid #2563EB" : "none",
+ borderRadius: "50%",
+ left: "-6px",
+ bottom: "-6px",
+ cursor: "nesw-resize",
+ },
+ bottomRight: {
+ width: "12px",
+ height: "12px",
+ backgroundColor: isSelected ? "white" : "transparent",
+ border: isSelected ? "2px solid #2563EB" : "none",
+ borderRadius: "50%",
+ right: "-6px",
+ bottom: "-6px",
+ cursor: "nwse-resize",
+ },
+ }}
+ >
+ <div
+ className={cn(
+ "w-full h-full rounded-lg",
+ annotation.type === "text" && "bg-transparent",
+ annotation.type === "image" && "bg-transparent",
+ annotation.type === "figure" && "bg-transparent",
+ isSelected && "shadow-lg",
+ )}
+ >
+ {renderContent()}
+ </div>
+ </Rnd>
+ );
+}
diff --git a/src/components/video-editor/AnnotationSettingsPanel.tsx b/src/components/video-editor/AnnotationSettingsPanel.tsx
index 291542d5..e887de46 100644
--- a/src/components/video-editor/AnnotationSettingsPanel.tsx
+++ b/src/components/video-editor/AnnotationSettingsPanel.tsx
@@ -1,626 +1,796 @@
-import { useRef, useState, useEffect, useMemo } from "react";
-import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
-import { Button } from "@/components/ui/button";
-import { Trash2, Type, Image as ImageIcon, Upload, Bold, Italic, Underline, AlignLeft, AlignCenter, AlignRight, ChevronDown, Info, SquareDashed } from "lucide-react";
+import Block from "@uiw/react-color-block";
+import {
+ AlignCenterHorizontal as AlignCenter,
+ AlignLeft,
+ AlignRight,
+ BoundingBox as SquareDashed,
+ CaretDown as ChevronDown,
+ Info,
+ ImageSquare as ImageIcon,
+ TextB as Bold,
+ TextItalic as Italic,
+ TextT as Type,
+ TextUnderline as Underline,
+ Trash as Trash2,
+ UploadSimple as Upload,
+} from "@phosphor-icons/react";
+import { useEffect, useMemo, useRef, useState } from "react";
import { toast } from "sonner";
-import Block from '@uiw/react-color-block';
-import type { AnnotationRegion, AnnotationType, ArrowDirection, FigureData } from "./types";
+import { Button } from "@/components/ui/button";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
-import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
-import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@/components/ui/select";
import { Slider } from "@/components/ui/slider";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
+import { ToggleGroup, ToggleGroupItem } from "@/components/ui/toggle-group";
+import { type CustomFont, getCustomFonts } from "@/lib/customFonts";
import { cn } from "@/lib/utils";
-import { getArrowComponent } from "./ArrowSvgs";
-import { AddCustomFontDialog } from "./AddCustomFontDialog";
-import { getCustomFonts, type CustomFont } from "@/lib/customFonts";
import { useScopedT } from "../../contexts/I18nContext";
+import { AddCustomFontDialog } from "./AddCustomFontDialog";
+import { getArrowComponent } from "./ArrowSvgs";
+import type { AnnotationRegion, AnnotationType, ArrowDirection, FigureData } from "./types";
interface AnnotationSettingsPanelProps {
- annotation: AnnotationRegion;
- onContentChange: (content: string) => void;
- onTypeChange: (type: AnnotationType) => void;
- onStyleChange: (style: Partial<AnnotationRegion['style']>) => void;
- onFigureDataChange?: (figureData: FigureData) => void;
- onBlurIntensityChange?: (intensity: number) => void;
- onBlurColorChange?: (color: string) => void;
- onDelete: () => void;
+ annotation: AnnotationRegion;
+ onContentChange: (content: string) => void;
+ onTypeChange: (type: AnnotationType) => void;
+ onStyleChange: (style: Partial<AnnotationRegion["style"]>) => void;
+ onFigureDataChange?: (figureData: FigureData) => void;
+ onBlurIntensityChange?: (intensity: number) => void;
+ onBlurColorChange?: (color: string) => void;
+ onDelete: () => void;
}
export const FONT_FAMILY_VALUES = [
- { value: 'system-ui, -apple-system, sans-serif', labelKey: 'fontStyles.classic' },
- { value: 'Georgia, serif', labelKey: 'fontStyles.editor' },
- { value: 'Impact, Arial Black, sans-serif', labelKey: 'fontStyles.strong' },
- { value: 'Courier New, monospace', labelKey: 'fontStyles.typewriter' },
- { value: 'Brush Script MT, cursive', labelKey: 'fontStyles.deco' },
- { value: 'Arial, sans-serif', labelKey: 'fontStyles.simple' },
- { value: 'Verdana, sans-serif', labelKey: 'fontStyles.modern' },
- { value: 'Trebuchet MS, sans-serif', labelKey: 'fontStyles.clean' },
+ { value: "system-ui, -apple-system, sans-serif", labelKey: "fontStyles.classic" },
+ { value: "Georgia, serif", labelKey: "fontStyles.editor" },
+ { value: "Impact, Arial Black, sans-serif", labelKey: "fontStyles.strong" },
+ { value: "Courier New, monospace", labelKey: "fontStyles.typewriter" },
+ { value: "Brush Script MT, cursive", labelKey: "fontStyles.deco" },
+ { value: "Arial, sans-serif", labelKey: "fontStyles.simple" },
+ { value: "Verdana, sans-serif", labelKey: "fontStyles.modern" },
+ { value: "Trebuchet MS, sans-serif", labelKey: "fontStyles.clean" },
];
export const FONT_SIZES = [12, 14, 16, 18, 20, 24, 28, 32, 36, 40, 48, 56, 64, 72, 80, 96, 128];
export function AnnotationSettingsPanel({
- annotation,
- onContentChange,
- onTypeChange,
- onStyleChange,
- onFigureDataChange,
- onBlurIntensityChange,
- onBlurColorChange,
- onDelete,
+ annotation,
+ onContentChange,
+ onTypeChange,
+ onStyleChange,
+ onFigureDataChange,
+ onBlurIntensityChange,
+ onBlurColorChange,
+ onDelete,
}: AnnotationSettingsPanelProps) {
- const t = useScopedT('editor');
- const fileInputRef = useRef<HTMLInputElement>(null);
- const [customFonts, setCustomFonts] = useState<CustomFont[]>([]);
-
- const fontFamilies = useMemo(() =>
- FONT_FAMILY_VALUES.map((f) => ({ value: f.value, label: t(f.labelKey) })),
- [t],
- );
-
- // Load custom fonts on mount
- useEffect(() => {
- setCustomFonts(getCustomFonts());
- }, []);
-
- const colorPalette = [
- '#FF0000', // Red
- '#FFD700', // Yellow/Gold
- '#00FF00', // Green
- '#FFFFFF', // White
- '#0000FF', // Blue
- '#FF6B00', // Orange
- '#9B59B6', // Purple
- '#E91E63', // Pink
- '#00BCD4', // Cyan
- '#FF5722', // Deep Orange
- '#8BC34A', // Light Green
- '#FFC107', // Amber
- '#2563EB', // Brand Blue
- '#000000', // Black
- '#607D8B', // Blue Grey
- '#795548', // Brown
- ];
-
-
-
- const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
- const files = event.target.files;
- if (!files || files.length === 0) return;
-
- const file = files[0];
-
- // Validate file type
- const validTypes = ['image/jpeg', 'image/jpg', 'image/png', 'image/gif', 'image/webp'];
- if (!validTypes.includes(file.type)) {
- toast.error(t('annotations.imageUploadError'), {
- description: t('annotations.imageUploadErrorDescription'),
- });
- event.target.value = '';
- return;
- }
-
- const reader = new FileReader();
-
- reader.onload = (e) => {
- const dataUrl = e.target?.result as string;
- if (dataUrl) {
- onContentChange(dataUrl);
- toast.success(t('annotations.imageUploadSuccess'));
- }
- };
-
- reader.onerror = () => {
- toast.error(t('annotations.imageUploadFailed'), {
- description: t('annotations.imageUploadFailedDescription'),
- });
- };
-
- reader.readAsDataURL(file);
- event.target.value = '';
- };
-
- return (
- <div className="flex-[2] min-w-0 bg-[#161619] border border-white/10 rounded-2xl p-4 flex flex-col shadow-xl h-full overflow-y-auto custom-scrollbar">
- <div className="mb-6">
- <div className="flex items-center justify-between mb-4">
- <span className="text-sm font-medium text-slate-200">{t('annotations.settings')}</span>
- <span className="text-[10px] uppercase tracking-wider font-medium text-[#2563EB] bg-[#2563EB]/10 px-2 py-1 rounded-full">
- {t('annotations.active')}
- </span>
- </div>
-
- {/* Type Selector */}
- <Tabs value={annotation.type} onValueChange={(value) => onTypeChange(value as AnnotationType)} className="mb-6">
- <TabsList className="mb-4 bg-white/5 border border-white/5 p-1 w-full grid grid-cols-4 h-auto rounded-xl">
- <TabsTrigger value="text" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2">
- <Type className="w-4 h-4" />
- {t('annotations.text')}
- </TabsTrigger>
- <TabsTrigger value="image" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2">
- <ImageIcon className="w-4 h-4" />
- {t('annotations.image')}
- </TabsTrigger>
- <TabsTrigger value="figure" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2">
- <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2">
- <path d="M4 12h16m0 0l-6-6m6 6l-6 6" strokeLinecap="round" strokeLinejoin="round" />
- </svg>
- {t('annotations.arrow')}
- </TabsTrigger>
- <TabsTrigger value="blur" className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2">
- <SquareDashed className="w-4 h-4" />
- {t('annotations.blur')}
- </TabsTrigger>
- </TabsList>
-
- {/* Text Content */}
- <TabsContent value="text" className="mt-0 space-y-4">
- <div>
- <label className="text-xs font-medium text-slate-200 mb-2 block">{t('annotations.textContent')}</label>
- <textarea
- value={annotation.textContent || annotation.content}
- onChange={(e) => onContentChange(e.target.value)}
- placeholder={t('annotations.textPlaceholder')}
- rows={5}
- className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-slate-200 text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-[#2563EB] focus:border-transparent resize-none"
- />
- </div>
-
- {/* Styling Controls */}
- <div className="space-y-4">
- {/* Font Family & Size */}
- <div className="grid grid-cols-2 gap-2">
- <div>
- <label className="text-xs font-medium text-slate-200 mb-2 block">{t('annotations.fontStyle')}</label>
- <Select
- value={annotation.style.fontFamily}
- onValueChange={(value) => onStyleChange({ fontFamily: value })}
- >
- <SelectTrigger className="w-full bg-white/5 border-white/10 text-slate-200 h-9 text-xs">
- <SelectValue placeholder={t('annotations.selectStyle')} />
- </SelectTrigger>
- <SelectContent className="bg-[#1a1a1c] border-white/10 text-slate-200 max-h-[300px]">
- {fontFamilies.map((font) => (
- <SelectItem key={font.value} value={font.value} style={{ fontFamily: font.value }}>
- {font.label}
- </SelectItem>
- ))}
- {customFonts.length > 0 && (
- <>
- <div className="px-2 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-wider">
- Custom Fonts
- </div>
- {customFonts.map((font) => (
- <SelectItem
- key={font.id}
- value={font.fontFamily}
- style={{ fontFamily: font.fontFamily }}
- >
- {font.name}
- </SelectItem>
- ))}
- </>
- )}
- </SelectContent>
- </Select>
- </div>
- <div>
- <label className="text-xs font-medium text-slate-200 mb-2 block">{t('annotations.size')}</label>
- <Select
- value={annotation.style.fontSize.toString()}
- onValueChange={(value) => onStyleChange({ fontSize: parseInt(value) })}
- >
- <SelectTrigger className="w-full bg-white/5 border-white/10 text-slate-200 h-9 text-xs">
- <SelectValue placeholder={t('annotations.size')} />
- </SelectTrigger>
- <SelectContent className="bg-[#1a1a1c] border-white/10 text-slate-200 max-h-[200px]">
- {FONT_SIZES.map((size) => (
- <SelectItem key={size} value={size.toString()}>
- {size}px
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- </div>
-
- {/* Add Custom Font Button */}
- <div>
- <AddCustomFontDialog
- onFontAdded={(font) => {
- setCustomFonts(getCustomFonts());
- onStyleChange({ fontFamily: font.fontFamily });
- }}
- />
- </div>
-
- {/* Formatting Toggles */}
- <div className="flex items-center justify-between gap-2">
- <ToggleGroup type="multiple" className="justify-start bg-white/5 p-1 rounded-lg border border-white/5">
- <ToggleGroupItem
- value="bold"
- aria-label={t('annotations.toggleBold')}
- data-state={annotation.style.fontWeight === 'bold' ? 'on' : 'off'}
- onClick={() => onStyleChange({ fontWeight: annotation.style.fontWeight === 'bold' ? 'normal' : 'bold' })}
- className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
- >
- <Bold className="h-4 w-4" />
- </ToggleGroupItem>
- <ToggleGroupItem
- value="italic"
- aria-label={t('annotations.toggleItalic')}
- data-state={annotation.style.fontStyle === 'italic' ? 'on' : 'off'}
- onClick={() => onStyleChange({ fontStyle: annotation.style.fontStyle === 'italic' ? 'normal' : 'italic' })}
- className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
- >
- <Italic className="h-4 w-4" />
- </ToggleGroupItem>
- <ToggleGroupItem
- value="underline"
- aria-label={t('annotations.toggleUnderline')}
- data-state={annotation.style.textDecoration === 'underline' ? 'on' : 'off'}
- onClick={() => onStyleChange({ textDecoration: annotation.style.textDecoration === 'underline' ? 'none' : 'underline' })}
- className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
- >
- <Underline className="h-4 w-4" />
- </ToggleGroupItem>
- </ToggleGroup>
-
- <ToggleGroup type="single" value={annotation.style.textAlign} className="justify-start bg-white/5 p-1 rounded-lg border border-white/5">
- <ToggleGroupItem
- value="left"
- aria-label={t('annotations.alignLeft')}
- onClick={() => onStyleChange({ textAlign: 'left' })}
- className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
- >
- <AlignLeft className="h-4 w-4" />
- </ToggleGroupItem>
- <ToggleGroupItem
- value="center"
- aria-label={t('annotations.alignCenter')}
- onClick={() => onStyleChange({ textAlign: 'center' })}
- className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
- >
- <AlignCenter className="h-4 w-4" />
- </ToggleGroupItem>
- <ToggleGroupItem
- value="right"
- aria-label={t('annotations.alignRight')}
- onClick={() => onStyleChange({ textAlign: 'right' })}
- className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
- >
- <AlignRight className="h-4 w-4" />
- </ToggleGroupItem>
- </ToggleGroup>
- </div>
-
- {/* Colors */}
- <div className="grid grid-cols-2 gap-4">
- <div>
- <label className="text-xs font-medium text-slate-200 mb-2 block">{t('annotations.textColor')}</label>
- <Popover>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- className="w-full h-9 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10 px-2"
- >
- <div
- className="w-4 h-4 rounded-full border border-white/20"
- style={{ backgroundColor: annotation.style.color }}
- />
- <span className="text-xs text-slate-300 truncate flex-1 text-left">
- {annotation.style.color}
- </span>
- <ChevronDown className="h-3 w-3 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl">
- <Block
- color={annotation.style.color}
- colors={colorPalette}
- onChange={(color) => {
- onStyleChange({ color: color.hex });
- }}
- style={{
- borderRadius: '8px',
- }}
- />
- </PopoverContent>
- </Popover>
- </div>
- <div>
- <label className="text-xs font-medium text-slate-200 mb-2 block">{t('annotations.background')}</label>
- <Popover>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- className="w-full h-9 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10 px-2"
- >
- <div
- className="w-4 h-4 rounded-full border border-white/20 relative overflow-hidden"
- >
- <div className="absolute inset-0 checkerboard-bg opacity-50" />
- <div
- className="absolute inset-0"
- style={{ backgroundColor: annotation.style.backgroundColor }}
- />
- </div>
- <span className="text-xs text-slate-300 truncate flex-1 text-left">
- {annotation.style.backgroundColor === 'transparent' ? t('annotations.none') : 'Color'}
- </span>
- <ChevronDown className="h-3 w-3 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl">
- <Block
- color={annotation.style.backgroundColor === 'transparent' ? '#000000' : annotation.style.backgroundColor}
- colors={colorPalette}
- onChange={(color) => {
- onStyleChange({ backgroundColor: color.hex });
- }}
- style={{
- borderRadius: '8px',
- }}
- />
- <Button
- variant="ghost"
- size="sm"
- className="w-full mt-2 text-xs h-7 hover:bg-white/5 text-slate-400"
- onClick={() => {
- onStyleChange({ backgroundColor: 'transparent' });
- }}
- >
- {t('annotations.clearBackground')}
- </Button>
- </PopoverContent>
- </Popover>
- </div>
- </div>
- </div>
-
-
- </TabsContent>
-
- {/* Image Upload */}
- <TabsContent value="image" className="mt-0 space-y-4">
- <input
- type="file"
- ref={fileInputRef}
- onChange={handleImageUpload}
- accept=".jpg,.jpeg,.png,.gif,.webp,image/*"
- className="hidden"
- />
- <Button
- onClick={() => fileInputRef.current?.click()}
- variant="outline"
- className="w-full gap-2 bg-white/5 text-slate-200 border-white/10 hover:bg-[#2563EB] hover:text-white hover:border-[#2563EB] transition-all py-8"
- >
- <Upload className="w-5 h-5" />
- {t('annotations.uploadImage')}
- </Button>
-
- {annotation.content && annotation.content.startsWith('data:image') && (
- <div className="rounded-lg border border-white/10 overflow-hidden bg-white/5 p-2">
- <img
- src={annotation.content}
- alt="Uploaded annotation"
- className="w-full h-auto rounded-md"
- />
- </div>
- )}
-
- <p className="text-xs text-slate-500 text-center leading-relaxed">
- {t('annotations.supportedFormats')}
- </p>
- </TabsContent>
-
- <TabsContent value="figure" className="mt-0 space-y-4">
- <div>
- <label className="text-xs font-medium text-slate-200 mb-3 block">{t('annotations.arrowDirection')}</label>
- <div className="grid grid-cols-4 gap-2">
- {([
- 'up', 'down', 'left', 'right',
- 'up-right', 'up-left', 'down-right', 'down-left',
- ] as ArrowDirection[]).map((direction) => {
- const ArrowComponent = getArrowComponent(direction);
- return (
- <button
- key={direction}
- onClick={() => {
- const newFigureData: FigureData = {
- ...annotation.figureData!,
- arrowDirection: direction,
- };
- onFigureDataChange?.(newFigureData);
- }}
- className={cn(
- "h-16 rounded-lg border flex items-center justify-center transition-all p-2",
- annotation.figureData?.arrowDirection === direction
- ? "bg-[#2563EB] border-[#2563EB]"
- : "bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20"
- )}
- >
- <ArrowComponent
- color={annotation.figureData?.arrowDirection === direction ? "#ffffff" : "#94a3b8"}
- strokeWidth={3}
- />
- </button>
- );
- })}
- </div>
- </div>
-
- <div>
- <label className="text-xs font-medium text-slate-200 mb-2 block">
- {t('annotations.strokeWidth', undefined, { width: annotation.figureData?.strokeWidth || 4 })}
- </label>
- <Slider
- value={[annotation.figureData?.strokeWidth || 4]}
- onValueChange={([value]) => {
- const newFigureData: FigureData = {
- ...annotation.figureData!,
- strokeWidth: value,
- };
- onFigureDataChange?.(newFigureData);
- }}
- min={1}
- max={6}
- step={1}
- className="w-full"
- />
- </div>
-
- <div>
- <label className="text-xs font-medium text-slate-200 mb-2 block">{t('annotations.arrowColor')}</label>
- <Popover>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- className="w-full h-10 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10"
- >
- <div
- className="w-5 h-5 rounded-full border border-white/20"
- style={{ backgroundColor: annotation.figureData?.color || '#2563EB' }}
- />
- <span className="text-xs text-slate-300 truncate flex-1 text-left">
- {annotation.figureData?.color || '#2563EB'}
- </span>
- <ChevronDown className="h-3 w-3 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl">
- <Block
- color={annotation.figureData?.color || '#2563EB'}
- colors={colorPalette}
- onChange={(color) => {
- const newFigureData: FigureData = {
- ...annotation.figureData!,
- color: color.hex,
- };
- onFigureDataChange?.(newFigureData);
- }}
- style={{
- borderRadius: '8px',
- }}
- />
- </PopoverContent>
- </Popover>
- </div>
- </TabsContent>
-
- <TabsContent value="blur" className="mt-0 space-y-4">
- <div className="p-4 bg-white/5 rounded-xl border border-white/10 flex flex-col items-center">
- <div className="w-full space-y-3">
- <div className="flex items-center justify-between">
- <span className="text-xs font-medium text-slate-200">
- {t('annotations.blurStrength', undefined, { strength: annotation.blurIntensity ?? 20 })}
- </span>
- </div>
- <Slider
- value={[annotation.blurIntensity ?? 20]}
- onValueChange={([value]) => onBlurIntensityChange?.(value)}
- min={1}
- max={100}
- step={1}
- className="w-full"
- />
- </div>
-
- <div className="w-full space-y-3 mt-4">
- <div className="flex items-center justify-between">
- <span className="text-xs font-medium text-slate-200">
- {t('annotations.solidColor', 'Solid Color (Censorship)')}
- </span>
- </div>
- <div className="flex flex-wrap gap-2">
- <button
- onClick={() => onBlurColorChange?.('')}
- className={cn(
- "w-8 h-8 rounded-full border-2 flex items-center justify-center transition-all",
- !annotation.blurColor || annotation.blurColor === 'transparent' ? "border-[#2563EB] scale-110" : "border-transparent hover:border-white/20"
- )}
- title={t('annotations.none', 'None')}
- >
- <div className="w-5 h-5 rounded-full bg-slate-800 flex items-center justify-center overflow-hidden relative">
- <div className="absolute w-full h-0.5 bg-red-500 rotate-45" />
- </div>
- </button>
- <button
- onClick={() => onBlurColorChange?.('#000000')}
- className={cn(
- "w-8 h-8 rounded-full border-2 transition-all bg-black",
- annotation.blurColor === '#000000' ? "border-[#2563EB] scale-110" : "border-transparent hover:border-white/20"
- )}
- title="Black"
- />
- <button
- onClick={() => onBlurColorChange?.('#FFFFFF')}
- className={cn(
- "w-8 h-8 rounded-full border-2 transition-all bg-white",
- annotation.blurColor === '#FFFFFF' ? "border-[#2563EB] scale-110" : "border-transparent hover:border-white/20"
- )}
- title="White"
- />
-
- <Popover>
- <PopoverTrigger asChild>
- <button
- className={cn(
- "w-8 h-8 rounded-full border-2 transition-all flex items-center justify-center overflow-hidden relative",
- annotation.blurColor && !['#000000', '#FFFFFF', 'transparent', ''].includes(annotation.blurColor) ? "border-[#2563EB] scale-110" : "border-transparent hover:border-white/20"
- )}
- style={{ backgroundColor: (annotation.blurColor && !['#000000', '#FFFFFF', 'transparent', ''].includes(annotation.blurColor)) ? annotation.blurColor : 'transparent' }}
- title="Custom Color"
- >
- {(!annotation.blurColor || ['#000000', '#FFFFFF', 'transparent', ''].includes(annotation.blurColor)) && (
- <div className="w-full h-full flex items-center justify-center bg-white/5">
- <div className="w-full h-full bg-gradient-to-tr from-red-500 via-green-500 to-blue-500 opacity-50" />
- </div>
- )}
- </button>
- </PopoverTrigger>
- <PopoverContent className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl">
- <Block
- color={annotation.blurColor || '#2563EB'}
- colors={colorPalette}
- onChange={(color) => {
- onBlurColorChange?.(color.hex);
- }}
- style={{
- borderRadius: '8px',
- }}
- />
- </PopoverContent>
- </Popover>
- </div>
- </div>
- </div>
- </TabsContent>
- </Tabs>
-
- <Button
- onClick={onDelete}
- variant="destructive"
- size="sm"
- className="w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all mt-4"
- >
- <Trash2 className="w-4 h-4" />
- {t('annotations.deleteAnnotation')}
- </Button>
-
- <div className="mt-6 p-3 bg-white/5 rounded-lg border border-white/5">
- <div className="flex items-center gap-2 mb-2 text-slate-300">
- <Info className="w-3.5 h-3.5" />
- <span className="text-xs font-medium">{t('annotations.shortcutsAndTips')}</span>
- </div>
- <ul className="text-[10px] text-slate-400 space-y-1.5 list-disc pl-3 leading-relaxed">
- <li>{t('annotations.tipSelectAnnotation')}</li>
- <li>{t('annotations.tipCycleForward')}</li>
- <li>{t('annotations.tipCycleBackward')}</li>
- </ul>
- </div>
- </div>
- </div>
- );
+ const t = useScopedT("editor");
+ const fileInputRef = useRef<HTMLInputElement>(null);
+ const [customFonts, setCustomFonts] = useState<CustomFont[]>([]);
+
+ const fontFamilies = useMemo(
+ () => FONT_FAMILY_VALUES.map((f) => ({ value: f.value, label: t(f.labelKey) })),
+ [t],
+ );
+
+ // Load custom fonts on mount
+ useEffect(() => {
+ setCustomFonts(getCustomFonts());
+ }, []);
+
+ const colorPalette = [
+ "#FF0000", // Red
+ "#FFD700", // Yellow/Gold
+ "#00FF00", // Green
+ "#FFFFFF", // White
+ "#0000FF", // Blue
+ "#FF6B00", // Orange
+ "#9B59B6", // Purple
+ "#E91E63", // Pink
+ "#00BCD4", // Cyan
+ "#FF5722", // Deep Orange
+ "#8BC34A", // Light Green
+ "#FFC107", // Amber
+ "#2563EB", // Brand Blue
+ "#000000", // Black
+ "#607D8B", // Blue Grey
+ "#795548", // Brown
+ ];
+
+ const handleImageUpload = (event: React.ChangeEvent<HTMLInputElement>) => {
+ const files = event.target.files;
+ if (!files || files.length === 0) return;
+
+ const file = files[0];
+
+ // Validate file type
+ const validTypes = ["image/jpeg", "image/jpg", "image/png", "image/gif", "image/webp"];
+ if (!validTypes.includes(file.type)) {
+ toast.error(t("annotations.imageUploadError"), {
+ description: t("annotations.imageUploadErrorDescription"),
+ });
+ event.target.value = "";
+ return;
+ }
+
+ const reader = new FileReader();
+
+ reader.onload = (e) => {
+ const dataUrl = e.target?.result as string;
+ if (dataUrl) {
+ onContentChange(dataUrl);
+ toast.success(t("annotations.imageUploadSuccess"));
+ }
+ };
+
+ reader.onerror = () => {
+ toast.error(t("annotations.imageUploadFailed"), {
+ description: t("annotations.imageUploadFailedDescription"),
+ });
+ };
+
+ reader.readAsDataURL(file);
+ event.target.value = "";
+ };
+
+ return (
+ <div className="flex-[2] min-w-0 bg-[#161619] border border-white/10 rounded-2xl p-4 flex flex-col shadow-xl h-full overflow-y-auto custom-scrollbar">
+ <div className="mb-6">
+ <div className="flex items-center justify-between mb-4">
+ <span className="text-sm font-medium text-slate-200">
+ {t("annotations.settings")}
+ </span>
+ <span className="text-[10px] uppercase tracking-wider font-medium text-[#2563EB] bg-[#2563EB]/10 px-2 py-1 rounded-full">
+ {t("annotations.active")}
+ </span>
+ </div>
+
+ {/* Type Selector */}
+ <Tabs
+ value={annotation.type}
+ onValueChange={(value) => onTypeChange(value as AnnotationType)}
+ className="mb-6"
+ >
+ <TabsList className="mb-4 bg-white/5 border border-white/5 p-1 w-full grid grid-cols-4 h-auto rounded-xl">
+ <TabsTrigger
+ value="text"
+ className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2"
+ >
+ <Type className="w-4 h-4" />
+ {t("annotations.text")}
+ </TabsTrigger>
+ <TabsTrigger
+ value="image"
+ className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2"
+ >
+ <ImageIcon className="w-4 h-4" />
+ {t("annotations.image")}
+ </TabsTrigger>
+ <TabsTrigger
+ value="figure"
+ className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2"
+ >
+ <svg
+ className="w-4 h-4"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ >
+ <path
+ d="M4 12h16m0 0l-6-6m6 6l-6 6"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ />
+ </svg>
+ {t("annotations.arrow")}
+ </TabsTrigger>
+ <TabsTrigger
+ value="blur"
+ className="data-[state=active]:bg-[#2563EB] data-[state=active]:text-white text-slate-400 py-2 rounded-lg transition-all gap-2"
+ >
+ <SquareDashed className="w-4 h-4" />
+ {t("annotations.blur")}
+ </TabsTrigger>
+ </TabsList>
+
+ {/* Text Content */}
+ <TabsContent value="text" className="mt-0 space-y-4">
+ <div>
+ <label className="text-xs font-medium text-slate-200 mb-2 block">
+ {t("annotations.textContent")}
+ </label>
+ <textarea
+ value={annotation.textContent || annotation.content}
+ onChange={(e) => onContentChange(e.target.value)}
+ placeholder={t("annotations.textPlaceholder")}
+ rows={5}
+ className="w-full px-3 py-2 bg-white/5 border border-white/10 rounded-lg text-slate-200 text-sm placeholder:text-slate-500 focus:outline-none focus:ring-2 focus:ring-[#2563EB] focus:border-transparent resize-none"
+ />
+ </div>
+
+ {/* Styling Controls */}
+ <div className="space-y-4">
+ {/* Font Family & Size */}
+ <div className="grid grid-cols-2 gap-2">
+ <div>
+ <label className="text-xs font-medium text-slate-200 mb-2 block">
+ {t("annotations.fontStyle")}
+ </label>
+ <Select
+ value={annotation.style.fontFamily}
+ onValueChange={(value) =>
+ onStyleChange({ fontFamily: value })
+ }
+ >
+ <SelectTrigger className="w-full bg-white/5 border-white/10 text-slate-200 h-9 text-xs">
+ <SelectValue
+ placeholder={t("annotations.selectStyle")}
+ />
+ </SelectTrigger>
+ <SelectContent className="bg-[#1a1a1c] border-white/10 text-slate-200 max-h-[300px]">
+ {fontFamilies.map((font) => (
+ <SelectItem
+ key={font.value}
+ value={font.value}
+ style={{ fontFamily: font.value }}
+ >
+ {font.label}
+ </SelectItem>
+ ))}
+ {customFonts.length > 0 && (
+ <>
+ <div className="px-2 py-1.5 text-[10px] font-medium text-slate-400 uppercase tracking-wider">
+ Custom Fonts
+ </div>
+ {customFonts.map((font) => (
+ <SelectItem
+ key={font.id}
+ value={font.fontFamily}
+ style={{ fontFamily: font.fontFamily }}
+ >
+ {font.name}
+ </SelectItem>
+ ))}
+ </>
+ )}
+ </SelectContent>
+ </Select>
+ </div>
+ <div>
+ <label className="text-xs font-medium text-slate-200 mb-2 block">
+ {t("annotations.size")}
+ </label>
+ <Select
+ value={annotation.style.fontSize.toString()}
+ onValueChange={(value) =>
+ onStyleChange({ fontSize: parseInt(value) })
+ }
+ >
+ <SelectTrigger className="w-full bg-white/5 border-white/10 text-slate-200 h-9 text-xs">
+ <SelectValue placeholder={t("annotations.size")} />
+ </SelectTrigger>
+ <SelectContent className="bg-[#1a1a1c] border-white/10 text-slate-200 max-h-[200px]">
+ {FONT_SIZES.map((size) => (
+ <SelectItem key={size} value={size.toString()}>
+ {size}px
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ {/* Add Custom Font Button */}
+ <div>
+ <AddCustomFontDialog
+ onFontAdded={(font) => {
+ setCustomFonts(getCustomFonts());
+ onStyleChange({ fontFamily: font.fontFamily });
+ }}
+ />
+ </div>
+
+ {/* Formatting Toggles */}
+ <div className="flex items-center justify-between gap-2">
+ <ToggleGroup
+ type="multiple"
+ className="justify-start bg-white/5 p-1 rounded-lg border border-white/5"
+ >
+ <ToggleGroupItem
+ value="bold"
+ aria-label={t("annotations.toggleBold")}
+ data-state={
+ annotation.style.fontWeight === "bold" ? "on" : "off"
+ }
+ onClick={() =>
+ onStyleChange({
+ fontWeight:
+ annotation.style.fontWeight === "bold"
+ ? "normal"
+ : "bold",
+ })
+ }
+ className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
+ >
+ <Bold className="h-4 w-4" />
+ </ToggleGroupItem>
+ <ToggleGroupItem
+ value="italic"
+ aria-label={t("annotations.toggleItalic")}
+ data-state={
+ annotation.style.fontStyle === "italic" ? "on" : "off"
+ }
+ onClick={() =>
+ onStyleChange({
+ fontStyle:
+ annotation.style.fontStyle === "italic"
+ ? "normal"
+ : "italic",
+ })
+ }
+ className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
+ >
+ <Italic className="h-4 w-4" />
+ </ToggleGroupItem>
+ <ToggleGroupItem
+ value="underline"
+ aria-label={t("annotations.toggleUnderline")}
+ data-state={
+ annotation.style.textDecoration === "underline"
+ ? "on"
+ : "off"
+ }
+ onClick={() =>
+ onStyleChange({
+ textDecoration:
+ annotation.style.textDecoration === "underline"
+ ? "none"
+ : "underline",
+ })
+ }
+ className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
+ >
+ <Underline className="h-4 w-4" />
+ </ToggleGroupItem>
+ </ToggleGroup>
+
+ <ToggleGroup
+ type="single"
+ value={annotation.style.textAlign}
+ className="justify-start bg-white/5 p-1 rounded-lg border border-white/5"
+ >
+ <ToggleGroupItem
+ value="left"
+ aria-label={t("annotations.alignLeft")}
+ onClick={() => onStyleChange({ textAlign: "left" })}
+ className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
+ >
+ <AlignLeft className="h-4 w-4" />
+ </ToggleGroupItem>
+ <ToggleGroupItem
+ value="center"
+ aria-label={t("annotations.alignCenter")}
+ onClick={() => onStyleChange({ textAlign: "center" })}
+ className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
+ >
+ <AlignCenter className="h-4 w-4" />
+ </ToggleGroupItem>
+ <ToggleGroupItem
+ value="right"
+ aria-label={t("annotations.alignRight")}
+ onClick={() => onStyleChange({ textAlign: "right" })}
+ className="h-8 w-8 data-[state=on]:bg-[#2563EB] data-[state=on]:text-white text-slate-400 hover:bg-white/5 hover:text-slate-200"
+ >
+ <AlignRight className="h-4 w-4" />
+ </ToggleGroupItem>
+ </ToggleGroup>
+ </div>
+
+ {/* Colors */}
+ <div className="grid grid-cols-2 gap-4">
+ <div>
+ <label className="text-xs font-medium text-slate-200 mb-2 block">
+ {t("annotations.textColor")}
+ </label>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ className="w-full h-9 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10 px-2"
+ >
+ <div
+ className="w-4 h-4 rounded-full border border-white/20"
+ style={{
+ backgroundColor: annotation.style.color,
+ }}
+ />
+ <span className="text-xs text-slate-300 truncate flex-1 text-left">
+ {annotation.style.color}
+ </span>
+ <ChevronDown className="h-3 w-3 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl">
+ <Block
+ color={annotation.style.color}
+ colors={colorPalette}
+ onChange={(color) => {
+ onStyleChange({ color: color.hex });
+ }}
+ style={{
+ borderRadius: "8px",
+ }}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ <div>
+ <label className="text-xs font-medium text-slate-200 mb-2 block">
+ {t("annotations.background")}
+ </label>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ className="w-full h-9 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10 px-2"
+ >
+ <div className="w-4 h-4 rounded-full border border-white/20 relative overflow-hidden">
+ <div className="absolute inset-0 checkerboard-bg opacity-50" />
+ <div
+ className="absolute inset-0"
+ style={{
+ backgroundColor:
+ annotation.style.backgroundColor,
+ }}
+ />
+ </div>
+ <span className="text-xs text-slate-300 truncate flex-1 text-left">
+ {annotation.style.backgroundColor ===
+ "transparent"
+ ? t("annotations.none")
+ : "Color"}
+ </span>
+ <ChevronDown className="h-3 w-3 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl">
+ <Block
+ color={
+ annotation.style.backgroundColor ===
+ "transparent"
+ ? "#000000"
+ : annotation.style.backgroundColor
+ }
+ colors={colorPalette}
+ onChange={(color) => {
+ onStyleChange({ backgroundColor: color.hex });
+ }}
+ style={{
+ borderRadius: "8px",
+ }}
+ />
+ <Button
+ variant="ghost"
+ size="sm"
+ className="w-full mt-2 text-xs h-7 hover:bg-white/5 text-slate-400"
+ onClick={() => {
+ onStyleChange({
+ backgroundColor: "transparent",
+ });
+ }}
+ >
+ {t("annotations.clearBackground")}
+ </Button>
+ </PopoverContent>
+ </Popover>
+ </div>
+ </div>
+ </div>
+ </TabsContent>
+
+ {/* Image Upload */}
+ <TabsContent value="image" className="mt-0 space-y-4">
+ <input
+ type="file"
+ ref={fileInputRef}
+ onChange={handleImageUpload}
+ accept=".jpg,.jpeg,.png,.gif,.webp,image/*"
+ className="hidden"
+ />
+ <Button
+ onClick={() => fileInputRef.current?.click()}
+ variant="outline"
+ className="w-full gap-2 bg-white/5 text-slate-200 border-white/10 hover:bg-[#2563EB] hover:text-white hover:border-[#2563EB] transition-all py-8"
+ >
+ <Upload className="w-5 h-5" />
+ {t("annotations.uploadImage")}
+ </Button>
+
+ {annotation.content && annotation.content.startsWith("data:image") && (
+ <div className="rounded-lg border border-white/10 overflow-hidden bg-white/5 p-2">
+ <img
+ src={annotation.content}
+ alt="Uploaded annotation"
+ className="w-full h-auto rounded-md"
+ />
+ </div>
+ )}
+
+ <p className="text-xs text-slate-500 text-center leading-relaxed">
+ {t("annotations.supportedFormats")}
+ </p>
+ </TabsContent>
+
+ <TabsContent value="figure" className="mt-0 space-y-4">
+ <div>
+ <label className="text-xs font-medium text-slate-200 mb-3 block">
+ {t("annotations.arrowDirection")}
+ </label>
+ <div className="grid grid-cols-4 gap-2">
+ {(
+ [
+ "up",
+ "down",
+ "left",
+ "right",
+ "up-right",
+ "up-left",
+ "down-right",
+ "down-left",
+ ] as ArrowDirection[]
+ ).map((direction) => {
+ const ArrowComponent = getArrowComponent(direction);
+ return (
+ <button
+ key={direction}
+ onClick={() => {
+ const newFigureData: FigureData = {
+ ...annotation.figureData!,
+ arrowDirection: direction,
+ };
+ onFigureDataChange?.(newFigureData);
+ }}
+ className={cn(
+ "h-16 rounded-lg border flex items-center justify-center transition-all p-2",
+ annotation.figureData?.arrowDirection === direction
+ ? "bg-[#2563EB] border-[#2563EB]"
+ : "bg-white/5 border-white/10 hover:bg-white/10 hover:border-white/20",
+ )}
+ >
+ <ArrowComponent
+ color={
+ annotation.figureData?.arrowDirection ===
+ direction
+ ? "#ffffff"
+ : "#94a3b8"
+ }
+ strokeWidth={3}
+ />
+ </button>
+ );
+ })}
+ </div>
+ </div>
+
+ <div>
+ <label className="text-xs font-medium text-slate-200 mb-2 block">
+ {t("annotations.strokeWidth", undefined, {
+ width: annotation.figureData?.strokeWidth || 4,
+ })}
+ </label>
+ <Slider
+ value={[annotation.figureData?.strokeWidth || 4]}
+ onValueChange={([value]) => {
+ const newFigureData: FigureData = {
+ ...annotation.figureData!,
+ strokeWidth: value,
+ };
+ onFigureDataChange?.(newFigureData);
+ }}
+ min={1}
+ max={6}
+ step={1}
+ className="w-full"
+ />
+ </div>
+
+ <div>
+ <label className="text-xs font-medium text-slate-200 mb-2 block">
+ {t("annotations.arrowColor")}
+ </label>
+ <Popover>
+ <PopoverTrigger asChild>
+ <Button
+ variant="outline"
+ className="w-full h-10 justify-start gap-2 bg-white/5 border-white/10 hover:bg-white/10"
+ >
+ <div
+ className="w-5 h-5 rounded-full border border-white/20"
+ style={{
+ backgroundColor:
+ annotation.figureData?.color || "#2563EB",
+ }}
+ />
+ <span className="text-xs text-slate-300 truncate flex-1 text-left">
+ {annotation.figureData?.color || "#2563EB"}
+ </span>
+ <ChevronDown className="h-3 w-3 opacity-50" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl">
+ <Block
+ color={annotation.figureData?.color || "#2563EB"}
+ colors={colorPalette}
+ onChange={(color) => {
+ const newFigureData: FigureData = {
+ ...annotation.figureData!,
+ color: color.hex,
+ };
+ onFigureDataChange?.(newFigureData);
+ }}
+ style={{
+ borderRadius: "8px",
+ }}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ </TabsContent>
+
+ <TabsContent value="blur" className="mt-0 space-y-4">
+ <div className="p-4 bg-white/5 rounded-xl border border-white/10 flex flex-col items-center">
+ <div className="w-full space-y-3">
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-medium text-slate-200">
+ {t("annotations.blurStrength", undefined, {
+ strength: annotation.blurIntensity ?? 20,
+ })}
+ </span>
+ </div>
+ <Slider
+ value={[annotation.blurIntensity ?? 20]}
+ onValueChange={([value]) => onBlurIntensityChange?.(value)}
+ min={1}
+ max={100}
+ step={1}
+ className="w-full"
+ />
+ </div>
+
+ <div className="w-full space-y-3 mt-4">
+ <div className="flex items-center justify-between">
+ <span className="text-xs font-medium text-slate-200">
+ {t("annotations.solidColor", "Solid Color (Censorship)")}
+ </span>
+ </div>
+ <div className="flex flex-wrap gap-2">
+ <button
+ onClick={() => onBlurColorChange?.("")}
+ className={cn(
+ "w-8 h-8 rounded-full border-2 flex items-center justify-center transition-all",
+ !annotation.blurColor ||
+ annotation.blurColor === "transparent"
+ ? "border-[#2563EB] scale-110"
+ : "border-transparent hover:border-white/20",
+ )}
+ title={t("annotations.none", "None")}
+ >
+ <div className="w-5 h-5 rounded-full bg-slate-800 flex items-center justify-center overflow-hidden relative">
+ <div className="absolute w-full h-0.5 bg-red-500 rotate-45" />
+ </div>
+ </button>
+ <button
+ onClick={() => onBlurColorChange?.("#000000")}
+ className={cn(
+ "w-8 h-8 rounded-full border-2 transition-all bg-black",
+ annotation.blurColor === "#000000"
+ ? "border-[#2563EB] scale-110"
+ : "border-transparent hover:border-white/20",
+ )}
+ title="Black"
+ />
+ <button
+ onClick={() => onBlurColorChange?.("#FFFFFF")}
+ className={cn(
+ "w-8 h-8 rounded-full border-2 transition-all bg-white",
+ annotation.blurColor === "#FFFFFF"
+ ? "border-[#2563EB] scale-110"
+ : "border-transparent hover:border-white/20",
+ )}
+ title="White"
+ />
+
+ <Popover>
+ <PopoverTrigger asChild>
+ <button
+ className={cn(
+ "w-8 h-8 rounded-full border-2 transition-all flex items-center justify-center overflow-hidden relative",
+ annotation.blurColor &&
+ ![
+ "#000000",
+ "#FFFFFF",
+ "transparent",
+ "",
+ ].includes(annotation.blurColor)
+ ? "border-[#2563EB] scale-110"
+ : "border-transparent hover:border-white/20",
+ )}
+ style={{
+ backgroundColor:
+ annotation.blurColor &&
+ ![
+ "#000000",
+ "#FFFFFF",
+ "transparent",
+ "",
+ ].includes(annotation.blurColor)
+ ? annotation.blurColor
+ : "transparent",
+ }}
+ title="Custom Color"
+ >
+ {(!annotation.blurColor ||
+ [
+ "#000000",
+ "#FFFFFF",
+ "transparent",
+ "",
+ ].includes(annotation.blurColor)) && (
+ <div className="w-full h-full flex items-center justify-center bg-white/5">
+ <div className="w-full h-full bg-gradient-to-tr from-red-500 via-green-500 to-blue-500 opacity-50" />
+ </div>
+ )}
+ </button>
+ </PopoverTrigger>
+ <PopoverContent className="w-[260px] p-3 bg-[#1a1a1c] border border-white/10 rounded-xl shadow-xl">
+ <Block
+ color={annotation.blurColor || "#2563EB"}
+ colors={colorPalette}
+ onChange={(color) => {
+ onBlurColorChange?.(color.hex);
+ }}
+ style={{
+ borderRadius: "8px",
+ }}
+ />
+ </PopoverContent>
+ </Popover>
+ </div>
+ </div>
+ </div>
+ </TabsContent>
+ </Tabs>
+
+ <Button
+ onClick={onDelete}
+ variant="destructive"
+ size="sm"
+ className="w-full gap-2 bg-red-500/10 text-red-400 border border-red-500/20 hover:bg-red-500/20 hover:border-red-500/30 transition-all mt-4"
+ >
+ <Trash2 className="w-4 h-4" />
+ {t("annotations.deleteAnnotation")}
+ </Button>
+
+ <div className="mt-6 p-3 bg-white/5 rounded-lg border border-white/5">
+ <div className="flex items-center gap-2 mb-2 text-slate-300">
+ <Info className="w-3.5 h-3.5" />
+ <span className="text-xs font-medium">
+ {t("annotations.shortcutsAndTips")}
+ </span>
+ </div>
+ <ul className="text-[10px] text-slate-400 space-y-1.5 list-disc pl-3 leading-relaxed">
+ <li>{t("annotations.tipSelectAnnotation")}</li>
+ <li>{t("annotations.tipCycleForward")}</li>
+ <li>{t("annotations.tipCycleBackward")}</li>
+ </ul>
+ </div>
+ </div>
+ </div>
+ );
}
-
diff --git a/src/components/video-editor/ArrowSvgs.tsx b/src/components/video-editor/ArrowSvgs.tsx
index ebfbee5d..99c542ff 100644
--- a/src/components/video-editor/ArrowSvgs.tsx
+++ b/src/components/video-editor/ArrowSvgs.tsx
@@ -1,9 +1,9 @@
-import type { ArrowDirection } from './types';
+import type { ArrowDirection } from "./types";
interface ArrowSvgProps {
- color: string;
- strokeWidth: number;
- className?: string;
+ color: string;
+ strokeWidth: number;
+ className?: string;
}
/**
@@ -13,183 +13,190 @@ interface ArrowSvgProps {
*/
export function ArrowUp({ color, strokeWidth, className }: ArrowSvgProps) {
- return (
- <svg viewBox="0 0 100 100" className={className} style={{ width: '100%', height: '100%' }}>
- <defs>
- <filter id="arrow-shadow">
- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
- </filter>
- </defs>
- <path
- d="M 50 20 L 50 80 M 50 20 L 35 35 M 50 20 L 65 35"
- stroke={color}
- strokeWidth={strokeWidth}
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- filter="url(#arrow-shadow)"
- />
- </svg>
- );
+ return (
+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>
+ <defs>
+ <filter id="arrow-shadow">
+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
+ </filter>
+ </defs>
+ <path
+ d="M 50 20 L 50 80 M 50 20 L 35 35 M 50 20 L 65 35"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ filter="url(#arrow-shadow)"
+ />
+ </svg>
+ );
}
export function ArrowDown({ color, strokeWidth, className }: ArrowSvgProps) {
- return (
- <svg viewBox="0 0 100 100" className={className} style={{ width: '100%', height: '100%' }}>
- <defs>
- <filter id="arrow-shadow">
- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
- </filter>
- </defs>
- <path
- d="M 50 20 L 50 80 M 50 80 L 35 65 M 50 80 L 65 65"
- stroke={color}
- strokeWidth={strokeWidth}
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- filter="url(#arrow-shadow)"
- />
- </svg>
- );
+ return (
+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>
+ <defs>
+ <filter id="arrow-shadow">
+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
+ </filter>
+ </defs>
+ <path
+ d="M 50 20 L 50 80 M 50 80 L 35 65 M 50 80 L 65 65"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ filter="url(#arrow-shadow)"
+ />
+ </svg>
+ );
}
export function ArrowLeft({ color, strokeWidth, className }: ArrowSvgProps) {
- return (
- <svg viewBox="0 0 100 100" className={className} style={{ width: '100%', height: '100%' }}>
- <defs>
- <filter id="arrow-shadow">
- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
- </filter>
- </defs>
- <path
- d="M 80 50 L 20 50 M 20 50 L 35 35 M 20 50 L 35 65"
- stroke={color}
- strokeWidth={strokeWidth}
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- filter="url(#arrow-shadow)"
- />
- </svg>
- );
+ return (
+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>
+ <defs>
+ <filter id="arrow-shadow">
+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
+ </filter>
+ </defs>
+ <path
+ d="M 80 50 L 20 50 M 20 50 L 35 35 M 20 50 L 35 65"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ filter="url(#arrow-shadow)"
+ />
+ </svg>
+ );
}
export function ArrowRight({ color, strokeWidth, className }: ArrowSvgProps) {
- return (
- <svg viewBox="0 0 100 100" className={className} style={{ width: '100%', height: '100%' }}>
- <defs>
- <filter id="arrow-shadow">
- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
- </filter>
- </defs>
- <path
- d="M 20 50 L 80 50 M 80 50 L 65 35 M 80 50 L 65 65"
- stroke={color}
- strokeWidth={strokeWidth}
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- filter="url(#arrow-shadow)"
- />
- </svg>
- );
+ return (
+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>
+ <defs>
+ <filter id="arrow-shadow">
+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
+ </filter>
+ </defs>
+ <path
+ d="M 20 50 L 80 50 M 80 50 L 65 35 M 80 50 L 65 65"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ filter="url(#arrow-shadow)"
+ />
+ </svg>
+ );
}
export function ArrowUpRight({ color, strokeWidth, className }: ArrowSvgProps) {
- return (
- <svg viewBox="0 0 100 100" className={className} style={{ width: '100%', height: '100%' }}>
- <defs>
- <filter id="arrow-shadow">
- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
- </filter>
- </defs>
- <path
- d="M 25 75 L 75 25 M 75 25 L 60 30 M 75 25 L 70 40"
- stroke={color}
- strokeWidth={strokeWidth}
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- filter="url(#arrow-shadow)"
- />
- </svg>
- );
+ return (
+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>
+ <defs>
+ <filter id="arrow-shadow">
+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
+ </filter>
+ </defs>
+ <path
+ d="M 25 75 L 75 25 M 75 25 L 60 30 M 75 25 L 70 40"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ filter="url(#arrow-shadow)"
+ />
+ </svg>
+ );
}
export function ArrowUpLeft({ color, strokeWidth, className }: ArrowSvgProps) {
- return (
- <svg viewBox="0 0 100 100" className={className} style={{ width: '100%', height: '100%' }}>
- <defs>
- <filter id="arrow-shadow">
- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
- </filter>
- </defs>
- <path
- d="M 75 75 L 25 25 M 25 25 L 40 30 M 25 25 L 30 40"
- stroke={color}
- strokeWidth={strokeWidth}
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- filter="url(#arrow-shadow)"
- />
- </svg>
- );
+ return (
+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>
+ <defs>
+ <filter id="arrow-shadow">
+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
+ </filter>
+ </defs>
+ <path
+ d="M 75 75 L 25 25 M 25 25 L 40 30 M 25 25 L 30 40"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ filter="url(#arrow-shadow)"
+ />
+ </svg>
+ );
}
export function ArrowDownRight({ color, strokeWidth, className }: ArrowSvgProps) {
- return (
- <svg viewBox="0 0 100 100" className={className} style={{ width: '100%', height: '100%' }}>
- <defs>
- <filter id="arrow-shadow">
- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
- </filter>
- </defs>
- <path
- d="M 25 25 L 75 75 M 75 75 L 70 60 M 75 75 L 60 70"
- stroke={color}
- strokeWidth={strokeWidth}
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- filter="url(#arrow-shadow)"
- />
- </svg>
- );
+ return (
+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>
+ <defs>
+ <filter id="arrow-shadow">
+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
+ </filter>
+ </defs>
+ <path
+ d="M 25 25 L 75 75 M 75 75 L 70 60 M 75 75 L 60 70"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ filter="url(#arrow-shadow)"
+ />
+ </svg>
+ );
}
export function ArrowDownLeft({ color, strokeWidth, className }: ArrowSvgProps) {
- return (
- <svg viewBox="0 0 100 100" className={className} style={{ width: '100%', height: '100%' }}>
- <defs>
- <filter id="arrow-shadow">
- <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
- </filter>
- </defs>
- <path
- d="M 75 25 L 25 75 M 25 75 L 30 60 M 25 75 L 40 70"
- stroke={color}
- strokeWidth={strokeWidth}
- strokeLinecap="round"
- strokeLinejoin="round"
- fill="none"
- filter="url(#arrow-shadow)"
- />
- </svg>
- );
+ return (
+ <svg viewBox="0 0 100 100" className={className} style={{ width: "100%", height: "100%" }}>
+ <defs>
+ <filter id="arrow-shadow">
+ <feDropShadow dx="0" dy="2" stdDeviation="4" floodOpacity="0.3" />
+ </filter>
+ </defs>
+ <path
+ d="M 75 25 L 25 75 M 25 75 L 30 60 M 25 75 L 40 70"
+ stroke={color}
+ strokeWidth={strokeWidth}
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ fill="none"
+ filter="url(#arrow-shadow)"
+ />
+ </svg>
+ );
}
export function getArrowComponent(direction: ArrowDirection) {
- switch (direction) {
- case 'up': return ArrowUp;
- case 'down': return ArrowDown;
- case 'left': return ArrowLeft;
- case 'right': return ArrowRight;
- case 'up-right': return ArrowUpRight;
- case 'up-left': return ArrowUpLeft;
- case 'down-right': return ArrowDownRight;
- case 'down-left': return ArrowDownLeft;
- }
+ switch (direction) {
+ case "up":
+ return ArrowUp;
+ case "down":
+ return ArrowDown;
+ case "left":
+ return ArrowLeft;
+ case "right":
+ return ArrowRight;
+ case "up-right":
+ return ArrowUpRight;
+ case "up-left":
+ return ArrowUpLeft;
+ case "down-right":
+ return ArrowDownRight;
+ case "down-left":
+ return ArrowDownLeft;
+ }
}
-
diff --git a/src/components/video-editor/CropControl.tsx b/src/components/video-editor/CropControl.tsx
index f12380a8..11ceacc9 100644
--- a/src/components/video-editor/CropControl.tsx
+++ b/src/components/video-editor/CropControl.tsx
@@ -3,232 +3,255 @@ import { cn } from "@/lib/utils";
import { type AspectRatio } from "@/utils/aspectRatioUtils";
interface CropRegion {
- x: number; // 0-1 normalized
- y: number; // 0-1 normalized
- width: number; // 0-1 normalized
- height: number; // 0-1 normalized
+ x: number; // 0-1 normalized
+ y: number; // 0-1 normalized
+ width: number; // 0-1 normalized
+ height: number; // 0-1 normalized
}
interface CropControlProps {
- videoElement: HTMLVideoElement | null;
- cropRegion: CropRegion;
- onCropChange: (region: CropRegion) => void;
- aspectRatio: AspectRatio;
+ videoElement: HTMLVideoElement | null;
+ cropRegion: CropRegion;
+ onCropChange: (region: CropRegion) => void;
+ aspectRatio: AspectRatio;
}
-type DragHandle = 'top' | 'right' | 'bottom' | 'left' | null;
+type DragHandle = "top" | "right" | "bottom" | "left" | null;
export function CropControl({ videoElement, cropRegion, onCropChange }: CropControlProps) {
- const canvasRef = useRef<HTMLCanvasElement>(null);
- const containerRef = useRef<HTMLDivElement>(null);
- const [isDragging, setIsDragging] = useState<DragHandle>(null);
- const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
- const [initialCrop, setInitialCrop] = useState<CropRegion>(cropRegion);
-
- useEffect(() => {
- if (!videoElement || !canvasRef.current) return;
-
- const canvas = canvasRef.current;
- const ctx = canvas.getContext('2d', { alpha: false });
- if (!ctx) return;
-
- canvas.width = videoElement.videoWidth || 1920;
- canvas.height = videoElement.videoHeight || 1080;
-
- const draw = () => {
- if (videoElement.readyState >= 2) {
- ctx.clearRect(0, 0, canvas.width, canvas.height);
- ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
- }
- requestAnimationFrame(draw);
- };
-
- const rafId = requestAnimationFrame(draw);
- return () => cancelAnimationFrame(rafId);
- }, [videoElement]);
-
- const getContainerRect = () => {
- return containerRef.current?.getBoundingClientRect() || { width: 0, height: 0, left: 0, top: 0 };
- };
-
- const handlePointerDown = (e: React.PointerEvent, handle: DragHandle) => {
- e.stopPropagation();
- e.preventDefault();
- setIsDragging(handle);
- const rect = getContainerRect();
- setDragStart({
- x: (e.clientX - rect.left) / rect.width,
- y: (e.clientY - rect.top) / rect.height,
- });
- setInitialCrop(cropRegion);
-
- e.currentTarget.setPointerCapture(e.pointerId);
- };
-
- const handlePointerMove = (e: React.PointerEvent) => {
- if (!isDragging) return;
-
- const rect = getContainerRect();
- const currentX = (e.clientX - rect.left) / rect.width;
- const currentY = (e.clientY - rect.top) / rect.height;
- const deltaX = currentX - dragStart.x;
- const deltaY = currentY - dragStart.y;
-
- let newCrop = { ...initialCrop };
-
- switch (isDragging) {
- case 'top': {
- const newY = Math.max(0, initialCrop.y + deltaY);
- const bottom = initialCrop.y + initialCrop.height;
- newCrop.y = Math.min(newY, bottom - 0.1);
- newCrop.height = bottom - newCrop.y;
- break;
- }
- case 'bottom':
- newCrop.height = Math.max(0.1, Math.min(initialCrop.height + deltaY, 1 - initialCrop.y));
- break;
- case 'left': {
- const newX = Math.max(0, initialCrop.x + deltaX);
- const right = initialCrop.x + initialCrop.width;
- newCrop.x = Math.min(newX, right - 0.1);
- newCrop.width = right - newCrop.x;
- break;
- }
- case 'right':
- newCrop.width = Math.max(0.1, Math.min(initialCrop.width + deltaX, 1 - initialCrop.x));
- break;
- }
-
- onCropChange(newCrop);
- };
-
- const handlePointerUp = (e: React.PointerEvent) => {
- if (isDragging) {
- try {
- e.currentTarget.releasePointerCapture(e.pointerId);
- } catch {
- }
- }
- setIsDragging(null);
- };
-
- const cropPixelX = cropRegion.x * 100;
- const cropPixelY = cropRegion.y * 100;
- const cropPixelWidth = cropRegion.width * 100;
- const cropPixelHeight = cropRegion.height * 100;
- const videoAspectRatio = videoElement ? videoElement.videoWidth / videoElement.videoHeight : 16/9;
- const isVideoPortrait = videoAspectRatio < 1;
- const maxContainerWidth = isVideoPortrait ? '40vw' : '75vw';
- const maxContainerHeight = '75vh';
-
- return (
- <div className="w-full p-8">
- <div
- ref={containerRef}
- className="relative w-full bg-black rounded-lg overflow-visible cursor-default select-none shadow-2xl"
- style={{
- aspectRatio: videoAspectRatio,
- maxWidth: maxContainerWidth,
- maxHeight: maxContainerHeight,
- margin: '0 auto',
- }}
- onPointerMove={handlePointerMove}
- onPointerUp={handlePointerUp}
- onPointerLeave={handlePointerUp}
- >
- <canvas
- ref={canvasRef}
- className="w-full h-full rounded-lg"
- style={{ imageRendering: 'auto' }}
- />
-
- <div className="absolute inset-0 pointer-events-none" style={{ transition: 'none' }}>
- <svg width="100%" height="100%" className="absolute inset-0" style={{ transition: 'none' }}>
- <defs>
- <mask id="cropMask">
- <rect width="100%" height="100%" fill="white" />
- <rect
- x={`${cropPixelX}%`}
- y={`${cropPixelY}%`}
- width={`${cropPixelWidth}%`}
- height={`${cropPixelHeight}%`}
- fill="black"
- style={{ transition: 'none' }}
- />
- </mask>
- </defs>
- <rect
- width="100%"
- height="100%"
- fill="black"
- fillOpacity="0.6"
- mask="url(#cropMask)"
- style={{ transition: 'none' }}
- />
- </svg>
- </div>
-
- <div
- className={cn(
- "absolute h-[3px] cursor-ns-resize z-20 pointer-events-auto bg-[#2563EB]"
- )}
- style={{
- left: `${cropPixelX}%`,
- top: `${cropPixelY}%`,
- width: `${cropPixelWidth}%`,
- transform: 'translateY(-50%)',
- willChange: 'transform',
- transition: 'none',
- }}
- onPointerDown={(e) => handlePointerDown(e, 'top')}
- />
-
- <div
- className={cn(
- "absolute h-[3px] cursor-ns-resize z-20 pointer-events-auto bg-[#2563EB]"
- )}
- style={{
- left: `${cropPixelX}%`,
- top: `${cropPixelY + cropPixelHeight}%`,
- width: `${cropPixelWidth}%`,
- transform: 'translateY(-50%)',
- willChange: 'transform',
- transition: 'none',
- }}
- onPointerDown={(e) => handlePointerDown(e, 'bottom')}
- />
-
- <div
- className={cn(
- "absolute w-[3px] cursor-ew-resize z-20 pointer-events-auto bg-[#2563EB]"
- )}
- style={{
- left: `${cropPixelX}%`,
- top: `${cropPixelY}%`,
- height: `${cropPixelHeight}%`,
- transform: 'translateX(-50%)',
- willChange: 'transform',
- transition: 'none',
- }}
- onPointerDown={(e) => handlePointerDown(e, 'left')}
- />
-
- <div
- className={cn(
- "absolute w-[3px] cursor-ew-resize z-20 pointer-events-auto bg-[#2563EB]"
- )}
- style={{
- left: `${cropPixelX + cropPixelWidth}%`,
- top: `${cropPixelY}%`,
- height: `${cropPixelHeight}%`,
- transform: 'translateX(-50%)',
- willChange: 'transform',
- transition: 'none',
- }}
- onPointerDown={(e) => handlePointerDown(e, 'right')}
- />
- </div>
- </div>
- );
-}
+ const canvasRef = useRef<HTMLCanvasElement>(null);
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [isDragging, setIsDragging] = useState<DragHandle>(null);
+ const [dragStart, setDragStart] = useState({ x: 0, y: 0 });
+ const [initialCrop, setInitialCrop] = useState<CropRegion>(cropRegion);
+
+ useEffect(() => {
+ if (!videoElement || !canvasRef.current) return;
+
+ const canvas = canvasRef.current;
+ const ctx = canvas.getContext("2d", { alpha: false });
+ if (!ctx) return;
+
+ canvas.width = videoElement.videoWidth || 1920;
+ canvas.height = videoElement.videoHeight || 1080;
+
+ const draw = () => {
+ if (videoElement.readyState >= 2) {
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
+ ctx.drawImage(videoElement, 0, 0, canvas.width, canvas.height);
+ }
+ requestAnimationFrame(draw);
+ };
+
+ const rafId = requestAnimationFrame(draw);
+ return () => cancelAnimationFrame(rafId);
+ }, [videoElement]);
+
+ const getContainerRect = () => {
+ return (
+ containerRef.current?.getBoundingClientRect() || {
+ width: 0,
+ height: 0,
+ left: 0,
+ top: 0,
+ }
+ );
+ };
+
+ const handlePointerDown = (e: React.PointerEvent, handle: DragHandle) => {
+ e.stopPropagation();
+ e.preventDefault();
+ setIsDragging(handle);
+ const rect = getContainerRect();
+ setDragStart({
+ x: (e.clientX - rect.left) / rect.width,
+ y: (e.clientY - rect.top) / rect.height,
+ });
+ setInitialCrop(cropRegion);
+
+ e.currentTarget.setPointerCapture(e.pointerId);
+ };
+
+ const handlePointerMove = (e: React.PointerEvent) => {
+ if (!isDragging) return;
+
+ const rect = getContainerRect();
+ const currentX = (e.clientX - rect.left) / rect.width;
+ const currentY = (e.clientY - rect.top) / rect.height;
+ const deltaX = currentX - dragStart.x;
+ const deltaY = currentY - dragStart.y;
+ let newCrop = { ...initialCrop };
+
+ switch (isDragging) {
+ case "top": {
+ const newY = Math.max(0, initialCrop.y + deltaY);
+ const bottom = initialCrop.y + initialCrop.height;
+ newCrop.y = Math.min(newY, bottom - 0.1);
+ newCrop.height = bottom - newCrop.y;
+ break;
+ }
+ case "bottom":
+ newCrop.height = Math.max(
+ 0.1,
+ Math.min(initialCrop.height + deltaY, 1 - initialCrop.y),
+ );
+ break;
+ case "left": {
+ const newX = Math.max(0, initialCrop.x + deltaX);
+ const right = initialCrop.x + initialCrop.width;
+ newCrop.x = Math.min(newX, right - 0.1);
+ newCrop.width = right - newCrop.x;
+ break;
+ }
+ case "right":
+ newCrop.width = Math.max(
+ 0.1,
+ Math.min(initialCrop.width + deltaX, 1 - initialCrop.x),
+ );
+ break;
+ }
+
+ onCropChange(newCrop);
+ };
+
+ const handlePointerUp = (e: React.PointerEvent) => {
+ if (isDragging) {
+ try {
+ e.currentTarget.releasePointerCapture(e.pointerId);
+ } catch {
+ /* Pointer capture may already be released while ending the drag. */
+ }
+ }
+ setIsDragging(null);
+ };
+
+ const cropPixelX = cropRegion.x * 100;
+ const cropPixelY = cropRegion.y * 100;
+ const cropPixelWidth = cropRegion.width * 100;
+ const cropPixelHeight = cropRegion.height * 100;
+ const videoAspectRatio = videoElement
+ ? videoElement.videoWidth / videoElement.videoHeight
+ : 16 / 9;
+ const isVideoPortrait = videoAspectRatio < 1;
+ const maxContainerWidth = isVideoPortrait ? "40vw" : "75vw";
+ const maxContainerHeight = "75vh";
+
+ return (
+ <div className="w-full p-8">
+ <div
+ ref={containerRef}
+ className="relative w-full bg-black rounded-lg overflow-visible cursor-default select-none shadow-2xl"
+ style={{
+ aspectRatio: videoAspectRatio,
+ maxWidth: maxContainerWidth,
+ maxHeight: maxContainerHeight,
+ margin: "0 auto",
+ }}
+ onPointerMove={handlePointerMove}
+ onPointerUp={handlePointerUp}
+ onPointerLeave={handlePointerUp}
+ >
+ <canvas
+ ref={canvasRef}
+ className="w-full h-full rounded-lg"
+ style={{ imageRendering: "auto" }}
+ />
+
+ <div
+ className="absolute inset-0 pointer-events-none"
+ style={{ transition: "none" }}
+ >
+ <svg
+ width="100%"
+ height="100%"
+ className="absolute inset-0"
+ style={{ transition: "none" }}
+ >
+ <defs>
+ <mask id="cropMask">
+ <rect width="100%" height="100%" fill="white" />
+ <rect
+ x={`${cropPixelX}%`}
+ y={`${cropPixelY}%`}
+ width={`${cropPixelWidth}%`}
+ height={`${cropPixelHeight}%`}
+ fill="black"
+ style={{ transition: "none" }}
+ />
+ </mask>
+ </defs>
+ <rect
+ width="100%"
+ height="100%"
+ fill="black"
+ fillOpacity="0.6"
+ mask="url(#cropMask)"
+ style={{ transition: "none" }}
+ />
+ </svg>
+ </div>
+
+ <div
+ className={cn(
+ "absolute h-[3px] cursor-ns-resize z-20 pointer-events-auto bg-[#2563EB]",
+ )}
+ style={{
+ left: `${cropPixelX}%`,
+ top: `${cropPixelY}%`,
+ width: `${cropPixelWidth}%`,
+ transform: "translateY(-50%)",
+ willChange: "transform",
+ transition: "none",
+ }}
+ onPointerDown={(e) => handlePointerDown(e, "top")}
+ />
+
+ <div
+ className={cn(
+ "absolute h-[3px] cursor-ns-resize z-20 pointer-events-auto bg-[#2563EB]",
+ )}
+ style={{
+ left: `${cropPixelX}%`,
+ top: `${cropPixelY + cropPixelHeight}%`,
+ width: `${cropPixelWidth}%`,
+ transform: "translateY(-50%)",
+ willChange: "transform",
+ transition: "none",
+ }}
+ onPointerDown={(e) => handlePointerDown(e, "bottom")}
+ />
+
+ <div
+ className={cn(
+ "absolute w-[3px] cursor-ew-resize z-20 pointer-events-auto bg-[#2563EB]",
+ )}
+ style={{
+ left: `${cropPixelX}%`,
+ top: `${cropPixelY}%`,
+ height: `${cropPixelHeight}%`,
+ transform: "translateX(-50%)",
+ willChange: "transform",
+ transition: "none",
+ }}
+ onPointerDown={(e) => handlePointerDown(e, "left")}
+ />
+
+ <div
+ className={cn(
+ "absolute w-[3px] cursor-ew-resize z-20 pointer-events-auto bg-[#2563EB]",
+ )}
+ style={{
+ left: `${cropPixelX + cropPixelWidth}%`,
+ top: `${cropPixelY}%`,
+ height: `${cropPixelHeight}%`,
+ transform: "translateX(-50%)",
+ willChange: "transform",
+ transition: "none",
+ }}
+ onPointerDown={(e) => handlePointerDown(e, "right")}
+ />
+ </div>
+ </div>
+ );
+}
diff --git a/src/components/video-editor/ExportSettingsMenu.tsx b/src/components/video-editor/ExportSettingsMenu.tsx
index d0cf053c..eee761d5 100644
--- a/src/components/video-editor/ExportSettingsMenu.tsx
+++ b/src/components/video-editor/ExportSettingsMenu.tsx
@@ -1,4 +1,4 @@
-import { Download, Film, Image } from "lucide-react";
+import { DownloadSimple as Download, FilmSlate as Film, Image } from "@phosphor-icons/react";
import { LayoutGroup, motion } from "motion/react";
import { Button } from "@/components/ui/button";
import { Switch } from "@/components/ui/switch";
@@ -47,7 +47,7 @@ export function ExportSettingsMenu({
onExportEncodingModeChange,
mp4FrameRate,
onMp4FrameRateChange,
- exportPipelineModel = "legacy",
+ exportPipelineModel = "modern",
onExportPipelineModelChange,
mp4OutputDimensions,
gifFrameRate,
@@ -64,7 +64,12 @@ export function ExportSettingsMenu({
const isLegacyModel = exportPipelineModel === "legacy";
return (
- <div className={cn("w-full rounded-2xl border border-white/10 bg-[#17171a] p-3 text-slate-200", className)}>
+ <div
+ className={cn(
+ "w-full rounded-2xl border border-white/10 bg-[#17171a] p-3 text-slate-200",
+ className,
+ )}
+ >
<div className="mb-2 flex items-center justify-between">
<span className="text-[11px] font-semibold uppercase tracking-[0.18em] text-slate-400">
{tSettings("export.title", "Export")}
@@ -73,10 +78,12 @@ export function ExportSettingsMenu({
<div className="mb-3 flex items-center gap-2">
<LayoutGroup id="header-export-format-toggle">
- {([
- { value: "mp4", label: tSettings("export.mp4"), icon: Film },
- { value: "gif", label: tSettings("export.gif"), icon: Image },
- ] as const).map((option) => {
+ {(
+ [
+ { value: "mp4", label: tSettings("export.mp4"), icon: Film },
+ { value: "gif", label: tSettings("export.gif"), icon: Image },
+ ] as const
+ ).map((option) => {
const Icon = option.icon;
const isActive = exportFormat === option.value;
return (
@@ -111,12 +118,14 @@ export function ExportSettingsMenu({
{exportFormat === "mp4" ? (
<LayoutGroup id="header-export-quality-toggle">
<div className="mb-3 grid min-h-12 w-full grid-cols-4 rounded-xl border border-white/5 bg-white/5 p-0.5">
- {([
- { value: "medium", label: tSettings("export.quality.low") },
- { value: "good", label: tSettings("export.quality.medium") },
- { value: "high", label: tSettings("export.quality.high") },
- { value: "source", label: tSettings("export.quality.original") },
- ] as const).map((option) => {
+ {(
+ [
+ { value: "medium", label: tSettings("export.quality.low") },
+ { value: "good", label: tSettings("export.quality.medium") },
+ { value: "high", label: tSettings("export.quality.high") },
+ { value: "source", label: tSettings("export.quality.original") },
+ ] as const
+ ).map((option) => {
const isActive = exportQuality === option.value;
return (
<button
@@ -129,16 +138,32 @@ export function ExportSettingsMenu({
<motion.span
layoutId="header-export-quality-pill"
className="absolute inset-0 rounded-lg bg-white"
- transition={{ type: "spring", stiffness: 420, damping: 34 }}
+ transition={{
+ type: "spring",
+ stiffness: 420,
+ damping: 34,
+ }}
/>
) : null}
<span className="relative z-10 flex h-full flex-col items-center justify-center leading-tight">
- <span className={cn(isActive ? "text-black" : "text-slate-400 hover:text-slate-200")}>
+ <span
+ className={cn(
+ isActive
+ ? "text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
{option.label}
</span>
{mp4OutputDimensions ? (
- <span className={cn("mt-0.5 text-[9px]", isActive ? "text-black/75" : "text-slate-500") }>
- {mp4OutputDimensions[option.value].width} x {mp4OutputDimensions[option.value].height}
+ <span
+ className={cn(
+ "mt-0.5 text-[9px]",
+ isActive ? "text-black/75" : "text-slate-500",
+ )}
+ >
+ {mp4OutputDimensions[option.value].width} x{" "}
+ {mp4OutputDimensions[option.value].height}
</span>
) : null}
</span>
@@ -152,11 +177,19 @@ export function ExportSettingsMenu({
</span>
</div>
<div className="mb-3 grid min-h-10 w-full grid-cols-3 rounded-xl border border-white/5 bg-white/5 p-0.5">
- {([
- { value: "fast", label: tSettings("export.encoding.fast", "Fast") },
- { value: "balanced", label: tSettings("export.encoding.balanced", "Balanced") },
- { value: "quality", label: tSettings("export.encoding.quality", "Quality") },
- ] as const).map((option) => {
+ {(
+ [
+ { value: "fast", label: tSettings("export.encoding.fast", "Fast") },
+ {
+ value: "balanced",
+ label: tSettings("export.encoding.balanced", "Balanced"),
+ },
+ {
+ value: "quality",
+ label: tSettings("export.encoding.quality", "Quality"),
+ },
+ ] as const
+ ).map((option) => {
const isActive = exportEncodingMode === option.value;
return (
<button
@@ -169,10 +202,21 @@ export function ExportSettingsMenu({
<motion.span
layoutId="header-export-encoding-pill"
className="absolute inset-0 rounded-lg bg-white"
- transition={{ type: "spring", stiffness: 420, damping: 34 }}
+ transition={{
+ type: "spring",
+ stiffness: 420,
+ damping: 34,
+ }}
/>
) : null}
- <span className={cn("relative z-10", isActive ? "text-black" : "text-slate-400 hover:text-slate-200")}>
+ <span
+ className={cn(
+ "relative z-10",
+ isActive
+ ? "text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
{option.label}
</span>
</button>
@@ -198,10 +242,21 @@ export function ExportSettingsMenu({
<motion.span
layoutId="header-export-fps-pill"
className="absolute inset-0 rounded-lg bg-white"
- transition={{ type: "spring", stiffness: 420, damping: 34 }}
+ transition={{
+ type: "spring",
+ stiffness: 420,
+ damping: 34,
+ }}
/>
) : null}
- <span className={cn("relative z-10", isActive ? "text-black" : "text-slate-400 hover:text-slate-200")}>
+ <span
+ className={cn(
+ "relative z-10",
+ isActive
+ ? "text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
{rate}
</span>
</button>
@@ -214,10 +269,18 @@ export function ExportSettingsMenu({
</span>
</div>
<div className="mb-3 grid min-h-10 w-full grid-cols-2 rounded-xl border border-white/5 bg-white/5 p-0.5">
- {([
- { value: "legacy", label: tSettings("export.pipeline.legacy", "Legacy") },
- { value: "modern", label: tSettings("export.pipeline.modern", "Lightning (Beta)") },
- ] as const).map((option) => {
+ {(
+ [
+ {
+ value: "legacy",
+ label: tSettings("export.pipeline.legacy", "Legacy"),
+ },
+ {
+ value: "modern",
+ label: tSettings("export.pipeline.modern", "Lightning (Beta)"),
+ },
+ ] as const
+ ).map((option) => {
const isActive = exportPipelineModel === option.value;
return (
<button
@@ -230,10 +293,21 @@ export function ExportSettingsMenu({
<motion.span
layoutId="header-export-pipeline-pill"
className="absolute inset-0 rounded-lg bg-white"
- transition={{ type: "spring", stiffness: 420, damping: 34 }}
+ transition={{
+ type: "spring",
+ stiffness: 420,
+ damping: 34,
+ }}
/>
) : null}
- <span className={cn("relative z-10", isActive ? "text-black" : "text-slate-400 hover:text-slate-200")}>
+ <span
+ className={cn(
+ "relative z-10",
+ isActive
+ ? "text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
{option.label}
</span>
</button>
@@ -242,11 +316,14 @@ export function ExportSettingsMenu({
</div>
<p className="mb-3 px-1 text-[10px] text-slate-500">
{isLegacyModel
- ? tSettings("export.pipeline.legacyHint", "Legacy uses the current stable WebCodecs export path.")
+ ? tSettings(
+ "export.pipeline.legacyHint",
+ "Legacy uses the current stable WebCodecs export path.",
+ )
: tSettings(
"export.pipeline.lightningHint",
"Lightning (Beta) automatically uses the fastest compatible backend and falls back when needed.",
- )}
+ )}
</p>
</LayoutGroup>
) : (
@@ -264,9 +341,24 @@ export function ExportSettingsMenu({
className="relative rounded-lg text-[11px] font-medium transition-colors"
>
{isActive ? (
- <motion.span layoutId="header-gif-frame-rate-pill" className="absolute inset-0 rounded-lg bg-white" transition={{ type: "spring", stiffness: 420, damping: 34 }} />
+ <motion.span
+ layoutId="header-gif-frame-rate-pill"
+ className="absolute inset-0 rounded-lg bg-white"
+ transition={{
+ type: "spring",
+ stiffness: 420,
+ damping: 34,
+ }}
+ />
) : null}
- <span className={cn("relative z-10", isActive ? "text-black" : "text-slate-400 hover:text-slate-200")}>
+ <span
+ className={cn(
+ "relative z-10",
+ isActive
+ ? "text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
{rate.value}
</span>
</button>
@@ -282,18 +374,44 @@ export function ExportSettingsMenu({
<button
key={key}
type="button"
- onClick={() => onGifSizePresetChange?.(key as GifSizePreset)}
+ onClick={() =>
+ onGifSizePresetChange?.(key as GifSizePreset)
+ }
className="relative rounded-lg text-[11px] font-medium transition-colors"
>
{isActive ? (
- <motion.span layoutId="header-gif-size-pill" className="absolute inset-0 rounded-lg bg-white" transition={{ type: "spring", stiffness: 420, damping: 34 }} />
+ <motion.span
+ layoutId="header-gif-size-pill"
+ className="absolute inset-0 rounded-lg bg-white"
+ transition={{
+ type: "spring",
+ stiffness: 420,
+ damping: 34,
+ }}
+ />
) : null}
- <span className={cn("relative z-10", isActive ? "text-black" : "text-slate-400 hover:text-slate-200")}>
+ <span
+ className={cn(
+ "relative z-10",
+ isActive
+ ? "text-black"
+ : "text-slate-400 hover:text-slate-200",
+ )}
+ >
{key === "original"
- ? tSettings("export.sizePresetOriginalShort", "Orig")
+ ? tSettings(
+ "export.sizePresetOriginalShort",
+ "Orig",
+ )
: key === "medium"
- ? tSettings("export.sizePresetMediumShort", "Med")
- : tSettings("export.sizePresetLargeShort", "Lar")}
+ ? tSettings(
+ "export.sizePresetMediumShort",
+ "Med",
+ )
+ : tSettings(
+ "export.sizePresetLargeShort",
+ "Lar",
+ )}
</span>
</button>
);
@@ -306,14 +424,25 @@ export function ExportSettingsMenu({
{gifOutputDimensions.width} × {gifOutputDimensions.height}px
</span>
<div className="flex items-center gap-2">
- <span className="text-[10px] text-slate-400">{tSettings("export.loop")}</span>
- <Switch checked={gifLoop} onCheckedChange={onGifLoopChange} className="scale-75 data-[state=checked]:bg-[#2563EB]" />
+ <span className="text-[10px] text-slate-400">
+ {tSettings("export.loop")}
+ </span>
+ <Switch
+ checked={gifLoop}
+ onCheckedChange={onGifLoopChange}
+ className="scale-75 data-[state=checked]:bg-[#2563EB]"
+ />
</div>
</div>
</div>
)}
- <Button type="button" size="lg" onClick={onExport} className="h-11 w-full gap-2 rounded-lg bg-[#2563EB] text-sm font-semibold text-white transition-colors duration-200 hover:bg-[#2563EB]/90">
+ <Button
+ type="button"
+ size="lg"
+ onClick={onExport}
+ className="h-11 w-full gap-2 rounded-lg bg-[#2563EB] text-sm font-semibold text-white transition-colors duration-200 hover:bg-[#2563EB]/90"
+ >
<Download className="h-4 w-4" />
{tSettings("export.exportVideo", undefined, {
format: exportFormat === "gif" ? "GIF" : "Video",
@@ -321,4 +450,4 @@ export function ExportSettingsMenu({
</Button>
</div>
);
-}
\ No newline at end of file
+}
diff --git a/src/components/video-editor/ExtensionIcon.tsx b/src/components/video-editor/ExtensionIcon.tsx
index 2e8329fb..7808bff3 100644
--- a/src/components/video-editor/ExtensionIcon.tsx
+++ b/src/components/video-editor/ExtensionIcon.tsx
@@ -1,88 +1,151 @@
-import { icons, Puzzle } from "lucide-react";
-import type { LucideProps } from "lucide-react";
+import type { Icon, IconProps } from "@phosphor-icons/react";
+import * as PhosphorIcons from "@phosphor-icons/react";
const WINDOWS_ABSOLUTE_PATH = /^[a-zA-Z]:[\\/]/;
+const { PuzzlePiece } = PhosphorIcons;
+
+const ICON_NAME_ALIASES: Record<string, keyof typeof PhosphorIcons> = {
+ Check: "Check",
+ ChevronDown: "CaretDown",
+ ChevronLeft: "CaretLeft",
+ ChevronRight: "CaretRight",
+ ChevronUp: "CaretUp",
+ Download: "DownloadSimple",
+ ExternalLink: "ArrowSquareOut",
+ Film: "FilmSlate",
+ FolderOpen: "FolderOpen",
+ HelpCircle: "Question",
+ ImageIcon: "ImageSquare",
+ Loader2: "Spinner",
+ MessageSquare: "ChatCircle",
+ MessageSquareMore: "ChatCircleDots",
+ Palette: "Palette",
+ Puzzle: "PuzzlePiece",
+ Redo2: "ArrowClockwise",
+ RefreshCw: "ArrowClockwise",
+ RotateCcw: "ArrowCounterClockwise",
+ Save: "FloppyDisk",
+ Search: "MagnifyingGlass",
+ Settings2: "Gear",
+ ShieldAlert: "ShieldWarning",
+ Trash2: "Trash",
+ Twitter: "TwitterLogo",
+ Undo2: "ArrowCounterClockwise",
+ Upload: "UploadSimple",
+ User: "UserCircle",
+ Volume1: "SpeakerLow",
+ Volume2: "SpeakerHigh",
+ VolumeX: "SpeakerX",
+ WandSparkles: "MagicWand",
+ ZoomIn: "MagnifyingGlassPlus",
+};
function isImagePath(value: string): boolean {
- return (
- value.startsWith("data:") ||
- value.startsWith("file://") ||
- value.startsWith("http://") ||
- value.startsWith("https://") ||
- value.includes("/") ||
- /\.(png|svg|jpg|jpeg|webp|gif)$/i.test(value)
- );
+ return (
+ value.startsWith("data:") ||
+ value.startsWith("file://") ||
+ value.startsWith("http://") ||
+ value.startsWith("https://") ||
+ value.includes("/") ||
+ /\.(png|svg|jpg|jpeg|webp|gif)$/i.test(value)
+ );
}
function toFileHref(filePath: string): string {
- const normalized = filePath.replace(/\\/g, "/");
+ const normalized = filePath.replace(/\\/g, "/");
- if (normalized.startsWith("file://")) {
- return normalized;
- }
+ if (normalized.startsWith("file://")) {
+ return normalized;
+ }
- if (normalized.startsWith("/")) {
- return `file://${normalized}`;
- }
+ if (normalized.startsWith("/")) {
+ return `file://${normalized}`;
+ }
- if (WINDOWS_ABSOLUTE_PATH.test(normalized)) {
- return `file:///${normalized}`;
- }
+ if (WINDOWS_ABSOLUTE_PATH.test(normalized)) {
+ return `file:///${normalized}`;
+ }
- return normalized;
+ return normalized;
}
function resolveIconSrc(icon: string, extensionPath?: string | null): string | null {
- if (!isImagePath(icon)) {
- return null;
- }
-
- if (
- icon.startsWith("data:") ||
- icon.startsWith("file://") ||
- icon.startsWith("http://") ||
- icon.startsWith("https://")
- ) {
- return icon;
- }
-
- if (icon.startsWith("/") || WINDOWS_ABSOLUTE_PATH.test(icon)) {
- return toFileHref(icon);
- }
-
- if (!extensionPath) {
- return icon;
- }
-
- const baseHref = toFileHref(extensionPath.endsWith("/") ? extensionPath : `${extensionPath}/`);
- return new URL(icon, baseHref).toString();
+ if (!isImagePath(icon)) {
+ return null;
+ }
+
+ if (
+ icon.startsWith("data:") ||
+ icon.startsWith("file://") ||
+ icon.startsWith("http://") ||
+ icon.startsWith("https://")
+ ) {
+ return icon;
+ }
+
+ if (icon.startsWith("/") || WINDOWS_ABSOLUTE_PATH.test(icon)) {
+ return toFileHref(icon);
+ }
+
+ if (!extensionPath) {
+ return icon;
+ }
+
+ const baseHref = toFileHref(extensionPath.endsWith("/") ? extensionPath : `${extensionPath}/`);
+ return new URL(icon, baseHref).toString();
+}
+
+function resolvePhosphorIcon(name: string): Icon | null {
+ const direct = PhosphorIcons[name as keyof typeof PhosphorIcons];
+ if (typeof direct === "function") {
+ return direct as Icon;
+ }
+
+ const alias = ICON_NAME_ALIASES[name];
+ if (!alias) {
+ return null;
+ }
+
+ const mapped = PhosphorIcons[alias];
+ return typeof mapped === "function" ? (mapped as Icon) : null;
}
/**
- * Renders either a Lucide icon (by PascalCase name) or an image (by path/URL).
- * Falls back to the Puzzle icon if nothing matches.
+ * Renders either a Phosphor icon (by PascalCase name) or an image (by path/URL).
+ * Falls back to the PuzzlePiece icon if nothing matches.
*/
export function ExtensionIcon({
- icon,
- extensionPath,
- className = "w-4 h-4",
- imageClassName,
- ...rest
-}: { icon?: string | null; extensionPath?: string | null; className?: string; imageClassName?: string } & Omit<LucideProps, "ref">) {
- if (!icon) {
- return <Puzzle className={className} {...rest} />;
- }
-
- const iconSrc = resolveIconSrc(icon, extensionPath);
- if (iconSrc) {
- return <img src={iconSrc} alt="" className={imageClassName ?? className} style={{ objectFit: "cover" }} />;
- }
-
- // Try Lucide icon name (PascalCase)
- const LucideIcon = (icons as Record<string, typeof Puzzle>)[icon];
- if (LucideIcon) {
- return <LucideIcon className={className} {...rest} />;
- }
-
- return <Puzzle className={className} {...rest} />;
+ icon,
+ extensionPath,
+ className = "w-4 h-4",
+ imageClassName,
+ ...rest
+}: {
+ icon?: string | null;
+ extensionPath?: string | null;
+ className?: string;
+ imageClassName?: string;
+} & Omit<IconProps, "ref">) {
+ if (!icon) {
+ return <PuzzlePiece className={className} {...rest} />;
+ }
+
+ const iconSrc = resolveIconSrc(icon, extensionPath);
+ if (iconSrc) {
+ return (
+ <img
+ src={iconSrc}
+ alt=""
+ className={imageClassName ?? className}
+ style={{ objectFit: "cover" }}
+ />
+ );
+ }
+
+ const PhosphorIcon = resolvePhosphorIcon(icon);
+ if (PhosphorIcon) {
+ return <PhosphorIcon className={className} {...rest} />;
+ }
+
+ return <PuzzlePiece className={className} {...rest} />;
}
diff --git a/src/components/video-editor/ExtensionManager.tsx b/src/components/video-editor/ExtensionManager.tsx
index 5b08c833..5520411c 100644
--- a/src/components/video-editor/ExtensionManager.tsx
+++ b/src/components/video-editor/ExtensionManager.tsx
@@ -6,43 +6,40 @@
* - Installed: Local extensions with toggle switches
*/
-import { useCallback, useEffect, useState } from "react";
+import {
+ BookOpen,
+ Check,
+ CaretLeft as ChevronLeft,
+ CaretRight as ChevronRight,
+ DownloadSimple as Download,
+ ArrowSquareOut as ExternalLink,
+ FolderOpen,
+ MagnifyingGlass as Search,
+ Plus,
+ PuzzlePiece as Puzzle,
+ ArrowClockwise as RefreshCw,
+ ShieldWarning as ShieldAlert,
+ Spinner as Loader2,
+ Tag,
+ Trash as Trash2,
+} from "@phosphor-icons/react";
import { AnimatePresence, LayoutGroup, motion } from "motion/react";
+import { useCallback, useEffect, useState } from "react";
+import { toast } from "sonner";
import { Button } from "@/components/ui/button";
+import { Dialog, DialogContent } from "@/components/ui/dialog";
import { Switch } from "@/components/ui/switch";
-import {
- Dialog,
- DialogContent,
-} from "@/components/ui/dialog";
-import {
- Puzzle,
- FolderOpen,
- Plus,
- Trash2,
- RefreshCw,
- Download,
- Search,
- ShieldAlert,
- Loader2,
- Check,
- BookOpen,
- Tag,
- ExternalLink,
- ChevronLeft,
- ChevronRight,
-} from "lucide-react";
-import { toast } from "sonner";
-import { cn } from "@/lib/utils";
-import { useExtensions } from "@/hooks/useExtensions";
-import { ExtensionIcon } from "./ExtensionIcon";
import { useScopedT } from "@/contexts/I18nContext";
+import { useExtensions } from "@/hooks/useExtensions";
import type { ExtensionInfo, MarketplaceExtension } from "@/lib/extensions";
+import { cn } from "@/lib/utils";
+import { ExtensionIcon } from "./ExtensionIcon";
type ExtensionTab = "installed" | "browse";
const TAB_OPTIONS: { value: ExtensionTab; labelKey: string }[] = [
- { value: "browse", labelKey: "tabs.browse" },
- { value: "installed", labelKey: "tabs.installed" },
+ { value: "browse", labelKey: "tabs.browse" },
+ { value: "installed", labelKey: "tabs.installed" },
];
const EXTENSIONS_DOCS_URL = "https://marketplace.recordly.dev/extensions";
@@ -53,103 +50,113 @@ const EXTENSIONS_SUBMIT_URL = "https://marketplace.recordly.dev/extensions/submi
// ---------------------------------------------------------------------------
function InstalledExtensionCard({
- extension,
- isActive,
- onToggle,
- onUninstall,
- onClick,
+ extension,
+ isActive,
+ onToggle,
+ onUninstall,
+ onClick,
}: {
- extension: ExtensionInfo;
- isActive: boolean;
- onToggle: () => void;
- onUninstall?: () => void;
- onClick?: () => void;
+ extension: ExtensionInfo;
+ isActive: boolean;
+ onToggle: () => void;
+ onUninstall?: () => void;
+ onClick?: () => void;
}) {
- const t = useScopedT("extensions");
- const isError = extension.status === "error";
- const isBuiltin = extension.builtin;
-
- return (
- <div
- className={cn(
- "flex items-start gap-3 p-3 rounded-xl border transition-colors cursor-pointer",
- isError
- ? "border-red-500/30 bg-red-500/5"
- : isActive
- ? "border-[#2563EB]/20 bg-[#2563EB]/5"
- : "border-white/[0.06] bg-white/[0.02] hover:bg-white/[0.04]",
- )}
- onClick={onClick}
- >
- <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-white/5 border border-white/10 flex items-center justify-center overflow-hidden">
- <ExtensionIcon icon={extension.manifest.icon} extensionPath={extension.path} className="w-3.5 h-3.5 text-slate-400" imageClassName="w-8 h-8 rounded-lg" />
- </div>
-
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-1.5">
- <span className="text-[13px] font-medium text-slate-200 truncate">
- {extension.manifest.name}
- </span>
- </div>
-
- {extension.manifest.author && (
- <p className="text-[10px] text-slate-500 mt-0.5">
- {extension.manifest.homepage ? (
- <a
- href={extension.manifest.homepage}
- target="_blank"
- rel="noopener noreferrer"
- className="hover:text-slate-300 transition-colors"
- onClick={(e) => e.stopPropagation()}
- >
- {t("detail.by", undefined, { author: extension.manifest.author })}
- </a>
- ) : (
- <>{t("detail.by", undefined, { author: extension.manifest.author })}</>
- )}
- </p>
- )}
-
- <p className="text-[11px] text-slate-500 mt-0.5 line-clamp-3">
- {extension.manifest.description || t("detail.noDescription")}
- </p>
-
- {isError && extension.error && (
- <p className="text-[10px] text-red-400 mt-1">{t("detail.error", undefined, { message: extension.error })}</p>
- )}
-
- {extension.manifest.permissions.length > 0 && (
- <div className="flex gap-1 mt-1.5 flex-wrap">
- {extension.manifest.permissions.map((perm) => (
- <span
- key={perm}
- className="text-[8px] px-1 py-[1px] rounded bg-white/5 text-slate-600 font-mono"
- >
- {perm}
- </span>
- ))}
- </div>
- )}
- </div>
-
- <div className="flex items-center gap-1.5 flex-shrink-0">
- {!isBuiltin && onUninstall && (
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6 text-slate-600 hover:text-red-400 hover:bg-red-500/10"
- onClick={(e) => { e.stopPropagation(); onUninstall(); }}
- title={t("actions.uninstall")}
- >
- <Trash2 className="w-3 h-3" />
- </Button>
- )}
- <div onClick={(e) => e.stopPropagation()}>
- <Switch checked={isActive} onCheckedChange={onToggle} disabled={isError} />
- </div>
- </div>
- </div>
- );
+ const t = useScopedT("extensions");
+ const isError = extension.status === "error";
+ const isBuiltin = extension.builtin;
+
+ return (
+ <div
+ className={cn(
+ "flex items-start gap-3 p-3 rounded-xl border transition-colors cursor-pointer",
+ isError
+ ? "border-red-500/30 bg-red-500/5"
+ : isActive
+ ? "border-[#2563EB]/20 bg-[#2563EB]/5"
+ : "border-white/[0.06] bg-white/[0.02] hover:bg-white/[0.04]",
+ )}
+ onClick={onClick}
+ >
+ <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-white/5 border border-white/10 flex items-center justify-center overflow-hidden">
+ <ExtensionIcon
+ icon={extension.manifest.icon}
+ extensionPath={extension.path}
+ className="w-3.5 h-3.5 text-slate-400"
+ imageClassName="w-8 h-8 rounded-lg"
+ />
+ </div>
+
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-1.5">
+ <span className="text-[13px] font-medium text-slate-200 truncate">
+ {extension.manifest.name}
+ </span>
+ </div>
+
+ {extension.manifest.author && (
+ <p className="text-[10px] text-slate-500 mt-0.5">
+ {extension.manifest.homepage ? (
+ <a
+ href={extension.manifest.homepage}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="hover:text-slate-300 transition-colors"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {t("detail.by", undefined, { author: extension.manifest.author })}
+ </a>
+ ) : (
+ <>{t("detail.by", undefined, { author: extension.manifest.author })}</>
+ )}
+ </p>
+ )}
+
+ <p className="text-[11px] text-slate-500 mt-0.5 line-clamp-3">
+ {extension.manifest.description || t("detail.noDescription")}
+ </p>
+
+ {isError && extension.error && (
+ <p className="text-[10px] text-red-400 mt-1">
+ {t("detail.error", undefined, { message: extension.error })}
+ </p>
+ )}
+
+ {extension.manifest.permissions.length > 0 && (
+ <div className="flex gap-1 mt-1.5 flex-wrap">
+ {extension.manifest.permissions.map((perm) => (
+ <span
+ key={perm}
+ className="text-[8px] px-1 py-[1px] rounded bg-white/5 text-slate-600 font-mono"
+ >
+ {perm}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <div className="flex items-center gap-1.5 flex-shrink-0">
+ {!isBuiltin && onUninstall && (
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 text-slate-600 hover:text-red-400 hover:bg-red-500/10"
+ onClick={(e) => {
+ e.stopPropagation();
+ onUninstall();
+ }}
+ title={t("actions.uninstall")}
+ >
+ <Trash2 className="w-3 h-3" />
+ </Button>
+ )}
+ <div onClick={(e) => e.stopPropagation()}>
+ <Switch checked={isActive} onCheckedChange={onToggle} disabled={isError} />
+ </div>
+ </div>
+ </div>
+ );
}
// ---------------------------------------------------------------------------
@@ -157,100 +164,110 @@ function InstalledExtensionCard({
// ---------------------------------------------------------------------------
function MarketplaceCard({
- extension,
- isInstalling,
- onInstall,
- onClick,
+ extension,
+ isInstalling,
+ onInstall,
+ onClick,
}: {
- extension: MarketplaceExtension;
- isInstalling: boolean;
- onInstall: () => void;
- onClick?: () => void;
+ extension: MarketplaceExtension;
+ isInstalling: boolean;
+ onInstall: () => void;
+ onClick?: () => void;
}) {
- const t = useScopedT("extensions");
- return (
- <div className="flex items-start gap-3 p-3 rounded-xl border border-white/[0.06] bg-white/[0.02] hover:bg-white/[0.04] transition-colors cursor-pointer" onClick={onClick}>
- <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-gradient-to-br from-white/10 to-white/5 border border-white/10 flex items-center justify-center overflow-hidden">
- {extension.iconUrl ? (
- <img src={extension.iconUrl} alt="" className="w-8 h-8 rounded-lg object-cover" />
- ) : (
- <ExtensionIcon icon={undefined} className="w-3.5 h-3.5 text-slate-400" />
- )}
- </div>
-
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-1.5">
- <span className="text-[13px] font-medium text-slate-200 truncate">
- {extension.name}
- </span>
- </div>
-
- <p className="text-[10px] text-slate-500 mt-0.5">
- {extension.homepage ? (
- <a
- href={extension.homepage}
- target="_blank"
- rel="noopener noreferrer"
- className="hover:text-slate-300 transition-colors"
- onClick={(e) => e.stopPropagation()}
- >
- {t("detail.by", undefined, { author: extension.author })}
- </a>
- ) : (
- <>{t("detail.by", undefined, { author: extension.author })}</>
- )}
- </p>
-
- <p className="text-[11px] text-slate-500 mt-0.5 line-clamp-3">
- {extension.description}
- </p>
-
- <div className="flex items-center gap-3 mt-1.5">
- <span className="flex items-center gap-0.5 text-[10px] text-slate-600">
- <Download className="w-2.5 h-2.5" />
- {extension.downloads.toLocaleString()}
- </span>
- </div>
-
- {extension.tags.length > 0 && (
- <div className="flex gap-1 mt-1.5 flex-wrap">
- {extension.tags.slice(0, 3).map((tag) => (
- <span
- key={tag}
- className="text-[8px] px-1 py-[1px] rounded bg-[#2563EB]/10 text-[#2563EB]/70 font-medium"
- >
- {tag}
- </span>
- ))}
- </div>
- )}
- </div>
-
- <div className="flex-shrink-0">
- {extension.installed ? (
- <span className="flex items-center gap-1 text-[10px] text-emerald-500 font-medium">
- <Check className="w-3 h-3" />
- {t("status.installed")}
- </span>
- ) : (
- <Button
- variant="ghost"
- size="sm"
- className="h-7 px-2.5 text-[11px] text-[#2563EB] hover:text-[#2563EB] hover:bg-[#2563EB]/10 font-medium gap-1"
- onClick={(e) => { e.stopPropagation(); onInstall(); }}
- disabled={isInstalling}
- >
- {isInstalling ? (
- <Loader2 className="w-3 h-3 animate-spin" />
- ) : (
- <Download className="w-3 h-3" />
- )}
- {isInstalling ? t("actions.installing") : t("actions.install")}
- </Button>
- )}
- </div>
- </div>
- );
+ const t = useScopedT("extensions");
+ return (
+ <div
+ className="flex items-start gap-3 p-3 rounded-xl border border-white/[0.06] bg-white/[0.02] hover:bg-white/[0.04] transition-colors cursor-pointer"
+ onClick={onClick}
+ >
+ <div className="flex-shrink-0 w-8 h-8 rounded-lg bg-gradient-to-br from-white/10 to-white/5 border border-white/10 flex items-center justify-center overflow-hidden">
+ {extension.iconUrl ? (
+ <img
+ src={extension.iconUrl}
+ alt=""
+ className="w-8 h-8 rounded-lg object-cover"
+ />
+ ) : (
+ <ExtensionIcon icon={undefined} className="w-3.5 h-3.5 text-slate-400" />
+ )}
+ </div>
+
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-1.5">
+ <span className="text-[13px] font-medium text-slate-200 truncate">
+ {extension.name}
+ </span>
+ </div>
+
+ <p className="text-[10px] text-slate-500 mt-0.5">
+ {extension.homepage ? (
+ <a
+ href={extension.homepage}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="hover:text-slate-300 transition-colors"
+ onClick={(e) => e.stopPropagation()}
+ >
+ {t("detail.by", undefined, { author: extension.author })}
+ </a>
+ ) : (
+ <>{t("detail.by", undefined, { author: extension.author })}</>
+ )}
+ </p>
+
+ <p className="text-[11px] text-slate-500 mt-0.5 line-clamp-3">
+ {extension.description}
+ </p>
+
+ <div className="flex items-center gap-3 mt-1.5">
+ <span className="flex items-center gap-0.5 text-[10px] text-slate-600">
+ <Download className="w-2.5 h-2.5" />
+ {extension.downloads.toLocaleString()}
+ </span>
+ </div>
+
+ {extension.tags.length > 0 && (
+ <div className="flex gap-1 mt-1.5 flex-wrap">
+ {extension.tags.slice(0, 3).map((tag) => (
+ <span
+ key={tag}
+ className="text-[8px] px-1 py-[1px] rounded bg-[#2563EB]/10 text-[#2563EB]/70 font-medium"
+ >
+ {tag}
+ </span>
+ ))}
+ </div>
+ )}
+ </div>
+
+ <div className="flex-shrink-0">
+ {extension.installed ? (
+ <span className="flex items-center gap-1 text-[10px] text-emerald-500 font-medium">
+ <Check className="w-3 h-3" />
+ {t("status.installed")}
+ </span>
+ ) : (
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2.5 text-[11px] text-[#2563EB] hover:text-[#2563EB] hover:bg-[#2563EB]/10 font-medium gap-1"
+ onClick={(e) => {
+ e.stopPropagation();
+ onInstall();
+ }}
+ disabled={isInstalling}
+ >
+ {isInstalling ? (
+ <Loader2 className="w-3 h-3 animate-spin" />
+ ) : (
+ <Download className="w-3 h-3" />
+ )}
+ {isInstalling ? t("actions.installing") : t("actions.install")}
+ </Button>
+ )}
+ </div>
+ </div>
+ );
}
// ---------------------------------------------------------------------------
@@ -258,56 +275,56 @@ function MarketplaceCard({
// ---------------------------------------------------------------------------
function ScreenshotGallery({ screenshots }: { screenshots: string[] }) {
- const t = useScopedT("extensions");
- const [index, setIndex] = useState(0);
- const count = screenshots.length;
- if (count === 0) return null;
-
- return (
- <div>
- <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
- {t("detail.preview")}
- </p>
- <div className="relative group rounded-lg overflow-hidden bg-black/20 border border-white/[0.06]">
- <img
- src={screenshots[index]}
- alt={t("detail.screenshotAlt", undefined, { number: String(index + 1) })}
- className="w-full aspect-video object-cover"
- />
- {count > 1 && (
- <>
- <button
- type="button"
- className="absolute left-1 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-black/60 text-white/80 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80"
- onClick={() => setIndex((i) => (i - 1 + count) % count)}
- >
- <ChevronLeft className="w-3.5 h-3.5" />
- </button>
- <button
- type="button"
- className="absolute right-1 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-black/60 text-white/80 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80"
- onClick={() => setIndex((i) => (i + 1) % count)}
- >
- <ChevronRight className="w-3.5 h-3.5" />
- </button>
- <div className="absolute bottom-1.5 left-1/2 -translate-x-1/2 flex gap-1">
- {screenshots.map((_, i) => (
- <button
- type="button"
- key={i}
- className={cn(
- "w-1.5 h-1.5 rounded-full transition-colors",
- i === index ? "bg-white" : "bg-white/30 hover:bg-white/50",
- )}
- onClick={() => setIndex(i)}
- />
- ))}
- </div>
- </>
- )}
- </div>
- </div>
- );
+ const t = useScopedT("extensions");
+ const [index, setIndex] = useState(0);
+ const count = screenshots.length;
+ if (count === 0) return null;
+
+ return (
+ <div>
+ <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
+ {t("detail.preview")}
+ </p>
+ <div className="relative group rounded-lg overflow-hidden bg-black/20 border border-white/[0.06]">
+ <img
+ src={screenshots[index]}
+ alt={t("detail.screenshotAlt", undefined, { number: String(index + 1) })}
+ className="w-full aspect-video object-cover"
+ />
+ {count > 1 && (
+ <>
+ <button
+ type="button"
+ className="absolute left-1 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-black/60 text-white/80 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80"
+ onClick={() => setIndex((i) => (i - 1 + count) % count)}
+ >
+ <ChevronLeft className="w-3.5 h-3.5" />
+ </button>
+ <button
+ type="button"
+ className="absolute right-1 top-1/2 -translate-y-1/2 w-6 h-6 rounded-full bg-black/60 text-white/80 flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80"
+ onClick={() => setIndex((i) => (i + 1) % count)}
+ >
+ <ChevronRight className="w-3.5 h-3.5" />
+ </button>
+ <div className="absolute bottom-1.5 left-1/2 -translate-x-1/2 flex gap-1">
+ {screenshots.map((_, i) => (
+ <button
+ type="button"
+ key={i}
+ className={cn(
+ "w-1.5 h-1.5 rounded-full transition-colors",
+ i === index ? "bg-white" : "bg-white/30 hover:bg-white/50",
+ )}
+ onClick={() => setIndex(i)}
+ />
+ ))}
+ </div>
+ </>
+ )}
+ </div>
+ </div>
+ );
}
// ---------------------------------------------------------------------------
@@ -315,208 +332,223 @@ function ScreenshotGallery({ screenshots }: { screenshots: string[] }) {
// ---------------------------------------------------------------------------
type ExtensionDetailData =
- | { source: 'installed'; ext: ExtensionInfo; isActive: boolean }
- | { source: 'marketplace'; ext: MarketplaceExtension };
+ | { source: "installed"; ext: ExtensionInfo; isActive: boolean }
+ | { source: "marketplace"; ext: MarketplaceExtension };
function ExtensionDetailModal({
- detail,
- onClose,
- onToggle,
- onInstall,
- isInstalling,
+ detail,
+ onClose,
+ onToggle,
+ onInstall,
+ isInstalling,
}: {
- detail: ExtensionDetailData;
- onClose: () => void;
- onToggle?: () => void;
- onInstall?: () => void;
- isInstalling?: boolean;
+ detail: ExtensionDetailData;
+ onClose: () => void;
+ onToggle?: () => void;
+ onInstall?: () => void;
+ isInstalling?: boolean;
}) {
- const t = useScopedT("extensions");
- const isInstalled = detail.source === 'installed';
- const name = isInstalled ? detail.ext.manifest.name : detail.ext.name;
- const description = isInstalled
- ? detail.ext.manifest.description || t("detail.noDescription")
- : detail.ext.description || t("detail.noDescription");
- const author = isInstalled ? detail.ext.manifest.author : detail.ext.author;
- const permissions = isInstalled ? detail.ext.manifest.permissions : detail.ext.permissions;
- const homepage = isInstalled ? detail.ext.manifest.homepage : detail.ext.homepage;
- const screenshots = detail.source === 'marketplace' ? detail.ext.screenshots ?? [] : [];
- const isError = isInstalled ? detail.ext.status === 'error' : false;
-
- return (
- <Dialog open onOpenChange={(open) => { if (!open) onClose(); }}>
- <DialogContent className="max-w-md bg-[#161619] border-white/10 text-slate-200 p-0 gap-0 overflow-hidden">
- {/* Header */}
- <div className="p-5 pb-4">
- <div className="flex items-start gap-3.5">
- <div className="flex-shrink-0 w-12 h-12 rounded-xl bg-gradient-to-br from-[#2563EB]/20 to-[#2563EB]/5 border border-white/10 flex items-center justify-center">
- {detail.source === 'marketplace' && detail.ext.iconUrl ? (
- <img src={detail.ext.iconUrl} alt="" className="w-7 h-7 rounded-lg" />
- ) : (
- <ExtensionIcon
- icon={isInstalled ? detail.ext.manifest.icon : undefined}
- extensionPath={isInstalled ? detail.ext.path : undefined}
- className="w-5 h-5 text-[#2563EB]/60"
- />
- )}
- </div>
- <div className="flex-1 min-w-0">
- <div className="flex items-center gap-1.5">
- <h2 className="text-[15px] font-semibold text-white truncate">{name}</h2>
- </div>
- <p className="text-[11px] text-slate-500 mt-0.5">
- {author ? (
- homepage ? (
- <a
- href={homepage}
- target="_blank"
- rel="noopener noreferrer"
- className="hover:text-slate-300 transition-colors inline-flex items-center gap-1"
- >
- {t("detail.by", undefined, { author })}
- <ExternalLink className="w-2.5 h-2.5" />
- </a>
- ) : (
- <>{t("detail.by", undefined, { author })}</>
- )
- ) : t("detail.unknownAuthor")}
- </p>
- </div>
- </div>
-
- {/* Stats for marketplace extensions */}
- {detail.source === 'marketplace' && (
- <div className="flex items-center gap-3 mt-3">
- <span className="flex items-center gap-1 text-[11px] text-slate-500">
- <Download className="w-3 h-3" />
- {t("detail.downloads", undefined, { count: detail.ext.downloads.toLocaleString() })}
- </span>
- </div>
- )}
- </div>
-
- {/* Body */}
- <div className="px-5 pb-5 space-y-4 max-h-[50vh] overflow-y-auto custom-scrollbar">
- {/* Screenshot gallery */}
- {screenshots.length > 0 && <ScreenshotGallery screenshots={screenshots} />}
-
- {/* Description */}
- <div>
- <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
- {t("detail.description")}
- </p>
- <p className="text-[12px] text-slate-400 leading-relaxed whitespace-pre-wrap">
- {description}
- </p>
- </div>
-
- {/* Tags */}
- {detail.source === 'marketplace' && detail.ext.tags.length > 0 && (
- <div>
- <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
- {t("detail.tags")}
- </p>
- <div className="flex flex-wrap gap-1.5">
- {detail.ext.tags.map((tag) => (
- <span
- key={tag}
- className="inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-[#2563EB]/10 text-[#2563EB]/70 font-medium"
- >
- <Tag className="w-2.5 h-2.5" />
- {tag}
- </span>
- ))}
- </div>
- </div>
- )}
-
- {/* Permissions */}
- {permissions.length > 0 && (
- <div>
- <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
- {t("detail.permissions")}
- </p>
- <div className="flex flex-wrap gap-1.5">
- {permissions.map((perm) => (
- <span
- key={perm}
- className="text-[10px] px-2 py-0.5 rounded bg-white/5 text-slate-400 font-mono"
- >
- {perm}
- </span>
- ))}
- </div>
- </div>
- )}
-
- {/* Path (installed extensions) */}
- {isInstalled && (
- <div>
- <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
- {t("detail.location")}
- </p>
- <p className="text-[10px] text-slate-500 font-mono break-all">
- {detail.ext.path}
- </p>
- </div>
- )}
-
- {/* Error */}
- {isError && isInstalled && detail.ext.error && (
- <div className="p-2.5 rounded-lg bg-red-500/10 border border-red-500/20">
- <p className="text-[11px] text-red-400">{detail.ext.error}</p>
- </div>
- )}
- </div>
-
- {/* Footer actions */}
- <div className="flex items-center gap-2 px-5 py-3 border-t border-white/[0.06] bg-white/[0.02]">
- {isInstalled && onToggle && (
- <div className="flex items-center gap-2">
- <Switch
- checked={detail.isActive}
- onCheckedChange={onToggle}
- disabled={isError}
- />
- <span className="text-[11px] text-slate-400">
- {detail.isActive ? t("status.enabled") : t("status.disabled")}
- </span>
- </div>
- )}
- {detail.source === 'marketplace' && !detail.ext.installed && onInstall && (
- <Button
- size="sm"
- className="h-8 px-3 text-[12px] bg-[#2563EB] hover:bg-[#2563EB]/90 text-white gap-1.5"
- onClick={onInstall}
- disabled={isInstalling}
- >
- {isInstalling ? (
- <Loader2 className="w-3.5 h-3.5 animate-spin" />
- ) : (
- <Download className="w-3.5 h-3.5" />
- )}
- {isInstalling ? t("actions.installing") : t("actions.install")}
- </Button>
- )}
- {detail.source === 'marketplace' && detail.ext.installed && (
- <span className="flex items-center gap-1 text-[11px] text-emerald-500 font-medium">
- <Check className="w-3.5 h-3.5" />
- {t("status.installed")}
- </span>
- )}
- <div className="flex-1" />
- <Button
- variant="ghost"
- size="sm"
- className="h-8 px-3 text-[12px] text-slate-400 hover:text-slate-200 hover:bg-white/10"
- onClick={onClose}
- >
- {t("actions.close")}
- </Button>
- </div>
- </DialogContent>
- </Dialog>
- );
+ const t = useScopedT("extensions");
+ const isInstalled = detail.source === "installed";
+ const name = isInstalled ? detail.ext.manifest.name : detail.ext.name;
+ const description = isInstalled
+ ? detail.ext.manifest.description || t("detail.noDescription")
+ : detail.ext.description || t("detail.noDescription");
+ const author = isInstalled ? detail.ext.manifest.author : detail.ext.author;
+ const permissions = isInstalled ? detail.ext.manifest.permissions : detail.ext.permissions;
+ const homepage = isInstalled ? detail.ext.manifest.homepage : detail.ext.homepage;
+ const screenshots = detail.source === "marketplace" ? (detail.ext.screenshots ?? []) : [];
+ const isError = isInstalled ? detail.ext.status === "error" : false;
+
+ return (
+ <Dialog
+ open
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ >
+ <DialogContent className="max-w-md bg-[#161619] border-white/10 text-slate-200 p-0 gap-0 overflow-hidden">
+ {/* Header */}
+ <div className="p-5 pb-4">
+ <div className="flex items-start gap-3.5">
+ <div className="flex-shrink-0 w-12 h-12 rounded-xl bg-gradient-to-br from-[#2563EB]/20 to-[#2563EB]/5 border border-white/10 flex items-center justify-center">
+ {detail.source === "marketplace" && detail.ext.iconUrl ? (
+ <img
+ src={detail.ext.iconUrl}
+ alt=""
+ className="w-7 h-7 rounded-lg"
+ />
+ ) : (
+ <ExtensionIcon
+ icon={isInstalled ? detail.ext.manifest.icon : undefined}
+ extensionPath={isInstalled ? detail.ext.path : undefined}
+ className="w-5 h-5 text-[#2563EB]/60"
+ />
+ )}
+ </div>
+ <div className="flex-1 min-w-0">
+ <div className="flex items-center gap-1.5">
+ <h2 className="text-[15px] font-semibold text-white truncate">
+ {name}
+ </h2>
+ </div>
+ <p className="text-[11px] text-slate-500 mt-0.5">
+ {author ? (
+ homepage ? (
+ <a
+ href={homepage}
+ target="_blank"
+ rel="noopener noreferrer"
+ className="hover:text-slate-300 transition-colors inline-flex items-center gap-1"
+ >
+ {t("detail.by", undefined, { author })}
+ <ExternalLink className="w-2.5 h-2.5" />
+ </a>
+ ) : (
+ <>{t("detail.by", undefined, { author })}</>
+ )
+ ) : (
+ t("detail.unknownAuthor")
+ )}
+ </p>
+ </div>
+ </div>
+
+ {/* Stats for marketplace extensions */}
+ {detail.source === "marketplace" && (
+ <div className="flex items-center gap-3 mt-3">
+ <span className="flex items-center gap-1 text-[11px] text-slate-500">
+ <Download className="w-3 h-3" />
+ {t("detail.downloads", undefined, {
+ count: detail.ext.downloads.toLocaleString(),
+ })}
+ </span>
+ </div>
+ )}
+ </div>
+
+ {/* Body */}
+ <div className="px-5 pb-5 space-y-4 max-h-[50vh] overflow-y-auto custom-scrollbar">
+ {/* Screenshot gallery */}
+ {screenshots.length > 0 && <ScreenshotGallery screenshots={screenshots} />}
+
+ {/* Description */}
+ <div>
+ <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
+ {t("detail.description")}
+ </p>
+ <p className="text-[12px] text-slate-400 leading-relaxed whitespace-pre-wrap">
+ {description}
+ </p>
+ </div>
+
+ {/* Tags */}
+ {detail.source === "marketplace" && detail.ext.tags.length > 0 && (
+ <div>
+ <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
+ {t("detail.tags")}
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ {detail.ext.tags.map((tag) => (
+ <span
+ key={tag}
+ className="inline-flex items-center gap-1 text-[10px] px-2 py-0.5 rounded-full bg-[#2563EB]/10 text-[#2563EB]/70 font-medium"
+ >
+ <Tag className="w-2.5 h-2.5" />
+ {tag}
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Permissions */}
+ {permissions.length > 0 && (
+ <div>
+ <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
+ {t("detail.permissions")}
+ </p>
+ <div className="flex flex-wrap gap-1.5">
+ {permissions.map((perm) => (
+ <span
+ key={perm}
+ className="text-[10px] px-2 py-0.5 rounded bg-white/5 text-slate-400 font-mono"
+ >
+ {perm}
+ </span>
+ ))}
+ </div>
+ </div>
+ )}
+
+ {/* Path (installed extensions) */}
+ {isInstalled && (
+ <div>
+ <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-500 mb-1.5">
+ {t("detail.location")}
+ </p>
+ <p className="text-[10px] text-slate-500 font-mono break-all">
+ {detail.ext.path}
+ </p>
+ </div>
+ )}
+
+ {/* Error */}
+ {isError && isInstalled && detail.ext.error && (
+ <div className="p-2.5 rounded-lg bg-red-500/10 border border-red-500/20">
+ <p className="text-[11px] text-red-400">{detail.ext.error}</p>
+ </div>
+ )}
+ </div>
+
+ {/* Footer actions */}
+ <div className="flex items-center gap-2 px-5 py-3 border-t border-white/[0.06] bg-white/[0.02]">
+ {isInstalled && onToggle && (
+ <div className="flex items-center gap-2">
+ <Switch
+ checked={detail.isActive}
+ onCheckedChange={onToggle}
+ disabled={isError}
+ />
+ <span className="text-[11px] text-slate-400">
+ {detail.isActive ? t("status.enabled") : t("status.disabled")}
+ </span>
+ </div>
+ )}
+ {detail.source === "marketplace" && !detail.ext.installed && onInstall && (
+ <Button
+ size="sm"
+ className="h-8 px-3 text-[12px] bg-[#2563EB] hover:bg-[#2563EB]/90 text-white gap-1.5"
+ onClick={onInstall}
+ disabled={isInstalling}
+ >
+ {isInstalling ? (
+ <Loader2 className="w-3.5 h-3.5 animate-spin" />
+ ) : (
+ <Download className="w-3.5 h-3.5" />
+ )}
+ {isInstalling ? t("actions.installing") : t("actions.install")}
+ </Button>
+ )}
+ {detail.source === "marketplace" && detail.ext.installed && (
+ <span className="flex items-center gap-1 text-[11px] text-emerald-500 font-medium">
+ <Check className="w-3.5 h-3.5" />
+ {t("status.installed")}
+ </span>
+ )}
+ <div className="flex-1" />
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-8 px-3 text-[12px] text-slate-400 hover:text-slate-200 hover:bg-white/10"
+ onClick={onClose}
+ >
+ {t("actions.close")}
+ </Button>
+ </div>
+ </DialogContent>
+ </Dialog>
+ );
}
// ---------------------------------------------------------------------------
@@ -524,59 +556,61 @@ function ExtensionDetailModal({
// ---------------------------------------------------------------------------
function TabSwitcher({
- activeTab,
- onTabChange,
- extensionCount,
+ activeTab,
+ onTabChange,
+ extensionCount,
}: {
- activeTab: ExtensionTab;
- onTabChange: (tab: ExtensionTab) => void;
- extensionCount: number;
+ activeTab: ExtensionTab;
+ onTabChange: (tab: ExtensionTab) => void;
+ extensionCount: number;
}) {
- const t = useScopedT("extensions");
- return (
- <LayoutGroup id="extension-tab-switcher">
- <div className="grid h-8 w-full grid-cols-2 rounded-xl border border-white/10 bg-white/[0.04] p-1">
- {TAB_OPTIONS.map((option) => {
- const isActive = activeTab === option.value;
- const count = option.value === "installed" ? extensionCount : undefined;
- return (
- <button
- key={option.value}
- type="button"
- onClick={() => onTabChange(option.value)}
- className="relative rounded-lg text-[10px] font-semibold tracking-wide transition-colors"
- >
- {isActive ? (
- <motion.span
- layoutId="extension-tab-pill"
- className="absolute inset-0 rounded-lg bg-[#2563EB]"
- transition={{ type: "spring", stiffness: 420, damping: 34 }}
- />
- ) : null}
- <span
- className={cn(
- "relative z-10 flex items-center justify-center gap-1",
- isActive ? "text-white" : "text-slate-400 hover:text-slate-200",
- )}
- >
- {t(option.labelKey)}
- {count !== undefined && count > 0 && (
- <span
- className={cn(
- "text-[8px] px-1 rounded-full font-semibold min-w-[14px] text-center leading-[14px]",
- isActive ? "bg-white/20 text-white" : "bg-white/5 text-slate-600",
- )}
- >
- {count}
- </span>
- )}
- </span>
- </button>
- );
- })}
- </div>
- </LayoutGroup>
- );
+ const t = useScopedT("extensions");
+ return (
+ <LayoutGroup id="extension-tab-switcher">
+ <div className="grid h-8 w-full grid-cols-2 rounded-xl border border-white/10 bg-white/[0.04] p-1">
+ {TAB_OPTIONS.map((option) => {
+ const isActive = activeTab === option.value;
+ const count = option.value === "installed" ? extensionCount : undefined;
+ return (
+ <button
+ key={option.value}
+ type="button"
+ onClick={() => onTabChange(option.value)}
+ className="relative rounded-lg text-[10px] font-semibold tracking-wide transition-colors"
+ >
+ {isActive ? (
+ <motion.span
+ layoutId="extension-tab-pill"
+ className="absolute inset-0 rounded-lg bg-[#2563EB]"
+ transition={{ type: "spring", stiffness: 420, damping: 34 }}
+ />
+ ) : null}
+ <span
+ className={cn(
+ "relative z-10 flex items-center justify-center gap-1",
+ isActive ? "text-white" : "text-slate-400 hover:text-slate-200",
+ )}
+ >
+ {t(option.labelKey)}
+ {count !== undefined && count > 0 && (
+ <span
+ className={cn(
+ "text-[8px] px-1 rounded-full font-semibold min-w-[14px] text-center leading-[14px]",
+ isActive
+ ? "bg-white/20 text-white"
+ : "bg-white/5 text-slate-600",
+ )}
+ >
+ {count}
+ </span>
+ )}
+ </span>
+ </button>
+ );
+ })}
+ </div>
+ </LayoutGroup>
+ );
}
// ---------------------------------------------------------------------------
@@ -584,262 +618,289 @@ function TabSwitcher({
// ---------------------------------------------------------------------------
export default function ExtensionManager() {
- const t = useScopedT("extensions");
- const {
- extensions,
- activeIds,
- ready,
- refresh,
- toggleExtension,
- installFromFolder,
- uninstall,
- openDirectory,
- marketplaceSearch,
- marketplaceInstall,
- } = useExtensions();
-
- const [activeTab, setActiveTab] = useState<ExtensionTab>("browse");
- const [isRefreshing, setIsRefreshing] = useState(false);
-
- // Marketplace state
- const [searchQuery, setSearchQuery] = useState("");
- const [marketplaceResults, setMarketplaceResults] = useState<MarketplaceExtension[]>([]);
- const [marketplaceLoading, setMarketplaceLoading] = useState(false);
- const [marketplaceError, setMarketplaceError] = useState<string | null>(null);
- const [installingIds, setInstallingIds] = useState<Set<string>>(new Set());
-
- // Extension detail modal state
- const [detailData, setDetailData] = useState<ExtensionDetailData | null>(null);
-
- const handleInstallFromFolder = useCallback(async () => {
- const success = await installFromFolder();
- if (success) {
- toast.success(t("toast.installedAndEnabled"));
- }
- }, [installFromFolder]);
-
- const handleUninstall = useCallback(
- async (id: string, name: string) => {
- const success = await uninstall(id);
- if (success) {
- toast.success(t("toast.uninstalled", undefined, { name }));
- // Clear installed flag in cached marketplace results
- setMarketplaceResults((prev) =>
- prev.map((e) => (e.id === id ? { ...e, installed: false } : e)),
- );
- } else {
- toast.error(t("toast.uninstallFailed", undefined, { name }));
- }
- },
- [uninstall],
- );
-
- // Marketplace search
- const handleSearch = useCallback(async () => {
- setMarketplaceLoading(true);
- setMarketplaceError(null);
- try {
- const result = await marketplaceSearch({
- query: searchQuery || undefined,
- sort: "popular",
- pageSize: 50,
- });
- setMarketplaceResults(result.extensions);
- } catch (err: any) {
- setMarketplaceError(err.message ?? t("toast.searchFailed"));
- setMarketplaceResults([]);
- } finally {
- setMarketplaceLoading(false);
- }
- }, [searchQuery, marketplaceSearch]);
-
- const handleRefresh = useCallback(async () => {
- setIsRefreshing(true);
- try {
- await refresh();
-
- if (activeTab === "browse") {
- await handleSearch();
- }
-
- toast.success(t("toast.refreshed"));
- } catch {
- toast.error(t("toast.refreshFailed"));
- } finally {
- setIsRefreshing(false);
- }
- }, [activeTab, handleSearch, refresh]);
-
- // Auto-search when switching to browse tab
- useEffect(() => {
- if (activeTab === "browse" && marketplaceResults.length === 0 && !marketplaceLoading) {
- handleSearch();
- }
- }, [activeTab]); // eslint-disable-line react-hooks/exhaustive-deps
-
- // Marketplace install
- const handleMarketplaceInstall = useCallback(
- async (ext: MarketplaceExtension) => {
- setInstallingIds((prev) => new Set(prev).add(ext.id));
- try {
- const result = await marketplaceInstall(ext.id, ext.downloadUrl);
- if (result.success) {
- toast.success(t("toast.marketplaceInstalled", undefined, { name: ext.name }));
- // Update the marketplace results to show installed state
- setMarketplaceResults((prev) =>
- prev.map((e) => (e.id === ext.id ? { ...e, installed: true } : e)),
- );
- } else {
- toast.error(t("toast.marketplaceInstallFailed", undefined, { name: ext.name }), {
- description: result.error,
- });
- }
- } finally {
- setInstallingIds((prev) => {
- const next = new Set(prev);
- next.delete(ext.id);
- return next;
- });
- }
- },
- [marketplaceInstall],
- );
-
- return (
- <div className="flex-[2] w-[332px] min-w-[280px] max-w-[332px] bg-[#161619] border border-white/10 rounded-2xl flex flex-col shadow-xl h-full overflow-hidden">
- {/* Header */}
- <div className="flex-shrink-0 p-4 pb-3">
- <div className="flex items-center justify-between mb-3">
- <div className="flex items-center gap-2">
- <Puzzle className="w-4 h-4 text-[#2563EB]" />
- <h3 className="text-[13px] font-semibold text-slate-200">{t("title")}</h3>
- </div>
- <div className="flex items-center gap-0.5">
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6 text-slate-500 hover:text-slate-300 hover:bg-white/10"
- onClick={() => (window as any).electronAPI?.openExternalUrl(EXTENSIONS_SUBMIT_URL)}
- title={t("actions.submit")}
- >
- <Plus className="w-3 h-3" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6 text-slate-500 hover:text-slate-300 hover:bg-white/10"
- onClick={() => (window as any).electronAPI?.openExternalUrl(EXTENSIONS_DOCS_URL)}
- title={t("actions.docs")}
- >
- <BookOpen className="w-3 h-3" />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6 text-slate-500 hover:text-slate-300 hover:bg-white/10"
- onClick={handleRefresh}
- disabled={isRefreshing}
- title={t("actions.refresh")}
- >
- <RefreshCw className={cn("w-3 h-3", isRefreshing && "animate-spin")} />
- </Button>
- <Button
- variant="ghost"
- size="icon"
- className="h-6 w-6 text-slate-500 hover:text-slate-300 hover:bg-white/10"
- onClick={openDirectory}
- title={t("actions.openFolder")}
- >
- <FolderOpen className="w-3 h-3" />
- </Button>
- </div>
- </div>
-
- <TabSwitcher
- activeTab={activeTab}
- onTabChange={setActiveTab}
- extensionCount={extensions.length}
- />
- </div>
-
- {/* Content */}
- <div className="flex-1 min-h-0 overflow-y-auto custom-scrollbar p-4 pb-0 pt-0" style={{ scrollbarGutter: "stable" }}>
- {!ready ? (
- <div className="flex-1 flex items-center justify-center py-12">
- <Loader2 className="w-5 h-5 text-slate-600 animate-spin" />
- </div>
- ) : (
- <AnimatePresence mode="wait" initial={false}>
- <motion.div
- key={activeTab}
- initial={{ opacity: 0, y: 8 }}
- animate={{ opacity: 1, y: 0 }}
- exit={{ opacity: 0, y: -8 }}
- transition={{ duration: 0.18, ease: "easeOut" }}
- >
- {activeTab === "installed" && (
- <InstalledTab
- extensions={extensions}
- activeIds={activeIds}
- onToggle={toggleExtension}
- onUninstall={handleUninstall}
- onInstallFromFolder={handleInstallFromFolder}
- onOpenDirectory={openDirectory}
- onViewDetail={(ext) =>
- setDetailData({ source: 'installed', ext, isActive: activeIds.has(ext.manifest.id) })
- }
- />
- )}
-
- {activeTab === "browse" && (
- <BrowseTab
- searchQuery={searchQuery}
- onSearchQueryChange={setSearchQuery}
- onSearch={handleSearch}
- results={marketplaceResults}
- loading={marketplaceLoading}
- error={marketplaceError}
- installingIds={installingIds}
- onInstall={handleMarketplaceInstall}
- onViewDetail={(ext) => setDetailData({ source: 'marketplace', ext })}
- />
- )}
- </motion.div>
- </AnimatePresence>
- )}
- </div>
-
- {/* Extension Detail Modal */}
- {detailData && (
- <ExtensionDetailModal
- detail={detailData}
- onClose={() => setDetailData(null)}
- onToggle={
- detailData.source === 'installed'
- ? () => {
- toggleExtension(detailData.ext.manifest.id);
- setDetailData((prev) =>
- prev?.source === 'installed'
- ? { ...prev, isActive: !prev.isActive }
- : prev,
- );
- }
- : undefined
- }
- onInstall={
- detailData.source === 'marketplace' && !detailData.ext.installed
- ? () => handleMarketplaceInstall(detailData.ext as MarketplaceExtension)
- : undefined
- }
- isInstalling={
- detailData.source === 'marketplace'
- ? installingIds.has(detailData.ext.id)
- : false
- }
- />
- )}
- </div>
- );
+ const t = useScopedT("extensions");
+ const {
+ extensions,
+ activeIds,
+ ready,
+ refresh,
+ toggleExtension,
+ installFromFolder,
+ uninstall,
+ openDirectory,
+ marketplaceSearch,
+ marketplaceInstall,
+ } = useExtensions();
+
+ const [activeTab, setActiveTab] = useState<ExtensionTab>("browse");
+ const [isRefreshing, setIsRefreshing] = useState(false);
+
+ // Marketplace state
+ const [searchQuery, setSearchQuery] = useState("");
+ const [marketplaceResults, setMarketplaceResults] = useState<MarketplaceExtension[]>([]);
+ const [marketplaceLoading, setMarketplaceLoading] = useState(false);
+ const [marketplaceError, setMarketplaceError] = useState<string | null>(null);
+ const [installingIds, setInstallingIds] = useState<Set<string>>(new Set());
+
+ // Extension detail modal state
+ const [detailData, setDetailData] = useState<ExtensionDetailData | null>(null);
+
+ const handleInstallFromFolder = useCallback(async () => {
+ const success = await installFromFolder();
+ if (success) {
+ toast.success(t("toast.installedAndEnabled"));
+ }
+ }, [installFromFolder]);
+
+ const handleToggleExtension = useCallback(
+ async (id: string) => {
+ try {
+ await toggleExtension(id);
+ } catch {
+ toast.error(t("toast.enableFailed"));
+ }
+ },
+ [toggleExtension, t],
+ );
+
+ const handleUninstall = useCallback(
+ async (id: string, name: string) => {
+ const success = await uninstall(id);
+ if (success) {
+ toast.success(t("toast.uninstalled", undefined, { name }));
+ // Clear installed flag in cached marketplace results
+ setMarketplaceResults((prev) =>
+ prev.map((e) => (e.id === id ? { ...e, installed: false } : e)),
+ );
+ } else {
+ toast.error(t("toast.uninstallFailed", undefined, { name }));
+ }
+ },
+ [uninstall],
+ );
+
+ // Marketplace search
+ const handleSearch = useCallback(async () => {
+ setMarketplaceLoading(true);
+ setMarketplaceError(null);
+ try {
+ const result = await marketplaceSearch({
+ query: searchQuery || undefined,
+ sort: "popular",
+ pageSize: 50,
+ });
+ setMarketplaceResults(result.extensions);
+ } catch (err) {
+ setMarketplaceError(err instanceof Error ? err.message : t("toast.searchFailed"));
+ setMarketplaceResults([]);
+ } finally {
+ setMarketplaceLoading(false);
+ }
+ }, [marketplaceSearch, searchQuery, t]);
+
+ const handleRefresh = useCallback(async () => {
+ setIsRefreshing(true);
+ try {
+ await refresh();
+
+ if (activeTab === "browse") {
+ await handleSearch();
+ }
+
+ toast.success(t("toast.refreshed"));
+ } catch {
+ toast.error(t("toast.refreshFailed"));
+ } finally {
+ setIsRefreshing(false);
+ }
+ }, [activeTab, handleSearch, refresh]);
+
+ // Auto-search when switching to browse tab
+ useEffect(() => {
+ if (activeTab === "browse" && marketplaceResults.length === 0 && !marketplaceLoading) {
+ handleSearch();
+ }
+ }, [activeTab]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ // Marketplace install
+ const handleMarketplaceInstall = useCallback(
+ async (ext: MarketplaceExtension) => {
+ setInstallingIds((prev) => new Set(prev).add(ext.id));
+ try {
+ const result = await marketplaceInstall(ext.id, ext.downloadUrl);
+ if (result.success) {
+ toast.success(t("toast.marketplaceInstalled", undefined, { name: ext.name }));
+ // Update the marketplace results to show installed state
+ setMarketplaceResults((prev) =>
+ prev.map((e) => (e.id === ext.id ? { ...e, installed: true } : e)),
+ );
+ } else {
+ toast.error(
+ t("toast.marketplaceInstallFailed", undefined, { name: ext.name }),
+ {
+ description: result.error,
+ },
+ );
+ }
+ } finally {
+ setInstallingIds((prev) => {
+ const next = new Set(prev);
+ next.delete(ext.id);
+ return next;
+ });
+ }
+ },
+ [marketplaceInstall],
+ );
+
+ return (
+ <div className="flex-[2] w-[332px] min-w-[280px] max-w-[332px] bg-[#161619] border border-white/10 rounded-2xl flex flex-col shadow-xl h-full overflow-hidden">
+ {/* Header */}
+ <div className="flex-shrink-0 p-4 pb-3">
+ <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center gap-2">
+ <Puzzle className="w-4 h-4 text-[#2563EB]" />
+ <h3 className="text-[13px] font-semibold text-slate-200">{t("title")}</h3>
+ </div>
+ <div className="flex items-center gap-0.5">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 text-slate-500 hover:text-slate-300 hover:bg-white/10"
+ onClick={() =>
+ void window.electronAPI.openExternalUrl(EXTENSIONS_SUBMIT_URL)
+ }
+ title={t("actions.submit")}
+ >
+ <Plus className="w-3 h-3" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 text-slate-500 hover:text-slate-300 hover:bg-white/10"
+ onClick={() =>
+ void window.electronAPI.openExternalUrl(EXTENSIONS_DOCS_URL)
+ }
+ title={t("actions.docs")}
+ >
+ <BookOpen className="w-3 h-3" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 text-slate-500 hover:text-slate-300 hover:bg-white/10"
+ onClick={handleRefresh}
+ disabled={isRefreshing}
+ title={t("actions.refresh")}
+ >
+ <RefreshCw className={cn("w-3 h-3", isRefreshing && "animate-spin")} />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="h-6 w-6 text-slate-500 hover:text-slate-300 hover:bg-white/10"
+ onClick={openDirectory}
+ title={t("actions.openFolder")}
+ >
+ <FolderOpen className="w-3 h-3" />
+ </Button>
+ </div>
+ </div>
+
+ <TabSwitcher
+ activeTab={activeTab}
+ onTabChange={setActiveTab}
+ extensionCount={extensions.length}
+ />
+ </div>
+
+ {/* Content */}
+ <div
+ className="flex-1 min-h-0 overflow-y-auto custom-scrollbar p-4 pb-0 pt-0"
+ style={{ scrollbarGutter: "stable" }}
+ >
+ {!ready ? (
+ <div className="flex-1 flex items-center justify-center py-12">
+ <Loader2 className="w-5 h-5 text-slate-600 animate-spin" />
+ </div>
+ ) : (
+ <AnimatePresence mode="wait" initial={false}>
+ <motion.div
+ key={activeTab}
+ initial={{ opacity: 0, y: 8 }}
+ animate={{ opacity: 1, y: 0 }}
+ exit={{ opacity: 0, y: -8 }}
+ transition={{ duration: 0.18, ease: "easeOut" }}
+ >
+ {activeTab === "installed" && (
+ <InstalledTab
+ extensions={extensions}
+ activeIds={activeIds}
+ onToggle={handleToggleExtension}
+ onUninstall={handleUninstall}
+ onInstallFromFolder={handleInstallFromFolder}
+ onOpenDirectory={openDirectory}
+ onViewDetail={(ext) =>
+ setDetailData({
+ source: "installed",
+ ext,
+ isActive: activeIds.has(ext.manifest.id),
+ })
+ }
+ />
+ )}
+
+ {activeTab === "browse" && (
+ <BrowseTab
+ searchQuery={searchQuery}
+ onSearchQueryChange={setSearchQuery}
+ onSearch={handleSearch}
+ results={marketplaceResults}
+ loading={marketplaceLoading}
+ error={marketplaceError}
+ installingIds={installingIds}
+ onInstall={handleMarketplaceInstall}
+ onViewDetail={(ext) =>
+ setDetailData({ source: "marketplace", ext })
+ }
+ />
+ )}
+ </motion.div>
+ </AnimatePresence>
+ )}
+ </div>
+
+ {/* Extension Detail Modal */}
+ {detailData && (
+ <ExtensionDetailModal
+ detail={detailData}
+ onClose={() => setDetailData(null)}
+ onToggle={
+ detailData.source === "installed"
+ ? async () => {
+ await handleToggleExtension(detailData.ext.manifest.id);
+ setDetailData((prev) =>
+ prev?.source === "installed"
+ ? { ...prev, isActive: !prev.isActive }
+ : prev,
+ );
+ }
+ : undefined
+ }
+ onInstall={
+ detailData.source === "marketplace" && !detailData.ext.installed
+ ? () => handleMarketplaceInstall(detailData.ext as MarketplaceExtension)
+ : undefined
+ }
+ isInstalling={
+ detailData.source === "marketplace"
+ ? installingIds.has(detailData.ext.id)
+ : false
+ }
+ />
+ )}
+ </div>
+ );
}
// ---------------------------------------------------------------------------
@@ -847,91 +908,91 @@ export default function ExtensionManager() {
// ---------------------------------------------------------------------------
function InstalledTab({
- extensions,
- activeIds,
- onToggle,
- onUninstall,
- onInstallFromFolder,
- onOpenDirectory,
- onViewDetail,
+ extensions,
+ activeIds,
+ onToggle,
+ onUninstall,
+ onInstallFromFolder,
+ onOpenDirectory,
+ onViewDetail,
}: {
- extensions: ExtensionInfo[];
- activeIds: Set<string>;
- onToggle: (id: string) => Promise<void>;
- onUninstall: (id: string, name: string) => void;
- onInstallFromFolder: () => void;
- onOpenDirectory: () => void;
- onViewDetail: (ext: ExtensionInfo) => void;
+ extensions: ExtensionInfo[];
+ activeIds: Set<string>;
+ onToggle: (id: string) => Promise<void>;
+ onUninstall: (id: string, name: string) => void;
+ onInstallFromFolder: () => void;
+ onOpenDirectory: () => void;
+ onViewDetail: (ext: ExtensionInfo) => void;
}) {
- const t = useScopedT("extensions");
- if (extensions.length === 0) {
- return (
- <div className="flex flex-col items-center justify-center gap-3 py-10">
- <div className="w-11 h-11 rounded-full bg-white/[0.04] flex items-center justify-center">
- <Puzzle className="w-5 h-5 text-slate-600" />
- </div>
- <div className="text-center">
- <p className="text-[13px] font-medium text-slate-400">{t("empty.title")}</p>
- <p className="text-[11px] text-slate-600 mt-1 leading-relaxed max-w-[200px]">
- {t("empty.description")}
- </p>
- </div>
- <div className="flex gap-2 mt-2">
- <Button
- variant="ghost"
- size="sm"
- className="h-7 px-2.5 text-[11px] text-slate-400 hover:text-slate-200 hover:bg-white/10 gap-1"
- onClick={onInstallFromFolder}
- >
- <Plus className="w-3 h-3" />
- {t("actions.install")}
- </Button>
- <Button
- variant="ghost"
- size="sm"
- className="h-7 px-2.5 text-[11px] text-slate-400 hover:text-slate-200 hover:bg-white/10 gap-1"
- onClick={onOpenDirectory}
- >
- <FolderOpen className="w-3 h-3" />
- {t("actions.folder")}
- </Button>
- </div>
- </div>
- );
- }
-
- return (
- <div className="flex flex-col gap-2">
- <div className="flex items-center justify-between mb-1">
- <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400">
- {t("tabs.installed")}
- </p>
- <Button
- variant="ghost"
- size="sm"
- className="h-6 px-2 text-[10px] text-slate-500 hover:text-slate-300 hover:bg-white/10 gap-1"
- onClick={onInstallFromFolder}
- >
- <Plus className="w-2.5 h-2.5" />
- {t("actions.add")}
- </Button>
- </div>
- {extensions.map((ext) => (
- <InstalledExtensionCard
- key={ext.manifest.id}
- extension={ext}
- isActive={activeIds.has(ext.manifest.id)}
- onToggle={() => onToggle(ext.manifest.id)}
- onUninstall={
- ext.builtin
- ? undefined
- : () => onUninstall(ext.manifest.id, ext.manifest.name)
- }
- onClick={() => onViewDetail(ext)}
- />
- ))}
- </div>
- );
+ const t = useScopedT("extensions");
+ if (extensions.length === 0) {
+ return (
+ <div className="flex flex-col items-center justify-center gap-3 py-10">
+ <div className="w-11 h-11 rounded-full bg-white/[0.04] flex items-center justify-center">
+ <Puzzle className="w-5 h-5 text-slate-600" />
+ </div>
+ <div className="text-center">
+ <p className="text-[13px] font-medium text-slate-400">{t("empty.title")}</p>
+ <p className="text-[11px] text-slate-600 mt-1 leading-relaxed max-w-[200px]">
+ {t("empty.description")}
+ </p>
+ </div>
+ <div className="flex gap-2 mt-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2.5 text-[11px] text-slate-400 hover:text-slate-200 hover:bg-white/10 gap-1"
+ onClick={onInstallFromFolder}
+ >
+ <Plus className="w-3 h-3" />
+ {t("actions.install")}
+ </Button>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2.5 text-[11px] text-slate-400 hover:text-slate-200 hover:bg-white/10 gap-1"
+ onClick={onOpenDirectory}
+ >
+ <FolderOpen className="w-3 h-3" />
+ {t("actions.folder")}
+ </Button>
+ </div>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex flex-col gap-2">
+ <div className="flex items-center justify-between mb-1">
+ <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400">
+ {t("tabs.installed")}
+ </p>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-6 px-2 text-[10px] text-slate-500 hover:text-slate-300 hover:bg-white/10 gap-1"
+ onClick={onInstallFromFolder}
+ >
+ <Plus className="w-2.5 h-2.5" />
+ {t("actions.add")}
+ </Button>
+ </div>
+ {extensions.map((ext) => (
+ <InstalledExtensionCard
+ key={ext.manifest.id}
+ extension={ext}
+ isActive={activeIds.has(ext.manifest.id)}
+ onToggle={() => onToggle(ext.manifest.id)}
+ onUninstall={
+ ext.builtin
+ ? undefined
+ : () => onUninstall(ext.manifest.id, ext.manifest.name)
+ }
+ onClick={() => onViewDetail(ext)}
+ />
+ ))}
+ </div>
+ );
}
// ---------------------------------------------------------------------------
@@ -939,94 +1000,94 @@ function InstalledTab({
// ---------------------------------------------------------------------------
function BrowseTab({
- searchQuery,
- onSearchQueryChange,
- onSearch,
- results,
- loading,
- error,
- installingIds,
- onInstall,
- onViewDetail,
+ searchQuery,
+ onSearchQueryChange,
+ onSearch,
+ results,
+ loading,
+ error,
+ installingIds,
+ onInstall,
+ onViewDetail,
}: {
- searchQuery: string;
- onSearchQueryChange: (q: string) => void;
- onSearch: () => void;
- results: MarketplaceExtension[];
- loading: boolean;
- error: string | null;
- installingIds: Set<string>;
- onInstall: (ext: MarketplaceExtension) => void;
- onViewDetail: (ext: MarketplaceExtension) => void;
+ searchQuery: string;
+ onSearchQueryChange: (q: string) => void;
+ onSearch: () => void;
+ results: MarketplaceExtension[];
+ loading: boolean;
+ error: string | null;
+ installingIds: Set<string>;
+ onInstall: (ext: MarketplaceExtension) => void;
+ onViewDetail: (ext: MarketplaceExtension) => void;
}) {
- const t = useScopedT("extensions");
- return (
- <div className="flex flex-col gap-3">
- {/* Search */}
- <div className="relative">
- <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-500 pointer-events-none" />
- <input
- type="text"
- placeholder={t("search.placeholder")}
- value={searchQuery}
- onChange={(e) => onSearchQueryChange(e.target.value)}
- onKeyDown={(e) => {
- e.stopPropagation();
- if (e.key === "Enter") onSearch();
- }}
- className="w-full h-8 pl-8 pr-3 rounded-lg bg-white/[0.04] border border-white/[0.08] text-[12px] text-slate-200 placeholder:text-slate-600 focus:outline-none focus:ring-1 focus:ring-[#2563EB]/50 focus:border-[#2563EB]/30 transition-colors"
- />
- </div>
-
- {/* Results */}
- {loading && (
- <div className="flex items-center justify-center py-10">
- <Loader2 className="w-5 h-5 text-slate-600 animate-spin" />
- </div>
- )}
-
- {error && (
- <div className="flex flex-col items-center gap-2 py-8">
- <ShieldAlert className="w-5 h-5 text-red-400/60" />
- <p className="text-[11px] text-red-400/80 text-center max-w-[200px]">{error}</p>
- <Button
- variant="ghost"
- size="sm"
- className="h-7 px-2.5 text-[11px] text-slate-400 hover:text-slate-200 hover:bg-white/10"
- onClick={onSearch}
- >
- {t("actions.retry")}
- </Button>
- </div>
- )}
-
- {!loading && !error && results.length === 0 && (
- <div className="flex flex-col items-center gap-2 py-10">
- <Search className="w-5 h-5 text-slate-600" />
- <p className="text-[11px] text-slate-600 text-center">
- {searchQuery ? t("search.noResults") : t("search.noMarketplace")}
- </p>
- </div>
- )}
-
- {!loading && !error && results.length > 0 && (
- <div className="flex flex-col gap-2">
- <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400">
- {results.length !== 1
- ? t("search.countPlural", undefined, { count: results.length })
- : t("search.count", undefined, { count: results.length })}
- </p>
- {results.map((ext) => (
- <MarketplaceCard
- key={ext.id}
- extension={ext}
- isInstalling={installingIds.has(ext.id)}
- onInstall={() => onInstall(ext)}
- onClick={() => onViewDetail(ext)}
- />
- ))}
- </div>
- )}
- </div>
- );
+ const t = useScopedT("extensions");
+ return (
+ <div className="flex flex-col gap-3">
+ {/* Search */}
+ <div className="relative">
+ <Search className="absolute left-2.5 top-1/2 -translate-y-1/2 w-3.5 h-3.5 text-slate-500 pointer-events-none" />
+ <input
+ type="text"
+ placeholder={t("search.placeholder")}
+ value={searchQuery}
+ onChange={(e) => onSearchQueryChange(e.target.value)}
+ onKeyDown={(e) => {
+ e.stopPropagation();
+ if (e.key === "Enter") onSearch();
+ }}
+ className="w-full h-8 pl-8 pr-3 rounded-lg bg-white/[0.04] border border-white/[0.08] text-[12px] text-slate-200 placeholder:text-slate-600 focus:outline-none focus:ring-1 focus:ring-[#2563EB]/50 focus:border-[#2563EB]/30 transition-colors"
+ />
+ </div>
+
+ {/* Results */}
+ {loading && (
+ <div className="flex items-center justify-center py-10">
+ <Loader2 className="w-5 h-5 text-slate-600 animate-spin" />
+ </div>
+ )}
+
+ {error && (
+ <div className="flex flex-col items-center gap-2 py-8">
+ <ShieldAlert className="w-5 h-5 text-red-400/60" />
+ <p className="text-[11px] text-red-400/80 text-center max-w-[200px]">{error}</p>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="h-7 px-2.5 text-[11px] text-slate-400 hover:text-slate-200 hover:bg-white/10"
+ onClick={onSearch}
+ >
+ {t("actions.retry")}
+ </Button>
+ </div>
+ )}
+
+ {!loading && !error && results.length === 0 && (
+ <div className="flex flex-col items-center gap-2 py-10">
+ <Search className="w-5 h-5 text-slate-600" />
+ <p className="text-[11px] text-slate-600 text-center">
+ {searchQuery ? t("search.noResults") : t("search.noMarketplace")}
+ </p>
+ </div>
+ )}
+
+ {!loading && !error && results.length > 0 && (
+ <div className="flex flex-col gap-2">
+ <p className="text-[10px] font-semibold uppercase tracking-widest text-slate-400">
+ {results.length !== 1
+ ? t("search.countPlural", undefined, { count: results.length })
+ : t("search.count", undefined, { count: results.length })}
+ </p>
+ {results.map((ext) => (
+ <MarketplaceCard
+ key={ext.id}
+ extension={ext}
+ isInstalling={installingIds.has(ext.id)}
+ onInstall={() => onInstall(ext)}
+ onClick={() => onViewDetail(ext)}
+ />
+ ))}
+ </div>
+ )}
+ </div>
+ );
}
diff --git a/src/components/video-editor/FormatSelector.tsx b/src/components/video-editor/FormatSelector.tsx
index 223528b4..66bd9632 100644
--- a/src/components/video-editor/FormatSelector.tsx
+++ b/src/components/video-editor/FormatSelector.tsx
@@ -1,4 +1,4 @@
-import { Film, Image } from "lucide-react";
+import { FilmSlate as Film, Image } from "@phosphor-icons/react";
import { useScopedT } from "@/contexts/I18nContext";
import type { ExportFormat } from "@/lib/exporter/types";
import { cn } from "@/lib/utils";
@@ -67,7 +67,9 @@ export function FormatSelector({
</div>
<div className="text-center">
<div className="font-medium text-sm">{option.label}</div>
- <div className="text-xs text-slate-500 mt-0.5">{option.description}</div>
+ <div className="text-xs text-slate-500 mt-0.5">
+ {option.description}
+ </div>
</div>
{isSelected && (
<div className="absolute top-2 right-2 w-2 h-2 rounded-full bg-[#2563EB]" />
diff --git a/src/components/video-editor/KeyboardShortcutsHelp.tsx b/src/components/video-editor/KeyboardShortcutsHelp.tsx
index c228b4b9..9c99ee16 100644
--- a/src/components/video-editor/KeyboardShortcutsHelp.tsx
+++ b/src/components/video-editor/KeyboardShortcutsHelp.tsx
@@ -1,4 +1,4 @@
-import { HelpCircle, Settings2 } from "lucide-react";
+import { Gear as Settings2, Question as HelpCircle } from "@phosphor-icons/react";
import { useEffect, useState } from "react";
import { useScopedT } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
@@ -53,19 +53,25 @@ export function KeyboardShortcutsHelp() {
<div className="pt-1 border-t border-white/5 mt-1">
<div className="flex items-center justify-between">
- <span className="text-slate-400">{t("keyboardShortcuts.panTimeline")}</span>
+ <span className="text-slate-400">
+ {t("keyboardShortcuts.panTimeline")}
+ </span>
<kbd className="px-1 py-0.5 bg-white/5 border border-white/10 rounded text-[#2563EB] font-mono">
{scrollLabels.pan}
</kbd>
</div>
<div className="flex items-center justify-between mt-1.5">
- <span className="text-slate-400">{t("keyboardShortcuts.zoomTimeline")}</span>
+ <span className="text-slate-400">
+ {t("keyboardShortcuts.zoomTimeline")}
+ </span>
<kbd className="px-1 py-0.5 bg-white/5 border border-white/10 rounded text-[#2563EB] font-mono">
{scrollLabels.zoom}
</kbd>
</div>
<div className="flex items-center justify-between mt-1.5">
- <span className="text-slate-400">{t("keyboardShortcuts.cycleAnnotations")}</span>
+ <span className="text-slate-400">
+ {t("keyboardShortcuts.cycleAnnotations")}
+ </span>
<kbd className="px-1 py-0.5 bg-white/5 border border-white/10 rounded text-[#2563EB] font-mono">
{t("keyboardShortcuts.tab")}
</kbd>
diff --git a/src/components/video-editor/PlaybackControls.tsx b/src/components/video-editor/PlaybackControls.tsx
index 820e13f0..729ccdb5 100644
--- a/src/components/video-editor/PlaybackControls.tsx
+++ b/src/components/video-editor/PlaybackControls.tsx
@@ -1,4 +1,4 @@
-import { Pause, Play, Volume2, VolumeX } from "lucide-react";
+import { Pause, Play, SpeakerHigh as Volume2, SpeakerX as VolumeX } from "@phosphor-icons/react";
import { useScopedT } from "@/contexts/I18nContext";
import { cn } from "@/lib/utils";
import { Button } from "../ui/button";
@@ -54,9 +54,9 @@ export default function PlaybackControls({
aria-label={isPlaying ? t("playback.pause") : t("playback.play")}
>
{isPlaying ? (
- <Pause className="w-3.5 h-3.5 fill-current" />
+ <Pause className="w-3.5 h-3.5" weight="fill" />
) : (
- <Play className="w-3.5 h-3.5 fill-current ml-0.5" />
+ <Play className="w-3.5 h-3.5" weight="fill" />
)}
</Button>
@@ -67,7 +67,10 @@ export default function PlaybackControls({
<div className="flex-1 relative h-6 flex items-center group">
{/* Custom Track Background */}
<div className="absolute left-0 right-0 h-0.5 bg-white/10 rounded-full overflow-hidden">
- <div className="h-full bg-[#2563EB] rounded-full" style={{ width: `${progress}%` }} />
+ <div
+ className="h-full bg-[#2563EB] rounded-full"
+ style={{ width: `${progress}%` }}
+ />
</div>
{/* Interactive Input */}
@@ -103,7 +106,10 @@ export default function PlaybackControls({
)}
<div className="group relative flex h-6 w-20 items-center">
<div className="absolute left-0 right-0 h-0.5 rounded-full bg-white/10 overflow-hidden">
- <div className="h-full rounded-full bg-white/70" style={{ width: `${volume * 100}%` }} />
+ <div
+ className="h-full rounded-full bg-white/70"
+ style={{ width: `${volume * 100}%` }}
+ />
</div>
<input
type="range"
diff --git a/src/components/video-editor/ProjectBrowserDialog.tsx b/src/components/video-editor/ProjectBrowserDialog.tsx
index 7cd4156b..26c92297 100644
--- a/src/components/video-editor/ProjectBrowserDialog.tsx
+++ b/src/components/video-editor/ProjectBrowserDialog.tsx
@@ -69,9 +69,15 @@ export default function ProjectBrowserDialog({
? Math.max(margin, anchorRect.top - Math.min(panelHeight, maxHeight) - gap)
: Math.min(
anchorRect.bottom + gap,
- Math.max(margin, viewportHeight - Math.min(panelHeight, maxHeight) - margin),
+ Math.max(
+ margin,
+ viewportHeight - Math.min(panelHeight, maxHeight) - margin,
+ ),
)
- : Math.min(56, Math.max(margin, viewportHeight - Math.min(panelHeight, maxHeight) - margin));
+ : Math.min(
+ 56,
+ Math.max(margin, viewportHeight - Math.min(panelHeight, maxHeight) - margin),
+ );
const alignedLeft = anchorRect
? anchorRect.right - panelWidth
: viewportWidth - panelWidth - 16;
@@ -175,7 +181,9 @@ export default function ProjectBrowserDialog({
{visibleEntries.length > 0 ? (
<div className="grid grid-cols-2 gap-2">
{visibleEntries.map((entry) => {
- const thumbnailSrc = entry.thumbnailPath ? toFileUrl(entry.thumbnailPath) : null;
+ const thumbnailSrc = entry.thumbnailPath
+ ? toFileUrl(entry.thumbnailPath)
+ : null;
return (
<button
key={entry.path}
@@ -215,7 +223,9 @@ export default function ProjectBrowserDialog({
</div>
) : (
<div className="flex min-h-[140px] flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-white/10 bg-[#111215] px-4 text-center shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]">
- <div className="text-sm font-semibold text-white">No saved projects yet</div>
+ <div className="text-sm font-semibold text-white">
+ No saved projects yet
+ </div>
</div>
)}
</div>
@@ -242,7 +252,9 @@ export default function ProjectBrowserDialog({
{visibleEntries.length > 0 ? (
<div className="grid grid-cols-2 gap-2">
{visibleEntries.map((entry) => {
- const thumbnailSrc = entry.thumbnailPath ? toFileUrl(entry.thumbnailPath) : null;
+ const thumbnailSrc = entry.thumbnailPath
+ ? toFileUrl(entry.thumbnailPath)
+ : null;
return (
<button
key={entry.path}
@@ -282,7 +294,9 @@ export default function ProjectBrowserDialog({
</div>
) : (
<div className="flex min-h-[140px] flex-col items-center justify-center gap-3 rounded-xl border border-dashed border-white/10 bg-[#111215] px-4 text-center shadow-[inset_0_1px_0_rgba(255,255,255,0.04)]">
- <div className="text-sm font-semibold text-white">No saved projects yet</div>
+ <div className="text-sm font-semibold text-white">
+ No saved projects yet
+ </div>
</div>
)}
</div>
diff --git a/src/components/video-editor/ShortcutsConfigDialog.tsx b/src/components/video-editor/ShortcutsConfigDialog.tsx
index f8bc24de..ac5713c2 100644
--- a/src/components/video-editor/ShortcutsConfigDialog.tsx
+++ b/src/components/video-editor/ShortcutsConfigDialog.tsx
@@ -1,226 +1,255 @@
-import { useCallback, useEffect, useState } from 'react';
-import { Keyboard, RotateCcw } from 'lucide-react';
-import { toast } from 'sonner';
-
-import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog';
-import { Button } from '@/components/ui/button';
+import { ArrowCounterClockwise as RotateCcw, Keyboard } from "@phosphor-icons/react";
+import { useCallback, useEffect, useState } from "react";
+import { toast } from "sonner";
+import { Button } from "@/components/ui/button";
+import {
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
+} from "@/components/ui/dialog";
+import { useShortcuts } from "@/contexts/ShortcutsContext";
import {
- DEFAULT_SHORTCUTS,
- FIXED_SHORTCUTS,
- SHORTCUT_ACTIONS,
- SHORTCUT_LABELS,
- findConflict,
- formatBinding,
- type ShortcutAction,
- type ShortcutBinding,
- type ShortcutConflict,
- type ShortcutsConfig,
-} from '@/lib/shortcuts';
-import { useShortcuts } from '@/contexts/ShortcutsContext';
-import { useScopedT } from '../../contexts/I18nContext';
-
-const MODIFIER_KEYS = new Set(['Control', 'Shift', 'Alt', 'Meta']);
+ DEFAULT_SHORTCUTS,
+ FIXED_SHORTCUTS,
+ findConflict,
+ formatBinding,
+ SHORTCUT_ACTIONS,
+ SHORTCUT_LABELS,
+ type ShortcutAction,
+ type ShortcutBinding,
+ type ShortcutConflict,
+ type ShortcutsConfig,
+} from "@/lib/shortcuts";
+import { useScopedT } from "../../contexts/I18nContext";
+
+const MODIFIER_KEYS = new Set(["Control", "Shift", "Alt", "Meta"]);
export function ShortcutsConfigDialog() {
- const t = useScopedT('dialogs');
- const { shortcuts, isMac, isConfigOpen, closeConfig, setShortcuts, persistShortcuts } =
- useShortcuts();
-
- const [draft, setDraft] = useState<ShortcutsConfig>(shortcuts);
- const [captureFor, setCaptureFor] = useState<ShortcutAction | null>(null);
- const [conflict, setConflict] = useState<{ forAction: ShortcutAction; pending: ShortcutBinding; conflictWith: ShortcutConflict } | null>(null);
-
- useEffect(() => {
- if (isConfigOpen) {
- setDraft(shortcuts);
- setCaptureFor(null);
- setConflict(null);
- }
- }, [isConfigOpen, shortcuts]);
-
- useEffect(() => {
- if (!captureFor) return;
-
- const handleCapture = (e: KeyboardEvent) => {
- e.preventDefault();
- e.stopPropagation();
-
- if (e.key === 'Escape') {
- setCaptureFor(null);
- return;
- }
-
- if (MODIFIER_KEYS.has(e.key)) return;
-
- const binding: ShortcutBinding = {
- key: e.key.toLowerCase(),
- ...(e.ctrlKey || e.metaKey ? { ctrl: true } : {}),
- ...(e.shiftKey ? { shift: true } : {}),
- ...(e.altKey ? { alt: true } : {}),
- };
-
- const found = findConflict(binding, captureFor, draft);
- setCaptureFor(null);
-
- if (found?.type === 'fixed') {
- toast.error(t('shortcutsConfig.reserved', undefined, { label: found.label }));
- return;
- }
-
- if (found?.type === 'configurable') {
- setConflict({ forAction: captureFor, pending: binding, conflictWith: found });
- return;
- }
-
- setDraft((prev: ShortcutsConfig) => ({ ...prev, [captureFor]: binding }));
- };
-
- window.addEventListener('keydown', handleCapture, { capture: true });
- return () => window.removeEventListener('keydown', handleCapture, { capture: true });
- }, [captureFor, t]);
-
- const handleSwap = useCallback(() => {
- if (!conflict || conflict.conflictWith.type !== 'configurable') return;
- const { forAction, pending, conflictWith } = conflict;
- setDraft((prev: ShortcutsConfig) => ({
- ...prev,
- [forAction]: pending,
- [conflictWith.action]: prev[forAction],
- }));
- setConflict(null);
- }, [conflict]);
-
- const handleCancelConflict = useCallback(() => setConflict(null), []);
-
- const handleSave = useCallback(async () => {
- setShortcuts(draft);
- await persistShortcuts(draft);
- toast.success(t('shortcutsConfig.saved'));
- closeConfig();
- }, [draft, setShortcuts, persistShortcuts, closeConfig, t]);
-
- const handleReset = useCallback(() => {
- setDraft({ ...DEFAULT_SHORTCUTS });
- toast.info(t('shortcutsConfig.resetNotice'));
- }, [t]);
-
- const handleClose = useCallback(() => {
- setCaptureFor(null);
- setConflict(null);
- closeConfig();
- }, [closeConfig]);
-
- return (
- <Dialog open={isConfigOpen} onOpenChange={(open: boolean) => { if (!open) handleClose(); }}>
- <DialogContent className="bg-[#09090b] border-white/10 text-white max-w-[460px]">
- <DialogHeader>
- <DialogTitle className="flex items-center gap-2 text-sm">
- <Keyboard className="w-4 h-4 text-[#2563EB]" />
- {t('shortcutsConfig.title')}
- </DialogTitle>
- </DialogHeader>
-
- <div className="space-y-0.5">
- <p className="text-[10px] text-slate-500 mb-2 uppercase tracking-wide font-semibold">{t('shortcutsConfig.configurable')}</p>
- {SHORTCUT_ACTIONS.map((action) => {
- const isCapturing = captureFor === action;
- const hasConflict = conflict?.forAction === action;
- return (
- <div key={action}>
- <div className="flex items-center justify-between py-1.5 px-1 border-b border-white/5">
- <span className="text-sm text-slate-300">{SHORTCUT_LABELS[action]}</span>
- <button
- type="button"
- onClick={() => {
- setConflict(null);
- setCaptureFor(isCapturing ? null : action);
- }}
- title={isCapturing ? t('shortcutsConfig.pressEscToCancel') : t('shortcutsConfig.clickToChange')}
- className={[
- 'px-2 py-1 rounded text-xs font-mono border transition-all min-w-[90px] text-center select-none',
- isCapturing
- ? 'bg-[#2563EB]/20 border-[#2563EB] text-[#2563EB] animate-pulse'
- : hasConflict
- ? 'bg-amber-500/10 border-amber-500/50 text-amber-400'
- : 'bg-white/5 border-white/10 text-slate-200 hover:border-[#2563EB]/50 hover:text-[#2563EB] cursor-pointer',
- ].join(' ')}
- >
- {isCapturing ? t('shortcutsConfig.pressAKey') : formatBinding(draft[action], isMac)}
- </button>
- </div>
- {hasConflict && conflict?.conflictWith.type === 'configurable' && (
- <div className="flex items-center justify-between px-1 py-1.5 mb-0.5 bg-amber-500/10 border border-amber-500/20 rounded text-xs">
- <span className="text-amber-400">
- {t('shortcutsConfig.alreadyUsedBy', undefined, { action: SHORTCUT_LABELS[conflict.conflictWith.action] })}
- </span>
- <div className="flex gap-1.5">
- <button
- type="button"
- onClick={handleSwap}
- className="px-2 py-0.5 bg-amber-500/20 hover:bg-amber-500/30 border border-amber-500/40 rounded text-amber-300 font-medium transition-colors"
- >
- {t('shortcutsConfig.swap')}
- </button>
- <button
- type="button"
- onClick={handleCancelConflict}
- className="px-2 py-0.5 bg-white/5 hover:bg-white/10 border border-white/10 rounded text-slate-400 transition-colors"
- >
- {t('shortcutsConfig.cancel')}
- </button>
- </div>
- </div>
- )}
- </div>
- );
- })}
- </div>
-
- <div className="space-y-0.5 mt-2">
- <p className="text-[10px] text-slate-500 mb-2 uppercase tracking-wide font-semibold">{t('shortcutsConfig.fixed')}</p>
- {FIXED_SHORTCUTS.map(({ label, display }) => (
- <div
- key={label}
- className="flex items-center justify-between py-1.5 px-1 border-b border-white/5 last:border-0"
- >
- <span className="text-sm text-slate-400">{label}</span>
- <kbd className="px-2 py-1 bg-white/5 border border-white/10 rounded text-xs font-mono text-slate-400 min-w-[90px] text-center">
- {display}
- </kbd>
- </div>
- ))}
- </div>
-
- <p className="text-[10px] text-slate-500 mt-1">
- {t('shortcutsConfig.instructions')}
- </p>
-
- <DialogFooter className="flex gap-2 sm:justify-between mt-2">
- <Button
- title={t('shortcutsConfig.resetToDefaults')}
- variant="ghost"
- size="sm"
- className="text-slate-400 hover:text-white hover:bg-white/10 gap-1.5 max-w-[200px]"
- onClick={handleReset}
- >
- <RotateCcw className="w-3 h-3" />
- <span className="truncate">{t('shortcutsConfig.resetToDefaults')}</span>
- </Button>
- <div className="flex gap-2">
- <Button variant="ghost" size="sm" onClick={handleClose}>
- {t('shortcutsConfig.cancel')}
- </Button>
- <Button
- size="sm"
- className="bg-[#2563EB] hover:bg-[#1d4ed8] text-white"
- onClick={handleSave}
- >
- {t('shortcutsConfig.save')}
- </Button>
- </div>
- </DialogFooter>
- </DialogContent>
- </Dialog>
- );
+ const t = useScopedT("dialogs");
+ const { shortcuts, isMac, isConfigOpen, closeConfig, setShortcuts, persistShortcuts } =
+ useShortcuts();
+
+ const [draft, setDraft] = useState<ShortcutsConfig>(shortcuts);
+ const [captureFor, setCaptureFor] = useState<ShortcutAction | null>(null);
+ const [conflict, setConflict] = useState<{
+ forAction: ShortcutAction;
+ pending: ShortcutBinding;
+ conflictWith: ShortcutConflict;
+ } | null>(null);
+
+ useEffect(() => {
+ if (isConfigOpen) {
+ setDraft(shortcuts);
+ setCaptureFor(null);
+ setConflict(null);
+ }
+ }, [isConfigOpen, shortcuts]);
+
+ useEffect(() => {
+ if (!captureFor) return;
+
+ const handleCapture = (e: KeyboardEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+
+ if (e.key === "Escape") {
+ setCaptureFor(null);
+ return;
+ }
+
+ if (MODIFIER_KEYS.has(e.key)) return;
+
+ const binding: ShortcutBinding = {
+ key: e.key.toLowerCase(),
+ ...(e.ctrlKey || e.metaKey ? { ctrl: true } : {}),
+ ...(e.shiftKey ? { shift: true } : {}),
+ ...(e.altKey ? { alt: true } : {}),
+ };
+
+ const found = findConflict(binding, captureFor, draft);
+ setCaptureFor(null);
+
+ if (found?.type === "fixed") {
+ toast.error(t("shortcutsConfig.reserved", undefined, { label: found.label }));
+ return;
+ }
+
+ if (found?.type === "configurable") {
+ setConflict({ forAction: captureFor, pending: binding, conflictWith: found });
+ return;
+ }
+
+ setDraft((prev: ShortcutsConfig) => ({ ...prev, [captureFor]: binding }));
+ };
+
+ window.addEventListener("keydown", handleCapture, { capture: true });
+ return () => window.removeEventListener("keydown", handleCapture, { capture: true });
+ }, [captureFor, t]);
+
+ const handleSwap = useCallback(() => {
+ if (!conflict || conflict.conflictWith.type !== "configurable") return;
+ const { forAction, pending, conflictWith } = conflict;
+ setDraft((prev: ShortcutsConfig) => ({
+ ...prev,
+ [forAction]: pending,
+ [conflictWith.action]: prev[forAction],
+ }));
+ setConflict(null);
+ }, [conflict]);
+
+ const handleCancelConflict = useCallback(() => setConflict(null), []);
+
+ const handleSave = useCallback(async () => {
+ setShortcuts(draft);
+ await persistShortcuts(draft);
+ toast.success(t("shortcutsConfig.saved"));
+ closeConfig();
+ }, [draft, setShortcuts, persistShortcuts, closeConfig, t]);
+
+ const handleReset = useCallback(() => {
+ setDraft({ ...DEFAULT_SHORTCUTS });
+ toast.info(t("shortcutsConfig.resetNotice"));
+ }, [t]);
+
+ const handleClose = useCallback(() => {
+ setCaptureFor(null);
+ setConflict(null);
+ closeConfig();
+ }, [closeConfig]);
+
+ return (
+ <Dialog
+ open={isConfigOpen}
+ onOpenChange={(open: boolean) => {
+ if (!open) handleClose();
+ }}
+ >
+ <DialogContent className="bg-[#09090b] border-white/10 text-white max-w-[460px]">
+ <DialogHeader>
+ <DialogTitle className="flex items-center gap-2 text-sm">
+ <Keyboard className="w-4 h-4 text-[#2563EB]" />
+ {t("shortcutsConfig.title")}
+ </DialogTitle>
+ </DialogHeader>
+
+ <div className="space-y-0.5">
+ <p className="text-[10px] text-slate-500 mb-2 uppercase tracking-wide font-semibold">
+ {t("shortcutsConfig.configurable")}
+ </p>
+ {SHORTCUT_ACTIONS.map((action) => {
+ const isCapturing = captureFor === action;
+ const hasConflict = conflict?.forAction === action;
+ return (
+ <div key={action}>
+ <div className="flex items-center justify-between py-1.5 px-1 border-b border-white/5">
+ <span className="text-sm text-slate-300">
+ {SHORTCUT_LABELS[action]}
+ </span>
+ <button
+ type="button"
+ onClick={() => {
+ setConflict(null);
+ setCaptureFor(isCapturing ? null : action);
+ }}
+ title={
+ isCapturing
+ ? t("shortcutsConfig.pressEscToCancel")
+ : t("shortcutsConfig.clickToChange")
+ }
+ className={[
+ "px-2 py-1 rounded text-xs font-mono border transition-all min-w-[90px] text-center select-none",
+ isCapturing
+ ? "bg-[#2563EB]/20 border-[#2563EB] text-[#2563EB] animate-pulse"
+ : hasConflict
+ ? "bg-amber-500/10 border-amber-500/50 text-amber-400"
+ : "bg-white/5 border-white/10 text-slate-200 hover:border-[#2563EB]/50 hover:text-[#2563EB] cursor-pointer",
+ ].join(" ")}
+ >
+ {isCapturing
+ ? t("shortcutsConfig.pressAKey")
+ : formatBinding(draft[action], isMac)}
+ </button>
+ </div>
+ {hasConflict && conflict?.conflictWith.type === "configurable" && (
+ <div className="flex items-center justify-between px-1 py-1.5 mb-0.5 bg-amber-500/10 border border-amber-500/20 rounded text-xs">
+ <span className="text-amber-400">
+ {t("shortcutsConfig.alreadyUsedBy", undefined, {
+ action: SHORTCUT_LABELS[
+ conflict.conflictWith.action
+ ],
+ })}
+ </span>
+ <div className="flex gap-1.5">
+ <button
+ type="button"
+ onClick={handleSwap}
+ className="px-2 py-0.5 bg-amber-500/20 hover:bg-amber-500/30 border border-amber-500/40 rounded text-amber-300 font-medium transition-colors"
+ >
+ {t("shortcutsConfig.swap")}
+ </button>
+ <button
+ type="button"
+ onClick={handleCancelConflict}
+ className="px-2 py-0.5 bg-white/5 hover:bg-white/10 border border-white/10 rounded text-slate-400 transition-colors"
+ >
+ {t("shortcutsConfig.cancel")}
+ </button>
+ </div>
+ </div>
+ )}
+ </div>
+ );
+ })}
+ </div>
+
+ <div className="space-y-0.5 mt-2">
+ <p className="text-[10px] text-slate-500 mb-2 uppercase tracking-wide font-semibold">
+ {t("shortcutsConfig.fixed")}
+ </p>
+ {FIXED_SHORTCUTS.map(({ label, display }) => (
+ <div
+ key={label}
+ className="flex items-center justify-between py-1.5 px-1 border-b border-white/5 last:border-0"
+ >
+ <span className="text-sm text-slate-400">{label}</span>
+ <kbd className="px-2 py-1 bg-white/5 border border-white/10 rounded text-xs font-mono text-slate-400 min-w-[90px] text-center">
+ {display}
+ </kbd>
+ </div>
+ ))}
+ </div>
+
+ <p className="text-[10px] text-slate-500 mt-1">
+ {t("shortcutsConfig.instructions")}
+ </p>
+
+ <DialogFooter className="flex gap-2 sm:justify-between mt-2">
+ <Button
+ title={t("shortcutsConfig.resetToDefaults")}
+ variant="ghost"
+ size="sm"
+ className="text-slate-400 hover:text-white hover:bg-white/10 gap-1.5 max-w-[200px]"
+ onClick={handleReset}
+ >
+ <RotateCcw className="w-3 h-3" />
+ <span className="truncate">{t("shortcutsConfig.resetToDefaults")}</span>
+ </Button>
+ <div className="flex gap-2">
+ <Button variant="ghost" size="sm" onClick={handleClose}>
+ {t("shortcutsConfig.cancel")}
+ </Button>
+ <Button
+ size="sm"
+ className="bg-[#2563EB] hover:bg-[#1d4ed8] text-white"
+ onClick={handleSave}
+ >
+ {t("shortcutsConfig.save")}
+ </Button>
+ </div>
+ </DialogFooter>
+ </DialogContent>
+ </Dialog>
+ );
}
-
diff --git a/src/components/video-editor/SliderControl.tsx b/src/components/video-editor/SliderControl.tsx
index 358658a8..6ad188ed 100644
--- a/src/components/video-editor/SliderControl.tsx
+++ b/src/components/video-editor/SliderControl.tsx
@@ -1,37 +1,37 @@
import { cn } from "@/lib/utils";
interface SliderControlProps {
- label: string;
- value: number;
- defaultValue: number;
- min: number;
- max: number;
- step: number;
- onChange: (value: number) => void;
- formatValue: (value: number) => string;
- parseInput: (text: string) => number | null;
- accentColor?: "purple" | "blue";
+ label: string;
+ value: number;
+ defaultValue: number;
+ min: number;
+ max: number;
+ step: number;
+ onChange: (value: number) => void;
+ formatValue: (value: number) => string;
+ parseInput: (text: string) => number | null;
+ accentColor?: "purple" | "blue";
}
export function SliderControl({
- label,
- value,
- defaultValue: _defaultValue,
- min,
- max,
- step,
- onChange,
- formatValue,
- parseInput: _parseInput,
- accentColor = "blue",
+ label,
+ value,
+ defaultValue: _defaultValue,
+ min,
+ max,
+ step,
+ onChange,
+ formatValue,
+ parseInput: _parseInput,
+ accentColor = "blue",
}: SliderControlProps) {
- const pct = Math.min(100, Math.max(0, ((value - min) / (max - min || 1)) * 100));
- const dividerClass =
- accentColor === "purple"
- ? "bg-white/95 shadow-[0_0_10px_rgba(139,92,246,0.28)]"
- : "bg-white/95 shadow-[0_0_10px_rgba(37,99,235,0.28)]";
+ const pct = Math.min(100, Math.max(0, ((value - min) / (max - min || 1)) * 100));
+ const dividerClass =
+ accentColor === "purple"
+ ? "bg-white/95 shadow-[0_0_10px_rgba(139,92,246,0.28)]"
+ : "bg-white/95 shadow-[0_0_10px_rgba(37,99,235,0.28)]";
- return (
+ return (
<div className="relative flex h-10 w-full select-none items-center overflow-hidden rounded-xl bg-black/60 px-1.5">
<div
className="absolute inset-y-[3px] left-[3px] right-auto rounded-[10px] bg-white/[0.08] shadow-[0_4px_10px_0_rgba(0,0,0,0.18)] transition-none"
@@ -39,28 +39,28 @@ export function SliderControl({
width: pct > 0 ? `max(calc(${pct}% - 6px), 2.1rem)` : 0,
}}
/>
- <div
- className={cn(
- "pointer-events-none absolute bottom-[18%] top-[18%] z-10 w-[2px] rounded-full transition-none",
- dividerClass,
- )}
- style={{ left: `calc(${pct}% - 8px)` }}
- />
- <span className="pointer-events-none relative z-10 flex-1 pl-3 text-[12px] font-medium text-slate-300">
- {label}
- </span>
- <span className="pointer-events-none relative z-10 pr-3 text-[12px] font-medium tabular-nums text-slate-100">
- {formatValue(value)}
- </span>
- <input
- type="range"
- min={min}
- max={max}
- step={step}
- value={value}
- onChange={(e) => onChange(Number(e.target.value))}
- className="absolute inset-0 h-full w-full cursor-ew-resize opacity-0"
- />
- </div>
- );
+ <div
+ className={cn(
+ "pointer-events-none absolute bottom-[18%] top-[18%] z-10 w-[2px] rounded-full transition-none",
+ dividerClass,
+ )}
+ style={{ left: `calc(${pct}% - 8px)` }}
+ />
+ <span className="pointer-events-none relative z-10 flex-1 pl-3 text-[12px] font-medium text-slate-300">
+ {label}
+ </span>
+ <span className="pointer-events-none relative z-10 pr-3 text-[12px] font-medium tabular-nums text-slate-100">
+ {formatValue(value)}
+ </span>
+ <input
+ type="range"
+ min={min}
+ max={max}
+ step={step}
+ value={value}
+ onChange={(e) => onChange(Number(e.target.value))}
+ className="absolute inset-0 h-full w-full cursor-ew-resize opacity-0"
+ />
+ </div>
+ );
}
diff --git a/src/components/video-editor/TutorialHelp.tsx b/src/components/video-editor/TutorialHelp.tsx
index fbfa6461..186351f5 100644
--- a/src/components/video-editor/TutorialHelp.tsx
+++ b/src/components/video-editor/TutorialHelp.tsx
@@ -1,5 +1,15 @@
-import { ArrowRight, ExternalLink, HelpCircle, Keyboard, MessageSquareMore, Scissors, Settings2, Twitter } from "lucide-react";
+import {
+ ArrowRight,
+ ArrowSquareOut as ExternalLink,
+ ChatCircleDots as MessageSquareMore,
+ Gear as Settings2,
+ Keyboard,
+ Question as HelpCircle,
+ Scissors,
+ TwitterLogo as Twitter,
+} from "@phosphor-icons/react";
import { useEffect, useState } from "react";
+import { toast } from "sonner";
import { Button } from "@/components/ui/button";
import {
Dialog,
@@ -13,14 +23,21 @@ import { useScopedT } from "@/contexts/I18nContext";
import { useShortcuts } from "@/contexts/ShortcutsContext";
import { formatBinding, SHORTCUT_ACTIONS, SHORTCUT_LABELS } from "@/lib/shortcuts";
import { formatShortcut } from "@/utils/platformUtils";
-import { toast } from "sonner";
export const RECORDLY_ISSUES_URL = "https://github.com/webadderall/Recordly/issues";
const RECORDLY_DISCORD_URL = "https://discord.gg/FcfNN4S9m";
const RECORDLY_X_URL = "https://x.com/webadderall";
const CONTACT_EMAIL = "[email protected]";
-export const APP_HEADER_ACTION_BUTTON_CLASS = "h-7 px-2 text-xs text-slate-400 hover:bg-white/10 hover:text-slate-200 transition-all gap-1.5";
-export const APP_HEADER_ICON_BUTTON_CLASS = "h-7 w-7 p-0 text-slate-400 hover:bg-white/10 hover:text-slate-200 transition-all";
+export const APP_HEADER_ACTION_BUTTON_CLASS =
+ "h-7 px-2 text-xs text-slate-400 hover:bg-white/10 hover:text-slate-200 transition-all gap-1.5";
+export const APP_HEADER_ICON_BUTTON_CLASS =
+ "h-7 w-7 p-0 text-slate-400 hover:bg-white/10 hover:text-slate-200 transition-all";
+
+type KeyboardShortcutsDialogProps = {
+ triggerLabel?: string;
+ triggerClassName?: string;
+ iconOnly?: boolean;
+};
function DiscordIcon(props: React.SVGProps<SVGSVGElement>) {
return (
@@ -49,7 +66,12 @@ export function DiscordLinkButton() {
type="button"
variant="ghost"
size="sm"
- onClick={() => void openExternalLink(RECORDLY_DISCORD_URL, t("feedback.openFailed", "Failed to open link."))}
+ onClick={() =>
+ void openExternalLink(
+ RECORDLY_DISCORD_URL,
+ t("feedback.openFailed", "Failed to open link."),
+ )
+ }
className={APP_HEADER_ICON_BUTTON_CLASS}
title={t("common.app.discord", "Join Discord")}
aria-label={t("common.app.discord", "Join Discord")}
@@ -78,10 +100,14 @@ export function FeedbackDialog() {
<DialogContent className="max-w-lg bg-[#09090b] border-white/10 [&>button]:text-slate-400 [&>button:hover]:text-white">
<DialogHeader>
<DialogTitle className="text-xl font-semibold text-slate-200 flex items-center gap-2">
- <MessageSquareMore className="h-5 w-5 text-[#2563EB]" /> {t("feedback.title", "Feedback & contact")}
+ <MessageSquareMore className="h-5 w-5 text-[#2563EB]" />{" "}
+ {t("feedback.title", "Feedback & contact")}
</DialogTitle>
<DialogDescription className="text-slate-400">
- {t("feedback.description", "Reach out directly or open an issue if something is broken or missing.")}
+ {t(
+ "feedback.description",
+ "Reach out directly or open an issue if something is broken or missing.",
+ )}
</DialogDescription>
</DialogHeader>
<div className="mt-4 space-y-4">
@@ -91,12 +117,19 @@ export function FeedbackDialog() {
<p className="text-[11px] uppercase tracking-[0.18em] text-slate-500">
{t("feedback.emailLabel", "Email")}
</p>
- <p className="mt-1 text-sm font-medium text-slate-100">{CONTACT_EMAIL}</p>
+ <p className="mt-1 text-sm font-medium text-slate-100">
+ {CONTACT_EMAIL}
+ </p>
</div>
<Button
type="button"
variant="outline"
- onClick={() => void openExternalLink(`mailto:${CONTACT_EMAIL}`, t("feedback.openFailed", "Failed to open link."))}
+ onClick={() =>
+ void openExternalLink(
+ `mailto:${CONTACT_EMAIL}`,
+ t("feedback.openFailed", "Failed to open link."),
+ )
+ }
className="border-white/10 bg-white/5 text-slate-200 hover:bg-white/10 hover:text-white"
>
<ExternalLink className="h-3.5 w-3.5" />
@@ -107,12 +140,19 @@ export function FeedbackDialog() {
<p className="text-[11px] uppercase tracking-[0.18em] text-slate-500">
{t("feedback.xLabel", "X")}
</p>
- <p className="mt-1 text-sm font-medium text-slate-100">@webadderall</p>
+ <p className="mt-1 text-sm font-medium text-slate-100">
+ @webadderall
+ </p>
</div>
<Button
type="button"
variant="outline"
- onClick={() => void openExternalLink(RECORDLY_X_URL, t("feedback.openFailed", "Failed to open link."))}
+ onClick={() =>
+ void openExternalLink(
+ RECORDLY_X_URL,
+ t("feedback.openFailed", "Failed to open link."),
+ )
+ }
className="border-white/10 bg-white/5 text-slate-200 hover:bg-white/10 hover:text-white"
>
<Twitter className="h-3.5 w-3.5" />
@@ -122,7 +162,12 @@ export function FeedbackDialog() {
<Button
type="button"
variant="outline"
- onClick={() => void openExternalLink(RECORDLY_ISSUES_URL, t("feedback.openFailed", "Failed to open link."))}
+ onClick={() =>
+ void openExternalLink(
+ RECORDLY_ISSUES_URL,
+ t("feedback.openFailed", "Failed to open link."),
+ )
+ }
className="h-10 w-full justify-between border-white/10 bg-white/5 px-4 text-slate-200 hover:bg-white/10 hover:text-white"
>
<span className="flex items-center gap-2 text-sm font-medium">
@@ -137,7 +182,11 @@ export function FeedbackDialog() {
);
}
-export function KeyboardShortcutsDialog() {
+export function KeyboardShortcutsDialog({
+ triggerLabel,
+ triggerClassName,
+ iconOnly = false,
+}: KeyboardShortcutsDialogProps = {}) {
const { shortcuts, isMac, openConfig } = useShortcuts();
const t = useScopedT("editor");
const [scrollLabels, setScrollLabels] = useState({
@@ -158,26 +207,36 @@ export function KeyboardShortcutsDialog() {
<Button
variant="ghost"
size="sm"
- className={APP_HEADER_ICON_BUTTON_CLASS}
+ className={triggerClassName ?? APP_HEADER_ICON_BUTTON_CLASS}
title={t("keyboardShortcuts.trigger", "Shortcuts")}
aria-label={t("keyboardShortcuts.trigger", "Shortcuts")}
>
<Keyboard className="h-3.5 w-3.5" />
+ {!iconOnly && triggerLabel ? (
+ <span className="text-sm font-medium">{triggerLabel}</span>
+ ) : null}
</Button>
</DialogTrigger>
<DialogContent className="max-w-lg bg-[#09090b] border-white/10 [&>button]:text-slate-400 [&>button:hover]:text-white">
<DialogHeader>
<DialogTitle className="text-xl font-semibold text-slate-200 flex items-center gap-2">
- <Keyboard className="h-5 w-5 text-[#2563EB]" /> {t("keyboardShortcuts.title")}
+ <Keyboard className="h-5 w-5 text-[#2563EB]" />{" "}
+ {t("keyboardShortcuts.title")}
</DialogTitle>
<DialogDescription className="text-slate-400">
- {t("keyboardShortcuts.description", "Quick reference for the timeline and editor controls.")}
+ {t(
+ "keyboardShortcuts.description",
+ "Quick reference for the timeline and editor controls.",
+ )}
</DialogDescription>
</DialogHeader>
<div className="mt-4 space-y-4">
<div className="rounded-xl border border-white/10 bg-white/[0.03] p-4 space-y-2 text-xs">
{SHORTCUT_ACTIONS.map((action) => (
- <div key={action} className="flex items-center justify-between gap-3 rounded-lg border border-white/5 bg-white/5 px-3 py-2.5">
+ <div
+ key={action}
+ className="flex items-center justify-between gap-3 rounded-lg border border-white/5 bg-white/5 px-3 py-2.5"
+ >
<span className="text-slate-300">{SHORTCUT_LABELS[action]}</span>
<kbd className="rounded border border-white/10 bg-black/20 px-2 py-1 font-mono text-[#2563EB]">
{formatBinding(shortcuts[action], isMac)}
@@ -186,19 +245,25 @@ export function KeyboardShortcutsDialog() {
))}
<div className="grid grid-cols-1 gap-2 pt-2 sm:grid-cols-3">
<div className="rounded-lg border border-white/5 bg-white/5 px-3 py-2.5">
- <p className="text-[11px] uppercase tracking-[0.18em] text-slate-500">{t("keyboardShortcuts.panTimeline")}</p>
+ <p className="text-[11px] uppercase tracking-[0.18em] text-slate-500">
+ {t("keyboardShortcuts.panTimeline")}
+ </p>
<kbd className="mt-2 inline-flex rounded border border-white/10 bg-black/20 px-2 py-1 font-mono text-[#2563EB]">
{scrollLabels.pan}
</kbd>
</div>
<div className="rounded-lg border border-white/5 bg-white/5 px-3 py-2.5">
- <p className="text-[11px] uppercase tracking-[0.18em] text-slate-500">{t("keyboardShortcuts.zoomTimeline")}</p>
+ <p className="text-[11px] uppercase tracking-[0.18em] text-slate-500">
+ {t("keyboardShortcuts.zoomTimeline")}
+ </p>
<kbd className="mt-2 inline-flex rounded border border-white/10 bg-black/20 px-2 py-1 font-mono text-[#2563EB]">
{scrollLabels.zoom}
</kbd>
</div>
<div className="rounded-lg border border-white/5 bg-white/5 px-3 py-2.5">
- <p className="text-[11px] uppercase tracking-[0.18em] text-slate-500">{t("keyboardShortcuts.cycleAnnotations")}</p>
+ <p className="text-[11px] uppercase tracking-[0.18em] text-slate-500">
+ {t("keyboardShortcuts.cycleAnnotations")}
+ </p>
<kbd className="mt-2 inline-flex rounded border border-white/10 bg-black/20 px-2 py-1 font-mono text-[#2563EB]">
{t("keyboardShortcuts.tab")}
</kbd>
@@ -228,11 +293,7 @@ export function TutorialHelp() {
return (
<Dialog>
<DialogTrigger asChild>
- <Button
- variant="ghost"
- size="sm"
- className={APP_HEADER_ACTION_BUTTON_CLASS}
- >
+ <Button variant="ghost" size="sm" className={APP_HEADER_ACTION_BUTTON_CLASS}>
<HelpCircle className="w-3.5 h-3.5" />
<span className="font-medium">{t("tutorial.howTrimmingWorks")}</span>
</Button>
@@ -251,8 +312,11 @@ export function TutorialHelp() {
<div className="bg-white/5 rounded-lg p-4 border border-white/5">
<p className="text-slate-300 leading-relaxed">
{t("tutorial.descriptionP1")}
- <span className="text-[#ef4444] font-bold"> {t("tutorial.descriptionRemove")}</span>.{" "}
- {t("tutorial.descriptionP3")}
+ <span className="text-[#ef4444] font-bold">
+ {" "}
+ {t("tutorial.descriptionRemove")}
+ </span>
+ . {t("tutorial.descriptionP3")}
</p>
</div>
{/* Visual Illustration */}
@@ -331,11 +395,15 @@ export function TutorialHelp() {
{/* Steps */}
<div className="grid grid-cols-2 gap-4">
<div className="p-3 rounded bg-white/5 border border-white/5">
- <div className="text-[#ef4444] font-bold mb-1">{t("tutorial.addTrimStep")}</div>
+ <div className="text-[#ef4444] font-bold mb-1">
+ {t("tutorial.addTrimStep")}
+ </div>
<p className="text-xs text-slate-400">{t("tutorial.addTrimDesc")}</p>
</div>
<div className="p-3 rounded bg-white/5 border border-white/5">
- <div className="text-[#ef4444] font-bold mb-1">{t("tutorial.adjustStep")}</div>
+ <div className="text-[#ef4444] font-bold mb-1">
+ {t("tutorial.adjustStep")}
+ </div>
<p className="text-xs text-slate-400">{t("tutorial.adjustDesc")}</p>
</div>
</div>
diff --git a/src/components/video-editor/VideoPlayback.tsx b/src/components/video-editor/VideoPlayback.tsx
index a4a4517c..e6021d90 100644
--- a/src/components/video-editor/VideoPlayback.tsx
+++ b/src/components/video-editor/VideoPlayback.tsx
@@ -1,2425 +1,2451 @@
+import {
+ Application,
+ BlurFilter,
+ Container,
+ Graphics,
+ Sprite,
+ Texture,
+ VideoSource,
+} from "pixi.js";
+import { MotionBlurFilter } from "pixi-filters/motion-blur";
import type React from "react";
import {
- useEffect,
- useRef,
- useImperativeHandle,
- forwardRef,
- useState,
- useMemo,
- useCallback,
+ forwardRef,
+ useCallback,
+ useEffect,
+ useImperativeHandle,
+ useMemo,
+ useRef,
+ useState,
} from "react";
import { getAssetPath, getRenderableAssetUrl } from "@/lib/assetPath";
import { clampMediaTimeToDuration } from "@/lib/mediaTiming";
import {
- DEFAULT_WALLPAPER_PATH,
- DEFAULT_WALLPAPER_RELATIVE_PATH,
- isVideoWallpaperSource,
+ DEFAULT_WALLPAPER_PATH,
+ DEFAULT_WALLPAPER_RELATIVE_PATH,
+ isVideoWallpaperSource,
} from "@/lib/wallpapers";
+import { buildActiveCaptionLayout } from "./captionLayout";
import {
- Application,
- Container,
- Sprite,
- Graphics,
- BlurFilter,
- Texture,
- VideoSource,
-} from "pixi.js";
-import { MotionBlurFilter } from "pixi-filters/motion-blur";
+ CAPTION_FONT_WEIGHT,
+ CAPTION_LINE_HEIGHT,
+ getCaptionPadding,
+ getCaptionScaledFontSize,
+ getCaptionScaledRadius,
+ getCaptionTextMaxWidth,
+ getCaptionWordVisualState,
+} from "./captionStyle";
import {
- type AutoCaptionSettings,
- type CaptionCue,
- ZOOM_DEPTH_SCALES,
- type ZoomRegion,
- type ZoomFocus,
- type ZoomDepth,
- type TrimRegion,
- type SpeedRegion,
- type AnnotationRegion,
- type CursorTelemetryPoint,
- type CursorStyle,
- type WebcamOverlaySettings,
- type ZoomTransitionEasing,
+ type AnnotationRegion,
+ type AutoCaptionSettings,
+ type CaptionCue,
+ type CursorStyle,
+ type CursorTelemetryPoint,
+ type SpeedRegion,
+ type TrimRegion,
+ type WebcamOverlaySettings,
+ ZOOM_DEPTH_SCALES,
+ type ZoomDepth,
+ type ZoomFocus,
+ type ZoomRegion,
+ type ZoomTransitionEasing,
} from "./types";
+import { DEFAULT_FOCUS } from "./videoPlayback/constants";
import {
- DEFAULT_FOCUS,
-} from "./videoPlayback/constants";
-import {
- type SpringState,
- createSpringState,
- resetSpringState,
- stepSpringValue,
- getZoomSpringConfig,
-} from "./videoPlayback/motionSmoothing";
-import {
- DEFAULT_CURSOR_CONFIG,
- PixiCursorOverlay,
- preloadCursorAssets,
+ DEFAULT_CURSOR_CONFIG,
+ PixiCursorOverlay,
+ preloadCursorAssets,
} from "./videoPlayback/cursorRenderer";
-import {
- buildActiveCaptionLayout,
-} from "./captionLayout";
-import {
- CAPTION_FONT_WEIGHT,
- CAPTION_LINE_HEIGHT,
- getCaptionPadding,
- getCaptionScaledRadius,
- getCaptionScaledFontSize,
- getCaptionTextMaxWidth,
- getCaptionWordVisualState,
-} from "./captionStyle";
import { clamp01 } from "./videoPlayback/mathUtils";
+import {
+ createSpringState,
+ getZoomSpringConfig,
+ resetSpringState,
+ type SpringState,
+ stepSpringValue,
+} from "./videoPlayback/motionSmoothing";
function getContributedCursorStylesSignature() {
- return extensionHost
- .getContributedCursorStyles()
- .map(
- (cursorStyle) =>
- `${cursorStyle.id}:${cursorStyle.resolvedDefaultUrl}:${cursorStyle.resolvedClickUrl ?? ""}:${cursorStyle.cursorStyle.hotspot?.x ?? ""}:${cursorStyle.cursorStyle.hotspot?.y ?? ""}`,
- )
- .sort()
- .join("|");
+ return extensionHost
+ .getContributedCursorStyles()
+ .map(
+ (cursorStyle) =>
+ `${cursorStyle.id}:${cursorStyle.resolvedDefaultUrl}:${cursorStyle.resolvedClickUrl ?? ""}:${cursorStyle.cursorStyle.hotspot?.x ?? ""}:${cursorStyle.cursorStyle.hotspot?.y ?? ""}`,
+ )
+ .sort()
+ .join("|");
}
-import { findDominantRegion } from "./videoPlayback/zoomRegionUtils";
-import {
- type CursorFollowCameraState,
- createCursorFollowCameraState,
- resetCursorFollowCamera,
- computeCursorFollowFocus,
- SNAP_TO_EDGES_RATIO_AUTO,
-} from "./videoPlayback/cursorFollowCamera";
-import { clampFocusToStage as clampFocusToStageUtil } from "./videoPlayback/focusUtils";
-import { updateOverlayIndicator } from "./videoPlayback/overlayUtils";
-import { layoutVideoContent as layoutVideoContentUtil } from "./videoPlayback/layoutUtils";
-import {
- applyZoomTransform,
- computeFocusFromTransform,
- computeZoomTransform,
- createMotionBlurState,
- type MotionBlurState,
-} from "./videoPlayback/zoomTransform";
-import { createVideoEventHandlers } from "./videoPlayback/videoEventHandlers";
-import {
- type AspectRatio,
- formatAspectRatioForCSS,
-} from "@/utils/aspectRatioUtils";
-import { AnnotationOverlay } from "./AnnotationOverlay";
+
import { extensionHost } from "@/lib/extensions";
import {
- mapCursorToCanvasNormalized,
- mapSmoothedCursorToCanvasNormalized,
+ mapCursorToCanvasNormalized,
+ mapSmoothedCursorToCanvasNormalized,
} from "@/lib/extensions/cursorCoordinates";
-import { applyCanvasSceneTransform } from "@/lib/extensions/sceneTransform";
import {
- notifyCursorInteraction,
- executeExtensionCursorEffects,
- executeExtensionRenderHooks,
- clearCursorEffects,
+ clearCursorEffects,
+ executeExtensionCursorEffects,
+ executeExtensionRenderHooks,
+ notifyCursorInteraction,
} from "@/lib/extensions/renderHooks";
+import { applyCanvasSceneTransform } from "@/lib/extensions/sceneTransform";
+import { getSquircleSvgPath } from "@/lib/geometry/squircle";
+import { type AspectRatio, formatAspectRatioForCSS } from "@/utils/aspectRatioUtils";
+import { AnnotationOverlay } from "./AnnotationOverlay";
import {
- DEFAULT_CURSOR_CLICK_BOUNCE,
- DEFAULT_CURSOR_CLICK_BOUNCE_DURATION,
- DEFAULT_CURSOR_MOTION_BLUR,
- DEFAULT_CURSOR_SIZE,
- DEFAULT_CURSOR_SMOOTHING,
- DEFAULT_CURSOR_SWAY,
- DEFAULT_CONNECTED_ZOOM_DURATION_MS,
- DEFAULT_CONNECTED_ZOOM_EASING,
- DEFAULT_CONNECTED_ZOOM_GAP_MS,
- DEFAULT_WEBCAM_CORNER_RADIUS,
- DEFAULT_WEBCAM_REACT_TO_ZOOM,
- DEFAULT_WEBCAM_SHADOW,
- DEFAULT_WEBCAM_SIZE,
- DEFAULT_ZOOM_IN_DURATION_MS,
- DEFAULT_ZOOM_IN_EASING,
- DEFAULT_ZOOM_IN_OVERLAP_MS,
- DEFAULT_ZOOM_OUT_DURATION_MS,
- DEFAULT_ZOOM_OUT_EASING,
- getDefaultCaptionFontFamily,
+ DEFAULT_CONNECTED_ZOOM_DURATION_MS,
+ DEFAULT_CONNECTED_ZOOM_EASING,
+ DEFAULT_CONNECTED_ZOOM_GAP_MS,
+ DEFAULT_CURSOR_CLICK_BOUNCE,
+ DEFAULT_CURSOR_CLICK_BOUNCE_DURATION,
+ DEFAULT_CURSOR_MOTION_BLUR,
+ DEFAULT_CURSOR_SIZE,
+ DEFAULT_CURSOR_SMOOTHING,
+ DEFAULT_CURSOR_SWAY,
+ DEFAULT_WEBCAM_CORNER_RADIUS,
+ DEFAULT_WEBCAM_REACT_TO_ZOOM,
+ DEFAULT_WEBCAM_SHADOW,
+ DEFAULT_WEBCAM_SIZE,
+ DEFAULT_ZOOM_IN_DURATION_MS,
+ DEFAULT_ZOOM_IN_EASING,
+ DEFAULT_ZOOM_IN_OVERLAP_MS,
+ DEFAULT_ZOOM_OUT_DURATION_MS,
+ DEFAULT_ZOOM_OUT_EASING,
+ getDefaultCaptionFontFamily,
} from "./types";
+import {
+ type CursorFollowCameraState,
+ computeCursorFollowFocus,
+ createCursorFollowCameraState,
+ resetCursorFollowCamera,
+ SNAP_TO_EDGES_RATIO_AUTO,
+} from "./videoPlayback/cursorFollowCamera";
+import { clampFocusToStage as clampFocusToStageUtil } from "./videoPlayback/focusUtils";
+import { layoutVideoContent as layoutVideoContentUtil } from "./videoPlayback/layoutUtils";
+import { updateOverlayIndicator } from "./videoPlayback/overlayUtils";
+import { createVideoEventHandlers } from "./videoPlayback/videoEventHandlers";
+import { findDominantRegion } from "./videoPlayback/zoomRegionUtils";
+import {
+ applyZoomTransform,
+ computeFocusFromTransform,
+ computeZoomTransform,
+ createMotionBlurState,
+ type MotionBlurState,
+} from "./videoPlayback/zoomTransform";
import { getWebcamOverlayPosition, getWebcamOverlaySizePx } from "./webcamOverlay";
-import { getSquircleSvgPath } from "@/lib/geometry/squircle";
type PlaybackAnimationState = {
- scale: number;
- appliedScale: number;
- focusX: number;
- focusY: number;
- progress: number;
- x: number;
- y: number;
+ scale: number;
+ appliedScale: number;
+ focusX: number;
+ focusY: number;
+ progress: number;
+ x: number;
+ y: number;
};
function createPlaybackAnimationState(): PlaybackAnimationState {
- return {
- scale: 1,
- appliedScale: 1,
- focusX: DEFAULT_FOCUS.cx,
- focusY: DEFAULT_FOCUS.cy,
- progress: 0,
- x: 0,
- y: 0,
- };
+ return {
+ scale: 1,
+ appliedScale: 1,
+ focusX: DEFAULT_FOCUS.cx,
+ focusY: DEFAULT_FOCUS.cy,
+ progress: 0,
+ x: 0,
+ y: 0,
+ };
}
function getCursorPositionAtTime(
- telemetry: CursorTelemetryPoint[],
- timeMs: number,
- params?: {
- maskRect?: { x: number; y: number; width: number; height: number } | null;
- canvasWidth: number;
- canvasHeight: number;
- },
+ telemetry: CursorTelemetryPoint[],
+ timeMs: number,
+ params?: {
+ maskRect?: { x: number; y: number; width: number; height: number } | null;
+ canvasWidth: number;
+ canvasHeight: number;
+ },
): { cx: number; cy: number; interactionType?: string } | null {
- if (telemetry.length === 0) {
- return null;
- }
-
- let closest = telemetry[0];
- let minDist = Math.abs(telemetry[0].timeMs - timeMs);
-
- for (let index = 1; index < telemetry.length; index++) {
- const point = telemetry[index];
- const distance = Math.abs(point.timeMs - timeMs);
- if (distance < minDist) {
- minDist = distance;
- closest = point;
- }
- if (point.timeMs > timeMs) {
- break;
- }
- }
-
- return mapCursorToCanvasNormalized({
- cx: closest.cx,
- cy: closest.cy,
- interactionType: closest.interactionType,
- }, params ?? { canvasWidth: 1, canvasHeight: 1 });
+ if (telemetry.length === 0) {
+ return null;
+ }
+
+ let closest = telemetry[0];
+ let minDist = Math.abs(telemetry[0].timeMs - timeMs);
+
+ for (let index = 1; index < telemetry.length; index++) {
+ const point = telemetry[index];
+ const distance = Math.abs(point.timeMs - timeMs);
+ if (distance < minDist) {
+ minDist = distance;
+ closest = point;
+ }
+ if (point.timeMs > timeMs) {
+ break;
+ }
+ }
+
+ return mapCursorToCanvasNormalized(
+ {
+ cx: closest.cx,
+ cy: closest.cy,
+ interactionType: closest.interactionType,
+ },
+ params ?? { canvasWidth: 1, canvasHeight: 1 },
+ );
}
function getEffectiveNativeAspectRatio(
- dimensions: { width: number; height: number } | null | undefined,
- cropRegion?: import("./types").CropRegion,
+ dimensions: { width: number; height: number } | null | undefined,
+ cropRegion?: import("./types").CropRegion,
): number {
- if (!dimensions || dimensions.height <= 0 || dimensions.width <= 0) {
- return 16 / 9;
- }
+ if (!dimensions || dimensions.height <= 0 || dimensions.width <= 0) {
+ return 16 / 9;
+ }
- const cropWidth = cropRegion?.width ?? 1;
- const cropHeight = cropRegion?.height ?? 1;
- const effectiveWidth = dimensions.width * cropWidth;
- const effectiveHeight = dimensions.height * cropHeight;
+ const cropWidth = cropRegion?.width ?? 1;
+ const cropHeight = cropRegion?.height ?? 1;
+ const effectiveWidth = dimensions.width * cropWidth;
+ const effectiveHeight = dimensions.height * cropHeight;
- if (effectiveWidth <= 0 || effectiveHeight <= 0) {
- return dimensions.width / dimensions.height;
- }
+ if (effectiveWidth <= 0 || effectiveHeight <= 0) {
+ return dimensions.width / dimensions.height;
+ }
- return effectiveWidth / effectiveHeight;
+ return effectiveWidth / effectiveHeight;
}
interface VideoPlaybackProps {
- videoPath: string;
- onDurationChange: (duration: number) => void;
- onPreviewReadyChange?: (ready: boolean) => void;
- onTimeUpdate: (time: number) => void;
- currentTime: number;
- onPlayStateChange: (playing: boolean) => void;
- onError: (error: string) => void;
- wallpaper?: string;
- zoomRegions: ZoomRegion[];
- selectedZoomId: string | null;
- onSelectZoom: (id: string | null) => void;
- onZoomFocusChange: (id: string, focus: ZoomFocus) => void;
- isPlaying: boolean;
- showShadow?: boolean;
- shadowIntensity?: number;
- backgroundBlur?: number;
- zoomMotionBlur?: number;
- connectZooms?: boolean;
- zoomInDurationMs?: number;
- zoomInOverlapMs?: number;
- zoomOutDurationMs?: number;
- connectedZoomGapMs?: number;
- connectedZoomDurationMs?: number;
- zoomInEasing?: ZoomTransitionEasing;
- zoomOutEasing?: ZoomTransitionEasing;
- connectedZoomEasing?: ZoomTransitionEasing;
- borderRadius?: number;
- padding?: number;
- frame?: string | null;
- cropRegion?: import("./types").CropRegion;
- webcam?: WebcamOverlaySettings;
- webcamVideoPath?: string | null;
- trimRegions?: TrimRegion[];
- speedRegions?: SpeedRegion[];
- aspectRatio: AspectRatio;
- annotationRegions?: AnnotationRegion[];
- autoCaptions?: CaptionCue[];
- autoCaptionSettings?: AutoCaptionSettings;
- selectedAnnotationId?: string | null;
- onSelectAnnotation?: (id: string | null) => void;
- onAnnotationPositionChange?: (
- id: string,
- position: { x: number; y: number },
- ) => void;
- onAnnotationSizeChange?: (
- id: string,
- size: { width: number; height: number },
- ) => void;
- cursorTelemetry?: CursorTelemetryPoint[];
- showCursor?: boolean;
- cursorStyle?: CursorStyle;
- cursorSize?: number;
- cursorSmoothing?: number;
- zoomSmoothness?: number;
- zoomClassicMode?: boolean;
- cursorMotionBlur?: number;
- cursorClickBounce?: number;
- cursorClickBounceDuration?: number;
- cursorSway?: number;
- volume?: number;
+ videoPath: string;
+ onDurationChange: (duration: number) => void;
+ onPreviewReadyChange?: (ready: boolean) => void;
+ onTimeUpdate: (time: number) => void;
+ currentTime: number;
+ onPlayStateChange: (playing: boolean) => void;
+ onError: (error: string) => void;
+ wallpaper?: string;
+ zoomRegions: ZoomRegion[];
+ selectedZoomId: string | null;
+ onSelectZoom: (id: string | null) => void;
+ onZoomFocusChange: (id: string, focus: ZoomFocus) => void;
+ isPlaying: boolean;
+ showShadow?: boolean;
+ shadowIntensity?: number;
+ backgroundBlur?: number;
+ zoomMotionBlur?: number;
+ connectZooms?: boolean;
+ zoomInDurationMs?: number;
+ zoomInOverlapMs?: number;
+ zoomOutDurationMs?: number;
+ connectedZoomGapMs?: number;
+ connectedZoomDurationMs?: number;
+ zoomInEasing?: ZoomTransitionEasing;
+ zoomOutEasing?: ZoomTransitionEasing;
+ connectedZoomEasing?: ZoomTransitionEasing;
+ borderRadius?: number;
+ padding?: number;
+ frame?: string | null;
+ cropRegion?: import("./types").CropRegion;
+ webcam?: WebcamOverlaySettings;
+ webcamVideoPath?: string | null;
+ trimRegions?: TrimRegion[];
+ speedRegions?: SpeedRegion[];
+ aspectRatio: AspectRatio;
+ annotationRegions?: AnnotationRegion[];
+ autoCaptions?: CaptionCue[];
+ autoCaptionSettings?: AutoCaptionSettings;
+ selectedAnnotationId?: string | null;
+ onSelectAnnotation?: (id: string | null) => void;
+ onAnnotationPositionChange?: (id: string, position: { x: number; y: number }) => void;
+ onAnnotationSizeChange?: (id: string, size: { width: number; height: number }) => void;
+ cursorTelemetry?: CursorTelemetryPoint[];
+ showCursor?: boolean;
+ cursorStyle?: CursorStyle;
+ cursorSize?: number;
+ cursorSmoothing?: number;
+ zoomSmoothness?: number;
+ zoomClassicMode?: boolean;
+ cursorMotionBlur?: number;
+ cursorClickBounce?: number;
+ cursorClickBounceDuration?: number;
+ cursorSway?: number;
+ volume?: number;
}
export interface VideoPlaybackRef {
- video: HTMLVideoElement | null;
- app: Application | null;
- videoSprite: Sprite | null;
- videoContainer: Container | null;
- containerRef: React.RefObject<HTMLDivElement>;
- play: () => Promise<void>;
- pause: () => void;
- refreshFrame: () => Promise<void>;
+ video: HTMLVideoElement | null;
+ app: Application | null;
+ videoSprite: Sprite | null;
+ videoContainer: Container | null;
+ containerRef: React.RefObject<HTMLDivElement>;
+ play: () => Promise<void>;
+ pause: () => void;
+ refreshFrame: () => Promise<void>;
}
const VideoPlayback = forwardRef<VideoPlaybackRef, VideoPlaybackProps>(
- (
- {
- videoPath,
- onDurationChange,
- onPreviewReadyChange,
- onTimeUpdate,
- currentTime,
- onPlayStateChange,
- onError,
- wallpaper,
- zoomRegions,
- selectedZoomId,
- onSelectZoom,
- onZoomFocusChange,
- isPlaying,
- showShadow,
- shadowIntensity = 0,
- backgroundBlur = 0,
- zoomMotionBlur = 0,
- connectZooms = true,
- zoomInDurationMs = DEFAULT_ZOOM_IN_DURATION_MS,
- zoomInOverlapMs = DEFAULT_ZOOM_IN_OVERLAP_MS,
- zoomOutDurationMs = DEFAULT_ZOOM_OUT_DURATION_MS,
- connectedZoomGapMs = DEFAULT_CONNECTED_ZOOM_GAP_MS,
- connectedZoomDurationMs = DEFAULT_CONNECTED_ZOOM_DURATION_MS,
- zoomInEasing = DEFAULT_ZOOM_IN_EASING,
- zoomOutEasing = DEFAULT_ZOOM_OUT_EASING,
- connectedZoomEasing = DEFAULT_CONNECTED_ZOOM_EASING,
- borderRadius = 0,
- padding = 50,
- frame = null,
- cropRegion,
- webcam,
- webcamVideoPath,
- trimRegions = [],
- speedRegions = [],
- aspectRatio,
- annotationRegions = [],
- autoCaptions = [],
- autoCaptionSettings,
- selectedAnnotationId,
- onSelectAnnotation,
- onAnnotationPositionChange,
- onAnnotationSizeChange,
- cursorTelemetry = [],
- showCursor = false,
- cursorStyle = "tahoe",
- cursorSize = DEFAULT_CURSOR_SIZE,
- cursorSmoothing = DEFAULT_CURSOR_SMOOTHING,
- zoomSmoothness = 0.5,
- zoomClassicMode = false,
- cursorMotionBlur = DEFAULT_CURSOR_MOTION_BLUR,
- cursorClickBounce = DEFAULT_CURSOR_CLICK_BOUNCE,
- cursorClickBounceDuration = DEFAULT_CURSOR_CLICK_BOUNCE_DURATION,
- cursorSway = DEFAULT_CURSOR_SWAY,
- volume = 1,
- },
- ref,
- ) => {
- const videoRef = useRef<HTMLVideoElement | null>(null);
- const containerRef = useRef<HTMLDivElement | null>(null);
- const appRef = useRef<Application | null>(null);
- const videoSpriteRef = useRef<Sprite | null>(null);
- const videoContainerRef = useRef<Container | null>(null);
- const cursorContainerRef = useRef<Container | null>(null);
- const cameraContainerRef = useRef<Container | null>(null);
- const timeUpdateAnimationRef = useRef<number | null>(null);
- const [pixiReady, setPixiReady] = useState(false);
- const [videoReady, setVideoReady] = useState(false);
- const overlayRef = useRef<HTMLDivElement | null>(null);
- const focusIndicatorRef = useRef<HTMLDivElement | null>(null);
- const webcamVideoRef = useRef<HTMLVideoElement | null>(null);
- const webcamBubbleRef = useRef<HTMLDivElement | null>(null);
- const webcamBubbleInnerRef = useRef<HTMLDivElement | null>(null);
- const captionBoxRef = useRef<HTMLDivElement | null>(null);
- const currentTimeRef = useRef(0);
- const zoomRegionsRef = useRef<ZoomRegion[]>([]);
- const selectedZoomIdRef = useRef<string | null>(null);
- const animationStateRef = useRef<PlaybackAnimationState>(
- createPlaybackAnimationState(),
- );
- const blurFilterRef = useRef<BlurFilter | null>(null);
- const motionBlurFilterRef = useRef<MotionBlurFilter | null>(null);
- const isDraggingFocusRef = useRef(false);
- const stageSizeRef = useRef({ width: 0, height: 0 });
- const videoSizeRef = useRef({ width: 0, height: 0 });
- const baseScaleRef = useRef(1);
- const baseOffsetRef = useRef({ x: 0, y: 0 });
- const baseMaskRef = useRef<{
- x: number;
- y: number;
- width: number;
- height: number;
- sourceCrop?: {
- x: number;
- y: number;
- width: number;
- height: number;
- };
- }>({ x: 0, y: 0, width: 0, height: 0 });
- const cropBoundsRef = useRef({ startX: 0, endX: 0, startY: 0, endY: 0 });
- const maskGraphicsRef = useRef<Graphics | null>(null);
- const frameSpriteRef = useRef<Sprite | null>(null);
- const frameContainerRef = useRef<Container | null>(null);
- const frameIdRef = useRef<string | null>(frame);
- const isPlayingRef = useRef(isPlaying);
- const isSeekingRef = useRef(false);
- const allowPlaybackRef = useRef(false);
- const lockedVideoDimensionsRef = useRef<{
- width: number;
- height: number;
- } | null>(null);
- const layoutVideoContentRef = useRef<(() => void) | null>(null);
- const trimRegionsRef = useRef<TrimRegion[]>([]);
- const speedRegionsRef = useRef<SpeedRegion[]>([]);
- const lastWebcamSyncTimeRef = useRef<number | null>(null);
- const bgVideoRef = useRef<HTMLVideoElement | null>(null);
- const zoomMotionBlurRef = useRef(zoomMotionBlur);
- const connectZoomsRef = useRef(connectZooms);
- const zoomInDurationMsRef = useRef(zoomInDurationMs);
- const zoomInOverlapMsRef = useRef(zoomInOverlapMs);
- const zoomOutDurationMsRef = useRef(zoomOutDurationMs);
- const connectedZoomGapMsRef = useRef(connectedZoomGapMs);
- const connectedZoomDurationMsRef = useRef(connectedZoomDurationMs);
- const zoomInEasingRef = useRef(zoomInEasing);
- const zoomOutEasingRef = useRef(zoomOutEasing);
- const connectedZoomEasingRef = useRef(connectedZoomEasing);
- const videoReadyRafRef = useRef<number | null>(null);
- const cursorOverlayRef = useRef<PixiCursorOverlay | null>(null);
- const cursorEffectsCanvasRef = useRef<HTMLCanvasElement | null>(null);
- const cursorTelemetryRef = useRef<CursorTelemetryPoint[]>([]);
- const showCursorRef = useRef(showCursor);
- const cursorSizeRef = useRef(cursorSize);
- const cursorStyleRef = useRef(cursorStyle);
- const cursorSmoothingRef = useRef(cursorSmoothing);
- const cursorMotionBlurRef = useRef(cursorMotionBlur);
- const cursorClickBounceRef = useRef(cursorClickBounce);
- const cursorClickBounceDurationRef = useRef(cursorClickBounceDuration);
- const cursorSwayRef = useRef(cursorSway);
- const lastEmittedClickTimeMsRef = useRef(-1);
-
- // Spring animation state for smooth zoom transitions
- const springScaleRef = useRef<SpringState>(createSpringState(1));
- const springXRef = useRef<SpringState>(createSpringState(0));
- const springYRef = useRef<SpringState>(createSpringState(0));
- const lastTickTimeRef = useRef<number | null>(null);
- const zoomSmoothnessRef = useRef(zoomSmoothness);
- const zoomClassicModeRef = useRef(zoomClassicMode);
- const cursorFollowCameraRef = useRef<CursorFollowCameraState>(createCursorFollowCameraState());
-
- const activeCaptionLayout = useMemo(() => {
- if (!autoCaptionSettings?.enabled || autoCaptions.length === 0 || typeof document === "undefined") {
- return null;
- }
-
- const overlayWidth = overlayRef.current?.clientWidth || 960;
- const fontSize = getCaptionScaledFontSize(
- autoCaptionSettings.fontSize,
- overlayWidth,
- autoCaptionSettings.maxWidth,
- );
- const maxTextWidthPx = getCaptionTextMaxWidth(
- overlayWidth,
- autoCaptionSettings.maxWidth,
- fontSize,
- );
- const measurementCanvas = document.createElement("canvas");
- const measurementContext = measurementCanvas.getContext("2d");
- if (!measurementContext) {
- return null;
- }
-
- measurementContext.font = `${CAPTION_FONT_WEIGHT} ${fontSize}px ${getDefaultCaptionFontFamily()}`;
-
- return buildActiveCaptionLayout({
- cues: autoCaptions,
- timeMs: Math.round(currentTime * 1000),
- settings: autoCaptionSettings,
- maxWidthPx: maxTextWidthPx,
- measureText: (text) => measurementContext.measureText(text).width,
- });
- }, [autoCaptionSettings, autoCaptions, currentTime]);
-
- useEffect(() => {
- const captionBox = captionBoxRef.current;
- if (!captionBox || !activeCaptionLayout || !autoCaptionSettings) {
- if (captionBox) {
- captionBox.style.clipPath = "";
- captionBox.style.removeProperty("-webkit-clip-path");
- }
- return;
- }
-
- const frame = requestAnimationFrame(() => {
- const width = captionBox.offsetWidth;
- const height = captionBox.offsetHeight;
- if (width <= 0 || height <= 0) {
- return;
- }
-
- const fontSize = getCaptionScaledFontSize(
- autoCaptionSettings.fontSize,
- overlayRef.current?.clientWidth || 960,
- autoCaptionSettings.maxWidth,
- );
-
- const squirclePath = getSquircleSvgPath({
- x: 0,
- y: 0,
- width,
- height,
- radius: getCaptionScaledRadius(autoCaptionSettings.boxRadius, fontSize),
- });
- captionBox.style.clipPath = `path('${squirclePath}')`;
- captionBox.style.setProperty("-webkit-clip-path", `path('${squirclePath}')`);
- });
-
- return () => cancelAnimationFrame(frame);
- }, [activeCaptionLayout, autoCaptionSettings]);
- const motionBlurStateRef = useRef<MotionBlurState>(createMotionBlurState());
-
- const applyWebcamBubbleLayout = useCallback((zoomScale: number) => {
- const bubble = webcamBubbleRef.current;
- const bubbleInner = webcamBubbleInnerRef.current;
- const overlay = overlayRef.current;
- if (!bubble || !bubbleInner || !overlay || !webcam?.enabled || !webcamVideoPath) {
- if (bubble) {
- bubble.style.display = "none";
- }
- return;
- }
-
- const margin = webcam.margin ?? 24;
- const scaledSize = getWebcamOverlaySizePx({
- containerWidth: overlay.clientWidth,
- containerHeight: overlay.clientHeight,
- sizePercent: webcam.size ?? DEFAULT_WEBCAM_SIZE,
- margin,
- zoomScale,
- reactToZoom: webcam.reactToZoom ?? DEFAULT_WEBCAM_REACT_TO_ZOOM,
- });
- const { x, y } = getWebcamOverlayPosition({
- containerWidth: overlay.clientWidth,
- containerHeight: overlay.clientHeight,
- size: scaledSize,
- margin,
- positionPreset: webcam.positionPreset ?? webcam.corner,
- positionX: webcam.positionX ?? 1,
- positionY: webcam.positionY ?? 1,
- legacyCorner: webcam.corner,
- });
-
- bubble.style.display = "block";
- bubble.style.left = `${x}px`;
- bubble.style.top = `${y}px`;
- bubble.style.width = `${scaledSize}px`;
- bubble.style.height = `${scaledSize}px`;
- const squirclePath = getSquircleSvgPath({
- x: 0,
- y: 0,
- width: scaledSize,
- height: scaledSize,
- radius: webcam.cornerRadius ?? DEFAULT_WEBCAM_CORNER_RADIUS,
- });
- bubble.style.filter = `drop-shadow(0 ${Math.round(scaledSize * 0.06)}px ${Math.round(
- scaledSize * 0.22,
- )}px rgba(0, 0, 0, ${webcam.shadow ?? DEFAULT_WEBCAM_SHADOW}))`;
- bubble.style.borderRadius = "0px";
- bubble.style.boxShadow = "none";
-
- bubbleInner.style.borderRadius = "0px";
- bubbleInner.style.clipPath = `path('${squirclePath}')`;
- bubbleInner.style.setProperty("-webkit-clip-path", `path('${squirclePath}')`);
- }, [webcam, webcamVideoPath]);
-
- const clampFocusToStage = useCallback(
- (focus: ZoomFocus, depth: ZoomDepth) => {
- return clampFocusToStageUtil(focus, depth, stageSizeRef.current);
- },
- [],
- );
-
- const updateOverlayForRegion = useCallback(
- (region: ZoomRegion | null, focusOverride?: ZoomFocus) => {
- const overlayEl = overlayRef.current;
- const indicatorEl = focusIndicatorRef.current;
-
- if (!overlayEl || !indicatorEl) {
- return;
- }
-
- // Update stage size from overlay dimensions
- const stageWidth = overlayEl.clientWidth;
- const stageHeight = overlayEl.clientHeight;
- if (stageWidth && stageHeight) {
- stageSizeRef.current = { width: stageWidth, height: stageHeight };
- }
-
- updateOverlayIndicator({
- overlayEl,
- indicatorEl,
- region,
- focusOverride,
- baseMask: baseMaskRef.current,
- isPlaying: isPlayingRef.current,
- });
- },
- [],
- );
-
- const layoutVideoContent = useCallback(() => {
- const container = containerRef.current;
- const app = appRef.current;
- const videoSprite = videoSpriteRef.current;
- const maskGraphics = maskGraphicsRef.current;
- const videoElement = videoRef.current;
- const cameraContainer = cameraContainerRef.current;
-
- if (
- !container ||
- !app ||
- !videoSprite ||
- !maskGraphics ||
- !videoElement ||
- !cameraContainer
- ) {
- return;
- }
-
- // Lock video dimensions on first layout to prevent resize issues
- if (
- !lockedVideoDimensionsRef.current &&
- videoElement.videoWidth > 0 &&
- videoElement.videoHeight > 0
- ) {
- lockedVideoDimensionsRef.current = {
- width: videoElement.videoWidth,
- height: videoElement.videoHeight,
- };
- }
-
- // Look up device frame insets so layout centers the full frame (video + bezels)
- let frameInsets: { top: number; right: number; bottom: number; left: number } | null = null;
- if (frame) {
- const frames = extensionHost.getFrames();
- const frameData = frames.find((f) => f.id === frame);
- if (frameData?.screenInsets) {
- frameInsets = frameData.screenInsets;
- }
- }
-
- const result = layoutVideoContentUtil({
- container,
- app,
- videoSprite,
- maskGraphics,
- videoElement,
- cropRegion,
- lockedVideoDimensions: lockedVideoDimensionsRef.current,
- borderRadius,
- padding,
- frameInsets,
- });
-
- if (result) {
- stageSizeRef.current = result.stageSize;
- videoSizeRef.current = result.videoSize;
- baseScaleRef.current = result.baseScale;
- baseOffsetRef.current = result.baseOffset;
- baseMaskRef.current = result.maskRect;
- cropBoundsRef.current = result.cropBounds;
-
- // Sync extension cursor effects canvas resolution with renderer
- const effectsCanvas = cursorEffectsCanvasRef.current;
- if (effectsCanvas) {
- const w = result.stageSize.width;
- const h = result.stageSize.height;
- if (effectsCanvas.width !== w || effectsCanvas.height !== h) {
- effectsCanvas.width = w;
- effectsCanvas.height = h;
- }
- }
-
- // Push layout info to extension host for query APIs
- extensionHost.setVideoLayout({
- maskRect: { x: result.maskRect.x, y: result.maskRect.y, width: result.maskRect.width, height: result.maskRect.height },
- canvasWidth: result.stageSize.width,
- canvasHeight: result.stageSize.height,
- borderRadius,
- padding,
- });
- extensionHost.setShadowConfig({
- enabled: Boolean(showShadow) && shadowIntensity > 0,
- intensity: shadowIntensity,
- });
-
- // Position device frame sprite to fill the stage
- const frameSprite = frameSpriteRef.current;
- if (frameSprite && frame) {
- const frames = extensionHost.getFrames();
- const frameData = frames.find((f) => f.id === frame);
- if (frameData) {
- const maskRect = result.maskRect;
- const insets = frameData.screenInsets;
- if (insets) {
- // Frame is larger than screen area — compute full frame size from insets
- const screenW = maskRect.width;
- const screenH = maskRect.height;
- const frameW = screenW / (1 - insets.left - insets.right);
- const frameH = screenH / (1 - insets.top - insets.bottom);
- const frameX = maskRect.x - insets.left * frameW;
- const frameY = maskRect.y - insets.top * frameH;
- frameSprite.position.set(frameX, frameY);
- frameSprite.width = frameW;
- frameSprite.height = frameH;
- } else {
- frameSprite.position.set(maskRect.x, maskRect.y);
- frameSprite.width = maskRect.width;
- frameSprite.height = maskRect.height;
- }
- }
- }
-
- // Reset camera container to identity
- cameraContainer.scale.set(1);
- cameraContainer.position.set(0, 0);
-
- const selectedId = selectedZoomIdRef.current;
- const activeRegion = selectedId
- ? (zoomRegionsRef.current.find(
- (region) => region.id === selectedId,
- ) ?? null)
- : null;
-
- updateOverlayForRegion(activeRegion);
- applyWebcamBubbleLayout(animationStateRef.current.appliedScale || 1);
- }
- }, [updateOverlayForRegion, cropRegion, borderRadius, padding, frame, showShadow, shadowIntensity, applyWebcamBubbleLayout]);
-
- useEffect(() => {
- const video = videoRef.current;
- if (!video) return;
-
- const nextVolume = Math.max(0, Math.min(1, volume));
- video.volume = nextVolume;
- video.muted = nextVolume <= 0.001;
- }, [volume, videoPath]);
-
- useEffect(() => {
- layoutVideoContentRef.current = layoutVideoContent;
- }, [layoutVideoContent]);
-
- // Sync device frame ref
- useEffect(() => {
- frameIdRef.current = frame;
- extensionHost.setActiveFrame(frame ?? null);
- }, [frame]);
-
- // Manage device frame sprite
- useEffect(() => {
- const frameContainer = frameContainerRef.current;
- if (!frameContainer) return;
-
- // Clear existing frame sprite
- if (frameSpriteRef.current) {
- frameContainer.removeChild(frameSpriteRef.current);
- frameSpriteRef.current.destroy();
- frameSpriteRef.current = null;
- }
-
- if (!frame) {
- layoutVideoContentRef.current?.();
- return;
- }
-
- let cancelled = false;
-
- function tryLoadFrame() {
- if (cancelled) return;
- const container = frameContainerRef.current;
- if (!container) return false;
- const frames = extensionHost.getFrames();
- const frameData = frames.find((f) => f.id === frame);
- if (!frameData) return false;
-
- if (frameData.draw) {
- // Resolution-independent: draw at a reasonable size, Pixi handles the rest
- const drawW = 1920;
- const drawH = 1080;
- const canvas = document.createElement('canvas');
- canvas.width = drawW;
- canvas.height = drawH;
- const ctx = canvas.getContext('2d');
- if (ctx) frameData.draw(ctx, drawW, drawH);
- if (cancelled || frameIdRef.current !== frame) return true;
- const texture = Texture.from(canvas);
- const sprite = new Sprite(texture);
- frameSpriteRef.current = sprite;
- container.addChild(sprite);
- layoutVideoContentRef.current?.();
- } else {
- const img = new Image();
- img.onload = () => {
- if (cancelled || frameIdRef.current !== frame) return;
- const texture = Texture.from(img);
- const sprite = new Sprite(texture);
- frameSpriteRef.current = sprite;
- container.addChild(sprite);
- layoutVideoContentRef.current?.();
- };
- img.src = frameData.filePath;
- }
- return true;
- }
-
- // Try immediately; if extension hasn't registered frames yet,
- // listen for changes and retry once they become available.
- if (!tryLoadFrame()) {
- const unsub = extensionHost.onChange(() => {
- if (tryLoadFrame()) unsub();
- });
- return () => { cancelled = true; unsub(); };
- }
-
- return () => { cancelled = true; };
- }, [frame]);
-
- const selectedZoom = useMemo(() => {
- if (!selectedZoomId) return null;
- return zoomRegions.find((region) => region.id === selectedZoomId) ?? null;
- }, [zoomRegions, selectedZoomId]);
-
- useImperativeHandle(ref, () => ({
- video: videoRef.current,
- app: appRef.current,
- videoSprite: videoSpriteRef.current,
- videoContainer: videoContainerRef.current,
- containerRef,
- play: async () => {
- const vid = videoRef.current;
- if (!vid) return;
- try {
- allowPlaybackRef.current = true;
- await vid.play();
- } catch (error) {
- allowPlaybackRef.current = false;
- throw error;
- }
- },
- pause: () => {
- const video = videoRef.current;
- allowPlaybackRef.current = false;
- if (!video) {
- return;
- }
- video.pause();
- },
- refreshFrame: async () => {
- const video = videoRef.current;
- if (!video || Number.isNaN(video.currentTime)) {
- return;
- }
-
- const restoreTime = video.currentTime;
- const duration = Number.isFinite(video.duration) ? video.duration : 0;
- const epsilon =
- duration > 0
- ? Math.min(1 / 120, duration / 1000 || 1 / 120)
- : 1 / 120;
- const nudgeTarget =
- restoreTime > epsilon
- ? restoreTime - epsilon
- : Math.min(
- duration || restoreTime + epsilon,
- restoreTime + epsilon,
- );
-
- if (Math.abs(nudgeTarget - restoreTime) < 0.000001) {
- return;
- }
-
- await new Promise<void>((resolve) => {
- const handleFirstSeeked = () => {
- video.removeEventListener("seeked", handleFirstSeeked);
- const handleSecondSeeked = () => {
- video.removeEventListener("seeked", handleSecondSeeked);
- video.pause();
- resolve();
- };
-
- video.addEventListener("seeked", handleSecondSeeked, {
- once: true,
- });
- video.currentTime = restoreTime;
- };
-
- video.addEventListener("seeked", handleFirstSeeked, { once: true });
- video.currentTime = nudgeTarget;
- });
- },
- }));
-
- const updateFocusFromClientPoint = (clientX: number, clientY: number) => {
- const overlayEl = overlayRef.current;
- if (!overlayEl) return;
-
- const regionId = selectedZoomIdRef.current;
- if (!regionId) return;
-
- const region = zoomRegionsRef.current.find((r) => r.id === regionId);
- if (!region) return;
-
- const rect = overlayEl.getBoundingClientRect();
- const stageWidth = rect.width;
- const stageHeight = rect.height;
-
- if (!stageWidth || !stageHeight) {
- return;
- }
-
- stageSizeRef.current = { width: stageWidth, height: stageHeight };
-
- const localX = clientX - rect.left;
- const localY = clientY - rect.top;
- const baseMask = baseMaskRef.current;
-
- const unclampedFocus: ZoomFocus = {
- cx: clamp01((localX - baseMask.x) / Math.max(1, baseMask.width)),
- cy: clamp01((localY - baseMask.y) / Math.max(1, baseMask.height)),
- };
- const clampedFocus = clampFocusToStage(unclampedFocus, region.depth);
-
- onZoomFocusChange(region.id, clampedFocus);
- updateOverlayForRegion({ ...region, focus: clampedFocus }, clampedFocus);
- };
-
- const handleOverlayPointerDown = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
- if (isPlayingRef.current) return;
- const regionId = selectedZoomIdRef.current;
- if (!regionId) return;
- const region = zoomRegionsRef.current.find((r) => r.id === regionId);
- if (!region) return;
- onSelectZoom(region.id);
- event.preventDefault();
- isDraggingFocusRef.current = true;
- event.currentTarget.setPointerCapture(event.pointerId);
- updateFocusFromClientPoint(event.clientX, event.clientY);
- };
-
- const handleOverlayPointerMove = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
- if (!isDraggingFocusRef.current) return;
- event.preventDefault();
- updateFocusFromClientPoint(event.clientX, event.clientY);
- };
-
- const endFocusDrag = (event: React.PointerEvent<HTMLDivElement>) => {
- if (!isDraggingFocusRef.current) return;
- isDraggingFocusRef.current = false;
- try {
- event.currentTarget.releasePointerCapture(event.pointerId);
- } catch {}
- };
-
- const handleOverlayPointerUp = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
- endFocusDrag(event);
- };
-
- const handleOverlayPointerLeave = (
- event: React.PointerEvent<HTMLDivElement>,
- ) => {
- endFocusDrag(event);
- };
-
- useEffect(() => {
- zoomRegionsRef.current = zoomRegions;
- }, [zoomRegions]);
-
- useEffect(() => {
- selectedZoomIdRef.current = selectedZoomId;
- }, [selectedZoomId]);
-
- useEffect(() => {
- isPlayingRef.current = isPlaying;
- extensionHost.emitEvent({ type: isPlaying ? 'playback:play' : 'playback:pause', timeMs: currentTimeRef.current });
- // Snap springs to current position when pausing so scrubbing is instant
- if (!isPlaying) {
- resetSpringState(springScaleRef.current);
- resetSpringState(springXRef.current);
- resetSpringState(springYRef.current);
- resetCursorFollowCamera(cursorFollowCameraRef.current);
- lastTickTimeRef.current = null;
- }
- const bgVideo = bgVideoRef.current;
- if (bgVideo) {
- if (isPlaying) {
- bgVideo.play().catch(() => {});
- } else {
- bgVideo.pause();
- }
- }
- }, [isPlaying]);
-
- // Sync background video wallpaper with timeline scrubbing
- useEffect(() => {
- const bgVideo = bgVideoRef.current;
- if (!bgVideo) return;
- if (!isPlaying && bgVideo.duration && Number.isFinite(bgVideo.duration)) {
- bgVideo.currentTime = currentTime % bgVideo.duration;
- }
- }, [currentTime, isPlaying]);
-
- useEffect(() => {
- trimRegionsRef.current = trimRegions;
- }, [trimRegions]);
-
- useEffect(() => {
- speedRegionsRef.current = speedRegions;
- }, [speedRegions]);
-
- useEffect(() => {
- zoomMotionBlurRef.current = zoomMotionBlur;
- }, [zoomMotionBlur]);
-
- useEffect(() => {
- connectZoomsRef.current = connectZooms;
- }, [connectZooms]);
-
- useEffect(() => {
- zoomInDurationMsRef.current = zoomInDurationMs;
- }, [zoomInDurationMs]);
-
- useEffect(() => {
- zoomInOverlapMsRef.current = zoomInOverlapMs;
- }, [zoomInOverlapMs]);
-
- useEffect(() => {
- zoomOutDurationMsRef.current = zoomOutDurationMs;
- }, [zoomOutDurationMs]);
-
- useEffect(() => {
- connectedZoomGapMsRef.current = connectedZoomGapMs;
- }, [connectedZoomGapMs]);
-
- useEffect(() => {
- connectedZoomDurationMsRef.current = connectedZoomDurationMs;
- }, [connectedZoomDurationMs]);
-
- useEffect(() => {
- zoomInEasingRef.current = zoomInEasing;
- }, [zoomInEasing]);
-
- useEffect(() => {
- zoomOutEasingRef.current = zoomOutEasing;
- }, [zoomOutEasing]);
-
- useEffect(() => {
- connectedZoomEasingRef.current = connectedZoomEasing;
- }, [connectedZoomEasing]);
-
- useEffect(() => {
- cursorTelemetryRef.current = cursorTelemetry;
- // Push to extension host for query APIs
- extensionHost.setCursorTelemetry(
- cursorTelemetry.map(p => ({
- timeMs: p.timeMs,
- cx: p.cx,
- cy: p.cy,
- interactionType: p.interactionType,
- pressure: (p as any).pressure,
- })),
- );
- }, [cursorTelemetry]);
-
- useEffect(() => {
- showCursorRef.current = showCursor;
- }, [showCursor]);
-
- useEffect(() => {
- cursorStyleRef.current = cursorStyle;
- }, [cursorStyle]);
-
- useEffect(() => {
- cursorSizeRef.current = cursorSize;
- }, [cursorSize]);
-
- useEffect(() => {
- cursorSmoothingRef.current = cursorSmoothing;
- }, [cursorSmoothing]);
-
- useEffect(() => {
- zoomSmoothnessRef.current = zoomSmoothness;
- }, [zoomSmoothness]);
-
- useEffect(() => {
- zoomClassicModeRef.current = zoomClassicMode;
- }, [zoomClassicMode]);
-
- useEffect(() => {
- cursorMotionBlurRef.current = cursorMotionBlur;
- }, [cursorMotionBlur]);
-
- useEffect(() => {
- cursorClickBounceRef.current = cursorClickBounce;
- }, [cursorClickBounce]);
-
- useEffect(() => {
- cursorClickBounceDurationRef.current = cursorClickBounceDuration;
- }, [cursorClickBounceDuration]);
-
- useEffect(() => {
- cursorSwayRef.current = cursorSway;
- }, [cursorSway]);
-
- useEffect(() => {
- const timeMs = currentTime * 1000;
- currentTimeRef.current = timeMs;
- const videoInfo = extensionHost.getVideoInfoSnapshot();
- extensionHost.setPlaybackState({
- currentTimeMs: timeMs,
- durationMs: videoInfo?.durationMs ?? 0,
- isPlaying,
- });
- }, [currentTime, isPlaying]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
-
- const app = appRef.current;
- const cameraContainer = cameraContainerRef.current;
- const video = videoRef.current;
-
- if (!app || !cameraContainer || !video) return;
-
- const tickerWasStarted = app.ticker?.started || false;
- if (tickerWasStarted && app.ticker) {
- app.ticker.stop();
- }
-
- const wasPlaying = !video.paused;
- if (wasPlaying) {
- video.pause();
- }
-
- animationStateRef.current = createPlaybackAnimationState();
- cursorOverlayRef.current?.reset();
- motionBlurStateRef.current = createMotionBlurState();
-
- if (blurFilterRef.current) {
- blurFilterRef.current.blur = 0;
- }
-
- requestAnimationFrame(() => {
- const container = cameraContainerRef.current;
- const videoStage = videoContainerRef.current;
- const sprite = videoSpriteRef.current;
- const currentApp = appRef.current;
- if (!container || !videoStage || !sprite || !currentApp) {
- return;
- }
-
- container.scale.set(1);
- container.position.set(0, 0);
- videoStage.scale.set(1);
- videoStage.position.set(0, 0);
- sprite.scale.set(1);
- sprite.position.set(0, 0);
-
- layoutVideoContent();
-
- applyZoomTransform({
- cameraContainer: container,
- blurFilter: blurFilterRef.current,
- stageSize: stageSizeRef.current,
- baseMask: baseMaskRef.current,
- zoomScale: 1,
- focusX: DEFAULT_FOCUS.cx,
- focusY: DEFAULT_FOCUS.cy,
- motionIntensity: 0,
- isPlaying: false,
- motionBlurAmount: zoomMotionBlurRef.current,
- });
-
- requestAnimationFrame(() => {
- const finalApp = appRef.current;
- if (wasPlaying && video) {
- video.play().catch(() => {});
- }
- if (tickerWasStarted && finalApp?.ticker) {
- finalApp.ticker.start();
- }
- });
- });
- }, [pixiReady, videoReady, layoutVideoContent, cropRegion]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
- const container = containerRef.current;
- if (!container) return;
-
- if (typeof ResizeObserver === "undefined") {
- return;
- }
-
- const observer = new ResizeObserver(() => {
- layoutVideoContent();
- });
-
- observer.observe(container);
- return () => {
- observer.disconnect();
- };
- }, [pixiReady, videoReady, layoutVideoContent]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
- updateOverlayForRegion(selectedZoom);
- }, [selectedZoom, pixiReady, videoReady, updateOverlayForRegion]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
- applyWebcamBubbleLayout(animationStateRef.current.appliedScale || 1);
- }, [applyWebcamBubbleLayout, pixiReady, videoReady, webcam, webcamVideoPath]);
-
- useEffect(() => {
- const webcamVideo = webcamVideoRef.current;
- if (!webcamVideo || !webcam?.enabled || !webcamVideoPath) {
- return;
- }
-
- const targetTime = clampMediaTimeToDuration(
- currentTime,
- Number.isFinite(webcamVideo.duration) ? webcamVideo.duration : null,
- );
-
- const activeSpeedRegion = speedRegionsRef.current.find(
- (region) => targetTime * 1000 >= region.startMs && targetTime * 1000 < region.endMs,
- );
- const targetPlaybackRate = activeSpeedRegion ? activeSpeedRegion.speed : 1;
- if (Math.abs(webcamVideo.playbackRate - targetPlaybackRate) > 0.001) {
- webcamVideo.playbackRate = targetPlaybackRate;
- }
-
- const previousTimelineTime = lastWebcamSyncTimeRef.current;
- const timelineJumped =
- previousTimelineTime === null || Math.abs(targetTime - previousTimelineTime) > 0.25;
- const driftThreshold = isPlaying ? 0.35 : 0.01;
- if (timelineJumped || Math.abs(webcamVideo.currentTime - targetTime) > driftThreshold) {
- try {
- webcamVideo.currentTime = targetTime;
- } catch {
- // no-op
- }
- }
-
- if (isPlaying) {
- const playPromise = webcamVideo.play();
- if (playPromise) {
- playPromise.catch(() => {});
- }
- } else {
- webcamVideo.pause();
- }
-
- lastWebcamSyncTimeRef.current = targetTime;
- }, [currentTime, isPlaying, webcam, webcamVideoPath]);
-
- useEffect(() => {
- lastWebcamSyncTimeRef.current = null;
- }, [webcamVideoPath]);
-
- useEffect(() => {
- const overlayEl = overlayRef.current;
- if (!overlayEl) return;
- if (!selectedZoom) {
- overlayEl.style.cursor = "default";
- overlayEl.style.pointerEvents = "none";
- return;
- }
- overlayEl.style.cursor = isPlaying ? "not-allowed" : "grab";
- overlayEl.style.pointerEvents = isPlaying ? "none" : "auto";
- }, [selectedZoom, isPlaying]);
-
- useEffect(() => {
- const container = containerRef.current;
- if (!container) return;
-
- let mounted = true;
- let app: Application | null = null;
-
- (async () => {
- let cursorOverlayEnabled = true;
- try {
- await preloadCursorAssets();
- } catch (error) {
- cursorOverlayEnabled = false;
- console.warn(
- "Native cursor assets are unavailable in preview; continuing without cursor overlay.",
- error,
- );
- }
-
- app = new Application();
-
- await app.init({
- width: container.clientWidth,
- height: container.clientHeight,
- backgroundAlpha: 0,
- antialias: true,
- failIfMajorPerformanceCaveat: false,
- resolution: window.devicePixelRatio || 1,
- autoDensity: true,
- preference: "webgl",
- });
-
- app.ticker.maxFPS = 60;
-
- if (!mounted) {
- app.destroy(true, {
- children: true,
- texture: false,
- textureSource: false,
- });
- return;
- }
-
- appRef.current = app;
- container.appendChild(app.canvas);
-
- // Camera container - this will be scaled/positioned for zoom
- const cameraContainer = new Container();
- cameraContainerRef.current = cameraContainer;
- app.stage.addChild(cameraContainer);
-
- // Video container - holds the masked video sprite
- const videoContainer = new Container();
- videoContainerRef.current = videoContainer;
- cameraContainer.addChild(videoContainer);
-
- // Device frame overlay container — sits above video but below cursor
- const frameContainer = new Container();
- frameContainerRef.current = frameContainer;
- cameraContainer.addChild(frameContainer);
-
- const cursorContainer = new Container();
- cursorContainerRef.current = cursorContainer;
- cameraContainer.addChild(cursorContainer);
-
- // Cursor overlay - rendered above the masked video so it can sit in front
- // of the content without getting clipped.
- if (cursorOverlayEnabled) {
- const cursorOverlay = new PixiCursorOverlay({
- dotRadius: DEFAULT_CURSOR_CONFIG.dotRadius * cursorSizeRef.current,
- style: cursorStyleRef.current,
- smoothingFactor: cursorSmoothingRef.current,
- motionBlur: cursorMotionBlurRef.current,
- clickBounce: cursorClickBounceRef.current,
- clickBounceDuration: cursorClickBounceDurationRef.current,
- sway: cursorSwayRef.current,
- });
- cursorOverlayRef.current = cursorOverlay;
- cursorContainer.addChild(cursorOverlay.container);
- } else {
- cursorOverlayRef.current = null;
- }
-
- setPixiReady(true);
- })().catch((error) => {
- console.error("Failed to initialize preview renderer:", error);
- onError(
- error instanceof Error
- ? error.message
- : "Failed to initialize preview renderer",
- );
- });
-
- return () => {
- mounted = false;
- setPixiReady(false);
- if (cursorOverlayRef.current) {
- cursorOverlayRef.current.destroy();
- cursorOverlayRef.current = null;
- }
- if (app && app.renderer) {
- app.destroy(true, {
- children: true,
- texture: false,
- textureSource: false,
- });
- }
- appRef.current = null;
- cameraContainerRef.current = null;
- videoContainerRef.current = null;
- frameContainerRef.current = null;
- frameSpriteRef.current = null;
- cursorContainerRef.current = null;
- videoSpriteRef.current = null;
- };
- }, [onError]);
-
- useEffect(() => {
- const video = videoRef.current;
- if (!video) return;
- video.pause();
- video.currentTime = 0;
- allowPlaybackRef.current = false;
- lockedVideoDimensionsRef.current = null;
- setVideoReady(false);
- if (videoReadyRafRef.current) {
- cancelAnimationFrame(videoReadyRafRef.current);
- videoReadyRafRef.current = null;
- }
- }, [videoPath]);
-
- useEffect(() => {
- onPreviewReadyChange?.(videoReady);
- }, [onPreviewReadyChange, videoReady]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
-
- const video = videoRef.current;
- const app = appRef.current;
- const videoContainer = videoContainerRef.current;
- const cursorContainer = cursorContainerRef.current;
-
- if (!video || !app || !videoContainer || !cursorContainer) return;
- if (video.videoWidth === 0 || video.videoHeight === 0) return;
-
- const source = VideoSource.from(video);
- if ("autoPlay" in source) {
- (source as { autoPlay?: boolean }).autoPlay = false;
- }
- if ("autoUpdate" in source) {
- (source as { autoUpdate?: boolean }).autoUpdate = true;
- }
- const videoTexture = Texture.from(source);
-
- const videoSprite = new Sprite(videoTexture);
- videoSpriteRef.current = videoSprite;
-
- const maskGraphics = new Graphics();
- videoContainer.addChild(videoSprite);
- videoContainer.addChild(maskGraphics);
- videoContainer.mask = maskGraphics;
- maskGraphicsRef.current = maskGraphics;
- if (cursorOverlayRef.current) {
- cursorContainer.addChild(cursorOverlayRef.current.container);
- }
-
- animationStateRef.current = createPlaybackAnimationState();
-
- const blurFilter = new BlurFilter();
- blurFilter.quality = 3;
- blurFilter.resolution = app.renderer.resolution;
- blurFilter.blur = 0;
- const motionBlurFilter = new MotionBlurFilter([0, 0], 5, 0);
- videoContainer.filters = [blurFilter, motionBlurFilter];
- blurFilterRef.current = blurFilter;
- motionBlurFilterRef.current = motionBlurFilter;
-
- layoutVideoContent();
- video.pause();
-
- const { handlePlay, handlePause, handleSeeked, handleSeeking } =
- createVideoEventHandlers({
- video,
- isSeekingRef,
- isPlayingRef,
- allowPlaybackRef,
- currentTimeRef,
- timeUpdateAnimationRef,
- onPlayStateChange,
- onTimeUpdate,
- trimRegionsRef,
- speedRegionsRef,
- });
-
- video.addEventListener("play", handlePlay);
- video.addEventListener("pause", handlePause);
- video.addEventListener("ended", handlePause);
- video.addEventListener("seeked", handleSeeked);
- video.addEventListener("seeking", handleSeeking);
-
- return () => {
- video.removeEventListener("play", handlePlay);
- video.removeEventListener("pause", handlePause);
- video.removeEventListener("ended", handlePause);
- video.removeEventListener("seeked", handleSeeked);
- video.removeEventListener("seeking", handleSeeking);
-
- if (timeUpdateAnimationRef.current) {
- cancelAnimationFrame(timeUpdateAnimationRef.current);
- }
-
- if (videoSprite) {
- videoContainer.removeChild(videoSprite);
- videoSprite.destroy();
- }
- if (maskGraphics) {
- videoContainer.removeChild(maskGraphics);
- maskGraphics.destroy();
- }
- videoContainer.mask = null;
- maskGraphicsRef.current = null;
- if (blurFilterRef.current) {
- videoContainer.filters = [];
- blurFilterRef.current.destroy();
- blurFilterRef.current = null;
- }
- if (motionBlurFilterRef.current) {
- motionBlurFilterRef.current.destroy();
- motionBlurFilterRef.current = null;
- }
- videoTexture.destroy(false);
-
- videoSpriteRef.current = null;
- };
- }, [pixiReady, videoReady, onTimeUpdate, updateOverlayForRegion]);
-
- useEffect(() => {
- if (!pixiReady || !videoReady) return;
-
- const app = appRef.current;
- const videoSprite = videoSpriteRef.current;
- const videoContainer = videoContainerRef.current;
- if (!app || !videoSprite || !videoContainer) return;
-
- const applyTransform = (
- transform: { scale: number; x: number; y: number },
- focus: ZoomFocus,
- motionIntensity: number,
- motionVector: { x: number; y: number },
- ) => {
- const cameraContainer = cameraContainerRef.current;
- if (!cameraContainer) return;
-
- const state = animationStateRef.current;
-
- const appliedTransform = applyZoomTransform({
- cameraContainer,
- blurFilter: blurFilterRef.current,
- stageSize: stageSizeRef.current,
- baseMask: baseMaskRef.current,
- zoomScale: state.scale,
- zoomProgress: state.progress,
- focusX: focus.cx,
- focusY: focus.cy,
- motionIntensity,
- motionVector,
- isPlaying: isPlayingRef.current,
- motionBlurAmount: zoomMotionBlurRef.current,
- motionBlurFilter: motionBlurFilterRef.current,
- transformOverride: transform,
- motionBlurState: motionBlurStateRef.current,
- frameTimeMs: performance.now(),
- });
-
- state.x = appliedTransform.x;
- state.y = appliedTransform.y;
- state.appliedScale = appliedTransform.scale;
- };
-
- const ticker = () => {
- const { region, strength, blendedScale, transition } =
- findDominantRegion(zoomRegionsRef.current, currentTimeRef.current, {
- connectZooms: connectZoomsRef.current,
- });
-
- const defaultFocus = DEFAULT_FOCUS;
- let targetScaleFactor = 1;
- let targetFocus = defaultFocus;
- let targetProgress = 0;
-
- // If a zoom is selected but video is not playing, show default unzoomed view
- // (the overlay will show where the zoom will be)
- const selectedId = selectedZoomIdRef.current;
- const hasSelectedZoom = selectedId !== null;
- const shouldShowUnzoomedView = hasSelectedZoom && !isPlayingRef.current;
-
- if (region && strength > 0 && !shouldShowUnzoomedView) {
- const zoomScale = blendedScale ?? ZOOM_DEPTH_SCALES[region.depth];
-
- // Cursor follow: use cursor-follow camera for non-manual zoom regions
- let regionFocus = region.focus;
- if (!zoomClassicModeRef.current && region.mode !== 'manual' && cursorTelemetryRef.current.length > 0) {
- regionFocus = computeCursorFollowFocus(
- cursorFollowCameraRef.current,
- cursorTelemetryRef.current,
- currentTimeRef.current,
- zoomScale,
- strength,
- region.focus,
- { snapToEdgesRatio: SNAP_TO_EDGES_RATIO_AUTO },
- );
- }
-
- targetScaleFactor = zoomScale;
- targetFocus = regionFocus;
- targetProgress = strength;
-
- if (transition) {
- const startTransform = computeZoomTransform({
- stageSize: stageSizeRef.current,
- baseMask: baseMaskRef.current,
- zoomScale: transition.startScale,
- zoomProgress: 1,
- focusX: transition.startFocus.cx,
- focusY: transition.startFocus.cy,
- });
- const endTransform = computeZoomTransform({
- stageSize: stageSizeRef.current,
- baseMask: baseMaskRef.current,
- zoomScale: transition.endScale,
- zoomProgress: 1,
- focusX: transition.endFocus.cx,
- focusY: transition.endFocus.cy,
- });
-
- const interpolatedTransform = {
- scale:
- startTransform.scale +
- (endTransform.scale - startTransform.scale) *
- transition.progress,
- x:
- startTransform.x +
- (endTransform.x - startTransform.x) * transition.progress,
- y:
- startTransform.y +
- (endTransform.y - startTransform.y) * transition.progress,
- };
-
- targetScaleFactor = interpolatedTransform.scale;
- targetFocus = computeFocusFromTransform({
- stageSize: stageSizeRef.current,
- baseMask: baseMaskRef.current,
- zoomScale: interpolatedTransform.scale,
- x: interpolatedTransform.x,
- y: interpolatedTransform.y,
- });
- targetProgress = 1;
- }
- }
-
- const state = animationStateRef.current;
- const prevScale = state.appliedScale;
- const prevX = state.x;
- const prevY = state.y;
-
- state.scale = targetScaleFactor;
- state.focusX = targetFocus.cx;
- state.focusY = targetFocus.cy;
- state.progress = targetProgress;
-
- // Push zoom state to extension host for query APIs
- extensionHost.setZoomState({
- scale: targetScaleFactor,
- focusX: targetFocus.cx,
- focusY: targetFocus.cy,
- progress: targetProgress,
- });
-
- const projectedTransform = computeZoomTransform({
- stageSize: stageSizeRef.current,
- baseMask: baseMaskRef.current,
- zoomScale: state.scale,
- zoomProgress: state.progress,
- focusX: state.focusX,
- focusY: state.focusY,
- });
-
- // Spring-driven zoom animation
- const now = performance.now();
- const deltaMs = lastTickTimeRef.current !== null
- ? now - lastTickTimeRef.current
- : 1000 / 60;
- lastTickTimeRef.current = now;
-
- const zoomSpringConfig = getZoomSpringConfig(zoomSmoothnessRef.current);
- const useSpring = isPlayingRef.current && !isSeekingRef.current && !zoomClassicModeRef.current;
-
- let appliedScale: number;
- let appliedX: number;
- let appliedY: number;
-
- if (useSpring) {
- appliedScale = stepSpringValue(springScaleRef.current, projectedTransform.scale, deltaMs, zoomSpringConfig);
- appliedX = stepSpringValue(springXRef.current, projectedTransform.x, deltaMs, zoomSpringConfig);
- appliedY = stepSpringValue(springYRef.current, projectedTransform.y, deltaMs, zoomSpringConfig);
- } else {
- // Snap instantly when paused, seeking, or in classic mode
- appliedScale = projectedTransform.scale;
- appliedX = projectedTransform.x;
- appliedY = projectedTransform.y;
- resetSpringState(springScaleRef.current, appliedScale);
- resetSpringState(springXRef.current, appliedX);
- resetSpringState(springYRef.current, appliedY);
- }
-
- const motionIntensity = Math.max(
- Math.abs(appliedScale - prevScale),
- Math.abs(appliedX - prevX) / Math.max(1, stageSizeRef.current.width),
- Math.abs(appliedY - prevY) / Math.max(1, stageSizeRef.current.height),
- );
-
- const motionVector = {
- x: appliedX - prevX,
- y: appliedY - prevY,
- };
-
- applyTransform(
- { scale: appliedScale, x: appliedX, y: appliedY },
- targetFocus,
- motionIntensity,
- motionVector,
- );
- applyWebcamBubbleLayout(animationStateRef.current.appliedScale || 1);
-
- const timeMs = currentTimeRef.current;
- const effectsCanvas = cursorEffectsCanvasRef.current;
- const extensionCanvasWidth = effectsCanvas?.width || stageSizeRef.current.width;
- const extensionCanvasHeight = effectsCanvas?.height || stageSizeRef.current.height;
- let smoothedCursorForHooks: {
- cx: number;
- cy: number;
- trail: Array<{ cx: number; cy: number }>;
- } | null = null;
-
- // Update cursor overlay + emit cursor events
- const cursorOverlay = cursorOverlayRef.current;
- if (cursorOverlay) {
- const telemetry = cursorTelemetryRef.current;
- cursorOverlay.update(
- telemetry,
- timeMs,
- baseMaskRef.current,
- showCursorRef.current,
- !isPlayingRef.current || isSeekingRef.current,
- );
-
- smoothedCursorForHooks = mapSmoothedCursorToCanvasNormalized(
- cursorOverlay.getSmoothedCursorSnapshot(),
- {
- maskRect: baseMaskRef.current,
- canvasWidth: extensionCanvasWidth,
- canvasHeight: extensionCanvasHeight,
- },
- );
- extensionHost.setSmoothedCursor(
- smoothedCursorForHooks
- ? {
- timeMs,
- cx: smoothedCursorForHooks.cx,
- cy: smoothedCursorForHooks.cy,
- trail: smoothedCursorForHooks.trail,
- }
- : null,
- );
-
- // Emit cursor:click events for extensions
- if (isPlayingRef.current && telemetry.length > 0) {
- for (let i = telemetry.length - 1; i >= 0; i--) {
- const p = telemetry[i];
- if (p.timeMs > timeMs) continue;
- if (p.timeMs < timeMs - 100) break;
- if (
- p.interactionType &&
- p.interactionType !== 'move' &&
- p.timeMs !== lastEmittedClickTimeMsRef.current
- ) {
- const extensionCursor = mapCursorToCanvasNormalized(
- {
- cx: p.cx,
- cy: p.cy,
- interactionType: p.interactionType,
- },
- {
- maskRect: baseMaskRef.current,
- canvasWidth: extensionCanvasWidth,
- canvasHeight: extensionCanvasHeight,
- },
- );
- lastEmittedClickTimeMsRef.current = p.timeMs;
- extensionHost.emitEvent({
- type: 'cursor:click',
- timeMs: p.timeMs,
- data: extensionCursor,
- });
- if (extensionCursor) {
- notifyCursorInteraction(
- p.timeMs,
- extensionCursor.cx,
- extensionCursor.cy,
- p.interactionType,
- );
- }
- }
- break;
- }
- }
- }
-
- if (!cursorOverlay) {
- extensionHost.setSmoothedCursor(null);
- }
-
- if (effectsCanvas && effectsCanvas.width > 0 && effectsCanvas.height > 0) {
- const ctx2d = effectsCanvas.getContext("2d");
- if (ctx2d) {
- ctx2d.clearRect(0, 0, effectsCanvas.width, effectsCanvas.height);
-
- const maskRect = baseMaskRef.current;
- const animationState = animationStateRef.current;
- const videoInfo = extensionHost.getVideoInfoSnapshot();
- const rawCursor = getCursorPositionAtTime(cursorTelemetryRef.current, timeMs, {
- maskRect,
- canvasWidth: effectsCanvas.width,
- canvasHeight: effectsCanvas.height,
- });
- const hookParams = {
- width: effectsCanvas.width,
- height: effectsCanvas.height,
- timeMs,
- durationMs: videoInfo?.durationMs ?? 0,
- cursor: smoothedCursorForHooks
- ? {
- cx: smoothedCursorForHooks.cx,
- cy: smoothedCursorForHooks.cy,
- interactionType: rawCursor?.interactionType,
- }
- : rawCursor,
- smoothedCursor: smoothedCursorForHooks,
- videoLayout:
- maskRect.width > 0 && maskRect.height > 0
- ? {
- maskRect: {
- x: maskRect.x,
- y: maskRect.y,
- width: maskRect.width,
- height: maskRect.height,
- },
- borderRadius,
- padding,
- }
- : undefined,
- zoom: {
- scale: animationState.scale,
- focusX: animationState.focusX,
- focusY: animationState.focusY,
- progress: animationState.progress,
- },
- shadow: {
- enabled: Boolean(showShadow) && shadowIntensity > 0,
- intensity: shadowIntensity,
- },
- sceneTransform: {
- scale: animationState.appliedScale,
- x: animationState.x,
- y: animationState.y,
- },
- };
-
- ctx2d.save();
- applyCanvasSceneTransform(ctx2d, {
- scale: animationState.appliedScale,
- x: animationState.x,
- y: animationState.y,
- });
- executeExtensionRenderHooks("post-video", ctx2d, hookParams);
- executeExtensionRenderHooks("post-zoom", ctx2d, hookParams);
- executeExtensionRenderHooks("post-cursor", ctx2d, hookParams);
-
- if (isSeekingRef.current) {
- clearCursorEffects();
- } else {
- executeExtensionCursorEffects(
- ctx2d,
- timeMs,
- effectsCanvas.width,
- effectsCanvas.height,
- {
- zoom: hookParams.zoom,
- sceneTransform: hookParams.sceneTransform,
- videoLayout: hookParams.videoLayout,
- },
- );
- }
- ctx2d.restore();
-
- executeExtensionRenderHooks("post-webcam", ctx2d, hookParams);
- executeExtensionRenderHooks("post-annotations", ctx2d, hookParams);
-
- executeExtensionRenderHooks("final", ctx2d, hookParams);
- }
- }
- };
-
- app.ticker.add(ticker);
- return () => {
- if (app && app.ticker) {
- app.ticker.remove(ticker);
- }
- };
- }, [
- pixiReady,
- videoReady,
- clampFocusToStage,
- applyWebcamBubbleLayout,
- borderRadius,
- padding,
- showShadow,
- shadowIntensity,
- ]);
-
- useEffect(() => {
- const overlay = cursorOverlayRef.current;
- if (!overlay) {
- return;
- }
-
- let cancelled = false;
-
- overlay.setDotRadius(DEFAULT_CURSOR_CONFIG.dotRadius * cursorSize);
- overlay.setSmoothingFactor(cursorSmoothing);
- overlay.setMotionBlur(cursorMotionBlur);
- overlay.setClickBounce(cursorClickBounce);
- overlay.setClickBounceDuration(cursorClickBounceDuration);
- overlay.setSway(cursorSway);
-
- void (async () => {
- try {
- await preloadCursorAssets();
- } catch (error) {
- console.warn("Failed to refresh cursor assets for preview:", error);
- return;
- }
-
- if (cancelled || cursorOverlayRef.current !== overlay) {
- return;
- }
-
- overlay.setStyle(cursorStyle);
- overlay.reset();
- })();
-
- return () => {
- cancelled = true;
- };
- }, [
- cursorStyle,
- cursorSize,
- cursorSmoothing,
- cursorMotionBlur,
- cursorClickBounce,
- cursorClickBounceDuration,
- cursorSway,
- ]);
-
- useEffect(() => {
- let cancelled = false;
- let signature = getContributedCursorStylesSignature();
-
- const refreshSelectedCursorStyle = async () => {
- const overlay = cursorOverlayRef.current;
- if (!overlay) {
- return;
- }
-
- try {
- await preloadCursorAssets();
- } catch (error) {
- console.warn("Failed to refresh contributed cursor styles in preview:", error);
- return;
- }
-
- if (cancelled || cursorOverlayRef.current !== overlay) {
- return;
- }
-
- overlay.setStyle(cursorStyleRef.current);
- overlay.reset();
- };
-
- const unsubscribe = extensionHost.onChange(() => {
- const nextSignature = getContributedCursorStylesSignature();
- if (nextSignature === signature) {
- return;
- }
-
- signature = nextSignature;
- void refreshSelectedCursorStyle();
- });
-
- return () => {
- cancelled = true;
- unsubscribe();
- };
- }, []);
-
- const handleLoadedMetadata = (
- e: React.SyntheticEvent<HTMLVideoElement, Event>,
- ) => {
- const video = e.currentTarget;
- onDurationChange(video.duration);
-
- // Push video info to extension host for query APIs
- extensionHost.setVideoInfo({
- width: video.videoWidth,
- height: video.videoHeight,
- durationMs: Number.isFinite(video.duration) ? video.duration * 1000 : 0,
- fps: 60, // Not available from HTMLVideoElement; default to 60
- });
- const targetTime = clampMediaTimeToDuration(
- currentTime,
- Number.isFinite(video.duration) ? video.duration : null,
- );
- video.currentTime = targetTime;
- video.pause();
- allowPlaybackRef.current = false;
- currentTimeRef.current = targetTime * 1000;
-
- if (videoReadyRafRef.current) {
- cancelAnimationFrame(videoReadyRafRef.current);
- videoReadyRafRef.current = null;
- }
-
- const waitForRenderableFrame = () => {
- const hasDimensions = video.videoWidth > 0 && video.videoHeight > 0;
- const hasData = video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA;
- if (hasDimensions && hasData) {
- videoReadyRafRef.current = null;
- setVideoReady(true);
- return;
- }
- videoReadyRafRef.current = requestAnimationFrame(
- waitForRenderableFrame,
- );
- };
-
- videoReadyRafRef.current = requestAnimationFrame(waitForRenderableFrame);
- };
-
- const [resolvedWallpaper, setResolvedWallpaper] = useState<string | null>(
- null,
- );
- const [resolvedWallpaperKind, setResolvedWallpaperKind] = useState<
- "image" | "video" | "style"
- >("image");
-
- useEffect(() => {
- let mounted = true;
- let revokeResolvedWallpaper = () => {};
- (async () => {
- try {
- if (!wallpaper) {
- const def = await getAssetPath(DEFAULT_WALLPAPER_RELATIVE_PATH);
- if (mounted) {
- setResolvedWallpaper(def);
- setResolvedWallpaperKind("image");
- }
- return;
- }
-
- if (
- wallpaper.startsWith("#") ||
- wallpaper.startsWith("linear-gradient") ||
- wallpaper.startsWith("radial-gradient")
- ) {
- if (mounted) {
- setResolvedWallpaper(wallpaper);
- setResolvedWallpaperKind("style");
- }
- return;
- }
-
- if (isVideoWallpaperSource(wallpaper)) {
- let videoSrc = wallpaper;
- if (wallpaper.startsWith("/") && !wallpaper.startsWith("//")) {
- videoSrc = await getAssetPath(wallpaper.replace(/^\//, ""));
- }
- if (mounted) {
- setResolvedWallpaper(videoSrc);
- setResolvedWallpaperKind("video");
- }
- return;
- }
-
- // If it's a data URL (custom uploaded image), use as-is
- if (wallpaper.startsWith("data:")) {
- if (mounted) {
- setResolvedWallpaper(wallpaper);
- setResolvedWallpaperKind("image");
- }
- return;
- }
-
- if (
- wallpaper.startsWith("http") ||
- wallpaper.startsWith("file://") ||
- wallpaper.startsWith("/")
- ) {
- const renderable = await getRenderableAssetUrl(wallpaper);
- if (mounted) {
- setResolvedWallpaper(renderable);
- setResolvedWallpaperKind("image");
- }
- return;
- }
- const p = await getRenderableAssetUrl(
- await getAssetPath(wallpaper.replace(/^\//, "")),
- );
- if (mounted) {
- setResolvedWallpaper(p);
- setResolvedWallpaperKind("image");
- }
- } catch (err) {
- if (mounted) {
- setResolvedWallpaper(wallpaper || DEFAULT_WALLPAPER_PATH);
- setResolvedWallpaperKind(
- isVideoWallpaperSource(wallpaper || "") ? "video" : "image",
- );
- }
- }
- })();
- return () => {
- mounted = false;
- revokeResolvedWallpaper();
- };
- }, [wallpaper]);
-
- useEffect(() => {
- return () => {
- if (videoReadyRafRef.current) {
- cancelAnimationFrame(videoReadyRafRef.current);
- videoReadyRafRef.current = null;
- }
- };
- }, []);
-
- const isImageUrl = resolvedWallpaperKind === "image" && Boolean(
- resolvedWallpaper &&
- (resolvedWallpaper.startsWith("file://") ||
- resolvedWallpaper.startsWith("http") ||
- resolvedWallpaper.startsWith("/") ||
- resolvedWallpaper.startsWith("data:")),
- );
- const backgroundStyle = isImageUrl
- ? { backgroundImage: `url(${resolvedWallpaper || ""})` }
- : resolvedWallpaperKind === "video"
- ? {}
- : { background: resolvedWallpaper || "" };
-
- const nativeAspectRatio = (() => {
- const locked = lockedVideoDimensionsRef.current;
- if (locked) {
- return getEffectiveNativeAspectRatio(locked, cropRegion);
- }
- const video = videoRef.current;
- if (video && video.videoHeight > 0 && video.videoWidth > 0) {
- return getEffectiveNativeAspectRatio(
- {
- width: video.videoWidth,
- height: video.videoHeight,
- },
- cropRegion,
- );
- }
- return 16 / 9;
- })();
-
- return (
- <div
- className="relative rounded-sm overflow-hidden"
- style={{
- width: "100%",
- aspectRatio: formatAspectRatioForCSS(aspectRatio, nativeAspectRatio),
- }}
- >
- {/* Background layer */}
- {resolvedWallpaperKind === "video" && resolvedWallpaper ? (
- <video
- key={resolvedWallpaper}
- ref={bgVideoRef}
- className="absolute inset-0 h-full w-full object-cover"
- src={resolvedWallpaper}
- muted
- loop
- playsInline
- style={{
- filter: backgroundBlur > 0 ? `blur(${backgroundBlur}px)` : "none",
- }}
- />
- ) : (
- <div
- className="absolute inset-0 bg-cover bg-center"
- style={{
- ...backgroundStyle,
- filter: backgroundBlur > 0 ? `blur(${backgroundBlur}px)` : "none",
- }}
- />
- )}
- <div
- ref={containerRef}
- className="absolute inset-0"
- style={{
- filter:
- showShadow && shadowIntensity > 0
- ? `drop-shadow(0 ${shadowIntensity * 12}px ${shadowIntensity * 48}px rgba(0,0,0,${shadowIntensity * 0.7})) drop-shadow(0 ${shadowIntensity * 4}px ${shadowIntensity * 16}px rgba(0,0,0,${shadowIntensity * 0.5})) drop-shadow(0 ${shadowIntensity * 2}px ${shadowIntensity * 8}px rgba(0,0,0,${shadowIntensity * 0.3}))`
- : "none",
- }}
- />
- {/* Canvas overlay for extension cursor effects (drawn via Canvas 2D API) */}
- <canvas
- ref={cursorEffectsCanvasRef}
- className="absolute inset-0 w-full h-full pointer-events-none"
- style={{ zIndex: 1 }}
- />
- {/* Only render overlay after PIXI and video are fully initialized */}
- {pixiReady && videoReady && (
- <div
- ref={overlayRef}
- className="absolute inset-0 select-none"
- style={{ pointerEvents: "none" }}
- onPointerDown={handleOverlayPointerDown}
- onPointerMove={handleOverlayPointerMove}
- onPointerUp={handleOverlayPointerUp}
- onPointerLeave={handleOverlayPointerLeave}
- >
- <div
- ref={focusIndicatorRef}
- className="absolute rounded-md border border-[#2563EB]/80 bg-[#2563EB]/20 shadow-[0_0_0_1px_rgba(37,99,235,0.35)]"
- style={{ display: "none", pointerEvents: "none" }}
- />
- {webcam && webcamVideoPath ? (
- <div
- ref={webcamBubbleRef}
- className="absolute"
- style={{
- display: webcam.enabled ? "block" : "none",
- pointerEvents: "none",
- }}
- >
- <div
- ref={webcamBubbleInnerRef}
- className="h-full w-full overflow-hidden bg-black/80"
- >
- <video
- ref={webcamVideoRef}
- src={webcamVideoPath}
- className="h-full w-full object-cover"
- muted
- playsInline
- preload="auto"
- style={{ transform: webcam.mirror ? "scaleX(-1)" : undefined }}
- />
- </div>
- </div>
- ) : null}
- {activeCaptionLayout && autoCaptionSettings ? (
- <div
- className="pointer-events-none absolute inset-x-0 flex justify-center"
- style={{
- bottom: `${autoCaptionSettings.bottomOffset}%`,
- }}
- >
- <div
- style={{
- maxWidth: `${autoCaptionSettings.maxWidth}%`,
- opacity: activeCaptionLayout.opacity,
- transform: `translateY(${activeCaptionLayout.translateY}px) scale(${activeCaptionLayout.scale})`,
- transformOrigin: "center bottom",
- filter: "drop-shadow(0 12px 30px rgba(0, 0, 0, 0.28))",
- }}
- >
- <div
- ref={captionBoxRef}
- style={{
- backgroundColor: `rgba(0, 0, 0, ${autoCaptionSettings.backgroundOpacity})`,
- fontFamily: getDefaultCaptionFontFamily(),
- fontSize: `${getCaptionScaledFontSize(
- autoCaptionSettings.fontSize,
- overlayRef.current?.clientWidth || 960,
- autoCaptionSettings.maxWidth,
- )}px`,
- lineHeight: CAPTION_LINE_HEIGHT,
- textAlign: "center",
- fontWeight: CAPTION_FONT_WEIGHT,
- padding: `${getCaptionPadding(
- getCaptionScaledFontSize(
- autoCaptionSettings.fontSize,
- overlayRef.current?.clientWidth || 960,
- autoCaptionSettings.maxWidth,
- ),
- ).y}px ${getCaptionPadding(
- getCaptionScaledFontSize(
- autoCaptionSettings.fontSize,
- overlayRef.current?.clientWidth || 960,
- autoCaptionSettings.maxWidth,
- ),
- ).x}px`,
- borderRadius: `${getCaptionScaledRadius(
- autoCaptionSettings.boxRadius,
- getCaptionScaledFontSize(
- autoCaptionSettings.fontSize,
- overlayRef.current?.clientWidth || 960,
- autoCaptionSettings.maxWidth,
- ),
- )}px`,
- boxSizing: "border-box",
- }}
- >
- {activeCaptionLayout.visibleLines.map((line) => (
- <div
- key={`${activeCaptionLayout.blockKey}-${line.startWordIndex}`}
- style={{
- display: "flex",
- justifyContent: "center",
- flexWrap: "nowrap",
- whiteSpace: "nowrap",
- }}
- >
- {line.words.map((word) => {
- const visualState = getCaptionWordVisualState(
- activeCaptionLayout.hasWordTimings,
- word.state,
- );
-
- return (
- <span
- key={`${activeCaptionLayout.blockKey}-${word.index}`}
- style={{
- display: "inline-block",
- whiteSpace: "pre",
- color: visualState.isInactive
- ? autoCaptionSettings.inactiveTextColor
- : autoCaptionSettings.textColor,
- opacity: visualState.opacity,
- }}
- >
- {`${word.leadingSpace ? " " : ""}${word.text}`}
- </span>
- );
- })}
- </div>
- ))}
- </div>
- </div>
- </div>
- ) : null}
- {(() => {
- const filtered = (annotationRegions || []).filter(
- (annotation) => {
- if (
- typeof annotation.startMs !== "number" ||
- typeof annotation.endMs !== "number"
- )
- return false;
-
- if (annotation.id === selectedAnnotationId) return true;
-
- const timeMs = Math.round(currentTime * 1000);
- return (
- timeMs >= annotation.startMs && timeMs <= annotation.endMs
- );
- },
- );
-
- // Sort by z-index (lowest to highest) so higher z-index renders on top
- const sorted = [...filtered].sort((a, b) => a.zIndex - b.zIndex);
-
- // Handle click-through cycling: when clicking same annotation, cycle to next
- const handleAnnotationClick = (clickedId: string) => {
- if (!onSelectAnnotation) return;
-
- // If clicking on already selected annotation and there are multiple overlapping
- if (clickedId === selectedAnnotationId && sorted.length > 1) {
- // Find current index and cycle to next
- const currentIndex = sorted.findIndex(
- (a) => a.id === clickedId,
- );
- const nextIndex = (currentIndex + 1) % sorted.length;
- onSelectAnnotation(sorted[nextIndex].id);
- } else {
- // First click or clicking different annotation
- onSelectAnnotation(clickedId);
- }
- };
-
- return sorted.map((annotation) => (
- <AnnotationOverlay
- key={annotation.id}
- annotation={annotation}
- isSelected={annotation.id === selectedAnnotationId}
- containerWidth={overlayRef.current?.clientWidth || 800}
- containerHeight={overlayRef.current?.clientHeight || 600}
- onPositionChange={(id, position) =>
- onAnnotationPositionChange?.(id, position)
- }
- onSizeChange={(id, size) =>
- onAnnotationSizeChange?.(id, size)
- }
- onClick={handleAnnotationClick}
- zIndex={annotation.zIndex}
- isSelectedBoost={annotation.id === selectedAnnotationId}
- />
- ));
- })()}
- </div>
- )}
- <video
- ref={videoRef}
- src={videoPath}
- className="hidden"
- preload="metadata"
- playsInline
- onLoadedMetadata={handleLoadedMetadata}
- onDurationChange={(e) => {
- onDurationChange(e.currentTarget.duration);
- }}
- onError={() => onError("Failed to load video")}
- />
- </div>
- );
- },
+ (
+ {
+ videoPath,
+ onDurationChange,
+ onPreviewReadyChange,
+ onTimeUpdate,
+ currentTime,
+ onPlayStateChange,
+ onError,
+ wallpaper,
+ zoomRegions,
+ selectedZoomId,
+ onSelectZoom,
+ onZoomFocusChange,
+ isPlaying,
+ showShadow,
+ shadowIntensity = 0,
+ backgroundBlur = 0,
+ zoomMotionBlur = 0,
+ connectZooms = true,
+ zoomInDurationMs = DEFAULT_ZOOM_IN_DURATION_MS,
+ zoomInOverlapMs = DEFAULT_ZOOM_IN_OVERLAP_MS,
+ zoomOutDurationMs = DEFAULT_ZOOM_OUT_DURATION_MS,
+ connectedZoomGapMs = DEFAULT_CONNECTED_ZOOM_GAP_MS,
+ connectedZoomDurationMs = DEFAULT_CONNECTED_ZOOM_DURATION_MS,
+ zoomInEasing = DEFAULT_ZOOM_IN_EASING,
+ zoomOutEasing = DEFAULT_ZOOM_OUT_EASING,
+ connectedZoomEasing = DEFAULT_CONNECTED_ZOOM_EASING,
+ borderRadius = 0,
+ padding = 50,
+ frame = null,
+ cropRegion,
+ webcam,
+ webcamVideoPath,
+ trimRegions = [],
+ speedRegions = [],
+ aspectRatio,
+ annotationRegions = [],
+ autoCaptions = [],
+ autoCaptionSettings,
+ selectedAnnotationId,
+ onSelectAnnotation,
+ onAnnotationPositionChange,
+ onAnnotationSizeChange,
+ cursorTelemetry = [],
+ showCursor = false,
+ cursorStyle = "tahoe",
+ cursorSize = DEFAULT_CURSOR_SIZE,
+ cursorSmoothing = DEFAULT_CURSOR_SMOOTHING,
+ zoomSmoothness = 0.5,
+ zoomClassicMode = false,
+ cursorMotionBlur = DEFAULT_CURSOR_MOTION_BLUR,
+ cursorClickBounce = DEFAULT_CURSOR_CLICK_BOUNCE,
+ cursorClickBounceDuration = DEFAULT_CURSOR_CLICK_BOUNCE_DURATION,
+ cursorSway = DEFAULT_CURSOR_SWAY,
+ volume = 1,
+ },
+ ref,
+ ) => {
+ const videoRef = useRef<HTMLVideoElement | null>(null);
+ const containerRef = useRef<HTMLDivElement | null>(null);
+ const appRef = useRef<Application | null>(null);
+ const videoSpriteRef = useRef<Sprite | null>(null);
+ const videoContainerRef = useRef<Container | null>(null);
+ const cursorContainerRef = useRef<Container | null>(null);
+ const cameraContainerRef = useRef<Container | null>(null);
+ const timeUpdateAnimationRef = useRef<number | null>(null);
+ const [pixiReady, setPixiReady] = useState(false);
+ const [videoReady, setVideoReady] = useState(false);
+ const overlayRef = useRef<HTMLDivElement | null>(null);
+ const focusIndicatorRef = useRef<HTMLDivElement | null>(null);
+ const webcamVideoRef = useRef<HTMLVideoElement | null>(null);
+ const webcamBubbleRef = useRef<HTMLDivElement | null>(null);
+ const webcamBubbleInnerRef = useRef<HTMLDivElement | null>(null);
+ const captionBoxRef = useRef<HTMLDivElement | null>(null);
+ const currentTimeRef = useRef(0);
+ const zoomRegionsRef = useRef<ZoomRegion[]>([]);
+ const selectedZoomIdRef = useRef<string | null>(null);
+ const animationStateRef = useRef<PlaybackAnimationState>(createPlaybackAnimationState());
+ const blurFilterRef = useRef<BlurFilter | null>(null);
+ const motionBlurFilterRef = useRef<MotionBlurFilter | null>(null);
+ const isDraggingFocusRef = useRef(false);
+ const stageSizeRef = useRef({ width: 0, height: 0 });
+ const videoSizeRef = useRef({ width: 0, height: 0 });
+ const baseScaleRef = useRef(1);
+ const baseOffsetRef = useRef({ x: 0, y: 0 });
+ const baseMaskRef = useRef<{
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ sourceCrop?: {
+ x: number;
+ y: number;
+ width: number;
+ height: number;
+ };
+ }>({ x: 0, y: 0, width: 0, height: 0 });
+ const cropBoundsRef = useRef({ startX: 0, endX: 0, startY: 0, endY: 0 });
+ const maskGraphicsRef = useRef<Graphics | null>(null);
+ const frameSpriteRef = useRef<Sprite | null>(null);
+ const frameContainerRef = useRef<Container | null>(null);
+ const frameIdRef = useRef<string | null>(frame);
+ const isPlayingRef = useRef(isPlaying);
+ const isSeekingRef = useRef(false);
+ const allowPlaybackRef = useRef(false);
+ const lockedVideoDimensionsRef = useRef<{
+ width: number;
+ height: number;
+ } | null>(null);
+ const layoutVideoContentRef = useRef<(() => void) | null>(null);
+ const trimRegionsRef = useRef<TrimRegion[]>([]);
+ const speedRegionsRef = useRef<SpeedRegion[]>([]);
+ const lastWebcamSyncTimeRef = useRef<number | null>(null);
+ const bgVideoRef = useRef<HTMLVideoElement | null>(null);
+ const zoomMotionBlurRef = useRef(zoomMotionBlur);
+ const connectZoomsRef = useRef(connectZooms);
+ const zoomInDurationMsRef = useRef(zoomInDurationMs);
+ const zoomInOverlapMsRef = useRef(zoomInOverlapMs);
+ const zoomOutDurationMsRef = useRef(zoomOutDurationMs);
+ const connectedZoomGapMsRef = useRef(connectedZoomGapMs);
+ const connectedZoomDurationMsRef = useRef(connectedZoomDurationMs);
+ const zoomInEasingRef = useRef(zoomInEasing);
+ const zoomOutEasingRef = useRef(zoomOutEasing);
+ const connectedZoomEasingRef = useRef(connectedZoomEasing);
+ const videoReadyRafRef = useRef<number | null>(null);
+ const cursorOverlayRef = useRef<PixiCursorOverlay | null>(null);
+ const cursorEffectsCanvasRef = useRef<HTMLCanvasElement | null>(null);
+ const cursorTelemetryRef = useRef<CursorTelemetryPoint[]>([]);
+ const showCursorRef = useRef(showCursor);
+ const cursorSizeRef = useRef(cursorSize);
+ const cursorStyleRef = useRef(cursorStyle);
+ const cursorSmoothingRef = useRef(cursorSmoothing);
+ const cursorMotionBlurRef = useRef(cursorMotionBlur);
+ const cursorClickBounceRef = useRef(cursorClickBounce);
+ const cursorClickBounceDurationRef = useRef(cursorClickBounceDuration);
+ const cursorSwayRef = useRef(cursorSway);
+ const lastEmittedClickTimeMsRef = useRef(-1);
+
+ // Spring animation state for smooth zoom transitions
+ const springScaleRef = useRef<SpringState>(createSpringState(1));
+ const springXRef = useRef<SpringState>(createSpringState(0));
+ const springYRef = useRef<SpringState>(createSpringState(0));
+ const lastTickTimeRef = useRef<number | null>(null);
+ const zoomSmoothnessRef = useRef(zoomSmoothness);
+ const zoomClassicModeRef = useRef(zoomClassicMode);
+ const cursorFollowCameraRef = useRef<CursorFollowCameraState>(
+ createCursorFollowCameraState(),
+ );
+
+ const activeCaptionLayout = useMemo(() => {
+ if (
+ !autoCaptionSettings?.enabled ||
+ autoCaptions.length === 0 ||
+ typeof document === "undefined"
+ ) {
+ return null;
+ }
+
+ const overlayWidth = overlayRef.current?.clientWidth || 960;
+ const fontSize = getCaptionScaledFontSize(
+ autoCaptionSettings.fontSize,
+ overlayWidth,
+ autoCaptionSettings.maxWidth,
+ );
+ const maxTextWidthPx = getCaptionTextMaxWidth(
+ overlayWidth,
+ autoCaptionSettings.maxWidth,
+ fontSize,
+ );
+ const measurementCanvas = document.createElement("canvas");
+ const measurementContext = measurementCanvas.getContext("2d");
+ if (!measurementContext) {
+ return null;
+ }
+
+ measurementContext.font = `${CAPTION_FONT_WEIGHT} ${fontSize}px ${getDefaultCaptionFontFamily()}`;
+
+ return buildActiveCaptionLayout({
+ cues: autoCaptions,
+ timeMs: Math.round(currentTime * 1000),
+ settings: autoCaptionSettings,
+ maxWidthPx: maxTextWidthPx,
+ measureText: (text) => measurementContext.measureText(text).width,
+ });
+ }, [autoCaptionSettings, autoCaptions, currentTime]);
+
+ useEffect(() => {
+ const captionBox = captionBoxRef.current;
+ if (!captionBox || !activeCaptionLayout || !autoCaptionSettings) {
+ if (captionBox) {
+ captionBox.style.clipPath = "";
+ captionBox.style.removeProperty("-webkit-clip-path");
+ }
+ return;
+ }
+
+ const frame = requestAnimationFrame(() => {
+ const width = captionBox.offsetWidth;
+ const height = captionBox.offsetHeight;
+ if (width <= 0 || height <= 0) {
+ return;
+ }
+
+ const fontSize = getCaptionScaledFontSize(
+ autoCaptionSettings.fontSize,
+ overlayRef.current?.clientWidth || 960,
+ autoCaptionSettings.maxWidth,
+ );
+
+ const squirclePath = getSquircleSvgPath({
+ x: 0,
+ y: 0,
+ width,
+ height,
+ radius: getCaptionScaledRadius(autoCaptionSettings.boxRadius, fontSize),
+ });
+ captionBox.style.clipPath = `path('${squirclePath}')`;
+ captionBox.style.setProperty("-webkit-clip-path", `path('${squirclePath}')`);
+ });
+
+ return () => cancelAnimationFrame(frame);
+ }, [activeCaptionLayout, autoCaptionSettings]);
+ const motionBlurStateRef = useRef<MotionBlurState>(createMotionBlurState());
+
+ const applyWebcamBubbleLayout = useCallback(
+ (zoomScale: number) => {
+ const bubble = webcamBubbleRef.current;
+ const bubbleInner = webcamBubbleInnerRef.current;
+ const overlay = overlayRef.current;
+ if (!bubble || !bubbleInner || !overlay || !webcam?.enabled || !webcamVideoPath) {
+ if (bubble) {
+ bubble.style.display = "none";
+ }
+ return;
+ }
+
+ const margin = webcam.margin ?? 24;
+ const scaledSize = getWebcamOverlaySizePx({
+ containerWidth: overlay.clientWidth,
+ containerHeight: overlay.clientHeight,
+ sizePercent: webcam.size ?? DEFAULT_WEBCAM_SIZE,
+ margin,
+ zoomScale,
+ reactToZoom: webcam.reactToZoom ?? DEFAULT_WEBCAM_REACT_TO_ZOOM,
+ });
+ const { x, y } = getWebcamOverlayPosition({
+ containerWidth: overlay.clientWidth,
+ containerHeight: overlay.clientHeight,
+ size: scaledSize,
+ margin,
+ positionPreset: webcam.positionPreset ?? webcam.corner,
+ positionX: webcam.positionX ?? 1,
+ positionY: webcam.positionY ?? 1,
+ legacyCorner: webcam.corner,
+ });
+
+ bubble.style.display = "block";
+ bubble.style.left = `${x}px`;
+ bubble.style.top = `${y}px`;
+ bubble.style.width = `${scaledSize}px`;
+ bubble.style.height = `${scaledSize}px`;
+ const squirclePath = getSquircleSvgPath({
+ x: 0,
+ y: 0,
+ width: scaledSize,
+ height: scaledSize,
+ radius: webcam.cornerRadius ?? DEFAULT_WEBCAM_CORNER_RADIUS,
+ });
+ bubble.style.filter = `drop-shadow(0 ${Math.round(scaledSize * 0.06)}px ${Math.round(
+ scaledSize * 0.22,
+ )}px rgba(0, 0, 0, ${webcam.shadow ?? DEFAULT_WEBCAM_SHADOW}))`;
+ bubble.style.borderRadius = "0px";
+ bubble.style.boxShadow = "none";
+
+ bubbleInner.style.borderRadius = "0px";
+ bubbleInner.style.clipPath = `path('${squirclePath}')`;
+ bubbleInner.style.setProperty("-webkit-clip-path", `path('${squirclePath}')`);
+ },
+ [webcam, webcamVideoPath],
+ );
+
+ const clampFocusToStage = useCallback((focus: ZoomFocus, depth: ZoomDepth) => {
+ return clampFocusToStageUtil(focus, depth, stageSizeRef.current);
+ }, []);
+
+ const updateOverlayForRegion = useCallback(
+ (region: ZoomRegion | null, focusOverride?: ZoomFocus) => {
+ const overlayEl = overlayRef.current;
+ const indicatorEl = focusIndicatorRef.current;
+
+ if (!overlayEl || !indicatorEl) {
+ return;
+ }
+
+ // Update stage size from overlay dimensions
+ const stageWidth = overlayEl.clientWidth;
+ const stageHeight = overlayEl.clientHeight;
+ if (stageWidth && stageHeight) {
+ stageSizeRef.current = { width: stageWidth, height: stageHeight };
+ }
+
+ updateOverlayIndicator({
+ overlayEl,
+ indicatorEl,
+ region,
+ focusOverride,
+ baseMask: baseMaskRef.current,
+ isPlaying: isPlayingRef.current,
+ });
+ },
+ [],
+ );
+
+ const layoutVideoContent = useCallback(() => {
+ const container = containerRef.current;
+ const app = appRef.current;
+ const videoSprite = videoSpriteRef.current;
+ const maskGraphics = maskGraphicsRef.current;
+ const videoElement = videoRef.current;
+ const cameraContainer = cameraContainerRef.current;
+
+ if (
+ !container ||
+ !app ||
+ !videoSprite ||
+ !maskGraphics ||
+ !videoElement ||
+ !cameraContainer
+ ) {
+ return;
+ }
+
+ // Lock video dimensions on first layout to prevent resize issues
+ if (
+ !lockedVideoDimensionsRef.current &&
+ videoElement.videoWidth > 0 &&
+ videoElement.videoHeight > 0
+ ) {
+ lockedVideoDimensionsRef.current = {
+ width: videoElement.videoWidth,
+ height: videoElement.videoHeight,
+ };
+ }
+
+ // Look up device frame insets so layout centers the full frame (video + bezels)
+ let frameInsets: { top: number; right: number; bottom: number; left: number } | null =
+ null;
+ if (frame) {
+ const frames = extensionHost.getFrames();
+ const frameData = frames.find((f) => f.id === frame);
+ if (frameData?.screenInsets) {
+ frameInsets = frameData.screenInsets;
+ }
+ }
+
+ const result = layoutVideoContentUtil({
+ container,
+ app,
+ videoSprite,
+ maskGraphics,
+ videoElement,
+ cropRegion,
+ lockedVideoDimensions: lockedVideoDimensionsRef.current,
+ borderRadius,
+ padding,
+ frameInsets,
+ });
+
+ if (result) {
+ stageSizeRef.current = result.stageSize;
+ videoSizeRef.current = result.videoSize;
+ baseScaleRef.current = result.baseScale;
+ baseOffsetRef.current = result.baseOffset;
+ baseMaskRef.current = result.maskRect;
+ cropBoundsRef.current = result.cropBounds;
+
+ // Sync extension cursor effects canvas resolution with renderer
+ const effectsCanvas = cursorEffectsCanvasRef.current;
+ if (effectsCanvas) {
+ const w = result.stageSize.width;
+ const h = result.stageSize.height;
+ if (effectsCanvas.width !== w || effectsCanvas.height !== h) {
+ effectsCanvas.width = w;
+ effectsCanvas.height = h;
+ }
+ }
+
+ // Push layout info to extension host for query APIs
+ extensionHost.setVideoLayout({
+ maskRect: {
+ x: result.maskRect.x,
+ y: result.maskRect.y,
+ width: result.maskRect.width,
+ height: result.maskRect.height,
+ },
+ canvasWidth: result.stageSize.width,
+ canvasHeight: result.stageSize.height,
+ borderRadius,
+ padding,
+ });
+ extensionHost.setShadowConfig({
+ enabled: Boolean(showShadow) && shadowIntensity > 0,
+ intensity: shadowIntensity,
+ });
+
+ // Position device frame sprite to fill the stage
+ const frameSprite = frameSpriteRef.current;
+ if (frameSprite && frame) {
+ const frames = extensionHost.getFrames();
+ const frameData = frames.find((f) => f.id === frame);
+ if (frameData) {
+ const maskRect = result.maskRect;
+ const insets = frameData.screenInsets;
+ if (insets) {
+ // Frame is larger than screen area — compute full frame size from insets
+ const screenW = maskRect.width;
+ const screenH = maskRect.height;
+ const frameW = screenW / (1 - insets.left - insets.right);
+ const frameH = screenH / (1 - insets.top - insets.bottom);
+ const frameX = maskRect.x - insets.left * frameW;
+ const frameY = maskRect.y - insets.top * frameH;
+ frameSprite.position.set(frameX, frameY);
+ frameSprite.width = frameW;
+ frameSprite.height = frameH;
+ } else {
+ frameSprite.position.set(maskRect.x, maskRect.y);
+ frameSprite.width = maskRect.width;
+ frameSprite.height = maskRect.height;
+ }
+ }
+ }
+
+ // Reset camera container to identity
+ cameraContainer.scale.set(1);
+ cameraContainer.position.set(0, 0);
+
+ const selectedId = selectedZoomIdRef.current;
+ const activeRegion = selectedId
+ ? (zoomRegionsRef.current.find((region) => region.id === selectedId) ?? null)
+ : null;
+
+ updateOverlayForRegion(activeRegion);
+ applyWebcamBubbleLayout(animationStateRef.current.appliedScale || 1);
+ }
+ }, [
+ updateOverlayForRegion,
+ cropRegion,
+ borderRadius,
+ padding,
+ frame,
+ showShadow,
+ shadowIntensity,
+ applyWebcamBubbleLayout,
+ ]);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) return;
+
+ const nextVolume = Math.max(0, Math.min(1, volume));
+ video.volume = nextVolume;
+ video.muted = nextVolume <= 0.001;
+ }, [volume, videoPath]);
+
+ useEffect(() => {
+ layoutVideoContentRef.current = layoutVideoContent;
+ }, [layoutVideoContent]);
+
+ // Sync device frame ref
+ useEffect(() => {
+ frameIdRef.current = frame;
+ extensionHost.setActiveFrame(frame ?? null);
+ }, [frame]);
+
+ // Manage device frame sprite
+ useEffect(() => {
+ const frameContainer = frameContainerRef.current;
+ if (!frameContainer) return;
+
+ // Clear existing frame sprite
+ if (frameSpriteRef.current) {
+ frameContainer.removeChild(frameSpriteRef.current);
+ frameSpriteRef.current.destroy();
+ frameSpriteRef.current = null;
+ }
+
+ if (!frame) {
+ layoutVideoContentRef.current?.();
+ return;
+ }
+
+ let cancelled = false;
+
+ function tryLoadFrame() {
+ if (cancelled) return;
+ const container = frameContainerRef.current;
+ if (!container) return false;
+ const frames = extensionHost.getFrames();
+ const frameData = frames.find((f) => f.id === frame);
+ if (!frameData) return false;
+
+ if (frameData.draw) {
+ // Resolution-independent: draw at a reasonable size, Pixi handles the rest
+ const drawW = 1920;
+ const drawH = 1080;
+ const canvas = document.createElement("canvas");
+ canvas.width = drawW;
+ canvas.height = drawH;
+ const ctx = canvas.getContext("2d");
+ if (ctx) frameData.draw(ctx, drawW, drawH);
+ if (cancelled || frameIdRef.current !== frame) return true;
+ const texture = Texture.from(canvas);
+ const sprite = new Sprite(texture);
+ frameSpriteRef.current = sprite;
+ container.addChild(sprite);
+ layoutVideoContentRef.current?.();
+ } else {
+ const img = new Image();
+ img.onload = () => {
+ if (cancelled || frameIdRef.current !== frame) return;
+ const texture = Texture.from(img);
+ const sprite = new Sprite(texture);
+ frameSpriteRef.current = sprite;
+ container.addChild(sprite);
+ layoutVideoContentRef.current?.();
+ };
+ img.src = frameData.filePath;
+ }
+ return true;
+ }
+
+ // Try immediately; if extension hasn't registered frames yet,
+ // listen for changes and retry once they become available.
+ if (!tryLoadFrame()) {
+ const unsub = extensionHost.onChange(() => {
+ if (tryLoadFrame()) unsub();
+ });
+ return () => {
+ cancelled = true;
+ unsub();
+ };
+ }
+
+ return () => {
+ cancelled = true;
+ };
+ }, [frame]);
+
+ const selectedZoom = useMemo(() => {
+ if (!selectedZoomId) return null;
+ return zoomRegions.find((region) => region.id === selectedZoomId) ?? null;
+ }, [zoomRegions, selectedZoomId]);
+
+ useImperativeHandle(ref, () => ({
+ video: videoRef.current,
+ app: appRef.current,
+ videoSprite: videoSpriteRef.current,
+ videoContainer: videoContainerRef.current,
+ containerRef,
+ play: async () => {
+ const vid = videoRef.current;
+ if (!vid) return;
+ try {
+ allowPlaybackRef.current = true;
+ await vid.play();
+ } catch (error) {
+ allowPlaybackRef.current = false;
+ throw error;
+ }
+ },
+ pause: () => {
+ const video = videoRef.current;
+ allowPlaybackRef.current = false;
+ if (!video) {
+ return;
+ }
+ video.pause();
+ },
+ refreshFrame: async () => {
+ const video = videoRef.current;
+ if (!video || Number.isNaN(video.currentTime)) {
+ return;
+ }
+
+ const restoreTime = video.currentTime;
+ const duration = Number.isFinite(video.duration) ? video.duration : 0;
+ const epsilon =
+ duration > 0 ? Math.min(1 / 120, duration / 1000 || 1 / 120) : 1 / 120;
+ const nudgeTarget =
+ restoreTime > epsilon
+ ? restoreTime - epsilon
+ : Math.min(duration || restoreTime + epsilon, restoreTime + epsilon);
+
+ if (Math.abs(nudgeTarget - restoreTime) < 0.000001) {
+ return;
+ }
+
+ await new Promise<void>((resolve) => {
+ const handleFirstSeeked = () => {
+ video.removeEventListener("seeked", handleFirstSeeked);
+ const handleSecondSeeked = () => {
+ video.removeEventListener("seeked", handleSecondSeeked);
+ video.pause();
+ resolve();
+ };
+
+ video.addEventListener("seeked", handleSecondSeeked, {
+ once: true,
+ });
+ video.currentTime = restoreTime;
+ };
+
+ video.addEventListener("seeked", handleFirstSeeked, { once: true });
+ video.currentTime = nudgeTarget;
+ });
+ },
+ }));
+
+ const updateFocusFromClientPoint = (clientX: number, clientY: number) => {
+ const overlayEl = overlayRef.current;
+ if (!overlayEl) return;
+
+ const regionId = selectedZoomIdRef.current;
+ if (!regionId) return;
+
+ const region = zoomRegionsRef.current.find((r) => r.id === regionId);
+ if (!region) return;
+
+ const rect = overlayEl.getBoundingClientRect();
+ const stageWidth = rect.width;
+ const stageHeight = rect.height;
+
+ if (!stageWidth || !stageHeight) {
+ return;
+ }
+
+ stageSizeRef.current = { width: stageWidth, height: stageHeight };
+
+ const localX = clientX - rect.left;
+ const localY = clientY - rect.top;
+ const baseMask = baseMaskRef.current;
+
+ const unclampedFocus: ZoomFocus = {
+ cx: clamp01((localX - baseMask.x) / Math.max(1, baseMask.width)),
+ cy: clamp01((localY - baseMask.y) / Math.max(1, baseMask.height)),
+ };
+ const clampedFocus = clampFocusToStage(unclampedFocus, region.depth);
+
+ onZoomFocusChange(region.id, clampedFocus);
+ updateOverlayForRegion({ ...region, focus: clampedFocus }, clampedFocus);
+ };
+
+ const handleOverlayPointerDown = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (isPlayingRef.current) return;
+ const regionId = selectedZoomIdRef.current;
+ if (!regionId) return;
+ const region = zoomRegionsRef.current.find((r) => r.id === regionId);
+ if (!region || region.mode !== "manual") return;
+ onSelectZoom(region.id);
+ event.preventDefault();
+ isDraggingFocusRef.current = true;
+ event.currentTarget.setPointerCapture(event.pointerId);
+ updateFocusFromClientPoint(event.clientX, event.clientY);
+ };
+
+ const handleOverlayPointerMove = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (!isDraggingFocusRef.current) return;
+ event.preventDefault();
+ updateFocusFromClientPoint(event.clientX, event.clientY);
+ };
+
+ const endFocusDrag = (event: React.PointerEvent<HTMLDivElement>) => {
+ if (!isDraggingFocusRef.current) return;
+ isDraggingFocusRef.current = false;
+ try {
+ event.currentTarget.releasePointerCapture(event.pointerId);
+ } catch {
+ /* Pointer capture may already be released during drag cleanup. */
+ }
+ };
+
+ const handleOverlayPointerUp = (event: React.PointerEvent<HTMLDivElement>) => {
+ endFocusDrag(event);
+ };
+
+ const handleOverlayPointerLeave = (event: React.PointerEvent<HTMLDivElement>) => {
+ endFocusDrag(event);
+ };
+
+ useEffect(() => {
+ zoomRegionsRef.current = zoomRegions;
+ }, [zoomRegions]);
+
+ useEffect(() => {
+ selectedZoomIdRef.current = selectedZoomId;
+ }, [selectedZoomId]);
+
+ useEffect(() => {
+ isPlayingRef.current = isPlaying;
+ extensionHost.emitEvent({
+ type: isPlaying ? "playback:play" : "playback:pause",
+ timeMs: currentTimeRef.current,
+ });
+ // Snap springs to current position when pausing so scrubbing is instant
+ if (!isPlaying) {
+ resetSpringState(springScaleRef.current);
+ resetSpringState(springXRef.current);
+ resetSpringState(springYRef.current);
+ resetCursorFollowCamera(cursorFollowCameraRef.current);
+ lastTickTimeRef.current = null;
+ }
+ const bgVideo = bgVideoRef.current;
+ if (bgVideo) {
+ if (isPlaying) {
+ bgVideo.play().catch(() => undefined);
+ } else {
+ bgVideo.pause();
+ }
+ }
+ }, [isPlaying]);
+
+ // Sync background video wallpaper with timeline scrubbing
+ useEffect(() => {
+ const bgVideo = bgVideoRef.current;
+ if (!bgVideo) return;
+ if (!isPlaying && bgVideo.duration && Number.isFinite(bgVideo.duration)) {
+ bgVideo.currentTime = currentTime % bgVideo.duration;
+ }
+ }, [currentTime, isPlaying]);
+
+ useEffect(() => {
+ trimRegionsRef.current = trimRegions;
+ }, [trimRegions]);
+
+ useEffect(() => {
+ speedRegionsRef.current = speedRegions;
+ }, [speedRegions]);
+
+ useEffect(() => {
+ zoomMotionBlurRef.current = zoomMotionBlur;
+ }, [zoomMotionBlur]);
+
+ useEffect(() => {
+ connectZoomsRef.current = connectZooms;
+ }, [connectZooms]);
+
+ useEffect(() => {
+ zoomInDurationMsRef.current = zoomInDurationMs;
+ }, [zoomInDurationMs]);
+
+ useEffect(() => {
+ zoomInOverlapMsRef.current = zoomInOverlapMs;
+ }, [zoomInOverlapMs]);
+
+ useEffect(() => {
+ zoomOutDurationMsRef.current = zoomOutDurationMs;
+ }, [zoomOutDurationMs]);
+
+ useEffect(() => {
+ connectedZoomGapMsRef.current = connectedZoomGapMs;
+ }, [connectedZoomGapMs]);
+
+ useEffect(() => {
+ connectedZoomDurationMsRef.current = connectedZoomDurationMs;
+ }, [connectedZoomDurationMs]);
+
+ useEffect(() => {
+ zoomInEasingRef.current = zoomInEasing;
+ }, [zoomInEasing]);
+
+ useEffect(() => {
+ zoomOutEasingRef.current = zoomOutEasing;
+ }, [zoomOutEasing]);
+
+ useEffect(() => {
+ connectedZoomEasingRef.current = connectedZoomEasing;
+ }, [connectedZoomEasing]);
+
+ useEffect(() => {
+ cursorTelemetryRef.current = cursorTelemetry;
+ // Push to extension host for query APIs
+ extensionHost.setCursorTelemetry(
+ cursorTelemetry.map((p) => ({
+ timeMs: p.timeMs,
+ cx: p.cx,
+ cy: p.cy,
+ interactionType: p.interactionType,
+ pressure: p.pressure,
+ })),
+ );
+ }, [cursorTelemetry]);
+
+ useEffect(() => {
+ showCursorRef.current = showCursor;
+ }, [showCursor]);
+
+ useEffect(() => {
+ cursorStyleRef.current = cursorStyle;
+ }, [cursorStyle]);
+
+ useEffect(() => {
+ cursorSizeRef.current = cursorSize;
+ }, [cursorSize]);
+
+ useEffect(() => {
+ cursorSmoothingRef.current = cursorSmoothing;
+ }, [cursorSmoothing]);
+
+ useEffect(() => {
+ zoomSmoothnessRef.current = zoomSmoothness;
+ }, [zoomSmoothness]);
+
+ useEffect(() => {
+ zoomClassicModeRef.current = zoomClassicMode;
+ }, [zoomClassicMode]);
+
+ useEffect(() => {
+ cursorMotionBlurRef.current = cursorMotionBlur;
+ }, [cursorMotionBlur]);
+
+ useEffect(() => {
+ cursorClickBounceRef.current = cursorClickBounce;
+ }, [cursorClickBounce]);
+
+ useEffect(() => {
+ cursorClickBounceDurationRef.current = cursorClickBounceDuration;
+ }, [cursorClickBounceDuration]);
+
+ useEffect(() => {
+ cursorSwayRef.current = cursorSway;
+ }, [cursorSway]);
+
+ useEffect(() => {
+ const timeMs = currentTime * 1000;
+ currentTimeRef.current = timeMs;
+ const videoInfo = extensionHost.getVideoInfoSnapshot();
+ extensionHost.setPlaybackState({
+ currentTimeMs: timeMs,
+ durationMs: videoInfo?.durationMs ?? 0,
+ isPlaying,
+ });
+ }, [currentTime, isPlaying]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+
+ const app = appRef.current;
+ const cameraContainer = cameraContainerRef.current;
+ const video = videoRef.current;
+
+ if (!app || !cameraContainer || !video) return;
+
+ const tickerWasStarted = app.ticker?.started || false;
+ if (tickerWasStarted && app.ticker) {
+ app.ticker.stop();
+ }
+
+ const wasPlaying = !video.paused;
+ if (wasPlaying) {
+ video.pause();
+ }
+
+ animationStateRef.current = createPlaybackAnimationState();
+ cursorOverlayRef.current?.reset();
+ motionBlurStateRef.current = createMotionBlurState();
+
+ if (blurFilterRef.current) {
+ blurFilterRef.current.blur = 0;
+ }
+
+ requestAnimationFrame(() => {
+ const container = cameraContainerRef.current;
+ const videoStage = videoContainerRef.current;
+ const sprite = videoSpriteRef.current;
+ const currentApp = appRef.current;
+ if (!container || !videoStage || !sprite || !currentApp) {
+ return;
+ }
+
+ container.scale.set(1);
+ container.position.set(0, 0);
+ videoStage.scale.set(1);
+ videoStage.position.set(0, 0);
+ sprite.scale.set(1);
+ sprite.position.set(0, 0);
+
+ layoutVideoContent();
+
+ applyZoomTransform({
+ cameraContainer: container,
+ blurFilter: blurFilterRef.current,
+ stageSize: stageSizeRef.current,
+ baseMask: baseMaskRef.current,
+ zoomScale: 1,
+ focusX: DEFAULT_FOCUS.cx,
+ focusY: DEFAULT_FOCUS.cy,
+ motionIntensity: 0,
+ isPlaying: false,
+ motionBlurAmount: zoomMotionBlurRef.current,
+ });
+
+ requestAnimationFrame(() => {
+ const finalApp = appRef.current;
+ if (wasPlaying && video) {
+ video.play().catch(() => undefined);
+ }
+ if (tickerWasStarted && finalApp?.ticker) {
+ finalApp.ticker.start();
+ }
+ });
+ });
+ }, [pixiReady, videoReady, layoutVideoContent, cropRegion]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+ const container = containerRef.current;
+ if (!container) return;
+
+ if (typeof ResizeObserver === "undefined") {
+ return;
+ }
+
+ const observer = new ResizeObserver(() => {
+ layoutVideoContent();
+ });
+
+ observer.observe(container);
+ return () => {
+ observer.disconnect();
+ };
+ }, [pixiReady, videoReady, layoutVideoContent]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+ updateOverlayForRegion(selectedZoom);
+ }, [selectedZoom, pixiReady, videoReady, updateOverlayForRegion]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+ applyWebcamBubbleLayout(animationStateRef.current.appliedScale || 1);
+ }, [applyWebcamBubbleLayout, pixiReady, videoReady, webcam, webcamVideoPath]);
+
+ useEffect(() => {
+ const webcamVideo = webcamVideoRef.current;
+ if (!webcamVideo || !webcam?.enabled || !webcamVideoPath) {
+ return;
+ }
+
+ const targetTime = clampMediaTimeToDuration(
+ currentTime,
+ Number.isFinite(webcamVideo.duration) ? webcamVideo.duration : null,
+ );
+
+ const activeSpeedRegion = speedRegionsRef.current.find(
+ (region) => targetTime * 1000 >= region.startMs && targetTime * 1000 < region.endMs,
+ );
+ const targetPlaybackRate = activeSpeedRegion ? activeSpeedRegion.speed : 1;
+ if (Math.abs(webcamVideo.playbackRate - targetPlaybackRate) > 0.001) {
+ webcamVideo.playbackRate = targetPlaybackRate;
+ }
+
+ const previousTimelineTime = lastWebcamSyncTimeRef.current;
+ const timelineJumped =
+ previousTimelineTime === null || Math.abs(targetTime - previousTimelineTime) > 0.25;
+ const driftThreshold = isPlaying ? 0.35 : 0.01;
+ if (timelineJumped || Math.abs(webcamVideo.currentTime - targetTime) > driftThreshold) {
+ try {
+ webcamVideo.currentTime = targetTime;
+ } catch {
+ // no-op
+ }
+ }
+
+ if (isPlaying) {
+ const playPromise = webcamVideo.play();
+ if (playPromise) {
+ playPromise.catch(() => undefined);
+ }
+ } else {
+ webcamVideo.pause();
+ }
+
+ lastWebcamSyncTimeRef.current = targetTime;
+ }, [currentTime, isPlaying, webcam, webcamVideoPath]);
+
+ useEffect(() => {
+ lastWebcamSyncTimeRef.current = null;
+ }, [webcamVideoPath]);
+
+ useEffect(() => {
+ const overlayEl = overlayRef.current;
+ if (!overlayEl) return;
+ if (!selectedZoom || selectedZoom.mode !== "manual") {
+ overlayEl.style.cursor = "default";
+ overlayEl.style.pointerEvents = "none";
+ return;
+ }
+ overlayEl.style.cursor = isPlaying ? "not-allowed" : "crosshair";
+ overlayEl.style.pointerEvents = isPlaying ? "none" : "auto";
+ }, [selectedZoom, isPlaying]);
+
+ useEffect(() => {
+ const container = containerRef.current;
+ if (!container) return;
+
+ let mounted = true;
+ let app: Application | null = null;
+
+ (async () => {
+ let cursorOverlayEnabled = true;
+ try {
+ await preloadCursorAssets();
+ } catch (error) {
+ cursorOverlayEnabled = false;
+ console.warn(
+ "Native cursor assets are unavailable in preview; continuing without cursor overlay.",
+ error,
+ );
+ }
+
+ app = new Application();
+
+ await app.init({
+ width: container.clientWidth,
+ height: container.clientHeight,
+ backgroundAlpha: 0,
+ antialias: true,
+ failIfMajorPerformanceCaveat: false,
+ resolution: window.devicePixelRatio || 1,
+ autoDensity: true,
+ preference: "webgl",
+ });
+
+ app.ticker.maxFPS = 60;
+
+ if (!mounted) {
+ app.destroy(true, {
+ children: true,
+ texture: false,
+ textureSource: false,
+ });
+ return;
+ }
+
+ appRef.current = app;
+ container.appendChild(app.canvas);
+
+ // Camera container - this will be scaled/positioned for zoom
+ const cameraContainer = new Container();
+ cameraContainerRef.current = cameraContainer;
+ app.stage.addChild(cameraContainer);
+
+ // Video container - holds the masked video sprite
+ const videoContainer = new Container();
+ videoContainerRef.current = videoContainer;
+ cameraContainer.addChild(videoContainer);
+
+ // Device frame overlay container — sits above video but below cursor
+ const frameContainer = new Container();
+ frameContainerRef.current = frameContainer;
+ cameraContainer.addChild(frameContainer);
+
+ const cursorContainer = new Container();
+ cursorContainerRef.current = cursorContainer;
+ cameraContainer.addChild(cursorContainer);
+
+ // Cursor overlay - rendered above the masked video so it can sit in front
+ // of the content without getting clipped.
+ if (cursorOverlayEnabled) {
+ const cursorOverlay = new PixiCursorOverlay({
+ dotRadius: DEFAULT_CURSOR_CONFIG.dotRadius * cursorSizeRef.current,
+ style: cursorStyleRef.current,
+ smoothingFactor: cursorSmoothingRef.current,
+ motionBlur: cursorMotionBlurRef.current,
+ clickBounce: cursorClickBounceRef.current,
+ clickBounceDuration: cursorClickBounceDurationRef.current,
+ sway: cursorSwayRef.current,
+ });
+ cursorOverlayRef.current = cursorOverlay;
+ cursorContainer.addChild(cursorOverlay.container);
+ } else {
+ cursorOverlayRef.current = null;
+ }
+
+ setPixiReady(true);
+ })().catch((error) => {
+ console.error("Failed to initialize preview renderer:", error);
+ onError(
+ error instanceof Error
+ ? error.message
+ : "Failed to initialize preview renderer",
+ );
+ });
+
+ return () => {
+ mounted = false;
+ setPixiReady(false);
+ if (cursorOverlayRef.current) {
+ cursorOverlayRef.current.destroy();
+ cursorOverlayRef.current = null;
+ }
+ if (app && app.renderer) {
+ app.destroy(true, {
+ children: true,
+ texture: false,
+ textureSource: false,
+ });
+ }
+ appRef.current = null;
+ cameraContainerRef.current = null;
+ videoContainerRef.current = null;
+ frameContainerRef.current = null;
+ frameSpriteRef.current = null;
+ cursorContainerRef.current = null;
+ videoSpriteRef.current = null;
+ };
+ }, [onError]);
+
+ useEffect(() => {
+ const video = videoRef.current;
+ if (!video) return;
+ video.pause();
+ video.currentTime = 0;
+ allowPlaybackRef.current = false;
+ lockedVideoDimensionsRef.current = null;
+ setVideoReady(false);
+ if (videoReadyRafRef.current) {
+ cancelAnimationFrame(videoReadyRafRef.current);
+ videoReadyRafRef.current = null;
+ }
+ }, [videoPath]);
+
+ useEffect(() => {
+ onPreviewReadyChange?.(videoReady);
+ }, [onPreviewReadyChange, videoReady]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+
+ const video = videoRef.current;
+ const app = appRef.current;
+ const videoContainer = videoContainerRef.current;
+ const cursorContainer = cursorContainerRef.current;
+
+ if (!video || !app || !videoContainer || !cursorContainer) return;
+ if (video.videoWidth === 0 || video.videoHeight === 0) return;
+
+ const source = VideoSource.from(video);
+ if ("autoPlay" in source) {
+ (source as { autoPlay?: boolean }).autoPlay = false;
+ }
+ if ("autoUpdate" in source) {
+ (source as { autoUpdate?: boolean }).autoUpdate = true;
+ }
+ const videoTexture = Texture.from(source);
+
+ const videoSprite = new Sprite(videoTexture);
+ videoSpriteRef.current = videoSprite;
+
+ const maskGraphics = new Graphics();
+ videoContainer.addChild(videoSprite);
+ videoContainer.addChild(maskGraphics);
+ videoContainer.mask = maskGraphics;
+ maskGraphicsRef.current = maskGraphics;
+ if (cursorOverlayRef.current) {
+ cursorContainer.addChild(cursorOverlayRef.current.container);
+ }
+
+ animationStateRef.current = createPlaybackAnimationState();
+
+ const blurFilter = new BlurFilter();
+ blurFilter.quality = 3;
+ blurFilter.resolution = app.renderer.resolution;
+ blurFilter.blur = 0;
+ const motionBlurFilter = new MotionBlurFilter([0, 0], 5, 0);
+ videoContainer.filters = [blurFilter, motionBlurFilter];
+ blurFilterRef.current = blurFilter;
+ motionBlurFilterRef.current = motionBlurFilter;
+
+ layoutVideoContent();
+ video.pause();
+
+ const { handlePlay, handlePause, handleSeeked, handleSeeking } =
+ createVideoEventHandlers({
+ video,
+ isSeekingRef,
+ isPlayingRef,
+ allowPlaybackRef,
+ currentTimeRef,
+ timeUpdateAnimationRef,
+ onPlayStateChange,
+ onTimeUpdate,
+ trimRegionsRef,
+ speedRegionsRef,
+ });
+
+ video.addEventListener("play", handlePlay);
+ video.addEventListener("pause", handlePause);
+ video.addEventListener("ended", handlePause);
+ video.addEventListener("seeked", handleSeeked);
+ video.addEventListener("seeking", handleSeeking);
+
+ return () => {
+ video.removeEventListener("play", handlePlay);
+ video.removeEventListener("pause", handlePause);
+ video.removeEventListener("ended", handlePause);
+ video.removeEventListener("seeked", handleSeeked);
+ video.removeEventListener("seeking", handleSeeking);
+
+ if (timeUpdateAnimationRef.current) {
+ cancelAnimationFrame(timeUpdateAnimationRef.current);
+ }
+
+ if (videoSprite) {
+ videoContainer.removeChild(videoSprite);
+ videoSprite.destroy();
+ }
+ if (maskGraphics) {
+ videoContainer.removeChild(maskGraphics);
+ maskGraphics.destroy();
+ }
+ videoContainer.mask = null;
+ maskGraphicsRef.current = null;
+ if (blurFilterRef.current) {
+ videoContainer.filters = [];
+ blurFilterRef.current.destroy();
+ blurFilterRef.current = null;
+ }
+ if (motionBlurFilterRef.current) {
+ motionBlurFilterRef.current.destroy();
+ motionBlurFilterRef.current = null;
+ }
+ videoTexture.destroy(false);
+
+ videoSpriteRef.current = null;
+ };
+ }, [pixiReady, videoReady, onTimeUpdate, updateOverlayForRegion]);
+
+ useEffect(() => {
+ if (!pixiReady || !videoReady) return;
+
+ const app = appRef.current;
+ const videoSprite = videoSpriteRef.current;
+ const videoContainer = videoContainerRef.current;
+ if (!app || !videoSprite || !videoContainer) return;
+
+ const applyTransform = (
+ transform: { scale: number; x: number; y: number },
+ focus: ZoomFocus,
+ motionIntensity: number,
+ motionVector: { x: number; y: number },
+ ) => {
+ const cameraContainer = cameraContainerRef.current;
+ if (!cameraContainer) return;
+
+ const state = animationStateRef.current;
+
+ const appliedTransform = applyZoomTransform({
+ cameraContainer,
+ blurFilter: blurFilterRef.current,
+ stageSize: stageSizeRef.current,
+ baseMask: baseMaskRef.current,
+ zoomScale: state.scale,
+ zoomProgress: state.progress,
+ focusX: focus.cx,
+ focusY: focus.cy,
+ motionIntensity,
+ motionVector,
+ isPlaying: isPlayingRef.current,
+ motionBlurAmount: zoomMotionBlurRef.current,
+ motionBlurFilter: motionBlurFilterRef.current,
+ transformOverride: transform,
+ motionBlurState: motionBlurStateRef.current,
+ frameTimeMs: performance.now(),
+ });
+
+ state.x = appliedTransform.x;
+ state.y = appliedTransform.y;
+ state.appliedScale = appliedTransform.scale;
+ };
+
+ const ticker = () => {
+ const { region, strength, blendedScale, transition } = findDominantRegion(
+ zoomRegionsRef.current,
+ currentTimeRef.current,
+ {
+ connectZooms: connectZoomsRef.current,
+ },
+ );
+
+ const defaultFocus = DEFAULT_FOCUS;
+ let targetScaleFactor = 1;
+ let targetFocus = defaultFocus;
+ let targetProgress = 0;
+
+ // If a zoom is selected but video is not playing, show default unzoomed view
+ // (the overlay will show where the zoom will be)
+ const selectedId = selectedZoomIdRef.current;
+ const hasSelectedZoom = selectedId !== null;
+ const shouldShowUnzoomedView = hasSelectedZoom && !isPlayingRef.current;
+
+ if (region && strength > 0 && !shouldShowUnzoomedView) {
+ const zoomScale = blendedScale ?? ZOOM_DEPTH_SCALES[region.depth];
+
+ // Cursor follow: use cursor-follow camera for non-manual zoom regions
+ let regionFocus = region.focus;
+ if (
+ !zoomClassicModeRef.current &&
+ region.mode !== "manual" &&
+ cursorTelemetryRef.current.length > 0
+ ) {
+ regionFocus = computeCursorFollowFocus(
+ cursorFollowCameraRef.current,
+ cursorTelemetryRef.current,
+ currentTimeRef.current,
+ zoomScale,
+ strength,
+ region.focus,
+ { snapToEdgesRatio: SNAP_TO_EDGES_RATIO_AUTO },
+ );
+ }
+
+ targetScaleFactor = zoomScale;
+ targetFocus = regionFocus;
+ targetProgress = strength;
+
+ if (transition) {
+ const startTransform = computeZoomTransform({
+ stageSize: stageSizeRef.current,
+ baseMask: baseMaskRef.current,
+ zoomScale: transition.startScale,
+ zoomProgress: 1,
+ focusX: transition.startFocus.cx,
+ focusY: transition.startFocus.cy,
+ });
+ const endTransform = computeZoomTransform({
+ stageSize: stageSizeRef.current,
+ baseMask: baseMaskRef.current,
+ zoomScale: transition.endScale,
+ zoomProgress: 1,
+ focusX: transition.endFocus.cx,
+ focusY: transition.endFocus.cy,
+ });
+
+ const interpolatedTransform = {
+ scale:
+ startTransform.scale +
+ (endTransform.scale - startTransform.scale) * transition.progress,
+ x:
+ startTransform.x +
+ (endTransform.x - startTransform.x) * transition.progress,
+ y:
+ startTransform.y +
+ (endTransform.y - startTransform.y) * transition.progress,
+ };
+
+ targetScaleFactor = interpolatedTransform.scale;
+ targetFocus = computeFocusFromTransform({
+ stageSize: stageSizeRef.current,
+ baseMask: baseMaskRef.current,
+ zoomScale: interpolatedTransform.scale,
+ x: interpolatedTransform.x,
+ y: interpolatedTransform.y,
+ });
+ targetProgress = 1;
+ }
+ }
+
+ const state = animationStateRef.current;
+ const prevScale = state.appliedScale;
+ const prevX = state.x;
+ const prevY = state.y;
+
+ state.scale = targetScaleFactor;
+ state.focusX = targetFocus.cx;
+ state.focusY = targetFocus.cy;
+ state.progress = targetProgress;
+
+ // Push zoom state to extension host for query APIs
+ extensionHost.setZoomState({
+ scale: targetScaleFactor,
+ focusX: targetFocus.cx,
+ focusY: targetFocus.cy,
+ progress: targetProgress,
+ });
+
+ const projectedTransform = computeZoomTransform({
+ stageSize: stageSizeRef.current,
+ baseMask: baseMaskRef.current,
+ zoomScale: state.scale,
+ zoomProgress: state.progress,
+ focusX: state.focusX,
+ focusY: state.focusY,
+ });
+
+ // Spring-driven zoom animation
+ const now = performance.now();
+ const deltaMs =
+ lastTickTimeRef.current !== null ? now - lastTickTimeRef.current : 1000 / 60;
+ lastTickTimeRef.current = now;
+
+ const zoomSpringConfig = getZoomSpringConfig(zoomSmoothnessRef.current);
+ const useSpring =
+ isPlayingRef.current && !isSeekingRef.current && !zoomClassicModeRef.current;
+
+ let appliedScale: number;
+ let appliedX: number;
+ let appliedY: number;
+
+ if (useSpring) {
+ appliedScale = stepSpringValue(
+ springScaleRef.current,
+ projectedTransform.scale,
+ deltaMs,
+ zoomSpringConfig,
+ );
+ appliedX = stepSpringValue(
+ springXRef.current,
+ projectedTransform.x,
+ deltaMs,
+ zoomSpringConfig,
+ );
+ appliedY = stepSpringValue(
+ springYRef.current,
+ projectedTransform.y,
+ deltaMs,
+ zoomSpringConfig,
+ );
+ } else {
+ // Snap instantly when paused, seeking, or in classic mode
+ appliedScale = projectedTransform.scale;
+ appliedX = projectedTransform.x;
+ appliedY = projectedTransform.y;
+ resetSpringState(springScaleRef.current, appliedScale);
+ resetSpringState(springXRef.current, appliedX);
+ resetSpringState(springYRef.current, appliedY);
+ }
+
+ const motionIntensity = Math.max(
+ Math.abs(appliedScale - prevScale),
+ Math.abs(appliedX - prevX) / Math.max(1, stageSizeRef.current.width),
+ Math.abs(appliedY - prevY) / Math.max(1, stageSizeRef.current.height),
+ );
+
+ const motionVector = {
+ x: appliedX - prevX,
+ y: appliedY - prevY,
+ };
+
+ applyTransform(
+ { scale: appliedScale, x: appliedX, y: appliedY },
+ targetFocus,
+ motionIntensity,
+ motionVector,
+ );
+ applyWebcamBubbleLayout(animationStateRef.current.appliedScale || 1);
+
+ const timeMs = currentTimeRef.current;
+ const effectsCanvas = cursorEffectsCanvasRef.current;
+ const extensionCanvasWidth = effectsCanvas?.width || stageSizeRef.current.width;
+ const extensionCanvasHeight = effectsCanvas?.height || stageSizeRef.current.height;
+ let smoothedCursorForHooks: {
+ cx: number;
+ cy: number;
+ trail: Array<{ cx: number; cy: number }>;
+ } | null = null;
+
+ // Update cursor overlay + emit cursor events
+ const cursorOverlay = cursorOverlayRef.current;
+ if (cursorOverlay) {
+ const telemetry = cursorTelemetryRef.current;
+ cursorOverlay.update(
+ telemetry,
+ timeMs,
+ baseMaskRef.current,
+ showCursorRef.current,
+ !isPlayingRef.current || isSeekingRef.current,
+ );
+
+ smoothedCursorForHooks = mapSmoothedCursorToCanvasNormalized(
+ cursorOverlay.getSmoothedCursorSnapshot(),
+ {
+ maskRect: baseMaskRef.current,
+ canvasWidth: extensionCanvasWidth,
+ canvasHeight: extensionCanvasHeight,
+ },
+ );
+ extensionHost.setSmoothedCursor(
+ smoothedCursorForHooks
+ ? {
+ timeMs,
+ cx: smoothedCursorForHooks.cx,
+ cy: smoothedCursorForHooks.cy,
+ trail: smoothedCursorForHooks.trail,
+ }
+ : null,
+ );
+
+ // Emit cursor:click events for extensions
+ if (isPlayingRef.current && telemetry.length > 0) {
+ for (let i = telemetry.length - 1; i >= 0; i--) {
+ const p = telemetry[i];
+ if (p.timeMs > timeMs) continue;
+ if (p.timeMs < timeMs - 100) break;
+ if (
+ p.interactionType &&
+ p.interactionType !== "move" &&
+ p.timeMs !== lastEmittedClickTimeMsRef.current
+ ) {
+ const extensionCursor = mapCursorToCanvasNormalized(
+ {
+ cx: p.cx,
+ cy: p.cy,
+ interactionType: p.interactionType,
+ },
+ {
+ maskRect: baseMaskRef.current,
+ canvasWidth: extensionCanvasWidth,
+ canvasHeight: extensionCanvasHeight,
+ },
+ );
+ lastEmittedClickTimeMsRef.current = p.timeMs;
+ extensionHost.emitEvent({
+ type: "cursor:click",
+ timeMs: p.timeMs,
+ data: extensionCursor,
+ });
+ if (extensionCursor) {
+ notifyCursorInteraction(
+ p.timeMs,
+ extensionCursor.cx,
+ extensionCursor.cy,
+ p.interactionType,
+ );
+ }
+ }
+ break;
+ }
+ }
+ }
+
+ if (!cursorOverlay) {
+ extensionHost.setSmoothedCursor(null);
+ }
+
+ if (effectsCanvas && effectsCanvas.width > 0 && effectsCanvas.height > 0) {
+ const ctx2d = effectsCanvas.getContext("2d");
+ if (ctx2d) {
+ ctx2d.clearRect(0, 0, effectsCanvas.width, effectsCanvas.height);
+
+ const maskRect = baseMaskRef.current;
+ const animationState = animationStateRef.current;
+ const videoInfo = extensionHost.getVideoInfoSnapshot();
+ const rawCursor = getCursorPositionAtTime(
+ cursorTelemetryRef.current,
+ timeMs,
+ {
+ maskRect,
+ canvasWidth: effectsCanvas.width,
+ canvasHeight: effectsCanvas.height,
+ },
+ );
+ const hookParams = {
+ width: effectsCanvas.width,
+ height: effectsCanvas.height,
+ timeMs,
+ durationMs: videoInfo?.durationMs ?? 0,
+ cursor: smoothedCursorForHooks
+ ? {
+ cx: smoothedCursorForHooks.cx,
+ cy: smoothedCursorForHooks.cy,
+ interactionType: rawCursor?.interactionType,
+ }
+ : rawCursor,
+ smoothedCursor: smoothedCursorForHooks,
+ videoLayout:
+ maskRect.width > 0 && maskRect.height > 0
+ ? {
+ maskRect: {
+ x: maskRect.x,
+ y: maskRect.y,
+ width: maskRect.width,
+ height: maskRect.height,
+ },
+ borderRadius,
+ padding,
+ }
+ : undefined,
+ zoom: {
+ scale: animationState.scale,
+ focusX: animationState.focusX,
+ focusY: animationState.focusY,
+ progress: animationState.progress,
+ },
+ shadow: {
+ enabled: Boolean(showShadow) && shadowIntensity > 0,
+ intensity: shadowIntensity,
+ },
+ sceneTransform: {
+ scale: animationState.appliedScale,
+ x: animationState.x,
+ y: animationState.y,
+ },
+ };
+
+ ctx2d.save();
+ applyCanvasSceneTransform(ctx2d, {
+ scale: animationState.appliedScale,
+ x: animationState.x,
+ y: animationState.y,
+ });
+ executeExtensionRenderHooks("post-video", ctx2d, hookParams);
+ executeExtensionRenderHooks("post-zoom", ctx2d, hookParams);
+ executeExtensionRenderHooks("post-cursor", ctx2d, hookParams);
+
+ if (isSeekingRef.current) {
+ clearCursorEffects();
+ } else {
+ executeExtensionCursorEffects(
+ ctx2d,
+ timeMs,
+ effectsCanvas.width,
+ effectsCanvas.height,
+ {
+ zoom: hookParams.zoom,
+ sceneTransform: hookParams.sceneTransform,
+ videoLayout: hookParams.videoLayout,
+ },
+ );
+ }
+ ctx2d.restore();
+
+ executeExtensionRenderHooks("post-webcam", ctx2d, hookParams);
+ executeExtensionRenderHooks("post-annotations", ctx2d, hookParams);
+
+ executeExtensionRenderHooks("final", ctx2d, hookParams);
+ }
+ }
+ };
+
+ app.ticker.add(ticker);
+ return () => {
+ if (app && app.ticker) {
+ app.ticker.remove(ticker);
+ }
+ };
+ }, [
+ pixiReady,
+ videoReady,
+ clampFocusToStage,
+ applyWebcamBubbleLayout,
+ borderRadius,
+ padding,
+ showShadow,
+ shadowIntensity,
+ ]);
+
+ useEffect(() => {
+ const overlay = cursorOverlayRef.current;
+ if (!overlay) {
+ return;
+ }
+
+ let cancelled = false;
+
+ overlay.setDotRadius(DEFAULT_CURSOR_CONFIG.dotRadius * cursorSize);
+ overlay.setSmoothingFactor(cursorSmoothing);
+ overlay.setMotionBlur(cursorMotionBlur);
+ overlay.setClickBounce(cursorClickBounce);
+ overlay.setClickBounceDuration(cursorClickBounceDuration);
+ overlay.setSway(cursorSway);
+
+ void (async () => {
+ try {
+ await preloadCursorAssets();
+ } catch (error) {
+ console.warn("Failed to refresh cursor assets for preview:", error);
+ return;
+ }
+
+ if (cancelled || cursorOverlayRef.current !== overlay) {
+ return;
+ }
+
+ overlay.setStyle(cursorStyle);
+ overlay.reset();
+ })();
+
+ return () => {
+ cancelled = true;
+ };
+ }, [
+ cursorStyle,
+ cursorSize,
+ cursorSmoothing,
+ cursorMotionBlur,
+ cursorClickBounce,
+ cursorClickBounceDuration,
+ cursorSway,
+ ]);
+
+ useEffect(() => {
+ let cancelled = false;
+ let signature = getContributedCursorStylesSignature();
+
+ const refreshSelectedCursorStyle = async () => {
+ const overlay = cursorOverlayRef.current;
+ if (!overlay) {
+ return;
+ }
+
+ try {
+ await preloadCursorAssets();
+ } catch (error) {
+ console.warn("Failed to refresh contributed cursor styles in preview:", error);
+ return;
+ }
+
+ if (cancelled || cursorOverlayRef.current !== overlay) {
+ return;
+ }
+
+ overlay.setStyle(cursorStyleRef.current);
+ overlay.reset();
+ };
+
+ const unsubscribe = extensionHost.onChange(() => {
+ const nextSignature = getContributedCursorStylesSignature();
+ if (nextSignature === signature) {
+ return;
+ }
+
+ signature = nextSignature;
+ void refreshSelectedCursorStyle();
+ });
+
+ return () => {
+ cancelled = true;
+ unsubscribe();
+ };
+ }, []);
+
+ const handleLoadedMetadata = (e: React.SyntheticEvent<HTMLVideoElement, Event>) => {
+ const video = e.currentTarget;
+ onDurationChange(video.duration);
+
+ // Push video info to extension host for query APIs
+ extensionHost.setVideoInfo({
+ width: video.videoWidth,
+ height: video.videoHeight,
+ durationMs: Number.isFinite(video.duration) ? video.duration * 1000 : 0,
+ fps: 60, // Not available from HTMLVideoElement; default to 60
+ });
+ const targetTime = clampMediaTimeToDuration(
+ currentTime,
+ Number.isFinite(video.duration) ? video.duration : null,
+ );
+ video.currentTime = targetTime;
+ video.pause();
+ allowPlaybackRef.current = false;
+ currentTimeRef.current = targetTime * 1000;
+
+ if (videoReadyRafRef.current) {
+ cancelAnimationFrame(videoReadyRafRef.current);
+ videoReadyRafRef.current = null;
+ }
+
+ const waitForRenderableFrame = () => {
+ const hasDimensions = video.videoWidth > 0 && video.videoHeight > 0;
+ const hasData = video.readyState >= HTMLMediaElement.HAVE_CURRENT_DATA;
+ if (hasDimensions && hasData) {
+ videoReadyRafRef.current = null;
+ setVideoReady(true);
+ return;
+ }
+ videoReadyRafRef.current = requestAnimationFrame(waitForRenderableFrame);
+ };
+
+ videoReadyRafRef.current = requestAnimationFrame(waitForRenderableFrame);
+ };
+
+ const [resolvedWallpaper, setResolvedWallpaper] = useState<string | null>(null);
+ const [resolvedWallpaperKind, setResolvedWallpaperKind] = useState<
+ "image" | "video" | "style"
+ >("image");
+
+ useEffect(() => {
+ let mounted = true;
+ const revokeResolvedWallpaper = () => undefined;
+ (async () => {
+ try {
+ if (!wallpaper) {
+ const def = await getAssetPath(DEFAULT_WALLPAPER_RELATIVE_PATH);
+ if (mounted) {
+ setResolvedWallpaper(def);
+ setResolvedWallpaperKind("image");
+ }
+ return;
+ }
+
+ if (
+ wallpaper.startsWith("#") ||
+ wallpaper.startsWith("linear-gradient") ||
+ wallpaper.startsWith("radial-gradient")
+ ) {
+ if (mounted) {
+ setResolvedWallpaper(wallpaper);
+ setResolvedWallpaperKind("style");
+ }
+ return;
+ }
+
+ if (isVideoWallpaperSource(wallpaper)) {
+ let videoSrc = wallpaper;
+ if (wallpaper.startsWith("/") && !wallpaper.startsWith("//")) {
+ videoSrc = await getAssetPath(wallpaper.replace(/^\//, ""));
+ }
+ if (mounted) {
+ setResolvedWallpaper(videoSrc);
+ setResolvedWallpaperKind("video");
+ }
+ return;
+ }
+
+ // If it's a data URL (custom uploaded image), use as-is
+ if (wallpaper.startsWith("data:")) {
+ if (mounted) {
+ setResolvedWallpaper(wallpaper);
+ setResolvedWallpaperKind("image");
+ }
+ return;
+ }
+
+ if (
+ wallpaper.startsWith("http") ||
+ wallpaper.startsWith("file://") ||
+ wallpaper.startsWith("/")
+ ) {
+ const renderable = await getRenderableAssetUrl(wallpaper);
+ if (mounted) {
+ setResolvedWallpaper(renderable);
+ setResolvedWallpaperKind("image");
+ }
+ return;
+ }
+ const p = await getRenderableAssetUrl(
+ await getAssetPath(wallpaper.replace(/^\//, "")),
+ );
+ if (mounted) {
+ setResolvedWallpaper(p);
+ setResolvedWallpaperKind("image");
+ }
+ } catch (_err) {
+ if (mounted) {
+ setResolvedWallpaper(wallpaper || DEFAULT_WALLPAPER_PATH);
+ setResolvedWallpaperKind(
+ isVideoWallpaperSource(wallpaper || "") ? "video" : "image",
+ );
+ }
+ }
+ })();
+ return () => {
+ mounted = false;
+ revokeResolvedWallpaper();
+ };
+ }, [wallpaper]);
+
+ useEffect(() => {
+ return () => {
+ if (videoReadyRafRef.current) {
+ cancelAnimationFrame(videoReadyRafRef.current);
+ videoReadyRafRef.current = null;
+ }
+ };
+ }, []);
+
+ const isImageUrl =
+ resolvedWallpaperKind === "image" &&
+ Boolean(
+ resolvedWallpaper &&
+ (resolvedWallpaper.startsWith("file://") ||
+ resolvedWallpaper.startsWith("http") ||
+ resolvedWallpaper.startsWith("/") ||
+ resolvedWallpaper.startsWith("data:")),
+ );
+ const backgroundStyle = isImageUrl
+ ? { backgroundImage: `url(${resolvedWallpaper || ""})` }
+ : resolvedWallpaperKind === "video"
+ ? {}
+ : { background: resolvedWallpaper || "" };
+
+ const nativeAspectRatio = (() => {
+ const locked = lockedVideoDimensionsRef.current;
+ if (locked) {
+ return getEffectiveNativeAspectRatio(locked, cropRegion);
+ }
+ const video = videoRef.current;
+ if (video && video.videoHeight > 0 && video.videoWidth > 0) {
+ return getEffectiveNativeAspectRatio(
+ {
+ width: video.videoWidth,
+ height: video.videoHeight,
+ },
+ cropRegion,
+ );
+ }
+ return 16 / 9;
+ })();
+
+ return (
+ <div
+ className="relative rounded-sm overflow-hidden"
+ style={{
+ width: "100%",
+ aspectRatio: formatAspectRatioForCSS(aspectRatio, nativeAspectRatio),
+ }}
+ >
+ {/* Background layer */}
+ {resolvedWallpaperKind === "video" && resolvedWallpaper ? (
+ <video
+ key={resolvedWallpaper}
+ ref={bgVideoRef}
+ className="absolute inset-0 h-full w-full object-cover"
+ src={resolvedWallpaper}
+ muted
+ loop
+ playsInline
+ style={{
+ filter: backgroundBlur > 0 ? `blur(${backgroundBlur}px)` : "none",
+ }}
+ />
+ ) : (
+ <div
+ className="absolute inset-0 bg-cover bg-center"
+ style={{
+ ...backgroundStyle,
+ filter: backgroundBlur > 0 ? `blur(${backgroundBlur}px)` : "none",
+ }}
+ />
+ )}
+ <div
+ ref={containerRef}
+ className="absolute inset-0"
+ style={{
+ filter:
+ showShadow && shadowIntensity > 0
+ ? `drop-shadow(0 ${shadowIntensity * 12}px ${shadowIntensity * 48}px rgba(0,0,0,${shadowIntensity * 0.7})) drop-shadow(0 ${shadowIntensity * 4}px ${shadowIntensity * 16}px rgba(0,0,0,${shadowIntensity * 0.5})) drop-shadow(0 ${shadowIntensity * 2}px ${shadowIntensity * 8}px rgba(0,0,0,${shadowIntensity * 0.3}))`
+ : "none",
+ }}
+ />
+ {/* Canvas overlay for extension cursor effects (drawn via Canvas 2D API) */}
+ <canvas
+ ref={cursorEffectsCanvasRef}
+ className="absolute inset-0 w-full h-full pointer-events-none"
+ style={{ zIndex: 1 }}
+ />
+ {/* Only render overlay after PIXI and video are fully initialized */}
+ {pixiReady && videoReady && (
+ <div
+ ref={overlayRef}
+ className="absolute inset-0 select-none"
+ style={{ pointerEvents: "none" }}
+ onPointerDown={handleOverlayPointerDown}
+ onPointerMove={handleOverlayPointerMove}
+ onPointerUp={handleOverlayPointerUp}
+ onPointerLeave={handleOverlayPointerLeave}
+ >
+ <div
+ ref={focusIndicatorRef}
+ className="absolute rounded-md border border-[#2563EB]/80 bg-[#2563EB]/20 shadow-[0_0_0_1px_rgba(37,99,235,0.35)]"
+ style={{ display: "none", pointerEvents: "none" }}
+ />
+ {webcam && webcamVideoPath ? (
+ <div
+ ref={webcamBubbleRef}
+ className="absolute"
+ style={{
+ display: webcam.enabled ? "block" : "none",
+ pointerEvents: "none",
+ }}
+ >
+ <div
+ ref={webcamBubbleInnerRef}
+ className="h-full w-full overflow-hidden bg-black/80"
+ >
+ <video
+ ref={webcamVideoRef}
+ src={webcamVideoPath}
+ className="h-full w-full object-cover"
+ muted
+ playsInline
+ preload="auto"
+ style={{
+ transform: webcam.mirror ? "scaleX(-1)" : undefined,
+ }}
+ />
+ </div>
+ </div>
+ ) : null}
+ {activeCaptionLayout && autoCaptionSettings ? (
+ <div
+ className="pointer-events-none absolute inset-x-0 flex justify-center"
+ style={{
+ bottom: `${autoCaptionSettings.bottomOffset}%`,
+ }}
+ >
+ <div
+ style={{
+ maxWidth: `${autoCaptionSettings.maxWidth}%`,
+ opacity: activeCaptionLayout.opacity,
+ transform: `translateY(${activeCaptionLayout.translateY}px) scale(${activeCaptionLayout.scale})`,
+ transformOrigin: "center bottom",
+ filter: "drop-shadow(0 12px 30px rgba(0, 0, 0, 0.28))",
+ }}
+ >
+ <div
+ ref={captionBoxRef}
+ style={{
+ backgroundColor: `rgba(0, 0, 0, ${autoCaptionSettings.backgroundOpacity})`,
+ fontFamily: getDefaultCaptionFontFamily(),
+ fontSize: `${getCaptionScaledFontSize(
+ autoCaptionSettings.fontSize,
+ overlayRef.current?.clientWidth || 960,
+ autoCaptionSettings.maxWidth,
+ )}px`,
+ lineHeight: CAPTION_LINE_HEIGHT,
+ textAlign: "center",
+ fontWeight: CAPTION_FONT_WEIGHT,
+ padding: `${
+ getCaptionPadding(
+ getCaptionScaledFontSize(
+ autoCaptionSettings.fontSize,
+ overlayRef.current?.clientWidth || 960,
+ autoCaptionSettings.maxWidth,
+ ),
+ ).y
+ }px ${
+ getCaptionPadding(
+ getCaptionScaledFontSize(
+ autoCaptionSettings.fontSize,
+ overlayRef.current?.clientWidth || 960,
+ autoCaptionSettings.maxWidth,
+ ),
+ ).x
+ }px`,
+ borderRadius: `${getCaptionScaledRadius(
+ autoCaptionSettings.boxRadius,
+ getCaptionScaledFontSize(
+ autoCaptionSettings.fontSize,
+ overlayRef.current?.clientWidth || 960,
+ autoCaptionSettings.maxWidth,
+ ),
+ )}px`,
+ boxSizing: "border-box",
+ }}
+ >
+ {activeCaptionLayout.visibleLines.map((line) => (
+ <div
+ key={`${activeCaptionLayout.blockKey}-${line.startWordIndex}`}
+ style={{
+ display: "flex",
+ justifyContent: "center",
+ flexWrap: "nowrap",
+ whiteSpace: "nowrap",
+ }}
+ >
+ {line.words.map((word) => {
+ const visualState = getCaptionWordVisualState(
+ activeCaptionLayout.hasWordTimings,
+ word.state,
+ );
+
+ return (
+ <span
+ key={`${activeCaptionLayout.blockKey}-${word.index}`}
+ style={{
+ display: "inline-block",
+ whiteSpace: "pre",
+ color: visualState.isInactive
+ ? autoCaptionSettings.inactiveTextColor
+ : autoCaptionSettings.textColor,
+ opacity: visualState.opacity,
+ }}
+ >
+ {`${word.leadingSpace ? " " : ""}${word.text}`}
+ </span>
+ );
+ })}
+ </div>
+ ))}
+ </div>
+ </div>
+ </div>
+ ) : null}
+ {(() => {
+ const filtered = (annotationRegions || []).filter((annotation) => {
+ if (
+ typeof annotation.startMs !== "number" ||
+ typeof annotation.endMs !== "number"
+ )
+ return false;
+
+ if (annotation.id === selectedAnnotationId) return true;
+
+ const timeMs = Math.round(currentTime * 1000);
+ return timeMs >= annotation.startMs && timeMs <= annotation.endMs;
+ });
+
+ // Sort by z-index (lowest to highest) so higher z-index renders on top
+ const sorted = [...filtered].sort((a, b) => a.zIndex - b.zIndex);
+
+ // Handle click-through cycling: when clicking same annotation, cycle to next
+ const handleAnnotationClick = (clickedId: string) => {
+ if (!onSelectAnnotation) return;
+
+ // If clicking on already selected annotation and there are multiple overlapping
+ if (clickedId === selectedAnnotationId && sorted.length > 1) {
+ // Find current index and cycle to next
+ const currentIndex = sorted.findIndex(
+ (a) => a.id === clickedId,
+ );
+ const nextIndex = (currentIndex + 1) % sorted.length;
+ onSelectAnnotation(sorted[nextIndex].id);
+ } else {
+ // First click or clicking different annotation
+ onSelectAnnotation(clickedId);
+ }
+ };
+
+ return sorted.map((annotation) => (
+ <AnnotationOverlay
+ key={annotation.id}
+ annotation={annotation}
+ isSelected={annotation.id === selectedAnnotationId}
+ containerWidth={overlayRef.current?.clientWidth || 800}
+ containerHeight={overlayRef.current?.clientHeight || 600}
+ onPositionChange={(id, position) =>
+ onAnnotationPositionChange?.(id, position)
+ }
+ onSizeChange={(id, size) => onAnnotationSizeChange?.(id, size)}
+ onClick={handleAnnotationClick}
+ zIndex={annotation.zIndex}
+ isSelectedBoost={annotation.id === selectedAnnotationId}
+ />
+ ));
+ })()}
+ </div>
+ )}
+ <video
+ ref={videoRef}
+ src={videoPath}
+ className="hidden"
+ preload="metadata"
+ playsInline
+ onLoadedMetadata={handleLoadedMetadata}
+ onDurationChange={(e) => {
+ onDurationChange(e.currentTarget.duration);
+ }}
+ onError={() => onError("Failed to load video")}
+ />
+ </div>
+ );
+ },
);
VideoPlayback.displayName = "VideoPlayback";
diff --git a/src/components/video-editor/audio.test.ts b/src/components/video-editor/audio.test.ts
index c4578df8..60a46f8a 100644
--- a/src/components/video-editor/audio.test.ts
+++ b/src/components/video-editor/audio.test.ts
@@ -1,6 +1,6 @@
-import { describe, it, expect } from "vitest";
import * as fc from "fast-check";
-import { toFileUrl, fromFileUrl, normalizeProjectEditor } from "./projectPersistence";
+import { describe, expect, it } from "vitest";
+import { fromFileUrl, normalizeProjectEditor, toFileUrl } from "./projectPersistence";
describe("Audio path handling", () => {
describe("toFileUrl produces valid file:// URLs for audio paths", () => {
@@ -69,7 +69,13 @@ describe("Audio region normalization", () => {
it("should clamp negative volume to 0", () => {
const result = normalizeProjectEditor({
audioRegions: [
- { id: "audio-1", startMs: 0, endMs: 1000, audioPath: "/test.mp3", volume: -0.5 },
+ {
+ id: "audio-1",
+ startMs: 0,
+ endMs: 1000,
+ audioPath: "/test.mp3",
+ volume: -0.5,
+ },
],
} as any);
expect(result.audioRegions[0].volume).toBe(0);
@@ -77,17 +83,20 @@ describe("Audio region normalization", () => {
it("should preserve valid volume values in [0, 1]", () => {
fc.assert(
- fc.property(
- fc.double({ min: 0, max: 1, noNaN: true }),
- (volume) => {
- const result = normalizeProjectEditor({
- audioRegions: [
- { id: "audio-1", startMs: 0, endMs: 1000, audioPath: "/test.mp3", volume },
- ],
- } as any);
- expect(result.audioRegions[0].volume).toBeCloseTo(volume, 10);
- },
- ),
+ fc.property(fc.double({ min: 0, max: 1, noNaN: true }), (volume) => {
+ const result = normalizeProjectEditor({
+ audioRegions: [
+ {
+ id: "audio-1",
+ startMs: 0,
+ endMs: 1000,
+ audioPath: "/test.mp3",
+ volume,
+ },
+ ],
+ } as any);
+ expect(result.audioRegions[0].volume).toBeCloseTo(volume, 10);
+ }),
);
});
@@ -102,9 +111,7 @@ describe("Audio region normalization", () => {
it("should default to 1 when volume is undefined", () => {
const result = normalizeProjectEditor({
- audioRegions: [
- { id: "audio-1", startMs: 0, endMs: 1000, audioPath: "/test.mp3" },
- ],
+ audioRegions: [{ id: "audio-1", startMs: 0, endMs: 1000, audioPath: "/test.mp3" }],
} as any);
expect(result.audioRegions[0].volume).toBe(1);
});
@@ -114,7 +121,13 @@ describe("Audio region normalization", () => {
it("should clamp negative startMs to 0", () => {
const result = normalizeProjectEditor({
audioRegions: [
- { id: "audio-1", startMs: -500, endMs: 1000, audioPath: "/test.mp3", volume: 1 },
+ {
+ id: "audio-1",
+ startMs: -500,
+ endMs: 1000,
+ audioPath: "/test.mp3",
+ volume: 1,
+ },
],
} as any);
expect(result.audioRegions[0].startMs).toBe(0);
@@ -132,7 +145,13 @@ describe("Audio region normalization", () => {
it("should handle equal startMs and endMs by ensuring minimum gap", () => {
const result = normalizeProjectEditor({
audioRegions: [
- { id: "audio-1", startMs: 1000, endMs: 1000, audioPath: "/test.mp3", volume: 1 },
+ {
+ id: "audio-1",
+ startMs: 1000,
+ endMs: 1000,
+ audioPath: "/test.mp3",
+ volume: 1,
+ },
],
} as any);
expect(result.audioRegions[0].endMs).toBeGreaterThan(result.audioRegions[0].startMs);
@@ -147,7 +166,13 @@ describe("Audio region normalization", () => {
const endMs = startMs + duration;
const result = normalizeProjectEditor({
audioRegions: [
- { id: "audio-1", startMs, endMs, audioPath: "/test.mp3", volume: 0.5 },
+ {
+ id: "audio-1",
+ startMs,
+ endMs,
+ audioPath: "/test.mp3",
+ volume: 0.5,
+ },
],
} as any);
expect(result.audioRegions[0].startMs).toBe(startMs);
@@ -162,7 +187,13 @@ describe("Audio region normalization", () => {
it("should preserve a valid string path", () => {
const result = normalizeProjectEditor({
audioRegions: [
- { id: "audio-1", startMs: 0, endMs: 1000, audioPath: "/Users/music/song.mp3", volume: 1 },
+ {
+ id: "audio-1",
+ startMs: 0,
+ endMs: 1000,
+ audioPath: "/Users/music/song.mp3",
+ volume: 1,
+ },
],
} as any);
expect(result.audioRegions[0].audioPath).toBe("/Users/music/song.mp3");
@@ -170,9 +201,7 @@ describe("Audio region normalization", () => {
it("should default to empty string for missing audioPath", () => {
const result = normalizeProjectEditor({
- audioRegions: [
- { id: "audio-1", startMs: 0, endMs: 1000, volume: 1 },
- ],
+ audioRegions: [{ id: "audio-1", startMs: 0, endMs: 1000, volume: 1 }],
} as any);
expect(result.audioRegions[0].audioPath).toBe("");
});
diff --git a/src/components/video-editor/captionLayout.ts b/src/components/video-editor/captionLayout.ts
index ca23ac1c..076cb5db 100644
--- a/src/components/video-editor/captionLayout.ts
+++ b/src/components/video-editor/captionLayout.ts
@@ -1,27 +1,27 @@
import type {
- AutoCaptionAnimation,
- AutoCaptionSettings,
- CaptionCue,
- CaptionCueWord,
+ AutoCaptionAnimation,
+ AutoCaptionSettings,
+ CaptionCue,
+ CaptionCueWord,
} from "./types";
export type CaptionWordState = "spoken" | "active" | "upcoming";
export interface CaptionWordLayout {
- text: string;
- index: number;
- forcedBreakBefore: boolean;
- leadingSpace: boolean;
- startMs: number;
- endMs: number;
- state: CaptionWordState;
+ text: string;
+ index: number;
+ forcedBreakBefore: boolean;
+ leadingSpace: boolean;
+ startMs: number;
+ endMs: number;
+ state: CaptionWordState;
}
export interface CaptionLineLayout {
- words: CaptionWordLayout[];
- width: number;
- startWordIndex: number;
- endWordIndex: number;
+ words: CaptionWordLayout[];
+ width: number;
+ startWordIndex: number;
+ endWordIndex: number;
}
interface CaptionPageLayout {
@@ -31,25 +31,25 @@ interface CaptionPageLayout {
}
export interface ActiveCaptionLayout {
- cue: CaptionCue;
- blockKey: string;
- visibleLines: CaptionLineLayout[];
- hasWordTimings: boolean;
- activeWordIndex: number;
- activeWordProgress: number;
- visiblePageIndex: number;
- opacity: number;
- translateY: number;
- scale: number;
+ cue: CaptionCue;
+ blockKey: string;
+ visibleLines: CaptionLineLayout[];
+ hasWordTimings: boolean;
+ activeWordIndex: number;
+ activeWordProgress: number;
+ visiblePageIndex: number;
+ opacity: number;
+ translateY: number;
+ scale: number;
}
type CaptionSourceWord = {
- cueId: string;
- text: string;
- forcedBreakBefore: boolean;
- leadingSpace?: boolean;
- startMs?: number;
- endMs?: number;
+ cueId: string;
+ text: string;
+ forcedBreakBefore: boolean;
+ leadingSpace?: boolean;
+ startMs?: number;
+ endMs?: number;
};
const CAPTION_ENTER_MS = 180;
@@ -57,407 +57,437 @@ const CAPTION_EXIT_MS = 140;
const CAPTION_BLOCK_GAP_BREAK_MS = 500;
function clamp(value: number, min: number, max: number) {
- return Math.min(max, Math.max(min, value));
+ return Math.min(max, Math.max(min, value));
}
function clamp01(value: number) {
- return clamp(value, 0, 1);
+ return clamp(value, 0, 1);
}
function splitCaptionWordsFromText(text: string) {
- const sourceLines = text
- .split(/\r?\n/)
- .map((line) => line.trim())
- .filter((line) => line.length > 0);
- const words: CaptionSourceWord[] = [];
-
- sourceLines.forEach((line, lineIndex) => {
- line.split(/\s+/).filter(Boolean).forEach((word, wordIndex) => {
- words.push({
- cueId: "",
- text: word,
- forcedBreakBefore: lineIndex > 0 && wordIndex === 0,
- });
- });
- });
-
- return words;
+ const sourceLines = text
+ .split(/\r?\n/)
+ .map((line) => line.trim())
+ .filter((line) => line.length > 0);
+ const words: CaptionSourceWord[] = [];
+
+ sourceLines.forEach((line, lineIndex) => {
+ line.split(/\s+/)
+ .filter(Boolean)
+ .forEach((word, wordIndex) => {
+ words.push({
+ cueId: "",
+ text: word,
+ forcedBreakBefore: lineIndex > 0 && wordIndex === 0,
+ });
+ });
+ });
+
+ return words;
}
function splitCaptionWords(cue: CaptionCue) {
- if (Array.isArray(cue.words) && cue.words.length > 0) {
- return cue.words
- .filter((word): word is CaptionCueWord => Boolean(word && typeof word.text === "string"))
- .map((word) => ({
- cueId: cue.id,
- text: word.text.trim(),
- forcedBreakBefore: false,
- leadingSpace: Boolean(word.leadingSpace),
- startMs: word.startMs,
- endMs: word.endMs,
- }))
- .filter((word) => word.text.length > 0);
- }
-
- return splitCaptionWordsFromText(cue.text);
+ if (Array.isArray(cue.words) && cue.words.length > 0) {
+ return cue.words
+ .filter((word): word is CaptionCueWord =>
+ Boolean(word && typeof word.text === "string"),
+ )
+ .map((word) => ({
+ cueId: cue.id,
+ text: word.text.trim(),
+ forcedBreakBefore: false,
+ leadingSpace: Boolean(word.leadingSpace),
+ startMs: word.startMs,
+ endMs: word.endMs,
+ }))
+ .filter((word) => word.text.length > 0);
+ }
+
+ return splitCaptionWordsFromText(cue.text);
}
function getActiveCaptionCue(cues: CaptionCue[], timeMs: number) {
- for (const cue of cues) {
- if (timeMs >= cue.startMs && timeMs <= cue.endMs) {
- return cue;
- }
- }
+ for (const cue of cues) {
+ if (timeMs >= cue.startMs && timeMs <= cue.endMs) {
+ return cue;
+ }
+ }
- return null;
+ return null;
}
function flattenCaptionWords(cues: CaptionCue[]) {
- const flattened: Array<{
- cueId: string;
- text: string;
- forcedBreakBefore: boolean;
- leadingSpace: boolean;
- startMs: number;
- endMs: number;
- hasRealTiming: boolean;
- }> = [];
-
- cues.forEach((cue, cueIndex) => {
- const sourceWords = splitCaptionWords(cue);
- if (sourceWords.length === 0) {
- return;
- }
-
- const cueHasRealWordTimings = sourceWords.every(
- (word) => isFiniteNumber(word.startMs) && isFiniteNumber(word.endMs) && word.endMs > word.startMs,
- );
- const cueDuration = Math.max(1, cue.endMs - cue.startMs);
- const fallbackWordDuration = cueDuration / sourceWords.length;
- const previousCue = cueIndex > 0 ? cues[cueIndex - 1] : null;
- const shouldForceCueBreak =
- previousCue !== null && cue.startMs - previousCue.endMs >= CAPTION_BLOCK_GAP_BREAK_MS;
-
- sourceWords.forEach((word, wordIndex) => {
- const fallbackStartMs = cue.startMs + fallbackWordDuration * wordIndex;
- const fallbackEndMs =
- wordIndex === sourceWords.length - 1
- ? cue.endMs
- : cue.startMs + fallbackWordDuration * (wordIndex + 1);
- const startsMergedCue = wordIndex === 0 && !word.forcedBreakBefore && !shouldForceCueBreak;
- const leadingSpace = wordIndex === 0
- ? flattened.length > 0 && startsMergedCue
- : (word.leadingSpace ?? true);
-
- flattened.push({
- cueId: cue.id,
- text: word.text,
- forcedBreakBefore:
- word.forcedBreakBefore || (wordIndex === 0 && shouldForceCueBreak),
- leadingSpace,
- startMs: cueHasRealWordTimings ? word.startMs! : fallbackStartMs,
- endMs: cueHasRealWordTimings ? word.endMs! : Math.max(fallbackStartMs + 1, fallbackEndMs),
- hasRealTiming: cueHasRealWordTimings,
- });
- });
- });
-
- return flattened;
+ const flattened: Array<{
+ cueId: string;
+ text: string;
+ forcedBreakBefore: boolean;
+ leadingSpace: boolean;
+ startMs: number;
+ endMs: number;
+ hasRealTiming: boolean;
+ }> = [];
+
+ cues.forEach((cue, cueIndex) => {
+ const sourceWords = splitCaptionWords(cue);
+ if (sourceWords.length === 0) {
+ return;
+ }
+
+ const cueHasRealWordTimings = sourceWords.every(
+ (word) =>
+ isFiniteNumber(word.startMs) &&
+ isFiniteNumber(word.endMs) &&
+ word.endMs > word.startMs,
+ );
+ const cueDuration = Math.max(1, cue.endMs - cue.startMs);
+ const fallbackWordDuration = cueDuration / sourceWords.length;
+ const previousCue = cueIndex > 0 ? cues[cueIndex - 1] : null;
+ const shouldForceCueBreak =
+ previousCue !== null && cue.startMs - previousCue.endMs >= CAPTION_BLOCK_GAP_BREAK_MS;
+
+ sourceWords.forEach((word, wordIndex) => {
+ const fallbackStartMs = cue.startMs + fallbackWordDuration * wordIndex;
+ const fallbackEndMs =
+ wordIndex === sourceWords.length - 1
+ ? cue.endMs
+ : cue.startMs + fallbackWordDuration * (wordIndex + 1);
+ const startsMergedCue =
+ wordIndex === 0 && !word.forcedBreakBefore && !shouldForceCueBreak;
+ const leadingSpace =
+ wordIndex === 0
+ ? flattened.length > 0 && startsMergedCue
+ : (word.leadingSpace ?? true);
+
+ flattened.push({
+ cueId: cue.id,
+ text: word.text,
+ forcedBreakBefore:
+ word.forcedBreakBefore || (wordIndex === 0 && shouldForceCueBreak),
+ leadingSpace,
+ startMs: cueHasRealWordTimings ? word.startMs! : fallbackStartMs,
+ endMs: cueHasRealWordTimings
+ ? word.endMs!
+ : Math.max(fallbackStartMs + 1, fallbackEndMs),
+ hasRealTiming: cueHasRealWordTimings,
+ });
+ });
+ });
+
+ return flattened;
}
function getCaptionAnimationState(
- animationStyle: AutoCaptionAnimation,
- enterProgress: number,
- exitProgress: number,
+ animationStyle: AutoCaptionAnimation,
+ enterProgress: number,
+ exitProgress: number,
) {
- const visibility = Math.min(enterProgress, exitProgress);
-
- switch (animationStyle) {
- case "none":
- return {
- opacity: 1,
- translateY: 0,
- scale: 1,
- };
- case "fade":
- return {
- opacity: 0.3 + visibility * 0.7,
- translateY: 0,
- scale: 1,
- };
- case "rise":
- return {
- opacity: 0.25 + visibility * 0.75,
- translateY: (1 - visibility) * 18,
- scale: 0.985 + visibility * 0.015,
- };
- case "pop":
- default:
- return {
- opacity: 0.35 + visibility * 0.65,
- translateY: (1 - visibility) * 8,
- scale: 0.94 + visibility * 0.06,
- };
- }
+ const visibility = Math.min(enterProgress, exitProgress);
+
+ switch (animationStyle) {
+ case "none":
+ return {
+ opacity: 1,
+ translateY: 0,
+ scale: 1,
+ };
+ case "fade":
+ return {
+ opacity: 0.3 + visibility * 0.7,
+ translateY: 0,
+ scale: 1,
+ };
+ case "rise":
+ return {
+ opacity: 0.25 + visibility * 0.75,
+ translateY: (1 - visibility) * 18,
+ scale: 0.985 + visibility * 0.015,
+ };
+ case "pop":
+ default:
+ return {
+ opacity: 0.35 + visibility * 0.65,
+ translateY: (1 - visibility) * 8,
+ scale: 0.94 + visibility * 0.06,
+ };
+ }
}
function buildCaptionPages(options: {
- lines: CaptionLineLayout[];
- words: CaptionWordLayout[];
- maxRows: number;
- hasWordTimings: boolean;
- cue: CaptionCue;
+ lines: CaptionLineLayout[];
+ words: CaptionWordLayout[];
+ maxRows: number;
+ hasWordTimings: boolean;
+ cue: CaptionCue;
}) {
- const pages: CaptionPageLayout[] = [];
- const totalPages = Math.max(1, Math.ceil(options.lines.length / options.maxRows));
- let lineIndex = 0;
- let remainingLines = options.lines.length;
-
- for (let pageIndex = 0; pageIndex < totalPages; pageIndex += 1) {
- const remainingPages = totalPages - pageIndex;
- const pageSize = Math.min(
- options.maxRows,
- Math.max(1, Math.ceil(remainingLines / remainingPages)),
- );
- const pageLines = options.lines.slice(lineIndex, lineIndex + pageSize);
- if (pageLines.length === 0) {
- continue;
- }
-
- lineIndex += pageLines.length;
- remainingLines -= pageLines.length;
-
- if (options.hasWordTimings) {
- const firstWord = options.words[pageLines[0].startWordIndex];
- const lastWord = options.words[pageLines[pageLines.length - 1].endWordIndex];
- pages.push({
- lines: pageLines,
- startMs: firstWord?.startMs ?? options.cue.startMs,
- endMs: lastWord?.endMs ?? options.cue.endMs,
- });
- continue;
- }
-
- pages.push({
- lines: pageLines,
- startMs: 0,
- endMs: 0,
- });
- }
-
- if (!options.hasWordTimings) {
- const totalWords = Math.max(1, options.words.length);
- const cueDuration = Math.max(1, options.cue.endMs - options.cue.startMs);
- let elapsedMs = options.cue.startMs;
-
- pages.forEach((page, pageIndex) => {
- const pageWordCount = page.lines.reduce((count, line) => count + line.words.length, 0);
- const proportionalDuration = Math.round((cueDuration * pageWordCount) / totalWords);
- const nextElapsed = pageIndex === pages.length - 1
- ? options.cue.endMs
- : Math.min(options.cue.endMs, elapsedMs + Math.max(1, proportionalDuration));
-
- page.startMs = elapsedMs;
- page.endMs = Math.max(elapsedMs + 1, nextElapsed);
- elapsedMs = page.endMs;
- });
- }
-
- for (let index = 0; index < pages.length - 1; index += 1) {
- pages[index].endMs = Math.max(pages[index].startMs + 1, pages[index + 1].startMs);
- }
-
- if (pages.length > 0) {
- pages[pages.length - 1].endMs = Math.max(pages[pages.length - 1].startMs + 1, options.cue.endMs);
- }
-
- return pages;
+ const pages: CaptionPageLayout[] = [];
+ const totalPages = Math.max(1, Math.ceil(options.lines.length / options.maxRows));
+ let lineIndex = 0;
+ let remainingLines = options.lines.length;
+
+ for (let pageIndex = 0; pageIndex < totalPages; pageIndex += 1) {
+ const remainingPages = totalPages - pageIndex;
+ const pageSize = Math.min(
+ options.maxRows,
+ Math.max(1, Math.ceil(remainingLines / remainingPages)),
+ );
+ const pageLines = options.lines.slice(lineIndex, lineIndex + pageSize);
+ if (pageLines.length === 0) {
+ continue;
+ }
+
+ lineIndex += pageLines.length;
+ remainingLines -= pageLines.length;
+
+ if (options.hasWordTimings) {
+ const firstWord = options.words[pageLines[0].startWordIndex];
+ const lastWord = options.words[pageLines[pageLines.length - 1].endWordIndex];
+ pages.push({
+ lines: pageLines,
+ startMs: firstWord?.startMs ?? options.cue.startMs,
+ endMs: lastWord?.endMs ?? options.cue.endMs,
+ });
+ continue;
+ }
+
+ pages.push({
+ lines: pageLines,
+ startMs: 0,
+ endMs: 0,
+ });
+ }
+
+ if (!options.hasWordTimings) {
+ const totalWords = Math.max(1, options.words.length);
+ const cueDuration = Math.max(1, options.cue.endMs - options.cue.startMs);
+ let elapsedMs = options.cue.startMs;
+
+ pages.forEach((page, pageIndex) => {
+ const pageWordCount = page.lines.reduce((count, line) => count + line.words.length, 0);
+ const proportionalDuration = Math.round((cueDuration * pageWordCount) / totalWords);
+ const nextElapsed =
+ pageIndex === pages.length - 1
+ ? options.cue.endMs
+ : Math.min(options.cue.endMs, elapsedMs + Math.max(1, proportionalDuration));
+
+ page.startMs = elapsedMs;
+ page.endMs = Math.max(elapsedMs + 1, nextElapsed);
+ elapsedMs = page.endMs;
+ });
+ }
+
+ for (let index = 0; index < pages.length - 1; index += 1) {
+ pages[index].endMs = Math.max(pages[index].startMs + 1, pages[index + 1].startMs);
+ }
+
+ if (pages.length > 0) {
+ pages[pages.length - 1].endMs = Math.max(
+ pages[pages.length - 1].startMs + 1,
+ options.cue.endMs,
+ );
+ }
+
+ return pages;
}
function buildCaptionLines(options: {
- words: CaptionWordLayout[];
- maxWidthPx: number;
- measureText: (text: string) => number;
+ words: CaptionWordLayout[];
+ maxWidthPx: number;
+ measureText: (text: string) => number;
}) {
- const wordCount = options.words.length;
- const segmentWidths = options.words.map((word, index) => {
- if (index === 0) {
- return options.measureText(word.text);
- }
-
- return options.measureText(`${word.leadingSpace ? " " : ""}${word.text}`);
- });
- const plainWordWidths = options.words.map((word) => options.measureText(word.text));
- const bestCost = new Array<number>(wordCount + 1).fill(Number.POSITIVE_INFINITY);
- const nextBreak = new Array<number>(wordCount).fill(wordCount);
-
- bestCost[wordCount] = 0;
-
- for (let startIndex = wordCount - 1; startIndex >= 0; startIndex -= 1) {
- let lineWidth = plainWordWidths[startIndex];
-
- for (let endIndex = startIndex; endIndex < wordCount; endIndex += 1) {
- if (endIndex > startIndex) {
- if (options.words[endIndex].forcedBreakBefore) {
- break;
- }
-
- lineWidth += segmentWidths[endIndex];
- }
-
- if (lineWidth > options.maxWidthPx && endIndex > startIndex) {
- break;
- }
-
- const slack = Math.max(0, options.maxWidthPx - lineWidth);
- const fullness = options.maxWidthPx <= 0 ? 1 : lineWidth / options.maxWidthPx;
- const isLastLine = endIndex === wordCount - 1;
- const linePenalty = isLastLine
- ? slack * slack * 0.18
- : slack * slack + (fullness < 0.72 ? (0.72 - fullness) * 26000 : 0);
- const candidateCost = linePenalty + bestCost[endIndex + 1];
-
- if (candidateCost < bestCost[startIndex]) {
- bestCost[startIndex] = candidateCost;
- nextBreak[startIndex] = endIndex + 1;
- }
- }
- }
-
- const lines: CaptionLineLayout[] = [];
- let startIndex = 0;
-
- while (startIndex < wordCount) {
- const endIndexExclusive = Math.max(startIndex + 1, nextBreak[startIndex]);
- const lineWords = options.words.slice(startIndex, endIndexExclusive).map((word, index) => ({
- ...word,
- leadingSpace: index === 0 ? false : word.leadingSpace,
- }));
- const width = lineWords.reduce(
- (total, word, index) => total + options.measureText(`${index === 0 ? "" : word.leadingSpace ? " " : ""}${word.text}`),
- 0,
- );
-
- lines.push({
- words: lineWords,
- width,
- startWordIndex: lineWords[0].index,
- endWordIndex: lineWords[lineWords.length - 1].index,
- });
-
- startIndex = endIndexExclusive;
- }
-
- return lines;
+ const wordCount = options.words.length;
+ const segmentWidths = options.words.map((word, index) => {
+ if (index === 0) {
+ return options.measureText(word.text);
+ }
+
+ return options.measureText(`${word.leadingSpace ? " " : ""}${word.text}`);
+ });
+ const plainWordWidths = options.words.map((word) => options.measureText(word.text));
+ const bestCost = new Array<number>(wordCount + 1).fill(Number.POSITIVE_INFINITY);
+ const nextBreak = new Array<number>(wordCount).fill(wordCount);
+
+ bestCost[wordCount] = 0;
+
+ for (let startIndex = wordCount - 1; startIndex >= 0; startIndex -= 1) {
+ let lineWidth = plainWordWidths[startIndex];
+
+ for (let endIndex = startIndex; endIndex < wordCount; endIndex += 1) {
+ if (endIndex > startIndex) {
+ if (options.words[endIndex].forcedBreakBefore) {
+ break;
+ }
+
+ lineWidth += segmentWidths[endIndex];
+ }
+
+ if (lineWidth > options.maxWidthPx && endIndex > startIndex) {
+ break;
+ }
+
+ const slack = Math.max(0, options.maxWidthPx - lineWidth);
+ const fullness = options.maxWidthPx <= 0 ? 1 : lineWidth / options.maxWidthPx;
+ const isLastLine = endIndex === wordCount - 1;
+ const linePenalty = isLastLine
+ ? slack * slack * 0.18
+ : slack * slack + (fullness < 0.72 ? (0.72 - fullness) * 26000 : 0);
+ const candidateCost = linePenalty + bestCost[endIndex + 1];
+
+ if (candidateCost < bestCost[startIndex]) {
+ bestCost[startIndex] = candidateCost;
+ nextBreak[startIndex] = endIndex + 1;
+ }
+ }
+ }
+
+ const lines: CaptionLineLayout[] = [];
+ let startIndex = 0;
+
+ while (startIndex < wordCount) {
+ const endIndexExclusive = Math.max(startIndex + 1, nextBreak[startIndex]);
+ const lineWords = options.words.slice(startIndex, endIndexExclusive).map((word, index) => ({
+ ...word,
+ leadingSpace: index === 0 ? false : word.leadingSpace,
+ }));
+ const width = lineWords.reduce(
+ (total, word, index) =>
+ total +
+ options.measureText(
+ `${index === 0 ? "" : word.leadingSpace ? " " : ""}${word.text}`,
+ ),
+ 0,
+ );
+
+ lines.push({
+ words: lineWords,
+ width,
+ startWordIndex: lineWords[0].index,
+ endWordIndex: lineWords[lineWords.length - 1].index,
+ });
+
+ startIndex = endIndexExclusive;
+ }
+
+ return lines;
}
function getVisibleCaptionPageIndex(pages: CaptionPageLayout[], timeMs: number) {
- for (let index = 0; index < pages.length; index += 1) {
- if (timeMs >= pages[index].startMs && timeMs <= pages[index].endMs) {
- return index;
- }
- }
+ for (let index = 0; index < pages.length; index += 1) {
+ if (timeMs >= pages[index].startMs && timeMs <= pages[index].endMs) {
+ return index;
+ }
+ }
- return -1;
+ return -1;
}
export function buildActiveCaptionLayout(options: {
- cues: CaptionCue[];
- timeMs: number;
- settings: AutoCaptionSettings;
- maxWidthPx: number;
- measureText: (text: string) => number;
+ cues: CaptionCue[];
+ timeMs: number;
+ settings: AutoCaptionSettings;
+ maxWidthPx: number;
+ measureText: (text: string) => number;
}) {
- const sourceWords = flattenCaptionWords(options.cues);
- if (sourceWords.length === 0) {
- return null;
- }
-
- const hasWordTimings = sourceWords.every((word) => word.hasRealTiming);
-
- let activeWordIndex = -1;
- if (hasWordTimings) {
- activeWordIndex = sourceWords.findIndex((word) => options.timeMs >= word.startMs && options.timeMs < word.endMs);
- if (activeWordIndex < 0) {
- activeWordIndex = sourceWords.findIndex((word) => options.timeMs < word.startMs);
- activeWordIndex = activeWordIndex < 0 ? sourceWords.length - 1 : clamp(activeWordIndex - 1, 0, sourceWords.length - 1);
- }
- }
- const maxRows = clamp(Math.round(options.settings.maxRows || 1), 1, 4);
-
- const words: CaptionWordLayout[] = sourceWords.map((word, index) => {
- return {
- text: word.text,
- index,
- forcedBreakBefore: word.forcedBreakBefore,
- leadingSpace: word.leadingSpace,
- startMs: word.startMs,
- endMs: word.endMs,
- state: !hasWordTimings
- ? "spoken"
- : index < activeWordIndex
- ? "spoken"
- : index === activeWordIndex
- ? "active"
- : "upcoming",
- };
- });
-
- const lines = buildCaptionLines({
- words,
- maxWidthPx: options.maxWidthPx,
- measureText: options.measureText,
- });
-
- const pages = buildCaptionPages({
- lines,
- words,
- maxRows,
- hasWordTimings: true,
- cue: {
- id: sourceWords[0].cueId,
- startMs: sourceWords[0].startMs,
- endMs: sourceWords[sourceWords.length - 1].endMs,
- text: "",
- },
- });
- const visiblePageIndex = getVisibleCaptionPageIndex(pages, options.timeMs);
- if (visiblePageIndex < 0) {
- return null;
- }
- const visiblePage = pages[visiblePageIndex] ?? null;
- const visibleLines = visiblePage?.lines ?? lines.slice(0, maxRows);
- const activeWord = activeWordIndex >= 0 ? words[activeWordIndex] : null;
- const activeWordProgress = activeWord
- ? clamp01((options.timeMs - activeWord.startMs) / Math.max(1, activeWord.endMs - activeWord.startMs))
- : 0;
- const animationStartMs = visiblePage?.startMs ?? sourceWords[0].startMs;
- const animationEndMs = visiblePage?.endMs ?? sourceWords[sourceWords.length - 1].endMs;
- const pageStartWordIndex = visibleLines[0]?.startWordIndex ?? 0;
- const pageCueId = sourceWords[pageStartWordIndex]?.cueId ?? sourceWords[0].cueId;
- const activeCue = getActiveCaptionCue(options.cues, options.timeMs) ?? options.cues.find((candidate) => candidate.id === pageCueId) ?? options.cues[0];
- const enterProgress = clamp01((options.timeMs - animationStartMs) / CAPTION_ENTER_MS);
- const exitProgress = clamp01((animationEndMs - options.timeMs) / CAPTION_EXIT_MS);
- const animation = getCaptionAnimationState(
- options.settings.animationStyle,
- enterProgress,
- exitProgress,
- );
-
- return {
- cue: activeCue,
- blockKey: `${Math.round(animationStartMs)}-${Math.round(animationEndMs)}`,
- visibleLines,
- hasWordTimings,
- activeWordIndex,
- activeWordProgress,
- visiblePageIndex,
- opacity: animation.opacity,
- translateY: animation.translateY,
- scale: animation.scale,
- } satisfies ActiveCaptionLayout;
+ const sourceWords = flattenCaptionWords(options.cues);
+ if (sourceWords.length === 0) {
+ return null;
+ }
+
+ const hasWordTimings = sourceWords.every((word) => word.hasRealTiming);
+
+ let activeWordIndex = -1;
+ if (hasWordTimings) {
+ activeWordIndex = sourceWords.findIndex(
+ (word) => options.timeMs >= word.startMs && options.timeMs < word.endMs,
+ );
+ if (activeWordIndex < 0) {
+ activeWordIndex = sourceWords.findIndex((word) => options.timeMs < word.startMs);
+ activeWordIndex =
+ activeWordIndex < 0
+ ? sourceWords.length - 1
+ : clamp(activeWordIndex - 1, 0, sourceWords.length - 1);
+ }
+ }
+ const maxRows = clamp(Math.round(options.settings.maxRows || 1), 1, 4);
+
+ const words: CaptionWordLayout[] = sourceWords.map((word, index) => {
+ return {
+ text: word.text,
+ index,
+ forcedBreakBefore: word.forcedBreakBefore,
+ leadingSpace: word.leadingSpace,
+ startMs: word.startMs,
+ endMs: word.endMs,
+ state: !hasWordTimings
+ ? "spoken"
+ : index < activeWordIndex
+ ? "spoken"
+ : index === activeWordIndex
+ ? "active"
+ : "upcoming",
+ };
+ });
+
+ const lines = buildCaptionLines({
+ words,
+ maxWidthPx: options.maxWidthPx,
+ measureText: options.measureText,
+ });
+
+ const pages = buildCaptionPages({
+ lines,
+ words,
+ maxRows,
+ hasWordTimings: true,
+ cue: {
+ id: sourceWords[0].cueId,
+ startMs: sourceWords[0].startMs,
+ endMs: sourceWords[sourceWords.length - 1].endMs,
+ text: "",
+ },
+ });
+ const visiblePageIndex = getVisibleCaptionPageIndex(pages, options.timeMs);
+ if (visiblePageIndex < 0) {
+ return null;
+ }
+ const visiblePage = pages[visiblePageIndex] ?? null;
+ const visibleLines = visiblePage?.lines ?? lines.slice(0, maxRows);
+ const activeWord = activeWordIndex >= 0 ? words[activeWordIndex] : null;
+ const activeWordProgress = activeWord
+ ? clamp01(
+ (options.timeMs - activeWord.startMs) /
+ Math.max(1, activeWord.endMs - activeWord.startMs),
+ )
+ : 0;
+ const animationStartMs = visiblePage?.startMs ?? sourceWords[0].startMs;
+ const animationEndMs = visiblePage?.endMs ?? sourceWords[sourceWords.length - 1].endMs;
+ const pageStartWordIndex = visibleLines[0]?.startWordIndex ?? 0;
+ const pageCueId = sourceWords[pageStartWordIndex]?.cueId ?? sourceWords[0].cueId;
+ const activeCue =
+ getActiveCaptionCue(options.cues, options.timeMs) ??
+ options.cues.find((candidate) => candidate.id === pageCueId) ??
+ options.cues[0];
+ const enterProgress = clamp01((options.timeMs - animationStartMs) / CAPTION_ENTER_MS);
+ const exitProgress = clamp01((animationEndMs - options.timeMs) / CAPTION_EXIT_MS);
+ const animation = getCaptionAnimationState(
+ options.settings.animationStyle,
+ enterProgress,
+ exitProgress,
+ );
+
+ return {
+ cue: activeCue,
+ blockKey: `${Math.round(animationStartMs)}-${Math.round(animationEndMs)}`,
+ visibleLines,
+ hasWordTimings,
+ activeWordIndex,
+ activeWordProgress,
+ visiblePageIndex,
+ opacity: animation.opacity,
+ translateY: animation.translateY,
+ scale: animation.scale,
+ } satisfies ActiveCaptionLayout;
}
function isFiniteNumber(value: unknown): value is number {
return typeof value === "number" && Number.isFinite(value);
-}
\ No newline at end of file
+}
diff --git a/src/components/video-editor/captionStyle.ts b/src/components/video-editor/captionStyle.ts
index 47953092..65ae376b 100644
--- a/src/components/video-editor/captionStyle.ts
+++ b/src/components/video-editor/captionStyle.ts
@@ -4,8 +4,7 @@ import { DEFAULT_AUTO_CAPTION_SETTINGS } from "./types";
export const CAPTION_FONT_WEIGHT = 400;
export const CAPTION_LINE_HEIGHT = 1.32;
-const DEFAULT_CAPTION_REFERENCE_WIDTH =
- 1920 * (DEFAULT_AUTO_CAPTION_SETTINGS.maxWidth / 100);
+const DEFAULT_CAPTION_REFERENCE_WIDTH = 1920 * (DEFAULT_AUTO_CAPTION_SETTINGS.maxWidth / 100);
export function getCaptionTargetWidth(containerWidth: number, maxWidthPercent: number) {
return Math.max(1, containerWidth * (maxWidthPercent / 100));
@@ -18,7 +17,9 @@ export function getCaptionScaledFontSize(
) {
return Math.max(
14,
- fontSize * (getCaptionTargetWidth(containerWidth, maxWidthPercent) / DEFAULT_CAPTION_REFERENCE_WIDTH),
+ fontSize *
+ (getCaptionTargetWidth(containerWidth, maxWidthPercent) /
+ DEFAULT_CAPTION_REFERENCE_WIDTH),
);
}
@@ -34,9 +35,16 @@ export function getCaptionScaledRadius(radius: number, fontSize: number) {
return Math.max(0, radius * (fontSize / baseline));
}
-export function getCaptionTextMaxWidth(containerWidth: number, maxWidthPercent: number, fontSize: number) {
+export function getCaptionTextMaxWidth(
+ containerWidth: number,
+ maxWidthPercent: number,
+ fontSize: number,
+) {
const padding = getCaptionPadding(fontSize);
- return Math.max(fontSize * 4, getCaptionTargetWidth(containerWidth, maxWidthPercent) - padding.x * 2);
+ return Math.max(
+ fontSize * 4,
+ getCaptionTargetWidth(containerWidth, maxWidthPercent) - padding.x * 2,
+ );
}
export function getCaptionWordVisualState(hasWordTimings: boolean, state: CaptionWordState) {
@@ -65,4 +73,4 @@ export function getCaptionWordVisualState(hasWordTimings: boolean, state: Captio
opacity: 1,
};
}
-}
\ No newline at end of file
+}
diff --git a/src/components/video-editor/index.ts b/src/components/video-editor/index.ts
index 8f1578b0..5afe5b8b 100644
--- a/src/components/video-editor/index.ts
+++ b/src/components/video-editor/index.ts
@@ -1,6 +1,5 @@
-export { default as VideoEditor } from './VideoEditor';
-export { default as VideoPlayback } from './VideoPlayback';
-export { default as PlaybackControls } from './PlaybackControls';
-export { default as TimelineEditor } from './timeline/TimelineEditor';
-export { default as SettingsPanel } from './SettingsPanel';
-
+export { default as PlaybackControls } from "./PlaybackControls";
+export { default as SettingsPanel } from "./SettingsPanel";
+export { default as TimelineEditor } from "./timeline/TimelineEditor";
+export { default as VideoEditor } from "./VideoEditor";
+export { default as VideoPlayback } from "./VideoPlayback";
diff --git a/src/components/video-editor/types.ts b/src/components/video-editor/types.ts
index 91d77a37..b47a2104 100644
--- a/src/components/video-editor/types.ts
+++ b/src/components/video-editor/types.ts
@@ -20,7 +20,14 @@ export interface CursorTelemetryPoint {
timeMs: number;
cx: number;
cy: number;
- interactionType?: "move" | "click" | "double-click" | "right-click" | "middle-click" | "mouseup";
+ pressure?: number;
+ interactionType?:
+ | "move"
+ | "click"
+ | "double-click"
+ | "right-click"
+ | "middle-click"
+ | "mouseup";
cursorType?:
| "arrow"
| "text"
@@ -43,12 +50,7 @@ export interface CursorVisualSettings {
style: CursorStyle;
}
-export type CursorStyle =
- | "tahoe"
- | "dot"
- | "figma"
- | "mono"
- | (string & {}); // extension-contributed cursor styles
+export type CursorStyle = "tahoe" | "dot" | "figma" | "mono" | (string & {}); // extension-contributed cursor styles
export const DEFAULT_CURSOR_STYLE: CursorStyle = "tahoe";
export type ZoomTransitionEasing = "recordly" | "glide" | "smooth" | "snappy" | "linear";
@@ -131,6 +133,13 @@ export interface ClipRegion {
startMs: number;
endMs: number;
speed: number;
+ muted?: boolean;
+}
+
+export function getClipSourceEndMs(clip: ClipRegion): number {
+ const displayDurationMs = Math.max(0, clip.endMs - clip.startMs);
+ const speed = Number.isFinite(clip.speed) && clip.speed > 0 ? clip.speed : 1;
+ return Math.round(clip.startMs + displayDurationMs * speed);
}
/** Convert clip regions (kept segments) to trim regions (gaps to remove). */
@@ -144,7 +153,7 @@ export function clipsToTrims(clips: ClipRegion[], totalDurationMs: number): Trim
if (clip.startMs > cursor) {
trims.push({ id: `trim-gap-${trimId++}`, startMs: cursor, endMs: clip.startMs });
}
- cursor = clip.endMs;
+ cursor = getClipSourceEndMs(clip);
}
if (cursor < totalDurationMs) {
trims.push({ id: `trim-gap-${trimId++}`, startMs: cursor, endMs: totalDurationMs });
@@ -176,7 +185,6 @@ export const BLUR_ANNOTATION_STRENGTH = 20;
export const BASE_PREVIEW_WIDTH = 1920;
export const BASE_PREVIEW_HEIGHT = 1080;
-
export type ArrowDirection =
| "up"
| "down"
@@ -246,6 +254,7 @@ export interface AnnotationRegion {
figureData?: FigureData;
blurIntensity?: number;
blurColor?: string;
+ trackIndex?: number;
}
export const DEFAULT_ANNOTATION_POSITION: AnnotationPosition = {
@@ -296,6 +305,7 @@ export interface AudioRegion {
endMs: number;
audioPath: string;
volume: number;
+ trackIndex?: number;
}
export interface CaptionCue {
diff --git a/src/components/video-editor/webcamOverlay.ts b/src/components/video-editor/webcamOverlay.ts
index 8d316837..5144231a 100644
--- a/src/components/video-editor/webcamOverlay.ts
+++ b/src/components/video-editor/webcamOverlay.ts
@@ -6,9 +6,7 @@ function clamp(value: number, min: number, max: number) {
return Math.min(max, Math.max(min, value));
}
-export function getWebcamPositionForPreset(
- preset: WebcamPositionPreset,
-): { x: number; y: number } {
+export function getWebcamPositionForPreset(preset: WebcamPositionPreset): { x: number; y: number } {
switch (preset) {
case "top-left":
return { x: 0, y: 0 };
@@ -50,10 +48,7 @@ export function resolveWebcamCorner(
return isCornerPreset(preset) ? preset : legacyCorner;
}
-export function getWebcamOverlayScale(
- zoomScale: number,
- reactToZoom: boolean,
-): number {
+export function getWebcamOverlayScale(zoomScale: number, reactToZoom: boolean): number {
const safeZoomScale = Number.isFinite(zoomScale) && zoomScale > 0 ? zoomScale : 1;
return reactToZoom ? 1 / safeZoomScale : 1;
}
@@ -78,9 +73,7 @@ export function getWebcamOverlaySizePx({
const safeMargin = Math.max(0, margin);
const maxSize = Math.max(MIN_WEBCAM_OVERLAY_SIZE_PX, minDimension - safeMargin * 2);
const scaledSize =
- minDimension
- * (clampedSizePercent / 100)
- * getWebcamOverlayScale(zoomScale, reactToZoom);
+ minDimension * (clampedSizePercent / 100) * getWebcamOverlayScale(zoomScale, reactToZoom);
return Math.min(maxSize, Math.max(MIN_WEBCAM_OVERLAY_SIZE_PX, scaledSize));
}
diff --git a/src/index.css b/src/index.css
index 680e5297..b3ec7cdf 100644
--- a/src/index.css
+++ b/src/index.css
@@ -1,199 +1,225 @@
-@tailwind base;
-@tailwind components;
-@tailwind utilities;
-
-@layer base {
- html,
- body,
- #root {
- width: 100%;
- height: 100%;
- margin: 0;
- }
-
- :root {
- --brand-accent: #2563eb;
- --brand-accent-rgb: 37, 99, 235;
- --background: 0 0% 100%;
- --foreground: 20 14.3% 4.1%;
- --card: 0 0% 100%;
- --card-foreground: 20 14.3% 4.1%;
- --popover: 0 0% 100%;
- --popover-foreground: 20 14.3% 4.1%;
- --primary: 221 83% 53%;
- --primary-foreground: 210 40% 98%;
- --secondary: 60 4.8% 95.9%;
- --secondary-foreground: 24 9.8% 10%;
- --muted: 60 4.8% 95.9%;
- --muted-foreground: 25 5.3% 44.7%;
- --accent: 214 100% 97%;
- --accent-foreground: 221 83% 40%;
- --destructive: 0 84.2% 60.2%;
- --destructive-foreground: 60 9.1% 97.8%;
- --border: 20 5.9% 90%;
- --input: 20 5.9% 90%;
- --ring: 221 83% 53%;
- --chart-1: 12 76% 61%;
- --chart-2: 173 58% 39%;
- --chart-3: 197 37% 24%;
- --chart-4: 43 74% 66%;
- --chart-5: 27 87% 67%;
- --radius: 0.5rem;
- }
- .dark {
- --background: 20 14.3% 4.1%;
- --foreground: 60 9.1% 97.8%;
- --card: 20 14.3% 4.1%;
- --card-foreground: 60 9.1% 97.8%;
- --popover: 20 14.3% 4.1%;
- --popover-foreground: 60 9.1% 97.8%;
- --primary: 221 83% 53%;
- --primary-foreground: 210 40% 98%;
- --secondary: 12 6.5% 15.1%;
- --secondary-foreground: 60 9.1% 97.8%;
- --muted: 12 6.5% 15.1%;
- --muted-foreground: 24 5.4% 63.9%;
- --accent: 217 33% 17%;
- --accent-foreground: 210 40% 98%;
- --destructive: 0 62.8% 30.6%;
- --destructive-foreground: 60 9.1% 97.8%;
- --border: 12 6.5% 15.1%;
- --input: 12 6.5% 15.1%;
- --ring: 221 83% 53%;
- --chart-1: 220 70% 50%;
- --chart-2: 160 60% 45%;
- --chart-3: 30 80% 55%;
- --chart-4: 280 65% 60%;
- --chart-5: 340 75% 55%;
- }
-}
-
-
-@layer base {
- * {
- @apply border-border;
- }
- body {
- @apply bg-background text-foreground;
- -webkit-user-select: none;
- user-select: none;
- font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
- }
-
- button,
- input,
- textarea,
- select {
- font: inherit;
- }
-
- [data-platform="macos"] body {
- font-family: "SF Pro Display", "SF Pro Text", -apple-system, BlinkMacSystemFont, sans-serif;
- }
-
- [data-platform="macos"] body .font-mono,
- [data-platform="macos"] body kbd {
- font-family: "SF Pro Text", "SF Pro Display", -apple-system, BlinkMacSystemFont, sans-serif;
- }
-}
-
-/* Smooth timeline cursor animations */
-@layer utilities {
- .timeline-cursor-smooth {
- will-change: transform;
- transition: left 33ms linear, right 33ms linear;
- }
-
- .indeterminate-progress {
- position: relative;
- overflow: hidden;
- isolation: isolate;
- }
-
- .indeterminate-progress::before {
- content: "";
- position: absolute;
- inset: 0;
- width: 38%;
- min-width: 3.5rem;
- border-radius: inherit;
- background: linear-gradient(90deg, rgba(37, 99, 235, 0) 0%, rgba(37, 99, 235, 0.35) 18%, rgba(96, 165, 250, 0.92) 52%, rgba(37, 99, 235, 0.3) 82%, rgba(37, 99, 235, 0) 100%);
- animation: indeterminate-progress 1.15s cubic-bezier(0.4, 0, 0.2, 1) infinite;
- }
-
- /* Hidden scrollbar - still scrollable but invisible */
- .custom-scrollbar {
- scrollbar-width: none; /* Firefox */
- -ms-overflow-style: none; /* IE/Edge */
- }
-
- .custom-scrollbar::-webkit-scrollbar {
- display: none; /* Chrome, Safari, Opera */
- }
-
- /* Smooth playback scrubber */
- input[type="range"] {
- -webkit-appearance: none;
- appearance: none;
- }
-
- input[type="range"]::-webkit-slider-thumb {
- -webkit-appearance: none;
- appearance: none;
- width: 16px;
- height: 16px;
- border-radius: 50%;
- background: #fff;
- cursor: pointer;
- box-shadow: 0 2px 8px rgba(255,255,255,0.32);
- border: 2px solid #fff;
- transition: all 0.08s ease-out;
- }
-
- input[type="range"]::-webkit-slider-thumb:hover {
- background: #fff;
- transform: scale(1.15);
- box-shadow: 0 3px 10px rgba(255,255,255,0.5);
- border-color: var(--brand-accent);
- }
-
- input[type="range"]::-webkit-slider-thumb:active {
- transform: scale(1.25);
- }
-
- input[type="range"]::-moz-range-thumb {
- width: 16px;
- height: 16px;
- border-radius: 50%;
- background: #fff;
- cursor: pointer;
- border: 2px solid #fff;
- box-shadow: 0 2px 8px rgba(255,255,255,0.32);
- transition: all 0.08s ease-out;
- }
-
- input[type="range"]::-moz-range-thumb:hover {
- background: #fff;
- transform: scale(1.15);
- box-shadow: 0 3px 10px rgba(255,255,255,0.5);
- border-color: var(--brand-accent);
- }
-
- input[type="range"]::-moz-range-thumb:active {
- transform: scale(1.25);
- }
-}
-
-@keyframes indeterminate-progress {
- 0% {
- transform: translateX(-150%);
- }
-
- 60% {
- transform: translateX(270%);
- }
-
- 100% {
- transform: translateX(270%);
- }
-}
+@tailwind base;
+@tailwind components;
+@tailwind utilities;
+
+@layer base {
+ /* Disable Electron/Chromium focus highlight (yellow/orange ring) */
+ *:focus {
+ outline: none !important;
+ -webkit-tap-highlight-color: transparent;
+ }
+
+ html,
+ body,
+ #root {
+ width: 100%;
+ height: 100%;
+ margin: 0;
+ }
+
+ :root {
+ --brand-accent: #2563eb;
+ --brand-accent-rgb: 37, 99, 235;
+ --background: 0 0% 100%;
+ --foreground: 20 14.3% 4.1%;
+ --card: 0 0% 100%;
+ --card-foreground: 20 14.3% 4.1%;
+ --popover: 0 0% 100%;
+ --popover-foreground: 20 14.3% 4.1%;
+ --primary: 221 83% 53%;
+ --primary-foreground: 210 40% 98%;
+ --secondary: 60 4.8% 95.9%;
+ --secondary-foreground: 24 9.8% 10%;
+ --muted: 60 4.8% 95.9%;
+ --muted-foreground: 25 5.3% 44.7%;
+ --accent: 214 100% 97%;
+ --accent-foreground: 221 83% 40%;
+ --destructive: 0 84.2% 60.2%;
+ --destructive-foreground: 60 9.1% 97.8%;
+ --border: 20 5.9% 90%;
+ --input: 20 5.9% 90%;
+ --ring: 221 83% 53%;
+ --chart-1: 12 76% 61%;
+ --chart-2: 173 58% 39%;
+ --chart-3: 197 37% 24%;
+ --chart-4: 43 74% 66%;
+ --chart-5: 27 87% 67%;
+ --radius: 0.5rem;
+ }
+ .dark {
+ --background: 20 14.3% 4.1%;
+ --foreground: 60 9.1% 97.8%;
+ --card: 20 14.3% 4.1%;
+ --card-foreground: 60 9.1% 97.8%;
+ --popover: 20 14.3% 4.1%;
+ --popover-foreground: 60 9.1% 97.8%;
+ --primary: 221 83% 53%;
+ --primary-foreground: 210 40% 98%;
+ --secondary: 12 6.5% 15.1%;
+ --secondary-foreground: 60 9.1% 97.8%;
+ --muted: 12 6.5% 15.1%;
+ --muted-foreground: 24 5.4% 63.9%;
+ --accent: 217 33% 17%;
+ --accent-foreground: 210 40% 98%;
+ --destructive: 0 62.8% 30.6%;
+ --destructive-foreground: 60 9.1% 97.8%;
+ --border: 12 6.5% 15.1%;
+ --input: 12 6.5% 15.1%;
+ --ring: 221 83% 53%;
+ --chart-1: 220 70% 50%;
+ --chart-2: 160 60% 45%;
+ --chart-3: 30 80% 55%;
+ --chart-4: 280 65% 60%;
+ --chart-5: 340 75% 55%;
+ }
+}
+
+@layer base {
+ * {
+ @apply border-border;
+ }
+ body {
+ @apply bg-background text-foreground;
+ -webkit-user-select: none;
+ user-select: none;
+ font-family: "Helvetica Neue", Helvetica, Arial, sans-serif;
+ }
+
+ button,
+ input,
+ textarea,
+ select {
+ font: inherit;
+ }
+
+ [data-platform="macos"] body {
+ font-family: "SF Pro Display", "SF Pro Text", -apple-system, BlinkMacSystemFont, sans-serif;
+ }
+
+ [data-platform="macos"] body .font-mono,
+ [data-platform="macos"] body kbd {
+ font-family: "SF Pro Text", "SF Pro Display", -apple-system, BlinkMacSystemFont, sans-serif;
+ }
+}
+
+/* Smooth timeline cursor animations */
+@layer utilities {
+ .timeline-cursor-smooth {
+ will-change: transform;
+ transition:
+ left 33ms linear,
+ right 33ms linear;
+ }
+
+ .indeterminate-progress {
+ position: relative;
+ overflow: hidden;
+ isolation: isolate;
+ }
+
+ .indeterminate-progress::before {
+ content: "";
+ position: absolute;
+ inset: 0;
+ width: 38%;
+ min-width: 3.5rem;
+ border-radius: inherit;
+ background: linear-gradient(
+ 90deg,
+ rgba(37, 99, 235, 0) 0%,
+ rgba(37, 99, 235, 0.35) 18%,
+ rgba(96, 165, 250, 0.92) 52%,
+ rgba(37, 99, 235, 0.3) 82%,
+ rgba(37, 99, 235, 0) 100%
+ );
+ animation: indeterminate-progress 1.15s cubic-bezier(0.4, 0, 0.2, 1) infinite;
+ }
+
+ /* Hidden scrollbar - still scrollable but invisible */
+ .custom-scrollbar {
+ scrollbar-width: none; /* Firefox */
+ -ms-overflow-style: none; /* IE/Edge */
+ }
+
+ .custom-scrollbar::-webkit-scrollbar {
+ display: none; /* Chrome, Safari, Opera */
+ }
+
+ /* Smooth playback scrubber */
+ input[type="range"] {
+ -webkit-appearance: none;
+ appearance: none;
+ }
+
+ input[type="range"]::-webkit-slider-runnable-track {
+ border-radius: 100px;
+ height: 4px;
+ background: rgba(255, 255, 255, 0.12);
+ }
+
+ input[type="range"]::-moz-range-track {
+ border-radius: 100px;
+ height: 4px;
+ background: rgba(255, 255, 255, 0.12);
+ }
+
+ input[type="range"]::-webkit-slider-thumb {
+ -webkit-appearance: none;
+ appearance: none;
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: #fff;
+ cursor: pointer;
+ box-shadow: 0 2px 8px rgba(255, 255, 255, 0.32);
+ border: 2px solid #fff;
+ transition: all 0.08s ease-out;
+ }
+
+ input[type="range"]::-webkit-slider-thumb:hover {
+ background: #fff;
+ transform: scale(1.15);
+ box-shadow: 0 3px 10px rgba(255, 255, 255, 0.5);
+ border-color: var(--brand-accent);
+ }
+
+ input[type="range"]::-webkit-slider-thumb:active {
+ transform: scale(1.25);
+ }
+
+ input[type="range"]::-moz-range-thumb {
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: #fff;
+ cursor: pointer;
+ border: 2px solid #fff;
+ box-shadow: 0 2px 8px rgba(255, 255, 255, 0.32);
+ transition: all 0.08s ease-out;
+ }
+
+ input[type="range"]::-moz-range-thumb:hover {
+ background: #fff;
+ transform: scale(1.15);
+ box-shadow: 0 3px 10px rgba(255, 255, 255, 0.5);
+ border-color: var(--brand-accent);
+ }
+
+ input[type="range"]::-moz-range-thumb:active {
+ transform: scale(1.25);
+ }
+}
+
+@keyframes indeterminate-progress {
+ 0% {
+ transform: translateX(-150%);
+ }
+
+ 60% {
+ transform: translateX(270%);
+ }
+
+ 100% {
+ transform: translateX(270%);
+ }
+}
diff --git a/src/lib/assetPath.ts b/src/lib/assetPath.ts
index 30069b23..2346f7cd 100644
--- a/src/lib/assetPath.ts
+++ b/src/lib/assetPath.ts
@@ -1,111 +1,123 @@
function encodeRelativeAssetPath(relativePath: string): string {
- return relativePath
- .replace(/^\/+/, '')
- .split('/')
- .filter(Boolean)
- .map((part) => encodeURIComponent(part))
- .join('/')
+ return relativePath
+ .replace(/^\/+/, "")
+ .split("/")
+ .filter(Boolean)
+ .map((part) => encodeURIComponent(part))
+ .join("/");
}
function ensureTrailingSlash(value: string): string {
- return value.endsWith('/') ? value : `${value}/`
+ return value.endsWith("/") ? value : `${value}/`;
}
export async function getAssetPath(relativePath: string): Promise<string> {
- const encodedRelativePath = encodeRelativeAssetPath(relativePath)
-
- try {
- if (typeof window !== 'undefined') {
- // If running in a dev server (http/https), prefer the web-served path
- if (window.location && window.location.protocol && window.location.protocol.startsWith('http')) {
- return `/${encodedRelativePath}`
- }
-
- if ((window as any).electronAPI && typeof (window as any).electronAPI.getAssetBasePath === 'function') {
- const base = await (window as any).electronAPI.getAssetBasePath()
- if (base) {
- return new URL(encodedRelativePath, ensureTrailingSlash(base)).toString()
- }
- }
- }
- } catch (err) {
- // ignore and use fallback
- }
-
- // Fallback for web/dev server: public/wallpapers are served at '/wallpapers/...'
- return `/${encodedRelativePath}`
+ const encodedRelativePath = encodeRelativeAssetPath(relativePath);
+
+ try {
+ if (typeof window !== "undefined") {
+ // If running in a dev server (http/https), prefer the web-served path
+ if (
+ window.location &&
+ window.location.protocol &&
+ window.location.protocol.startsWith("http")
+ ) {
+ return `/${encodedRelativePath}`;
+ }
+
+ if (typeof window.electronAPI?.getAssetBasePath === "function") {
+ const base = await window.electronAPI.getAssetBasePath();
+ if (base) {
+ return new URL(encodedRelativePath, ensureTrailingSlash(base)).toString();
+ }
+ }
+ }
+ } catch {
+ // ignore and use fallback
+ }
+
+ // Fallback for web/dev server: public/wallpapers are served at '/wallpapers/...'
+ return `/${encodedRelativePath}`;
}
-const BASE64_CHUNK_SIZE = 0x8000
-const localFileDataUrlCache = new Map<string, string>()
+const BASE64_CHUNK_SIZE = 0x8000;
+const localFileDataUrlCache = new Map<string, string>();
function toLocalFilePath(resourceUrl: string) {
- if (!resourceUrl.startsWith('file://')) {
- return null
- }
+ if (!resourceUrl.startsWith("file://")) {
+ return null;
+ }
- const decodedPath = decodeURIComponent(resourceUrl.replace(/^file:\/\//, ''))
- if (/^\/[A-Za-z]:/.test(decodedPath)) {
- return decodedPath.slice(1)
- }
+ const decodedPath = decodeURIComponent(resourceUrl.replace(/^file:\/\//, ""));
+ if (/^\/[A-Za-z]:/.test(decodedPath)) {
+ return decodedPath.slice(1);
+ }
- return decodedPath
+ return decodedPath;
}
function getMimeTypeForAsset(resourceUrl: string) {
- const normalized = resourceUrl.split('?')[0].toLowerCase()
-
- if (normalized.endsWith('.png')) return 'image/png'
- if (normalized.endsWith('.webp')) return 'image/webp'
- if (normalized.endsWith('.gif')) return 'image/gif'
- if (normalized.endsWith('.svg')) return 'image/svg+xml'
- if (normalized.endsWith('.avif')) return 'image/avif'
- return 'image/jpeg'
+ const normalized = resourceUrl.split("?")[0].toLowerCase();
+
+ if (normalized.endsWith(".png")) return "image/png";
+ if (normalized.endsWith(".webp")) return "image/webp";
+ if (normalized.endsWith(".gif")) return "image/gif";
+ if (normalized.endsWith(".svg")) return "image/svg+xml";
+ if (normalized.endsWith(".avif")) return "image/avif";
+ return "image/jpeg";
}
function toBase64(bytes: Uint8Array) {
- let binary = ''
+ let binary = "";
- for (let index = 0; index < bytes.length; index += BASE64_CHUNK_SIZE) {
- const chunk = bytes.subarray(index, index + BASE64_CHUNK_SIZE)
- binary += String.fromCharCode(...chunk)
- }
+ for (let index = 0; index < bytes.length; index += BASE64_CHUNK_SIZE) {
+ const chunk = bytes.subarray(index, index + BASE64_CHUNK_SIZE);
+ binary += String.fromCharCode(...chunk);
+ }
- return btoa(binary)
+ return btoa(binary);
}
export async function getRenderableAssetUrl(asset: string): Promise<string> {
- if (!asset || asset.startsWith('data:') || asset.startsWith('http') || asset.startsWith('#') || asset.startsWith('linear-gradient') || asset.startsWith('radial-gradient')) {
- return asset
- }
-
- const resolvedAsset = asset.startsWith('/') && !asset.startsWith('//')
- ? await getAssetPath(asset.replace(/^\//, ''))
- : asset
-
- const localFilePath = toLocalFilePath(resolvedAsset)
- if (!localFilePath || typeof window === 'undefined' || !window.electronAPI?.readLocalFile) {
- return resolvedAsset
- }
-
- const cached = localFileDataUrlCache.get(resolvedAsset)
- if (cached) {
- return cached
- }
-
- try {
- const result = await window.electronAPI.readLocalFile(localFilePath)
- if (!result.success || !result.data) {
- return resolvedAsset
- }
-
- const bytes = result.data instanceof Uint8Array ? result.data : new Uint8Array(result.data)
- const dataUrl = `data:${getMimeTypeForAsset(localFilePath)};base64,${toBase64(bytes)}`
- localFileDataUrlCache.set(resolvedAsset, dataUrl)
- return dataUrl
- } catch {
- return resolvedAsset
- }
+ if (
+ !asset ||
+ asset.startsWith("data:") ||
+ asset.startsWith("http") ||
+ asset.startsWith("#") ||
+ asset.startsWith("linear-gradient") ||
+ asset.startsWith("radial-gradient")
+ ) {
+ return asset;
+ }
+
+ const resolvedAsset =
+ asset.startsWith("/") && !asset.startsWith("//")
+ ? await getAssetPath(asset.replace(/^\//, ""))
+ : asset;
+
+ const localFilePath = toLocalFilePath(resolvedAsset);
+ if (!localFilePath || typeof window === "undefined" || !window.electronAPI?.readLocalFile) {
+ return resolvedAsset;
+ }
+
+ const cached = localFileDataUrlCache.get(resolvedAsset);
+ if (cached) {
+ return cached;
+ }
+
+ try {
+ const result = await window.electronAPI.readLocalFile(localFilePath);
+ if (!result.success || !result.data) {
+ return resolvedAsset;
+ }
+
+ const bytes = result.data instanceof Uint8Array ? result.data : new Uint8Array(result.data);
+ const dataUrl = `data:${getMimeTypeForAsset(localFilePath)};base64,${toBase64(bytes)}`;
+ localFileDataUrlCache.set(resolvedAsset, dataUrl);
+ return dataUrl;
+ } catch {
+ return resolvedAsset;
+ }
}
// ---------------------------------------------------------------------------
@@ -114,57 +126,72 @@ export async function getRenderableAssetUrl(asset: string): Promise<string> {
// Concurrency is capped to avoid OOM from loading many full-res images at once.
// ---------------------------------------------------------------------------
-const thumbnailCache = new Map<string, string>()
+const thumbnailCache = new Map<string, string>();
-const THUMB_CONCURRENCY = 3
-let thumbActive = 0
-const thumbQueue: Array<() => void> = []
+const THUMB_CONCURRENCY = 3;
+let thumbActive = 0;
+const thumbQueue: Array<() => void> = [];
function acquireThumbSlot(): Promise<void> {
- if (thumbActive < THUMB_CONCURRENCY) {
- thumbActive++
- return Promise.resolve()
- }
- return new Promise<void>((resolve) => thumbQueue.push(resolve))
+ if (thumbActive < THUMB_CONCURRENCY) {
+ thumbActive++;
+ return Promise.resolve();
+ }
+ return new Promise<void>((resolve) => thumbQueue.push(resolve));
}
function releaseThumbSlot(): void {
- const next = thumbQueue.shift()
- if (next) {
- next()
- } else {
- thumbActive--
- }
+ const next = thumbQueue.shift();
+ if (next) {
+ next();
+ } else {
+ thumbActive--;
+ }
}
export async function getWallpaperThumbnailUrl(asset: string): Promise<string> {
- if (!asset || asset.startsWith('data:') || asset.startsWith('http') || asset.startsWith('#') || asset.startsWith('linear-gradient') || asset.startsWith('radial-gradient')) {
- return asset
- }
-
- const cached = thumbnailCache.get(asset)
- if (cached) return cached
-
- const localFilePath = toLocalFilePath(asset.startsWith('/') && !asset.startsWith('//') ? await getAssetPath(asset.replace(/^\//, '')) : asset)
- if (!localFilePath || typeof window === 'undefined' || !window.electronAPI?.generateWallpaperThumbnail) {
- return getRenderableAssetUrl(asset)
- }
-
- await acquireThumbSlot()
- try {
- const result = await window.electronAPI.generateWallpaperThumbnail(localFilePath)
- if (!result.success || !result.data) {
- return getRenderableAssetUrl(asset)
- }
- const bytes = result.data instanceof Uint8Array ? result.data : new Uint8Array(result.data)
- const dataUrl = `data:image/jpeg;base64,${toBase64(bytes)}`
- thumbnailCache.set(asset, dataUrl)
- return dataUrl
- } catch {
- return getRenderableAssetUrl(asset)
- } finally {
- releaseThumbSlot()
- }
+ if (
+ !asset ||
+ asset.startsWith("data:") ||
+ asset.startsWith("http") ||
+ asset.startsWith("#") ||
+ asset.startsWith("linear-gradient") ||
+ asset.startsWith("radial-gradient")
+ ) {
+ return asset;
+ }
+
+ const cached = thumbnailCache.get(asset);
+ if (cached) return cached;
+
+ const localFilePath = toLocalFilePath(
+ asset.startsWith("/") && !asset.startsWith("//")
+ ? await getAssetPath(asset.replace(/^\//, ""))
+ : asset,
+ );
+ if (
+ !localFilePath ||
+ typeof window === "undefined" ||
+ !window.electronAPI?.generateWallpaperThumbnail
+ ) {
+ return getRenderableAssetUrl(asset);
+ }
+
+ await acquireThumbSlot();
+ try {
+ const result = await window.electronAPI.generateWallpaperThumbnail(localFilePath);
+ if (!result.success || !result.data) {
+ return getRenderableAssetUrl(asset);
+ }
+ const bytes = result.data instanceof Uint8Array ? result.data : new Uint8Array(result.data);
+ const dataUrl = `data:image/jpeg;base64,${toBase64(bytes)}`;
+ thumbnailCache.set(asset, dataUrl);
+ return dataUrl;
+ } catch {
+ return getRenderableAssetUrl(asset);
+ } finally {
+ releaseThumbSlot();
+ }
}
export default getAssetPath;
diff --git a/src/lib/customFonts.ts b/src/lib/customFonts.ts
index ab2e05ba..4eede969 100644
--- a/src/lib/customFonts.ts
+++ b/src/lib/customFonts.ts
@@ -1,181 +1,186 @@
-// Google Fonts loading and management utility
-
-export interface CustomFont {
- id: string;
- name: string; // Display name
- fontFamily: string; // CSS font-family value
- importUrl: string; // Google Fonts @import URL
-}
-
-const STORAGE_KEY = 'recordly_custom_fonts';
-const LEGACY_STORAGE_KEY = 'openscreen_custom_fonts';
-const loadedFonts = new Set<string>();
-
-// Load custom fonts from localStorage
-export function getCustomFonts(): CustomFont[] {
- try {
- const stored = localStorage.getItem(STORAGE_KEY) ?? localStorage.getItem(LEGACY_STORAGE_KEY);
- return stored ? JSON.parse(stored) : [];
- } catch (error) {
- console.error('Failed to load custom fonts from storage:', error);
- return [];
- }
-}
-
-// Save custom fonts to localStorage
-export function saveCustomFonts(fonts: CustomFont[]): void {
- try {
- localStorage.setItem(STORAGE_KEY, JSON.stringify(fonts));
- localStorage.removeItem(LEGACY_STORAGE_KEY);
- } catch (error) {
- console.error('Failed to save custom fonts to storage:', error);
- }
-}
-
-// Add a new custom font (throws error if font fails to load)
-export async function addCustomFont(font: CustomFont): Promise<CustomFont[]> {
- const fonts = getCustomFonts();
- const exists = fonts.some(f => f.id === font.id || f.fontFamily === font.fontFamily);
-
- if (exists) {
- return fonts;
- }
-
- // Try to load the font first - this will throw if it fails
- await loadFont(font);
-
- // Only add to storage if font loaded successfully
- fonts.push(font);
- saveCustomFonts(fonts);
-
- return fonts;
-}
-
-// Remove a custom font
-export function removeCustomFont(fontId: string): CustomFont[] {
- const fonts = getCustomFonts();
- const filtered = fonts.filter(f => f.id !== fontId);
- saveCustomFonts(filtered);
-
- // Remove the style element
- const styleEl = document.getElementById(`custom-font-${fontId}`);
- if (styleEl) {
- styleEl.remove();
- }
-
- loadedFonts.delete(fontId);
- return filtered;
-}
-
-// Load a Google Font into the document
-export function loadFont(font: CustomFont): Promise<void> {
- return new Promise((resolve, reject) => {
- // Skip if already loaded
- if (loadedFonts.has(font.id)) {
- resolve();
- return;
- }
-
- try {
- const styleId = `custom-font-${font.id}`;
-
- // Remove existing style if present
- const existing = document.getElementById(styleId);
- if (existing) {
- existing.remove();
- }
-
- // Create style element with @import
- const style = document.createElement('style');
- style.id = styleId;
- style.textContent = `@import url('${font.importUrl}');`;
- document.head.appendChild(style);
-
- // Wait for font to load
- waitForFont(font.fontFamily)
- .then(() => {
- loadedFonts.add(font.id);
- resolve();
- })
- .catch(reject);
-
- } catch (error) {
- console.error('Failed to load font:', font, error);
- reject(error);
- }
- });
-}
-
-// Wait for a font to be available and verify it loaded
-function waitForFont(fontFamily: string, timeout = 5000): Promise<void> {
- return new Promise((resolve, reject) => {
- // Use CSS Font Loading API if available
- if ('fonts' in document) {
- Promise.race([
- document.fonts.load(`16px "${fontFamily}"`),
- new Promise((_, rej) => setTimeout(() => rej(new Error('Font load timeout')), timeout))
- ])
- .then(() => {
- // Verify the font actually loaded by checking if it's available
- const isAvailable = document.fonts.check(`16px "${fontFamily}"`);
- if (isAvailable) {
- resolve();
- } else {
- reject(new Error(`Font "${fontFamily}" failed to load`));
- }
- })
- .catch((error) => {
- reject(error);
- });
- } else {
- // Fallback for browsers without Font Loading API
- // Wait a bit and hope for the best
- setTimeout(() => resolve(), 1000);
- }
- });
-}
-
-// Load all stored custom fonts on app initialization
-export function loadAllCustomFonts(): Promise<void[]> {
- const fonts = getCustomFonts();
- return Promise.all(fonts.map(font => loadFont(font).catch(err => {
- console.error('Failed to load custom font:', font.name, err);
- })));
-}
-
-// Generate a unique ID for a font
-export function generateFontId(name: string): string {
- return `${name.toLowerCase().replace(/\s+/g, '-')}-${Date.now()}`;
-}
-
-// Parse Google Fonts @import URL to extract font family name
-export function parseFontFamilyFromImport(importUrl: string): string | null {
- try {
- // Extract from URL like: https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap
- const url = new URL(importUrl);
- const familyParam = url.searchParams.get('family');
-
- if (familyParam) {
- // Remove weight/style info: "Roboto:wght@400;700" -> "Roboto"
- const fontName = familyParam.split(':')[0];
- // Replace + with spaces: "Open+Sans" -> "Open Sans"
- return fontName.replace(/\+/g, ' ');
- }
-
- return null;
- } catch (error) {
- console.error('Failed to parse font family from import URL:', error);
- return null;
- }
-}
-
-// Validate if a string looks like a Google Fonts import URL
-export function isValidGoogleFontsUrl(url: string): boolean {
- try {
- const urlObj = new URL(url);
- return urlObj.hostname === 'fonts.googleapis.com' && urlObj.searchParams.has('family');
- } catch {
- return false;
- }
-}
+// Google Fonts loading and management utility
+export interface CustomFont {
+ id: string;
+ name: string; // Display name
+ fontFamily: string; // CSS font-family value
+ importUrl: string; // Google Fonts @import URL
+}
+
+const STORAGE_KEY = "recordly_custom_fonts";
+const LEGACY_STORAGE_KEY = "openscreen_custom_fonts";
+const loadedFonts = new Set<string>();
+
+// Load custom fonts from localStorage
+export function getCustomFonts(): CustomFont[] {
+ try {
+ const stored =
+ localStorage.getItem(STORAGE_KEY) ?? localStorage.getItem(LEGACY_STORAGE_KEY);
+ return stored ? JSON.parse(stored) : [];
+ } catch (error) {
+ console.error("Failed to load custom fonts from storage:", error);
+ return [];
+ }
+}
+
+// Save custom fonts to localStorage
+export function saveCustomFonts(fonts: CustomFont[]): void {
+ try {
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(fonts));
+ localStorage.removeItem(LEGACY_STORAGE_KEY);
+ } catch (error) {
+ console.error("Failed to save custom fonts to storage:", error);
+ }
+}
+
+// Add a new custom font (throws error if font fails to load)
+export async function addCustomFont(font: CustomFont): Promise<CustomFont[]> {
+ const fonts = getCustomFonts();
+ const exists = fonts.some((f) => f.id === font.id || f.fontFamily === font.fontFamily);
+
+ if (exists) {
+ return fonts;
+ }
+
+ // Try to load the font first - this will throw if it fails
+ await loadFont(font);
+
+ // Only add to storage if font loaded successfully
+ fonts.push(font);
+ saveCustomFonts(fonts);
+
+ return fonts;
+}
+
+// Remove a custom font
+export function removeCustomFont(fontId: string): CustomFont[] {
+ const fonts = getCustomFonts();
+ const filtered = fonts.filter((f) => f.id !== fontId);
+ saveCustomFonts(filtered);
+
+ // Remove the style element
+ const styleEl = document.getElementById(`custom-font-${fontId}`);
+ if (styleEl) {
+ styleEl.remove();
+ }
+
+ loadedFonts.delete(fontId);
+ return filtered;
+}
+
+// Load a Google Font into the document
+export function loadFont(font: CustomFont): Promise<void> {
+ return new Promise((resolve, reject) => {
+ // Skip if already loaded
+ if (loadedFonts.has(font.id)) {
+ resolve();
+ return;
+ }
+
+ try {
+ const styleId = `custom-font-${font.id}`;
+
+ // Remove existing style if present
+ const existing = document.getElementById(styleId);
+ if (existing) {
+ existing.remove();
+ }
+
+ // Create style element with @import
+ const style = document.createElement("style");
+ style.id = styleId;
+ style.textContent = `@import url('${font.importUrl}');`;
+ document.head.appendChild(style);
+
+ // Wait for font to load
+ waitForFont(font.fontFamily)
+ .then(() => {
+ loadedFonts.add(font.id);
+ resolve();
+ })
+ .catch(reject);
+ } catch (error) {
+ console.error("Failed to load font:", font, error);
+ reject(error);
+ }
+ });
+}
+
+// Wait for a font to be available and verify it loaded
+function waitForFont(fontFamily: string, timeout = 5000): Promise<void> {
+ return new Promise((resolve, reject) => {
+ // Use CSS Font Loading API if available
+ if ("fonts" in document) {
+ Promise.race([
+ document.fonts.load(`16px "${fontFamily}"`),
+ new Promise((_, rej) =>
+ setTimeout(() => rej(new Error("Font load timeout")), timeout),
+ ),
+ ])
+ .then(() => {
+ // Verify the font actually loaded by checking if it's available
+ const isAvailable = document.fonts.check(`16px "${fontFamily}"`);
+ if (isAvailable) {
+ resolve();
+ } else {
+ reject(new Error(`Font "${fontFamily}" failed to load`));
+ }
+ })
+ .catch((error) => {
+ reject(error);
+ });
+ } else {
+ // Fallback for browsers without Font Loading API
+ // Wait a bit and hope for the best
+ setTimeout(() => resolve(), 1000);
+ }
+ });
+}
+
+// Load all stored custom fonts on app initialization
+export function loadAllCustomFonts(): Promise<void[]> {
+ const fonts = getCustomFonts();
+ return Promise.all(
+ fonts.map((font) =>
+ loadFont(font).catch((err) => {
+ console.error("Failed to load custom font:", font.name, err);
+ }),
+ ),
+ );
+}
+
+// Generate a unique ID for a font
+export function generateFontId(name: string): string {
+ return `${name.toLowerCase().replace(/\s+/g, "-")}-${Date.now()}`;
+}
+
+// Parse Google Fonts @import URL to extract font family name
+export function parseFontFamilyFromImport(importUrl: string): string | null {
+ try {
+ // Extract from URL like: https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap
+ const url = new URL(importUrl);
+ const familyParam = url.searchParams.get("family");
+
+ if (familyParam) {
+ // Remove weight/style info: "Roboto:wght@400;700" -> "Roboto"
+ const fontName = familyParam.split(":")[0];
+ // Replace + with spaces: "Open+Sans" -> "Open Sans"
+ return fontName.replace(/\+/g, " ");
+ }
+
+ return null;
+ } catch (error) {
+ console.error("Failed to parse font family from import URL:", error);
+ return null;
+ }
+}
+
+// Validate if a string looks like a Google Fonts import URL
+export function isValidGoogleFontsUrl(url: string): boolean {
+ try {
+ const urlObj = new URL(url);
+ return urlObj.hostname === "fonts.googleapis.com" && urlObj.searchParams.has("family");
+ } catch {
+ return false;
+ }
+}
diff --git a/src/lib/geometry/squircle.ts b/src/lib/geometry/squircle.ts
index d317d692..86d8f939 100644
--- a/src/lib/geometry/squircle.ts
+++ b/src/lib/geometry/squircle.ts
@@ -24,12 +24,7 @@ function getClampedRadius(width: number, height: number, radius: number) {
return clamp(radius, 0, Math.min(width, height) / 2);
}
-function getSuperellipsePoint(
- centerX: number,
- centerY: number,
- radius: number,
- angle: number,
-) {
+function getSuperellipsePoint(centerX: number, centerY: number, radius: number, angle: number) {
const cos = Math.cos(angle);
const sin = Math.sin(angle);
const exponent = 2 / SQUIRCLE_EXPONENT;
@@ -63,24 +58,37 @@ export function getSquirclePathPoints({
const points: SquirclePoint[] = [{ x: x + clampedRadius, y }];
const corners = [
- { centerX: x + width - clampedRadius, centerY: y + clampedRadius, start: -Math.PI / 2, end: 0 },
- { centerX: x + width - clampedRadius, centerY: y + height - clampedRadius, start: 0, end: Math.PI / 2 },
- { centerX: x + clampedRadius, centerY: y + height - clampedRadius, start: Math.PI / 2, end: Math.PI },
- { centerX: x + clampedRadius, centerY: y + clampedRadius, start: Math.PI, end: (Math.PI * 3) / 2 },
+ {
+ centerX: x + width - clampedRadius,
+ centerY: y + clampedRadius,
+ start: -Math.PI / 2,
+ end: 0,
+ },
+ {
+ centerX: x + width - clampedRadius,
+ centerY: y + height - clampedRadius,
+ start: 0,
+ end: Math.PI / 2,
+ },
+ {
+ centerX: x + clampedRadius,
+ centerY: y + height - clampedRadius,
+ start: Math.PI / 2,
+ end: Math.PI,
+ },
+ {
+ centerX: x + clampedRadius,
+ centerY: y + clampedRadius,
+ start: Math.PI,
+ end: (Math.PI * 3) / 2,
+ },
];
for (const corner of corners) {
for (let index = 1; index <= SQUIRCLE_SEGMENTS_PER_CORNER; index += 1) {
const t = index / SQUIRCLE_SEGMENTS_PER_CORNER;
const angle = corner.start + (corner.end - corner.start) * t;
- points.push(
- getSuperellipsePoint(
- corner.centerX,
- corner.centerY,
- clampedRadius,
- angle,
- ),
- );
+ points.push(getSuperellipsePoint(corner.centerX, corner.centerY, clampedRadius, angle));
}
}
@@ -99,10 +107,7 @@ export function getSquircleSvgPath(rect: SquircleRect) {
.join(" ")} Z`;
}
-export function drawSquircleOnCanvas(
- ctx: CanvasRenderingContext2D,
- rect: SquircleRect,
-) {
+export function drawSquircleOnCanvas(ctx: CanvasRenderingContext2D, rect: SquircleRect) {
const points = getSquirclePathPoints(rect);
if (points.length === 0) {
return;
@@ -127,4 +132,4 @@ export function drawSquircleOnGraphics(graphics: Graphics, rect: SquircleRect) {
graphics.lineTo(points[index].x, points[index].y);
}
graphics.closePath();
-}
\ No newline at end of file
+}
diff --git a/src/lib/mediaTiming.test.ts b/src/lib/mediaTiming.test.ts
index cc595dac..1f74a259 100644
--- a/src/lib/mediaTiming.test.ts
+++ b/src/lib/mediaTiming.test.ts
@@ -1,124 +1,124 @@
import { describe, expect, it } from "vitest";
import {
- clampMediaTimeToDuration,
- estimateCompanionAudioStartDelaySeconds,
- getEffectiveVideoStreamDurationSeconds,
- getEffectiveRecordingDurationMs,
- getMediaSyncPlaybackRate,
+ clampMediaTimeToDuration,
+ estimateCompanionAudioStartDelaySeconds,
+ getEffectiveRecordingDurationMs,
+ getEffectiveVideoStreamDurationSeconds,
+ getMediaSyncPlaybackRate,
} from "./mediaTiming";
describe("clampMediaTimeToDuration", () => {
- it("clamps playback time to known media duration", () => {
- expect(clampMediaTimeToDuration(12, 4.5)).toBe(4.5);
- expect(clampMediaTimeToDuration(-1, 4.5)).toBe(0);
- });
+ it("clamps playback time to known media duration", () => {
+ expect(clampMediaTimeToDuration(12, 4.5)).toBe(4.5);
+ expect(clampMediaTimeToDuration(-1, 4.5)).toBe(0);
+ });
- it("leaves playback time unchanged when duration is unknown", () => {
- expect(clampMediaTimeToDuration(12, null)).toBe(12);
- expect(clampMediaTimeToDuration(12, Number.NaN)).toBe(12);
- });
+ it("leaves playback time unchanged when duration is unknown", () => {
+ expect(clampMediaTimeToDuration(12, null)).toBe(12);
+ expect(clampMediaTimeToDuration(12, Number.NaN)).toBe(12);
+ });
});
describe("estimateCompanionAudioStartDelaySeconds", () => {
- it("returns the positive tail gap when companion audio is shorter", () => {
- expect(estimateCompanionAudioStartDelaySeconds(10, 9.6)).toBeCloseTo(0.4);
- });
+ it("returns the positive tail gap when companion audio is shorter", () => {
+ expect(estimateCompanionAudioStartDelaySeconds(10, 9.6)).toBeCloseTo(0.4);
+ });
- it("ignores tiny or negative differences", () => {
- expect(estimateCompanionAudioStartDelaySeconds(10, 9.97)).toBe(0);
- expect(estimateCompanionAudioStartDelaySeconds(10, 10.5)).toBe(0);
- });
+ it("ignores tiny or negative differences", () => {
+ expect(estimateCompanionAudioStartDelaySeconds(10, 9.97)).toBe(0);
+ expect(estimateCompanionAudioStartDelaySeconds(10, 10.5)).toBe(0);
+ });
});
describe("getEffectiveRecordingDurationMs", () => {
- it("subtracts accumulated paused time", () => {
- expect(
- getEffectiveRecordingDurationMs({
- startTimeMs: 1_000,
- endTimeMs: 11_000,
- accumulatedPausedDurationMs: 2_500,
- }),
- ).toBe(7_500);
- });
+ it("subtracts accumulated paused time", () => {
+ expect(
+ getEffectiveRecordingDurationMs({
+ startTimeMs: 1_000,
+ endTimeMs: 11_000,
+ accumulatedPausedDurationMs: 2_500,
+ }),
+ ).toBe(7_500);
+ });
- it("subtracts an active pause interval", () => {
- expect(
- getEffectiveRecordingDurationMs({
- startTimeMs: 1_000,
- endTimeMs: 11_000,
- accumulatedPausedDurationMs: 2_000,
- pauseStartedAtMs: 9_000,
- }),
- ).toBe(6_000);
- });
+ it("subtracts an active pause interval", () => {
+ expect(
+ getEffectiveRecordingDurationMs({
+ startTimeMs: 1_000,
+ endTimeMs: 11_000,
+ accumulatedPausedDurationMs: 2_000,
+ pauseStartedAtMs: 9_000,
+ }),
+ ).toBe(6_000);
+ });
});
describe("getMediaSyncPlaybackRate", () => {
- it("returns the base rate when drift is within tolerance", () => {
- expect(
- getMediaSyncPlaybackRate({
- basePlaybackRate: 1,
- currentTime: 10,
- targetTime: 10.01,
- }),
- ).toBe(1);
- });
+ it("returns the base rate when drift is within tolerance", () => {
+ expect(
+ getMediaSyncPlaybackRate({
+ basePlaybackRate: 1,
+ currentTime: 10,
+ targetTime: 10.01,
+ }),
+ ).toBe(1);
+ });
- it("nudges playback rate toward the target time", () => {
- expect(
- getMediaSyncPlaybackRate({
- basePlaybackRate: 1,
- currentTime: 10,
- targetTime: 10.1,
- }),
- ).toBeCloseTo(1.05);
+ it("nudges playback rate toward the target time", () => {
+ expect(
+ getMediaSyncPlaybackRate({
+ basePlaybackRate: 1,
+ currentTime: 10,
+ targetTime: 10.1,
+ }),
+ ).toBeCloseTo(1.05);
- expect(
- getMediaSyncPlaybackRate({
- basePlaybackRate: 1,
- currentTime: 10.1,
- targetTime: 10,
- }),
- ).toBeCloseTo(0.95);
- });
+ expect(
+ getMediaSyncPlaybackRate({
+ basePlaybackRate: 1,
+ currentTime: 10.1,
+ targetTime: 10,
+ }),
+ ).toBeCloseTo(0.95);
+ });
- it("clamps oversized corrections", () => {
- expect(
- getMediaSyncPlaybackRate({
- basePlaybackRate: 1,
- currentTime: 10,
- targetTime: 10.5,
- }),
- ).toBeCloseTo(1.08);
- });
+ it("clamps oversized corrections", () => {
+ expect(
+ getMediaSyncPlaybackRate({
+ basePlaybackRate: 1,
+ currentTime: 10,
+ targetTime: 10.5,
+ }),
+ ).toBeCloseTo(1.08);
+ });
});
describe("getEffectiveVideoStreamDurationSeconds", () => {
- it("prefers the video stream duration when present", () => {
- expect(
- getEffectiveVideoStreamDurationSeconds({
- duration: 12,
- streamDuration: 11.2,
- }),
- ).toBe(11.2);
- });
+ it("prefers the video stream duration when present", () => {
+ expect(
+ getEffectiveVideoStreamDurationSeconds({
+ duration: 12,
+ streamDuration: 11.2,
+ }),
+ ).toBe(11.2);
+ });
- it("falls back to the container duration when stream duration is missing", () => {
- expect(
- getEffectiveVideoStreamDurationSeconds({
- duration: 12,
- streamDuration: undefined,
- }),
- ).toBe(12);
- });
+ it("falls back to the container duration when stream duration is missing", () => {
+ expect(
+ getEffectiveVideoStreamDurationSeconds({
+ duration: 12,
+ streamDuration: undefined,
+ }),
+ ).toBe(12);
+ });
- it("returns zero when neither duration is usable", () => {
- expect(
- getEffectiveVideoStreamDurationSeconds({
- duration: Number.NaN,
- streamDuration: 0,
- }),
- ).toBe(0);
- });
+ it("returns zero when neither duration is usable", () => {
+ expect(
+ getEffectiveVideoStreamDurationSeconds({
+ duration: Number.NaN,
+ streamDuration: 0,
+ }),
+ ).toBe(0);
+ });
});
diff --git a/src/lib/mediaTiming.ts b/src/lib/mediaTiming.ts
index d41419cb..11b6a50e 100644
--- a/src/lib/mediaTiming.ts
+++ b/src/lib/mediaTiming.ts
@@ -1,114 +1,109 @@
-export function clampMediaTimeToDuration(
- targetTime: number,
- duration?: number | null,
-): number {
- const safeTargetTime = Math.max(0, targetTime);
- if (!Number.isFinite(duration) || duration === null || duration === undefined) {
- return safeTargetTime;
- }
+export function clampMediaTimeToDuration(targetTime: number, duration?: number | null): number {
+ const safeTargetTime = Math.max(0, targetTime);
+ if (!Number.isFinite(duration) || duration === null || duration === undefined) {
+ return safeTargetTime;
+ }
- return Math.max(0, Math.min(safeTargetTime, Math.max(0, duration)));
+ return Math.max(0, Math.min(safeTargetTime, Math.max(0, duration)));
}
export function estimateCompanionAudioStartDelaySeconds(
- timelineDuration?: number | null,
- audioDuration?: number | null,
+ timelineDuration?: number | null,
+ audioDuration?: number | null,
): number {
- if (!Number.isFinite(timelineDuration) || !Number.isFinite(audioDuration)) {
- return 0;
- }
+ if (!Number.isFinite(timelineDuration) || !Number.isFinite(audioDuration)) {
+ return 0;
+ }
- const safeTimelineDuration = Math.max(0, timelineDuration ?? 0);
- const safeAudioDuration = Math.max(0, audioDuration ?? 0);
- const estimatedDelaySeconds = safeTimelineDuration - safeAudioDuration;
+ const safeTimelineDuration = Math.max(0, timelineDuration ?? 0);
+ const safeAudioDuration = Math.max(0, audioDuration ?? 0);
+ const estimatedDelaySeconds = safeTimelineDuration - safeAudioDuration;
- return estimatedDelaySeconds > 0.05 ? estimatedDelaySeconds : 0;
+ return estimatedDelaySeconds > 0.05 ? estimatedDelaySeconds : 0;
}
export function getMediaSyncPlaybackRate({
- basePlaybackRate,
- currentTime,
- targetTime,
- toleranceSeconds = 0.015,
- correctionWindowSeconds = 2,
- maxAdjustment = 0.08,
+ basePlaybackRate,
+ currentTime,
+ targetTime,
+ toleranceSeconds = 0.015,
+ correctionWindowSeconds = 2,
+ maxAdjustment = 0.08,
}: {
- basePlaybackRate: number;
- currentTime: number;
- targetTime: number;
- toleranceSeconds?: number;
- correctionWindowSeconds?: number;
- maxAdjustment?: number;
+ basePlaybackRate: number;
+ currentTime: number;
+ targetTime: number;
+ toleranceSeconds?: number;
+ correctionWindowSeconds?: number;
+ maxAdjustment?: number;
}): number {
- const safeBasePlaybackRate =
- Number.isFinite(basePlaybackRate) && basePlaybackRate > 0
- ? basePlaybackRate
- : 1;
+ const safeBasePlaybackRate =
+ Number.isFinite(basePlaybackRate) && basePlaybackRate > 0 ? basePlaybackRate : 1;
- if (!Number.isFinite(currentTime) || !Number.isFinite(targetTime)) {
- return safeBasePlaybackRate;
- }
+ if (!Number.isFinite(currentTime) || !Number.isFinite(targetTime)) {
+ return safeBasePlaybackRate;
+ }
- const driftSeconds = targetTime - currentTime;
- if (Math.abs(driftSeconds) <= toleranceSeconds) {
- return safeBasePlaybackRate;
- }
+ const driftSeconds = targetTime - currentTime;
+ if (Math.abs(driftSeconds) <= toleranceSeconds) {
+ return safeBasePlaybackRate;
+ }
- const safeCorrectionWindow = correctionWindowSeconds > 0 ? correctionWindowSeconds : 2;
- const safeMaxAdjustment = Math.max(0, maxAdjustment);
- const adjustment = Math.max(
- -safeMaxAdjustment,
- Math.min(safeMaxAdjustment, driftSeconds / safeCorrectionWindow),
- );
+ const safeCorrectionWindow = correctionWindowSeconds > 0 ? correctionWindowSeconds : 2;
+ const safeMaxAdjustment = Math.max(0, maxAdjustment);
+ const adjustment = Math.max(
+ -safeMaxAdjustment,
+ Math.min(safeMaxAdjustment, driftSeconds / safeCorrectionWindow),
+ );
- return Math.max(0.1, safeBasePlaybackRate + adjustment);
+ return Math.max(0.1, safeBasePlaybackRate + adjustment);
}
export function getEffectiveVideoStreamDurationSeconds({
- duration,
- streamDuration,
+ duration,
+ streamDuration,
}: {
- duration?: number | null;
- streamDuration?: number | null;
+ duration?: number | null;
+ streamDuration?: number | null;
}): number {
- if (Number.isFinite(streamDuration) && (streamDuration ?? 0) > 0) {
- return Math.max(0, streamDuration ?? 0);
- }
+ if (Number.isFinite(streamDuration) && (streamDuration ?? 0) > 0) {
+ return Math.max(0, streamDuration ?? 0);
+ }
- if (Number.isFinite(duration) && (duration ?? 0) > 0) {
- return Math.max(0, duration ?? 0);
- }
+ if (Number.isFinite(duration) && (duration ?? 0) > 0) {
+ return Math.max(0, duration ?? 0);
+ }
- return 0;
+ return 0;
}
export function getEffectiveRecordingDurationMs({
- startTimeMs,
- endTimeMs,
- accumulatedPausedDurationMs = 0,
- pauseStartedAtMs = null,
+ startTimeMs,
+ endTimeMs,
+ accumulatedPausedDurationMs = 0,
+ pauseStartedAtMs = null,
}: {
- startTimeMs: number;
- endTimeMs: number;
- accumulatedPausedDurationMs?: number;
- pauseStartedAtMs?: number | null;
+ startTimeMs: number;
+ endTimeMs: number;
+ accumulatedPausedDurationMs?: number;
+ pauseStartedAtMs?: number | null;
}): number {
- if (!Number.isFinite(startTimeMs) || !Number.isFinite(endTimeMs)) {
- return 0;
- }
+ if (!Number.isFinite(startTimeMs) || !Number.isFinite(endTimeMs)) {
+ return 0;
+ }
- const safeStartTime = Math.max(0, startTimeMs);
- const safeEndTime = Math.max(safeStartTime, endTimeMs);
- const activePauseDuration =
- Number.isFinite(pauseStartedAtMs) && pauseStartedAtMs !== null
- ? Math.max(0, safeEndTime - pauseStartedAtMs)
- : 0;
+ const safeStartTime = Math.max(0, startTimeMs);
+ const safeEndTime = Math.max(safeStartTime, endTimeMs);
+ const activePauseDuration =
+ Number.isFinite(pauseStartedAtMs) && pauseStartedAtMs !== null
+ ? Math.max(0, safeEndTime - pauseStartedAtMs)
+ : 0;
- return Math.max(
- 0,
- safeEndTime -
- safeStartTime -
- Math.max(0, accumulatedPausedDurationMs) -
- activePauseDuration,
- );
-}
\ No newline at end of file
+ return Math.max(
+ 0,
+ safeEndTime -
+ safeStartTime -
+ Math.max(0, accumulatedPausedDurationMs) -
+ activePauseDuration,
+ );
+}
diff --git a/src/lib/shortcuts.ts b/src/lib/shortcuts.ts
index 418e9e25..f1bc84b4 100644
--- a/src/lib/shortcuts.ts
+++ b/src/lib/shortcuts.ts
@@ -1,129 +1,142 @@
export const SHORTCUT_ACTIONS = [
- 'addZoom',
- 'addTrim',
- 'splitClip',
- 'addSpeed',
- 'addAnnotation',
- 'addKeyframe',
- 'deleteSelected',
- 'playPause',
+ "addZoom",
+ "addTrim",
+ "splitClip",
+ "addSpeed",
+ "addAnnotation",
+ "addKeyframe",
+ "deleteSelected",
+ "playPause",
] as const;
export type ShortcutAction = (typeof SHORTCUT_ACTIONS)[number];
export interface ShortcutBinding {
- key: string;
- /** Maps to Cmd on macOS, Ctrl on Windows/Linux */
- ctrl?: boolean;
- shift?: boolean;
- alt?: boolean;
+ key: string;
+ /** Maps to Cmd on macOS, Ctrl on Windows/Linux */
+ ctrl?: boolean;
+ shift?: boolean;
+ alt?: boolean;
}
export type ShortcutsConfig = Record<ShortcutAction, ShortcutBinding>;
export interface FixedShortcut {
- label: string;
- display: string;
- bindings: ShortcutBinding[];
+ label: string;
+ display: string;
+ bindings: ShortcutBinding[];
}
export const FIXED_SHORTCUTS: FixedShortcut[] = [
- { label: 'Cycle Annotations Forward', display: 'Tab', bindings: [{ key: 'tab' }] },
- { label: 'Cycle Annotations Backward', display: 'Shift + Tab', bindings: [{ key: 'tab', shift: true }] },
- { label: 'Delete Selected (alt)', display: 'Del / ⌫', bindings: [{ key: 'delete' }, { key: 'backspace' }] },
- { label: 'Pan Timeline', display: 'Shift + Ctrl + Scroll', bindings: [] },
- { label: 'Zoom Timeline', display: 'Ctrl + Scroll', bindings: [] },
+ { label: "Cycle Annotations Forward", display: "Tab", bindings: [{ key: "tab" }] },
+ {
+ label: "Cycle Annotations Backward",
+ display: "Shift + Tab",
+ bindings: [{ key: "tab", shift: true }],
+ },
+ {
+ label: "Delete Selected (alt)",
+ display: "Del / ⌫",
+ bindings: [{ key: "delete" }, { key: "backspace" }],
+ },
+ { label: "Pan Timeline", display: "Shift + Ctrl + Scroll", bindings: [] },
+ { label: "Zoom Timeline", display: "Ctrl + Scroll", bindings: [] },
];
export type ShortcutConflict =
- | { type: 'configurable'; action: ShortcutAction }
- | { type: 'fixed'; label: string };
+ | { type: "configurable"; action: ShortcutAction }
+ | { type: "fixed"; label: string };
export function bindingsEqual(a: ShortcutBinding, b: ShortcutBinding): boolean {
- return (
- a.key.toLowerCase() === b.key.toLowerCase() &&
- !!a.ctrl === !!b.ctrl &&
- !!a.shift === !!b.shift &&
- !!a.alt === !!b.alt
- );
+ return (
+ a.key.toLowerCase() === b.key.toLowerCase() &&
+ !!a.ctrl === !!b.ctrl &&
+ !!a.shift === !!b.shift &&
+ !!a.alt === !!b.alt
+ );
}
export function findConflict(
- binding: ShortcutBinding,
- forAction: ShortcutAction,
- config: ShortcutsConfig,
+ binding: ShortcutBinding,
+ forAction: ShortcutAction,
+ config: ShortcutsConfig,
): ShortcutConflict | null {
- for (const fixed of FIXED_SHORTCUTS) {
- if (fixed.bindings.some((b) => bindingsEqual(b, binding))) {
- return { type: 'fixed', label: fixed.label };
- }
- }
- for (const action of SHORTCUT_ACTIONS) {
- if (action !== forAction && bindingsEqual(config[action], binding)) {
- return { type: 'configurable', action };
- }
- }
- return null;
+ for (const fixed of FIXED_SHORTCUTS) {
+ if (fixed.bindings.some((b) => bindingsEqual(b, binding))) {
+ return { type: "fixed", label: fixed.label };
+ }
+ }
+ for (const action of SHORTCUT_ACTIONS) {
+ if (action !== forAction && bindingsEqual(config[action], binding)) {
+ return { type: "configurable", action };
+ }
+ }
+ return null;
}
export const DEFAULT_SHORTCUTS: ShortcutsConfig = {
- addZoom: { key: 'z' },
- addTrim: { key: 't' },
- splitClip: { key: 'c' },
- addSpeed: { key: 's' },
- addAnnotation: { key: 'a' },
- addKeyframe: { key: 'f' },
- deleteSelected: { key: 'd', ctrl: true },
- playPause: { key: ' ' },
+ addZoom: { key: "z" },
+ addTrim: { key: "t" },
+ splitClip: { key: "c" },
+ addSpeed: { key: "s" },
+ addAnnotation: { key: "a" },
+ addKeyframe: { key: "f" },
+ deleteSelected: { key: "d", ctrl: true },
+ playPause: { key: " " },
};
export const SHORTCUT_LABELS: Record<ShortcutAction, string> = {
- addZoom: 'Add Zoom',
- addTrim: 'Add Trim',
- splitClip: 'Split Clip',
- addSpeed: 'Add Speed',
- addAnnotation: 'Add Annotation',
- addKeyframe: 'Add Keyframe',
- deleteSelected: 'Delete Selected',
- playPause: 'Play / Pause',
+ addZoom: "Add Zoom",
+ addTrim: "Add Trim",
+ splitClip: "Split Clip",
+ addSpeed: "Add Speed",
+ addAnnotation: "Add Annotation",
+ addKeyframe: "Add Keyframe",
+ deleteSelected: "Delete Selected",
+ playPause: "Play / Pause",
};
export function matchesShortcut(
- e: KeyboardEvent,
- binding: ShortcutBinding,
- isMacPlatform: boolean,
+ e: KeyboardEvent,
+ binding: ShortcutBinding,
+ isMacPlatform: boolean,
): boolean {
- if (e.key.toLowerCase() !== binding.key.toLowerCase()) return false;
+ if (e.key.toLowerCase() !== binding.key.toLowerCase()) return false;
- const primaryMod = isMacPlatform ? e.metaKey : e.ctrlKey;
- if (primaryMod !== !!binding.ctrl) return false;
- if (e.shiftKey !== !!binding.shift) return false;
- if (e.altKey !== !!binding.alt) return false;
+ const primaryMod = isMacPlatform ? e.metaKey : e.ctrlKey;
+ if (primaryMod !== !!binding.ctrl) return false;
+ if (e.shiftKey !== !!binding.shift) return false;
+ if (e.altKey !== !!binding.alt) return false;
- return true;
+ return true;
}
const KEY_LABELS: Record<string, string> = {
- ' ': 'Space', 'delete': 'Del', 'backspace': '⌫', 'escape': 'Esc',
- 'arrowup': '↑', 'arrowdown': '↓', 'arrowleft': '←', 'arrowright': '→',
+ " ": "Space",
+ delete: "Del",
+ backspace: "⌫",
+ escape: "Esc",
+ arrowup: "↑",
+ arrowdown: "↓",
+ arrowleft: "←",
+ arrowright: "→",
};
export function formatBinding(binding: ShortcutBinding, isMac: boolean): string {
- const parts: string[] = [];
- if (binding.ctrl) parts.push(isMac ? '⌘' : 'Ctrl');
- if (binding.shift) parts.push(isMac ? '⇧' : 'Shift');
- if (binding.alt) parts.push(isMac ? '⌥' : 'Alt');
- parts.push(KEY_LABELS[binding.key] ?? binding.key.toUpperCase());
- return parts.join(' + ');
+ const parts: string[] = [];
+ if (binding.ctrl) parts.push(isMac ? "⌘" : "Ctrl");
+ if (binding.shift) parts.push(isMac ? "⇧" : "Shift");
+ if (binding.alt) parts.push(isMac ? "⌥" : "Alt");
+ parts.push(KEY_LABELS[binding.key] ?? binding.key.toUpperCase());
+ return parts.join(" + ");
}
export function mergeWithDefaults(partial: Partial<ShortcutsConfig>): ShortcutsConfig {
- const merged = { ...DEFAULT_SHORTCUTS };
- for (const action of SHORTCUT_ACTIONS) {
- if (partial[action]) {
- merged[action] = partial[action] as ShortcutBinding;
- }
- }
- return merged;
+ const merged = { ...DEFAULT_SHORTCUTS };
+ for (const action of SHORTCUT_ACTIONS) {
+ if (partial[action]) {
+ merged[action] = partial[action] as ShortcutBinding;
+ }
+ }
+ return merged;
}
-
diff --git a/src/lib/utils.ts b/src/lib/utils.ts
index e8ed5251..ac680b30 100644
--- a/src/lib/utils.ts
+++ b/src/lib/utils.ts
@@ -1,7 +1,6 @@
-import { clsx, type ClassValue } from "clsx"
-import { twMerge } from "tailwind-merge"
+import { type ClassValue, clsx } from "clsx";
+import { twMerge } from "tailwind-merge";
export function cn(...inputs: ClassValue[]) {
- return twMerge(clsx(inputs))
+ return twMerge(clsx(inputs));
}
-
diff --git a/src/lib/wallpapers.ts b/src/lib/wallpapers.ts
index 5f5d896d..ee964c77 100644
--- a/src/lib/wallpapers.ts
+++ b/src/lib/wallpapers.ts
@@ -1,114 +1,239 @@
export interface BuiltInWallpaper {
- id: string;
- label: string;
- relativePath: string;
- publicPath: string;
+ id: string;
+ label: string;
+ relativePath: string;
+ publicPath: string;
}
const IMAGE_FILE_PATTERN = /\.(avif|gif|jpe?g|png|svg|webp)$/i;
const VIDEO_FILE_PATTERN = /\.(avi|m4v|mkv|mov|mp4|webm)$/i;
export const BUILT_IN_WALLPAPERS: BuiltInWallpaper[] = [
- { id: 'wallpaper-1', label: 'Wallpaper 1', relativePath: 'wallpapers/wallpaper1.jpg', publicPath: '/wallpapers/wallpaper1.jpg' },
- { id: 'wallpaper-2', label: 'Wallpaper 2', relativePath: 'wallpapers/wallpaper2.jpg', publicPath: '/wallpapers/wallpaper2.jpg' },
- { id: 'wallpaper-3', label: 'Wallpaper 3', relativePath: 'wallpapers/wallpaper3.jpg', publicPath: '/wallpapers/wallpaper3.jpg' },
- { id: 'wallpaper-4', label: 'Wallpaper 4', relativePath: 'wallpapers/wallpaper4.jpg', publicPath: '/wallpapers/wallpaper4.jpg' },
- { id: 'wallpaper-5', label: 'Wallpaper 5', relativePath: 'wallpapers/wallpaper5.jpg', publicPath: '/wallpapers/wallpaper5.jpg' },
- { id: 'wallpaper-6', label: 'Wallpaper 6', relativePath: 'wallpapers/wallpaper6.jpg', publicPath: '/wallpapers/wallpaper6.jpg' },
- { id: 'wallpaper-7', label: 'Wallpaper 7', relativePath: 'wallpapers/wallpaper7.jpg', publicPath: '/wallpapers/wallpaper7.jpg' },
- { id: 'wallpaper-8', label: 'Wallpaper 8', relativePath: 'wallpapers/wallpaper8.jpg', publicPath: '/wallpapers/wallpaper8.jpg' },
- { id: 'wallpaper-9', label: 'Wallpaper 9', relativePath: 'wallpapers/wallpaper9.jpg', publicPath: '/wallpapers/wallpaper9.jpg' },
- { id: 'wallpaper-10', label: 'Wallpaper 10', relativePath: 'wallpapers/wallpaper10.jpg', publicPath: '/wallpapers/wallpaper10.jpg' },
- { id: 'wallpaper-11', label: 'Wallpaper 11', relativePath: 'wallpapers/wallpaper11.jpg', publicPath: '/wallpapers/wallpaper11.jpg' },
- { id: 'wallpaper-12', label: 'Wallpaper 12', relativePath: 'wallpapers/wallpaper12.jpg', publicPath: '/wallpapers/wallpaper12.jpg' },
- { id: 'wallpaper-13', label: 'Wallpaper 13', relativePath: 'wallpapers/wallpaper13.jpg', publicPath: '/wallpapers/wallpaper13.jpg' },
- { id: 'wallpaper-14', label: 'Wallpaper 14', relativePath: 'wallpapers/wallpaper14.jpg', publicPath: '/wallpapers/wallpaper14.jpg' },
- { id: 'wallpaper-15', label: 'Wallpaper 15', relativePath: 'wallpapers/wallpaper15.jpg', publicPath: '/wallpapers/wallpaper15.jpg' },
- { id: 'wallpaper-16', label: 'Wallpaper 16', relativePath: 'wallpapers/wallpaper16.jpg', publicPath: '/wallpapers/wallpaper16.jpg' },
- { id: 'wallpaper-17', label: 'Wallpaper 17', relativePath: 'wallpapers/wallpaper17.jpg', publicPath: '/wallpapers/wallpaper17.jpg' },
- { id: 'wallpaper-18', label: 'Wallpaper 18', relativePath: 'wallpapers/wallpaper18.jpg', publicPath: '/wallpapers/wallpaper18.jpg' },
- { id: 'cityscape', label: 'Cityscape', relativePath: 'wallpapers/cityscape.jpg', publicPath: '/wallpapers/cityscape.jpg' },
- { id: 'farmvalley', label: 'Farm Valley', relativePath: 'wallpapers/farmvalley.jpg', publicPath: '/wallpapers/farmvalley.jpg' },
- { id: 'levels', label: 'Levels', relativePath: 'wallpapers/levels.jpg', publicPath: '/wallpapers/levels.jpg' },
- { id: 'mountaintrees', label: 'Mountain Trees', relativePath: 'wallpapers/mountaintrees.jpg', publicPath: '/wallpapers/mountaintrees.jpg' },
- { id: 'luisdelrio', label: 'Luis Del Rio', relativePath: 'wallpapers/luisdelrio.jpg', publicPath: '/wallpapers/luisdelrio.jpg' },
- { id: 'wispysky', label: 'Wispy Sky', relativePath: 'wallpapers/wispysky.mp4', publicPath: '/wallpapers/wispysky.mp4' },
+ {
+ id: "wallpaper-1",
+ label: "Wallpaper 1",
+ relativePath: "wallpapers/wallpaper1.jpg",
+ publicPath: "/wallpapers/wallpaper1.jpg",
+ },
+ {
+ id: "wallpaper-2",
+ label: "Wallpaper 2",
+ relativePath: "wallpapers/wallpaper2.jpg",
+ publicPath: "/wallpapers/wallpaper2.jpg",
+ },
+ {
+ id: "wallpaper-3",
+ label: "Wallpaper 3",
+ relativePath: "wallpapers/wallpaper3.jpg",
+ publicPath: "/wallpapers/wallpaper3.jpg",
+ },
+ {
+ id: "wallpaper-4",
+ label: "Wallpaper 4",
+ relativePath: "wallpapers/wallpaper4.jpg",
+ publicPath: "/wallpapers/wallpaper4.jpg",
+ },
+ {
+ id: "wallpaper-5",
+ label: "Wallpaper 5",
+ relativePath: "wallpapers/wallpaper5.jpg",
+ publicPath: "/wallpapers/wallpaper5.jpg",
+ },
+ {
+ id: "wallpaper-6",
+ label: "Wallpaper 6",
+ relativePath: "wallpapers/wallpaper6.jpg",
+ publicPath: "/wallpapers/wallpaper6.jpg",
+ },
+ {
+ id: "wallpaper-7",
+ label: "Wallpaper 7",
+ relativePath: "wallpapers/wallpaper7.jpg",
+ publicPath: "/wallpapers/wallpaper7.jpg",
+ },
+ {
+ id: "wallpaper-8",
+ label: "Wallpaper 8",
+ relativePath: "wallpapers/wallpaper8.jpg",
+ publicPath: "/wallpapers/wallpaper8.jpg",
+ },
+ {
+ id: "wallpaper-9",
+ label: "Wallpaper 9",
+ relativePath: "wallpapers/wallpaper9.jpg",
+ publicPath: "/wallpapers/wallpaper9.jpg",
+ },
+ {
+ id: "wallpaper-10",
+ label: "Wallpaper 10",
+ relativePath: "wallpapers/wallpaper10.jpg",
+ publicPath: "/wallpapers/wallpaper10.jpg",
+ },
+ {
+ id: "wallpaper-11",
+ label: "Wallpaper 11",
+ relativePath: "wallpapers/wallpaper11.jpg",
+ publicPath: "/wallpapers/wallpaper11.jpg",
+ },
+ {
+ id: "wallpaper-12",
+ label: "Wallpaper 12",
+ relativePath: "wallpapers/wallpaper12.jpg",
+ publicPath: "/wallpapers/wallpaper12.jpg",
+ },
+ {
+ id: "wallpaper-13",
+ label: "Wallpaper 13",
+ relativePath: "wallpapers/wallpaper13.jpg",
+ publicPath: "/wallpapers/wallpaper13.jpg",
+ },
+ {
+ id: "wallpaper-14",
+ label: "Wallpaper 14",
+ relativePath: "wallpapers/wallpaper14.jpg",
+ publicPath: "/wallpapers/wallpaper14.jpg",
+ },
+ {
+ id: "wallpaper-15",
+ label: "Wallpaper 15",
+ relativePath: "wallpapers/wallpaper15.jpg",
+ publicPath: "/wallpapers/wallpaper15.jpg",
+ },
+ {
+ id: "wallpaper-16",
+ label: "Wallpaper 16",
+ relativePath: "wallpapers/wallpaper16.jpg",
+ publicPath: "/wallpapers/wallpaper16.jpg",
+ },
+ {
+ id: "wallpaper-17",
+ label: "Wallpaper 17",
+ relativePath: "wallpapers/wallpaper17.jpg",
+ publicPath: "/wallpapers/wallpaper17.jpg",
+ },
+ {
+ id: "wallpaper-18",
+ label: "Wallpaper 18",
+ relativePath: "wallpapers/wallpaper18.jpg",
+ publicPath: "/wallpapers/wallpaper18.jpg",
+ },
+ {
+ id: "cityscape",
+ label: "Cityscape",
+ relativePath: "wallpapers/cityscape.jpg",
+ publicPath: "/wallpapers/cityscape.jpg",
+ },
+ {
+ id: "farmvalley",
+ label: "Farm Valley",
+ relativePath: "wallpapers/farmvalley.jpg",
+ publicPath: "/wallpapers/farmvalley.jpg",
+ },
+ {
+ id: "levels",
+ label: "Levels",
+ relativePath: "wallpapers/levels.jpg",
+ publicPath: "/wallpapers/levels.jpg",
+ },
+ {
+ id: "mountaintrees",
+ label: "Mountain Trees",
+ relativePath: "wallpapers/mountaintrees.jpg",
+ publicPath: "/wallpapers/mountaintrees.jpg",
+ },
+ {
+ id: "luisdelrio",
+ label: "Luis Del Rio",
+ relativePath: "wallpapers/luisdelrio.jpg",
+ publicPath: "/wallpapers/luisdelrio.jpg",
+ },
+ {
+ id: "wispysky",
+ label: "Wispy Sky",
+ relativePath: "wallpapers/wispysky.mp4",
+ publicPath: "/wallpapers/wispysky.mp4",
+ },
];
export const WALLPAPER_PATHS = BUILT_IN_WALLPAPERS.map((wallpaper) => wallpaper.publicPath);
-export const WALLPAPER_RELATIVE_PATHS = BUILT_IN_WALLPAPERS.map((wallpaper) => wallpaper.relativePath);
-export const DEFAULT_WALLPAPER_PATH = '/wallpapers/wallpaper2.jpg';
-export const DEFAULT_WALLPAPER_RELATIVE_PATH = 'wallpapers/wallpaper2.jpg';
+export const WALLPAPER_RELATIVE_PATHS = BUILT_IN_WALLPAPERS.map(
+ (wallpaper) => wallpaper.relativePath,
+);
+export const DEFAULT_WALLPAPER_PATH = "/wallpapers/wallpaper2.jpg";
+export const DEFAULT_WALLPAPER_RELATIVE_PATH = "wallpapers/wallpaper2.jpg";
export function isVideoWallpaperSource(value: string): boolean {
- if (!value) {
- return false;
- }
+ if (!value) {
+ return false;
+ }
- const normalizedValue = value.split("?")[0]?.toLowerCase() ?? value.toLowerCase();
- return VIDEO_FILE_PATTERN.test(normalizedValue);
+ const normalizedValue = value.split("?")[0]?.toLowerCase() ?? value.toLowerCase();
+ return VIDEO_FILE_PATTERN.test(normalizedValue);
}
function toWallpaperId(fileName: string) {
- return fileName
- .replace(/\.[^.]+$/, "")
- .trim()
- .toLowerCase()
- .replace(/[^a-z0-9]+/g, "-")
- .replace(/^-+|-+$/g, "");
+ return fileName
+ .replace(/\.[^.]+$/, "")
+ .trim()
+ .toLowerCase()
+ .replace(/[^a-z0-9]+/g, "-")
+ .replace(/^-+|-+$/g, "");
}
function toWallpaperLabel(fileName: string) {
- const baseName = fileName.replace(/\.[^.]+$/, "").trim();
- if (!baseName) {
- return "Wallpaper";
- }
-
- return baseName
- .replace(/[_-]+/g, " ")
- .replace(/\s+/g, " ")
- .replace(/\b\w/g, (match) => match.toUpperCase());
+ const baseName = fileName.replace(/\.[^.]+$/, "").trim();
+ if (!baseName) {
+ return "Wallpaper";
+ }
+
+ return baseName
+ .replace(/[_-]+/g, " ")
+ .replace(/\s+/g, " ")
+ .replace(/\b\w/g, (match) => match.toUpperCase());
}
function createWallpaperEntry(fileName: string): BuiltInWallpaper {
- const encodedFileName = encodeURIComponent(fileName);
- return {
- id: toWallpaperId(fileName) || `wallpaper-${encodedFileName.toLowerCase()}`,
- label: toWallpaperLabel(fileName),
- relativePath: `wallpapers/${fileName}`,
- publicPath: `/wallpapers/${encodedFileName}`,
- };
+ const encodedFileName = encodeURIComponent(fileName);
+ return {
+ id: toWallpaperId(fileName) || `wallpaper-${encodedFileName.toLowerCase()}`,
+ label: toWallpaperLabel(fileName),
+ relativePath: `wallpapers/${fileName}`,
+ publicPath: `/wallpapers/${encodedFileName}`,
+ };
}
function sortWallpaperFiles(fileNames: string[]) {
- return [...fileNames].sort(
- new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare,
- );
+ return [...fileNames].sort(
+ new Intl.Collator(undefined, { numeric: true, sensitivity: "base" }).compare,
+ );
}
export async function getAvailableWallpapers(): Promise<BuiltInWallpaper[]> {
- const fallbackWallpapers = BUILT_IN_WALLPAPERS;
-
- if (typeof window === "undefined" || !window.electronAPI?.listAssetDirectory) {
- return fallbackWallpapers;
- }
-
- try {
- const result = await window.electronAPI.listAssetDirectory("wallpapers");
- if (!result.success || !result.files?.length) {
- return fallbackWallpapers;
- }
-
- const discoveredFiles = sortWallpaperFiles(
- result.files.filter((fileName) => IMAGE_FILE_PATTERN.test(fileName) || VIDEO_FILE_PATTERN.test(fileName)),
- );
-
- if (discoveredFiles.length === 0) {
- return fallbackWallpapers;
- }
-
- return discoveredFiles.map(createWallpaperEntry);
- } catch {
- return fallbackWallpapers;
- }
+ const fallbackWallpapers = BUILT_IN_WALLPAPERS;
+
+ if (typeof window === "undefined" || !window.electronAPI?.listAssetDirectory) {
+ return fallbackWallpapers;
+ }
+
+ try {
+ const result = await window.electronAPI.listAssetDirectory("wallpapers");
+ if (!result.success || !result.files?.length) {
+ return fallbackWallpapers;
+ }
+
+ const discoveredFiles = sortWallpaperFiles(
+ result.files.filter(
+ (fileName) =>
+ IMAGE_FILE_PATTERN.test(fileName) || VIDEO_FILE_PATTERN.test(fileName),
+ ),
+ );
+
+ if (discoveredFiles.length === 0) {
+ return fallbackWallpapers;
+ }
+
+ return discoveredFiles.map(createWallpaperEntry);
+ } catch {
+ return fallbackWallpapers;
+ }
}
diff --git a/src/main.tsx b/src/main.tsx
index 89aa334b..5d6ff6b1 100644
--- a/src/main.tsx
+++ b/src/main.tsx
@@ -1,16 +1,15 @@
-import React from 'react'
-import ReactDOM from 'react-dom/client'
-import App from './App.tsx'
-import { I18nProvider } from './contexts/I18nContext.tsx'
-import './index.css'
-
-document.documentElement.dataset.platform = /mac/i.test(navigator.platform) ? 'macos' : 'other'
-
-ReactDOM.createRoot(document.getElementById('root')!).render(
- <React.StrictMode>
- <I18nProvider>
- <App />
- </I18nProvider>
- </React.StrictMode>,
-)
-
+import React from "react";
+import ReactDOM from "react-dom/client";
+import App from "./App.tsx";
+import { I18nProvider } from "./contexts/I18nContext.tsx";
+import "./index.css";
+
+document.documentElement.dataset.platform = /mac/i.test(navigator.platform) ? "macos" : "other";
+
+ReactDOM.createRoot(document.getElementById("root")!).render(
+ <React.StrictMode>
+ <I18nProvider>
+ <App />
+ </I18nProvider>
+ </React.StrictMode>,
+);
diff --git a/src/utils/aspectRatioUtils.ts b/src/utils/aspectRatioUtils.ts
index 983f93a6..45c12f96 100644
--- a/src/utils/aspectRatioUtils.ts
+++ b/src/utils/aspectRatioUtils.ts
@@ -1,6 +1,15 @@
-export const ASPECT_RATIOS = ['native', '16:9', '9:16', '1:1', '4:3', '4:5', '16:10', '10:16'] as const;
+export const ASPECT_RATIOS = [
+ "native",
+ "16:9",
+ "9:16",
+ "1:1",
+ "4:3",
+ "4:5",
+ "16:10",
+ "10:16",
+] as const;
-type PresetAspectRatio = typeof ASPECT_RATIOS[number];
+type PresetAspectRatio = (typeof ASPECT_RATIOS)[number];
type CustomAspectRatio = `${number}:${number}`;
export type AspectRatio = PresetAspectRatio | CustomAspectRatio;
@@ -8,29 +17,29 @@ export type AspectRatio = PresetAspectRatio | CustomAspectRatio;
const CUSTOM_ASPECT_RATIO_REGEX = /^(\d+):(\d+)$/;
export function isCustomAspectRatio(aspectRatio: string): aspectRatio is CustomAspectRatio {
- if ((ASPECT_RATIOS as readonly string[]).includes(aspectRatio)) {
- return false;
- }
- const match = aspectRatio.match(CUSTOM_ASPECT_RATIO_REGEX);
- if (!match) {
- return false;
- }
- const width = Number(match[1]);
- const height = Number(match[2]);
- return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0;
+ if ((ASPECT_RATIOS as readonly string[]).includes(aspectRatio)) {
+ return false;
+ }
+ const match = aspectRatio.match(CUSTOM_ASPECT_RATIO_REGEX);
+ if (!match) {
+ return false;
+ }
+ const width = Number(match[1]);
+ const height = Number(match[2]);
+ return Number.isFinite(width) && Number.isFinite(height) && width > 0 && height > 0;
}
function parseCustomAspectRatioValue(aspectRatio: string): number | null {
- if (!isCustomAspectRatio(aspectRatio)) {
- return null;
- }
- const [widthText, heightText] = aspectRatio.split(':');
- const width = Number(widthText);
- const height = Number(heightText);
- if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
- return null;
- }
- return width / height;
+ if (!isCustomAspectRatio(aspectRatio)) {
+ return null;
+ }
+ const [widthText, heightText] = aspectRatio.split(":");
+ const width = Number(widthText);
+ const height = Number(heightText);
+ if (!Number.isFinite(width) || !Number.isFinite(height) || width <= 0 || height <= 0) {
+ return null;
+ }
+ return width / height;
}
/**
@@ -39,47 +48,56 @@ function parseCustomAspectRatioValue(aspectRatio: string): number | null {
* If TypeScript errors here, a new ratio was added to the type but not handled.
*/
export function getAspectRatioValue(aspectRatio: AspectRatio, nativeAspectRatio = 16 / 9): number {
- switch (aspectRatio) {
- case 'native': return nativeAspectRatio > 0 ? nativeAspectRatio : 16 / 9;
- case '16:9': return 16 / 9;
- case '9:16': return 9 / 16;
- case '1:1': return 1;
- case '4:3': return 4 / 3;
- case '4:5': return 4 / 5;
- case '16:10': return 16 / 10;
- case '10:16': return 10 / 16;
- default:
- return parseCustomAspectRatioValue(aspectRatio) ?? 16 / 9;
- }
+ switch (aspectRatio) {
+ case "native":
+ return nativeAspectRatio > 0 ? nativeAspectRatio : 16 / 9;
+ case "16:9":
+ return 16 / 9;
+ case "9:16":
+ return 9 / 16;
+ case "1:1":
+ return 1;
+ case "4:3":
+ return 4 / 3;
+ case "4:5":
+ return 4 / 5;
+ case "16:10":
+ return 16 / 10;
+ case "10:16":
+ return 10 / 16;
+ default:
+ return parseCustomAspectRatioValue(aspectRatio) ?? 16 / 9;
+ }
}
export function getAspectRatioDimensions(
- aspectRatio: AspectRatio,
- baseWidth: number,
- nativeAspectRatio?: number,
+ aspectRatio: AspectRatio,
+ baseWidth: number,
+ nativeAspectRatio?: number,
): { width: number; height: number } {
- const ratio = getAspectRatioValue(aspectRatio, nativeAspectRatio);
- return {
- width: baseWidth,
- height: baseWidth / ratio,
- };
+ const ratio = getAspectRatioValue(aspectRatio, nativeAspectRatio);
+ return {
+ width: baseWidth,
+ height: baseWidth / ratio,
+ };
}
export function getAspectRatioLabel(aspectRatio: AspectRatio): string {
- if (aspectRatio === 'native') {
- return 'Native';
- }
- if (isCustomAspectRatio(aspectRatio)) {
- return `Custom ${aspectRatio}`;
- }
- return aspectRatio;
+ if (aspectRatio === "native") {
+ return "Native";
+ }
+ if (isCustomAspectRatio(aspectRatio)) {
+ return `Custom ${aspectRatio}`;
+ }
+ return aspectRatio;
}
-
-export function formatAspectRatioForCSS(aspectRatio: AspectRatio, nativeAspectRatio = 16 / 9): string {
- if (aspectRatio === 'native') {
- return `${nativeAspectRatio > 0 ? nativeAspectRatio : 16 / 9}`;
- }
- return aspectRatio.replace(':', '/');
+export function formatAspectRatioForCSS(
+ aspectRatio: AspectRatio,
+ nativeAspectRatio = 16 / 9,
+): string {
+ if (aspectRatio === "native") {
+ return `${nativeAspectRatio > 0 ? nativeAspectRatio : 16 / 9}`;
+ }
+ return aspectRatio.replace(":", "/");
}
-
diff --git a/src/utils/platformUtils.ts b/src/utils/platformUtils.ts
index cca70852..37d5a6dc 100644
--- a/src/utils/platformUtils.ts
+++ b/src/utils/platformUtils.ts
@@ -4,44 +4,44 @@ let cachedPlatform: string | null = null;
* Gets the current platform from Electron
*/
const getPlatform = async (): Promise<string> => {
- if (cachedPlatform) return cachedPlatform;
-
- try {
- const platform = await window.electronAPI.getPlatform();
- cachedPlatform = platform;
- return platform;
- } catch (error) {
- console.warn('Failed to get platform from Electron, falling back to navigator:', error);
- // Fallback for development/testing
- let fallbackPlatform = 'win32';
- if (typeof navigator !== 'undefined' && /Mac|iPhone|iPad|iPod/.test(navigator.platform)) {
- fallbackPlatform = 'darwin';
- }
- cachedPlatform = fallbackPlatform;
- return fallbackPlatform;
- }
+ if (cachedPlatform) return cachedPlatform;
+
+ try {
+ const platform = await window.electronAPI.getPlatform();
+ cachedPlatform = platform;
+ return platform;
+ } catch (error) {
+ console.warn("Failed to get platform from Electron, falling back to navigator:", error);
+ // Fallback for development/testing
+ let fallbackPlatform = "win32";
+ if (typeof navigator !== "undefined" && /Mac|iPhone|iPad|iPod/.test(navigator.platform)) {
+ fallbackPlatform = "darwin";
+ }
+ cachedPlatform = fallbackPlatform;
+ return fallbackPlatform;
+ }
};
/**
* Detects if the current platform is macOS
*/
export const isMac = async (): Promise<boolean> => {
- const platform = await getPlatform();
- return platform === 'darwin';
+ const platform = await getPlatform();
+ return platform === "darwin";
};
/**
* Gets the modifier key symbol based on the platform
*/
export const getModifierKey = async (): Promise<string> => {
- return (await isMac()) ? '⌘' : 'Ctrl';
+ return (await isMac()) ? "⌘" : "Ctrl";
};
/**
* Gets the shift key symbol based on the platform
*/
export const getShiftKey = async (): Promise<string> => {
- return (await isMac()) ? '⇧' : 'Shift';
+ return (await isMac()) ? "⇧" : "Shift";
};
/**
@@ -49,12 +49,12 @@ export const getShiftKey = async (): Promise<string> => {
* @param keys Array of key combinations (e.g., ['mod', 'D'] or ['shift', 'mod', 'Scroll'])
*/
export const formatShortcut = async (keys: string[]): Promise<string> => {
- const isMacPlatform = await isMac();
- return keys
- .map(key => {
- if (key.toLowerCase() === 'mod') return isMacPlatform ? '⌘' : 'Ctrl';
- if (key.toLowerCase() === 'shift') return isMacPlatform ? '⇧' : 'Shift';
- return key;
- })
- .join(' + ');
+ const isMacPlatform = await isMac();
+ return keys
+ .map((key) => {
+ if (key.toLowerCase() === "mod") return isMacPlatform ? "⌘" : "Ctrl";
+ if (key.toLowerCase() === "shift") return isMacPlatform ? "⇧" : "Shift";
+ return key;
+ })
+ .join(" + ");
};
diff --git a/tailwind.config.cjs b/tailwind.config.cjs
index 1c9b746b..4a3cae0a 100644
--- a/tailwind.config.cjs
+++ b/tailwind.config.cjs
@@ -1,75 +1,71 @@
/** @type {import('tailwindcss').Config} */
module.exports = {
- darkMode: ['class'],
- content: [
- './index.html',
- './src/**/*.{js,ts,jsx,tsx}',
- ],
- theme: {
- extend: {
- keyframes: {
- "accordion-down": {
- from: { height: "0" },
- to: { height: "var(--radix-accordion-content-height)" },
- },
- "accordion-up": {
- from: { height: "var(--radix-accordion-content-height)" },
- to: { height: "0" },
- },
- },
- animation: {
- "accordion-down": "accordion-down 0.2s ease-out",
- "accordion-up": "accordion-up 0.2s ease-out",
- },
- borderRadius: {
- lg: 'var(--radius)',
- md: 'calc(var(--radius) - 2px)',
- sm: 'calc(var(--radius) - 4px)'
- },
- colors: {
- background: 'hsl(var(--background))',
- foreground: 'hsl(var(--foreground))',
- card: {
- DEFAULT: 'hsl(var(--card))',
- foreground: 'hsl(var(--card-foreground))'
- },
- popover: {
- DEFAULT: 'hsl(var(--popover))',
- foreground: 'hsl(var(--popover-foreground))'
- },
- primary: {
- DEFAULT: 'hsl(var(--primary))',
- foreground: 'hsl(var(--primary-foreground))'
- },
- secondary: {
- DEFAULT: 'hsl(var(--secondary))',
- foreground: 'hsl(var(--secondary-foreground))'
- },
- muted: {
- DEFAULT: 'hsl(var(--muted))',
- foreground: 'hsl(var(--muted-foreground))'
- },
- accent: {
- DEFAULT: 'hsl(var(--accent))',
- foreground: 'hsl(var(--accent-foreground))'
- },
- destructive: {
- DEFAULT: 'hsl(var(--destructive))',
- foreground: 'hsl(var(--destructive-foreground))'
- },
- border: 'hsl(var(--border))',
- input: 'hsl(var(--input))',
- ring: 'hsl(var(--ring))',
- chart: {
- '1': 'hsl(var(--chart-1))',
- '2': 'hsl(var(--chart-2))',
- '3': 'hsl(var(--chart-3))',
- '4': 'hsl(var(--chart-4))',
- '5': 'hsl(var(--chart-5))'
- }
- }
- }
- },
- plugins: [require("tailwindcss-animate")],
-}
-
+ darkMode: ["class"],
+ content: ["./index.html", "./src/**/*.{js,ts,jsx,tsx}"],
+ theme: {
+ extend: {
+ keyframes: {
+ "accordion-down": {
+ from: { height: "0" },
+ to: { height: "var(--radix-accordion-content-height)" },
+ },
+ "accordion-up": {
+ from: { height: "var(--radix-accordion-content-height)" },
+ to: { height: "0" },
+ },
+ },
+ animation: {
+ "accordion-down": "accordion-down 0.2s ease-out",
+ "accordion-up": "accordion-up 0.2s ease-out",
+ },
+ borderRadius: {
+ lg: "var(--radius)",
+ md: "calc(var(--radius) - 2px)",
+ sm: "calc(var(--radius) - 4px)",
+ },
+ colors: {
+ background: "hsl(var(--background))",
+ foreground: "hsl(var(--foreground))",
+ card: {
+ DEFAULT: "hsl(var(--card))",
+ foreground: "hsl(var(--card-foreground))",
+ },
+ popover: {
+ DEFAULT: "hsl(var(--popover))",
+ foreground: "hsl(var(--popover-foreground))",
+ },
+ primary: {
+ DEFAULT: "hsl(var(--primary))",
+ foreground: "hsl(var(--primary-foreground))",
+ },
+ secondary: {
+ DEFAULT: "hsl(var(--secondary))",
+ foreground: "hsl(var(--secondary-foreground))",
+ },
+ muted: {
+ DEFAULT: "hsl(var(--muted))",
+ foreground: "hsl(var(--muted-foreground))",
+ },
+ accent: {
+ DEFAULT: "hsl(var(--accent))",
+ foreground: "hsl(var(--accent-foreground))",
+ },
+ destructive: {
+ DEFAULT: "hsl(var(--destructive))",
+ foreground: "hsl(var(--destructive-foreground))",
+ },
+ border: "hsl(var(--border))",
+ input: "hsl(var(--input))",
+ ring: "hsl(var(--ring))",
+ chart: {
+ 1: "hsl(var(--chart-1))",
+ 2: "hsl(var(--chart-2))",
+ 3: "hsl(var(--chart-3))",
+ 4: "hsl(var(--chart-4))",
+ 5: "hsl(var(--chart-5))",
+ },
+ },
+ },
+ },
+ plugins: [require("tailwindcss-animate")],
+};
diff --git a/tsconfig.json b/tsconfig.json
index f9acd4ad..4a7aee40 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -5,6 +5,7 @@
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
+ "ignoreDeprecations": "5.0",
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
diff --git a/tsconfig.node.json b/tsconfig.node.json
index 72d34131..1caabefc 100644
--- a/tsconfig.node.json
+++ b/tsconfig.node.json
@@ -1,12 +1,11 @@
-{
- "compilerOptions": {
- "composite": true,
- "skipLibCheck": true,
- "module": "ESNext",
- "moduleResolution": "bundler",
- "allowSyntheticDefaultImports": true,
- "strict": true
- },
- "include": ["vite.config.ts"]
-}
-
+{
+ "compilerOptions": {
+ "composite": true,
+ "skipLibCheck": true,
+ "module": "ESNext",
+ "moduleResolution": "bundler",
+ "allowSyntheticDefaultImports": true,
+ "strict": true
+ },
+ "include": ["vite.config.ts"]
+}
diff --git a/vite.config.ts b/vite.config.ts
index 42b066fa..5d512c04 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -1,76 +1,75 @@
-import { defineConfig } from 'vite'
-import path from 'node:path'
-import electron from 'vite-plugin-electron/simple'
-import react from '@vitejs/plugin-react'
-
+import path from "node:path";
+import react from "@vitejs/plugin-react";
+import { defineConfig } from "vite";
+import electron from "vite-plugin-electron/simple";
// https://vitejs.dev/config/
export default defineConfig({
- plugins: [
- react(),
- electron({
- main: {
- // Shortcut of `build.lib.entry`.
- entry: 'electron/main.ts',
- vite: {
- build: {
- rollupOptions: {
- external: ['ffmpeg-static', 'uiohook-napi'],
- },
- }
- }
- },
- preload: {
- // Shortcut of `build.rollupOptions.input`.
- // Preload scripts may contain Web assets, so use the `build.rollupOptions.input` instead `build.lib.entry`.
- input: path.join(__dirname, 'electron/preload.ts'),
- },
- // Ployfill the Electron and Node.js API for Renderer process.
- // If you want use Node.js in Renderer process, the `nodeIntegration` needs to be enabled in the Main process.
- // See https://github.com/electron-vite/vite-plugin-electron-renderer
- renderer: process.env.NODE_ENV === 'test'
- // https://github.com/electron-vite/vite-plugin-electron-renderer/issues/78#issuecomment-2053600808
- ? undefined
- : {},
- }),
- ],
- resolve: {
- alias: {
- '@': path.resolve(__dirname, 'src'),
- },
- },
- optimizeDeps: {
- entries: ['index.html'],
- exclude: [
- 'lucide-react',
- 'react-icons/bs',
- 'react-icons/fa',
- 'react-icons/fa6',
- 'react-icons/fi',
- 'react-icons/md',
- 'react-icons/rx',
- ],
- },
- build: {
- target: 'esnext',
- minify: 'terser',
- terserOptions: {
- compress: {
- drop_console: true,
- drop_debugger: true,
- pure_funcs: ['console.log', 'console.debug']
- }
- },
- rollupOptions: {
- output: {
- manualChunks: {
- 'pixi': ['pixi.js'],
- 'react-vendor': ['react', 'react-dom'],
- 'video-processing': ['mediabunny', 'mp4box', '@fix-webm-duration/fix']
- }
- }
- },
- chunkSizeWarningLimit: 1000
- }
-})
-
+ plugins: [
+ react(),
+ electron({
+ main: {
+ // Shortcut of `build.lib.entry`.
+ entry: "electron/main.ts",
+ vite: {
+ build: {
+ rollupOptions: {
+ external: ["ffmpeg-static", "uiohook-napi"],
+ },
+ },
+ },
+ },
+ preload: {
+ // Shortcut of `build.rollupOptions.input`.
+ // Preload scripts may contain Web assets, so use the `build.rollupOptions.input` instead `build.lib.entry`.
+ input: path.join(__dirname, "electron/preload.ts"),
+ },
+ // Ployfill the Electron and Node.js API for Renderer process.
+ // If you want use Node.js in Renderer process, the `nodeIntegration` needs to be enabled in the Main process.
+ // See https://github.com/electron-vite/vite-plugin-electron-renderer
+ renderer:
+ process.env.NODE_ENV === "test"
+ ? // https://github.com/electron-vite/vite-plugin-electron-renderer/issues/78#issuecomment-2053600808
+ undefined
+ : {},
+ }),
+ ],
+ resolve: {
+ alias: {
+ "@": path.resolve(__dirname, "src"),
+ },
+ },
+ optimizeDeps: {
+ entries: ["index.html"],
+ exclude: [
+ "lucide-react",
+ "react-icons/bs",
+ "react-icons/fa",
+ "react-icons/fa6",
+ "react-icons/fi",
+ "react-icons/md",
+ "react-icons/rx",
+ ],
+ },
+ build: {
+ target: "esnext",
+ minify: "terser",
+ terserOptions: {
+ compress: {
+ drop_console: true,
+ drop_debugger: true,
+ pure_funcs: ["console.log", "console.debug"],
+ },
+ },
+ rollupOptions: {
+ output: {
+ manualChunks: {
+ pixi: ["pixi.js"],
+ "react-vendor": ["react", "react-dom"],
+ "video-processing": ["mediabunny", "mp4box", "@fix-webm-duration/fix"],
+ },
+ },
+ },
+ chunkSizeWarningLimit: 1000,
+ },
+});