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/FirstHarmonicFunctionCallout.workspace-scope.test.tsx b/apps/desktop/src/features/workspace/FirstHarmonicFunctionCallout.workspace-scope.test.tsx new file mode 100644 index 000000000..207fd1e16 --- /dev/null +++ b/apps/desktop/src/features/workspace/FirstHarmonicFunctionCallout.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 { FirstHarmonicFunctionCallout } from "./FirstHarmonicFunctionCallout"; + +describe("FirstHarmonicFunctionCallout 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 function 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..7bf8b8cb1 100644 --- a/apps/desktop/src/features/workspace/Workspace.test.tsx +++ b/apps/desktop/src/features/workspace/Workspace.test.tsx @@ -217,7 +217,7 @@ describe("Workspace", () => { fireEvent.click(screen.getByRole("tab", { name: "Bass Guitar" })); - expect(screen.getByText("vi pedal anchor")).toBeTruthy(); + expect(screen.getAllByText("vi pedal anchor").length).toBeGreaterThan(0); expect(screen.getAllByText("Stay on roots if the chorus entrance gets muddy.").length).toBeGreaterThan(0); }); @@ -326,4 +326,30 @@ describe("Workspace", () => { expect(screen.getByText("합주 우선순위")).toBeTruthy(); expect(screen.getByText("역할과 화성")).toBeTruthy(); }); + + it("names tonight's first harmonic function 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("vi pedal anchor").length).toBeGreaterThan(0); + const action = screen.getByRole("button", { + name: "Open Bass Guitar function at 0:10" + }); + expect(action).toBeTruthy(); + fireEvent.click(action); + expect(scrollIntoView).toHaveBeenCalledWith({ block: "nearest", behavior: "smooth" }); + expect( + screen.getByText(/Lock that function 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..ce83e1166 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 { FirstHarmonicFunctionCallout } from "./FirstHarmonicFunctionCallout"; 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/firstHarmonicFunction.inherited-metadata.test.ts b/apps/desktop/src/features/workspace/firstHarmonicFunction.inherited-metadata.test.ts new file mode 100644 index 000000000..825c6a102 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstHarmonicFunction.inherited-metadata.test.ts @@ -0,0 +1,120 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstHarmonicFunction } from "./firstHarmonicFunction"; + +function songWithFunctionLabel() { + const song = createDemoRehearsalSong(); + const section = structuredClone(song.sections[0]!); + section.id = "function-own"; + section.roles = [ + { + ...section.roles[0]!, + id: "bass-guitar", + name: "Bass Guitar", + rehearsalPriority: "high", + harmony: { + chord: "C#m7", + functionLabel: "vi pedal anchor", + source: "model" + } + } + ]; + section.partGraph = [{ role_id: "bass-guitar", is_active: true, handoff_to: [], handoff_from: [] }]; + song.sections = [section]; + return { song, section }; +} + +describe("resolveFirstHarmonicFunction inherited metadata", () => { + it("rejects a song or section whose required metadata is inherited", () => { + const { song, section } = songWithFunctionLabel(); + const inheritedSong = Object.create({ sections: song.sections }) as typeof song; + expect(resolveFirstHarmonicFunction(inheritedSong)).toBeNull(); + + const inheritedSection = Object.create(section) as typeof section; + song.sections = [inheritedSection]; + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("rejects inherited timing fields", () => { + const { song, section } = songWithFunctionLabel(); + section.timeRange = Object.create({ start: 10, end: 30 }) as typeof section.timeRange; + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("contains exceptions from own runtime accessors instead of trusting them", () => { + const { song, section } = songWithFunctionLabel(); + Object.defineProperty(section.roles[0]!.harmony, "functionLabel", { + configurable: true, + enumerable: true, + get() { + throw new Error("hostile functionLabel getter"); + } + }); + + expect(() => resolveFirstHarmonicFunction(song)).not.toThrow(); + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("does not treat own accessors as stable harmonic-function identity authority", () => { + const { song, section } = songWithFunctionLabel(); + Object.defineProperty(section, "id", { + configurable: true, + enumerable: true, + get() { + return "function-own"; + } + }); + + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("does not let inherited function labels establish the named copy", () => { + const { song, section } = songWithFunctionLabel(); + const inheritedHarmony = Object.create({ + functionLabel: "Inherited harmonic function" + }) as (typeof section.roles)[0]["harmony"]; + Object.defineProperties(inheritedHarmony, { + chord: { configurable: true, enumerable: true, value: "C#m7" }, + source: { configurable: true, enumerable: true, value: "model" } + }); + const inheritedRole = Object.create({ + harmony: inheritedHarmony + }) 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(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("does not let inherited role or graph metadata establish the holding part", () => { + const { song, section } = songWithFunctionLabel(); + const node = section.partGraph[0]!; + section.partGraph = [Object.create(node) as typeof node]; + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("rejects arrays masquerading as section records", () => { + const { song, section } = songWithFunctionLabel(); + const arraySection = Object.assign([], section) as unknown as typeof section; + song.sections = [arraySection]; + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("does not let inherited harmony records supply the named function", () => { + const { song, section } = songWithFunctionLabel(); + const inheritedHarmony = Object.create({ + chord: "C#m7", + functionLabel: "vi pedal anchor", + source: "model" + }) as (typeof section.roles)[0]["harmony"]; + Object.defineProperty(section.roles[0]!, "harmony", { + configurable: true, + enumerable: true, + value: inheritedHarmony + }); + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstHarmonicFunction.proxy-authority.test.ts b/apps/desktop/src/features/workspace/firstHarmonicFunction.proxy-authority.test.ts new file mode 100644 index 000000000..36a9a0adb --- /dev/null +++ b/apps/desktop/src/features/workspace/firstHarmonicFunction.proxy-authority.test.ts @@ -0,0 +1,49 @@ +import { createDemoRehearsalSong, type RehearsalRole } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstHarmonicFunction } from "./firstHarmonicFunction"; + +describe("resolveFirstHarmonicFunction Proxy authority", () => { + it("uses the owned function-label descriptor instead of a Proxy get substitution", () => { + const song = createDemoRehearsalSong(); + const role = song.sections[0]!.roles[0]!; + const trustedHarmony = role.harmony!; + const hostileHarmony = new Proxy(trustedHarmony, { + get(target, property, receiver) { + if (property === "functionLabel") { + return "proxy injected function"; + } + return Reflect.get(target, property, receiver); + } + }); + Object.defineProperty(role, "harmony", { + configurable: true, + enumerable: true, + value: hostileHarmony + }); + + expect(resolveFirstHarmonicFunction(song)?.functionLabel).toBe("vi pedal anchor"); + }); + + it("does not let a Proxy get trap replace the owned role identity used for graph corroboration", () => { + const song = createDemoRehearsalSong(); + const section = song.sections[0]!; + const role = section.roles[0]!; + Object.defineProperty(role, "id", { + configurable: true, + enumerable: true, + writable: true, + value: "descriptor-only-role" + }); + const hostileRole = new Proxy(role, { + get(target, property, receiver) { + if (property === "id") { + return "bass-guitar"; + } + return Reflect.get(target, property, receiver); + } + }); + section.roles = [hostileRole as RehearsalRole]; + + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstHarmonicFunction.test.ts b/apps/desktop/src/features/workspace/firstHarmonicFunction.test.ts new file mode 100644 index 000000000..4f14b163d --- /dev/null +++ b/apps/desktop/src/features/workspace/firstHarmonicFunction.test.ts @@ -0,0 +1,267 @@ +import { describe, expect, it } from "vitest"; +import { MAX_SECTION_TIME_SECONDS, createDemoRehearsalSong } from "@bandscope/shared-types"; +import { formatHarmonicFunctionTime, resolveFirstHarmonicFunction } from "./firstHarmonicFunction"; + +function withFunctionSection( + overrides: { + id?: string; + start?: number; + end?: number; + functionLabel?: string; + label?: "intro" | "verse" | "pre-chorus" | "chorus" | "bridge" | "outro" | "tag" | "pickup" | "stop" | "handoff"; + roleId?: string; + roleName?: string; + priority?: "low" | "medium" | "high"; + isActive?: boolean; + chord?: string; + } = {} +) { + const song = createDemoRehearsalSong(); + const verse = song.sections[0]!; + const section = structuredClone(verse); + section.id = overrides.id ?? "verse-function"; + 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: overrides.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." + }, + manualOverrides: [] + } + ]; + section.partGraph = [ + { + role_id: roleId, + is_active: overrides.isActive ?? true, + handoff_to: [], + handoff_from: [] + } + ]; + song.sections = [section]; + return song; +} + +describe("resolveFirstHarmonicFunction", () => { + it("picks the demo song's earliest high-priority harmonic function and the part that owns it", () => { + const resolved = resolveFirstHarmonicFunction(createDemoRehearsalSong()); + expect(resolved?.section.id).toBe("verse-1"); + expect(resolved?.holdingRole.id).toBe("bass-guitar"); + expect(resolved?.functionLabel).toBe("vi pedal anchor"); + expect(resolved?.atSeconds).toBe(10); + expect(formatHarmonicFunctionTime(resolved?.atSeconds ?? -1)).toBe("0:10"); + expect(formatHarmonicFunctionTime(Number.NaN)).toBe("0:00"); + expect(formatHarmonicFunctionTime(-4)).toBe("0:00"); + }); + + it("does not invent a harmonic function from groove, cue, simplification, overlap, range, chords, explanations, setup notes, confirmed overrides, or confidence notes", () => { + const song = withFunctionSection(); + song.sections[0]!.roles[0]!.harmony = { + ...song.sections[0]!.roles[0]!.harmony, + functionLabel: "" + }; + 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]!.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]!.setupNote = "Watch the breath before the last line of the verse."; + 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: "vi pedal anchor" + }; + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("skips a blank harmonic function", () => { + expect(resolveFirstHarmonicFunction(withFunctionSection({ functionLabel: " " }))).toBeNull(); + }); + + it("prefers the earlier of two harmonic functions", () => { + const song = withFunctionSection({ + id: "verse-late", + start: 40, + end: 56, + roleId: "keys-right", + functionLabel: "Late Imaj7 color." + }); + const earlier = structuredClone(song.sections[0]!); + earlier.id = "verse-early"; + earlier.roles = [ + { + ...earlier.roles[0]!, + id: "lead-vocal", + name: "Lead Vocal", + rehearsalPriority: "low", + harmony: { + ...earlier.roles[0]!.harmony, + functionLabel: "Earlier vi pull." + } + } + ]; + 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 = resolveFirstHarmonicFunction(song); + expect(resolved?.section.id).toBe("verse-early"); + expect(resolved?.holdingRole.id).toBe("lead-vocal"); + expect(resolved?.functionLabel).toBe("Earlier vi pull."); + expect(resolved?.atSeconds).toBe(8); + }); + + it("breaks same-time harmonic-function ties with locale-independent id ordering", () => { + const song = withFunctionSection({ id: "ä-function", start: 10, end: 26 }); + const ascii = structuredClone(song.sections[0]!); + ascii.id = "z-function"; + song.sections = [song.sections[0]!, ascii]; + + expect(resolveFirstHarmonicFunction(song)?.section.id).toBe("z-function"); + }); + + it("prefers a high-priority function part over a low-priority part in the same section", () => { + const song = withFunctionSection({ + roleId: "keys-right", + roleName: "Keys", + priority: "low", + functionLabel: "Low-priority color." + }); + const section = song.sections[0]!; + const highRole = { + ...section.roles[0]!, + id: "lead-vocal", + name: "Lead Vocal", + rehearsalPriority: "high" as const, + harmony: { + ...section.roles[0]!.harmony, + functionLabel: "High-priority vi pull." + } + }; + 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(resolveFirstHarmonicFunction(song)?.holdingRole.id).toBe("lead-vocal"); + expect(resolveFirstHarmonicFunction(song)?.functionLabel).toBe("High-priority vi pull."); + }); + + it("breaks equal-priority role ties with locale-independent id ordering", () => { + const song = withFunctionSection({ roleId: "ä-role", roleName: "Umlaut role", priority: "high" }); + const section = song.sections[0]!; + const asciiRole = { + ...section.roles[0]!, + id: "z-role", + name: "ASCII role", + harmony: { + ...section.roles[0]!.harmony, + functionLabel: "ASCII function." + } + }; + 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(resolveFirstHarmonicFunction(song)?.holdingRole.id).toBe("z-role"); + expect(resolveFirstHarmonicFunction(song)?.functionLabel).toBe("ASCII function."); + }); + + it("skips a harmonic function whose graph node is inactive", () => { + expect(resolveFirstHarmonicFunction(withFunctionSection({ isActive: false }))).toBeNull(); + }); + + it("skips a harmonic function whose rehearsal window is unbounded", () => { + expect(resolveFirstHarmonicFunction(withFunctionSection({ start: Number.NaN, end: 30 }))).toBeNull(); + }); + + it("skips a harmonic function whose end precedes its start", () => { + expect(resolveFirstHarmonicFunction(withFunctionSection({ start: 30, end: 10 }))).toBeNull(); + }); + + it("skips a zero-length harmonic-function window", () => { + expect(resolveFirstHarmonicFunction(withFunctionSection({ start: 10, end: 10 }))).toBeNull(); + }); + + it("skips a harmonic function whose endpoint overflows the shared timing bound", () => { + expect( + resolveFirstHarmonicFunction( + withFunctionSection({ + start: MAX_SECTION_TIME_SECONDS, + end: MAX_SECTION_TIME_SECONDS + 1 + }) + ) + ).toBeNull(); + }); + + it("returns null for a non-object song root", () => { + expect(resolveFirstHarmonicFunction(null as never)).toBeNull(); + }); + + it("returns null when the runtime section collection is sparse", () => { + const song = withFunctionSection(); + const sparseSections: typeof song.sections = new Array(2); + sparseSections[1] = song.sections[0]!; + song.sections = sparseSections; + expect(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("keeps the harmonic function unnamed when role identities are duplicated", () => { + const song = withFunctionSection(); + 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(resolveFirstHarmonicFunction(song)).toBeNull(); + }); + + it("bounds the harmonic function to 180 Unicode code points", () => { + const song = withFunctionSection({ functionLabel: `${"G".repeat(200)}` }); + const resolved = resolveFirstHarmonicFunction(song); + expect(resolved?.functionLabel.length).toBe(180); + }); + + it("does not split a Unicode surrogate pair at the harmonic-function boundary", () => { + const song = withFunctionSection({ functionLabel: `${"a".repeat(179)}😀tail` }); + const resolved = resolveFirstHarmonicFunction(song); + expect(Array.from(resolved?.functionLabel ?? "")).toHaveLength(180); + expect(resolved?.functionLabel.endsWith("😀")).toBe(true); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstHarmonicFunction.time-authority.test.ts b/apps/desktop/src/features/workspace/firstHarmonicFunction.time-authority.test.ts new file mode 100644 index 000000000..8b7295149 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstHarmonicFunction.time-authority.test.ts @@ -0,0 +1,26 @@ +import { createDemoRehearsalSong } from "@bandscope/shared-types"; +import { describe, expect, it } from "vitest"; +import { resolveFirstHarmonicFunction } from "./firstHarmonicFunction"; + +describe("resolveFirstHarmonicFunction time authority", () => { + it("uses owned time-range descriptors instead of Proxy get substitutions", () => { + const song = createDemoRehearsalSong(); + const section = song.sections[0]!; + const trustedTimeRange = section.timeRange; + const hostileTimeRange = new Proxy(trustedTimeRange, { + get(target, property, receiver) { + if (property === "start") { + return 20; + } + return Reflect.get(target, property, receiver); + } + }); + Object.defineProperty(section, "timeRange", { + configurable: true, + enumerable: true, + value: hostileTimeRange + }); + + expect(resolveFirstHarmonicFunction(song)?.atSeconds).toBe(10); + }); +}); diff --git a/apps/desktop/src/features/workspace/firstHarmonicFunction.ts b/apps/desktop/src/features/workspace/firstHarmonicFunction.ts new file mode 100644 index 000000000..7414f2de9 --- /dev/null +++ b/apps/desktop/src/features/workspace/firstHarmonicFunction.ts @@ -0,0 +1,321 @@ +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; +const MAX_FUNCTION_LABEL_CHARACTERS = 180; + +type RankedRoleMetadata = Readonly<{ + id: string; + name: string; + rehearsalPriority: keyof typeof PRIORITY_RANK; +}>; + +/** Tonight's first harmonic function: the earliest labeled section and the part that owns it. */ +export type FirstHarmonicFunction = { + section: RehearsalSection; + holdingRole: RehearsalRole; + holdingRoleId: string; + holdingRoleName: string; + functionLabel: string; + atSeconds: number; +}; + +/** Format a non-negative harmonic-function time as m:ss for rehearsal copy. */ +export function formatHarmonicFunctionTime(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 a getter 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; +} + +/** 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 snapshotted own harmonic function label, or null when it cannot be shown. */ +function ownedFunctionLabel(role: unknown): string | null { + if (!isRuntimeObject(role)) { + return null; + } + const harmony = ownDataValue(role, "harmony"); + if (!isRuntimeObject(harmony)) { + return null; + } + const functionLabel = ownDataValue(harmony, "functionLabel"); + if (typeof functionLabel !== "string") { + return null; + } + const trimmed = functionLabel.trim(); + if (trimmed.length === 0) { + return null; + } + return truncateCodePoints(trimmed, MAX_FUNCTION_LABEL_CHARACTERS); +} + +/** Snapshot trusted role identity, display name, and priority without Proxy get authority. */ +function ownedRankedRoleMetadata(role: RehearsalRole): RankedRoleMetadata | 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 { + 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: RehearsalRole[]): RehearsalRole | null { + if (roles.length === 0) { + return null; + } + return ( + [...roles].sort((left, right) => { + const leftMetadata = ownedRankedRoleMetadata(left); + const rightMetadata = ownedRankedRoleMetadata(right); + if (!leftMetadata || !rightMetadata) { + return leftMetadata ? -1 : rightMetadata ? 1 : 0; + } + const priorityDelta = + PRIORITY_RANK[leftMetadata.rehearsalPriority] - + PRIORITY_RANK[rightMetadata.rehearsalPriority]; + if (priorityDelta !== 0) { + return priorityDelta; + } + return compareStableId(leftMetadata.id, rightMetadata.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.flatMap((role) => { + if (!isRuntimeObject(role)) { + return []; + } + const id = ownDataValue(role, "id"); + return typeof id === "string" && id.trim().length > 0 ? [id] : []; + }); + const safeGraphRoleIds = section.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( + section.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 section.roles.filter((role) => { + if (!isRuntimeObject(role)) { + return false; + } + const metadata = ownedRankedRoleMetadata(role as RehearsalRole); + return ( + metadata !== null && + !repeatedRoleIds.has(metadata.id) && + activeIds.has(metadata.id) + ); + }) as RehearsalRole[]; +} + +/** Resolve a harmonic function after the runtime root has passed its structural boundary checks. */ +function resolveSafeFirstHarmonicFunction(song: RehearsalSong): FirstHarmonicFunction | null { + if (!isRuntimeObject(song) || !hasOwnData(song, "sections") || !isDenseRuntimeArray(song.sections)) { + return null; + } + + const candidates = song.sections + .map((section) => ({ + section, + timeRange: isRuntimeObject(section) ? ownedBoundedTimeRange(section) : null + })) + .filter( + ({ section, timeRange }) => + 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 && + timeRange !== null + ) + .flatMap(({ section, timeRange }) => { + if (!timeRange) { + return []; + } + const holdingRole = pickHoldingRole( + rankedActiveRoles(section).filter((role) => ownedFunctionLabel(role) !== null) + ); + if (!holdingRole) { + return []; + } + const holdingRoleMetadata = ownedRankedRoleMetadata(holdingRole); + const functionLabel = ownedFunctionLabel(holdingRole); + if (!holdingRoleMetadata || !functionLabel) { + return []; + } + return [ + { + section, + holdingRole, + holdingRoleId: holdingRoleMetadata.id, + holdingRoleName: holdingRoleMetadata.name, + functionLabel, + atSeconds: 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 harmonic function, or null when untrusted runtime metadata cannot be read safely. */ +export function resolveFirstHarmonicFunction(song: RehearsalSong): FirstHarmonicFunction | null { + try { + return resolveSafeFirstHarmonicFunction(song); + } catch { + return null; + } +} diff --git a/apps/desktop/src/i18n/index.test.ts b/apps/desktop/src/i18n/index.test.ts index dc49a0a25..2f68c6ecc 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-harmonic-function next-action copy particle-safe", () => { + const t = createTranslator("ko"); + expect(t("firstHarmonicFunctionOpenAction")).toBe("{at} {role} 화성 기능 위치 열기"); + expect(t("firstHarmonicFunctionBody")).toBe("{at} {section}에서 {role} 파트의 화성 기능이 있습니다."); + expect(t("firstHarmonicFunctionArmed")).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..3bea94788 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", + "firstHarmonicFunctionLabel": "Tonight's first harmonic function", + "firstHarmonicFunctionOpenAction": "Open {role} function at {at}", + "firstHarmonicFunctionBody": "{role} still has a harmonic function in the {section} at {at}.", + "firstHarmonicFunctionArmed": "Lock that function on {role} at {at} before the room starts.", + "firstHarmonicFunctionUnavailable": "Nothing still has a harmonic function. Stay on tonight's map until a part owns rehearsal-facing function 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..f18c4f019 100644 --- a/apps/desktop/src/locales/ko/common.json +++ b/apps/desktop/src/locales/ko/common.json @@ -149,6 +149,11 @@ "practiceProgressLabel": "연습 진척도", "decreasePracticeProgressLabel": "진척도 감소", "increasePracticeProgressLabel": "진척도 증가", + "firstHarmonicFunctionLabel": "오늘 첫 화성 기능", + "firstHarmonicFunctionOpenAction": "{at} {role} 화성 기능 위치 열기", + "firstHarmonicFunctionBody": "{at} {section}에서 {role} 파트의 화성 기능이 있습니다.", + "firstHarmonicFunctionArmed": "{at}에서 {role} 파트의 화성 기능을 맞춘 다음 합주를 시작하세요.", + "firstHarmonicFunctionUnavailable": "화성 기능이 있는 파트가 없습니다. 합주용 기능이 있는 파트가 생길 때까지 오늘 맵에 머무르세요.", "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..4f13134da 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 Harmonic Function Callout | workspace next-action pattern | `apps/desktop/src/features/workspace/FirstHarmonicFunctionCallout.tsx` | Name the owning part when an active graph node corroborates it, the owned `harmony.functionLabel` copy, the labeled section start, and the time. Do not invent that copy from `groove`, cue text, `simplification`, overlap warnings, range copy, `harmony.chord`, `setupNote`, confirmed overrides, `harmonicExplanation`, or confidence notes. Open scrolls the renderer-owned song-structure section. Keep the unavailable state guidance-only. Distinct from first-harmonic-explanation, first-confirmed-harmony, first-setup-note, and first-transpose 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-harmonic-function-navigation.md b/docs/doctoring/reduced-motion-first-harmonic-function-navigation.md new file mode 100644 index 000000000..738bb4559 --- /dev/null +++ b/docs/doctoring/reduced-motion-first-harmonic-function-navigation.md @@ -0,0 +1,5 @@ +# Reduced-motion first harmonic-function navigation + +When `prefers-reduced-motion: reduce` matches, `FirstHarmonicFunctionCallout` scrolls the renderer-owned song-structure section with `behavior: "auto"`. Otherwise it uses `behavior: "smooth"`. + +Open still names the owning part, labeled section, and time. Analysis `section.id` is never DOM-ID authority.