diff --git a/AGENTS.md b/AGENTS.md index b9a67ce17..d14a0db5a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -83,6 +83,7 @@ This section applies to any agent (Claude, Codex, Cursor, opencode, ...) working - Keep UI and analysis engine decoupled through shared contracts. - Prefer minimal, test-first changes for production code. - Prefer practical, friendly, rehearsal-first wording over academic or authority-heavy language. +- Name tonight's first labeled tag with the holding part when an active role is corroborated, the labeled last line, and the time so the next action is obvious. - Do not reduce the product to a chord analyzer when form, timing, player coordination, playable ranges, simplification, and setup cues are the real rehearsal blockers. - Do not frame usability as a reason to accept weak analysis quality; BandScope should aim for both easy use and high accuracy. diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index ca0df5ac4..a6540ef19 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -6,6 +6,7 @@ Last updated: 2026-03-11 - Product identity, UX tone, copy rules, and prioritization tie-breakers live in `docs/brand-story.md`. - Future PRDs, TRDs, onboarding copy, empty states, error messages, and marketing copy should use that document as the single brand source of truth. +- The mounted workspace copy for tonight's first labeled tag must name the holding part when corroborated, the labeled last line, and the time so the next action is obvious. Open moves to the matching rendered map section. Do not invent a tag from outro, verse, chorus, or the last unlabeled section. ## Security source diff --git a/CHANGELOG.md b/CHANGELOG.md index 0b6f7e784..3173b9715 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ - Name tonight's first playable range on the ready rehearsal map and tell the player to check that span on their instrument before the section. - Display the analyzed song tempo (BPM) as a badge in the rehearsal workspace. +- Name tonight's first labeled tag in the mounted rehearsal workspace so the room can catch the last line together; the Open action moves to the matching rendered map section, while inherited or accessor-backed runtime metadata remains guidance-only instead of becoming navigation authority. - 각 합주 역할(Role)별 개인 연습 진행도를 0~100% 범위로 기록 및 시각화할 수 있는 연습 진척도(`practiceProgress`) 트래커 기능 추가. UI 컨트롤(슬라이더 및 +/- 버튼)과 한/영 다국어 지원 포함. ### Changed diff --git a/CLAUDE.md b/CLAUDE.md index b5a34c1fa..7ba94be76 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -51,7 +51,7 @@ BandScope is a local-first desktop app for rehearsal prep: it turns a song into Three layers, decoupled through shared contracts: -- `apps/desktop` — Tauri 2 + Vite + React 19 shell (Tailwind 4, Base UI, Storybook). Feature screens live in `src/features/` (home, workspace, chords, ranges, player, settings). The ready workspace names tonight's first playable range and the next instrument check. `src/lib/analysis.ts` and `src/lib/job_runner.ts` call typed Tauri IPC commands, with a browser fallback that serves demo data when not running inside Tauri. +- `apps/desktop` — Tauri 2 + Vite + React 19 shell (Tailwind 4, Base UI, Storybook). Feature screens live in `src/features/` (home, workspace, chords, ranges, player, settings). The mounted workspace names tonight's first labeled tag and opens the matching rendered map section. Do not invent a last line from outro, verse, or an unlabeled ending. The ready workspace also names tonight's first playable range and the next instrument check. `src/lib/analysis.ts` and `src/lib/job_runner.ts` call typed Tauri IPC commands, with a browser fallback that serves demo data when not running inside Tauri. - `apps/desktop/src-tauri/src/main.rs` — the Rust orchestration boundary. Tauri commands (`start_analysis_job`, `get_analysis_job_status`, `select_local_audio_source`, `import_youtube_url`) validate untrusted input (project IDs, file paths, URLs) and spawn the Python engine as a subprocess. There is no loopback HTTP listener and no network path for local analysis. - `services/analysis-engine` — Python package `bandscope_analysis` (librosa/numpy). Entry point `cli.py` reads a JSON job request on stdin and prints a structured job-status JSON envelope on stdout (`--progress-jsonl` streams progress lines). `api.py` orchestrates the pipeline across the `separation`, `sections`, `roles`, `chords`, `ranges`, `temporal`, `transcription`, and `youtube` modules. diff --git a/apps/desktop/src/features/workspace/FirstTagCallout.particle.test.tsx b/apps/desktop/src/features/workspace/FirstTagCallout.particle.test.tsx new file mode 100644 index 000000000..8093c7085 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstTagCallout.particle.test.tsx @@ -0,0 +1,48 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { FirstTagCallout } from "./FirstTagCallout"; + +describe("FirstTagCallout Korean role copy", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("keeps vowel-ending dynamic role names particle-safe before and after the tag action", () => { + vi.stubGlobal("navigator", { language: "ko-KR" }); + const song = createDemoRehearsalSong(); + const seed = song.sections[0]!; + const tag = structuredClone(seed); + tag.id = "tag-particle"; + tag.label = "tag"; + tag.timeRange = { start: 200, end: 208 }; + tag.roles = [{ ...seed.roles[0]!, id: "piano", name: "피아노", rehearsalPriority: "high" }]; + tag.partGraph = [{ role_id: "piano", is_active: true, handoff_to: [], handoff_from: [] }]; + song.sections = [tag]; + + const grid = document.createElement("div"); + grid.dataset.testid = "song-structure-grid"; + grid.setAttribute("role", "region"); + grid.setAttribute("aria-label", "Scrollable song structure timeline"); + const target = document.createElement("div"); + target.dataset.sectionIndex = "0"; + Object.defineProperty(target, "scrollIntoView", { + configurable: true, + value: vi.fn() + }); + grid.appendChild(target); + document.body.appendChild(grid); + + render(); + + expect(screen.getByText("3:20 태그에서 피아노 파트가 마지막 한 줄을 잡습니다.")).toBeTruthy(); + expect(screen.queryByText(/피아노이/)).toBeNull(); + + fireEvent.click(screen.getByRole("button", { name: "3:20 피아노 태그 위치 열기" })); + + expect(screen.getByText("3:20에서 피아노 파트와 함께 마지막 한 줄을 잡으세요. 같이 끝내세요.")).toBeTruthy(); + expect(screen.queryByText(/피아노과/)).toBeNull(); + + grid.remove(); + }); +}); diff --git a/apps/desktop/src/features/workspace/FirstTagCallout.reduced-motion.test.tsx b/apps/desktop/src/features/workspace/FirstTagCallout.reduced-motion.test.tsx new file mode 100644 index 000000000..ecf6c31cf --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstTagCallout.reduced-motion.test.tsx @@ -0,0 +1,88 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { FirstTagCallout } from "./FirstTagCallout"; + +function songWithTag() { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + const tag = structuredClone(verse); + tag.id = "tag-1"; + tag.label = "tag"; + tag.timeRange = { start: 200, end: 208 }; + tag.roles = [ + { + ...verse.roles[0]!, + id: "lead-vocal", + name: "Lead Vocal", + rehearsalPriority: "high" + } + ]; + tag.partGraph = [ + { + role_id: "lead-vocal", + is_active: true, + handoff_to: [], + handoff_from: [] + } + ]; + song.sections = [verse, tag]; + return song; +} + +function appendTagTarget() { + const grid = document.createElement("div"); + grid.dataset.testid = "song-structure-grid"; + grid.setAttribute("role", "region"); + grid.setAttribute("aria-label", "Scrollable song structure timeline"); + const first = document.createElement("div"); + first.dataset.sectionIndex = "0"; + const target = document.createElement("div"); + target.dataset.sectionIndex = "1"; + const scrollIntoView = vi.fn(); + Object.defineProperty(target, "scrollIntoView", { + configurable: true, + value: scrollIntoView + }); + grid.appendChild(first); + grid.appendChild(target); + document.body.appendChild(grid); + return { grid, scrollIntoView }; +} + +describe("FirstTagCallout reduced motion", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("scrolls immediately when the operating system requests reduced motion", () => { + vi.stubGlobal("matchMedia", (query: string) => ({ + matches: query === "(prefers-reduced-motion: reduce)", + media: query, + onchange: null, + addListener: vi.fn(), + removeListener: vi.fn(), + addEventListener: vi.fn(), + removeEventListener: vi.fn(), + dispatchEvent: vi.fn() + })); + const { grid, scrollIntoView } = appendTagTarget(); + + render(); + fireEvent.click(screen.getByRole("button", { name: "Open Lead Vocal tag at 3:20" })); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "auto" }); + + grid.remove(); + }); + + it("uses smooth scrolling when matchMedia is unavailable", () => { + vi.stubGlobal("matchMedia", undefined); + const { grid, scrollIntoView } = appendTagTarget(); + + render(); + fireEvent.click(screen.getByRole("button", { name: "Open Lead Vocal tag at 3:20" })); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + + grid.remove(); + }); +}); diff --git a/apps/desktop/src/features/workspace/FirstTagCallout.test.tsx b/apps/desktop/src/features/workspace/FirstTagCallout.test.tsx new file mode 100644 index 000000000..f94f0bc77 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstTagCallout.test.tsx @@ -0,0 +1,225 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong, type RehearsalSong } from "@bandscope/shared-types"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { FirstTagCallout } from "./FirstTagCallout"; + +function songWithTag() { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + const tag = structuredClone(verse); + tag.id = "tag-1"; + tag.label = "tag"; + tag.timeRange = { start: 200, end: 208 }; + tag.roles = [ + { + ...verse.roles[0]!, + id: "lead-vocal", + name: "Lead Vocal", + rehearsalPriority: "high" + } + ]; + tag.partGraph = [ + { + role_id: "lead-vocal", + is_active: true, + handoff_to: [], + handoff_from: [] + } + ]; + song.sections = [verse, tag]; + return song; +} + +function appendSongStructureTarget(ariaLabel = "Scrollable song structure timeline") { + const timeline = document.createElement("div"); + timeline.setAttribute("role", "region"); + timeline.setAttribute("aria-label", ariaLabel); + const grid = document.createElement("div"); + grid.dataset.testid = "song-structure-grid"; + const first = document.createElement("div"); + first.dataset.sectionIndex = "0"; + const unrelatedSibling = document.createElement("div"); + const target = document.createElement("div"); + target.dataset.sectionIndex = "1"; + const scrollIntoView = vi.fn(); + Object.defineProperty(target, "scrollIntoView", { + configurable: true, + value: scrollIntoView + }); + grid.appendChild(first); + grid.appendChild(unrelatedSibling); + grid.appendChild(target); + timeline.appendChild(grid); + document.body.appendChild(timeline); + return { grid: timeline, scrollIntoView }; +} + +describe("FirstTagCallout", () => { + afterEach(() => { + vi.unstubAllGlobals(); + }); + + it("contains a malformed runtime song root instead of crashing the callout", () => { + render(); + + expect( + screen.getByText("No tag yet. Stay on tonight's map until the last line is labeled.") + ).toBeTruthy(); + }); + + it("contains a hostile song identity accessor instead of crashing the callout", () => { + const song = songWithTag(); + Object.defineProperty(song, "id", { + configurable: true, + enumerable: true, + get() { + throw new Error("hostile song id getter"); + } + }); + + expect(() => render()).not.toThrow(); + expect(screen.getByRole("button", { name: "Open Lead Vocal tag at 3:20" })).toBeTruthy(); + }); + + it("resets armed guidance when accessor-id songs change with the same tag signature", () => { + const firstSong = songWithTag(); + const nextSong = songWithTag(); + for (const song of [firstSong, nextSong]) { + Object.defineProperty(song, "id", { + configurable: true, + enumerable: true, + get() { + throw new Error("hostile song id getter"); + } + }); + } + const { grid } = appendSongStructureTarget(); + const { rerender } = render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Lead Vocal tag at 3:20" })); + expect(screen.getByText(/Catch the last line with Lead Vocal at 3:20. End together./)).toBeTruthy(); + + rerender(); + + expect(screen.getByText("Lead Vocal holds the tag at 3:20.")).toBeTruthy(); + expect(screen.queryByText(/Catch the last line with Lead Vocal at 3:20. End together./)).toBeNull(); + + grid.remove(); + }); + + it("names the first tag as map navigation, scrolls to its rendered section, and arms that action", () => { + const { grid, scrollIntoView } = appendSongStructureTarget(); + + render(); + + const action = screen.getByRole("button", { + name: "Open Lead Vocal tag at 3:20" + }); + expect(action).toBeTruthy(); + fireEvent.click(action); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + expect(screen.getByText(/Catch the last line with Lead Vocal at 3:20. End together./)).toBeTruthy(); + + grid.remove(); + }); + + it("keeps map navigation stable when the renderer accessible name is localized", () => { + const { grid, scrollIntoView } = appendSongStructureTarget("스크롤 가능한 곡 구조 타임라인"); + + render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Lead Vocal tag at 3:20" })); + + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + expect(screen.getByText(/Catch the last line with Lead Vocal at 3:20. End together./)).toBeTruthy(); + + grid.remove(); + }); + + it("does not claim map navigation completed when the rendered section target is missing", () => { + render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Lead Vocal tag at 3:20" })); + + expect(screen.getByText("Lead Vocal holds the tag at 3:20.")).toBeTruthy(); + expect(screen.queryByText(/Catch the last line with Lead Vocal at 3:20. End together./)).toBeNull(); + }); + + it("navigates by renderer-owned section position instead of untrusted analysis ids", () => { + const song = songWithTag(); + song.sections[1]!.id = "analysis section / duplicate"; + const { grid, scrollIntoView } = appendSongStructureTarget(); + + render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Lead Vocal tag at 3:20" })); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + + grid.remove(); + }); + + it("scopes map navigation to the song-structure renderer when another surface reuses an index", () => { + const decoy = document.createElement("div"); + decoy.dataset.sectionIndex = "1"; + const decoyScrollIntoView = vi.fn(); + Object.defineProperty(decoy, "scrollIntoView", { + configurable: true, + value: decoyScrollIntoView + }); + document.body.appendChild(decoy); + const { grid, scrollIntoView } = appendSongStructureTarget(); + + render(); + + fireEvent.click(screen.getByRole("button", { name: "Open Lead Vocal tag at 3:20" })); + + expect(decoyScrollIntoView).not.toHaveBeenCalled(); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + + decoy.remove(); + grid.remove(); + }); + + it("shows fresh guidance when the first tag changes or returns later", () => { + const initialSong = songWithTag(); + const { grid } = appendSongStructureTarget(); + const { rerender } = render(); + fireEvent.click(screen.getByRole("button", { name: "Open Lead Vocal tag at 3:20" })); + expect(screen.getByText(/Catch the last line with Lead Vocal at 3:20. End together./)).toBeTruthy(); + + const nextSong = songWithTag(); + nextSong.id = "next-song"; + nextSong.sections[1]!.timeRange = { start: 220, end: 228 }; + rerender(); + expect(screen.getByText("Lead Vocal holds the tag at 3:40.")).toBeTruthy(); + + grid.remove(); + }); + + it("keeps an unavailable tag guidance-only", () => { + render(); + expect(screen.queryByRole("button")).toBeNull(); + expect( + screen.getByText("No tag yet. Stay on tonight's map until the last line is labeled.") + ).toBeTruthy(); + }); + + it("names a band-wide last line when no part holds the tag", () => { + const song = songWithTag(); + song.sections[1]!.partGraph[0]!.is_active = false; + render(); + expect(screen.getByRole("button", { name: "Open the first tag at 3:20" })).toBeTruthy(); + expect(screen.getByText("The band catches the tag at 3:20.")).toBeTruthy(); + }); + + it("localizes the tag form label instead of exposing its raw enum in Korean copy", () => { + vi.stubGlobal("navigator", { language: "ko-KR" }); + const song = songWithTag(); + song.sections[1]!.roles[0]!.name = "리드 보컬"; + + render(); + + expect(screen.getByText("3:20 태그에서 리드 보컬 파트가 마지막 한 줄을 잡습니다.")).toBeTruthy(); + expect(screen.queryByText(/tag에서/)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/FirstTagCallout.tsx b/apps/desktop/src/features/workspace/FirstTagCallout.tsx new file mode 100644 index 000000000..f63c16de4 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstTagCallout.tsx @@ -0,0 +1,130 @@ +import { useEffect, useState } from "react"; +import type { RehearsalSong } from "@bandscope/shared-types"; +import { Button } from "@/components/ui/button"; +import { + createTranslator, + detectPreferredLocale, + translateSectionFormLabel +} from "../../i18n"; +import { formatTagTime, resolveFirstTag } from "./firstTag"; + +/** Props for the first-tag rehearsal callout. */ +export interface FirstTagCalloutProps { + song: RehearsalSong; +} + +type TagCopyValues = Readonly>; + +type OpenedTag = Readonly<{ + songIdentity: unknown; + sectionId: string; + sectionIndex: number; + holdingRoleId: string | null; + atSeconds: number; +}>; + +/** Interpolate tag placeholders once so rehearsal data is never rescanned as template syntax. */ +function formatTagCopy(template: string, values: TagCopyValues): string { + return template.replace(/\{(role|section|at)\}/g, (placeholder) => { + const key = placeholder.slice(1, -1) as keyof TagCopyValues; + return values[key] ?? placeholder; + }); +} + +/** Use immediate scrolling when the operating system requests reduced motion. */ +function preferredTagScrollBehavior(): ScrollBehavior { + return typeof window.matchMedia === "function" && + window.matchMedia("(prefers-reduced-motion: reduce)").matches + ? "auto" + : "smooth"; +} + +/** Name tonight's first labeled tag and open the matching rendered map section. */ +export function FirstTagCallout({ song }: FirstTagCalloutProps) { + const locale = detectPreferredLocale(); + const t = createTranslator(locale); + const songIdentity: unknown = song; + const runtimeSong = song as unknown as Partial | null; + const tag = resolveFirstTag(song); + const tagSectionIndex = + tag && Array.isArray(runtimeSong?.sections) ? runtimeSong.sections.indexOf(tag.section) : -1; + const [openedTag, setOpenedTag] = useState(null); + + useEffect(() => { + setOpenedTag(null); + }, [songIdentity, tagSectionIndex, tag?.section.id, tag?.holdingRole?.id, tag?.atSeconds]); + + if (!tag) { + return ( + + ); + } + + const opened = + openedTag !== null && + openedTag.songIdentity === songIdentity && + openedTag.sectionId === tag.section.id && + openedTag.sectionIndex === tagSectionIndex && + openedTag.holdingRoleId === (tag.holdingRole?.id ?? null) && + openedTag.atSeconds === tag.atSeconds; + const at = formatTagTime(tag.atSeconds); + const copyValues: TagCopyValues = { + role: tag.holdingRole?.name ?? "", + section: translateSectionFormLabel(locale, tag.section.label), + at + }; + const hasRole = tag.holdingRole !== null; + const actionLabel = formatTagCopy( + t(hasRole ? "firstTagOpenAction" : "firstTagOpenActionBand"), + copyValues + ); + const body = formatTagCopy(t(hasRole ? "firstTagBody" : "firstTagBodyBand"), copyValues); + const armed = formatTagCopy(t(hasRole ? "firstTagArmed" : "firstTagArmedBand"), copyValues); + + return ( + + ); +} diff --git a/apps/desktop/src/features/workspace/Workspace.test.tsx b/apps/desktop/src/features/workspace/Workspace.test.tsx index 7837bf80e..544c3b104 100644 --- a/apps/desktop/src/features/workspace/Workspace.test.tsx +++ b/apps/desktop/src/features/workspace/Workspace.test.tsx @@ -326,4 +326,48 @@ describe("Workspace", () => { expect(screen.getByText("합주 우선순위")).toBeTruthy(); expect(screen.getByText("역할과 화성")).toBeTruthy(); }); + + it("names tonight's first tag as workspace navigation", () => { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + const tag = structuredClone(verse); + tag.id = "tag-1"; + tag.label = "tag"; + tag.timeRange = { start: 200, end: 208 }; + tag.roles = [ + { + ...verse.roles[0]!, + id: "lead-vocal", + name: "Lead Vocal", + rehearsalPriority: "high" + } + ]; + tag.partGraph = [ + { + role_id: "lead-vocal", + is_active: true, + handoff_to: [], + handoff_from: [] + } + ]; + song.sections = [verse, tag]; + + render(); + + const target = screen.getByTestId("song-structure-grid").children.item(1); + expect(target).toBeTruthy(); + const scrollIntoView = vi.fn(); + Object.defineProperty(target!, "scrollIntoView", { + configurable: true, + value: scrollIntoView + }); + + const action = screen.getByRole("button", { + name: "Open Lead Vocal tag at 3:20" + }); + expect(action).toBeTruthy(); + fireEvent.click(action); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + expect(screen.getByText(/Catch the last line with Lead Vocal at 3:20. End together./)).toBeTruthy(); + }); }); diff --git a/apps/desktop/src/features/workspace/Workspace.tsx b/apps/desktop/src/features/workspace/Workspace.tsx index d44e20777..85305323e 100644 --- a/apps/desktop/src/features/workspace/Workspace.tsx +++ b/apps/desktop/src/features/workspace/Workspace.tsx @@ -4,6 +4,7 @@ import { RoleSwitcher } from "./RoleSwitcher"; import { SectionRoadmap } from "./SectionRoadmap"; import { GrooveMap } from "./GrooveMap"; import { PracticeProgress } from "./PracticeProgress"; +import { FirstTagCallout } from "./FirstTagCallout"; import { fillRangeCopy, firstRangeSqueeze } from "./firstRangeSqueeze"; import { createTranslator, detectPreferredLocale } from "../../i18n"; import { generateCueSheetCsv, generateChartSummaryJson, generateMetadataHandoffJson, sanitizeFilename } from "../../lib/export"; @@ -91,8 +92,12 @@ const SongStructure = memo(function SongStructure({ sections, t }: { sections: R data-testid="song-structure-grid" style={{ gridTemplateColumns: `repeat(${Math.max(1, sections.length)}, minmax(8rem, 1fr))` }} > - {sections.map((section) => ( - + {sections.map((section, sectionIndex) => ( + {section.label} · {formatTimelineTime(section.timeRange.start)}–{formatTimelineTime(section.timeRange.end)} @@ -353,6 +358,8 @@ export function Workspace({ song, sourceBootstrap = null, onSongUpdate }: Worksp + + diff --git a/apps/desktop/src/features/workspace/firstTag.inherited-metadata.test.ts b/apps/desktop/src/features/workspace/firstTag.inherited-metadata.test.ts new file mode 100644 index 000000000..8da6b41af --- /dev/null +++ b/apps/desktop/src/features/workspace/firstTag.inherited-metadata.test.ts @@ -0,0 +1,77 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstTag } from "./firstTag"; + +function songWithTag() { + const song = createDemoRehearsalSong(); + const tag = structuredClone(song.sections[0]!); + tag.id = "tag-own"; + tag.label = "tag"; + tag.timeRange = { start: 200, end: 208 }; + song.sections = [tag]; + return { song, tag }; +} + +describe("resolveFirstTag inherited metadata", () => { + it("rejects a song or section whose required metadata is inherited", () => { + const { song, tag } = songWithTag(); + const inheritedSong = Object.create({ sections: song.sections }) as typeof song; + expect(resolveFirstTag(inheritedSong)).toBeNull(); + + const inheritedSection = Object.create(tag) as typeof tag; + song.sections = [inheritedSection]; + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("rejects inherited timing fields", () => { + const { song, tag } = songWithTag(); + tag.timeRange = Object.create({ start: 200, end: 208 }) as typeof tag.timeRange; + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("contains exceptions from own runtime accessors instead of trusting them", () => { + const { song, tag } = songWithTag(); + Object.defineProperty(tag, "label", { + configurable: true, + enumerable: true, + get() { + throw new Error("hostile tag label getter"); + } + }); + + expect(() => resolveFirstTag(song)).not.toThrow(); + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("does not treat own accessors as stable tag identity authority", () => { + const { song, tag } = songWithTag(); + Object.defineProperty(tag, "id", { + configurable: true, + enumerable: true, + get() { + return "tag-own"; + } + }); + + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("does not let inherited role or graph metadata establish the holding part", () => { + const { song, tag } = songWithTag(); + const role = tag.roles[0]!; + const node = tag.partGraph[0]!; + tag.roles = [Object.create(role) as typeof role]; + tag.partGraph = [Object.create(node) as typeof node]; + + const resolved = resolveFirstTag(song); + expect(resolved?.section.id).toBe("tag-own"); + expect(resolved?.holdingRole).toBeNull(); + }); + + it("rejects arrays masquerading as section records", () => { + const { song, tag } = songWithTag(); + const arraySection = Object.assign([], tag) as unknown as typeof tag; + song.sections = [arraySection]; + expect(resolveFirstTag(song)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstTag.test.ts b/apps/desktop/src/features/workspace/firstTag.test.ts new file mode 100644 index 000000000..d3d3c643c --- /dev/null +++ b/apps/desktop/src/features/workspace/firstTag.test.ts @@ -0,0 +1,206 @@ +import { describe, expect, it } from "vitest"; +import { MAX_SECTION_TIME_SECONDS, createDemoRehearsalSong } from "@bandscope/shared-types"; +import { formatTagTime, resolveFirstTag } from "./firstTag"; + +function withTagSection( + overrides: { + id?: string; + start?: number; + end?: number; + roleId?: string; + roleName?: string; + priority?: "low" | "medium" | "high"; + isActive?: boolean; + } = {} +) { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + const tag = structuredClone(verse); + tag.id = overrides.id ?? "tag-1"; + tag.label = "tag"; + tag.timeRange = { start: overrides.start ?? 200, end: overrides.end ?? 208 }; + const roleId = overrides.roleId ?? "lead-vocal"; + tag.roles = [ + { + ...verse.roles[0]!, + id: roleId, + name: overrides.roleName ?? "Lead Vocal", + rehearsalPriority: overrides.priority ?? "high" + } + ]; + tag.partGraph = [ + { + role_id: roleId, + is_active: overrides.isActive ?? true, + handoff_to: [], + handoff_from: [] + } + ]; + song.sections = [verse, tag]; + return song; +} + +describe("resolveFirstTag", () => { + it("returns null when the demo song has no labeled tag", () => { + expect(resolveFirstTag(createDemoRehearsalSong())).toBeNull(); + expect(formatTagTime(Number.NaN)).toBe("0:00"); + expect(formatTagTime(-4)).toBe("0:00"); + }); + + it("does not invent a tag from a verse, chorus, intro, outro, pickup, stop, or handoff", () => { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + const chorus = structuredClone(verse); + chorus.id = "chorus-1"; + chorus.label = "chorus"; + chorus.timeRange = { start: 30, end: 46 }; + const intro = structuredClone(verse); + intro.id = "intro-1"; + intro.label = "intro"; + intro.timeRange = { start: 0, end: 8 }; + const outro = structuredClone(verse); + outro.id = "outro-1"; + outro.label = "outro"; + outro.timeRange = { start: 180, end: 196 }; + const pickup = structuredClone(verse); + pickup.id = "pickup-1"; + pickup.label = "pickup"; + pickup.timeRange = { start: 8, end: 10 }; + const stop = structuredClone(verse); + stop.id = "stop-1"; + stop.label = "stop"; + stop.timeRange = { start: 18, end: 19 }; + const handoff = structuredClone(verse); + handoff.id = "handoff-1"; + handoff.label = "handoff"; + handoff.timeRange = { start: 22, end: 24 }; + song.sections = [intro, verse, pickup, stop, chorus, handoff, outro]; + + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("does not treat the last unlabeled section as a tag", () => { + const song = createDemoRehearsalSong(); + song.sections[0]!.timeRange = { start: 200, end: 208 }; + expect(song.sections[0]!.label).toBe("verse"); + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("picks the earliest labeled tag and the part that holds it", () => { + const song = withTagSection({ start: 200, end: 208 }); + const tag = resolveFirstTag(song); + + expect(tag?.section.id).toBe("tag-1"); + expect(tag?.holdingRole?.id).toBe("lead-vocal"); + expect(tag?.atSeconds).toBe(200); + expect(formatTagTime(tag?.atSeconds ?? -1)).toBe("3:20"); + }); + + it("prefers the earlier of two labeled tags", () => { + const song = withTagSection({ id: "tag-late", start: 220, end: 228 }); + const verse = song.sections[0]!; + const earlier = structuredClone(song.sections[1]!); + earlier.id = "tag-early"; + earlier.timeRange = { start: 200, end: 208 }; + earlier.roles = [ + { + ...verse.roles[0]!, + id: "bass-guitar", + name: "Bass Guitar", + rehearsalPriority: "medium" + } + ]; + earlier.partGraph = [ + { + role_id: "bass-guitar", + is_active: true, + handoff_to: [], + handoff_from: [] + } + ]; + song.sections = [song.sections[0]!, song.sections[1]!, earlier]; + + const tag = resolveFirstTag(song); + expect(tag?.section.id).toBe("tag-early"); + expect(tag?.holdingRole?.id).toBe("bass-guitar"); + expect(tag?.atSeconds).toBe(200); + }); + + it("breaks same-time tag ties with locale-independent id ordering", () => { + const song = withTagSection({ id: "ä-tag", start: 200, end: 208 }); + const asciiTag = structuredClone(song.sections[1]!); + asciiTag.id = "z-tag"; + song.sections = [song.sections[0]!, song.sections[1]!, asciiTag]; + + expect(resolveFirstTag(song)?.section.id).toBe("z-tag"); + }); + + it("breaks equal-priority role ties with locale-independent id ordering", () => { + const song = withTagSection({ roleId: "ä-role", roleName: "Umlaut role", priority: "high" }); + const tag = song.sections[1]!; + const asciiRole = { ...tag.roles[0]!, id: "z-role", name: "ASCII role" }; + tag.roles = [tag.roles[0]!, asciiRole]; + tag.partGraph = [ + { role_id: "ä-role", is_active: true, handoff_to: [], handoff_from: [] }, + { role_id: "z-role", is_active: true, handoff_to: [], handoff_from: [] } + ]; + + expect(resolveFirstTag(song)?.holdingRole?.id).toBe("z-role"); + }); + + it("keeps a band-wide last line when no active ranked role holds it", () => { + const song = withTagSection({ isActive: false }); + const tag = resolveFirstTag(song); + expect(tag?.section.id).toBe("tag-1"); + expect(tag?.holdingRole).toBeNull(); + expect(tag?.atSeconds).toBe(200); + }); + + it("skips a tag whose rehearsal window is unbounded", () => { + const song = withTagSection({ start: Number.NaN, end: 208 }); + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("skips a tag whose end precedes its start", () => { + const song = withTagSection({ start: 208, end: 200 }); + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("skips a zero-length tag window", () => { + const song = withTagSection({ start: 200, end: 200 }); + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("skips a tag whose endpoint overflows the shared timing bound", () => { + const song = withTagSection({ + start: MAX_SECTION_TIME_SECONDS, + end: MAX_SECTION_TIME_SECONDS + 1 + }); + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("returns null for a non-object song root", () => { + expect(resolveFirstTag(null as never)).toBeNull(); + }); + + it("returns null when the runtime section collection is sparse", () => { + const song = withTagSection(); + const sparseSections: typeof song.sections = new Array(2); + sparseSections[1] = song.sections[1]!; + song.sections = sparseSections; + expect(resolveFirstTag(song)).toBeNull(); + }); + + it("keeps the last line band-wide when role identities are duplicated", () => { + const song = withTagSection(); + const role = song.sections[1]!.roles[0]!; + song.sections[1]!.roles = [role, { ...role }]; + song.sections[1]!.partGraph = [ + { role_id: role.id, is_active: true, handoff_to: [], handoff_from: [] }, + { role_id: role.id, is_active: true, handoff_to: [], handoff_from: [] } + ]; + const tag = resolveFirstTag(song); + expect(tag?.section.id).toBe("tag-1"); + expect(tag?.holdingRole).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstTag.ts b/apps/desktop/src/features/workspace/firstTag.ts new file mode 100644 index 000000000..ccc59d89b --- /dev/null +++ b/apps/desktop/src/features/workspace/firstTag.ts @@ -0,0 +1,238 @@ +import { + MAX_SECTION_TIME_SECONDS, + type RehearsalRole, + type RehearsalSection, + type RehearsalSong +} from "@bandscope/shared-types"; + +const PRIORITY_RANK = { high: 0, medium: 1, low: 2 } as const; + +/** Tonight's first labeled tag: the earliest last-line ending and the part that holds it. */ +export type FirstTag = { + section: RehearsalSection; + holdingRole: RehearsalRole | null; + atSeconds: number; +}; + +/** Format a non-negative tag time as m:ss for rehearsal copy. */ +export function formatTagTime(totalSeconds: number): string { + const safeSeconds = Number.isFinite(totalSeconds) && totalSeconds >= 0 ? totalSeconds : 0; + const minutes = Math.floor(safeSeconds / 60); + const seconds = Math.floor(safeSeconds % 60) + .toString() + .padStart(2, "0"); + return `${minutes}:${seconds}`; +} + +/** Compare opaque ids by Unicode code units so tie-breaking never depends on host locale. */ +function compareStableId(left: string, right: string): number { + if (left < right) { + return -1; + } + if (left > right) { + return 1; + } + return 0; +} + +/** Return whether an untrusted runtime value can be inspected as a record. */ +function isRuntimeObject(value: unknown): value is object { + return value !== null && typeof value === "object" && !Array.isArray(value); +} + +/** Return whether a runtime record owns a stable data property rather than inherited/accessor state. */ +function hasOwnData(value: object, key: PropertyKey): boolean { + const descriptor = Object.getOwnPropertyDescriptor(value, key); + return descriptor !== undefined && Object.prototype.hasOwnProperty.call(descriptor, "value"); +} + +/** Return whether every numeric index is an own data element in a bounded runtime array. */ +function isDenseRuntimeArray(value: unknown): value is unknown[] { + if (!Array.isArray(value)) { + return false; + } + const length = Number(value.length); + if (!Number.isSafeInteger(length) || length < 0 || length > 0xffffffff) { + return false; + } + for (let index = 0; index < length; index += 1) { + if (!hasOwnData(value, index)) { + return false; + } + } + return true; +} + +/** Return true when the role has safe owned identity/copy and ranked rehearsal priority. */ +function hasRankedPriority(role: RehearsalRole): boolean { + return ( + hasOwnData(role, "id") && + typeof role.id === "string" && + role.id.trim().length > 0 && + hasOwnData(role, "name") && + typeof role.name === "string" && + role.name.trim().length > 0 && + hasOwnData(role, "rehearsalPriority") && + Object.prototype.hasOwnProperty.call(PRIORITY_RANK, role.rehearsalPriority) + ); +} + +/** Return whether a section owns a bounded, positive-length integer rehearsal window. */ +function hasBoundedTimeRange(section: RehearsalSection): boolean { + if (!hasOwnData(section, "timeRange")) { + return false; + } + const timeRange = section.timeRange as Partial | null; + if ( + !isRuntimeObject(timeRange) || + !hasOwnData(timeRange, "start") || + !hasOwnData(timeRange, "end") + ) { + return false; + } + + const start = timeRange.start ?? -1; + const end = timeRange.end ?? -1; + return ( + Number.isInteger(start) && + start >= 0 && + start <= MAX_SECTION_TIME_SECONDS && + Number.isInteger(end) && + end > start && + end <= MAX_SECTION_TIME_SECONDS + ); +} + +/** Return safe identities that appear more than once in one section-local collection. */ +function repeatedIds(ids: string[]): Set { + const seen = new Set(); + const repeated = new Set(); + for (const id of ids) { + if (seen.has(id)) { + repeated.add(id); + } else { + seen.add(id); + } + } + return repeated; +} + +/** Prefer the highest-priority ranked role, then a locale-independent stable id order. */ +function pickHighestPriorityRole(roles: RehearsalRole[]): RehearsalRole | null { + if (roles.length === 0) { + return null; + } + return ( + [...roles].sort((left, right) => { + const rankDelta = PRIORITY_RANK[left.rehearsalPriority] - PRIORITY_RANK[right.rehearsalPriority]; + if (rankDelta !== 0) { + return rankDelta; + } + return compareStableId(left.id, right.id); + })[0] ?? null + ); +} + +/** Return ranked roles whose unique graph node is explicitly active. */ +function rankedActiveRoles(section: RehearsalSection): RehearsalRole[] { + if ( + !hasOwnData(section, "roles") || + !hasOwnData(section, "partGraph") || + !isDenseRuntimeArray(section.roles) || + !isDenseRuntimeArray(section.partGraph) + ) { + return []; + } + + const safeRoleIds = section.roles + .filter( + (role) => + isRuntimeObject(role) && + hasOwnData(role, "id") && + typeof role.id === "string" && + role.id.trim().length > 0 + ) + .map((role) => role.id); + const safeGraphRoleIds = section.partGraph + .filter( + (node) => + isRuntimeObject(node) && + hasOwnData(node, "role_id") && + typeof node.role_id === "string" && + node.role_id.trim().length > 0 + ) + .map((node) => node.role_id); + const repeatedRoleIds = repeatedIds(safeRoleIds); + const repeatedGraphRoleIds = repeatedIds(safeGraphRoleIds); + const activeIds = new Set( + section.partGraph + .filter( + (node) => + isRuntimeObject(node) && + hasOwnData(node, "is_active") && + node.is_active === true && + hasOwnData(node, "role_id") && + typeof node.role_id === "string" && + node.role_id.trim().length > 0 && + !repeatedGraphRoleIds.has(node.role_id) + ) + .map((node) => node.role_id) + ); + + return section.roles.filter( + (role) => + isRuntimeObject(role) && + hasRankedPriority(role) && + !repeatedRoleIds.has(role.id) && + activeIds.has(role.id) + ); +} + +/** Resolve a tag after the runtime root has passed its structural boundary checks. */ +function resolveSafeFirstTag(song: RehearsalSong): FirstTag | null { + if ( + !isRuntimeObject(song) || + !hasOwnData(song, "sections") || + !isDenseRuntimeArray(song.sections) + ) { + return null; + } + + const tagSections = song.sections + .filter( + (section) => + isRuntimeObject(section) && + hasOwnData(section, "label") && + section.label === "tag" && + hasOwnData(section, "id") && + typeof section.id === "string" && + section.id.trim().length > 0 && + hasBoundedTimeRange(section) + ) + .sort((left, right) => { + if (left.timeRange.start !== right.timeRange.start) { + return left.timeRange.start - right.timeRange.start; + } + return compareStableId(left.id, right.id); + }); + + const section = tagSections[0]; + if (!section) { + return null; + } + + return { + section, + holdingRole: pickHighestPriorityRole(rankedActiveRoles(section)), + atSeconds: section.timeRange.start + }; +} + +/** Return the first labeled tag, or null when untrusted runtime metadata cannot be read safely. */ +export function resolveFirstTag(song: RehearsalSong): FirstTag | null { + try { + return resolveSafeFirstTag(song); + } catch { + return null; + } +} diff --git a/apps/desktop/src/i18n/index.test.ts b/apps/desktop/src/i18n/index.test.ts index dc49a0a25..b00a18761 100644 --- a/apps/desktop/src/i18n/index.test.ts +++ b/apps/desktop/src/i18n/index.test.ts @@ -1,5 +1,5 @@ import { describe, it, expect, vi, afterEach } from "vitest"; -import { createTranslator, detectPreferredLocale } from "./index"; +import { createTranslator, detectPreferredLocale, translateSectionFormLabel } from "./index"; import koCommon from "../locales/ko/common.json"; describe("i18n", () => { @@ -75,4 +75,51 @@ describe("i18n", () => { } }); }); + + describe("translateSectionFormLabel", () => { + it("localizes every supported section form label for Korean rehearsal copy", () => { + expect( + [ + "intro", + "verse", + "pre-chorus", + "chorus", + "bridge", + "outro", + "tag", + "pickup", + "stop", + "handoff" + ].map((label) => translateSectionFormLabel("ko", label as never)) + ).toEqual([ + "인트로", + "벌스", + "프리코러스", + "코러스", + "브리지", + "아웃트로", + "태그", + "픽업", + "스톱", + "핸드오프" + ]); + }); + + it("preserves every supported English section form label", () => { + expect(translateSectionFormLabel("en", "tag")).toBe("tag"); + expect(translateSectionFormLabel("en", "outro")).toBe("outro"); + }); + + it("does not treat inherited object keys as localized section labels", () => { + const inheritedKey = "toString" as never; + expect(translateSectionFormLabel("ko", inheritedKey)).toBe("toString"); + }); + + it("keeps Korean first-tag next-action copy particle-safe", () => { + const t = createTranslator("ko"); + expect(t("firstTagOpenAction")).toBe("{at} {role} 태그 위치 열기"); + expect(t("firstTagBody")).toBe("{at} {section}에서 {role} 파트가 마지막 한 줄을 잡습니다."); + expect(t("firstTagArmed")).toBe("{at}에서 {role} 파트와 함께 마지막 한 줄을 잡으세요. 같이 끝내세요."); + }); + }); }); diff --git a/apps/desktop/src/i18n/index.ts b/apps/desktop/src/i18n/index.ts index 1a9f471f0..352eff65e 100644 --- a/apps/desktop/src/i18n/index.ts +++ b/apps/desktop/src/i18n/index.ts @@ -1,3 +1,4 @@ +import type { SectionFormLabel } from "@bandscope/shared-types"; import enCommon from "../locales/en/common.json"; import koCommon from "../locales/ko/common.json"; @@ -11,13 +12,46 @@ const dictionaries = { ko: koCommon } as const; -/** Documented. */ +const sectionFormLabels: Readonly>>> = { + en: { + intro: "intro", + verse: "verse", + "pre-chorus": "pre-chorus", + chorus: "chorus", + bridge: "bridge", + outro: "outro", + tag: "tag", + pickup: "pickup", + stop: "stop", + handoff: "handoff" + }, + ko: { + intro: "인트로", + verse: "벌스", + "pre-chorus": "프리코러스", + chorus: "코러스", + bridge: "브리지", + outro: "아웃트로", + tag: "태그", + pickup: "픽업", + stop: "스톱", + handoff: "핸드오프" + } +}; + +/** Create a locale-aware translation lookup that falls back to English copy. */ export function createTranslator(locale: Locale = "en") { return function t(key: TranslationKey): string { return dictionaries[locale][key] ?? dictionaries.en[key]; }; } +/** Return the localized display label for a supported rehearsal section form. */ +export function translateSectionFormLabel(locale: Locale, label: SectionFormLabel): string { + const labels = sectionFormLabels[locale] as Readonly>; + return Object.prototype.hasOwnProperty.call(labels, label) ? labels[label] : String(label); +} + /** Documented. */ export function detectPreferredLocale(): Locale { if (typeof navigator !== "undefined" && navigator.language?.toLowerCase().startsWith("ko")) { diff --git a/apps/desktop/src/locales/en/common.json b/apps/desktop/src/locales/en/common.json index d803a765e..ad377f804 100644 --- a/apps/desktop/src/locales/en/common.json +++ b/apps/desktop/src/locales/en/common.json @@ -149,6 +149,14 @@ "practiceProgressLabel": "Practice Progress", "decreasePracticeProgressLabel": "Decrease progress", "increasePracticeProgressLabel": "Increase progress", + "firstTagLabel": "Tonight's first tag", + "firstTagOpenAction": "Open {role} tag at {at}", + "firstTagOpenActionBand": "Open the first tag at {at}", + "firstTagBody": "{role} holds the {section} at {at}.", + "firstTagBodyBand": "The band catches the {section} at {at}.", + "firstTagArmed": "Catch the last line with {role} at {at}. End together.", + "firstTagArmedBand": "Catch the last line at {at}. End together.", + "firstTagUnavailable": "No tag yet. Stay on tonight's map until the last line is labeled.", "workspaceFirstRangeTitle": "Tonight's first range", "workspaceFirstRangeCheck": "{roleName} sits {lowestNote}–{highestNote} in {sectionLabel}. Check that span on your instrument before the {sectionLabel}.", "workspaceFirstRangeClash": "{roleName} sits {lowestNote}–{highestNote} in {sectionLabel}. Hear that clash on your instrument before the {sectionLabel}.", diff --git a/apps/desktop/src/locales/ko/common.json b/apps/desktop/src/locales/ko/common.json index 0f6c6c66d..996b930cf 100644 --- a/apps/desktop/src/locales/ko/common.json +++ b/apps/desktop/src/locales/ko/common.json @@ -149,6 +149,14 @@ "practiceProgressLabel": "연습 진척도", "decreasePracticeProgressLabel": "진척도 감소", "increasePracticeProgressLabel": "진척도 증가", + "firstTagLabel": "오늘 첫 태그", + "firstTagOpenAction": "{at} {role} 태그 위치 열기", + "firstTagOpenActionBand": "{at} 첫 태그 위치 열기", + "firstTagBody": "{at} {section}에서 {role} 파트가 마지막 한 줄을 잡습니다.", + "firstTagBodyBand": "밴드가 {at} {section}에서 마지막 한 줄을 잡습니다.", + "firstTagArmed": "{at}에서 {role} 파트와 함께 마지막 한 줄을 잡으세요. 같이 끝내세요.", + "firstTagArmedBand": "{at}에서 마지막 한 줄을 잡으세요. 같이 끝내세요.", + "firstTagUnavailable": "아직 태그가 없습니다. 마지막 한 줄이 표시될 때까지 오늘 지도에 머무르세요.", "workspaceFirstRangeTitle": "오늘 먼저 볼 음역", "workspaceFirstRangeCheck": "{sectionLabel}의 {roleName}은 {lowestNote}–{highestNote}입니다. {sectionLabel} 들어가기 전에 그 음역을 악기로 확인해 보세요.", "workspaceFirstRangeClash": "{sectionLabel}의 {roleName}은 {lowestNote}–{highestNote}이고 다른 파트와 겹칩니다. {sectionLabel} 들어가기 전에 그 충돌을 악기로 들어 보세요.", diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.ts index f1db6f2b8..e3a192297 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -25,7 +25,9 @@ export default defineConfig({ "src/i18n/index.ts", "src/features/score/ScoreViewer.tsx", "src/features/score/ScoreView.tsx", - "src/features/score/scoreStorage.ts" + "src/features/score/scoreStorage.ts", + "src/features/workspace/firstTag.ts", + "src/features/workspace/FirstTagCallout.tsx" ], thresholds: { lines: 90, diff --git a/docs/design-system/component-contract.md b/docs/design-system/component-contract.md index 22602c313..b9a2e81c9 100644 --- a/docs/design-system/component-contract.md +++ b/docs/design-system/component-contract.md @@ -32,6 +32,7 @@ The authoritative Figma view is `31 Component Contract Catalog`. This file mirro | Section Roadmap Card | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-402 | `apps/desktop/src/features/workspace/SectionRoadmap.tsx` | Use `song`, `activeRole`, and optional `onSongUpdate`; avoid rebuilding its internal card layout. | | Song Structure Timeline | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-457 | `apps/desktop/src/features/workspace/Workspace.tsx` | Feature-local `SongStructure({ sections, t })` memo component; not exported. | | Groove Map | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-526 | `apps/desktop/src/features/workspace/GrooveMap.tsx` | Use `notes?: TranscriptionNote[]` and `isLoading?: boolean`; preserve scrollable region semantics and note labels. | +| First Tag Callout | workspace next-action pattern | `apps/desktop/src/features/workspace/FirstTagCallout.tsx` | Name the holding part when an active graph node corroborates it, the labeled `tag` start, and the time. Do not invent a last line from `intro`, `verse`, `chorus`, `outro`, `pickup`, `stop`, `handoff`, or the last unlabeled section. Open scrolls the renderer-owned song-structure section. Keep the unavailable state guidance-only. Distinct from first-outro, first-chorus, first-stop, and first-handoff work. | | Source Control Stack | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-655 | `apps/desktop/src/App.tsx` | Feature-local source controls for local audio, YouTube URL import, project actions, and Start Analysis; keep before metrics at 375px. | | Export Action Group | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=19-731 | `apps/desktop/src/features/workspace/Workspace.tsx` | Feature-local export buttons call `handleExportCueSheet`, `handleExportChart`, and `handleExportHandoff`. | | Workspace State Matrix | https://www.figma.com/design/zthWmqfNKUgJBECvv002Qk/Bandscope-Design-System-v1?node-id=99-560 | `apps/desktop/src/features/workspace/WorkspaceStates.tsx`, `apps/desktop/src/App.tsx` | Whole-workspace empty, loading, error, and ready state routing; use before changing `renderWorkspaceState()`. | diff --git a/docs/doctoring/reduced-motion-first-tag-navigation.md b/docs/doctoring/reduced-motion-first-tag-navigation.md new file mode 100644 index 000000000..f0da4b1c0 --- /dev/null +++ b/docs/doctoring/reduced-motion-first-tag-navigation.md @@ -0,0 +1,14 @@ +# Reduced-motion first-tag navigation + +Workspace map navigation for tonight's first tag follows the operating-system reduced-motion preference. + +When `prefers-reduced-motion: reduce` matches, `FirstTagCallout` scrolls the renderer-owned song-structure section with `behavior: "auto"`. Otherwise it uses `behavior: "smooth"`. + +This is a presentation contract only. Tag resolution and analysis-id isolation stay unchanged. + +## Security Notes + +- Untrusted input: song, section, time-range, role, and section-local graph metadata are runtime data; inherited properties and arrays masquerading as record metadata are not authority. +- Trust boundary: tag resolution accepts required fields only when the inspected record owns them, while renderer-owned song-structure children remain the only navigation targets; analysis `section.id` is never DOM-ID authority. +- Mitigations: runtime record guards reject arrays, dense collections require own indexed elements, required metadata fields must be own properties, `matchMedia` is read-only, scroll targets come from renderer child index, and copy interpolation runs once. +- Test points: inherited song/section/timing/role/graph metadata is rejected, array-backed section records are rejected, reduced-motion scroll uses `auto`, and default motion uses `smooth`.
{section.label} · {formatTimelineTime(section.timeRange.start)}–{formatTimelineTime(section.timeRange.end)}