diff --git a/.Jules/palette.md b/.Jules/palette.md deleted file mode 100644 index 5c1c16989..000000000 --- a/.Jules/palette.md +++ /dev/null @@ -1,39 +0,0 @@ -## 2024-05-18 - Added focus visible styles for keyboard navigation -**Learning:** Interactive inline buttons (like the chord editor) and scrollable regions with `tabIndex={0}` do not automatically get focus visible styles, meaning keyboard users tabbing through won't know they are focused on them. Unlike central ` + + ); +} diff --git a/apps/desktop/src/features/workspace/FirstPartHandoffCallout.workspace-scope.test.tsx b/apps/desktop/src/features/workspace/FirstPartHandoffCallout.workspace-scope.test.tsx new file mode 100644 index 000000000..1d193cba0 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstPartHandoffCallout.workspace-scope.test.tsx @@ -0,0 +1,54 @@ +import { fireEvent, render, screen } from "@testing-library/react"; +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it, vi } from "vitest"; +import { FirstPartHandoffCallout } from "./FirstPartHandoffCallout"; + +describe("FirstPartHandoffCallout workspace scope", () => { + it("opens the song-structure renderer owned by the current workspace", () => { + const firstSong = createDemoRehearsalSong(); + const secondSong = createDemoRehearsalSong(); + secondSong.id = "second-workspace-song"; + + const { container } = render( + <> +
+ +
+
+
+
+
+ +
+
+
+
+ + ); + + const targets = container.querySelectorAll('[data-section-index="0"]'); + expect(targets).toHaveLength(2); + const firstScrollIntoView = vi.fn(); + const secondScrollIntoView = vi.fn(); + Object.defineProperty(targets[0]!, "scrollIntoView", { + configurable: true, + value: firstScrollIntoView + }); + Object.defineProperty(targets[1]!, "scrollIntoView", { + configurable: true, + value: secondScrollIntoView + }); + + const actions = screen.getAllByRole("button", { + name: "Open Bass Guitar handoff at 0:10" + }); + expect(actions).toHaveLength(2); + fireEvent.click(actions[1]!); + + expect(firstScrollIntoView).not.toHaveBeenCalled(); + expect(secondScrollIntoView).toHaveBeenCalledWith({ + block: "nearest", + behavior: "smooth" + }); + }); +}); diff --git a/apps/desktop/src/features/workspace/Workspace.test.tsx b/apps/desktop/src/features/workspace/Workspace.test.tsx index 7837bf80e..79b56b4da 100644 --- a/apps/desktop/src/features/workspace/Workspace.test.tsx +++ b/apps/desktop/src/features/workspace/Workspace.test.tsx @@ -326,4 +326,32 @@ describe("Workspace", () => { expect(screen.getByText("합주 우선순위")).toBeTruthy(); expect(screen.getByText("역할과 화성")).toBeTruthy(); }); + + it("names tonight's first part handoff as workspace navigation", () => { + setNavigatorLanguage("en-US"); + const song = createDemoRehearsalSong(); + + render(); + + const target = screen.getByTestId("song-structure-grid").children.item(0); + expect(target).toBeTruthy(); + const scrollIntoView = vi.fn(); + Object.defineProperty(target!, "scrollIntoView", { + configurable: true, + value: scrollIntoView + }); + + expect( + screen.getByText("Bass Guitar still hands off to Lead Vocal in the verse at 0:10.") + ).toBeTruthy(); + const action = screen.getByRole("button", { + name: "Open Bass Guitar handoff at 0:10" + }); + expect(action).toBeTruthy(); + fireEvent.click(action); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + expect( + screen.getByText(/Lock that pass from Bass Guitar to Lead Vocal at 0:10 before the room starts./) + ).toBeTruthy(); + }); }); diff --git a/apps/desktop/src/features/workspace/Workspace.tsx b/apps/desktop/src/features/workspace/Workspace.tsx index d44e20777..e7a7c4c27 100644 --- a/apps/desktop/src/features/workspace/Workspace.tsx +++ b/apps/desktop/src/features/workspace/Workspace.tsx @@ -1,5 +1,6 @@ import { useState, useMemo, memo, type MouseEvent } from "react"; import { parseProjectBootstrapSummary, type ProjectBootstrapSummary, type RehearsalSong, type RehearsalRole } from "@bandscope/shared-types"; +import { FirstPartHandoffCallout } from "./FirstPartHandoffCallout"; import { RoleSwitcher } from "./RoleSwitcher"; import { SectionRoadmap } from "./SectionRoadmap"; import { GrooveMap } from "./GrooveMap"; @@ -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/firstPartHandoff.inherited-metadata.test.ts b/apps/desktop/src/features/workspace/firstPartHandoff.inherited-metadata.test.ts new file mode 100644 index 000000000..69f399caf --- /dev/null +++ b/apps/desktop/src/features/workspace/firstPartHandoff.inherited-metadata.test.ts @@ -0,0 +1,102 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstPartHandoff } from "./firstPartHandoff"; + +function songWithPartHandoff() { + const song = createDemoRehearsalSong(); + const section = structuredClone(song.sections[0]!); + section.id = "handoff-own"; + section.roles = [ + { + ...section.roles[0]!, + id: "bass-guitar", + name: "Bass Guitar", + rehearsalPriority: "high" + }, + { + ...section.roles[2]!, + id: "lead-vocal", + name: "Lead Vocal", + rehearsalPriority: "medium" + } + ]; + section.partGraph = [ + { role_id: "bass-guitar", is_active: true, handoff_to: ["lead-vocal"], handoff_from: [] }, + { role_id: "lead-vocal", is_active: true, handoff_to: [], handoff_from: ["bass-guitar"] } + ]; + song.sections = [section]; + return { song, section }; +} + +describe("resolveFirstPartHandoff inherited metadata", () => { + it("rejects a song or section whose required metadata is inherited", () => { + const { song, section } = songWithPartHandoff(); + const inheritedSong = Object.create({ sections: song.sections }) as typeof song; + expect(resolveFirstPartHandoff(inheritedSong)).toBeNull(); + + const inheritedSection = Object.create(section) as typeof section; + song.sections = [inheritedSection]; + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); + + it("rejects inherited timing fields", () => { + const { song, section } = songWithPartHandoff(); + section.timeRange = Object.create({ start: 10, end: 30 }) as typeof section.timeRange; + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); + + it("contains exceptions from own runtime accessors instead of trusting them", () => { + const { song, section } = songWithPartHandoff(); + Object.defineProperty(section.partGraph[0]!, "handoff_to", { + configurable: true, + enumerable: true, + get() { + throw new Error("hostile handoff_to getter"); + } + }); + + expect(() => resolveFirstPartHandoff(song)).not.toThrow(); + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); + + it("does not treat own accessors as stable section identity authority", () => { + const { song, section } = songWithPartHandoff(); + Object.defineProperty(section, "id", { + configurable: true, + enumerable: true, + get() { + return "handoff-own"; + } + }); + + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); + + it("does not let inherited handoff edges establish the named pass", () => { + const { song, section } = songWithPartHandoff(); + const inheritedNode = Object.create({ + handoff_to: ["lead-vocal"] + }) as (typeof section.partGraph)[0]; + Object.defineProperties(inheritedNode, { + role_id: { configurable: true, enumerable: true, value: "bass-guitar" }, + is_active: { configurable: true, enumerable: true, value: true }, + handoff_from: { configurable: true, enumerable: true, value: [] } + }); + section.partGraph = [inheritedNode, section.partGraph[1]!]; + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); + + it("does not let inherited role or graph metadata establish the holding part", () => { + const { song, section } = songWithPartHandoff(); + const node = section.partGraph[0]!; + section.partGraph = [Object.create(node) as typeof node, section.partGraph[1]!]; + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); + + it("rejects arrays masquerading as section records", () => { + const { song, section } = songWithPartHandoff(); + const arraySection = Object.assign([], section) as unknown as typeof section; + song.sections = [arraySection]; + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstPartHandoff.test.ts b/apps/desktop/src/features/workspace/firstPartHandoff.test.ts new file mode 100644 index 000000000..b27048379 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstPartHandoff.test.ts @@ -0,0 +1,284 @@ +import { describe, expect, it } from "vitest"; +import { MAX_SECTION_TIME_SECONDS, createDemoRehearsalSong } from "@bandscope/shared-types"; +import { formatPartHandoffTime, resolveFirstPartHandoff } from "./firstPartHandoff"; + +function withHandoffSection( + overrides: { + id?: string; + start?: number; + end?: number; + label?: "intro" | "verse" | "pre-chorus" | "chorus" | "bridge" | "outro" | "tag" | "pickup" | "stop" | "handoff"; + givingId?: string; + givingName?: string; + receivingId?: string; + receivingName?: string; + givingPriority?: "low" | "medium" | "high"; + receivingPriority?: "low" | "medium" | "high"; + givingActive?: boolean; + receivingActive?: boolean; + handoffTo?: string[]; + handoffFrom?: string[]; + } = {} +) { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + const section = structuredClone(verse); + section.id = overrides.id ?? "verse-handoff"; + section.label = overrides.label ?? "verse"; + section.groove = "Straight eighths with a late snare feel"; + section.timeRange = { start: overrides.start ?? 10, end: overrides.end ?? 30 }; + const givingId = overrides.givingId ?? "bass-guitar"; + const receivingId = overrides.receivingId ?? "lead-vocal"; + section.roles = [ + { + ...verse.roles[0]!, + id: givingId, + name: overrides.givingName ?? "Bass Guitar", + rehearsalPriority: overrides.givingPriority ?? "high", + cue: { kind: "transition", value: "Hold through the pickup before the downbeat." }, + range: { lowestNote: "C#2", highestNote: "E3" }, + setupNote: "Keep the attack short so the verse breathes.", + simplification: "Stay on roots if the chorus entrance gets muddy.", + overlapWarnings: ["Density warning: competing with Keyboard Left Hand in low register."], + harmony: { chord: "C#m7", functionLabel: "vi pedal anchor", source: "model" }, + harmonicExplanation: "The bass holds the vi center.", + confidence: { level: "medium", source: "model", notes: "Watch the slide into the turnaround." }, + transpositionPlan: "If the singer drops to B minor, keep the shape a whole step lower.", + manualOverrides: [] + }, + { + ...verse.roles[2]!, + id: receivingId, + name: overrides.receivingName ?? "Lead Vocal", + rehearsalPriority: overrides.receivingPriority ?? "medium", + cue: { kind: "lyric", value: "city lights" }, + range: { lowestNote: "G#3", highestNote: "C#5" }, + setupNote: "Watch the breath before the last line of the verse.", + simplification: "Keep the sustained note centered.", + overlapWarnings: ["Melodic overlap: competing with Keyboard 1 Right Hand."], + harmony: { chord: "C#m7", functionLabel: "vi melodic pull", source: "model" }, + harmonicExplanation: "The melody leans on the ninth over vi.", + confidence: { level: "high", source: "user", notes: "Singer confirmed the pickup phrasing." }, + transpositionPlan: "Move the section down a whole step.", + manualOverrides: [] + } + ]; + section.partGraph = [ + { + role_id: givingId, + is_active: overrides.givingActive ?? true, + handoff_to: overrides.handoffTo ?? [receivingId], + handoff_from: [] + }, + { + role_id: receivingId, + is_active: overrides.receivingActive ?? true, + handoff_to: [], + handoff_from: overrides.handoffFrom ?? [givingId] + } + ]; + song.sections = [section]; + return song; +} + +describe("resolveFirstPartHandoff", () => { + it("picks the demo song's earliest corroborated part handoff", () => { + const resolved = resolveFirstPartHandoff(createDemoRehearsalSong()); + expect(resolved?.section.id).toBe("verse-1"); + expect(resolved?.givingRole.id).toBe("bass-guitar"); + expect(resolved?.receivingRole.id).toBe("lead-vocal"); + expect(resolved?.givingName).toBe("Bass Guitar"); + expect(resolved?.receivingName).toBe("Lead Vocal"); + expect(resolved?.atSeconds).toBe(10); + expect(formatPartHandoffTime(resolved?.atSeconds ?? -1)).toBe("0:10"); + expect(formatPartHandoffTime(Number.NaN)).toBe("0:00"); + expect(formatPartHandoffTime(-4)).toBe("0:00"); + }); + + it("does not invent a part handoff from groove, cue, simplification, overlap, range, chords, function labels, setup notes, confirmed overrides, harmonic explanations, confidence notes, transposition plans, or a labeled handoff section", () => { + const song = withHandoffSection({ label: "handoff" }); + song.sections[0]!.partGraph[0]!.handoff_to = []; + song.sections[0]!.partGraph[1]!.handoff_from = []; + song.sections[0]!.groove = "Straight eighths with a late snare feel"; + song.sections[0]!.roles[0]!.simplification = "Stay on roots."; + song.sections[0]!.roles[0]!.setupNote = "Keep the attack short."; + song.sections[0]!.roles[0]!.cue = { kind: "transition", value: "Hold through the pickup." }; + song.sections[0]!.roles[0]!.range = { lowestNote: "C#2", highestNote: "E3" }; + song.sections[0]!.roles[0]!.overlapWarnings = ["Density warning."]; + song.sections[0]!.roles[0]!.harmony = { chord: "C#m7", functionLabel: "vi pedal anchor", source: "user" }; + song.sections[0]!.roles[0]!.harmonicExplanation = "The bass holds the vi center."; + song.sections[0]!.roles[0]!.transpositionPlan = "Drop a whole step."; + song.sections[0]!.roles[0]!.confidence = { + level: "high", + source: "user", + notes: "Bass Guitar hands off to Lead Vocal." + }; + song.sections[0]!.roles[0]!.manualOverrides = [ + { + field: "harmony", + value: { chord: "C#m11", functionLabel: "vi suspended lift", source: "user" }, + source: "user" + } + ]; + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); + + it("skips a one-sided outgoing pass that the receiving part does not corroborate", () => { + expect(resolveFirstPartHandoff(withHandoffSection({ handoffFrom: [] }))).toBeNull(); + }); + + it("skips a self-handoff", () => { + expect( + resolveFirstPartHandoff(withHandoffSection({ handoffTo: ["bass-guitar"], handoffFrom: ["bass-guitar"] })) + ).toBeNull(); + }); + + it("prefers the earlier of two corroborated handoffs", () => { + const song = withHandoffSection({ + id: "verse-late", + start: 40, + end: 56, + givingId: "keys-right", + givingName: "Keys", + receivingId: "lead-vocal", + receivingName: "Lead Vocal" + }); + const earlier = structuredClone(song.sections[0]!); + earlier.id = "verse-early"; + earlier.timeRange = { start: 8, end: 24 }; + earlier.roles = [ + { ...earlier.roles[0]!, id: "bass-guitar", name: "Bass Guitar", rehearsalPriority: "low" }, + { ...earlier.roles[1]!, id: "lead-vocal", name: "Lead Vocal", rehearsalPriority: "medium" } + ]; + earlier.partGraph = [ + { role_id: "bass-guitar", is_active: true, handoff_to: ["lead-vocal"], handoff_from: [] }, + { role_id: "lead-vocal", is_active: true, handoff_to: [], handoff_from: ["bass-guitar"] } + ]; + song.sections = [song.sections[0]!, earlier]; + + const resolved = resolveFirstPartHandoff(song); + expect(resolved?.section.id).toBe("verse-early"); + expect(resolved?.givingRole.id).toBe("bass-guitar"); + expect(resolved?.receivingRole.id).toBe("lead-vocal"); + expect(resolved?.atSeconds).toBe(8); + }); + + it("breaks same-time handoff ties with locale-independent section id ordering", () => { + const song = withHandoffSection({ id: "ä-handoff", start: 10, end: 26 }); + const ascii = structuredClone(song.sections[0]!); + ascii.id = "z-handoff"; + song.sections = [song.sections[0]!, ascii]; + + expect(resolveFirstPartHandoff(song)?.section.id).toBe("z-handoff"); + }); + + it("prefers a high-priority giving part over a low-priority giving part in the same section", () => { + const song = withHandoffSection({ + givingId: "keys-right", + givingName: "Keys", + givingPriority: "low", + receivingId: "lead-vocal" + }); + const section = song.sections[0]!; + const highRole = { + ...section.roles[0]!, + id: "bass-guitar", + name: "Bass Guitar", + rehearsalPriority: "high" as const + }; + section.roles = [section.roles[0]!, highRole, section.roles[1]!]; + section.partGraph = [ + { role_id: "keys-right", is_active: true, handoff_to: ["lead-vocal"], handoff_from: [] }, + { role_id: "bass-guitar", is_active: true, handoff_to: ["lead-vocal"], handoff_from: [] }, + { role_id: "lead-vocal", is_active: true, handoff_to: [], handoff_from: ["keys-right", "bass-guitar"] } + ]; + + expect(resolveFirstPartHandoff(song)?.givingRole.id).toBe("bass-guitar"); + }); + + it("breaks equal-priority giving-role ties with locale-independent id ordering", () => { + const song = withHandoffSection({ givingId: "ä-role", givingName: "Umlaut role", givingPriority: "high" }); + const section = song.sections[0]!; + const asciiRole = { + ...section.roles[0]!, + id: "z-role", + name: "ASCII role" + }; + section.roles = [section.roles[0]!, asciiRole, section.roles[1]!]; + section.partGraph = [ + { role_id: "ä-role", is_active: true, handoff_to: ["lead-vocal"], handoff_from: [] }, + { role_id: "z-role", is_active: true, handoff_to: ["lead-vocal"], handoff_from: [] }, + { role_id: "lead-vocal", is_active: true, handoff_to: [], handoff_from: ["ä-role", "z-role"] } + ]; + + expect(resolveFirstPartHandoff(song)?.givingRole.id).toBe("z-role"); + }); + + it("skips a handoff whose giving graph node is inactive", () => { + expect(resolveFirstPartHandoff(withHandoffSection({ givingActive: false }))).toBeNull(); + }); + + it("skips a handoff whose receiving graph node is inactive", () => { + expect(resolveFirstPartHandoff(withHandoffSection({ receivingActive: false }))).toBeNull(); + }); + + it("skips a handoff whose rehearsal window is unbounded", () => { + expect(resolveFirstPartHandoff(withHandoffSection({ start: Number.NaN, end: 30 }))).toBeNull(); + }); + + it("skips a handoff whose end precedes its start", () => { + expect(resolveFirstPartHandoff(withHandoffSection({ start: 30, end: 10 }))).toBeNull(); + }); + + it("skips a zero-length handoff window", () => { + expect(resolveFirstPartHandoff(withHandoffSection({ start: 10, end: 10 }))).toBeNull(); + }); + + it("skips a handoff whose endpoint overflows the shared timing bound", () => { + expect( + resolveFirstPartHandoff( + withHandoffSection({ + start: MAX_SECTION_TIME_SECONDS, + end: MAX_SECTION_TIME_SECONDS + 1 + }) + ) + ).toBeNull(); + }); + + it("returns null for a non-object song root", () => { + expect(resolveFirstPartHandoff(null as never)).toBeNull(); + }); + + it("returns null when the runtime section collection is sparse", () => { + const song = withHandoffSection(); + const sparseSections: typeof song.sections = new Array(2); + sparseSections[1] = song.sections[0]!; + song.sections = sparseSections; + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); + + it("keeps the handoff unnamed when role identities are duplicated", () => { + const song = withHandoffSection(); + const role = song.sections[0]!.roles[0]!; + song.sections[0]!.roles = [role, { ...role }, song.sections[0]!.roles[1]!]; + song.sections[0]!.partGraph = [ + { role_id: role.id, is_active: true, handoff_to: ["lead-vocal"], handoff_from: [] }, + { role_id: role.id, is_active: true, handoff_to: ["lead-vocal"], handoff_from: [] }, + { role_id: "lead-vocal", is_active: true, handoff_to: [], handoff_from: [role.id] } + ]; + expect(resolveFirstPartHandoff(song)).toBeNull(); + }); + + it("bounds displayed giving-role names to 80 Unicode code points", () => { + const song = withHandoffSection({ givingName: "G".repeat(200) }); + const resolved = resolveFirstPartHandoff(song); + expect(resolved?.givingName.length).toBe(80); + }); + + it("does not split a Unicode surrogate pair at the giving-name boundary", () => { + const song = withHandoffSection({ givingName: `${"a".repeat(79)}😀tail` }); + const resolved = resolveFirstPartHandoff(song); + expect(Array.from(resolved?.givingName ?? "")).toHaveLength(80); + expect(resolved?.givingName.endsWith("😀")).toBe(true); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstPartHandoff.ts b/apps/desktop/src/features/workspace/firstPartHandoff.ts new file mode 100644 index 000000000..96d7f5866 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstPartHandoff.ts @@ -0,0 +1,356 @@ +import { + MAX_SECTION_TIME_SECONDS, + type PartGraphNode, + type RehearsalRole, + type RehearsalSection, + type RehearsalSong +} from "@bandscope/shared-types"; + +const PRIORITY_RANK = { high: 0, medium: 1, low: 2 } as const; +const MAX_ROLE_NAME_CHARACTERS = 80; + +/** Tonight's first part handoff: the earliest labeled section and the parts that own the pass. */ +export type FirstPartHandoff = { + section: RehearsalSection; + givingRole: RehearsalRole; + receivingRole: RehearsalRole; + givingName: string; + receivingName: string; + atSeconds: number; +}; + +/** Format a non-negative part-handoff time as m:ss for rehearsal copy. */ +export function formatPartHandoffTime(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; +} + +/** Bound buyer-visible text by Unicode code points without splitting a surrogate pair. */ +function truncateCodePoints(value: string, maximum: number): string { + let codePoints = 0; + let endIndex = 0; + for (const character of value) { + if (codePoints >= maximum) { + break; + } + endIndex += character.length; + codePoints += 1; + } + return endIndex === value.length ? value : value.slice(0, endIndex); +} + +/** Return a bounded own role name, or null when it cannot be shown. */ +function ownedRoleName(role: unknown): string | null { + if (!isRuntimeObject(role) || !hasOwnData(role, "name")) { + return null; + } + const name = (role as { name?: unknown }).name; + if (typeof name !== "string") { + return null; + } + const trimmed = name.trim(); + if (trimmed.length === 0 || trimmed.includes("\n") || trimmed.includes("\r")) { + return null; + } + return truncateCodePoints(trimmed, MAX_ROLE_NAME_CHARACTERS); +} + +/** 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 && + ownedRoleName(role) !== null && + 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; +} + +/** Return owned unique non-blank string ids from a dense graph-edge collection. */ +function ownedUniqueEdgeIds(value: unknown): string[] | null { + if (!isDenseRuntimeArray(value)) { + return null; + } + const ids: string[] = []; + for (const entry of value) { + if (typeof entry !== "string") { + return null; + } + const trimmed = entry.trim(); + if (trimmed.length === 0 || trimmed.includes("\n") || trimmed.includes("\r")) { + return null; + } + ids.push(trimmed); + } + if (repeatedIds(ids).size > 0) { + return null; + } + return ids; +} + +/** Prefer the earlier ranked role, then rehearsal priority, then a locale-independent id. */ +function pickRankedRole(roles: RehearsalRole[]): RehearsalRole | null { + if (roles.length === 0) { + return null; + } + return ( + [...roles].sort((left, right) => { + const priorityDelta = PRIORITY_RANK[left.rehearsalPriority] - PRIORITY_RANK[right.rehearsalPriority]; + if (priorityDelta !== 0) { + return priorityDelta; + } + 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) + ); +} + +/** Return the unique owned graph node for a role, or null when identity is untrusted. */ +function ownedGraphNode(section: RehearsalSection, roleId: string): PartGraphNode | null { + if (!hasOwnData(section, "partGraph") || !isDenseRuntimeArray(section.partGraph)) { + return null; + } + const matches = section.partGraph.filter( + (node) => + isRuntimeObject(node) && + hasOwnData(node, "role_id") && + typeof node.role_id === "string" && + node.role_id === roleId + ); + return matches.length === 1 ? (matches[0] ?? null) : null; +} + +/** Resolve a corroborated outgoing pass after the runtime root has passed its structural boundary checks. */ +function resolveSafeFirstPartHandoff(song: RehearsalSong): FirstPartHandoff | null { + if (!isRuntimeObject(song) || !hasOwnData(song, "sections") || !isDenseRuntimeArray(song.sections)) { + return null; + } + + const candidates = song.sections + .filter( + (section) => + isRuntimeObject(section) && + hasOwnData(section, "label") && + typeof section.label === "string" && + section.label.trim().length > 0 && + hasOwnData(section, "id") && + typeof section.id === "string" && + section.id.trim().length > 0 && + hasBoundedTimeRange(section) + ) + .flatMap((section) => { + const activeRoles = rankedActiveRoles(section); + const byId = new Map(activeRoles.map((role) => [role.id, role])); + const passes = activeRoles.flatMap((givingRole) => { + const givingNode = ownedGraphNode(section, givingRole.id); + if ( + givingNode === null || + !hasOwnData(givingNode, "handoff_to") || + !hasOwnData(givingNode, "is_active") || + givingNode.is_active !== true + ) { + return []; + } + const outgoing = ownedUniqueEdgeIds(givingNode.handoff_to); + if (outgoing === null) { + return []; + } + const receivingRoles = outgoing + .filter((roleId) => roleId !== givingRole.id) + .map((roleId) => byId.get(roleId)) + .filter((role): role is RehearsalRole => role !== undefined) + .filter((receivingRole) => { + const receivingNode = ownedGraphNode(section, receivingRole.id); + if ( + receivingNode === null || + !hasOwnData(receivingNode, "handoff_from") || + !hasOwnData(receivingNode, "is_active") || + receivingNode.is_active !== true + ) { + return false; + } + const incoming = ownedUniqueEdgeIds(receivingNode.handoff_from); + return incoming !== null && incoming.includes(givingRole.id); + }); + const receivingRole = pickRankedRole(receivingRoles); + if (!receivingRole) { + return []; + } + return [{ givingRole, receivingRole }]; + }); + const chosen = pickRankedRole(passes.map((pass) => pass.givingRole)); + if (!chosen) { + return []; + } + const matched = passes.find((pass) => pass.givingRole.id === chosen.id); + if (!matched) { + return []; + } + const givingName = ownedRoleName(matched.givingRole); + const receivingName = ownedRoleName(matched.receivingRole); + if (!givingName || !receivingName) { + return []; + } + return [ + { + section, + givingRole: matched.givingRole, + receivingRole: matched.receivingRole, + givingName, + receivingName, + atSeconds: section.timeRange.start + } + ]; + }) + .sort((left, right) => { + if (left.atSeconds !== right.atSeconds) { + return left.atSeconds - right.atSeconds; + } + return compareStableId(left.section.id, right.section.id); + }); + + return candidates[0] ?? null; +} + +/** Return the first named part handoff, or null when untrusted runtime metadata cannot be read safely. */ +export function resolveFirstPartHandoff(song: RehearsalSong): FirstPartHandoff | null { + try { + return resolveSafeFirstPartHandoff(song); + } catch { + return null; + } +} diff --git a/apps/desktop/src/i18n/index.test.ts b/apps/desktop/src/i18n/index.test.ts index dc49a0a25..9dbf5d8d6 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 Korean section form label", () => { + 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", "verse")).toBe("verse"); + 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-part-handoff next-action copy particle-safe", () => { + const t = createTranslator("ko"); + expect(t("firstPartHandoffOpenAction")).toBe("{at} {from} 핸드오프 위치 열기"); + expect(t("firstPartHandoffBody")).toBe("{at} {section}에서 {from} 파트가 {to} 파트로 넘깁니다."); + expect(t("firstPartHandoffArmed")).toBe("{at}에서 {from} 파트에서 {to} 파트로 넘긴 다음 합주를 시작하세요."); + }); + }); }); 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..5c2220d10 100644 --- a/apps/desktop/src/locales/en/common.json +++ b/apps/desktop/src/locales/en/common.json @@ -149,6 +149,11 @@ "practiceProgressLabel": "Practice Progress", "decreasePracticeProgressLabel": "Decrease progress", "increasePracticeProgressLabel": "Increase progress", + "firstPartHandoffLabel": "Tonight's first part handoff", + "firstPartHandoffOpenAction": "Open {from} handoff at {at}", + "firstPartHandoffBody": "{from} still hands off to {to} in the {section} at {at}.", + "firstPartHandoffArmed": "Lock that pass from {from} to {to} at {at} before the room starts.", + "firstPartHandoffUnavailable": "Nothing still has a part handoff. Stay on tonight's map until a part owns a rehearsal-facing pass.", "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..991e59930 100644 --- a/apps/desktop/src/locales/ko/common.json +++ b/apps/desktop/src/locales/ko/common.json @@ -149,6 +149,11 @@ "practiceProgressLabel": "연습 진척도", "decreasePracticeProgressLabel": "진척도 감소", "increasePracticeProgressLabel": "진척도 증가", + "firstPartHandoffLabel": "오늘 첫 파트 핸드오프", + "firstPartHandoffOpenAction": "{at} {from} 핸드오프 위치 열기", + "firstPartHandoffBody": "{at} {section}에서 {from} 파트가 {to} 파트로 넘깁니다.", + "firstPartHandoffArmed": "{at}에서 {from} 파트에서 {to} 파트로 넘긴 다음 합주를 시작하세요.", + "firstPartHandoffUnavailable": "넘기는 파트가 없습니다. 합주용 핸드오프가 있는 파트가 생길 때까지 오늘 맵에 머무르세요.", "workspaceFirstRangeTitle": "오늘 먼저 볼 음역", "workspaceFirstRangeCheck": "{sectionLabel}의 {roleName}은 {lowestNote}–{highestNote}입니다. {sectionLabel} 들어가기 전에 그 음역을 악기로 확인해 보세요.", "workspaceFirstRangeClash": "{sectionLabel}의 {roleName}은 {lowestNote}–{highestNote}이고 다른 파트와 겹칩니다. {sectionLabel} 들어가기 전에 그 충돌을 악기로 들어 보세요.", diff --git a/docs/design-system/component-contract.md b/docs/design-system/component-contract.md index 22602c313..437e0ba0f 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 Part Handoff Callout | workspace next-action pattern | `apps/desktop/src/features/workspace/FirstPartHandoffCallout.tsx` | Name the giving part and receiving part when both unique active `partGraph` nodes corroborate the owned `handoff_to` / `handoff_from` pass, plus the labeled section and time. Do not invent that pass from `groove`, cue text, `simplification`, overlap warnings, range copy, `harmony.chord`, `harmony.functionLabel`, `setupNote`, confirmed overrides, `harmonicExplanation`, confidence notes, `transpositionPlan`, or a labeled `handoff` form without owned bidirectional graph edges. Open scrolls the renderer-owned song-structure section. Keep the unavailable state guidance-only. Distinct from labeled-form handoff (#937) and Part Handoff Map visualization (#850). | | 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-part-handoff-navigation.md b/docs/doctoring/reduced-motion-first-part-handoff-navigation.md new file mode 100644 index 000000000..b419a7232 --- /dev/null +++ b/docs/doctoring/reduced-motion-first-part-handoff-navigation.md @@ -0,0 +1,5 @@ +# Reduced-motion first part-handoff navigation + +When `prefers-reduced-motion: reduce` matches, `FirstPartHandoffCallout` scrolls the renderer-owned song-structure section with `behavior: "auto"`. Otherwise it uses `behavior: "smooth"`. + +Open still names the giving part, receiving part, labeled section, and time. Analysis `section.id` is never DOM-ID authority. This map next-action is distinct from the labeled `handoff` form (#937) and the Part Handoff Map visualization (#850).