@molecule/app-feature-piano-roll-angular 0.0.0-stage → 1.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,789 @@
1
+ /**
2
+ * PianoRoll component (React parity): MIDI piano-roll editor with a vertical
3
+ * piano keyboard, a horizontal time grid and draggable / resizable notes.
4
+ *
5
+ * @module
6
+ */
7
+ import { Component, signal, ViewChild, } from '@angular/core';
8
+ import { useTranslation } from '@molecule/app-angular';
9
+ import { getClassMap } from '@molecule/app-ui';
10
+ import { beatsToPixels, DEFAULT_NOTE_VELOCITY, DRAG_DISTANCE_THRESHOLD_PX, isBlackKey, MIN_NOTE_DURATION_BEATS, PIANO_KEYS_WIDTH_PX, pitchLabel, pitchToY, pixelsToBeats, snapBeat, snapBeatRound, snapToBeats, yToPitch, } from './geometry.js';
11
+ import * as i0 from "@angular/core";
12
+ const _c0 = ["grid"];
13
+ const _forTrack0 = ($index, $item) => $item.id;
14
+ function PianoRoll_For_2_Conditional_1_Template(rf, ctx) { if (rf & 1) {
15
+ i0.ɵɵdomElementStart(0, "span", 11);
16
+ i0.ɵɵtext(1);
17
+ i0.ɵɵdomElementEnd();
18
+ } if (rf & 2) {
19
+ const pitch_r1 = i0.ɵɵnextContext().$implicit;
20
+ const ctx_r1 = i0.ɵɵnextContext();
21
+ i0.ɵɵclassMap(ctx_r1.keyLabelClasses());
22
+ i0.ɵɵadvance();
23
+ i0.ɵɵtextInterpolate(ctx_r1.pitchLabel(pitch_r1));
24
+ } }
25
+ function PianoRoll_For_2_Template(rf, ctx) { if (rf & 1) {
26
+ i0.ɵɵdomElementStart(0, "div", 9);
27
+ i0.ɵɵconditionalCreate(1, PianoRoll_For_2_Conditional_1_Template, 2, 3, "span", 10);
28
+ i0.ɵɵdomElementEnd();
29
+ } if (rf & 2) {
30
+ const pitch_r1 = ctx.$implicit;
31
+ const ctx_r1 = i0.ɵɵnextContext();
32
+ i0.ɵɵstyleMap(ctx_r1.keyStyle(ctx_r1.isBlackKey(pitch_r1)));
33
+ i0.ɵɵattribute("data-pitch", pitch_r1)("data-key-color", ctx_r1.isBlackKey(pitch_r1) ? "black" : "white");
34
+ i0.ɵɵadvance();
35
+ i0.ɵɵconditional(ctx_r1.isC(pitch_r1) ? 1 : -1);
36
+ } }
37
+ function PianoRoll_For_6_Template(rf, ctx) { if (rf & 1) {
38
+ i0.ɵɵdomElement(0, "div", 12);
39
+ } if (rf & 2) {
40
+ const pitch_r3 = ctx.$implicit;
41
+ const ctx_r1 = i0.ɵɵnextContext();
42
+ i0.ɵɵstyleMap(ctx_r1.rowStyle(pitch_r3));
43
+ i0.ɵɵattribute("data-pitch", pitch_r3)("data-key-color", ctx_r1.isBlackKey(pitch_r3) ? "black" : "white");
44
+ } }
45
+ function PianoRoll_For_8_Template(rf, ctx) { if (rf & 1) {
46
+ i0.ɵɵdomElement(0, "div", 13);
47
+ } if (rf & 2) {
48
+ const beat_r4 = ctx.$implicit;
49
+ const ctx_r1 = i0.ɵɵnextContext();
50
+ i0.ɵɵstyleMap(ctx_r1.lineStyle(beat_r4));
51
+ i0.ɵɵattribute("data-beat", beat_r4)("data-bar", beat_r4 % 4 === 0 ? "true" : "false");
52
+ } }
53
+ function PianoRoll_Conditional_9_Template(rf, ctx) { if (rf & 1) {
54
+ i0.ɵɵdomElement(0, "div", 14);
55
+ } if (rf & 2) {
56
+ const ctx_r1 = i0.ɵɵnextContext();
57
+ i0.ɵɵstyleMap(ctx_r1.cursorStyle());
58
+ } }
59
+ function PianoRoll_Conditional_12_Template(rf, ctx) { if (rf & 1) {
60
+ i0.ɵɵdomElementStart(0, "div", 15);
61
+ i0.ɵɵtext(1);
62
+ i0.ɵɵdomElementEnd();
63
+ } if (rf & 2) {
64
+ const ctx_r1 = i0.ɵɵnextContext();
65
+ i0.ɵɵclassMap(ctx_r1.srOnlyClass());
66
+ i0.ɵɵadvance();
67
+ i0.ɵɵtextInterpolate(ctx_r1.cursorLabel());
68
+ } }
69
+ function PianoRoll_For_14_Template(rf, ctx) { if (rf & 1) {
70
+ const _r5 = i0.ɵɵgetCurrentView();
71
+ i0.ɵɵdomElementStart(0, "div", 16);
72
+ i0.ɵɵdomListener("pointerdown", function PianoRoll_For_14_Template_div_pointerdown_0_listener($event) { const note_r6 = i0.ɵɵrestoreView(_r5).$implicit; const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.beginDrag($event, note_r6, "move")); })("contextmenu", function PianoRoll_For_14_Template_div_contextmenu_0_listener($event) { const note_r6 = i0.ɵɵrestoreView(_r5).$implicit; const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.handleNoteContextMenu($event, note_r6)); });
73
+ i0.ɵɵdomElementStart(1, "div", 17);
74
+ i0.ɵɵdomListener("pointerdown", function PianoRoll_For_14_Template_div_pointerdown_1_listener($event) { const note_r6 = i0.ɵɵrestoreView(_r5).$implicit; const ctx_r1 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r1.beginDrag($event, note_r6, "resize")); });
75
+ i0.ɵɵdomElementEnd()();
76
+ } if (rf & 2) {
77
+ const note_r6 = ctx.$implicit;
78
+ const ctx_r1 = i0.ɵɵnextContext();
79
+ i0.ɵɵstyleMap(ctx_r1.noteStyle(note_r6));
80
+ i0.ɵɵclassMap(ctx_r1.noteClasses());
81
+ i0.ɵɵattribute("aria-label", ctx_r1.noteAria(note_r6))("data-note-id", note_r6.id)("data-pitch", note_r6.pitch)("data-start-beat", note_r6.startBeat)("data-duration-beats", note_r6.durationBeats);
82
+ i0.ɵɵadvance();
83
+ i0.ɵɵstyleMap(ctx_r1.handleStyle);
84
+ i0.ɵɵattribute("aria-label", ctx_r1.resizeLabel());
85
+ } }
86
+ /**
87
+ * Next value of the module-wide grid-help id counter.
88
+ *
89
+ * React derives the note grid's `aria-describedby` id from `useId()`, which
90
+ * numbers ids from one process-wide counter; the grid names its visually
91
+ * hidden description element by it, so the port generates ids from the same
92
+ * kind of counter — unique per instance.
93
+ */
94
+ let nextGridHelpId = 0;
95
+ /**
96
+ * PianoRoll component.
97
+ *
98
+ * The host IS React's root `<div>` (`div[mol-piano-roll]`), matching React's
99
+ * root exactly. Renders a vertical piano keyboard on the left, a horizontal
100
+ * time grid on the right, and draggable / resizable note rectangles on top.
101
+ * Click an empty cell to paint a new note, drag a note body to move it
102
+ * (snapped), drag the right-edge handle to resize, right-click a note to
103
+ * delete it.
104
+ *
105
+ * Keyboard users get the same paint action: focus the grid (Tab), move the
106
+ * cell cursor with the arrow keys, and press Enter or Space to paint a new note
107
+ * at the cursor cell.
108
+ */
109
+ export class PianoRoll {
110
+ /** MIDI notes rendered on the grid, in display order. */
111
+ notes = [];
112
+ /** Horizontal scale in pixels per beat (defaults to 80 at render time). */
113
+ pixelsPerBeat;
114
+ /** Row height in pixels per pitch (defaults to 20 at render time). */
115
+ noteHeight;
116
+ /** Lowest visible pitch (defaults to 21 at render time). */
117
+ lowestPitch;
118
+ /** Highest visible pitch (defaults to 108 at render time). */
119
+ highestPitch;
120
+ /** Snap resolution (defaults to `'1/16'` at render time). */
121
+ snap;
122
+ /** Beats the time grid covers (auto-sized from the notes when omitted). */
123
+ beatsCount;
124
+ /** Called with a freshly-painted note. */
125
+ onNoteAdd;
126
+ /** Called with the new geometry when a note body is dragged. */
127
+ onNoteMove;
128
+ /** Called with the new duration when a note's right-edge handle is dragged. */
129
+ onNoteResize;
130
+ /** Called with the note id when a note is right-clicked. */
131
+ onNoteDelete;
132
+ /** Extra classes merged onto the root element. */
133
+ className;
134
+ /** The grid surface, whose bounding box turns a click into a beat + pitch. */
135
+ gridRef;
136
+ /**
137
+ * The visually hidden grid-description element's id, which the grid's
138
+ * `aria-describedby` names (React derives it from `useId()`; a per-instance
139
+ * counter gives each instance its own).
140
+ */
141
+ gridHelpId = `piano-roll-grid-help-${nextGridHelpId++}`;
142
+ /** The i18n state; `t` re-reads the provider on every call and on every locale switch. */
143
+ i18n = useTranslation();
144
+ /** The drag gesture in progress, or null. */
145
+ drag = null;
146
+ /** The keyboard cell cursor (the cell Enter / Space paint into), in raw beats + pitch. */
147
+ rawCursor = signal({ beat: 0, pitch: 108 }, /* @ts-ignore */
148
+ ...(ngDevMode ? [{ debugName: "rawCursor" }] : /* istanbul ignore next */ []));
149
+ /** `true` while the grid surface (or a child) has focus. */
150
+ gridFocused = signal(false, /* @ts-ignore */
151
+ ...(ngDevMode ? [{ debugName: "gridFocused" }] : /* istanbul ignore next */ []));
152
+ /** React's root inline geometry (constant for every render). */
153
+ rootStyle = {
154
+ display: 'flex',
155
+ 'align-items': 'stretch',
156
+ width: '100%',
157
+ overflow: 'auto',
158
+ position: 'relative',
159
+ };
160
+ /** The resize handle's inline geometry (React's `handleStyle`). */
161
+ handleStyle = {
162
+ position: 'absolute',
163
+ top: '0px',
164
+ right: '0px',
165
+ bottom: '0px',
166
+ width: '6px',
167
+ cursor: 'ew-resize',
168
+ 'touch-action': 'none',
169
+ };
170
+ /**
171
+ * Seeds the keyboard cell cursor from the mounted props and registers the
172
+ * global drag listeners, as React's effect does on mount.
173
+ */
174
+ ngOnInit() {
175
+ this.rawCursor.set({ beat: 0, pitch: this.highestPitch ?? 108 });
176
+ window.addEventListener('pointermove', this.onMove);
177
+ window.addEventListener('pointerup', this.onUp);
178
+ window.addEventListener('pointercancel', this.onUp);
179
+ }
180
+ /** Removes the global drag listeners, as React's effect cleanup does. */
181
+ ngOnDestroy() {
182
+ window.removeEventListener('pointermove', this.onMove);
183
+ window.removeEventListener('pointerup', this.onUp);
184
+ window.removeEventListener('pointercancel', this.onUp);
185
+ }
186
+ /**
187
+ * The current class map.
188
+ *
189
+ * @returns The UIClassMap.
190
+ */
191
+ cm() {
192
+ return getClassMap();
193
+ }
194
+ /**
195
+ * The root element's class list (React's root `cm.cn`).
196
+ *
197
+ * @returns The class string.
198
+ */
199
+ classes() {
200
+ return this.cm().cn(this.className);
201
+ }
202
+ /**
203
+ * The piano-key label span's class list.
204
+ *
205
+ * @returns The class string.
206
+ */
207
+ keyLabelClasses() {
208
+ return this.cm().cn(this.cm().textSize('xs'));
209
+ }
210
+ /**
211
+ * One note block's class list.
212
+ *
213
+ * @returns The class string.
214
+ */
215
+ noteClasses() {
216
+ return this.cm().cn(this.cm().cursorPointer);
217
+ }
218
+ /**
219
+ * The screen-reader-only status class.
220
+ *
221
+ * @returns The class string.
222
+ */
223
+ srOnlyClass() {
224
+ return this.cm().cn(this.cm().srOnly);
225
+ }
226
+ /**
227
+ * The derived grid geometry for the current props.
228
+ *
229
+ * @returns The geometry of one render.
230
+ */
231
+ geometry() {
232
+ const pixelsPerBeat = this.pixelsPerBeat ?? 80;
233
+ const noteHeight = this.noteHeight ?? 20;
234
+ const lowestPitch = this.lowestPitch ?? 21;
235
+ const highestPitch = this.highestPitch ?? 108;
236
+ const snap = this.snap ?? '1/16';
237
+ const safeHighest = Math.max(highestPitch, lowestPitch);
238
+ const safeLowest = Math.min(highestPitch, lowestPitch);
239
+ const rowCount = safeHighest - safeLowest + 1;
240
+ const gridHeight = rowCount * noteHeight;
241
+ // Auto-size the grid width to fit the longest note when `beatsCount` is
242
+ // omitted; pad to a sensible minimum so empty rolls are usable.
243
+ const computedBeats = this.beatsCount ??
244
+ Math.max(16, Math.ceil(this.notes.reduce((max, n) => Math.max(max, (n.startBeat ?? 0) + (n.durationBeats ?? 0)), 0) + 4));
245
+ return {
246
+ pixelsPerBeat,
247
+ noteHeight,
248
+ snap,
249
+ safeHighest,
250
+ safeLowest,
251
+ rowCount,
252
+ gridHeight,
253
+ computedBeats,
254
+ };
255
+ }
256
+ /**
257
+ * The cell cursor clamped into the current grid bounds.
258
+ *
259
+ * @returns The clamped cursor.
260
+ */
261
+ cursor() {
262
+ const grid = this.geometry();
263
+ const raw = this.rawCursor();
264
+ return {
265
+ beat: Math.max(0, Math.min(raw.beat, grid.computedBeats)),
266
+ pitch: Math.max(grid.safeLowest, Math.min(grid.safeHighest, raw.pitch)),
267
+ };
268
+ }
269
+ /**
270
+ * The snap resolution in effect.
271
+ *
272
+ * @returns The snap setting.
273
+ */
274
+ snapValue() {
275
+ return this.snap ?? '1/16';
276
+ }
277
+ /** The pitch rows, top-to-bottom (highest first). */
278
+ rows() {
279
+ const grid = this.geometry();
280
+ const list = [];
281
+ for (let pitch = grid.safeHighest; pitch >= grid.safeLowest; pitch--)
282
+ list.push(pitch);
283
+ return list;
284
+ }
285
+ /** The beatline indices — `Array.from` floors a fractional count, as React does. */
286
+ beatLines() {
287
+ return Array.from({ length: Math.max(0, this.geometry().computedBeats) + 1 }, (_v, beat) => beat);
288
+ }
289
+ /**
290
+ * Whether a pitch is a C (the only keys that carry a label).
291
+ *
292
+ * @param pitch - MIDI pitch number.
293
+ * @returns True for a C pitch class.
294
+ */
295
+ isC(pitch) {
296
+ return ((pitch % 12) + 12) % 12 === 0;
297
+ }
298
+ /**
299
+ * Whether a pitch is a black key.
300
+ *
301
+ * @param pitch - MIDI pitch number.
302
+ * @returns True for a black key.
303
+ */
304
+ isBlackKey(pitch) {
305
+ return isBlackKey(pitch);
306
+ }
307
+ /**
308
+ * Format a MIDI pitch as a scientific-pitch-notation label.
309
+ *
310
+ * @param pitch - MIDI pitch number.
311
+ * @returns The label.
312
+ */
313
+ pitchLabel(pitch) {
314
+ return pitchLabel(pitch);
315
+ }
316
+ /** Whether the keyboard cell cursor highlight renders (React's condition). */
317
+ showsCursor() {
318
+ return !!this.onNoteAdd && this.gridFocused();
319
+ }
320
+ /** Whether the keyboard cursor announcement renders (React's condition). */
321
+ showsStatus() {
322
+ return !!this.onNoteAdd;
323
+ }
324
+ /**
325
+ * Track the grid's focus, as React's `onFocus` / `onBlur` do.
326
+ *
327
+ * @param focused - Whether the grid (or a child) now holds focus.
328
+ */
329
+ setGridFocused(focused) {
330
+ this.gridFocused.set(focused);
331
+ }
332
+ /**
333
+ * The translated region label (React's `pianoRoll.aria.roll`).
334
+ *
335
+ * @returns The translated label.
336
+ */
337
+ rollLabel() {
338
+ return this.i18n.t('pianoRoll.aria.roll', {}, { defaultValue: 'Piano roll' });
339
+ }
340
+ /**
341
+ * The translated keys-column label (React's `pianoRoll.aria.keys`).
342
+ *
343
+ * @returns The translated label.
344
+ */
345
+ keysLabel() {
346
+ return this.i18n.t('pianoRoll.aria.keys', {}, { defaultValue: 'Piano keys' });
347
+ }
348
+ /**
349
+ * The translated grid label (React's `pianoRoll.aria.grid`).
350
+ *
351
+ * @returns The translated label.
352
+ */
353
+ gridLabel() {
354
+ return this.i18n.t('pianoRoll.aria.grid', {}, { defaultValue: 'Note grid' });
355
+ }
356
+ /**
357
+ * The translated grid keyboard help (React's `pianoRoll.aria.gridHelp`).
358
+ *
359
+ * @returns The translated text.
360
+ */
361
+ gridHelpLabel() {
362
+ return this.i18n.t('pianoRoll.aria.gridHelp', {}, { defaultValue: 'The arrow keys move the cell cursor, Enter or Space paints a note at it.' });
363
+ }
364
+ /**
365
+ * The translated resize-handle label (React's `pianoRoll.aria.resize`).
366
+ *
367
+ * @returns The translated label.
368
+ */
369
+ resizeLabel() {
370
+ return this.i18n.t('pianoRoll.aria.resize', {}, { defaultValue: 'Resize note' });
371
+ }
372
+ /**
373
+ * The translated cell-cursor announcement (React's `pianoRoll.aria.cursor`).
374
+ *
375
+ * @returns The translated text.
376
+ */
377
+ cursorLabel() {
378
+ const cursor = this.cursor();
379
+ return this.i18n.t('pianoRoll.aria.cursor', { pitch: pitchLabel(cursor.pitch), beat: cursor.beat.toFixed(2) }, { defaultValue: 'Cursor on {{pitch}} at beat {{beat}}' });
380
+ }
381
+ /**
382
+ * The translated aria label of one note (React's `pianoRoll.aria.note`).
383
+ *
384
+ * @param note - The note.
385
+ * @returns The translated label.
386
+ */
387
+ noteAria(note) {
388
+ return this.i18n.t('pianoRoll.aria.note', {
389
+ pitch: pitchLabel(note.pitch),
390
+ startBeat: note.startBeat.toFixed(2),
391
+ durationBeats: note.durationBeats.toFixed(2),
392
+ }, { defaultValue: 'Note {{pitch}} starting at beat {{startBeat}} for {{durationBeats}} beats' });
393
+ }
394
+ /**
395
+ * The keys column's inline geometry (React's `keysColumnStyle`).
396
+ *
397
+ * @returns The style declarations.
398
+ */
399
+ keysColumnStyle() {
400
+ return {
401
+ width: `${PIANO_KEYS_WIDTH_PX}px`,
402
+ 'min-width': `${PIANO_KEYS_WIDTH_PX}px`,
403
+ height: `${this.geometry().gridHeight}px`,
404
+ position: 'sticky',
405
+ left: '0px',
406
+ 'z-index': '2',
407
+ background: 'var(--mol-piano-roll-keys-bg, #f6f6f8)',
408
+ color: 'currentcolor',
409
+ };
410
+ }
411
+ /**
412
+ * One piano key's inline geometry (React's `keyStyle`).
413
+ *
414
+ * @param black - Whether the key is black.
415
+ * @returns The style declarations.
416
+ */
417
+ keyStyle(black) {
418
+ return {
419
+ position: 'relative',
420
+ height: `${this.geometry().noteHeight}px`,
421
+ 'box-sizing': 'border-box',
422
+ background: black
423
+ ? 'var(--mol-piano-roll-key-black, #2b2b34)'
424
+ : 'var(--mol-piano-roll-key-white, #ffffff)',
425
+ color: black
426
+ ? 'var(--mol-piano-roll-key-black-fg, #f6f6f8)'
427
+ : 'var(--mol-piano-roll-key-white-fg, #2b2b34)',
428
+ 'border-bottom': '1px solid rgba(0, 0, 0, 0.08)',
429
+ 'padding-left': '6px',
430
+ 'padding-right': '6px',
431
+ display: 'flex',
432
+ 'align-items': 'center',
433
+ 'font-size': '10px',
434
+ 'line-height': '1',
435
+ };
436
+ }
437
+ /**
438
+ * One pitch row's inline geometry (React's `rowStyle`).
439
+ *
440
+ * @param pitch - The row's pitch.
441
+ * @returns The style declarations.
442
+ */
443
+ rowStyle(pitch) {
444
+ const grid = this.geometry();
445
+ return {
446
+ position: 'absolute',
447
+ left: '0px',
448
+ right: '0px',
449
+ top: `${pitchToY(pitch, grid.noteHeight, grid.safeHighest)}px`,
450
+ height: `${grid.noteHeight}px`,
451
+ background: isBlackKey(pitch) ? 'rgba(0, 0, 0, 0.04)' : 'transparent',
452
+ 'border-bottom': '1px solid rgba(0, 0, 0, 0.04)',
453
+ 'pointer-events': 'none',
454
+ };
455
+ }
456
+ /**
457
+ * One beat gridline's inline geometry (React's `lineStyle`).
458
+ *
459
+ * @param beat - The beat index.
460
+ * @returns The style declarations.
461
+ */
462
+ lineStyle(beat) {
463
+ return {
464
+ position: 'absolute',
465
+ top: '0px',
466
+ bottom: '0px',
467
+ left: `${beatsToPixels(beat, this.geometry().pixelsPerBeat)}px`,
468
+ width: '1px',
469
+ background: beat % 4 === 0 ? 'rgba(0, 0, 0, 0.18)' : 'rgba(0, 0, 0, 0.06)',
470
+ 'pointer-events': 'none',
471
+ };
472
+ }
473
+ /**
474
+ * The cell cursor's inline geometry (React's cursor style).
475
+ *
476
+ * @returns The style declarations.
477
+ */
478
+ cursorStyle() {
479
+ const grid = this.geometry();
480
+ const cursor = this.cursor();
481
+ return {
482
+ position: 'absolute',
483
+ left: `${beatsToPixels(cursor.beat, grid.pixelsPerBeat)}px`,
484
+ top: `${pitchToY(cursor.pitch, grid.noteHeight, grid.safeHighest)}px`,
485
+ width: `${beatsToPixels(snapToBeats(grid.snap), grid.pixelsPerBeat)}px`,
486
+ height: `${grid.noteHeight}px`,
487
+ border: '2px solid var(--mol-piano-roll-note-bg, #5b8def)',
488
+ 'border-radius': '3px',
489
+ 'box-sizing': 'border-box',
490
+ 'pointer-events': 'none',
491
+ };
492
+ }
493
+ /**
494
+ * The grid surface's inline geometry (React's `gridSurfaceStyle`).
495
+ *
496
+ * @returns The style declarations.
497
+ */
498
+ gridSurfaceStyle() {
499
+ const grid = this.geometry();
500
+ const width = `${beatsToPixels(grid.computedBeats, grid.pixelsPerBeat)}px`;
501
+ return {
502
+ position: 'relative',
503
+ width,
504
+ 'min-width': width,
505
+ height: `${grid.gridHeight}px`,
506
+ background: 'var(--mol-piano-roll-grid-bg, #ffffff)',
507
+ cursor: this.onNoteAdd ? 'crosshair' : 'default',
508
+ 'touch-action': 'pan-y',
509
+ 'user-select': 'none',
510
+ };
511
+ }
512
+ /**
513
+ * One note block's inline geometry (React's `noteStyle`).
514
+ *
515
+ * @param note - The note.
516
+ * @returns The style declarations.
517
+ */
518
+ noteStyle(note) {
519
+ const grid = this.geometry();
520
+ const velocity = Math.max(0, Math.min(127, note.velocity ?? DEFAULT_NOTE_VELOCITY));
521
+ return {
522
+ position: 'absolute',
523
+ left: `${beatsToPixels(note.startBeat, grid.pixelsPerBeat)}px`,
524
+ width: `${Math.max(2, beatsToPixels(note.durationBeats, grid.pixelsPerBeat))}px`,
525
+ top: `${pitchToY(note.pitch, grid.noteHeight, grid.safeHighest) + 1}px`,
526
+ height: `${Math.max(2, grid.noteHeight - 2)}px`,
527
+ background: 'var(--mol-piano-roll-note-bg, #5b8def)',
528
+ opacity: String(0.45 + (velocity / 127) * 0.55),
529
+ 'border-radius': '3px',
530
+ 'box-sizing': 'border-box',
531
+ cursor: 'grab',
532
+ 'touch-action': 'none',
533
+ };
534
+ }
535
+ /**
536
+ * Paint a new note at an exact cell: `startBeat` + `pitch`, with the
537
+ * configured snap-step duration and the default velocity.
538
+ *
539
+ * @param startBeat - Snapped start beat of the new note.
540
+ * @param pitch - MIDI pitch of the row to paint into.
541
+ */
542
+ paintNoteAt(startBeat, pitch) {
543
+ const onNoteAdd = this.onNoteAdd;
544
+ if (!onNoteAdd)
545
+ return;
546
+ const id = `note-${Date.now().toString(36)}-${Math.floor(Math.random() * 1e6).toString(36)}`;
547
+ onNoteAdd({
548
+ id,
549
+ pitch,
550
+ startBeat,
551
+ durationBeats: snapToBeats(this.geometry().snap),
552
+ velocity: DEFAULT_NOTE_VELOCITY,
553
+ });
554
+ }
555
+ /**
556
+ * Click handler on the empty grid: paints a new note at the snapped cell
557
+ * under the cursor and moves the keyboard cell cursor to that cell.
558
+ *
559
+ * @param event - The native click event from the grid surface.
560
+ */
561
+ handleGridClick(event) {
562
+ // Suppress synthetic clicks fired at the end of a drag.
563
+ if (this.drag && this.drag.moved)
564
+ return;
565
+ if (!this.onNoteAdd)
566
+ return;
567
+ const node = this.gridRef?.nativeElement;
568
+ if (!node)
569
+ return;
570
+ const grid = this.geometry();
571
+ const rect = node.getBoundingClientRect();
572
+ const x = event.clientX - rect.left;
573
+ const y = event.clientY - rect.top;
574
+ if (x < 0 || y < 0 || x > rect.width || y > rect.height)
575
+ return;
576
+ const startBeat = snapBeat(pixelsToBeats(x, grid.pixelsPerBeat), grid.snap);
577
+ const pitch = yToPitch(y, grid.noteHeight, grid.safeHighest, grid.safeLowest);
578
+ this.rawCursor.set({ beat: startBeat, pitch });
579
+ this.paintNoteAt(startBeat, pitch);
580
+ }
581
+ /**
582
+ * Keyboard handler on the grid surface: the arrow keys move the cell
583
+ * cursor, and Enter or Space paints a new note at the cursor cell.
584
+ *
585
+ * @param event - The native keydown event from the grid surface.
586
+ */
587
+ handleGridKeyDown(event) {
588
+ if (!this.onNoteAdd)
589
+ return;
590
+ // Only the grid surface itself drives the cell cursor — a keydown
591
+ // bubbling from a focused note child belongs to that note.
592
+ if (event.target !== event.currentTarget)
593
+ return;
594
+ const grid = this.geometry();
595
+ const cursor = this.cursor();
596
+ if (event.key === 'Enter' || event.key === ' ') {
597
+ // Ignore key auto-repeat so holding the key doesn't flood the roll
598
+ // with notes; each press paints exactly one note.
599
+ event.preventDefault();
600
+ if (!event.repeat)
601
+ this.paintNoteAt(cursor.beat, cursor.pitch);
602
+ return;
603
+ }
604
+ switch (event.key) {
605
+ case 'ArrowLeft':
606
+ this.rawCursor.set({ ...cursor, beat: cursor.beat - snapToBeats(grid.snap) });
607
+ break;
608
+ case 'ArrowRight':
609
+ this.rawCursor.set({ ...cursor, beat: cursor.beat + snapToBeats(grid.snap) });
610
+ break;
611
+ case 'ArrowUp':
612
+ this.rawCursor.set({ ...cursor, pitch: cursor.pitch + 1 });
613
+ break;
614
+ case 'ArrowDown':
615
+ this.rawCursor.set({ ...cursor, pitch: cursor.pitch - 1 });
616
+ break;
617
+ default:
618
+ return;
619
+ }
620
+ // Keep the scrollable surface from moving while moving the cursor.
621
+ event.preventDefault();
622
+ }
623
+ /**
624
+ * Right-click handler on a note: deletes it.
625
+ *
626
+ * @param event - The native mouse event.
627
+ * @param note - The note to delete.
628
+ */
629
+ handleNoteContextMenu(event, note) {
630
+ if (!this.onNoteDelete)
631
+ return;
632
+ event.preventDefault();
633
+ event.stopPropagation();
634
+ this.onNoteDelete(note.id);
635
+ }
636
+ /**
637
+ * Begin a drag gesture on a note body or a resize handle.
638
+ *
639
+ * @param event - The native pointer event from the note element.
640
+ * @param note - The note being dragged.
641
+ * @param mode - `'move'` for body drags, `'resize'` for handle drags.
642
+ */
643
+ beginDrag(event, note, mode) {
644
+ if (event.button !== undefined && event.button !== 0)
645
+ return;
646
+ event.stopPropagation();
647
+ this.drag = {
648
+ noteId: note.id,
649
+ mode,
650
+ pointerId: event.pointerId,
651
+ startX: event.clientX,
652
+ startY: event.clientY,
653
+ originStartBeat: note.startBeat,
654
+ originDurationBeats: note.durationBeats,
655
+ originPitch: note.pitch,
656
+ moved: false,
657
+ };
658
+ }
659
+ /**
660
+ * Native pointermove handler used during an active drag.
661
+ *
662
+ * @param event - Native pointer event.
663
+ */
664
+ onMove = (event) => {
665
+ const current = this.drag;
666
+ if (!current || event.pointerId !== current.pointerId)
667
+ return;
668
+ const dx = event.clientX - current.startX;
669
+ const dy = event.clientY - current.startY;
670
+ if (!current.moved &&
671
+ Math.abs(dx) < DRAG_DISTANCE_THRESHOLD_PX &&
672
+ Math.abs(dy) < DRAG_DISTANCE_THRESHOLD_PX) {
673
+ return;
674
+ }
675
+ current.moved = true;
676
+ const grid = this.geometry();
677
+ if (current.mode === 'move') {
678
+ const beatDelta = pixelsToBeats(dx, grid.pixelsPerBeat);
679
+ const nextStart = snapBeatRound(current.originStartBeat + beatDelta, grid.snap);
680
+ const rowDelta = Math.round(dy / Math.max(grid.noteHeight, 1));
681
+ // Higher rows on screen = higher pitch numbers. Dragging down
682
+ // (positive dy) decreases pitch.
683
+ const proposedPitch = current.originPitch - rowDelta;
684
+ const nextPitch = Math.max(grid.safeLowest, Math.min(grid.safeHighest, proposedPitch));
685
+ this.onNoteMove?.(current.noteId, nextStart, nextPitch);
686
+ }
687
+ else {
688
+ const beatDelta = pixelsToBeats(dx, grid.pixelsPerBeat);
689
+ const nextDuration = Math.max(MIN_NOTE_DURATION_BEATS, snapBeatRound(current.originDurationBeats + beatDelta, grid.snap) ||
690
+ MIN_NOTE_DURATION_BEATS);
691
+ this.onNoteResize?.(current.noteId, nextDuration);
692
+ }
693
+ };
694
+ /**
695
+ * Native pointerup / pointercancel handler that closes the drag gesture.
696
+ *
697
+ * @param event - Native pointer event.
698
+ */
699
+ onUp = (event) => {
700
+ const current = this.drag;
701
+ if (!current || event.pointerId !== current.pointerId)
702
+ return;
703
+ this.drag = null;
704
+ };
705
+ static ɵfac = function PianoRoll_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || PianoRoll)(); };
706
+ static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: PianoRoll, selectors: [["div", "mol-piano-roll", ""]], viewQuery: function PianoRoll_Query(rf, ctx) { if (rf & 1) {
707
+ i0.ɵɵviewQuery(_c0, 5);
708
+ } if (rf & 2) {
709
+ let _t;
710
+ i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.gridRef = _t.first);
711
+ } }, hostAttrs: ["role", "region", "data-mol-id", "piano-roll"], hostVars: 5, hostBindings: function PianoRoll_HostBindings(rf, ctx) { if (rf & 2) {
712
+ i0.ɵɵattribute("aria-label", ctx.rollLabel());
713
+ i0.ɵɵstyleMap(ctx.rootStyle);
714
+ i0.ɵɵclassMap(ctx.classes());
715
+ } }, inputs: { notes: "notes", pixelsPerBeat: "pixelsPerBeat", noteHeight: "noteHeight", lowestPitch: "lowestPitch", highestPitch: "highestPitch", snap: "snap", beatsCount: "beatsCount", onNoteAdd: "onNoteAdd", onNoteMove: "onNoteMove", onNoteResize: "onNoteResize", onNoteDelete: "onNoteDelete", className: "className" }, decls: 15, vars: 14, consts: [["grid", ""], ["role", "list", "data-mol-id", "piano-roll-keys"], ["role", "listitem", "data-mol-id", "piano-roll-key", 3, "style"], ["role", "application", "data-mol-id", "piano-roll-grid", "tabindex", "0", 3, "click", "keydown", "focusin", "focusout"], ["data-mol-id", "piano-roll-row", 3, "style"], ["data-mol-id", "piano-roll-beat-line", 3, "style"], ["data-mol-id", "piano-roll-cell-cursor", "aria-hidden", "true", 3, "style"], ["role", "status", 3, "class"], ["role", "button", "tabindex", "0", "data-mol-id", "piano-roll-note", 3, "class", "style"], ["role", "listitem", "data-mol-id", "piano-roll-key"], ["data-mol-id", "piano-roll-key-label", 3, "class"], ["data-mol-id", "piano-roll-key-label"], ["data-mol-id", "piano-roll-row"], ["data-mol-id", "piano-roll-beat-line"], ["data-mol-id", "piano-roll-cell-cursor", "aria-hidden", "true"], ["role", "status"], ["role", "button", "tabindex", "0", "data-mol-id", "piano-roll-note", 3, "pointerdown", "contextmenu"], ["role", "separator", "data-mol-id", "piano-roll-note-handle", 3, "pointerdown"]], template: function PianoRoll_Template(rf, ctx) { if (rf & 1) {
716
+ i0.ɵɵdomElementStart(0, "div", 1);
717
+ i0.ɵɵrepeaterCreate(1, PianoRoll_For_2_Template, 2, 5, "div", 2, i0.ɵɵrepeaterTrackByIdentity);
718
+ i0.ɵɵdomElementEnd();
719
+ i0.ɵɵdomElementStart(3, "div", 3, 0);
720
+ i0.ɵɵdomListener("click", function PianoRoll_Template_div_click_3_listener($event) { return ctx.handleGridClick($event); })("keydown", function PianoRoll_Template_div_keydown_3_listener($event) { return ctx.handleGridKeyDown($event); })("focusin", function PianoRoll_Template_div_focusin_3_listener() { return ctx.setGridFocused(true); })("focusout", function PianoRoll_Template_div_focusout_3_listener() { return ctx.setGridFocused(false); });
721
+ i0.ɵɵrepeaterCreate(5, PianoRoll_For_6_Template, 1, 4, "div", 4, i0.ɵɵrepeaterTrackByIdentity);
722
+ i0.ɵɵrepeaterCreate(7, PianoRoll_For_8_Template, 1, 4, "div", 5, i0.ɵɵrepeaterTrackByIdentity);
723
+ i0.ɵɵconditionalCreate(9, PianoRoll_Conditional_9_Template, 1, 2, "div", 6);
724
+ i0.ɵɵdomElementStart(10, "div");
725
+ i0.ɵɵtext(11);
726
+ i0.ɵɵdomElementEnd();
727
+ i0.ɵɵconditionalCreate(12, PianoRoll_Conditional_12_Template, 2, 3, "div", 7);
728
+ i0.ɵɵrepeaterCreate(13, PianoRoll_For_14_Template, 2, 12, "div", 8, _forTrack0);
729
+ i0.ɵɵdomElementEnd();
730
+ } if (rf & 2) {
731
+ i0.ɵɵstyleMap(ctx.keysColumnStyle());
732
+ i0.ɵɵattribute("aria-label", ctx.keysLabel());
733
+ i0.ɵɵadvance();
734
+ i0.ɵɵrepeater(ctx.rows());
735
+ i0.ɵɵadvance(2);
736
+ i0.ɵɵstyleMap(ctx.gridSurfaceStyle());
737
+ i0.ɵɵattribute("aria-label", ctx.gridLabel())("aria-describedby", ctx.gridHelpId)("data-snap", ctx.snapValue());
738
+ i0.ɵɵadvance(2);
739
+ i0.ɵɵrepeater(ctx.rows());
740
+ i0.ɵɵadvance(2);
741
+ i0.ɵɵrepeater(ctx.beatLines());
742
+ i0.ɵɵadvance(2);
743
+ i0.ɵɵconditional(ctx.showsCursor() ? 9 : -1);
744
+ i0.ɵɵadvance();
745
+ i0.ɵɵclassMap(ctx.srOnlyClass());
746
+ i0.ɵɵattribute("id", ctx.gridHelpId);
747
+ i0.ɵɵadvance();
748
+ i0.ɵɵtextInterpolate(ctx.gridHelpLabel());
749
+ i0.ɵɵadvance();
750
+ i0.ɵɵconditional(ctx.showsStatus() ? 12 : -1);
751
+ i0.ɵɵadvance();
752
+ i0.ɵɵrepeater(ctx.notes);
753
+ } }, encapsulation: 2 });
754
+ }
755
+ (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(PianoRoll, [{
756
+ type: Component,
757
+ args: [{
758
+ selector: 'div[mol-piano-roll]',
759
+ standalone: true,
760
+ inputs: [
761
+ 'notes',
762
+ 'pixelsPerBeat',
763
+ 'noteHeight',
764
+ 'lowestPitch',
765
+ 'highestPitch',
766
+ 'snap',
767
+ 'beatsCount',
768
+ 'onNoteAdd',
769
+ 'onNoteMove',
770
+ 'onNoteResize',
771
+ 'onNoteDelete',
772
+ 'className',
773
+ ],
774
+ host: {
775
+ role: 'region',
776
+ 'data-mol-id': 'piano-roll',
777
+ '[attr.aria-label]': 'rollLabel()',
778
+ '[class]': 'classes()',
779
+ '[style]': 'rootStyle',
780
+ },
781
+ // prettier-ignore
782
+ template: `<div role="list" [attr.aria-label]="keysLabel()" data-mol-id="piano-roll-keys" [style]="keysColumnStyle()">@for (pitch of rows(); track pitch) {<div role="listitem" data-mol-id="piano-roll-key" [attr.data-pitch]="pitch" [attr.data-key-color]="isBlackKey(pitch) ? 'black' : 'white'" [style]="keyStyle(isBlackKey(pitch))">@if (isC(pitch)) {<span data-mol-id="piano-roll-key-label" [class]="keyLabelClasses()">{{ pitchLabel(pitch) }}</span>}</div>}</div><div #grid role="application" [attr.aria-label]="gridLabel()" [attr.aria-describedby]="gridHelpId" data-mol-id="piano-roll-grid" [attr.data-snap]="snapValue()" [style]="gridSurfaceStyle()" tabindex="0" (click)="handleGridClick($event)" (keydown)="handleGridKeyDown($event)" (focusin)="setGridFocused(true)" (focusout)="setGridFocused(false)">@for (pitch of rows(); track pitch) {<div data-mol-id="piano-roll-row" [attr.data-pitch]="pitch" [attr.data-key-color]="isBlackKey(pitch) ? 'black' : 'white'" [style]="rowStyle(pitch)"></div>}@for (beat of beatLines(); track beat) {<div data-mol-id="piano-roll-beat-line" [attr.data-beat]="beat" [attr.data-bar]="beat % 4 === 0 ? 'true' : 'false'" [style]="lineStyle(beat)"></div>}@if (showsCursor()) {<div data-mol-id="piano-roll-cell-cursor" aria-hidden="true" [style]="cursorStyle()"></div>}<div [attr.id]="gridHelpId" [class]="srOnlyClass()">{{ gridHelpLabel() }}</div>@if (showsStatus()) {<div role="status" [class]="srOnlyClass()">{{ cursorLabel() }}</div>}@for (note of notes; track note.id) {<div role="button" tabindex="0" [attr.aria-label]="noteAria(note)" data-mol-id="piano-roll-note" [attr.data-note-id]="note.id" [attr.data-pitch]="note.pitch" [attr.data-start-beat]="note.startBeat" [attr.data-duration-beats]="note.durationBeats" [class]="noteClasses()" [style]="noteStyle(note)" (pointerdown)="beginDrag($event, note, 'move')" (contextmenu)="handleNoteContextMenu($event, note)"><div role="separator" [attr.aria-label]="resizeLabel()" data-mol-id="piano-roll-note-handle" [style]="handleStyle" (pointerdown)="beginDrag($event, note, 'resize')"></div></div>}</div>`,
783
+ }]
784
+ }], null, { gridRef: [{
785
+ type: ViewChild,
786
+ args: ['grid']
787
+ }] }); })();
788
+ (() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(PianoRoll, { className: "PianoRoll", filePath: "piano-roll.component.ts", lineNumber: 131 }); })();
789
+ //# sourceMappingURL=piano-roll.component.js.map