From 8d8e025a6941749975844e89e09efb6486afac9f Mon Sep 17 00:00:00 2001 From: translator Date: Tue, 21 Apr 2026 16:24:11 +0900 Subject: [PATCH] Myriad changes. --- .env.example | 16 + .../workflows/muon-iframe-build-publish.yml | 100 + 20260313_Fixes (Copilot).md | 779 ++++ 20260417_Phase2_1_Completion_Report.md | 387 ++ 20260417_Phase2_Session_Summary.txt | 217 + Phase2_Architecture_And_Dependencies.md | 574 +++ Phase2_Initiation_Report.md | 429 ++ SUMMARIES (Claude).md | 501 +++ backend/main.py | 28 +- backend/routers/local_library.py | 74 + backend/routers/projects.py | 11 + backend/routers/separate.py | 12 + backend/routers/settings.py | 51 +- backend/routers/subsonic.py | 52 +- backend/services/local_library_service.py | 309 ++ backend/services/project_assets_service.py | 173 +- backend/services/project_metadata.py | 2 + backend/services/project_service.py | 1 + backend/services/separator_service.py | 1 + backend/services/subsonic_service.py | 285 +- backend/static/index.html | 4 +- backend/tests/support.py | 6 + .../tests/test_local_library_config_source.py | 34 + backend/tests/test_local_library_security.py | 71 + backend/tests/test_settings.py | 28 + backend/tests/test_subsonic_imports_search.py | 52 + ...026-04-16_Frontend_Deployment_Readiness.md | 220 + .../README.md | 191 + .../README.md | 142 + .../Audit_Fix_Plan.md | 879 ++++ .../2026-04-21_Copilot_Handoff/Checklist.md | 182 + .../2026-04-21_Copilot_Handoff/README.md | 37 + .../Reactivity_Plan.md | 737 ++++ .../2026-04-14_Frontend_UI_Audit.md | 0 ..._LyricsLivePreview_and_Visualizer_Audit.md | 0 .../2026-04-14_SingUI_Karaoke_Box_Gaps.md | 0 ...4_Visualizer_Per_Stem_Reactivity_Design.md | 0 ...UG-VS-A_VS-B_VS-C_Implementation_Record.md | 0 ...ontend_UI_Audit_Issue_and_PR_Checklists.md | 28 +- ...iew_Visualizer_Regression_Investigation.md | 0 .../2026-04-15_Vite_HMR_Docker_Stale_Code.md | 0 .../2026-04-16_Auto_Pipeline_Presets_Plan.md | 0 .../2026-04-16_Execution_Log.md | 0 .../2026-04-16_GPU_OOM_Root_Causes.md | 0 ...026-04-16_Hardware_Adaptive_Config_Plan.md | 0 .../2026-04-16_Implementation_Checklist.md | 92 +- .../2026-04-16_Plan_Review_Amendments.md | 0 .../2026-04-16_Stem_Name_Consistency_Plan.md | 0 .../benchmark_run_2026-04-16.json | 0 ...026-04-17_Local_Music_Library_Path_Plan.md | 319 ++ ...6-04-14_SingUI_Mobile_Karaoke_Box_Index.md | 0 ..._SingUI_Mobile_Karaoke_Box_Issue_Bodies.md | 0 ..._SingUI_Mobile_Karaoke_Box_Issue_Slices.md | 0 ...le_Karaoke_Box_Transformation_Checklist.md | 0 ..._Mobile_Karaoke_Box_Transformation_Plan.md | 0 .../adr/ADR-001-ia-and-routing.md | 0 ...ADR-002-system-boundaries-and-transport.md | 0 ...3-queue-mutation-and-reconnect-contract.md | 0 .../adr/ADR-004-security-and-permissions.md | 0 .../adr/ADR-005-metrics-and-telemetry.md | 0 .../adr/ADR-006-validation-gates.md | 0 .../adr/ADR-007-rollout-and-kill-switch.md | 0 .../adr/ADR-INDEX.md | 0 .../2026-04-16_Deployment_Log.md | 477 +++ ...26-04-16_Deployment_Readiness_Checklist.md | 233 ++ .../2026-04-16_Final_Sign_Off.md | 369 ++ ...6-04-16_Implementation_Complete_Summary.md | 297 ++ .../2026-04-16_Preset_Persistence_WorkLog.md | 118 + ...04-16_QA_Report_and_Deployment_Decision.md | 263 ++ .../2026-04-16_Track_Details_Checklist.md | 362 ++ .../2026-04-16_Track_Details_Plan.md | 576 +++ .../Preparation_Request_Approval_Plan.md | 671 ++++ docs/plans/done/track-details/README.md | 398 ++ .../2026-04-16_UVR_Borrowing_Checklist.md | 169 + .../2026-04-16_UVR_Borrowing_Plan.md | 210 + .../2026-04-17_Plan.md | 119 + .../2026-04-19_Checklist.md | 188 + .../2026-04-19_Findings.md | 184 + .../2026-04-17_Checklist.md | 226 ++ .../2026-04-17_Plan.md | 470 +++ .../2026-04-17_Plan_Patched.md | 306 ++ .../20260417_Session_Completion_Summary.md | 280 ++ .../INSTRUCTIONS.md | 102 + .../P0C_Compliance_Signoff.md | 82 + .../PROJECT_STATUS_BOARD.md | 315 ++ .../Phase1_GateCheck_Execution_Report.md | 193 + .../Phase1_GateCheck_TestPlan.md | 268 ++ .../visualizer-muon-fluid-style/README.md | 235 ++ .../visualizer-muon-iframe/2026-04-17_Plan.md | 216 + .../2026-04-20_Checklist.md | 250 ++ .../2026-04-20_Findings.md | 282 ++ .../2026-04-16_Track_Details_Plan.md | 315 -- .../2026-04-20_KaraokeTV_Visualizer_Audit.md | 68 + .../2026-04-20_Streamlined_Checklist.md | 259 ++ .../2026-04-20_Streamlined_Plan.md | 669 ++++ .../2026-04-20_Visualizer_Reactivity_Audit.md | 160 + .../2026-04-20_Checklist.md | 306 ++ .../2026-04-20_Findings.md | 253 ++ .../2026-04-20_Checklist.md | 307 ++ .../2026-04-20_Copilot_Worklist.md | 212 + .../2026-04-20_Findings.md | 261 ++ ...26-04-20_LyricsLivePreview_Cleanup_Plan.md | 383 ++ .../2026-04-21_Audit_Fix_Plan.md | 879 ++++ ...26-04-21_Claude_Audit_Handoff_NewSchema.md | 106 + .../2026-04-21_Claude_Audit_Results.md | 146 + .../2026-04-21_Implementation_Plan.md | 534 +++ frontend/e2e/lyrics-live-preview.spec.ts | 35 + frontend/e2e/muon-preset-validation.spec.ts | 184 + frontend/e2e/singui-mobile-karaoke.spec.ts | 255 +- frontend/e2e/track-detail-visualizer.spec.ts | 404 ++ frontend/e2e/ui-qol.spec.ts | 216 +- frontend/package-lock.json | 307 +- frontend/package.json | 2 + frontend/src/App.tsx | 5 + frontend/src/api/client.ts | 227 +- frontend/src/components/AppLibraryShell.tsx | 5 +- frontend/src/components/ColorSwatch.tsx | 24 + .../src/components/KaraokePerformanceMode.tsx | 9 +- frontend/src/components/LrcEditor.tsx | 93 + frontend/src/components/LyricsCanvas.tsx | 1255 ++++++ frontend/src/components/LyricsLivePreview.tsx | 3547 +++-------------- frontend/src/components/LyricsStylePicker.tsx | 445 +++ .../src/components/LyricsTransportBar.tsx | 107 + frontend/src/components/LyricsViewport.tsx | 306 ++ .../src/components/PerformanceSidebar.tsx | 235 +- frontend/src/components/Sidebar.tsx | 428 +- frontend/src/components/StemMixerPanel.tsx | 83 + .../components/VisualizerPreviewWidget.tsx | 627 ++- .../components/singui/MobileKaraokeShell.tsx | 22 +- .../components/singui/SongPreviewSheet.tsx | 16 + .../visualizers/DissolveVisualizerCanvas.tsx | 126 + .../visualizers/FluidVisualizerCanvas.tsx | 21 +- .../visualizers/GlitchVisualizerCanvas.tsx | 125 + .../visualizers/MoireVisualizerCanvas.tsx | 125 + .../visualizers/SpiralVisualizerCanvas.tsx | 125 + .../visualizers/SpiritVisualizerCanvas.tsx | 10 +- .../visualizers/TendrilsVisualizerCanvas.tsx | 11 +- .../visualizers/VisualizerBackdrop.tsx | 36 + .../src/components/visualizers/dissolveSim.ts | 295 ++ .../src/components/visualizers/glitchSim.ts | 311 ++ .../src/components/visualizers/moireSim.ts | 202 + .../components/visualizers/muonAudioBridge.ts | 98 + .../src/components/visualizers/spiralSim.ts | 193 + .../visualizers/visualizerSettings.ts | 453 +++ .../components/visualizers/visualizerTypes.ts | 89 +- frontend/src/hooks/useAlbumColor.ts | 64 + frontend/src/hooks/useAudioFeatures.ts | 20 +- frontend/src/hooks/useConvertStatus.ts | 139 +- frontend/src/hooks/useStemAudio.ts | 241 ++ frontend/src/pages/KaraokeTV.tsx | 19 +- frontend/src/pages/SearchPage.tsx | 584 ++- frontend/src/pages/Separator.tsx | 21 +- frontend/src/pages/Settings.tsx | 372 +- frontend/src/pages/TrackDetail.tsx | 875 +++- frontend/src/pages/VisualizerLabPage.tsx | 774 ++++ frontend/src/routes.ts | 1 + frontend/src/types.ts | 19 + frontend/src/utils/colorUtils.ts | 263 ++ frontend/src/utils/featureFlags.ts | 7 + frontend/src/utils/twoJsAccessors.ts | 79 + frontend/src/utils/waitForMediaReady.ts | 32 + frontend/tailwind.config.js | 9 + ...3bec21a7292f545789362d4b13728ef0aef656.png | Bin 29053 -> 0 bytes ...841ca1d7222aafa4ad39982545b078553e46f.json | 34 - ...a562f6ca735180a9c0d7405b5f4842949d5a14.png | Bin 30862 -> 0 bytes .../g1-host-prepare-ready.png | Bin 29053 -> 0 bytes .../g1-host-prepare-telemetry.json | 34 - .../g1-host-prepare-visible.png | Bin 30862 -> 0 bytes ...3bb9bd8dfc226c66cccd99086ee4863a79d078.png | Bin 23570 -> 0 bytes ...859f72e7235a1e7506413d50ab78bd57c7109.json | 18 - .../g1-guest-no-prepare.png | Bin 23570 -> 0 bytes .../g1-guest-prepare-telemetry.json | 18 - muon-iframe/Dockerfile | 51 + muon-iframe/PHASE2_SHADER_GUIDE.md | 422 ++ muon-iframe/README.md | 119 + muon-iframe/THIRD_PARTY_NOTICES.md | 25 + muon-iframe/fluid-render-graph.js | 1082 +++++ muon-iframe/nginx.conf | 17 + muon-iframe/overlayless.css | 50 + muon-iframe/spirit-render-graph.js | 254 ++ muon-iframe/stemengine-bootstrap.js | 96 + muon-iframe/stemengine-router.js | 293 ++ muon-iframe/tendrils-render-graph.js | 247 ++ 183 files changed, 32982 insertions(+), 4095 deletions(-) create mode 100644 .env.example create mode 100644 .github/workflows/muon-iframe-build-publish.yml create mode 100644 20260417_Phase2_1_Completion_Report.md create mode 100644 20260417_Phase2_Session_Summary.txt create mode 100644 Phase2_Architecture_And_Dependencies.md create mode 100644 Phase2_Initiation_Report.md create mode 100644 backend/routers/local_library.py create mode 100644 backend/services/local_library_service.py create mode 100644 backend/tests/test_local_library_config_source.py create mode 100644 backend/tests/test_local_library_security.py create mode 100644 backend/tests/test_subsonic_imports_search.py create mode 100644 docs/deployment/2026-04-16_Frontend_Deployment_Readiness.md create mode 100644 docs/evidence/frontend-ui-audit/2026-04-17-visualizer-root-causes/README.md create mode 100644 docs/evidence/frontend-ui-audit/2026-04-17-visualizer-runtime-deep-dive/README.md create mode 100644 docs/plans/2026-04-21_Copilot_Handoff/Audit_Fix_Plan.md create mode 100644 docs/plans/2026-04-21_Copilot_Handoff/Checklist.md create mode 100644 docs/plans/2026-04-21_Copilot_Handoff/README.md create mode 100644 docs/plans/2026-04-21_Copilot_Handoff/Reactivity_Plan.md rename docs/plans/{ => done}/frontend-ui-audit/2026-04-14_Frontend_UI_Audit.md (100%) rename docs/plans/{ => done}/frontend-ui-audit/2026-04-14_LyricsLivePreview_and_Visualizer_Audit.md (100%) rename docs/plans/{ => done}/frontend-ui-audit/2026-04-14_SingUI_Karaoke_Box_Gaps.md (100%) rename docs/plans/{ => done}/frontend-ui-audit/2026-04-14_Visualizer_Per_Stem_Reactivity_Design.md (100%) rename docs/plans/{ => done}/frontend-ui-audit/2026-04-15_BUG-VS-A_VS-B_VS-C_Implementation_Record.md (100%) rename docs/plans/{ => done}/frontend-ui-audit/2026-04-15_Frontend_UI_Audit_Issue_and_PR_Checklists.md (95%) rename docs/plans/{ => done}/frontend-ui-audit/2026-04-15_LyricsLivePreview_Visualizer_Regression_Investigation.md (100%) rename docs/plans/{ => done}/frontend-ui-audit/2026-04-15_Vite_HMR_Docker_Stale_Code.md (100%) rename docs/plans/{ => done}/gpu-resource-management/2026-04-16_Auto_Pipeline_Presets_Plan.md (100%) rename docs/plans/{ => done}/gpu-resource-management/2026-04-16_Execution_Log.md (100%) rename docs/plans/{ => done}/gpu-resource-management/2026-04-16_GPU_OOM_Root_Causes.md (100%) rename docs/plans/{ => done}/gpu-resource-management/2026-04-16_Hardware_Adaptive_Config_Plan.md (100%) rename docs/plans/{ => done}/gpu-resource-management/2026-04-16_Implementation_Checklist.md (86%) rename docs/plans/{ => done}/gpu-resource-management/2026-04-16_Plan_Review_Amendments.md (100%) rename docs/plans/{ => done}/gpu-resource-management/2026-04-16_Stem_Name_Consistency_Plan.md (100%) rename docs/plans/{ => done}/gpu-resource-management/benchmark_run_2026-04-16.json (100%) create mode 100644 docs/plans/done/local-music-library/2026-04-17_Local_Music_Library_Path_Plan.md rename docs/plans/{ => done}/singui-mobile-karaoke-box/2026-04-14_SingUI_Mobile_Karaoke_Box_Index.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/2026-04-14_SingUI_Mobile_Karaoke_Box_Issue_Bodies.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/2026-04-14_SingUI_Mobile_Karaoke_Box_Issue_Slices.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/2026-04-14_SingUI_Mobile_Karaoke_Box_Transformation_Checklist.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/2026-04-14_SingUI_Mobile_Karaoke_Box_Transformation_Plan.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/adr/ADR-001-ia-and-routing.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/adr/ADR-002-system-boundaries-and-transport.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/adr/ADR-003-queue-mutation-and-reconnect-contract.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/adr/ADR-004-security-and-permissions.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/adr/ADR-005-metrics-and-telemetry.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/adr/ADR-006-validation-gates.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/adr/ADR-007-rollout-and-kill-switch.md (100%) rename docs/plans/{ => done}/singui-mobile-karaoke-box/adr/ADR-INDEX.md (100%) create mode 100644 docs/plans/done/track-details/2026-04-16_Deployment_Log.md create mode 100644 docs/plans/done/track-details/2026-04-16_Deployment_Readiness_Checklist.md create mode 100644 docs/plans/done/track-details/2026-04-16_Final_Sign_Off.md create mode 100644 docs/plans/done/track-details/2026-04-16_Implementation_Complete_Summary.md create mode 100644 docs/plans/done/track-details/2026-04-16_Preset_Persistence_WorkLog.md create mode 100644 docs/plans/done/track-details/2026-04-16_QA_Report_and_Deployment_Decision.md create mode 100644 docs/plans/done/track-details/2026-04-16_Track_Details_Checklist.md create mode 100644 docs/plans/done/track-details/2026-04-16_Track_Details_Plan.md create mode 100644 docs/plans/done/track-details/Preparation_Request_Approval_Plan.md create mode 100644 docs/plans/done/track-details/README.md create mode 100644 docs/plans/done/uvr-borrowing/2026-04-16_UVR_Borrowing_Checklist.md create mode 100644 docs/plans/done/uvr-borrowing/2026-04-16_UVR_Borrowing_Plan.md create mode 100644 docs/plans/done/visualizer-hydra-replacement/2026-04-17_Plan.md create mode 100644 docs/plans/done/visualizer-lab-audit/2026-04-19_Checklist.md create mode 100644 docs/plans/done/visualizer-lab-audit/2026-04-19_Findings.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/2026-04-17_Checklist.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/2026-04-17_Plan.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/2026-04-17_Plan_Patched.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/20260417_Session_Completion_Summary.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/INSTRUCTIONS.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/P0C_Compliance_Signoff.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/PROJECT_STATUS_BOARD.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/Phase1_GateCheck_Execution_Report.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/Phase1_GateCheck_TestPlan.md create mode 100644 docs/plans/done/visualizer-muon-fluid-style/README.md create mode 100644 docs/plans/done/visualizer-muon-iframe/2026-04-17_Plan.md create mode 100644 docs/plans/done/visualizer-ui-audit/2026-04-20_Checklist.md create mode 100644 docs/plans/done/visualizer-ui-audit/2026-04-20_Findings.md delete mode 100644 docs/plans/track-details/2026-04-16_Track_Details_Plan.md create mode 100644 docs/plans/visualizer-audit-unified/2026-04-20_KaraokeTV_Visualizer_Audit.md create mode 100644 docs/plans/visualizer-audit-unified/2026-04-20_Streamlined_Checklist.md create mode 100644 docs/plans/visualizer-audit-unified/2026-04-20_Streamlined_Plan.md create mode 100644 docs/plans/visualizer-audit-unified/2026-04-20_Visualizer_Reactivity_Audit.md create mode 100644 docs/plans/visualizer-muon-debug/2026-04-20_Checklist.md create mode 100644 docs/plans/visualizer-muon-debug/2026-04-20_Findings.md create mode 100644 docs/plans/visualizer-reactivity-fix/2026-04-20_Checklist.md create mode 100644 docs/plans/visualizer-reactivity-fix/2026-04-20_Copilot_Worklist.md create mode 100644 docs/plans/visualizer-reactivity-fix/2026-04-20_Findings.md create mode 100644 docs/plans/visualizer-reactivity-fix/2026-04-20_LyricsLivePreview_Cleanup_Plan.md create mode 100644 docs/plans/visualizer-reactivity-fix/2026-04-21_Audit_Fix_Plan.md create mode 100644 docs/plans/visualizer-reactivity-fix/2026-04-21_Claude_Audit_Handoff_NewSchema.md create mode 100644 docs/plans/visualizer-reactivity-fix/2026-04-21_Claude_Audit_Results.md create mode 100644 docs/plans/visualizer-reactivity-fix/2026-04-21_Implementation_Plan.md create mode 100644 frontend/e2e/muon-preset-validation.spec.ts create mode 100644 frontend/e2e/track-detail-visualizer.spec.ts create mode 100644 frontend/src/components/ColorSwatch.tsx create mode 100644 frontend/src/components/LrcEditor.tsx create mode 100644 frontend/src/components/LyricsCanvas.tsx create mode 100644 frontend/src/components/LyricsStylePicker.tsx create mode 100644 frontend/src/components/LyricsTransportBar.tsx create mode 100644 frontend/src/components/LyricsViewport.tsx create mode 100644 frontend/src/components/StemMixerPanel.tsx create mode 100644 frontend/src/components/visualizers/DissolveVisualizerCanvas.tsx create mode 100644 frontend/src/components/visualizers/GlitchVisualizerCanvas.tsx create mode 100644 frontend/src/components/visualizers/MoireVisualizerCanvas.tsx create mode 100644 frontend/src/components/visualizers/SpiralVisualizerCanvas.tsx create mode 100644 frontend/src/components/visualizers/dissolveSim.ts create mode 100644 frontend/src/components/visualizers/glitchSim.ts create mode 100644 frontend/src/components/visualizers/moireSim.ts create mode 100644 frontend/src/components/visualizers/muonAudioBridge.ts create mode 100644 frontend/src/components/visualizers/spiralSim.ts create mode 100644 frontend/src/components/visualizers/visualizerSettings.ts create mode 100644 frontend/src/hooks/useAlbumColor.ts create mode 100644 frontend/src/hooks/useStemAudio.ts create mode 100644 frontend/src/pages/VisualizerLabPage.tsx create mode 100644 frontend/src/utils/colorUtils.ts create mode 100644 frontend/src/utils/twoJsAccessors.ts create mode 100644 frontend/src/utils/waitForMediaReady.ts delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-3774c-nd-karaoke-readiness-status-chromium/attachments/g1-host-prepare-ready-463bec21a7292f545789362d4b13728ef0aef656.png delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-3774c-nd-karaoke-readiness-status-chromium/attachments/g1-host-prepare-telemetry-336841ca1d7222aafa4ad39982545b078553e46f.json delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-3774c-nd-karaoke-readiness-status-chromium/attachments/g1-host-prepare-visible-30a562f6ca735180a9c0d7405b5f4842949d5a14.png delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-3774c-nd-karaoke-readiness-status-chromium/g1-host-prepare-ready.png delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-3774c-nd-karaoke-readiness-status-chromium/g1-host-prepare-telemetry.json delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-3774c-nd-karaoke-readiness-status-chromium/g1-host-prepare-visible.png delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-a5dc1-re-action-on-search-results-chromium/attachments/g1-guest-no-prepare-b73bb9bd8dfc226c66cccd99086ee4863a79d078.png delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-a5dc1-re-action-on-search-results-chromium/attachments/g1-guest-prepare-telemetry-3b6859f72e7235a1e7506413d50ab78bd57c7109.json delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-a5dc1-re-action-on-search-results-chromium/g1-guest-no-prepare.png delete mode 100644 frontend/test-results/singui-mobile-karaoke-Sear-a5dc1-re-action-on-search-results-chromium/g1-guest-prepare-telemetry.json create mode 100644 muon-iframe/Dockerfile create mode 100644 muon-iframe/PHASE2_SHADER_GUIDE.md create mode 100644 muon-iframe/README.md create mode 100644 muon-iframe/THIRD_PARTY_NOTICES.md create mode 100644 muon-iframe/fluid-render-graph.js create mode 100644 muon-iframe/nginx.conf create mode 100644 muon-iframe/overlayless.css create mode 100644 muon-iframe/spirit-render-graph.js create mode 100644 muon-iframe/stemengine-bootstrap.js create mode 100644 muon-iframe/stemengine-router.js create mode 100644 muon-iframe/tendrils-render-graph.js diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..3bd2b9b --- /dev/null +++ b/.env.example @@ -0,0 +1,16 @@ +# StemEngine example environment variables +# Copy to .env and adjust for your deployment. + +# Muon iframe source URL consumed by frontend/backend settings fallback. +MUON_IFRAME_URL=http://localhost:3011 + +# Pinned Muon fork commit/tag/branch used by muon-iframe build context. +# Examples: main, v0.1.0, 1a2b3c4d +MUON_GIT_REF=main + +# Origin allowlist that the Muon iframe will accept postMessage commands from. +# Supports comma-separated values. +# Examples: +# Dev only: http://localhost:5173,http://localhost:3001 +# Dev + Tailscale: http://localhost:5173,https://stemengine-node.tailnet.ts.net +STEMENGINE_ALLOWED_ORIGIN=http://localhost:5173,http://localhost:3001 diff --git a/.github/workflows/muon-iframe-build-publish.yml b/.github/workflows/muon-iframe-build-publish.yml new file mode 100644 index 0000000..57c5b30 --- /dev/null +++ b/.github/workflows/muon-iframe-build-publish.yml @@ -0,0 +1,100 @@ +name: muon-iframe-build-publish + +on: + workflow_dispatch: + inputs: + muon_git_ref: + description: "Upstream Muon ref (branch/tag/commit) used as Docker build arg" + required: true + default: "main" + stemengine_allowed_origin: + description: "Comma-separated frontend origin allowlist for Muon postMessage" + required: true + default: "http://localhost:5174,http://localhost:3001" + push_image: + description: "Push image to GHCR" + required: true + type: boolean + default: true + push: + tags: + - "muon-iframe-v*" + +permissions: + contents: read + packages: write + +jobs: + build-and-publish: + runs-on: ubuntu-latest + env: + IMAGE_NAME: ghcr.io/${{ github.repository_owner }}/stemengine-muon + MUON_GIT_REF: ${{ inputs.muon_git_ref || 'main' }} + STEMENGINE_ALLOWED_ORIGIN: ${{ inputs.stemengine_allowed_origin || 'http://localhost:5174,http://localhost:3001' }} + + steps: + - name: Checkout + uses: actions/checkout@v4 + + - name: Set up QEMU + uses: docker/setup-qemu-action@v3 + + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@v3 + + - name: Log in to GHCR + if: ${{ inputs.push_image != false || startsWith(github.ref, 'refs/tags/muon-iframe-v') }} + uses: docker/login-action@v3 + with: + registry: ghcr.io + username: ${{ github.actor }} + password: ${{ secrets.GITHUB_TOKEN }} + + - name: Docker metadata + id: meta + uses: docker/metadata-action@v5 + with: + images: ${{ env.IMAGE_NAME }} + tags: | + type=raw,value=latest + type=raw,value=${{ env.MUON_GIT_REF }} + type=sha + type=ref,event=tag + + - name: Build and optionally push image + uses: docker/build-push-action@v6 + with: + context: ./muon-iframe + file: ./muon-iframe/Dockerfile + push: ${{ inputs.push_image != false || startsWith(github.ref, 'refs/tags/muon-iframe-v') }} + tags: ${{ steps.meta.outputs.tags }} + labels: ${{ steps.meta.outputs.labels }} + build-args: | + MUON_GIT_REF=${{ env.MUON_GIT_REF }} + STEMENGINE_ALLOWED_ORIGIN=${{ env.STEMENGINE_ALLOWED_ORIGIN }} + + - name: Placeholder substitution gate + run: | + set -euo pipefail + docker build \ + --build-arg MUON_GIT_REF="${MUON_GIT_REF}" \ + --build-arg STEMENGINE_ALLOWED_ORIGIN="${STEMENGINE_ALLOWED_ORIGIN}" \ + -t stemengine-muon-ci-verify \ + ./muon-iframe + + if docker run --rm stemengine-muon-ci-verify sh -lc "grep -R -n '__STEMENGINE_ALLOWED_ORIGIN__' /usr/share/nginx/html"; then + echo "PLACEHOLDER NOT SUBSTITUTED" + exit 1 + fi + + - name: Summary + run: | + { + echo "## Muon iframe build" + echo "" + echo "- Image: \\`${IMAGE_NAME}\\`" + echo "- MUON_GIT_REF: \\`${MUON_GIT_REF}\\`" + echo "- STEMENGINE_ALLOWED_ORIGIN: \\`${STEMENGINE_ALLOWED_ORIGIN}\\`" + echo "- Trigger: \\`${GITHUB_EVENT_NAME}\\`" + echo "- Ref: \\`${GITHUB_REF}\\`" + } >> "$GITHUB_STEP_SUMMARY" diff --git a/20260313_Fixes (Copilot).md b/20260313_Fixes (Copilot).md index eea805f..993ee80 100644 --- a/20260313_Fixes (Copilot).md +++ b/20260313_Fixes (Copilot).md @@ -1,5 +1,85 @@ # 2026-03-13 Backend Fixes / Improvement Plan (Copilot) +## 2026-04-17 Work Log — Muon Fluid/Tendrils/Spirit Visualizer Phase 0-1 + +**Status**: ✅ **Phase 0 functionally complete (95%)** | ✅ **Phase 1 scaffolding complete (100%)** + +Completed all prerequisites and fork scaffolding for Muon visualizer fork integration. + +### Phase 0 Completion (2026-04-15 to 2026-04-17) + +**P0-B: Security hardening** [2026-04-15] +- CSP header generation: `frame-src` derived from `MUON_IFRAME_URL` env var +- iframe attributes: `sandbox="allow-scripts allow-same-origin"`, `referrerpolicy="no-referrer"` +- postMessage origin check: rejects third-party origins (muon-vis.netlify.app) + +**P0-C: Licensing inventory + compliance** [2026-04-16 to 2026-04-17] +- Verified all three upstream libraries are MIT-licensed +- Created `THIRD_PARTY_NOTICES.md` with commit hashes and usage scope +- Created formal `P0C_Compliance_Signoff.md` — **APPROVED FOR PHASE 2/4 RENDERING WORK** + +**P0-D: WebGL capability baseline** [2026-04-16] +- `stemengine-bootstrap.js`: startup extension checks for `OES_texture_float_linear`, `EXT_color_buffer_float` +- Context lifecycle hooks: `webglcontextlost`/`webglcontextrestored` recovery strategy + +**P0-A: Fork hosting + CI** [2026-04-15 to 2026-04-16] +- `.github/workflows/muon-iframe-build-publish.yml` created (build → GHCR publish) +- Build args: `MUON_GIT_REF` config in compose, CI workflow, release documentation +- Status: 3/4 complete (fork itself blocked on external action) + +### Phase 1 Completion (2026-04-17) + +**1.1: Style router** [Complete] +- Query param reader: `?style=fluid|tendrils|spirit|default` +- Router dispatcher: sets `window.__STEMENGINE_MUON_STYLE__` +- Injected via `stemengine-router.js` overlay at build time + +**1.2: postMessage command contract** [Complete] +- Origin guard: `STEMENGINE_ALLOWED_ORIGIN` build-arg derived token +- Schema validation: version/type/payload structure +- Numeric clamping: all values bounded before state update +- RAF rate-limit: `pushAudioFeatures` gated to one-per-RAF +- Events: `ready` on load, `error` callback exported + +**1.3: Audio feature bridge policy** [Complete] +- Decision: **host push** (leverage existing `MuonFeatureExtractor`) +- Rate-limiting: dual-RAF (host send + iframe consume) +- Documented in README + +**1.4: Host-side wiring** [Complete] +- `setStyle` on preferredMode change +- `setQuality` on quality setting (new `muon_quality` backend setting) +- `setViewport` debounced 100 ms on resize +- Full-state rehydrate on iframe `ready` event +- `visibilitychange` → `setPaused` (no fork change required) + +### Code changes summary + +- **New files**: `stemengine-router.js` (180 lines overlay), 3 docs (compliance + test plan + summary) +- **Modified files**: 7 (backend security + settings, frontend wiring + types, compose config, dockerfile, env example, README, checklist) +- **Validation**: ✅ Typecheck clean, ✅ Python compile clean, ✅ CSP injection functional + +### Artifacts created + +1. `P0C_Compliance_Signoff.md` — Compliance approval for Phase 2/4 +2. `Phase1_GateCheck_TestPlan.md` — Test strategy + blocker analysis +3. `20260417_Session_Completion_Summary.md` — Detailed session scorecard + +### Phase 1 Gate Check Status + +- 3/6 items testable now (ready event, origin check, regressions, typecheck) +- 3/6 items blocked on fork + Phase 2 (style router stubs, setPaused render pause) +- Comprehensive test plan available for immediate execution + +### Blockers and next steps + +**External action required**: Fork `najafmohammed/muon-music-visualizer` to StemEngine GitHub org +- Once forked: `MUON_GIT_REF` can point to fork, Phase 1.1 stubs can be committed, Phase 2 rendering begins + +**Recommended next**: Execute unblocked gate checks (1.2, 1.4, 1.5, 1.6) for ~60 min validation run + +--- + ## 2026-04-15 Work Log — SingUI Milestone G (continuation) Status update for current implementation stream (mobile karaoke box gaps). @@ -11166,3 +11246,702 @@ Validation: - output includes `SearchPage-BI9ziDal.js` - output includes `useConvertStatus-C_bVvWyE.js` +### 2026-04-16 Follow-up Fix — Track Details PR-1 Core Implementation + +Reviewed new planning docs under `docs/plans/track-details/` and implemented the core Track Details upgrade from that plan/checklist. + +Implemented: + +- `frontend/package.json` + - added `fast-average-color@^9.5.0` +- `frontend/src/hooks/useAlbumColor.ts` + - new dominant-color extraction hook with near-white / near-black rejection +- `frontend/tailwind.config.js` + - added `fadeInPage` keyframe + animation +- `frontend/src/pages/TrackDetail.tsx` + - dynamic background (`color` / `image` mode) persisted in `localStorage` + - Feishin-style hero layout with 250×250 cover art and dynamic title sizing + - visualizer moved below hero with mode pills + - 30-second looping preview player + - karaoke readiness card with Quick / Pro / Rich preset selection + - ready-state project link and stem chips + - existing video-link editor retained +- `frontend/src/components/singui/SongPreviewSheet.tsx` + - added `View track details →` router-state deep link +- `frontend/src/utils/featureFlags.ts` + - added `KARAOKE_TRACK_DETAILS_ENHANCED` (off by default for future TD-5 / TD-6) + +Documentation updated: + +- `docs/plans/track-details/2026-04-16_Track_Details_Checklist.md` + - marked shipped PR-1 tasks complete + - recorded deviations and validation notes +- `docs/plans/gpu-resource-management/2026-04-16_Implementation_Checklist.md` + - added R6 tracker row/status note pointing to dedicated track-details docs +- `SUMMARIES (Claude).md` + - added Track Details implementation summary + +Known deviation: + +- ready-state stem chips currently derive from `getProjectDetail().sep_job.files` because the lightweight project summary does not expose a normalized `stems` map yet +- SEK file size is not displayed because the current frontend API payload does not provide it + +Validation: + +- `get_errors` clean for touched Track Details files +- `npm run build` ✅ + - output includes `TrackDetail-CVakaceC.js` + +### 2026-04-16 Follow-up Fix — Track Details PR-2 Enhanced Content Pass + +Implemented the next Track Details pass behind `KARAOKE_TRACK_DETAILS_ENHANCED`. + +Implemented: + +- `backend/routers/projects.py` +- `backend/services/project_assets_service.py` + - added `GET /api/projects/{projectId}/lyrics` and a project lyrics-preview helper + - preview prefers the primary `.elrc` track when present, then falls back to the best available project lyrics file +- `backend/routers/subsonic.py` +- `backend/services/subsonic_service.py` + - added `GET /api/subsonic/songs/{songId}/similar?count=5` +- `frontend/src/api/client.ts` +- `frontend/src/types.ts` + - added client helpers/types for project lyrics preview and similar songs +- `frontend/src/pages/TrackDetail.tsx` + - feature-gated lyrics snippet panel with `Full lyrics in Project →` + - feature-gated similar-track cards with cover art, router-state links, and live readiness badges + - extended `useConvertStatus(...)` input to include similar songs so readiness pills stay in sync + - added `Last prepared …` processing-history line below the readiness card + +Documentation updated: + +- `docs/plans/track-details/2026-04-16_Track_Details_Checklist.md` + - marked TD-5 / TD-6 / TD-7 complete + - added implementation notes and validation evidence +- `SUMMARIES (Claude).md` + - added Track Details PR-2 summary + +Known limitation: + +- preset name is still not stored on the project payload, so the processing-history line currently renders relative date only + +Validation: + +- `get_errors` clean for touched frontend/backend files +- `python3 -m py_compile` ✅ +- `frontend`: `npm run -s build:local` ✅ + +### 2026-04-17 — Muon iframe quick-win hardening pass + +Additional implementation landed: + +- `frontend/src/components/VisualizerPreviewWidget.tsx` + - tightened iframe sandbox to `allow-scripts allow-same-origin` and kept `referrerPolicy="no-referrer"`. + - added `visibilitychange` host postMessage (`setPaused`) wiring for Muon iframe lifecycle pause/resume behavior. + - added `?preset=default` passthrough to Muon iframe URL when absent. + - prevented control postMessage target origin from using third-party `muon-vis.netlify.app`. + +- `.env.example` + - added `MUON_GIT_REF` (and `MUON_IFRAME_URL`) sample variables for pinned Muon build references. + +- `muon-iframe/THIRD_PARTY_NOTICES.md` + - added licensing/provenance scaffold entries for Muon upstream, WebGL Fluid Simulation, and The Spirit. + +- `docs/plans/visualizer-muon-fluid-style/2026-04-17_Checklist.md` + - marked completed quick wins and completed P0-B iframe attribute/typecheck checklist items with evidence from this pass. + +Validation: +- `frontend`: `npm run -s typecheck` ✅ +- `frontend`: `npm run -s build:local` ✅ + +### 2026-04-20 (continuation) — Muon debug checklist evidence sync + +Additional documentation/evidence updates landed: + +- `docs/plans/visualizer-muon-debug/2026-04-20_Checklist.md` + - marked Phase 1.4 backend settings verification complete (`/api/settings` returns `muon_iframe_url`). + - marked Phase 1 validation item complete for running/reachable Muon service (`http://localhost:3011`). + - marked Phase 5 item complete for TrackDetail muon iframe style-cycle validation based on passing focused E2E. + +- `20260313_Fixes (Copilot).md` + - appended this continuation block to keep command evidence and checklist status in sync. + +Validation (today continuation): +- `backend`: `curl -sf http://localhost:8000/api/settings | grep -i "muon"` ✅ (`muon_iframe_url` confirmed) +- `docker`: `docker ps --format '{{.Names}}\t{{.Status}}\t{{.Ports}}' | grep stemengine-muon` ✅ (container up, host `3011->80`) +- `docker`: `curl -sI http://localhost:3011 | head -n 1` ✅ (`HTTP/1.1 200 OK`) +- `frontend`: `VITE_UI_FLAVOR=sing npx playwright test e2e/track-detail-visualizer.spec.ts --config playwright.sing.config.ts` ✅ (3/3) +- `frontend`: `VITE_UI_FLAVOR=sing npx playwright test e2e/muon-preset-validation.spec.ts --config playwright.sing.config.ts` ✅ (1/1) + +Current remaining items are manual/browser-origin checks only (DevTools console verification + remote Tailscale style-switch cycle). + +### 2026-04-20 (continuation) — Karaoke TV visualizer audit/fix (`/karaoke/tv`) + +Issue reported: + +- `http://work:3001/karaoke/tv` was not using the correct visualizer path for non-video playback and could fall back to legacy mode behavior. + +Audit documentation: + +- `docs/plans/visualizer-audit-unified/2026-04-20_KaraokeTV_Visualizer_Audit.md` + - captured findings, root causes, fixes, and validation targets. + +Code fixes landed: + +- `frontend/src/pages/KaraokeTV.tsx` + - replaced non-video TV default from legacy `muon` to canonical `muon_iframe`. + - added route-level visualizer-mode normalizer (legacy `muon|fluid|tendrils|spirit` → `muon_iframe`; canonical modes pass through). + +- `frontend/src/components/LyricsLivePreview.tsx` + - added `asKaraokeVisualizerStyle(...)` resolver to preserve `muon_iframe` and normalize legacy values to iframe runtime. + - switched initial/default/enforced visualizer resolution to use the normalized karaoke resolver. + +- `frontend/src/components/KaraokePerformanceMode.tsx` + - widened `defaultStyle` prop typing to include canonical visualizer values including `muon_iframe`. + +- `frontend/src/api/client.ts` + - updated `SekManifestResponse.manifest.visualizer.mode` union to include canonical + legacy + `auto`. + - aligned `visualizer.settings` typing with shared `VisualizerSettings`. + +Validation: + +- `frontend`: `npm run -s typecheck` ✅ + +### 2026-04-20 — Muon debug hardening pass (origin allowlist + lifecycle + CI gate) + +Additional implementation landed: + +- `muon-iframe/stemengine-router.js` + - added comma-separated origin allowlist parsing (`STEMENGINE_ALLOWED_ORIGIN`) with wildcard handling and strict startup fatal log when placeholder substitution is missing. + - added robust version guard (`Number(msg.version) !== 1`) and canonical viewport payload support (`cssWidth/cssHeight/dpr` with computed pixel dims). + - added explicit default-style resume behavior and stop-hook invocation before non-default render graph activation. + - passed captured canvas/context/viewport/quality into render graph constructors. + +- `muon-iframe/stemengine-bootstrap.js` + - added early `getContext` interception to capture the connected Muon canvas and active WebGL context. + - added default no-op `window.__STEMENGINE_MUON_STOP_FN__` / `window.__STEMENGINE_MUON_RESUME_FN__` hooks. + +- `muon-iframe/fluid-render-graph.js`, `muon-iframe/tendrils-render-graph.js`, `muon-iframe/spirit-render-graph.js` + - updated constructors to accept reused Muon canvas/context parameters. + - fixed fluid capability checks to use resolved `this.gl` context. + +- `muon-iframe/Dockerfile` + - replaced ambiguous repeated import insertion with deterministic ordered injection: bootstrap → router → fluid → tendrils → spirit. + +- `frontend/src/components/VisualizerPreviewWidget.tsx`, `frontend/src/pages/VisualizerLabPage.tsx` + - added iframe `onLoad` rehydration (`rehydrateMuonState`) to remove post-reload command race. + - added strict host-side origin checks for incoming iframe messages. + - aligned lab-page target-origin guard with widget behavior (rejects third-party netlify origin). + +- `.env`, `.env.example`, `/home/translator/docker/stemengine.yml` + - documented/propagated Muon URL + comma-separated local/Tailscale-capable origin allowlist configuration. + +- `.github/workflows/muon-iframe-build-publish.yml` + - added `stemengine_allowed_origin` workflow input. + - passed `STEMENGINE_ALLOWED_ORIGIN` as Docker build arg in publish build. + - added placeholder-substitution CI gate that fails if `__STEMENGINE_ALLOWED_ORIGIN__` is present in built assets. + +- `docs/plans/visualizer-muon-debug/2026-04-20_Checklist.md` + - updated implementation status to reflect completed code work and completed automated validations. + +Validation: +- `frontend`: `npm run -s typecheck` ✅ +- `frontend`: `npx playwright test e2e/track-detail-visualizer.spec.ts --config playwright.sing.config.ts --grep "Preview widget style tabs update style selection when mode is muon_iframe|style switches persist while hidden and restore after visibilitychange|ready event carries capability payload"` ✅ (4/4) +- `frontend`: `npx playwright test e2e/singui-mobile-karaoke.spec.ts --config playwright.sing.config.ts --grep "Search-to-enqueue"` ✅ (14/14) +- `docker`: `docker compose -f /home/translator/docker/stemengine.yml build stemengine-muon` ✅ +- `docker`: placeholder token verification inside built image (`grep -R -n '__STEMENGINE_ALLOWED_ORIGIN__' /usr/share/nginx/html`) ✅ no matches +- `backend`: `curl -sf http://localhost:8000/api/settings | grep -i muon` ✅ (`muon_iframe_url` present) +- `docker`: `docker ps ... | grep stemengine-muon` + `curl -sI http://localhost:3011` ✅ (service running, HTTP 200) +- `frontend`: `VITE_UI_FLAVOR=sing npx playwright test e2e/track-detail-visualizer.spec.ts --config playwright.sing.config.ts` ✅ (3/3) +- `frontend`: `VITE_UI_FLAVOR=sing npx playwright test e2e/muon-preset-validation.spec.ts --config playwright.sing.config.ts` ✅ (1/1) + +### 2026-04-20 follow-up — Muon style-switching hardening pass (host + iframe) + +Implemented core fixes from `docs/plans/visualizer-muon-debug/2026-04-20_Checklist.md`. + +#### Iframe-side (`muon-iframe`) + +- `muon-iframe/stemengine-router.js` + - added startup fatal assertion when `__STEMENGINE_ALLOWED_ORIGIN__` placeholder is not substituted. + - upgraded origin guard to support comma-separated allowlists (still supports `*` and single origin). + - added safe parent message helper for ready/error emission under allowlist mode. + - updated viewport command handling to accept canonical payload (`cssWidth`, `cssHeight`, `dpr`) while preserving `width`/`height` compatibility. + - changed command schema check to `Number(msg.version) !== 1`. + - added explicit `'default'` style branch and stop/resume hook integration. + - wired render-graph constructor calls to pass captured canvas/context and viewport/quality where supported. + +- `muon-iframe/stemengine-bootstrap.js` + - added `getContext` capture hook to retain Muon-owned canvas/context for reuse by style graphs. + - limited capture to connected canvases to avoid detached probe-canvas capture during baseline checks. + - exposed default no-op stop/resume hooks for router compatibility (`__STEMENGINE_MUON_STOP_FN__`, `__STEMENGINE_MUON_RESUME_FN__`). + +- `muon-iframe/fluid-render-graph.js` + - fixed capabilities detection to use resolved context (`this.gl`) instead of optional constructor arg. + +- `muon-iframe/tendrils-render-graph.js` + - updated constructor to accept optional `(canvas, gl, width, height, quality)` inputs from router. + +- `muon-iframe/spirit-render-graph.js` + - updated constructor to accept optional `(canvas, gl, width, height, quality)` inputs from router. + +- `muon-iframe/Dockerfile` + - replaced reversed multiple `sed '1i'` injections with one deterministic ordered import block: + bootstrap → router → fluid → tendrils → spirit. + +#### Host-side (`frontend`) + +- `frontend/src/components/VisualizerPreviewWidget.tsx` + - removed dead legacy-mode branches in `muonStyleFromPreferredMode()` and documented style source of truth. + - guarded listener-side eager rehydrate so it runs only in `muon_iframe` mode. + - added guaranteed `rehydrateMuonState()` on iframe `onLoad`. + +- `frontend/src/pages/VisualizerLabPage.tsx` + - aligned target-origin logic with widget guard (`muon-vis.netlify.app` is command-disabled). + - added guaranteed `rehydrateMuonState()` on iframe `onLoad`. + +#### Environment/config alignment + +- `.env` + - added explicit `MUON_IFRAME_URL` and `STEMENGINE_ALLOWED_ORIGIN` defaults. + +- `.env.example` + - documented comma-separated allowlist usage for local + Tailscale frontend origins. + +- `/home/translator/docker/stemengine.yml` + - clarified Muon build-arg comment to reflect allowlist semantics (including Tailscale usage). + +#### Validation snapshot + +- `frontend`: `npm run -s typecheck` ✅ +- `frontend`: `VITE_UI_FLAVOR=sing npx playwright test e2e/track-detail-visualizer.spec.ts e2e/muon-preset-validation.spec.ts --reporter=line` ✅ (`4 passed`) +- `frontend`: `VITE_UI_FLAVOR=sing npx playwright test e2e/singui-mobile-karaoke.spec.ts --grep "Search-to-enqueue flow" --reporter=line` ✅ (`14 passed`) + +### 2026-04-17 — Muon Phase 5 closeout (preset validation + release gate) + +Additional implementation landed: + +- `frontend/e2e/muon-preset-validation.spec.ts` + - added a dedicated 10-track Muon style/preset/quality stability validation suite for track-detail route coverage. + - included deterministic API mocks and iframe harness routing so preset/state controls can be validated across repeated navigation. + +- `frontend/e2e/track-detail-visualizer.spec.ts` + - removed a sparse/null mocked project entry in the test fixture array that caused intermittent validation-track render failures. + - added heading readiness assertion in the 10-track artifact loop to stabilize page-load sequencing. + +- `docs/plans/visualizer-muon-fluid-style/2026-04-17_Checklist.md` + - marked Phase 5.3 promotion items complete (`candidate` + `approved`). + - marked Phase 5.4 release-gate items complete. + +- `docs/plans/visualizer-muon-fluid-style/2026-04-17_Plan_Patched.md` + - checked all acceptance criteria entries for Phase 5 release closure. + +- `SUMMARIES (Claude).md` + - added Phase 5 closeout summary with validation evidence and final status. + +Validation: +- `frontend`: `VITE_UI_FLAVOR=sing npx playwright test e2e/track-detail-visualizer.spec.ts e2e/muon-preset-validation.spec.ts --project=chromium` ✅ (4/4) + +### 2026-04-17 — Track Detail preview button accessibility fix (E2E unblock) + +Additional implementation landed: + +- `frontend/src/pages/TrackDetail.tsx` + - added explicit `aria-label`/`title` on the 30s preview play/pause icon button (`Play preview` / `Pause preview`). + - this restores a stable accessible selector for Playwright and improves keyboard/screen-reader discoverability. + +Validation: +- `frontend`: `npm run -s typecheck` ✅ +- `frontend`: `npm run -s build:local` ✅ + +### 2026-04-17 — Muon Phase 3/4 render graphs + Phase 5 host wiring pass + +Additional implementation landed: + +- `muon-iframe/tendrils-render-graph.js` + - added Tendrils render graph overlay with flow/trail feedback pipeline, audio-reactive force/jitter/brightness mapping, quality-tier render scaling, and RAF lifecycle (`start`/`stop`/`dispose`). + +- `muon-iframe/spirit-render-graph.js` + - added Spirit render graph overlay with atmospheric accumulation/glow pipeline, audio-reactive drift/shimmer/pulse mapping, quality-tier scaling, and lifecycle controls. + +- `muon-iframe/Dockerfile` + - added injection/import steps for `tendrils-render-graph.js` and `spirit-render-graph.js` alongside fluid/router/bootstrap overlays. + +- `frontend/src/components/visualizers/visualizerTypes.ts` + - added `muon_iframe` settings schema (`style`, `preset`, `quality`) to `VisualizerSettings`. + +- `backend/services/project_assets_service.py` + - extended `_normalize_visualizer_config` to include `muon_iframe` sub-settings and allow `muon_iframe` mode in normalization. + +- `frontend/src/components/VisualizerPreviewWidget.tsx` + - added Muon iframe style tabs (`default`, `fluid`, `tendrils`, `spirit`) and preset/quality controls. + - wired `setStyle`, `setPreset`, `setQuality`, `setPaused`, `setViewport` command flow with full-state rehydrate on iframe `ready`. + - added explicit lifecycle pause/resume hooks for iframe mode transitions. + +- `frontend/src/pages/VisualizerLabPage.tsx` + - added iframe-side style/preset controls and command dispatch bridge (`setStyle`, `setPreset`, `setQuality`, `setViewport`, `setPaused`) for Muon mode. + +- `docs/plans/visualizer-muon-fluid-style/2026-04-17_Checklist.md` + - marked Phase 3.1/3.2, Phase 4.1/4.2, Phase 5.1/5.2 as completed from code + validation evidence. + - recorded 9 draft preset identifiers under Phase 5.3. + +Validation: +- `frontend`: `npm run -s typecheck` ✅ +- `frontend`: `npm run -s build:local` ✅ +- `frontend`: `VITE_UI_FLAVOR=sing npx playwright test e2e/track-detail-visualizer.spec.ts --project=chromium` ✅ (2/2) +- `backend`: `python3 -m compileall backend/services/project_assets_service.py` ✅ +- `muon-iframe`: `node --check stemengine-router.js && node --check fluid-render-graph.js && node --check tendrils-render-graph.js && node --check spirit-render-graph.js` ✅ +- `docker`: `docker compose -f stemengine.yml build stemengine-muon` ✅ + +### 2026-04-17 — Muon startup WebGL baseline check injection + +Additional implementation landed: + +- `muon-iframe/stemengine-bootstrap.js` + - added startup WebGL baseline checks for required extensions (`OES_texture_float_linear`, `EXT_color_buffer_float`) with explicit console warnings when missing. + - added canvas lifecycle hooks for `webglcontextlost` / `webglcontextrestored` logging and state flags. + +- `muon-iframe/Dockerfile` + - now injects `stemengine-bootstrap.js` into cloned Muon source at build time. + - patches Muon `src/index.js` import once so baseline checks run at app startup. + +- `docs/plans/visualizer-muon-fluid-style/2026-04-17_Checklist.md` + - marked P0-D startup extension-check item complete. + +Validation: +- `frontend`: `npm run -s typecheck` ✅ +- `frontend`: `npm run -s build:local` ✅ + +### 2026-04-17 — Muon CI/release pipeline scaffolding (Phase 0-A) + +Additional implementation landed: + +- `.github/workflows/muon-iframe-build-publish.yml` + - added a dedicated workflow to build/publish the self-hosted Muon iframe image with configurable `MUON_GIT_REF`. + - supports manual dispatch and tag-triggered release (`muon-iframe-v*`) with GHCR publish flow. + +- `muon-iframe/README.md` + - added documented build/release/rollback process for pinned Muon refs. + - linked compose build-arg usage and CI workflow entrypoint for deterministic image builds. + +- `docs/plans/visualizer-muon-fluid-style/2026-04-17_Checklist.md` + - marked P0-A subitems complete for `MUON_GIT_REF` build config, CI job creation, and documented release process. + +Validation: +- `frontend`: `npm run -s typecheck` ✅ +- `frontend`: `npm run -s build:local` ✅ + +### 2026-04-17 — Muon iframe CSP and self-hosted default alignment + +Additional implementation landed: + +- `backend/main.py` + - added a `frame-src` Content-Security-Policy header for HTML responses, derived from `MUON_IFRAME_URL` origin plus `'self'`. + - this closes the checklist requirement to constrain iframe sources to StemEngine-owned origin(s) for backend-served SPA HTML. + +- `frontend/src/components/VisualizerPreviewWidget.tsx` + - changed default Muon iframe URL fallback from third-party Netlify to self-hosted `http://localhost:3011`. + +- `frontend/src/pages/VisualizerLabPage.tsx` + - changed default Muon iframe URL fallback to `http://localhost:3011`. + - tightened iframe sandbox to `allow-scripts allow-same-origin` (removed `allow-downloads`) to match security baseline. + +- `frontend/src/pages/Settings.tsx` + - updated Muon iframe URL placeholder to `http://localhost:3011` to align UX with self-hosted default. + +- `docs/plans/visualizer-muon-fluid-style/2026-04-17_Checklist.md` + - marked remaining P0-B security items complete (`frame-src` CSP allowlist and no third-party command allowlist target). + +Validation: +- `backend`: `python3 -m compileall backend/main.py` ✅ +- `frontend`: `npm run -s typecheck` ✅ +- `frontend`: `npm run -s build:local` ✅ + +### 2026-04-17 — Phase 0 licensing and WebGL baseline documentation pass + +Additional implementation landed: + +- `muon-iframe/THIRD_PARTY_NOTICES.md` + - replaced TODO placeholders with pinned upstream commit hashes and verified license file references for Muon upstream, WebGL Fluid Simulation, and The Spirit. + +- `muon-iframe/README.md` + - added Phase 0 runtime baseline notes: required WebGL extensions, fallback behavior, and `webglcontextlost` / `webglcontextrestored` recovery strategy. + +- `docs/plans/visualizer-muon-fluid-style/2026-04-17_Checklist.md` + - marked completed P0-C license verification tasks. + - marked completed P0-D documentation/fallback/recovery strategy tasks. + +Validation: +- `frontend`: `npm run -s typecheck` ✅ +- `frontend`: `npm run -s build:local` ✅ + + +--- + +### 2026-04-20 — Visualizer reactivity bridge (Blocks 2–4) + LyricsLivePreview cleanup plan + +**Audit pre-work (pre-patch):** +- Identified `beat` field name mismatch: `AudioFeatures.beatDetected` ≠ iframe contract `.beat` — explicit mapping required in bridge. +- Confirmed `featuresRef`/`sendMuonCommand`/`isPlaying` present in all three integration files. +- Confirmed `emitReady` target at `stemengine-router.js` lines 238–252. +- Confirmed canvas visualizer dep arrays at line 124 in all four canvas files. + +**New file:** +- `frontend/src/components/visualizers/muonAudioBridge.ts` + - `createAudioPushLoop(sendCommand, featuresRef)` — RAF-driven host→iframe audio bridge. + - Visibility guard, silence gate (4-frame threshold at rms < 0.001), `beatDetected→beat` mapping. + +**Block 2 — pushAudioFeatures bridge:** +- `VisualizerPreviewWidget.tsx` — added bridge `useEffect` gated on `mode === 'muon_iframe' && isPlaying`. +- `VisualizerLabPage.tsx` — same pattern. +- `LyricsLivePreview.tsx` — same pattern gated on `isIframeVisualizerMode && isPlaying`. +- `muon-iframe/stemengine-router.js` — added `audioMode: 'host-push'` to `emitReady` capabilities payload. + +**Block 3 — AudioContext reliability:** +- `LyricsLivePreview.tsx` `getCtx()` — added `void ctx.resume().catch(() => {})` immediately after `new AudioContext()`. +- `hooks/useAudioFeatures.ts` — added `ctx.state !== 'running'` guard: zero features + DEV warning when AudioContext suspended during playback. + +**Block 4 — Native mode and hook correctness:** +- `MoireVisualizerCanvas.tsx`, `DissolveVisualizerCanvas.tsx`, `GlitchVisualizerCanvas.tsx`, `SpiralVisualizerCanvas.tsx` — removed `featuresRef` and `paletteRef` from `useEffect` dep arrays (stable mutable refs, read inside RAF loop). +- `hooks/useAudioFeatures.ts` — added `wasPlayingRef` to zero `featuresRef` exactly once on pause→play transition instead of every silent frame. `bandPeaks` preserved. +- `LyricsLivePreview.tsx` — changed `useAudioFeatures` `enabled` from `isVisualizerMode` to `isPlaying`. +- `VisualizerLabPage.tsx` — replaced render-time `featuresRef.current` snapshot with `useState` + `setInterval` at 10 Hz for live stats panel. + +**Cleanup plan:** +- `docs/plans/visualizer-reactivity-fix/2026-04-20_LyricsLivePreview_Cleanup_Plan.md` + - 23 findings (C-1–C-23) across Architecture, Complexity, Hook misuse, Performance, Duplicate logic, Type safety, Maintainability, Dead code. + - Extraction map: 11 proposed new files. + - Ordered work sequence with dependency graph. + +Validation: +- `frontend`: `npm run -s typecheck` ✅ + + +--- + +### 2026-04-21 — Visualizer reactivity: Blocks 3.3, 5.3, and 2.5 Docker rebuild + +**Blocks completed this session:** 3.3 (autoplay gesture overlay), 5.3 (stem `createMediaElementSource` error handling), 2.5 Docker image rebuild. + +--- + +#### Block 3.3 — Autoplay gate + "Tap to begin" overlay + +**File:** `frontend/src/components/LyricsLivePreview.tsx` + +- Added `const [awaitingGesture, setAwaitingGesture] = useState(false)` alongside `videoStartPhase`. +- Added `import { reportNonFatal } from '../utils/nonFatal'`. +- **Multi-stem play branch:** replaced fire-and-forget `audios.forEach(a => a.play().catch())` with: + ```ts + try { await ctx.resume() } catch { setAwaitingGesture(true); return } + const playResults = await Promise.allSettled(audios.map(a => a.play())) + if (playResults.some(r => r.status === 'rejected')) { setAwaitingGesture(true); return } + ``` +- **Single-audio branch:** `audioRef.current.play().catch(() => {})` → `await audioRef.current.play()` with catch → `setAwaitingGesture(true); return`. +- **Video-only branch:** same `await` + gate pattern for `videoRef.current.play()`. +- **Autoplay effect** catch: now calls `setAwaitingGesture(true)` instead of silently ignoring. +- **Tap-to-begin overlay JSX** added before `` at `zIndex: 20`: + - `role="button"`, `aria-label="Tap to begin playback"` + - On click: `ctx.resume()`, `setAwaitingGesture(false)`, `autoplayAttemptedRef.current = false`, retry `togglePlayRef.current()` + - SVG play icon + "Tap to begin" label, dark semi-transparent overlay background + +#### Block 5.3 — `createMediaElementSource` error handling + +**File:** `frontend/src/components/LyricsLivePreview.tsx` (stem init loop, `stems.forEach`) + +- Wrapped each `ctx.createMediaElementSource(audio)` call in `try/catch`. +- On catch: `reportNonFatal('LyricsLivePreview: createMediaElementSource', err, { stem: stem.name })` then `return` (forEach, not `continue`). +- Used `source!` non-null assertions after the guarded try/catch block. + +#### Block 2.5 — Docker image rebuild + +- `muon-iframe/stemengine-router.js` line 244: `audioMode: 'host-push'` in `emitReady` capabilities — confirmed present in source. +- Docker image rebuilt: `docker compose -f stemengine.yml build stemengine-muon` → `Image stemengine-muon:latest Built`. +- Container restarted: `docker compose -f stemengine.yml up -d stemengine-muon` → HTTP 200 confirmed. +- Note: `audioMode`/`host-push` strings are absent from the Webpack bundle because webpack minifies property names in production builds. The source-level change is correct and the runtime behavior is unaffected. + +#### Worklist updates + +- `docs/plans/visualizer-reactivity-fix/2026-04-20_Copilot_Worklist.md` — checked off all Block 2.5, 3.3, and 5.3 items. + +Validation: +- `frontend`: `npm run -s typecheck` ✅ +- Container HTTP 200 ✅ + +Remaining open: +- Block 1: browser-side validation (manual) +- Block 2 validation: DevTools console check (manual) +- Block 3 validation: autoplay block test (manual) +- Block 5.1, 5.2: analysis source refactor (deferred) + +--- + +### 2026-04-20 — LyricsLivePreview cleanup-plan implementation pass + +Worked through `docs/plans/visualizer-reactivity-fix/2026-04-20_LyricsLivePreview_Cleanup_Plan.md` and implemented a focused cleanup pass in `frontend/src/components/LyricsLivePreview.tsx` plus related utilities. + +Implemented: +- Removed module-level mutable speaker color globals; `speakerColor()` is now deterministic from `speakerId` (C-1). +- Fixed multi-stem playback branch duplication bug (removed redundant `ctx.resume()` and premature stem `play()` calls) while preserving autoplay gesture gating (C-2 partial). +- Replaced constant `styleRebuildVersion` memo with direct style-field deps in the rebuild effect (C-3). +- Extracted duplicated blur primitive cleanup into `pruneBlurPrimitives()` and reused in both scene paths (C-6). +- Added `sekSettingsToVizPatch()` in `frontend/src/components/visualizers/visualizerSettings.ts` and switched manifest mapping to use it (C-7). +- Stabilized speaker helpers with `useCallback` (`getSpeakerColor`, `getSpeakerName`) and memoized `mergeableGroups` (C-9, C-10). +- Stabilized stem-init dependency churn with `stemIdentityKey`/`stableStems` to avoid unnecessary rebuilds on equivalent stem arrays (C-13). +- Documented `previewPrefsKey` as an intentional signal dependency (C-15). +- Added shared utility `frontend/src/utils/waitForMediaReady.ts` and rewired stem/video readiness waits to it (C-16). +- Moved priming ring keyframes out of inline JSX ` - - {/* track ring */} - - {/* fill ring — starts at top (-90 deg rotation) */} - - - - - - )} - -
- -
- - {/* Windowed album art overlay — top-left hovering card (only shown in non-performance view) */} - {!isPerformanceView && artworkUrl && artLoaded && ( -
- Cover - {(artist || songTitle || title) && ( -
- {artist && ( -

- {artist} -

- )} - {(songTitle ?? title) && ( -

- {songTitle ?? title} -

- )} -
- )} -
- )} - {/* Hidden image used to detect whether cover art is available */} - {artworkUrl && !artLoaded && ( - setArtLoaded(true)} - onError={() => setArtLoaded(false)} - /> - )} - - ) + const lyricsCanvasStyle: StyleState & { bgGradient?: string | null } = { + bgColor: (hasVideoBackdrop || isVisualizerMode) ? 'rgba(0,0,0,0)' : effectiveBgColor, + bgGradient: (hasVideoBackdrop || isVisualizerMode) ? null : effectiveBgGradient, + textColor: effectiveTextColor, + highlightColor: effectiveHighlightColor, + wordHighlight: effectiveWordHighlight, + fontFamily: style.fontFamily, + fontSize, + fontBold: style.fontBold, + lineSpacing: style.lineSpacing, + textAlign: style.textAlign, + activeLineVerticalAlign: style.activeLineVerticalAlign, + dynBg: isVisualizerMode ? false : style.dynBg, + dynBgMode: isVisualizerMode ? 'flat' : style.dynBgMode, + scaleX: style.scaleX, + scaleY: style.scaleY, + strokeEnabled: style.strokeEnabled, + strokeColor: style.strokeColor, + strokeWidth: scaledStrokeWidth, + shadowEnabled: style.shadowEnabled, + shadowColor: style.shadowColor, + shadowOpacity: style.shadowOpacity, + shadowBlur: scaledShadowBlur, + shadowX: scaledShadowX, + shadowY: scaledShadowY, + glowSize: scaledGlowSize, + karaokeMode: style.karaokeMode, + popScale: style.popScale, + popSnap: style.popSnap, + effectGlowEnabled: style.effectGlowEnabled, + effectBlurEnabled: style.effectBlurEnabled, + videoAnimStyle: style.videoAnimStyle, + videoGranularity: style.videoGranularity, + videoDisplayMode: style.videoDisplayMode, + videoLineTransition: style.videoLineTransition, + layoutOffsetXScroll: style.layoutOffsetXScroll, + layoutOffsetYScroll: style.layoutOffsetYScroll, + layoutOffsetXLine: style.layoutOffsetXLine, + layoutOffsetYLine: style.layoutOffsetYLine, + layoutOffsetXWord: style.layoutOffsetXWord, + layoutOffsetYWord: style.layoutOffsetYWord, + layoutOffsetXSyllable: style.layoutOffsetXSyllable, + layoutOffsetYSyllable: style.layoutOffsetYSyllable, } - // Helper: transport controls - function renderTransport() { - return ( -
- - -
- -
- - {formatTime(currentTime)} - - - {hasAudio && ( -
- - -
- )} -
- ) - } - - // Helper: per-stem controls - function renderStems() { - if (!isMultiStem || !stems) return null - return ( -
- {stems.map(stem => ( -
- - {stem.label} - - - -
- updateStemGain(stem.name, parseFloat(e.target.value))} - className="w-full h-1.5 accent-brand-500 cursor-pointer" - /> -
- - {(gains[stem.name] ?? 1.0).toFixed(1)}x - -
- ))} -
- ) - } return (
))}
- + {/* Speaker colour swatches — always shown so user knows if diarization is missing */}
Speakers @@ -3933,9 +2626,80 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, audioUrl, ana {/* Content area: always full-frame lyrics/visualizer in performance mode */} <> - {renderLyricsArea()} - {renderTransport()} - {!performanceMode && renderStems()} + + + {!performanceMode && ( + + )} {/* Performance metadata card — top-left overlay (never split-screen) */} @@ -4061,7 +2825,6 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, audioUrl, ana src={analysisAudioUrl ?? audioUrl} preload="auto" crossOrigin="anonymous" - muted style={{ display: 'none' }} /> )} @@ -4083,1241 +2846,3 @@ export default function LyricsLivePreview({ lrcText, lyricsTracks, audioUrl, ana ) } -interface CanvasWordUnit { - behindText: InstanceType - frontText: InstanceType - frontElem: SVGElement | null - gradStops: [SVGStopElement, SVGStopElement] | null - gradId: string - shadowFilterId: string | null - activeColor: string - behindColor: string - perWord: boolean - measuredWidth: number - startTime: number - duration: number -} - -interface CanvasLineRecord { - group: InstanceType - wordUnits: CanvasWordUnit[] - dotCircle: InstanceType | null - lineIdx: number - yOffset: number - subRowCount: number -} - -interface CanvasSceneState { - two: InstanceType - linesGroup: InstanceType | null - bgRect: InstanceType | null - lineRecords: CanvasLineRecord[] - metricsCanvas: HTMLCanvasElement - metricsCtx: CanvasRenderingContext2D - metricsCache: Map - defs: SVGDefsElement | null - glowPrimitive: SVGElement | null - blurPrimitives: Map - activeIdx: number - overlayEl: HTMLDivElement | null - activeAnimations: Animation[] - lastVideoLineIdx: number - lastVideoWordIdx: number - videoFlexEl: HTMLDivElement | null - videoWordEls: HTMLSpanElement[] - videoLineUnits: Array<{ text: string; time: number; added: boolean; wordElIdx: number; el: HTMLSpanElement | null }> - lineWordGroups: Array }>> -} - -interface LyricsCanvasProps { - lines: LrcLine[] - currentTimeRef: { current: number | null } - visualStyle: LyricsVisualStyle - style: StyleState & { bgGradient?: string | null } - speakerColorFn: (id: string) => string -} - -function applyVideoTextRenderStyle(el: HTMLElement): void { - el.style.setProperty('text-rendering', 'geometricPrecision') - el.style.setProperty('-webkit-font-smoothing', 'antialiased') - el.style.setProperty('paint-order', 'stroke fill') -} - -const LINE_STRIDE_FACTOR = 1.4 -const INACTIVE_OPACITY = 0.35 -const INACTIVE_SCALE = 0.92 -const LERP_FACTOR = 0.12 -const BLUR_CULL_DIST = 4 - -function canvasLerp(a: number, b: number, t: number): number { - return a + (b - a) * t -} - -function buildCanvasWordGroups(words: LrcWord[]): Array<{ text: string; startTime: number; syllables: Array<{ text: string; time: number }> }> { - const groups: Array<{ text: string; startTime: number; syllables: Array<{ text: string; time: number }> }> = [] - let syllables: Array<{ text: string; time: number }> = [] - let text = '' - let startTime = -1 - for (const word of words) { - if (startTime < 0) startTime = word.time - text += word.text - syllables.push({ text: word.text, time: word.time }) - if (word.isWordEnd !== false) { - groups.push({ text, startTime, syllables }) - text = '' - startTime = -1 - syllables = [] - } - } - if (text) groups.push({ text, startTime, syllables }) - return groups -} - -function findCanvasActiveWordGroup(groups: Array<{ startTime: number }>, time: number): number { - let idx = -1 - for (let i = 0; i < groups.length; i++) { - if (groups[i].startTime <= time) idx = i - else break - } - return idx -} - -function measureCanvasWord(text: string, ctx: CanvasRenderingContext2D, cache: Map): number { - const key = ctx.font + '|' + text - if (cache.has(key)) return cache.get(key)! - const width = ctx.measureText(text).width - cache.set(key, width) - return width -} - -function canvasFontString(style: StyleState): string { - return `${style.fontBold ? 700 : 400} ${style.fontSize}px ${style.fontFamily}` -} - -function lineStride(style: StyleState): number { - return style.fontSize * style.lineSpacing * LINE_STRIDE_FACTOR -} - -function activeLineAnchorY(height: number, align: StyleState['activeLineVerticalAlign']): number { - if (align === 'top') return height * 0.28 - if (align === 'bottom') return height * 0.72 - return height * 0.5 -} - -function getCanvasLineVisualTargets( - visualStyle: LyricsVisualStyle, - style: StyleState, - isActive: boolean, - isPast: boolean, - absDist: number, -): { targetOp: number; targetSc: number } { - if (style.videoDisplayMode !== 'scroll') { - return { targetOp: isActive ? 1.0 : 0.0, targetSc: 1.0 } - } - if (visualStyle === 'video') { - if (style.videoDisplayMode === 'scroll') { - return { targetOp: isActive ? 0 : (isPast ? 0.30 : (absDist <= 5 ? 0.15 : 0)), targetSc: 1.0 } - } - return { targetOp: 0, targetSc: 1.0 } - } - if (isActive) { - return { - targetOp: 1.0, - targetSc: visualStyle === 'scroll' ? 1.08 : visualStyle === 'fade' ? 1.12 : 1.0, - } - } - switch (visualStyle) { - case 'scroll': - return { targetOp: isPast ? 0.45 : 0.35, targetSc: 0.9 } - case 'fade': - return { targetOp: absDist === 1 ? 0.40 : absDist === 2 ? 0.18 : 0.06, targetSc: 1.0 } - case 'karaoke': - return { targetOp: isPast ? 0.55 : (absDist <= 5 ? 0.25 : 0), targetSc: absDist <= 1 ? 0.88 : absDist <= 2 ? 0.82 : 0.78 } - case 'glow': - return { targetOp: isPast ? 0.50 : (absDist <= 5 ? 0.20 : 0), targetSc: absDist <= 1 ? 0.88 : absDist <= 2 ? 0.82 : 0.78 } - case 'blur': - return { targetOp: isPast ? 0.40 : (absDist <= 5 ? 0.15 : 0), targetSc: absDist <= 1 ? 0.88 : absDist <= 2 ? 0.82 : 0.78 } - default: - return { targetOp: Math.max(0.1, INACTIVE_OPACITY - absDist * 0.05), targetSc: INACTIVE_SCALE } - } -} - -function wrapCanvasText(text: string, metricsCtx: CanvasRenderingContext2D, metricsCache: Map, availableWidth: number): string[] { - const tokens = text.split(' ') - const rows: string[] = [] - let current = '' - for (const token of tokens) { - const candidate = current ? current + ' ' + token : token - if (current && measureCanvasWord(candidate, metricsCtx, metricsCache) > availableWidth) { - rows.push(current) - current = token - } else { - current = candidate - } - } - if (current) rows.push(current) - return rows.length > 0 ? rows : [text] -} - -function buildCanvasWordUnits( - line: LrcLine, - lineGroup: InstanceType, - style: StyleState, - visualStyle: LyricsVisualStyle, - two: InstanceType, - defs: SVGDefsElement, - metricsCtx: CanvasRenderingContext2D, - metricsCache: Map, - lineIdx: number, - speakerColorFn: (id: string) => string, -): CanvasWordUnit[] { - const layoutOffset = getLayoutOffset(style) - const speakerColorValue = line.speaker ? speakerColorFn(line.speaker) : null - const lineTextColor = style.textColor - const lineActiveColor = speakerColorValue ?? style.wordHighlight - const lineHighlight = speakerColorValue ?? style.highlightColor - const words = line.words.length > 0 ? line.words : [{ time: line.time, text: line.text, isWordEnd: true }] - - metricsCtx.font = canvasFontString(style) - const spaceWidth = measureCanvasWord(' ', metricsCtx, metricsCache) - const totalWidth = words.reduce((sum, word, index) => { - const addSpace = index < words.length - 1 && word.isWordEnd !== false - return sum + measureCanvasWord(word.text, metricsCtx, metricsCache) + (addSpace ? spaceWidth : 0) - }, 0) - - const needsWordUnits = visualStyle === 'karaoke' || visualStyle === 'glow' || visualStyle === 'blur' || style.effectGlowEnabled || style.effectBlurEnabled - const units: CanvasWordUnit[] = [] - - if (!needsWordUnits) { - const textX = (style.textAlign === 'left' ? -(two.width / 2) + 24 : style.textAlign === 'right' ? (two.width / 2) - 24 : 0) + layoutOffset.x - const text = new Two.Text(line.text, textX, 0, { - fill: lineHighlight, - size: style.fontSize, - family: style.fontFamily, - weight: style.fontBold ? 700 : 400, - alignment: style.textAlign, - } as any) - lineGroup.add(text) - units.push({ - behindText: text, - frontText: text, - frontElem: null, - gradStops: null, - gradId: '', - shadowFilterId: null, - activeColor: lineHighlight, - behindColor: lineHighlight, - perWord: false, - measuredWidth: totalWidth, - startTime: line.time, - duration: (line.endTime ?? line.time + 1) - line.time, - }) - return units - } - - const behindTexts: InstanceType[] = [] - const frontTexts: InstanceType[] = [] - const availableWidth = two.width - 48 - const subRows: Array<{ words: LrcWord[]; startIdx: number }> = [] - { - let rowWords: LrcWord[] = [] - let rowStart = 0 - let rowWidth = 0 - for (let wi = 0; wi < words.length; wi++) { - const wordWidth = measureCanvasWord(words[wi].text, metricsCtx, metricsCache) - const prevEnd = rowWords.length > 0 && words[wi - 1]?.isWordEnd !== false - const spaceBefore = rowWords.length > 0 && prevEnd ? spaceWidth : 0 - const needed = spaceBefore + wordWidth - if (rowWords.length > 0 && rowWidth + needed > availableWidth) { - subRows.push({ words: rowWords, startIdx: rowStart }) - rowStart = wi - rowWords = [words[wi]] - rowWidth = wordWidth - } else { - rowWords.push(words[wi]) - rowWidth += needed - } - } - if (rowWords.length > 0) subRows.push({ words: rowWords, startIdx: rowStart }) - } - - const stride = lineStride(style) - - for (let rowIdx = 0; rowIdx < subRows.length; rowIdx++) { - const { words: rowWords, startIdx } = subRows[rowIdx] - const rowY = rowIdx * stride - const rowTotalWidth = rowWords.reduce((sum, word, index) => { - const addSpace = index < rowWords.length - 1 && word.isWordEnd !== false - return sum + measureCanvasWord(word.text, metricsCtx, metricsCache) + (addSpace ? spaceWidth : 0) - }, 0) - let cursorX = style.textAlign === 'left' - ? -(two.width / 2) + 24 - : style.textAlign === 'right' - ? (two.width / 2) - rowTotalWidth - 24 - : -rowTotalWidth / 2 - - for (let i = 0; i < rowWords.length; i++) { - const word = rowWords[i] - const globalWordIndex = startIdx + i - const wordWidth = measureCanvasWord(word.text, metricsCtx, metricsCache) - const wordX = cursorX + wordWidth / 2 - const isWordEnd = word.isWordEnd !== false - cursorX += wordWidth + (i < rowWords.length - 1 && isWordEnd ? spaceWidth : 0) - - const rawEnd = globalWordIndex + 1 < words.length - ? words[globalWordIndex + 1].time - : (line.endTime ?? word.time + 1) - const duration = silenceAwareEnd(word.time, rawEnd) - word.time - - const behind = new Two.Text(word.text, wordX, rowY, { - fill: lineTextColor, - stroke: style.strokeEnabled ? style.strokeColor : 'none', - linewidth: style.strokeEnabled ? style.strokeWidth * 2 : 0, - size: style.fontSize, - family: style.fontFamily, - weight: style.fontBold ? 700 : 400, - alignment: 'center', - } as any) - - const isFillMode = style.karaokeMode === 'fill' - let front: InstanceType - let gradStops: [SVGStopElement, SVGStopElement] | null = null - const gradId = isFillMode ? `grad-${lineIdx}-${globalWordIndex}` : '' - - if (isFillMode) { - gradStops = injectGradient(defs, gradId, lineActiveColor, lineTextColor) - front = new Two.Text(word.text, wordX, rowY, { - fill: `url(#${gradId})`, - stroke: 'none', - linewidth: 0, - size: style.fontSize, - family: style.fontFamily, - weight: style.fontBold ? 700 : 400, - alignment: 'center', - } as any) - frontTexts.push(front) - } else { - front = behind - } - - behindTexts.push(behind) - - let shadowFilterId: string | null = null - if (style.shadowEnabled) { - shadowFilterId = `shadow-${lineIdx}-${globalWordIndex}` - injectFilter(defs, shadowFilterId, 'glow', { - dx: style.shadowX, - dy: style.shadowY, - stdDeviation: style.shadowBlur, - floodColor: style.shadowColor, - floodOpacity: style.shadowOpacity, - }) - } - - units.push({ - behindText: behind, - frontText: front, - frontElem: null, - gradStops, - gradId, - shadowFilterId, - activeColor: lineActiveColor, - behindColor: lineTextColor, - perWord: true, - measuredWidth: wordWidth, - startTime: word.time, - duration, - }) - } - } - - for (const behind of behindTexts) lineGroup.add(behind) - for (const front of frontTexts) lineGroup.add(front) - - return units -} - -function buildCanvasScene( - state: CanvasSceneState, - lines: LrcLine[], - style: StyleState & { bgGradient?: string | null }, - visualStyle: LyricsVisualStyle, - speakerColorFn: (id: string) => string, -): void { - const { two, metricsCtx } = state - two.clear() - state.lineRecords = [] - state.activeIdx = -1 - for (const animation of state.activeAnimations) animation.cancel() - state.activeAnimations = [] - state.lastVideoLineIdx = -1 - state.lastVideoWordIdx = -1 - state.videoFlexEl = null - state.videoWordEls = [] - state.videoLineUnits = [] - state.lineWordGroups = lines.map(line => line.words.length > 0 ? buildCanvasWordGroups(line.words) : []) - if (state.overlayEl) state.overlayEl.innerHTML = '' - state.defs = (two as any).renderer?.defs ?? null - if (state.defs) while (state.defs.firstChild) state.defs.removeChild(state.defs.firstChild) - - state.bgRect = new Two.Rectangle(two.width / 2, two.height / 2, two.width, two.height) - ;(state.bgRect as any).fill = style.bgColor - ;(state.bgRect as any).noStroke() - two.add(state.bgRect) - - state.linesGroup = new Two.Group() - const layoutOffset = getLayoutOffset(style) - state.linesGroup.translation.set(layoutOffset.x, two.height / 2) - two.add(state.linesGroup) - - metricsCtx.font = canvasFontString(style) - const stride = lineStride(style) - - if (state.defs) { - if (style.bgGradient) { - const gradientId = 'bg-grad' - const existing = state.defs.querySelector(`#${CSS.escape(gradientId)}`) - if (existing) existing.parentElement?.removeChild(existing) - const grad = document.createElementNS('http://www.w3.org/2000/svg', 'linearGradient') - grad.setAttribute('id', gradientId) - grad.setAttribute('x1', '0') - grad.setAttribute('y1', '0') - grad.setAttribute('x2', '0') - grad.setAttribute('y2', '1') - const top = document.createElementNS('http://www.w3.org/2000/svg', 'stop') - top.setAttribute('offset', '0%') - const bottom = document.createElementNS('http://www.w3.org/2000/svg', 'stop') - bottom.setAttribute('offset', '100%') - const gm = String(style.bgGradient).match(/linear-gradient\(180deg,\s*([^,]+),\s*([^)]+)\)/i) - top.setAttribute('stop-color', (gm?.[1] ?? style.bgColor).trim()) - bottom.setAttribute('stop-color', (gm?.[2] ?? style.bgColor).trim()) - grad.appendChild(top) - grad.appendChild(bottom) - state.defs.appendChild(grad) - ;(state.bgRect as any).fill = `url(#${gradientId})` - } - if (visualStyle === 'glow' || style.effectGlowEnabled) { - state.glowPrimitive = injectFilter(state.defs, 'glow-active', 'glow', { - dx: 0, - dy: 0, - stdDeviation: style.glowSize, - floodColor: style.wordHighlight, - floodOpacity: 0.9, - }) - } - if (visualStyle === 'blur' || style.effectBlurEnabled) state.blurPrimitives = new Map() - } - - const availableWidth = two.width - 48 - let cumulativeY = 0 - for (let i = 0; i < lines.length; i++) { - const line = lines[i] - const textRows = wrapCanvasText(line.text, metricsCtx, state.metricsCache, availableWidth) - const subRowCount = textRows.length - const yOffset = cumulativeY - const lineGroup = new Two.Group() - lineGroup.translation.set(two.width / 2, yOffset) - if (style.scaleX !== 1 || style.scaleY !== 1) (lineGroup as any).scale = new (Two as any).Vector(style.scaleX, style.scaleY) - - const wordUnits: CanvasWordUnit[] = [] - let dotCircle: InstanceType | null = null - if (i > 0 && line.speaker && line.speaker !== lines[i - 1].speaker) { - dotCircle = new Two.Circle(-two.width / 2 + 12, 0, 4) - ;(dotCircle as any).fill = speakerColorFn(line.speaker) - ;(dotCircle as any).noStroke() - lineGroup.add(dotCircle) - } - - const textX = (style.textAlign === 'left' ? -(two.width / 2) + 24 : style.textAlign === 'right' ? (two.width / 2) - 24 : 0) + layoutOffset.x - for (let ri = 0; ri < textRows.length; ri++) { - lineGroup.add(new Two.Text(textRows[ri], textX, ri * stride, { - fill: style.textColor, - stroke: style.strokeEnabled ? style.strokeColor : 'none', - linewidth: style.strokeEnabled ? style.strokeWidth * 2 : 0, - size: style.fontSize, - family: style.fontFamily, - weight: style.fontBold ? 700 : 400, - alignment: style.textAlign, - } as any)) - } - - lineGroup.opacity = INACTIVE_OPACITY - state.linesGroup.add(lineGroup) - state.lineRecords.push({ group: lineGroup, wordUnits, dotCircle, lineIdx: i, yOffset, subRowCount }) - cumulativeY += stride * subRowCount - } - - if (style.strokeEnabled || style.shadowEnabled) { - (two as any).renderer?.render() - for (let i = 0; i < state.lineRecords.length; i++) { - const record = state.lineRecords[i] - const children = record.group.children as any[] - const startIndex = record.dotCircle ? 1 : 0 - for (let ci = startIndex; ci < children.length; ci++) { - const textNode = children[ci] - const svgNode = textNode?._renderer?.elem as SVGElement | undefined - if (!svgNode) continue - if (style.strokeEnabled) svgNode.setAttribute('paint-order', 'stroke fill') - if (style.shadowEnabled && state.defs) { - const filterId = `shadow-inactive-${i}-${ci}` - injectFilter(state.defs, filterId, 'glow', { - dx: style.shadowX, - dy: style.shadowY, - stdDeviation: style.shadowBlur, - floodColor: style.shadowColor, - floodOpacity: style.shadowOpacity, - }) - applyFilter(textNode, filterId) - } - } - } - } -} - -function snapCanvasSceneState( - state: CanvasSceneState, - lines: LrcLine[], - style: StyleState, - visualStyle: LyricsVisualStyle, - speakerColorFn: (id: string) => string, - currentTimeRef: { current: number | null }, -): void { - if (!state.linesGroup) return - const time = currentTimeRef.current ?? 0 - const activeIdx = findActiveLine(lines, time) - activateCanvasLineGroup(state, activeIdx, lines, style, visualStyle, speakerColorFn) - const scrollIdx = Math.max(0, activeIdx) - const scrollRecord = state.lineRecords[scrollIdx] - const layoutOffset = getLayoutOffset(style) - const anchorY = activeLineAnchorY(state.two.height, style.activeLineVerticalAlign) + layoutOffset.y - state.linesGroup.translation.x = layoutOffset.x - state.linesGroup.translation.y = anchorY - (scrollRecord?.yOffset ?? 0) - - const blurEnabled = visualStyle === 'blur' || style.effectBlurEnabled - const blurKeep = blurEnabled ? new Set() : null - for (const record of state.lineRecords) { - const signedDist = record.lineIdx - activeIdx - const absDist = Math.abs(signedDist) - const isActive = signedDist === 0 - const isPast = signedDist < 0 - const { targetOp, targetSc } = getCanvasLineVisualTargets(visualStyle, style, isActive, isPast, absDist) - record.group.opacity = targetOp - ;(record.group as any).scale = (style.scaleX !== 1 || style.scaleY !== 1) - ? new (Two as any).Vector(style.scaleX * targetSc, style.scaleY * targetSc) - : targetSc - - if (blurEnabled) { - const svgNode = (record.group as any)._renderer?.elem as SVGElement | undefined - if (!svgNode || isActive) { - if (svgNode) svgNode.removeAttribute('filter') - continue - } - if (absDist <= BLUR_CULL_DIST) { - let primitive = state.blurPrimitives.get(record.lineIdx) - if (!primitive && state.defs) { - primitive = injectFilter(state.defs, `blur-line-${record.lineIdx}`, 'blur', { stdDeviation: 0 }) - state.blurPrimitives.set(record.lineIdx, primitive) - } - if (!primitive) continue - primitive.setAttribute('stdDeviation', String(Math.min(absDist * 1.5, 6))) - svgNode.setAttribute('filter', `url(#blur-line-${record.lineIdx})`) - blurKeep?.add(record.lineIdx) - } else { - svgNode.removeAttribute('filter') - } - } - } - - if (blurKeep && state.defs) { - for (const [lineIdx, primitive] of state.blurPrimitives.entries()) { - if (blurKeep.has(lineIdx)) continue - if (primitive.parentNode === state.defs) state.defs.removeChild(primitive) - state.blurPrimitives.delete(lineIdx) - } - } -} - -function activateCanvasLineGroup( - state: CanvasSceneState, - newIdx: number, - lines: LrcLine[], - style: StyleState, - visualStyle: LyricsVisualStyle, - speakerColorFn: (id: string) => string, -): void { - const oldIdx = state.activeIdx - if (state.defs && oldIdx >= 0 && oldIdx < state.lineRecords.length) { - const oldRecord = state.lineRecords[oldIdx] - for (const wordUnit of oldRecord.wordUnits) { - if (wordUnit.gradId) { - const stale = state.defs.querySelector(`#${CSS.escape(wordUnit.gradId)}`) - if (stale) state.defs.removeChild(stale) - } - if (wordUnit.shadowFilterId) { - const stale = state.defs.querySelector(`#${wordUnit.shadowFilterId}`) - if (stale) state.defs.removeChild(stale) - } - } - oldRecord.wordUnits = [] - if (visualStyle === 'glow' || style.effectGlowEnabled) { - const oldSvgNode = (oldRecord.group as any)._renderer?.elem as SVGElement | undefined - if (oldSvgNode) oldSvgNode.removeAttribute('filter') - } - - const oldGroup = oldRecord.group - oldGroup.remove(...(oldGroup.children as any[])) - if (oldRecord.dotCircle) oldGroup.add(oldRecord.dotCircle) - - const oldLine = lines[oldIdx] - const stride = lineStride(style) - const layoutOffset = getLayoutOffset(style) - const textX = (style.textAlign === 'left' ? -(state.two.width / 2) + 24 : style.textAlign === 'right' ? (state.two.width / 2) - 24 : 0) + layoutOffset.x - const oldTextRows = wrapCanvasText(oldLine.text, state.metricsCtx, state.metricsCache, state.two.width - 48) - for (let ri = 0; ri < oldTextRows.length; ri++) { - oldGroup.add(new Two.Text(oldTextRows[ri], textX, ri * stride, { - fill: style.textColor, - stroke: style.strokeEnabled ? style.strokeColor : 'none', - linewidth: style.strokeEnabled ? style.strokeWidth * 2 : 0, - size: style.fontSize, - family: style.fontFamily, - weight: style.fontBold ? 700 : 400, - alignment: style.textAlign, - } as any)) - } - } - - state.activeIdx = newIdx - if (newIdx < 0 || newIdx >= state.lineRecords.length || !state.defs) return - - const record = state.lineRecords[newIdx] - record.group.remove(...(record.group.children as any[])) - if (record.dotCircle) record.group.add(record.dotCircle) - record.wordUnits = buildCanvasWordUnits(lines[newIdx], record.group, style, visualStyle, state.two, state.defs, state.metricsCtx, state.metricsCache, newIdx, speakerColorFn) - ;(state.two as any).renderer?.render() - - for (const wordUnit of record.wordUnits) { - if (wordUnit.shadowFilterId) applyFilter(wordUnit.behindText, wordUnit.shadowFilterId) - const behindNode = (wordUnit.behindText as any)._renderer?.elem as SVGElement | undefined - if (behindNode) behindNode.setAttribute('paint-order', 'stroke fill') - if (behindNode) behindNode.setAttribute('text-rendering', 'geometricPrecision') - if (wordUnit.gradId) { - wordUnit.frontElem = (wordUnit.frontText as any)._renderer?.elem as SVGElement ?? null - if (wordUnit.frontElem) { - wordUnit.frontElem.setAttribute('fill', `url(#${wordUnit.gradId})`) - wordUnit.frontElem.setAttribute('text-rendering', 'geometricPrecision') - } - } - } - - if (oldIdx >= 0 && oldIdx < state.lineRecords.length) { - const oldRecord2 = state.lineRecords[oldIdx] - const oldChildren = oldRecord2.group.children as any[] - const startIndex = oldRecord2.dotCircle ? 1 : 0 - for (let ci = startIndex; ci < oldChildren.length; ci++) { - const restoredText = oldChildren[ci] - const restoredNode = restoredText?._renderer?.elem as SVGElement | undefined - if (!restoredNode) continue - if (style.strokeEnabled) restoredNode.setAttribute('paint-order', 'stroke fill') - restoredNode.setAttribute('text-rendering', 'geometricPrecision') - if (style.shadowEnabled && state.defs) { - const filterId = `shadow-inactive-${oldIdx}-${ci}` - injectFilter(state.defs, filterId, 'glow', { - dx: style.shadowX, - dy: style.shadowY, - stdDeviation: style.shadowBlur, - floodColor: style.shadowColor, - floodOpacity: style.shadowOpacity, - }) - applyFilter(restoredText, filterId) - } - } - } - - if ((visualStyle === 'glow' || style.effectGlowEnabled) && state.defs) { - applyFilter(record.group, 'glow-active') - const glowColor = lines[newIdx].speaker ? speakerColorFn(lines[newIdx].speaker) : style.wordHighlight - state.defs.querySelectorAll('#glow-active feDropShadow').forEach(element => { - element.setAttribute('flood-color', glowColor) - }) - } - - if (visualStyle === 'blur' || style.effectBlurEnabled) { - const svgNode = (record.group as any)._renderer?.elem as SVGElement | undefined - if (svgNode) svgNode.removeAttribute('filter') - } -} - -function updateCanvasWordFills(wordUnits: CanvasWordUnit[], line: LrcLine, time: number, style: StyleState): void { - const displayMode = style.videoDisplayMode - let activeSyllableIdx = -1 - let activeWordRange: { start: number; end: number } | null = null - - if (displayMode === 'syllable') { - activeSyllableIdx = line.words.length > 0 ? findActiveWord(line.words, time) : 0 - } else if (displayMode === 'word') { - if (line.words.length > 0) { - const ranges: Array<{ start: number; end: number; time: number }> = [] - let start = 0 - for (let i = 0; i < line.words.length; i++) { - if (line.words[i].isWordEnd !== false) { - ranges.push({ start, end: i, time: line.words[start]?.time ?? line.time }) - start = i + 1 - } - } - if (start < line.words.length) { - ranges.push({ start, end: line.words.length - 1, time: line.words[start]?.time ?? line.time }) - } - const activeWordIdx = findCanvasActiveWordGroup(ranges.map(r => ({ startTime: r.time })), time) - activeWordRange = activeWordIdx >= 0 ? ranges[activeWordIdx] : null - } else { - activeWordRange = { start: 0, end: 0 } - } - } - - let unitIdx = 0 - for (const wordUnit of wordUnits) { - if (!wordUnit.perWord) continue - const elapsed = time - wordUnit.startTime - const frac = wordUnit.duration > 0 ? Math.max(0, Math.min(1, elapsed / wordUnit.duration)) : (elapsed >= 0 ? 1 : 0) - const hideInactiveUnits = displayMode === 'word' || displayMode === 'syllable' - const isActiveUnit = displayMode === 'word' - ? !!activeWordRange && unitIdx >= activeWordRange.start && unitIdx <= activeWordRange.end - : displayMode === 'syllable' - ? unitIdx === activeSyllableIdx - : true - - if (hideInactiveUnits) { - const op = isActiveUnit ? 1 : 0 - wordUnit.behindText.opacity = op - wordUnit.frontText.opacity = op - } else { - wordUnit.behindText.opacity = 1 - wordUnit.frontText.opacity = 1 - } - - if (wordUnit.gradStops) { - const pct = String(frac) - wordUnit.gradStops[0].setAttribute('offset', pct) - wordUnit.gradStops[1].setAttribute('offset', pct) - if (wordUnit.frontElem) wordUnit.frontElem.setAttribute('fill', `url(#${wordUnit.gradId})`) - } else { - const isCurrentWord = elapsed >= 0 && elapsed < wordUnit.duration - const targetScale = isCurrentWord ? 1 + style.popScale / 100 : 1 - const popLerp = Math.min(1, 16 / Math.max(style.popSnap, 16)) - const curScale = (wordUnit.frontText as any).scale ?? 1 - ;(wordUnit.frontText as any).fill = frac > 0 ? wordUnit.activeColor : wordUnit.behindColor - ;(wordUnit.frontText as any).scale = canvasLerp(typeof curScale === 'number' ? curScale : 1, targetScale, popLerp) - } - unitIdx++ - } -} - -function updateCanvasScene( - state: CanvasSceneState, - lines: LrcLine[], - styleRef: { current: StyleState }, - visualStyleRef: { current: LyricsVisualStyle }, - speakerColorFn: (id: string) => string, - currentTimeRef: { current: number | null }, -): void { - const time = currentTimeRef.current ?? 0 - const style = styleRef.current - const visualStyle = visualStyleRef.current - const stride = lineStride(style) - const newActiveIdx = findActiveLine(lines, time) - - if (newActiveIdx !== state.activeIdx) activateCanvasLineGroup(state, newActiveIdx, lines, style, visualStyle, speakerColorFn) - - if (visualStyle === 'video') { - const displayMode = style.videoDisplayMode - const videoRowGap = Math.max(0, (style.lineSpacing - 1) * style.fontSize) - const strokeVal = style.strokeEnabled && style.strokeWidth > 0 ? `${style.strokeWidth}px ${style.strokeColor}` : '0 transparent' - const shadowVal = style.shadowEnabled ? `${style.shadowX}px ${style.shadowY}px ${style.shadowBlur}px ${hexToRgba(style.shadowColor, style.shadowOpacity)}` : 'none' - const layoutOffset = getLayoutOffset(style) - - const makeFlexDiv = (lineColor: string, forceCenter = false): HTMLDivElement => { - const justifyContent = forceCenter - ? 'center' - : style.textAlign === 'left' ? 'flex-start' : style.textAlign === 'right' ? 'flex-end' : 'center' - const div = document.createElement('div') - div.style.cssText = [ - 'position:absolute;inset:0', - 'display:flex;flex-wrap:wrap', - `align-items:center;justify-content:${justifyContent}`, - 'align-content:center', - 'padding:0 24px', - `font-family:${style.fontFamily}`, - `font-size:${style.fontSize}px`, - `font-weight:${style.fontBold ? 700 : 400}`, - `line-height:${style.lineSpacing}`, - `color:${lineColor}`, - `-webkit-text-stroke:${strokeVal}`, - 'paint-order:stroke fill', - `text-shadow:${shadowVal}`, - 'column-gap:0.3em', - `row-gap:${videoRowGap}px`, - 'text-rendering:geometricPrecision', - '-webkit-font-smoothing:antialiased', - '-moz-osx-font-smoothing:grayscale', - 'backface-visibility:hidden', - 'overflow:hidden', - ].join(';') - div.style.transform = `translate(${layoutOffset.x}px, ${layoutOffset.y}px)` - return div - } - - const animateSpan = (span: HTMLElement, animDef: typeof VIDEO_ANIM_REGISTRY[0], lineColor: string) => { - const parent = span.parentElement - const next = span.nextSibling - span.dataset.delay = '0' - const tmp = document.createElement('div') - tmp.appendChild(span) - const animations = animDef.animate(tmp, style.videoGranularity, { text: lineColor, active: lineColor }) - state.activeAnimations.push(...animations) - if (parent) { - if (next) parent.insertBefore(span, next) - else parent.appendChild(span) - } - } - - if (displayMode === 'scroll' || displayMode === 'line') { - const lineChanged = newActiveIdx !== state.lastVideoLineIdx - if (lineChanged) { - for (const animation of state.activeAnimations) animation.cancel() - state.activeAnimations = [] - const outgoingFlex = state.videoFlexEl - state.videoFlexEl = null - state.videoWordEls = [] - state.videoLineUnits = [] - - if (state.overlayEl) { - if (outgoingFlex) outgoingFlex.remove() - state.overlayEl.innerHTML = '' - const transDef = outgoingFlex && style.videoLineTransition !== 'none' - ? VIDEO_TRANSITION_REGISTRY.find(transition => transition.name === style.videoLineTransition) - : undefined - if (outgoingFlex && transDef) { - outgoingFlex.style.pointerEvents = 'none' - state.overlayEl.appendChild(outgoingFlex) - const exitAnimation = transDef.animate(outgoingFlex) - const removeAfter = transDef.duration + 50 - setTimeout(() => { exitAnimation.cancel(); outgoingFlex.remove() }, removeAfter) - } - - if (newActiveIdx >= 0 && newActiveIdx < lines.length) { - const activeLine = lines[newActiveIdx] - const lineColor = activeLine.speaker ? speakerColorFn(activeLine.speaker) : style.textColor - const words = activeLine.words.length > 0 ? activeLine.words : null - const isStaticLineReveal = displayMode === 'line' - const granularity: 'word' | 'syllable' = isStaticLineReveal - ? (words ? 'syllable' : 'word') - : (style.videoGranularity === 'syllable' ? 'syllable' : 'word') - - const flexDiv = makeFlexDiv(lineColor) - state.overlayEl.appendChild(flexDiv) - state.videoFlexEl = flexDiv - - if (granularity === 'syllable') { - const buckets: Array> = words - ? (() => { - const built: Array> = [] - let current: Array<{ text: string; time: number }> = [] - for (const word of words) { - current.push({ text: word.text, time: word.time }) - if (word.isWordEnd !== false) { - built.push(current) - current = [] - } - } - if (current.length) built.push(current) - return built - })() - : activeLine.text.split(' ').filter(Boolean).map((text, index) => [{ text, time: activeLine.time + index * 0.2 }]) - - for (let wi = 0; wi < buckets.length; wi++) { - const wordEl = document.createElement('span') - wordEl.style.cssText = `display:inline-flex;align-items:baseline;line-height:${style.lineSpacing}` - state.videoWordEls.push(wordEl) - if (isStaticLineReveal) state.videoFlexEl.appendChild(wordEl) - for (const syllable of buckets[wi]) { - let syllableEl: HTMLSpanElement | null = null - if (isStaticLineReveal) { - syllableEl = document.createElement('span') - syllableEl.setAttribute('data-unit', '') - syllableEl.textContent = syllable.text - syllableEl.style.display = 'inline-block' - syllableEl.style.visibility = 'hidden' - syllableEl.style.webkitTextStroke = strokeVal - syllableEl.style.textShadow = shadowVal - applyVideoTextRenderStyle(syllableEl) - wordEl.appendChild(syllableEl) - } - state.videoLineUnits.push({ text: syllable.text, time: syllable.time, added: false, wordElIdx: wi, el: syllableEl }) - } - } - } else { - const wordGroups = words - ? buildCanvasWordGroups(words) - : activeLine.text.split(' ').filter(Boolean).map((text, index) => ({ text, startTime: activeLine.time + index * 0.2, syllables: [{ text, time: activeLine.time + index * 0.2 }] })) - for (const wordGroup of wordGroups) { - let wordSpan: HTMLSpanElement | null = null - if (isStaticLineReveal) { - wordSpan = document.createElement('span') - wordSpan.setAttribute('data-unit', '') - wordSpan.textContent = wordGroup.text - wordSpan.style.display = 'inline-block' - wordSpan.style.visibility = 'hidden' - wordSpan.style.webkitTextStroke = strokeVal - wordSpan.style.textShadow = shadowVal - applyVideoTextRenderStyle(wordSpan) - state.videoFlexEl.appendChild(wordSpan) - } - state.videoLineUnits.push({ text: wordGroup.text, time: wordGroup.startTime, added: false, wordElIdx: -1, el: wordSpan }) - } - } - } - } - state.lastVideoLineIdx = newActiveIdx - } - - if (state.videoFlexEl && state.videoLineUnits.length > 0) { - const animDef = VIDEO_ANIM_REGISTRY.find(animation => animation.name === style.videoAnimStyle) ?? VIDEO_ANIM_REGISTRY[0] - const isStaticLineReveal = displayMode === 'line' - for (const unit of state.videoLineUnits) { - if (unit.added || unit.time > time) continue - unit.added = true - if (isStaticLineReveal && unit.el) { - unit.el.style.visibility = 'visible' - const activeLine = newActiveIdx >= 0 && newActiveIdx < lines.length ? lines[newActiveIdx] : null - const lineColor = activeLine?.speaker ? speakerColorFn(activeLine.speaker) : style.textColor - animateSpan(unit.el, animDef, lineColor) - continue - } - const span = document.createElement('span') - span.setAttribute('data-unit', '') - span.textContent = unit.text - span.style.display = 'inline-block' - span.style.webkitTextStroke = strokeVal - span.style.textShadow = shadowVal - applyVideoTextRenderStyle(span) - const activeLine = newActiveIdx >= 0 && newActiveIdx < lines.length ? lines[newActiveIdx] : null - const lineColor = activeLine?.speaker ? speakerColorFn(activeLine.speaker) : style.textColor - animateSpan(span, animDef, lineColor) - if (unit.wordElIdx >= 0) { - const wordEl = state.videoWordEls[unit.wordElIdx] - wordEl.appendChild(span) - if (!wordEl.parentElement) state.videoFlexEl.appendChild(wordEl) - } else { - state.videoFlexEl.appendChild(span) - } - } - } - } else { - let activeUnitIdx = -1 - if (newActiveIdx >= 0) { - const activeLine = lines[newActiveIdx] - const hasWords = activeLine?.words.length > 0 - if (displayMode === 'word') { - const groups = hasWords ? (state.lineWordGroups[newActiveIdx] ?? []) : [] - activeUnitIdx = hasWords ? findCanvasActiveWordGroup(groups, time) : 0 - } - if (displayMode === 'syllable') activeUnitIdx = findActiveWord(activeLine.words, time) - } - - const lineChanged = newActiveIdx !== state.lastVideoLineIdx - const wordChanged = activeUnitIdx !== state.lastVideoWordIdx - if (lineChanged || wordChanged) { - if (lineChanged) state.lastVideoWordIdx = -1 - for (const animation of state.activeAnimations) animation.cancel() - state.activeAnimations = [] - - if (state.overlayEl) { - state.overlayEl.innerHTML = '' - const canRender = newActiveIdx >= 0 && newActiveIdx < lines.length && activeUnitIdx >= 0 - if (canRender) { - const activeLine = lines[newActiveIdx] - const lineColor = activeLine.speaker ? speakerColorFn(activeLine.speaker) : style.textColor - const words = activeLine.words.length > 0 ? activeLine.words : null - const flexDiv = makeFlexDiv(lineColor, true) - let spanText: string - if (displayMode === 'word') { - const groups = state.lineWordGroups[newActiveIdx] ?? [] - spanText = groups[activeUnitIdx]?.text ?? activeLine.text - } else { - spanText = words?.[activeUnitIdx]?.text ?? activeLine.text - } - const span = document.createElement('span') - span.setAttribute('data-unit', '') - span.textContent = spanText - span.style.cssText = 'display:inline-block' - span.style.webkitTextStroke = strokeVal - span.style.textShadow = shadowVal - applyVideoTextRenderStyle(span) - const animDef = VIDEO_ANIM_REGISTRY.find(animation => animation.name === style.videoAnimStyle) ?? VIDEO_ANIM_REGISTRY[0] - animateSpan(span, animDef, lineColor) - flexDiv.appendChild(span) - state.overlayEl.appendChild(flexDiv) - } - } - state.lastVideoLineIdx = newActiveIdx - state.lastVideoWordIdx = activeUnitIdx - } - } - } - - const scrollIdx = Math.max(0, newActiveIdx) - const scrollRecord = state.lineRecords[scrollIdx] - const layoutOffset = getLayoutOffset(style) - const anchorY = activeLineAnchorY(state.two.height, style.activeLineVerticalAlign) + layoutOffset.y - if (!state.linesGroup) return - state.linesGroup.translation.x = canvasLerp(state.linesGroup.translation.x, layoutOffset.x, LERP_FACTOR) - const targetY = anchorY - (scrollRecord?.yOffset ?? scrollIdx * stride) - state.linesGroup.translation.y = canvasLerp(state.linesGroup.translation.y, targetY, LERP_FACTOR) - - const blurEnabled = visualStyle === 'blur' || style.effectBlurEnabled - const blurKeep = blurEnabled ? new Set() : null - for (const record of state.lineRecords) { - const signedDist = record.lineIdx - newActiveIdx - const absDist = Math.abs(signedDist) - const isActive = signedDist === 0 - const isPast = signedDist < 0 - const { targetOp, targetSc } = getCanvasLineVisualTargets(visualStyle, style, isActive, isPast, absDist) - - record.group.opacity = canvasLerp(record.group.opacity, targetOp, LERP_FACTOR) - const curScale = (record.group as any).scale ?? 1 - const curScalar = typeof curScale === 'object' ? ((curScale.x || 1) / (style.scaleX || 1)) : (curScale || 1) - const newAnim = canvasLerp(curScalar, targetSc, LERP_FACTOR) - ;(record.group as any).scale = (style.scaleX !== 1 || style.scaleY !== 1) - ? new (Two as any).Vector(style.scaleX * newAnim, style.scaleY * newAnim) - : newAnim - - if (visualStyle === 'scroll') { - const children = record.group.children as any[] - const startIndex = record.dotCircle ? 1 : 0 - for (let ci = startIndex; ci < children.length; ci++) { - const child = children[ci] - if (child && typeof child.weight !== 'undefined') child.weight = isActive ? 700 : 400 - } - } - - if ((visualStyle === 'karaoke' || visualStyle === 'glow' || visualStyle === 'blur' || style.effectGlowEnabled || style.effectBlurEnabled) && record.wordUnits.length === 0) { - const lineData = lines[record.lineIdx] - const speakerColorValue = lineData?.speaker ? speakerColorFn(lineData.speaker) : null - const targetFill = isPast ? (speakerColorValue ?? style.highlightColor) : (speakerColorValue ?? style.textColor) - const children = record.group.children as any[] - const startIndex = record.dotCircle ? 1 : 0 - for (let ci = startIndex; ci < children.length; ci++) { - const child = children[ci] - if (child) child.fill = targetFill - } - } - - if (blurEnabled && !isActive) { - let primitive = state.blurPrimitives.get(record.lineIdx) - const svgNode = (record.group as any)._renderer?.elem as SVGElement | undefined - if (svgNode) { - if (absDist <= BLUR_CULL_DIST) { - if (!primitive && state.defs) { - primitive = injectFilter(state.defs, `blur-line-${record.lineIdx}`, 'blur', { stdDeviation: 0 }) - state.blurPrimitives.set(record.lineIdx, primitive) - } - if (!primitive) continue - primitive.setAttribute('stdDeviation', String(Math.min(absDist * 1.5, 6))) - svgNode.setAttribute('filter', `url(#blur-line-${record.lineIdx})`) - blurKeep?.add(record.lineIdx) - } else { - svgNode.removeAttribute('filter') - } - } - } - } - - if (blurKeep && state.defs) { - for (const [lineIdx, primitive] of state.blurPrimitives.entries()) { - if (blurKeep.has(lineIdx)) continue - if (primitive.parentNode === state.defs) state.defs.removeChild(primitive) - state.blurPrimitives.delete(lineIdx) - } - } - - if (newActiveIdx >= 0 && newActiveIdx < state.lineRecords.length) { - const activeRecord = state.lineRecords[newActiveIdx] - if (activeRecord.wordUnits.length > 0) updateCanvasWordFills(activeRecord.wordUnits, lines[newActiveIdx], time, style) - } -} - -function LyricsCanvas({ lines, currentTimeRef, visualStyle, style, speakerColorFn }: LyricsCanvasProps) { - const containerRef = useRef(null) - const stateRef = useRef(null) - const styleRef = useRef(style) - const visualStyleRef = useRef(visualStyle) - const linesRef = useRef(lines) - const speakerColorFnRef = useRef(speakerColorFn) - - styleRef.current = style - visualStyleRef.current = visualStyle - linesRef.current = lines - speakerColorFnRef.current = speakerColorFn - - useEffect(() => { - if (!containerRef.current) return - const metricsCanvas = document.createElement('canvas') - const metricsCtx = metricsCanvas.getContext('2d')! - const two = new Two({ - type: Two.Types.svg, - autostart: true, - width: containerRef.current.clientWidth || 600, - height: containerRef.current.clientHeight || 400, - } as any) - two.appendTo(containerRef.current) - - const overlayEl = document.createElement('div') - overlayEl.style.cssText = 'position:absolute;inset:0;pointer-events:none;' - containerRef.current.appendChild(overlayEl) - - const state: CanvasSceneState = { - two, - linesGroup: null, - bgRect: null, - lineRecords: [], - metricsCanvas, - metricsCtx, - metricsCache: new Map(), - defs: null, - glowPrimitive: null, - blurPrimitives: new Map(), - activeIdx: -1, - overlayEl, - activeAnimations: [], - lastVideoLineIdx: -1, - lastVideoWordIdx: -1, - videoFlexEl: null, - videoWordEls: [], - videoLineUnits: [], - lineWordGroups: [], - } - stateRef.current = state - - let disposed = false - document.fonts.ready.then(() => { - if (disposed || stateRef.current !== state) return - buildCanvasScene(state, linesRef.current, styleRef.current, visualStyleRef.current, speakerColorFnRef.current) - }) - - two.bind('update', () => { - if (!stateRef.current || !stateRef.current.linesGroup) return - updateCanvasScene(stateRef.current, linesRef.current, styleRef, visualStyleRef, speakerColorFnRef.current, currentTimeRef) - }) - - const ro = new ResizeObserver(() => { - if (!containerRef.current || !stateRef.current) return - const width = containerRef.current.clientWidth - const height = containerRef.current.clientHeight - two.width = width - two.height = height - ;(two as any).renderer?.setSize(width, height) - buildCanvasScene(stateRef.current, linesRef.current, styleRef.current, visualStyleRef.current, speakerColorFnRef.current) - snapCanvasSceneState(stateRef.current, linesRef.current, styleRef.current, visualStyleRef.current, speakerColorFnRef.current, currentTimeRef) - }) - ro.observe(containerRef.current) - - return () => { - disposed = true - two.pause() - two.unbind('update') - ro.disconnect() - const svgEl = (two as any).renderer?.domElement - if (svgEl?.parentNode) svgEl.parentNode.removeChild(svgEl) - for (const animation of state.activeAnimations) animation.cancel() - if (overlayEl.parentNode) overlayEl.parentNode.removeChild(overlayEl) - } - }, [currentTimeRef]) - - const styleRebuildVersion = useMemo(() => 1, [ - style.fontFamily, - style.fontSize, - style.fontBold, - style.textAlign, - style.activeLineVerticalAlign, - style.lineSpacing, - style.scaleX, - style.scaleY, - style.bgColor, - style.bgGradient, - style.dynBgMode, - style.textColor, - style.wordHighlight, - style.highlightColor, - style.strokeEnabled, - style.strokeColor, - style.strokeWidth, - style.shadowEnabled, - style.shadowColor, - style.shadowOpacity, - style.shadowBlur, - style.shadowX, - style.shadowY, - style.karaokeMode, - style.glowSize, - style.popScale, - style.popSnap, - style.videoAnimStyle, - style.videoGranularity, - style.videoDisplayMode, - style.videoLineTransition, - style.layoutOffsetXScroll, - style.layoutOffsetYScroll, - style.layoutOffsetXLine, - style.layoutOffsetYLine, - style.layoutOffsetXWord, - style.layoutOffsetYWord, - style.layoutOffsetXSyllable, - style.layoutOffsetYSyllable, - ]) - - useEffect(() => { - const state = stateRef.current - if (!state) return - state.metricsCache.clear() - buildCanvasScene(state, linesRef.current, styleRef.current, visualStyleRef.current, speakerColorFnRef.current) - snapCanvasSceneState(state, linesRef.current, styleRef.current, visualStyleRef.current, speakerColorFnRef.current, currentTimeRef) - }, [styleRebuildVersion, currentTimeRef]) - - useEffect(() => { - const state = stateRef.current - if (!state) return - buildCanvasScene(state, linesRef.current, styleRef.current, visualStyleRef.current, speakerColorFnRef.current) - snapCanvasSceneState(state, linesRef.current, styleRef.current, visualStyleRef.current, speakerColorFnRef.current, currentTimeRef) - }, [visualStyle, currentTimeRef]) - - useEffect(() => { - const state = stateRef.current - if (!state) return - let cancelled = false - document.fonts.ready.then(() => { - if (cancelled || stateRef.current !== state) return - buildCanvasScene(state, lines, styleRef.current, visualStyleRef.current, speakerColorFnRef.current) - snapCanvasSceneState(state, lines, styleRef.current, visualStyleRef.current, speakerColorFnRef.current, currentTimeRef) - }) - return () => { cancelled = true } - }, [lines, currentTimeRef]) - - const isVisualizerVisualStyle = asVisualizerMode(visualStyle) !== null - - return ( -
- ) -} diff --git a/frontend/src/components/LyricsStylePicker.tsx b/frontend/src/components/LyricsStylePicker.tsx new file mode 100644 index 0000000..be6a02a --- /dev/null +++ b/frontend/src/components/LyricsStylePicker.tsx @@ -0,0 +1,445 @@ +import { AlignLeft, AlignCenter, AlignRight, Type } from 'lucide-react' +import { VIDEO_ANIM_REGISTRY, VIDEO_TRANSITION_REGISTRY, type VideoAnimStyle, type VideoTimingGranularity, type VideoLineTransition } from '../utils/videoAnimations' +import ColorSwatch from './ColorSwatch' + +export interface StyleState { + fontFamily: string + fontSize: number + bgColor: string + textColor: string + highlightColor: string + wordHighlight: string + textAlign: 'left' | 'center' | 'right' + activeLineVerticalAlign: 'top' | 'center' | 'bottom' + lineSpacing: number + dynBg: boolean + dynBgMode: 'flat' | 'gradient' + karaokeMode: 'fill' | 'pop' + fontBold: boolean + strokeEnabled: boolean + strokeWidth: number + strokeColor: string + shadowEnabled: boolean + shadowBlur: number + shadowX: number + shadowY: number + shadowColor: string + shadowOpacity: number + scaleX: number + scaleY: number + popScale: number + popSnap: number + glowSize: number + effectGlowEnabled: boolean + effectBlurEnabled: boolean + videoAnimStyle: VideoAnimStyle + videoGranularity: VideoTimingGranularity + videoDisplayMode: 'scroll' | 'line' | 'word' | 'syllable' + videoLineTransition: VideoLineTransition + layoutOffsetXScroll: number + layoutOffsetYScroll: number + layoutOffsetXLine: number + layoutOffsetYLine: number + layoutOffsetXWord: number + layoutOffsetYWord: number + layoutOffsetXSyllable: number + layoutOffsetYSyllable: number +} + +const FONT_OPTIONS = [ + { value: 'system-ui, sans-serif', label: 'System' }, + { value: '"Inter", sans-serif', label: 'Inter' }, + { value: '"Work Sans", sans-serif', label: 'Work Sans' }, + { value: '"Archivo", sans-serif', label: 'Archivo' }, + { value: '"Poppins", sans-serif', label: 'Poppins' }, + { value: '"Roboto", sans-serif', label: 'Roboto' }, + { value: '"Oswald", sans-serif', label: 'Oswald' }, + { value: '"EB Garamond", serif', label: 'EB Garamond' }, + { value: '"Libre Baskerville", serif', label: 'Libre Baskerville' }, + { value: '"Young Serif", serif', label: 'Young Serif' }, +] + +function getLayoutOffset(style: StyleState): { x: number; y: number } { + switch (style.videoDisplayMode) { + case 'line': + return { x: style.layoutOffsetXLine, y: style.layoutOffsetYLine } + case 'word': + return { x: style.layoutOffsetXWord, y: style.layoutOffsetYWord } + case 'syllable': + return { x: style.layoutOffsetXSyllable, y: style.layoutOffsetYSyllable } + case 'scroll': + default: + return { x: style.layoutOffsetXScroll, y: style.layoutOffsetYScroll } + } +} + +interface LyricsStylePickerProps { + style: StyleState + onChange: (patch: Partial) => void + onReset: () => void + hasCoverArt?: boolean + hasElrc?: boolean +} + +export default function LyricsStylePicker({ style, onChange, onReset, hasCoverArt, hasElrc }: LyricsStylePickerProps) { + const fontMin = style.videoDisplayMode === 'word' || style.videoDisplayMode === 'syllable' ? 18 : 12 + const fontMax = style.videoDisplayMode === 'word' || style.videoDisplayMode === 'syllable' ? 140 : 56 + const activeOffset = getLayoutOffset(style) + + const applyLayoutOffset = (axis: 'x' | 'y', value: number) => { + if (style.videoDisplayMode === 'line') { + onChange(axis === 'x' ? { layoutOffsetXLine: value } : { layoutOffsetYLine: value }) + return + } + if (style.videoDisplayMode === 'word') { + onChange(axis === 'x' ? { layoutOffsetXWord: value } : { layoutOffsetYWord: value }) + return + } + if (style.videoDisplayMode === 'syllable') { + onChange(axis === 'x' ? { layoutOffsetXSyllable: value } : { layoutOffsetYSyllable: value }) + return + } + onChange(axis === 'x' ? { layoutOffsetXScroll: value } : { layoutOffsetYScroll: value }) + } + + return ( +
+
+
+ + + +
+
+ Size + onChange({ fontSize: +e.target.value })} + className="w-24 h-1.5 accent-brand-400" + /> + {style.fontSize} +
+
+ {(['left', 'center', 'right'] as const).map(a => { + const Icon = a === 'left' ? AlignLeft : a === 'center' ? AlignCenter : AlignRight + return ( + + ) + })} + +
+
+
+ onChange({ bgColor: v })} /> + onChange({ textColor: v })} /> +
+ {(['fill', 'pop'] as const).map(m => ( + + ))} +
+
+ Spacing + onChange({ lineSpacing: +e.target.value })} + className="w-20 h-1.5 accent-brand-400" + /> +
+
+ Anchor + {([ + { value: 'top', label: 'Top' }, + { value: 'center', label: 'Center' }, + { value: 'bottom', label: 'Bottom' }, + ] as const).map(opt => ( + + ))} +
+
+
+ + + {style.effectGlowEnabled && ( +
+ Glow + onChange({ glowSize: +e.target.value })} + className="w-16 h-1.5 accent-brand-400" title="Glow radius (px)" /> + {style.glowSize}px +
+ )} +
+
+
+ + {style.strokeEnabled && <> + onChange({ strokeColor: v })} /> + onChange({ strokeWidth: +e.target.value })} + className="w-16 h-1.5 accent-brand-400" title="Stroke width" /> + {style.strokeWidth} + } +
+
+ + {style.shadowEnabled && <> + onChange({ shadowColor: v })} /> + onChange({ shadowOpacity: +e.target.value })} + className="w-10 h-1.5 accent-brand-400" title="Opacity" /> + onChange({ shadowBlur: +e.target.value })} + className="w-14 h-1.5 accent-brand-400" title="Blur" /> + onChange({ shadowX: +e.target.value })} + className="w-10 h-1.5 accent-brand-400" title="X" /> + onChange({ shadowY: +e.target.value })} + className="w-10 h-1.5 accent-brand-400" title="Y" /> + } +
+
+
+
+ W + onChange({ scaleX: +e.target.value })} + className="w-20 h-1.5 accent-brand-400" title="Horizontal scale" /> + {style.scaleX.toFixed(2)} +
+
+ H + onChange({ scaleY: +e.target.value })} + className="w-20 h-1.5 accent-brand-400" title="Vertical scale" /> + {style.scaleY.toFixed(2)} +
+ {style.karaokeMode === 'pop' && ( +
+ Pop + onChange({ popScale: +e.target.value })} + className="w-16 h-1.5 accent-brand-400" title="Pop word scale %" /> + {style.popScale}% +
+ )} + {style.karaokeMode === 'pop' && ( +
+ Snap + onChange({ popSnap: +e.target.value })} + className="w-16 h-1.5 accent-brand-400" title="Transition duration (ms)" /> + {style.popSnap}ms +
+ )} + { +
+
+ Layout + {(['scroll', 'line', 'word', 'syllable'] as const).map(dm => ( + + ))} +
+
+ Anim + + {style.videoDisplayMode === 'scroll' && ( + <> + Unit + {(['line', 'word', 'syllable'] as VideoTimingGranularity[]).map(g => ( + + ))} + + )} +
+
+ Exit + +
+ +
+ Offset + X + applyLayoutOffset('x', +e.target.value)} + className="w-24 h-1.5 accent-brand-400" + title={`Horizontal offset for ${style.videoDisplayMode} layout`} + /> + {activeOffset.x}px + + Y + applyLayoutOffset('y', +e.target.value)} + className="w-24 h-1.5 accent-brand-400" + title={`Vertical offset for ${style.videoDisplayMode} layout`} + /> + {activeOffset.y}px +
+ +
+ } +
+ {hasCoverArt && ( +
+ + {style.dynBg && ( +
+ Mode + {(['flat', 'gradient'] as const).map(mode => ( + + ))} +
+ )} + {style.dynBg && ( + + Dynamic mode auto-adjusts lyric colors for contrast. + + )} +
+ )} +
+ ) +} diff --git a/frontend/src/components/LyricsTransportBar.tsx b/frontend/src/components/LyricsTransportBar.tsx new file mode 100644 index 0000000..f1ffb93 --- /dev/null +++ b/frontend/src/components/LyricsTransportBar.tsx @@ -0,0 +1,107 @@ +import { Play, Pause, SkipBack, Volume2, VolumeX } from 'lucide-react' +import type { ChangeEvent, FormEvent } from 'react' + +interface LyricsTransportBarProps { + isFullscreen: boolean + isPlaying: boolean + currentTime: number + displayDuration: number + seekDragTime: number | null + hasAudio: boolean + isMuted: boolean + volume: number + onReset: () => void + onTogglePlay: () => void + onSeek: (event: ChangeEvent | FormEvent) => void + onBeginSeekDrag: () => void + onEndSeekDrag: () => void + onToggleMute: () => void + onVolumeChange: (event: ChangeEvent) => void + formatTime: (seconds: number) => string +} + +export default function LyricsTransportBar({ + isFullscreen, + isPlaying, + currentTime, + displayDuration, + seekDragTime, + hasAudio, + isMuted, + volume, + onReset, + onTogglePlay, + onSeek, + onBeginSeekDrag, + onEndSeekDrag, + onToggleMute, + onVolumeChange, + formatTime, +}: LyricsTransportBarProps) { + return ( +
+ + +
+ +
+ + {formatTime(currentTime)} + + + {hasAudio && ( +
+ + +
+ )} +
+ ) +} diff --git a/frontend/src/components/LyricsViewport.tsx b/frontend/src/components/LyricsViewport.tsx new file mode 100644 index 0000000..5a2f8fd --- /dev/null +++ b/frontend/src/components/LyricsViewport.tsx @@ -0,0 +1,306 @@ +import React from 'react' +import type { MutableRefObject, RefObject, Dispatch, SetStateAction } from 'react' +import VisualizerBackdrop from './visualizers/VisualizerBackdrop' +import LyricsCanvasView from './LyricsCanvas' +import { asVisualizerMode } from './LyricsLivePreview' +import type { LyricsVisualStyle, LrcLine, StyleState } from './LyricsLivePreview' +import type { AudioFeatures } from '../hooks/useAudioFeatures' +import type { VisualizerPalette } from '../hooks/useVisualizerPalette' +import type { VizSettings } from './visualizers/visualizerSettings' +import type { StemFeatureChannel } from '../utils/visualizerStemChannels' + +export interface LyricsViewportProps { + // refs + containerRef: RefObject + featuresRef: MutableRefObject + paletteRef: MutableRefObject + iframeRef: RefObject + videoRef: RefObject + currentTimeRef: MutableRefObject + audioCtxRef: MutableRefObject + autoplayAttemptedRef: MutableRefObject + togglePlayRef: MutableRefObject<() => void> + desiredVideoSegmentRef: MutableRefObject<{ index: number; localTime: number } | null> + // booleans + isPerformanceView: boolean + isBackdropVisualizerMode: boolean + isIframeVisualizerMode: boolean + hasVideoBackdrop: boolean + isPlaylistBackdropMode: boolean + isPlaying: boolean + awaitingGesture: boolean + muonIframeError: boolean + // values + visualStyle: LyricsVisualStyle + visualizerSize: { width: number; height: number } + liveVizSettings: VizSettings + stemFeaturesByChannel: Partial>> | undefined + activeSpeakerVisualizerPalette: string[] | undefined + muonEmbedUrl: string + currentVideoUrl: string | undefined + videoStartPhase: 'idle' | 'priming' | 'playing' + resolvedVideoPlaylist: Array<{ url: string; duration?: number }> + videoPlaylistIndex: number + lines: LrcLine[] + lyricsCanvasStyle: StyleState & { bgGradient?: string | null } + artworkUrl: string | undefined + artLoaded: boolean + artist?: string + songTitle?: string + title?: string + // setters + setMuonIframeError: Dispatch> + setDuration: Dispatch> + setVideoPlaylistIndex: Dispatch> + setAwaitingGesture: Dispatch> + setArtLoaded: Dispatch> + // callbacks + speakerColorFn: (id: string) => string + mapTransportTimeToVideoSegment: (t: number) => { index: number; localTime: number } +} + +function LyricsViewport(props: LyricsViewportProps) { + return ( +
+ {props.isBackdropVisualizerMode && ( +
+ +
+ )} + + {props.isIframeVisualizerMode && ( +
+