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/FirstDynamicsPlanCallout.workspace-scope.test.tsx b/apps/desktop/src/features/workspace/FirstDynamicsPlanCallout.workspace-scope.test.tsx new file mode 100644 index 000000000..cd356a666 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstDynamicsPlanCallout.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 { FirstDynamicsPlanCallout } from "./FirstDynamicsPlanCallout"; + +describe("FirstDynamicsPlanCallout 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 dynamics 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..69123e304 100644 --- a/apps/desktop/src/features/workspace/Workspace.test.tsx +++ b/apps/desktop/src/features/workspace/Workspace.test.tsx @@ -326,4 +326,34 @@ describe("Workspace", () => { expect(screen.getByText("합주 우선순위")).toBeTruthy(); expect(screen.getByText("역할과 화성")).toBeTruthy(); }); + + it("names tonight's first dynamics plan 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.getAllByText( + "Keep the verse under the vocal so the chorus still has somewhere to lift." + ).length + ).toBeGreaterThan(0); + const action = screen.getByRole("button", { + name: "Open Bass Guitar dynamics at 0:10" + }); + expect(action).toBeTruthy(); + fireEvent.click(action); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + expect( + screen.getByText(/Lock that dynamics on Bass Guitar 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..cd99288c1 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 { FirstDynamicsPlanCallout } from "./FirstDynamicsPlanCallout"; import { fillRangeCopy, firstRangeSqueeze } from "./firstRangeSqueeze"; import { createTranslator, detectPreferredLocale } from "../../i18n"; import { generateCueSheetCsv, generateChartSummaryJson, generateMetadataHandoffJson, sanitizeFilename } from "../../lib/export"; @@ -88,11 +89,16 @@ const SongStructure = memo(function SongStructure({ sections, t }: { sections: R >
- {sections.map((section) => ( -
+ {sections.map((section, sectionIndex) => ( +

{section.label} · {formatTimelineTime(section.timeRange.start)}–{formatTimelineTime(section.timeRange.end)}

@@ -353,6 +359,8 @@ export function Workspace({ song, sourceBootstrap = null, onSongUpdate }: Worksp
+ +
diff --git a/apps/desktop/src/features/workspace/dynamicsCoverageContract.test.ts b/apps/desktop/src/features/workspace/dynamicsCoverageContract.test.ts new file mode 100644 index 000000000..95bd07a16 --- /dev/null +++ b/apps/desktop/src/features/workspace/dynamicsCoverageContract.test.ts @@ -0,0 +1,13 @@ +import { describe, expect, it } from "vitest"; +import { DESKTOP_OWNED_PRODUCTION_COVERAGE } from "../../../vite.config"; + +describe("desktop owned production coverage", () => { + it("keeps the dynamics-plan resolver and callout inside the coverage gate", () => { + expect(DESKTOP_OWNED_PRODUCTION_COVERAGE).toEqual( + expect.arrayContaining([ + "src/features/workspace/firstDynamicsPlan.ts", + "src/features/workspace/FirstDynamicsPlanCallout.tsx" + ]) + ); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstDynamicsPlan.inherited-metadata.test.ts b/apps/desktop/src/features/workspace/firstDynamicsPlan.inherited-metadata.test.ts new file mode 100644 index 000000000..7fde764be --- /dev/null +++ b/apps/desktop/src/features/workspace/firstDynamicsPlan.inherited-metadata.test.ts @@ -0,0 +1,94 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstDynamicsPlan } from "./firstDynamicsPlan"; + +function songWithDynamicsPlan() { + const song = createDemoRehearsalSong(); + const section = structuredClone(song.sections[0]!); + section.id = "dynamics-own"; + section.roles = [ + { + ...section.roles[0]!, + id: "bass-guitar", + name: "Bass Guitar", + rehearsalPriority: "high", + dynamicsPlan: "Keep the verse under the vocal so the chorus still has somewhere to lift." + } + ]; + section.partGraph = [{ role_id: "bass-guitar", is_active: true, handoff_to: [], handoff_from: [] }]; + song.sections = [section]; + return { song, section }; +} + +describe("resolveFirstDynamicsPlan inherited metadata", () => { + it("rejects a song or section whose required metadata is inherited", () => { + const { song, section } = songWithDynamicsPlan(); + const inheritedSong = Object.create({ sections: song.sections }) as typeof song; + expect(resolveFirstDynamicsPlan(inheritedSong)).toBeNull(); + + const inheritedSection = Object.create(section) as typeof section; + song.sections = [inheritedSection]; + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); + + it("rejects inherited timing fields", () => { + const { song, section } = songWithDynamicsPlan(); + section.timeRange = Object.create({ start: 10, end: 30 }) as typeof section.timeRange; + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); + + it("contains exceptions from own runtime accessors instead of trusting them", () => { + const { song, section } = songWithDynamicsPlan(); + Object.defineProperty(section.roles[0]!, "dynamicsPlan", { + configurable: true, + enumerable: true, + get() { + throw new Error("hostile dynamicsPlan getter"); + } + }); + + expect(() => resolveFirstDynamicsPlan(song)).not.toThrow(); + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); + + it("does not treat own accessors as stable dynamics-plan identity authority", () => { + const { song, section } = songWithDynamicsPlan(); + Object.defineProperty(section, "id", { + configurable: true, + enumerable: true, + get() { + return "dynamics-own"; + } + }); + + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); + + it("does not let inherited dynamics plans establish the named copy", () => { + const { song, section } = songWithDynamicsPlan(); + const inheritedRole = Object.create({ + dynamicsPlan: "Inherited dynamics plan" + }) as (typeof section.roles)[0]; + Object.defineProperties(inheritedRole, { + id: { configurable: true, enumerable: true, value: "bass-guitar" }, + name: { configurable: true, enumerable: true, value: "Bass Guitar" }, + rehearsalPriority: { configurable: true, enumerable: true, value: "high" } + }); + section.roles = [inheritedRole]; + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); + + it("does not let inherited role or graph metadata establish the holding part", () => { + const { song, section } = songWithDynamicsPlan(); + const node = section.partGraph[0]!; + section.partGraph = [Object.create(node) as typeof node]; + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); + + it("rejects arrays masquerading as section records", () => { + const { song, section } = songWithDynamicsPlan(); + const arraySection = Object.assign([], section) as unknown as typeof section; + song.sections = [arraySection]; + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstDynamicsPlan.proxy-authority.test.ts b/apps/desktop/src/features/workspace/firstDynamicsPlan.proxy-authority.test.ts new file mode 100644 index 000000000..3e70da5e7 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstDynamicsPlan.proxy-authority.test.ts @@ -0,0 +1,83 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstDynamicsPlan } from "./firstDynamicsPlan"; + +const DEMO_DYNAMICS_PLAN = + "Keep the verse under the vocal so the chorus still has somewhere to lift."; + +describe("resolveFirstDynamicsPlan own-data authority", () => { + it("uses the snapshotted own-data dynamics plan instead of a Proxy get trap", () => { + const song = createDemoRehearsalSong(); + const section = song.sections.find((candidate) => candidate.id === "verse-1"); + const roleIndex = section?.roles.findIndex((role) => role.id === "bass-guitar") ?? -1; + const role = roleIndex >= 0 ? section?.roles[roleIndex] : undefined; + expect(section).toBeDefined(); + expect(role).toBeDefined(); + if (!section || !role || roleIndex < 0) { + throw new Error("Demo dynamics-plan fixture is missing the expected Bass Guitar role."); + } + + section.roles[roleIndex] = new Proxy(role, { + get(target, property, receiver) { + if (property === "dynamicsPlan") { + return "Injected proxy dynamics."; + } + return Reflect.get(target, property, receiver); + } + }); + + expect(resolveFirstDynamicsPlan(song)?.dynamicsPlan).toBe(DEMO_DYNAMICS_PLAN); + }); + + it("uses the snapshotted own-data time range instead of a Proxy get trap", () => { + const song = createDemoRehearsalSong(); + const section = song.sections.find((candidate) => candidate.id === "verse-1"); + expect(section).toBeDefined(); + if (!section) { + throw new Error("Demo dynamics-plan fixture is missing the expected verse section."); + } + const expectedStart = section.timeRange.start; + section.timeRange = new Proxy(section.timeRange, { + get(target, property, receiver) { + if (property === "start") { + return expectedStart + 15; + } + return Reflect.get(target, property, receiver); + } + }); + + expect(resolveFirstDynamicsPlan(song)?.atSeconds).toBe(expectedStart); + }); + + it("returns snapshotted role identity and display copy instead of Proxy get values", () => { + const song = createDemoRehearsalSong(); + const section = song.sections.find((candidate) => candidate.id === "verse-1"); + const roleIndex = section?.roles.findIndex((role) => role.id === "bass-guitar") ?? -1; + const role = roleIndex >= 0 ? section?.roles[roleIndex] : undefined; + expect(section).toBeDefined(); + expect(role).toBeDefined(); + if (!section || !role || roleIndex < 0) { + throw new Error("Demo dynamics-plan fixture is missing the expected Bass Guitar role."); + } + const expectedId = role.id; + const expectedName = role.name; + section.roles[roleIndex] = new Proxy(role, { + get(target, property, receiver) { + if (property === "name") { + return "Injected proxy role"; + } + return Reflect.get(target, property, receiver); + } + }); + + const resolved = resolveFirstDynamicsPlan(song) as + | (ReturnType & { + holdingRoleId?: string; + holdingRoleName?: string; + }) + | null; + expect(resolved?.dynamicsPlan).toBe(DEMO_DYNAMICS_PLAN); + expect(resolved?.holdingRoleId).toBe(expectedId); + expect(resolved?.holdingRoleName).toBe(expectedName); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstDynamicsPlan.section-label.test.ts b/apps/desktop/src/features/workspace/firstDynamicsPlan.section-label.test.ts new file mode 100644 index 000000000..c173fc68f --- /dev/null +++ b/apps/desktop/src/features/workspace/firstDynamicsPlan.section-label.test.ts @@ -0,0 +1,14 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstDynamicsPlan } from "./firstDynamicsPlan"; + +describe("resolveFirstDynamicsPlan section-label authority", () => { + it("fails closed when runtime metadata supplies a label outside the shared SectionFormLabel contract", () => { + const song = createDemoRehearsalSong(); + const section = song.sections[0]!; + + (section as unknown as { label: string }).label = "verse-legacy"; + + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstDynamicsPlan.test.ts b/apps/desktop/src/features/workspace/firstDynamicsPlan.test.ts new file mode 100644 index 000000000..2bec9904a --- /dev/null +++ b/apps/desktop/src/features/workspace/firstDynamicsPlan.test.ts @@ -0,0 +1,286 @@ +import { describe, expect, it } from "vitest"; +import { MAX_SECTION_TIME_SECONDS, createDemoRehearsalSong } from "@bandscope/shared-types"; +import { formatDynamicsPlanTime, resolveFirstDynamicsPlan } from "./firstDynamicsPlan"; + +const DEMO_DYNAMICS_PLAN = + "Keep the verse under the vocal so the chorus still has somewhere to lift."; + +function withDynamicsSection( + overrides: { + id?: string; + start?: number; + end?: number; + dynamicsPlan?: string; + label?: "intro" | "verse" | "pre-chorus" | "chorus" | "bridge" | "outro" | "tag" | "pickup" | "stop" | "handoff"; + roleId?: string; + roleName?: string; + priority?: "low" | "medium" | "high"; + isActive?: boolean; + functionLabel?: string; + } = {} +) { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + const section = structuredClone(verse); + section.id = overrides.id ?? "verse-dynamics"; + 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 roleId = overrides.roleId ?? "lead-vocal"; + section.roles = [ + { + ...verse.roles[2]!, + id: roleId, + name: overrides.roleName ?? "Lead Vocal", + rehearsalPriority: overrides.priority ?? "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; skip the ad-lib on the first pass.", + overlapWarnings: ["Melodic overlap: competing with Keyboard 1 Right Hand."], + harmony: { + chord: "C#m7", + functionLabel: overrides.functionLabel ?? "vi melodic pull", + source: "model" + }, + harmonicExplanation: + "The melody leans on the ninth over vi, so the vocal line should feel like a lift rather than a strict chord-tone outline.", + confidence: { + level: "high", + source: "user", + notes: "Singer confirmed the pickup phrasing in rehearsal notes." + }, + dynamicsPlan: + overrides.dynamicsPlan ?? + "Keep the verse under the vocal so the chorus still has somewhere to lift.", + manualOverrides: [] + } + ]; + section.partGraph = [ + { + role_id: roleId, + is_active: overrides.isActive ?? true, + handoff_to: [], + handoff_from: [] + } + ]; + song.sections = [section]; + return song; +} + +describe("resolveFirstDynamicsPlan", () => { + it("picks the demo song's earliest high-priority dynamics plan and the part that owns it", () => { + const resolved = resolveFirstDynamicsPlan(createDemoRehearsalSong()); + expect(resolved?.section.id).toBe("verse-1"); + expect(resolved?.holdingRole.id).toBe("bass-guitar"); + expect(resolved?.dynamicsPlan).toBe(DEMO_DYNAMICS_PLAN); + expect(resolved?.atSeconds).toBe(10); + expect(formatDynamicsPlanTime(resolved?.atSeconds ?? -1)).toBe("0:10"); + expect(formatDynamicsPlanTime(Number.NaN)).toBe("0:00"); + expect(formatDynamicsPlanTime(-4)).toBe("0:00"); + }); + + it("does not invent a dynamics plan from groove, cue, simplification, overlap, range, chords, function labels, setup notes, transposition plans, confirmed overrides, harmonic explanations, or confidence notes", () => { + const song = withDynamicsSection(); + delete song.sections[0]!.roles[0]!.dynamicsPlan; + song.sections[0]!.groove = "Straight eighths with a late snare feel"; + song.sections[0]!.roles[0]!.simplification = "Keep the sustained note centered."; + song.sections[0]!.roles[0]!.setupNote = + "Keep the verse under the vocal so the chorus still has somewhere to lift."; + song.sections[0]!.roles[0]!.transpositionPlan = + "If the singer drops to B minor, keep the shape a whole step lower."; + (song.sections[0]!.roles[0] as { tuningPlan?: string }).tuningPlan = + "Tune the E string down to D so the verse riff sits on the open fifth."; + song.sections[0]!.roles[0]!.cue = { kind: "lyric", value: "city lights" }; + song.sections[0]!.roles[0]!.range = { lowestNote: "G#3", highestNote: "C#5" }; + song.sections[0]!.roles[0]!.overlapWarnings = ["Melodic overlap: competing with Keyboard 1 Right Hand."]; + song.sections[0]!.roles[0]!.harmony = { + chord: "C#m7", + functionLabel: "vi melodic pull", + source: "user" + }; + song.sections[0]!.roles[0]!.harmonicExplanation = "The ninth is the reason this lift works."; + song.sections[0]!.roles[0]!.manualOverrides = [ + { + field: "harmony", + value: { + chord: "C#m11", + functionLabel: "vi suspended lift", + source: "user" + }, + source: "user" + } + ]; + song.sections[0]!.roles[0]!.confidence = { + level: "high", + source: "user", + notes: "Keep the verse under the vocal so the chorus still has somewhere to lift." + }; + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); + + it("skips a blank dynamics plan", () => { + expect(resolveFirstDynamicsPlan(withDynamicsSection({ dynamicsPlan: " " }))).toBeNull(); + }); + + it("skips a multi-line dynamics plan", () => { + expect( + resolveFirstDynamicsPlan(withDynamicsSection({ dynamicsPlan: "Drop under the vocal.\nKeep the pickup." })) + ).toBeNull(); + }); + + it("skips Unicode line separators and accepts BOM-padded dynamics text", () => { + for (const dynamicsPlan of ["Hold\u0085here", "Hold\u2028here", "Hold\u2029here"]) { + expect(resolveFirstDynamicsPlan(withDynamicsSection({ dynamicsPlan }))).toBeNull(); + } + expect(resolveFirstDynamicsPlan(withDynamicsSection({ dynamicsPlan: "\uFEFF Hold here \uFEFF" }))?.dynamicsPlan).toBe( + "Hold here" + ); + }); + + it("prefers the earlier of two dynamics plans", () => { + const song = withDynamicsSection({ + id: "verse-late", + start: 40, + end: 56, + roleId: "keys-right", + dynamicsPlan: "Late dynamics." + }); + const earlier = structuredClone(song.sections[0]!); + earlier.id = "verse-early"; + earlier.roles = [ + { + ...earlier.roles[0]!, + id: "lead-vocal", + name: "Lead Vocal", + rehearsalPriority: "low", + dynamicsPlan: "Earlier dynamics." + } + ]; + earlier.timeRange = { start: 8, end: 24 }; + earlier.partGraph = [{ role_id: "lead-vocal", is_active: true, handoff_to: [], handoff_from: [] }]; + song.sections = [song.sections[0]!, earlier]; + + const resolved = resolveFirstDynamicsPlan(song); + expect(resolved?.section.id).toBe("verse-early"); + expect(resolved?.holdingRole.id).toBe("lead-vocal"); + expect(resolved?.dynamicsPlan).toBe("Earlier dynamics."); + expect(resolved?.atSeconds).toBe(8); + }); + + it("breaks same-time dynamics-plan ties with locale-independent id ordering", () => { + const song = withDynamicsSection({ id: "ä-dynamics", start: 10, end: 26 }); + const ascii = structuredClone(song.sections[0]!); + ascii.id = "z-dynamics"; + song.sections = [song.sections[0]!, ascii]; + + expect(resolveFirstDynamicsPlan(song)?.section.id).toBe("z-dynamics"); + }); + + it("prefers a high-priority dynamics part over a low-priority part in the same section", () => { + const song = withDynamicsSection({ + roleId: "keys-right", + roleName: "Keys", + priority: "low", + dynamicsPlan: "Low-priority dynamics." + }); + const section = song.sections[0]!; + const highRole = { + ...section.roles[0]!, + id: "lead-vocal", + name: "Lead Vocal", + rehearsalPriority: "high" as const, + dynamicsPlan: "High-priority dynamics." + }; + section.roles = [section.roles[0]!, highRole]; + section.partGraph = [ + { role_id: "keys-right", is_active: true, handoff_to: [], handoff_from: [] }, + { role_id: "lead-vocal", is_active: true, handoff_to: [], handoff_from: [] } + ]; + + expect(resolveFirstDynamicsPlan(song)?.holdingRole.id).toBe("lead-vocal"); + expect(resolveFirstDynamicsPlan(song)?.dynamicsPlan).toBe("High-priority dynamics."); + }); + + it("breaks equal-priority role ties with locale-independent id ordering", () => { + const song = withDynamicsSection({ roleId: "ä-role", roleName: "Umlaut role", priority: "high" }); + const section = song.sections[0]!; + const asciiRole = { + ...section.roles[0]!, + id: "z-role", + name: "ASCII role", + dynamicsPlan: "ASCII dynamics." + }; + section.roles = [section.roles[0]!, asciiRole]; + section.partGraph = [ + { role_id: "ä-role", is_active: true, handoff_to: [], handoff_from: [] }, + { role_id: "z-role", is_active: true, handoff_to: [], handoff_from: [] } + ]; + + expect(resolveFirstDynamicsPlan(song)?.holdingRole.id).toBe("z-role"); + expect(resolveFirstDynamicsPlan(song)?.dynamicsPlan).toBe("ASCII dynamics."); + }); + + it("skips a dynamics plan whose graph node is inactive", () => { + expect(resolveFirstDynamicsPlan(withDynamicsSection({ isActive: false }))).toBeNull(); + }); + + it("skips a dynamics plan whose rehearsal window is unbounded", () => { + expect(resolveFirstDynamicsPlan(withDynamicsSection({ start: Number.NaN, end: 30 }))).toBeNull(); + }); + + it("skips a dynamics plan whose end precedes its start", () => { + expect(resolveFirstDynamicsPlan(withDynamicsSection({ start: 30, end: 10 }))).toBeNull(); + }); + + it("skips a zero-length dynamics-plan window", () => { + expect(resolveFirstDynamicsPlan(withDynamicsSection({ start: 10, end: 10 }))).toBeNull(); + }); + + it("skips a dynamics plan whose endpoint overflows the shared timing bound", () => { + expect( + resolveFirstDynamicsPlan( + withDynamicsSection({ + start: MAX_SECTION_TIME_SECONDS, + end: MAX_SECTION_TIME_SECONDS + 1 + }) + ) + ).toBeNull(); + }); + + it("returns null for a non-object song root", () => { + expect(resolveFirstDynamicsPlan(null as never)).toBeNull(); + }); + + it("returns null when the runtime section collection is sparse", () => { + const song = withDynamicsSection(); + const sparseSections: typeof song.sections = new Array(2); + sparseSections[1] = song.sections[0]!; + song.sections = sparseSections; + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); + + it("keeps the dynamics plan unnamed when role identities are duplicated", () => { + const song = withDynamicsSection(); + const role = song.sections[0]!.roles[0]!; + song.sections[0]!.roles = [role, { ...role }]; + song.sections[0]!.partGraph = [ + { role_id: role.id, is_active: true, handoff_to: [], handoff_from: [] }, + { role_id: role.id, is_active: true, handoff_to: [], handoff_from: [] } + ]; + expect(resolveFirstDynamicsPlan(song)).toBeNull(); + }); + + it("bounds the dynamics plan to 180 Unicode code points", () => { + const song = withDynamicsSection({ dynamicsPlan: `${"G".repeat(200)}` }); + const resolved = resolveFirstDynamicsPlan(song); + expect(resolved?.dynamicsPlan.length).toBe(180); + }); + + it("does not split a Unicode surrogate pair at the dynamics-plan boundary", () => { + const song = withDynamicsSection({ dynamicsPlan: `${"a".repeat(179)}😀tail` }); + const resolved = resolveFirstDynamicsPlan(song); + expect(Array.from(resolved?.dynamicsPlan ?? "")).toHaveLength(180); + expect(resolved?.dynamicsPlan.endsWith("😀")).toBe(true); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstDynamicsPlan.ts b/apps/desktop/src/features/workspace/firstDynamicsPlan.ts new file mode 100644 index 000000000..3fb3ea0e0 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstDynamicsPlan.ts @@ -0,0 +1,280 @@ +import { + MAX_SECTION_TIME_SECONDS, + SECTION_FORM_LABELS, + isNonEmptySingleLineText, + type RehearsalRole, + type RehearsalSection, + type RehearsalSong +} from "@bandscope/shared-types"; + +const PRIORITY_RANK = { high: 0, medium: 1, low: 2 } as const; +const MAX_DYNAMICS_PLAN_CHARACTERS = 180; +const SECTION_FORM_LABEL_SET = new Set(SECTION_FORM_LABELS); + +type RankedRoleMetadata = Readonly<{ + role: RehearsalRole; + id: string; + name: string; + rehearsalPriority: keyof typeof PRIORITY_RANK; +}>; + +/** Tonight's first dynamics plan: the earliest labeled section and the part that owns it. */ +export type FirstDynamicsPlan = { + section: RehearsalSection; + sectionId: string; + sectionLabel: RehearsalSection["label"]; + sectionIndex: number; + holdingRole: RehearsalRole; + holdingRoleId: string; + holdingRoleName: string; + dynamicsPlan: string; + atSeconds: number; +}; + +/** Format a non-negative dynamics-plan time as m:ss for rehearsal copy. */ +export function formatDynamicsPlanTime(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"); +} + +/** Snapshot one owned data-property value without invoking an accessor or Proxy get trap. */ +function ownDataValue(value: object, key: PropertyKey): unknown { + const descriptor = Object.getOwnPropertyDescriptor(value, key); + return descriptor !== undefined && Object.prototype.hasOwnProperty.call(descriptor, "value") + ? descriptor.value + : undefined; +} + +/** Snapshot every numeric own data element from a bounded runtime array. */ +function ownedDenseRuntimeArray(value: unknown): unknown[] | null { + if (!Array.isArray(value)) return null; + const length = ownDataValue(value, "length"); + if ( + typeof length !== "number" || + !Number.isSafeInteger(length) || + length < 0 || + length > 0xffffffff + ) { + return null; + } + const items: unknown[] = []; + for (let index = 0; index < length; index += 1) { + if (!hasOwnData(value, index)) return null; + items.push(ownDataValue(value, index)); + } + return items; +} + +/** 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 snapshotted own dynamics plan, or null when it cannot be shown. */ +function ownedDynamicsPlan(role: unknown): string | null { + if (!isRuntimeObject(role)) return null; + const dynamicsPlan = ownDataValue(role, "dynamicsPlan"); + if (typeof dynamicsPlan !== "string") return null; + if (!isNonEmptySingleLineText(dynamicsPlan)) return null; + const trimmed = dynamicsPlan.trim(); + return truncateCodePoints(trimmed, MAX_DYNAMICS_PLAN_CHARACTERS); +} + +/** Snapshot trusted role identity, display name, and priority without Proxy get authority. */ +function ownedRankedRoleMetadata(role: unknown): RankedRoleMetadata | null { + if (!isRuntimeObject(role)) return null; + const id = ownDataValue(role, "id"); + const name = ownDataValue(role, "name"); + const rehearsalPriority = ownDataValue(role, "rehearsalPriority"); + if ( + typeof id !== "string" || + id.trim().length === 0 || + typeof name !== "string" || + name.trim().length === 0 || + typeof rehearsalPriority !== "string" || + !Object.prototype.hasOwnProperty.call(PRIORITY_RANK, rehearsalPriority) + ) { + return null; + } + return { + role: role as RehearsalRole, + id, + name, + rehearsalPriority: rehearsalPriority as keyof typeof PRIORITY_RANK + }; +} + +/** Snapshot a section's bounded positive-length integer rehearsal window. */ +function ownedBoundedTimeRange(section: RehearsalSection): RehearsalSection["timeRange"] | null { + const timeRange = ownDataValue(section, "timeRange"); + if (!isRuntimeObject(timeRange)) return null; + const start = ownDataValue(timeRange, "start"); + const end = ownDataValue(timeRange, "end"); + if ( + typeof start !== "number" || + !Number.isInteger(start) || + start < 0 || + start > MAX_SECTION_TIME_SECONDS || + typeof end !== "number" || + !Number.isInteger(end) || + end <= start || + end > MAX_SECTION_TIME_SECONDS + ) { + return null; + } + return { start, end }; +} + +/** 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 earlier ranked role, then rehearsal priority, then a locale-independent id. */ +function pickHoldingRole(roles: RankedRoleMetadata[]): RankedRoleMetadata | null { + if (roles.length === 0) return null; + return ( + [...roles].sort((left, right) => { + const priorityDelta = + PRIORITY_RANK[left.rehearsalPriority] - PRIORITY_RANK[right.rehearsalPriority]; + return priorityDelta !== 0 ? priorityDelta : compareStableId(left.id, right.id); + })[0] ?? null + ); +} + +/** Return ranked roles whose unique graph node is explicitly active. */ +function rankedActiveRoles(section: RehearsalSection): RankedRoleMetadata[] { + const roles = ownedDenseRuntimeArray(ownDataValue(section, "roles")); + const partGraph = ownedDenseRuntimeArray(ownDataValue(section, "partGraph")); + if (!roles || !partGraph) return []; + + const safeRoleIds = roles.flatMap((role) => { + if (!isRuntimeObject(role)) return []; + const id = ownDataValue(role, "id"); + return typeof id === "string" && id.trim().length > 0 ? [id] : []; + }); + const safeGraphRoleIds = partGraph.flatMap((node) => { + if (!isRuntimeObject(node)) return []; + const roleId = ownDataValue(node, "role_id"); + return typeof roleId === "string" && roleId.trim().length > 0 ? [roleId] : []; + }); + const repeatedRoleIds = repeatedIds(safeRoleIds); + const repeatedGraphRoleIds = repeatedIds(safeGraphRoleIds); + const activeIds = new Set( + partGraph.flatMap((node) => { + if (!isRuntimeObject(node) || ownDataValue(node, "is_active") !== true) return []; + const roleId = ownDataValue(node, "role_id"); + return typeof roleId === "string" && + roleId.trim().length > 0 && + !repeatedGraphRoleIds.has(roleId) + ? [roleId] + : []; + }) + ); + + return roles.flatMap((role) => { + const metadata = ownedRankedRoleMetadata(role); + return metadata !== null && + !repeatedRoleIds.has(metadata.id) && + activeIds.has(metadata.id) + ? [metadata] + : []; + }); +} + +/** Resolve a dynamics plan after the runtime root has passed its structural boundary checks. */ +function resolveSafeFirstDynamicsPlan(song: RehearsalSong): FirstDynamicsPlan | null { + if (!isRuntimeObject(song)) return null; + const sections = ownedDenseRuntimeArray(ownDataValue(song, "sections")); + if (!sections) return null; + + const candidates = sections + .flatMap((section, sectionIndex) => { + if (!isRuntimeObject(section)) return []; + const sectionId = ownDataValue(section, "id"); + const sectionLabel = ownDataValue(section, "label"); + const timeRange = ownedBoundedTimeRange(section as RehearsalSection); + if ( + typeof sectionId !== "string" || + sectionId.trim().length === 0 || + typeof sectionLabel !== "string" || + !SECTION_FORM_LABEL_SET.has(sectionLabel) || + timeRange === null + ) { + return []; + } + + const holdingRole = pickHoldingRole( + rankedActiveRoles(section as RehearsalSection).filter( + (metadata) => ownedDynamicsPlan(metadata.role) !== null + ) + ); + if (!holdingRole) return []; + const dynamicsPlan = ownedDynamicsPlan(holdingRole.role); + if (!dynamicsPlan) return []; + return [ + { + section: section as RehearsalSection, + sectionId, + sectionLabel: sectionLabel as RehearsalSection["label"], + sectionIndex, + holdingRole: holdingRole.role, + holdingRoleId: holdingRole.id, + holdingRoleName: holdingRole.name, + dynamicsPlan, + atSeconds: timeRange.start + } + ]; + }) + .sort((left, right) => + left.atSeconds !== right.atSeconds + ? left.atSeconds - right.atSeconds + : compareStableId(left.sectionId, right.sectionId) + ); + + return candidates[0] ?? null; +} + +/** Return the first named dynamics plan, or null when untrusted runtime metadata cannot be read safely. */ +export function resolveFirstDynamicsPlan(song: RehearsalSong): FirstDynamicsPlan | null { + try { + return resolveSafeFirstDynamicsPlan(song); + } catch { + return null; + } +} diff --git a/apps/desktop/src/i18n/index.test.ts b/apps/desktop/src/i18n/index.test.ts index dc49a0a25..039a19fa7 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-dynamics-plan next-action copy particle-safe", () => { + const t = createTranslator("ko"); + expect(t("firstDynamicsPlanOpenAction")).toBe("{at} {role} 다이내믹 열기"); + expect(t("firstDynamicsPlanBody")).toBe("{at} {section}에서 {role} 파트의 다이내믹 계획이 있습니다."); + expect(t("firstDynamicsPlanArmed")).toBe("{at}에서 {role} 파트의 다이내믹을 맞춘 다음 합주를 시작하세요."); + }); + }); }); diff --git a/apps/desktop/src/i18n/index.ts b/apps/desktop/src/i18n/index.ts index 1a9f471f0..ff6e218d1 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,6 +12,33 @@ const dictionaries = { ko: koCommon } as const; +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: "핸드오프" + } +}; + /** Documented. */ export function createTranslator(locale: Locale = "en") { return function t(key: TranslationKey): string { @@ -18,6 +46,12 @@ export function createTranslator(locale: Locale = "en") { }; } +/** 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..9c92b6a2c 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", + "firstDynamicsPlanLabel": "Tonight's first dynamics plan", + "firstDynamicsPlanOpenAction": "Open {role} dynamics at {at}", + "firstDynamicsPlanBody": "{role} still has a dynamics plan in the {section} at {at}.", + "firstDynamicsPlanArmed": "Lock that dynamics on {role} at {at} before the room starts.", + "firstDynamicsPlanUnavailable": "Nothing still has a dynamics plan. Stay on tonight's map until a part owns rehearsal-facing dynamics copy.", "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..fb6242e24 100644 --- a/apps/desktop/src/locales/ko/common.json +++ b/apps/desktop/src/locales/ko/common.json @@ -149,6 +149,11 @@ "practiceProgressLabel": "연습 진척도", "decreasePracticeProgressLabel": "진척도 감소", "increasePracticeProgressLabel": "진척도 증가", + "firstDynamicsPlanLabel": "오늘 첫 다이내믹 계획", + "firstDynamicsPlanOpenAction": "{at} {role} 다이내믹 열기", + "firstDynamicsPlanBody": "{at} {section}에서 {role} 파트의 다이내믹 계획이 있습니다.", + "firstDynamicsPlanArmed": "{at}에서 {role} 파트의 다이내믹을 맞춘 다음 합주를 시작하세요.", + "firstDynamicsPlanUnavailable": "다이내믹을 맞춰야 하는 파트가 없습니다. 합주용 다이내믹 카피가 있는 파트가 생길 때까지 오늘 맵에 머무르세요.", "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..83b79d564 100644 --- a/apps/desktop/vite.config.ts +++ b/apps/desktop/vite.config.ts @@ -6,6 +6,18 @@ import { fileURLToPath } from "node:url"; const configDirectory = path.dirname(fileURLToPath(import.meta.url)); +/** Production files whose V8 coverage is owned by the desktop test gate. */ +export const DESKTOP_OWNED_PRODUCTION_COVERAGE = [ + "src/App.tsx", + "src/lib/export.ts", + "src/i18n/index.ts", + "src/features/score/ScoreViewer.tsx", + "src/features/score/ScoreView.tsx", + "src/features/score/scoreStorage.ts", + "src/features/workspace/firstDynamicsPlan.ts", + "src/features/workspace/FirstDynamicsPlanCallout.tsx" +]; + export default defineConfig({ plugins: [react(), tailwindcss()], resolve: { @@ -19,14 +31,7 @@ export default defineConfig({ setupFiles: ["./src/setupTests.ts"], coverage: { provider: "v8", - include: [ - "src/App.tsx", - "src/lib/export.ts", - "src/i18n/index.ts", - "src/features/score/ScoreViewer.tsx", - "src/features/score/ScoreView.tsx", - "src/features/score/scoreStorage.ts" - ], + include: DESKTOP_OWNED_PRODUCTION_COVERAGE, thresholds: { lines: 90, functions: 90, diff --git a/docs/design-system/component-contract.md b/docs/design-system/component-contract.md index 22602c313..f82e29bc0 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 Dynamics Plan Callout | workspace next-action pattern | `apps/desktop/src/features/workspace/FirstDynamicsPlanCallout.tsx` | Name the owning part when an active graph node corroborates it, the owned `dynamicsPlan` copy, the labeled section start, and the time. Do not invent that copy from `groove`, cue text, `simplification`, overlap warnings, range copy, `harmony.chord`, `harmony.functionLabel`, `setupNote`, `transpositionPlan`, confirmed overrides, `harmonicExplanation`, or confidence notes. Open scrolls the renderer-owned song-structure section. Keep the unavailable state guidance-only. Distinct from first-setup-note, first-transposition-plan, and first-tuning-plan. | | 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-dynamics-plan-navigation.md b/docs/doctoring/reduced-motion-first-dynamics-plan-navigation.md new file mode 100644 index 000000000..448086536 --- /dev/null +++ b/docs/doctoring/reduced-motion-first-dynamics-plan-navigation.md @@ -0,0 +1,3 @@ +# Reduced-motion first dynamics-plan navigation + +Open tonight's first dynamics plan with `behavior: "auto"` when `prefers-reduced-motion: reduce` matches. Do not keep a smooth scroll for that next action. diff --git a/packages/shared-types/src/index.ts b/packages/shared-types/src/index.ts index cba4606a2..d0825a415 100644 --- a/packages/shared-types/src/index.ts +++ b/packages/shared-types/src/index.ts @@ -139,6 +139,7 @@ export type RehearsalRole = { simplification: string; setupNote: string; transpositionPlan?: string; + dynamicsPlan?: string; manualOverrides: ManualOverride[]; overlapWarnings: string[]; transcription?: TranscriptionNote[]; @@ -407,6 +408,48 @@ function isOneOf(options: readonly T[], value: unknown): value return typeof value === "string" && options.includes(value as T); } +/** Return whether a code point is in the cross-language plan whitespace set. */ +function isPlanWhitespaceCodePoint(codePoint: number): boolean { + return ( + (codePoint >= 0x0009 && codePoint <= 0x000d) || + codePoint === 0x0020 || + codePoint === 0x0085 || + codePoint === 0x00a0 || + codePoint === 0x1680 || + (codePoint >= 0x2000 && codePoint <= 0x200a) || + codePoint === 0x2028 || + codePoint === 0x2029 || + codePoint === 0x202f || + codePoint === 0x205f || + codePoint === 0x3000 || + codePoint === 0xfeff + ); +} + +/** Apply one explicit cross-language Unicode whitespace policy to plan text. */ +export function isNonEmptySingleLineText(value: unknown): value is string { + if (typeof value !== "string") { + return false; + } + let hasNonWhitespace = false; + for (const character of value) { + const codePoint = character.codePointAt(0)!; + if ( + codePoint === 0x000a || + codePoint === 0x000d || + codePoint === 0x0085 || + codePoint === 0x2028 || + codePoint === 0x2029 + ) { + return false; + } + if (!isPlanWhitespaceCodePoint(codePoint)) { + hasNonWhitespace = true; + } + } + return hasNonWhitespace; +} + /** Documented. */ function invalidField(path: string): string { return `Invalid rehearsal song contract: invalid field '${path}'`; @@ -474,6 +517,7 @@ const demoRehearsalSongSeed: RehearsalSong = { simplification: "Stay on roots if the chorus entrance gets muddy.", setupNote: "Keep the attack short so the verse breathes.", transpositionPlan: "If the singer drops to B minor, keep the shape a whole step lower and let keys keep the color tones.", + dynamicsPlan: "Keep the verse under the vocal so the chorus still has somewhere to lift.", manualOverrides: [], overlapWarnings: [ "Density warning: competing with Keyboard Left Hand in low register." @@ -1497,6 +1541,7 @@ function validateRehearsalRole(value: unknown, path: string): string | null { "simplification", "setupNote", "transpositionPlan", + "dynamicsPlan", "manualOverrides", "overlapWarnings", "transcription", @@ -1552,6 +1597,9 @@ function validateRehearsalRole(value: unknown, path: string): string | null { if (value.transpositionPlan !== undefined && typeof value.transpositionPlan !== "string") { return invalidField(`${path}.transpositionPlan`); } + if (value.dynamicsPlan !== undefined && !isNonEmptySingleLineText(value.dynamicsPlan)) { + return invalidField(`${path}.dynamicsPlan`); + } if (!isDenseArray(value.manualOverrides)) { return invalidField(`${path}.manualOverrides`); } diff --git a/packages/shared-types/test/index.test.ts b/packages/shared-types/test/index.test.ts index 564ee1827..fecbec905 100644 --- a/packages/shared-types/test/index.test.ts +++ b/packages/shared-types/test/index.test.ts @@ -738,6 +738,7 @@ describe("shared type helpers", () => { expect(song.sections[0]?.roles[2]?.harmony?.source).toBe("model"); expect(song.sections[0]?.roles[0]?.harmonicExplanation).toContain("tonal floor"); expect(song.sections[0]?.roles[0]?.transpositionPlan).toContain("whole step lower"); + expect(song.sections[0]?.roles[0]?.dynamicsPlan).toContain("chorus still has somewhere to lift"); expect(song.collaboration?.assignments).toHaveLength(2); expect(song.collaboration?.comments[0]?.status).toBe("open"); expect(song.sections[0]?.roles[2]?.manualOverrides?.[0]).toMatchObject({ @@ -763,6 +764,28 @@ describe("shared type helpers", () => { expect(second.collaboration?.assignments).toHaveLength(2); }); + it("keeps optional dynamics plans aligned with Rust project loading", () => { + for (const dynamicsPlan of [ + "", + " ", + "\uFEFF", + "\u0085", + "hold here\nthen lift", + "hold here\rthen lift", + "hold here\u0085then lift" + ]) { + const song = createDemoRehearsalSong(); + song.sections[0]!.roles[0]!.dynamicsPlan = dynamicsPlan; + + expect(isRehearsalSong(song)).toBe(false); + expect(() => parseRehearsalSong(song)).toThrow("sections[0].roles[0].dynamicsPlan"); + } + + const paddedPlan = createDemoRehearsalSong(); + paddedPlan.sections[0]!.roles[0]!.dynamicsPlan = "\uFEFF Hold the string \uFEFF"; + expect(isRehearsalSong(paddedPlan)).toBe(true); + }); + it("validates and parses rehearsal song payloads", () => { const song = createDemoRehearsalSong(); const malformedSong = createDemoRehearsalSong() as unknown as { @@ -1257,6 +1280,12 @@ describe("shared type helpers", () => { song.sections[0]!.roles[0]!.transpositionPlan = 2 as never; }) }, + { + message: "sections[0].roles[0].dynamicsPlan", + payload: createInvalidSong((song) => { + song.sections[0]!.roles[0]!.dynamicsPlan = 2 as never; + }) + }, { message: "sections[0].roles[0].practiceProgress", payload: createInvalidSong((song) => {