diff --git a/app/static/js/app.jsx b/app/static/js/app.jsx index 1fbdef6..dc74d14 100644 --- a/app/static/js/app.jsx +++ b/app/static/js/app.jsx @@ -9056,6 +9056,7 @@ const PianoRollTabEditor = ({ st, zoom, bpm, viewportWidth, activeTracks, onClos target_id: match.id, label: 'Piano Roll: ' + (match.name || 'MIDI'), notes: match.notes || [], + cc11_global_curve: match.cc11_global_curve || null, duration: match.duration || 4, instrumentProgram: scope ? scope.instrument_program : (trk ? trk.instrumentProgram : undefined), instrumentName: scope ? scope.instrument_name : (trk ? trk.instrumentName : undefined), @@ -9635,7 +9636,10 @@ const PianoRollTabEditor = ({ st, zoom, bpm, viewportWidth, activeTracks, onClos // CC11 = GLOBAL curve tu note dau den note cuoi (khong per-note). Khi commit // sinh lai per-note expression_curve (engine doc per-note) bang cach sample // global tai vung tung note. - const [cc11GlobalCurve, setCc11GlobalCurve] = React.useState([]); + const [cc11GlobalCurve, setCc11GlobalCurve] = React.useState(() => Array.isArray(st.cc11_global_curve) && st.cc11_global_curve.length ? st.cc11_global_curve.slice() : []); + React.useEffect(() => { + setCc11GlobalCurve(Array.isArray(st.cc11_global_curve) && st.cc11_global_curve.length ? st.cc11_global_curve.slice() : []); + }, [st.cc11_global_curve]); React.useEffect(() => { if (cc11GlobalCurve && cc11GlobalCurve.length) return; const n = notes.find(x => Array.isArray(x.expression_curve) && x.expression_curve.length); @@ -10598,6 +10602,9 @@ const PianoRollTabEditor = ({ st, zoom, bpm, viewportWidth, activeTracks, onClos return { ...n, expression_curve: pts.sort((a, b) => a.position_ratio - b.position_ratio) }; }); setNotes(updatedNotes); + // Đồng bộ subTab NGAY (không chờ effect): schedulePianoRollMidi đọc + // st.notes khi Play (realtime) + cc11_global_curve để persist save/load. + if (setSubTabs) setSubTabs(prev => prev.map(s => s.id === st.id ? { ...s, notes: updatedNotes, cc11_global_curve: curve, isDirty: true } : s)); if (isPlaying && onRescheduleMidi) onRescheduleMidi(updatedNotes); }; const handleCC11MouseDown = (e) => { @@ -11894,6 +11901,7 @@ const serializeTracksList = (tracksList, secondsPerBar) => { clip_start_offset_bars: 0.0, source_data: { total_buffer_bars: m.duration ? (m.duration / secondsPerBar) : 8.0, + ...(Array.isArray(m.cc11_global_curve) && m.cc11_global_curve.length ? { cc11_global_curve: m.cc11_global_curve.map(p => ({ position_ratio: p.position_ratio, value: p.value })) } : {}), notes: (m.notes || []).map(n => ({ id: n.id || 'note_' + Math.random().toString(36).substr(2, 9), pitch: n.pitch || 60, @@ -12014,7 +12022,8 @@ const deserializeTracksList = (schemaTracks, secondsPerBar, sectionStore, visite velocity: n.velocity || 0.8, pan: n.pan || 0.0, ...(Array.isArray(n.expression_curve) ? { expression_curve: n.expression_curve } : {}) - })) + })), + ...(Array.isArray(src.cc11_global_curve) && src.cc11_global_curve.length ? { cc11_global_curve: src.cc11_global_curve } : {}) }); } else if (item.type === "SECTION_ITEM") { const src = item.source_data || {}; @@ -12156,6 +12165,7 @@ const serializeProjectToSchema = (projectId, name, bpmVal, tracksList, subTabsLi target_id: st.target_id, parent_tab_id: st.parent_tab_id, notes: st.notes || [], + ...(Array.isArray(st.cc11_global_curve) && st.cc11_global_curve.length ? { cc11_global_curve: st.cc11_global_curve.map(p => ({ position_ratio: p.position_ratio, value: p.value })) } : {}), duration: st.duration || 4, instrument_program: st.instrumentProgram, instrument_name: st.instrumentName, @@ -12260,6 +12270,7 @@ const deserializeProjectFromSchema = (schemaObj) => { target_id: st.target_id, parent_tab_id: st.parent_tab_id, notes: st.notes || [], + cc11_global_curve: st.cc11_global_curve || null, duration: st.duration || 4, instrumentProgram: st.instrument_program, instrumentName: st.instrument_name, @@ -21657,6 +21668,7 @@ const App = () => { target_id: midiItemId, parent_tab_id: activeTab === 'main' ? null : activeTab, notes: midiItem.notes || [], + cc11_global_curve: midiItem.cc11_global_curve || null, duration: midiItem.duration || 4, buffer: silentBuffer, instrumentProgram: track.instrumentProgram !== undefined ? track.instrumentProgram : (track.synth_engine ? track.synth_engine.soundfont_program : undefined), @@ -21702,7 +21714,7 @@ const App = () => { ...t, midiItems: (t.midiItems || []).map(m => { if (m.id !== midiItemId) return m; - return { ...m, notes: updatedNotes }; + return { ...m, notes: updatedNotes, cc11_global_curve: pianoRollTab ? (pianoRollTab.cc11_global_curve || null) : null }; }) }; }) @@ -21715,7 +21727,7 @@ const App = () => { ...t, midiItems: (t.midiItems || []).map(m => { if (m.id !== midiItemId) return m; - return { ...m, notes: updatedNotes }; + return { ...m, notes: updatedNotes, cc11_global_curve: pianoRollTab ? (pianoRollTab.cc11_global_curve || null) : null }; }) }; })); diff --git a/app/static/js/app.precompiled.js b/app/static/js/app.precompiled.js index 84963f8..0521aef 100644 --- a/app/static/js/app.precompiled.js +++ b/app/static/js/app.precompiled.js @@ -705,7 +705,7 @@ const draggedNoteRef=React.useRef(draggedNote);draggedNoteRef.current=draggedNot // FluidSynth (scheduled qua setTimeout) TRỄ → âm bị lag 1-2 lần khi mở // piano roll tab lúc đang play (user bug 06:30). Ghost chỉ là hiển thị // tham chiếu — không cần khi âm đang chạy — tính lại khi dừng. -if(isPlaying)return[];if(!activeTracks||!st||!st.target_id)return[];var fn=window.SonicGhost&&window.SonicGhost.extractGhostLayers;return fn?fn(activeTracks,st.trackId,st.target_id,parseInt(bpm)||120):[];},[activeTracks,st.trackId,st.target_id,bpm,isPlaying]);const secondsPerBar=60.0/(parseInt(bpm)||120)*4;const activeTargetItem=React.useMemo(function(){if(!activeTracks||!st)return null;var trk=activeTracks.find(function(t){return t.id===st.trackId;});return trk?(trk.midiItems||[]).find(function(m){return m.id===st.target_id;}):null;},[activeTracks,st.trackId,st.target_id]);var activeParentTrackName='';if(st.target_id&&activeTracks){var aptTrk=window.SonicPianoRoll?window.SonicPianoRoll.getParentTrackByItemId(st.target_id,activeTracks):null;if(!aptTrk)aptTrk=activeTracks.find(function(t){return t.id===st.trackId;});if(!aptTrk&&activeTargetItem)aptTrk=activeTracks.find(function(t){return(t.midiItems||[]).some(function(m){return m.id===st.target_id;});});if(aptTrk)activeParentTrackName=aptTrk.name||aptTrk.id;}const sessionStartBar=0;const renderBeatOffset=sessionSyncMode&&activeTargetItem?activeTargetItem.startTime/secondsPerBar*timeSigNum:0;const sessionLengthBars=React.useMemo(function(){var maxSec=0;(activeTracks||[]).forEach(function(tr){(tr.midiItems||[]).forEach(function(m){var end=(m.startTime||0)+(m.duration||4);if(end>maxSec)maxSec=end;});});return Math.ceil((maxSec||4)/secondsPerBar);},[activeTracks,secondsPerBar]);const handleSwitchMidiItem=function(itemId){if(itemId===st.target_id)return;var match=allMidiItems.find(function(m){return m.id===itemId;});if(!match)return;var scope=window.SonicPianoRoll?window.SonicPianoRoll.buildActiveScope(itemId,activeTracks):null;var trk=scope?null:(activeTracks||[]).find(function(t){return t.id===match._trackId;});var newBeatOff=match.startTime/secondsPerBar*timeSigNum;var spb=60.0/(parseInt(bpm)||120);var newTime=0;setSubTabs(function(prev){return prev.map(function(s){if(s.id!==st.id)return s;return Object.assign({},s,{trackId:scope?scope.parent_track_id:match._trackId||trk?.id,target_id:match.id,label:'Piano Roll: '+(match.name||'MIDI'),notes:match.notes||[],duration:match.duration||4,instrumentProgram:scope?scope.instrument_program:trk?trk.instrumentProgram:undefined,instrumentName:scope?scope.instrument_name:trk?trk.instrumentName:undefined,active_scope:scope||null,note_selection:[],currentTime:newTime});});});setSelectedNoteIds([]);};const rawTotalBeats=Math.max(rollBeats,noteMaxBeat+16,64);const drawWidth=rawTotalBeats*pixelsPerBeat;const[rollViewWidth,setRollViewWidth]=React.useState(800);const viewWidth=Math.max(drawWidth,rollViewWidth);const viewBeats=Math.ceil(viewWidth/pixelsPerBeat)+4;const totalBeats=Math.max(rawTotalBeats,viewBeats+32);const[notes,setNotes]=React.useState(st.notes||[]);const notesRef=React.useRef(notes);notesRef.current=notes;React.useEffect(()=>{if(!draggedNoteRef.current)setNotes(st.notes||[]);},[st.notes]);const brushVelocityRef=React.useRef(0.8);const lastNoteDurationRef=React.useRef(null);const previewPitchRef=React.useRef(null);const previewNodesRef=React.useRef(null);var stopPreviewNote=function(){var pn=previewNodesRef.current;if(pn){try{pn.osc.stop();}catch(e){}try{pn.osc.disconnect();}catch(e){}try{pn.gain.disconnect();}catch(e){}previewNodesRef.current=null;}};const[selectedNoteIds,setSelectedNoteIds]=React.useState([]);const[loopStartBeat,setLoopStartBeat]=React.useState(null);const[loopEndBeat,setLoopEndBeat]=React.useState(null);const[isLooping,setIsLooping]=React.useState(false);const rulerDragRef=React.useRef(null);React.useEffect(()=>{const handler=e=>{if((e.ctrlKey||e.metaKey)&&e.key==='a'){const target=e.target;if(target&&(target.tagName==='INPUT'||target.tagName==='TEXTAREA'||target.isContentEditable))return;e.preventDefault();setSelectedNoteIds(notes.map(n=>n.id));return;}// Spec 20:12 shortcuts: Alt+A Arp, Alt+S Strum, Alt+R Humanize, +if(isPlaying)return[];if(!activeTracks||!st||!st.target_id)return[];var fn=window.SonicGhost&&window.SonicGhost.extractGhostLayers;return fn?fn(activeTracks,st.trackId,st.target_id,parseInt(bpm)||120):[];},[activeTracks,st.trackId,st.target_id,bpm,isPlaying]);const secondsPerBar=60.0/(parseInt(bpm)||120)*4;const activeTargetItem=React.useMemo(function(){if(!activeTracks||!st)return null;var trk=activeTracks.find(function(t){return t.id===st.trackId;});return trk?(trk.midiItems||[]).find(function(m){return m.id===st.target_id;}):null;},[activeTracks,st.trackId,st.target_id]);var activeParentTrackName='';if(st.target_id&&activeTracks){var aptTrk=window.SonicPianoRoll?window.SonicPianoRoll.getParentTrackByItemId(st.target_id,activeTracks):null;if(!aptTrk)aptTrk=activeTracks.find(function(t){return t.id===st.trackId;});if(!aptTrk&&activeTargetItem)aptTrk=activeTracks.find(function(t){return(t.midiItems||[]).some(function(m){return m.id===st.target_id;});});if(aptTrk)activeParentTrackName=aptTrk.name||aptTrk.id;}const sessionStartBar=0;const renderBeatOffset=sessionSyncMode&&activeTargetItem?activeTargetItem.startTime/secondsPerBar*timeSigNum:0;const sessionLengthBars=React.useMemo(function(){var maxSec=0;(activeTracks||[]).forEach(function(tr){(tr.midiItems||[]).forEach(function(m){var end=(m.startTime||0)+(m.duration||4);if(end>maxSec)maxSec=end;});});return Math.ceil((maxSec||4)/secondsPerBar);},[activeTracks,secondsPerBar]);const handleSwitchMidiItem=function(itemId){if(itemId===st.target_id)return;var match=allMidiItems.find(function(m){return m.id===itemId;});if(!match)return;var scope=window.SonicPianoRoll?window.SonicPianoRoll.buildActiveScope(itemId,activeTracks):null;var trk=scope?null:(activeTracks||[]).find(function(t){return t.id===match._trackId;});var newBeatOff=match.startTime/secondsPerBar*timeSigNum;var spb=60.0/(parseInt(bpm)||120);var newTime=0;setSubTabs(function(prev){return prev.map(function(s){if(s.id!==st.id)return s;return Object.assign({},s,{trackId:scope?scope.parent_track_id:match._trackId||trk?.id,target_id:match.id,label:'Piano Roll: '+(match.name||'MIDI'),notes:match.notes||[],cc11_global_curve:match.cc11_global_curve||null,duration:match.duration||4,instrumentProgram:scope?scope.instrument_program:trk?trk.instrumentProgram:undefined,instrumentName:scope?scope.instrument_name:trk?trk.instrumentName:undefined,active_scope:scope||null,note_selection:[],currentTime:newTime});});});setSelectedNoteIds([]);};const rawTotalBeats=Math.max(rollBeats,noteMaxBeat+16,64);const drawWidth=rawTotalBeats*pixelsPerBeat;const[rollViewWidth,setRollViewWidth]=React.useState(800);const viewWidth=Math.max(drawWidth,rollViewWidth);const viewBeats=Math.ceil(viewWidth/pixelsPerBeat)+4;const totalBeats=Math.max(rawTotalBeats,viewBeats+32);const[notes,setNotes]=React.useState(st.notes||[]);const notesRef=React.useRef(notes);notesRef.current=notes;React.useEffect(()=>{if(!draggedNoteRef.current)setNotes(st.notes||[]);},[st.notes]);const brushVelocityRef=React.useRef(0.8);const lastNoteDurationRef=React.useRef(null);const previewPitchRef=React.useRef(null);const previewNodesRef=React.useRef(null);var stopPreviewNote=function(){var pn=previewNodesRef.current;if(pn){try{pn.osc.stop();}catch(e){}try{pn.osc.disconnect();}catch(e){}try{pn.gain.disconnect();}catch(e){}previewNodesRef.current=null;}};const[selectedNoteIds,setSelectedNoteIds]=React.useState([]);const[loopStartBeat,setLoopStartBeat]=React.useState(null);const[loopEndBeat,setLoopEndBeat]=React.useState(null);const[isLooping,setIsLooping]=React.useState(false);const rulerDragRef=React.useRef(null);React.useEffect(()=>{const handler=e=>{if((e.ctrlKey||e.metaKey)&&e.key==='a'){const target=e.target;if(target&&(target.tagName==='INPUT'||target.tagName==='TEXTAREA'||target.isContentEditable))return;e.preventDefault();setSelectedNoteIds(notes.map(n=>n.id));return;}// Spec 20:12 shortcuts: Alt+A Arp, Alt+S Strum, Alt+R Humanize, // Shift+C chord stamp, Shift+S lock-scale toggle const inField=e.target&&(e.target.tagName==='INPUT'||e.target.tagName==='TEXTAREA'||e.target.isContentEditable);// Ctrl+C/X/V — copy/paste/cut NOTES (thay 2 nút Copy/Paste đã bỏ — // user 08:40) — CHỈ tác động NOTES ĐƯỢC CHỌN (user 09:10) @@ -744,7 +744,7 @@ if(st.currentTime!==undefined&&st.currentTime!==null){const phBeat=st.currentTim const[showCC,setShowCC]=React.useState(true);const[ccHeight,setCcHeight]=React.useState(80);// CC11 = GLOBAL curve tu note dau den note cuoi (khong per-note). Khi commit // sinh lai per-note expression_curve (engine doc per-note) bang cach sample // global tai vung tung note. -const[cc11GlobalCurve,setCc11GlobalCurve]=React.useState([]);React.useEffect(()=>{if(cc11GlobalCurve&&cc11GlobalCurve.length)return;const n=notes.find(x=>Array.isArray(x.expression_curve)&&x.expression_curve.length);if(n)setCc11GlobalCurve(n.expression_curve.slice());// ponytail: chi khoi phuc khi project cu co curve; chua hop nhat migration +const[cc11GlobalCurve,setCc11GlobalCurve]=React.useState(()=>Array.isArray(st.cc11_global_curve)&&st.cc11_global_curve.length?st.cc11_global_curve.slice():[]);React.useEffect(()=>{setCc11GlobalCurve(Array.isArray(st.cc11_global_curve)&&st.cc11_global_curve.length?st.cc11_global_curve.slice():[]);},[st.cc11_global_curve]);React.useEffect(()=>{if(cc11GlobalCurve&&cc11GlobalCurve.length)return;const n=notes.find(x=>Array.isArray(x.expression_curve)&&x.expression_curve.length);if(n)setCc11GlobalCurve(n.expression_curve.slice());// ponytail: chi khoi phuc khi project cu co curve; chua hop nhat migration },[notes]);// CC lane grid: vẽ cột beat/bar GIỐNG HỆT piano roll (cùng pixelsPerBeat + // snapBeats + timeSigNum) → không lệch khi zoom. snapBeats copy nguyên từ // notes canvas để hai lane trùng khít. @@ -805,7 +805,9 @@ const prKeyStateRef=React.useRef({shift:false,ctrl:false});const prMouseInRef=Re // (trước đây findCCNoteIndex chỉ trả 1 note → chord khó draw). const findCCNoteIndicesAtBeat=b=>{const snapped=getSnapBeat(b,snapValue);const out=[];notes.forEach((n,idx)=>{if(Math.abs(n.start_beat-snapped)<0.01)out.push(idx);});return out;};// ── CC11 EXPRESSION CURVE (piano roll lane) ── const cc11ValueAt=(curve,ratio)=>{if(!curve||!curve.length)return 127;if(curve.length===1)return curve[0].value;const pts=curve.slice().sort((a,b)=>a.position_ratio-b.position_ratio);if(ratio<=pts[0].position_ratio)return pts[0].value;if(ratio>=pts[pts.length-1].position_ratio)return pts[pts.length-1].value;for(let i=1;i{const cur=notesRef.current;if(!cur.length)return null;let minS=Infinity,maxE=-Infinity;cur.forEach(n=>{minS=Math.min(minS,n.start_beat);maxE=Math.max(maxE,n.start_beat+(n.duration_beats||1));});return{minS,maxE,span:maxE-minS||1};};// GLOBAL curve -> per-note expression_curve: sample global tai vung tung note -const commitCC11Curve=curve=>{setCc11GlobalCurve(curve);const curNotes=notesRef.current;const g=cc11GlobalRange();if(!g){setNotes(curNotes);return;}const updatedNotes=curNotes.map(n=>{const s=n.start_beat;const e=s+(n.duration_beats||1);const pts=[];const add=(ratio,value)=>pts.push({position_ratio:ratio,value});add(0,cc11ValueAt(curve,(s-g.minS)/g.span));(curve||[]).forEach(p=>{const b=g.minS+p.position_ratio*g.span;if(b>s&&ba.position_ratio-b.position_ratio)};});setNotes(updatedNotes);if(isPlaying&&onRescheduleMidi)onRescheduleMidi(updatedNotes);};const handleCC11MouseDown=e=>{const canvas=ccCanvasRef.current;if(!canvas)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const y=e.clientY-rect.top;const h=rect.height;const beat=x/pixelsPerBeat-renderBeatOffset;const g=cc11GlobalRange();if(!g||beatg.maxE){ccDragRef.current=null;return;}const ratio=Math.max(0,Math.min(1,(beat-g.minS)/g.span));const val=Math.max(0,Math.min(127,Math.round((h-y)/h*127)));const curve=(cc11GlobalCurve||[]).slice();const x0=(renderBeatOffset+g.minS)*pixelsPerBeat;const x1=(renderBeatOffset+g.maxE)*pixelsPerBeat;const yOf=v=>h-(v/127*(h-20)+10);let anchorIdx=-1;curve.forEach((p,i)=>{const ax=x0+p.position_ratio*(x1-x0);const ay=yOf(p.value);if(Math.hypot(ax-x,ay-y)<=8)anchorIdx=i;});if(anchorIdx===-1){// Click trong: THEM node tai do ngay lap tuc — khong keo node moi +const commitCC11Curve=curve=>{setCc11GlobalCurve(curve);const curNotes=notesRef.current;const g=cc11GlobalRange();if(!g){setNotes(curNotes);return;}const updatedNotes=curNotes.map(n=>{const s=n.start_beat;const e=s+(n.duration_beats||1);const pts=[];const add=(ratio,value)=>pts.push({position_ratio:ratio,value});add(0,cc11ValueAt(curve,(s-g.minS)/g.span));(curve||[]).forEach(p=>{const b=g.minS+p.position_ratio*g.span;if(b>s&&ba.position_ratio-b.position_ratio)};});setNotes(updatedNotes);// Đồng bộ subTab NGAY (không chờ effect): schedulePianoRollMidi đọc +// st.notes khi Play (realtime) + cc11_global_curve để persist save/load. +if(setSubTabs)setSubTabs(prev=>prev.map(s=>s.id===st.id?{...s,notes:updatedNotes,cc11_global_curve:curve,isDirty:true}:s));if(isPlaying&&onRescheduleMidi)onRescheduleMidi(updatedNotes);};const handleCC11MouseDown=e=>{const canvas=ccCanvasRef.current;if(!canvas)return;const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const y=e.clientY-rect.top;const h=rect.height;const beat=x/pixelsPerBeat-renderBeatOffset;const g=cc11GlobalRange();if(!g||beatg.maxE){ccDragRef.current=null;return;}const ratio=Math.max(0,Math.min(1,(beat-g.minS)/g.span));const val=Math.max(0,Math.min(127,Math.round((h-y)/h*127)));const curve=(cc11GlobalCurve||[]).slice();const x0=(renderBeatOffset+g.minS)*pixelsPerBeat;const x1=(renderBeatOffset+g.maxE)*pixelsPerBeat;const yOf=v=>h-(v/127*(h-20)+10);let anchorIdx=-1;curve.forEach((p,i)=>{const ax=x0+p.position_ratio*(x1-x0);const ay=yOf(p.value);if(Math.hypot(ax-x,ay-y)<=8)anchorIdx=i;});if(anchorIdx===-1){// Click trong: THEM node tai do ngay lap tuc — khong keo node moi const dup=curve.findIndex(p=>Math.abs(p.position_ratio-ratio)<1e-6);let newCurve;if(dup!==-1){newCurve=curve.slice();newCurve[dup]={position_ratio:ratio,value:val};}else{newCurve=curve.concat([{position_ratio:ratio,value:val}]).sort((a,b)=>a.position_ratio-b.position_ratio);}commitCC11Curve(newCurve);ccDragRef.current=null;return;}curve[anchorIdx]={position_ratio:ratio,value:val};// Khong setNotes ngay: ve preview truc tiep, commit khi mouseup/mouseleave ccDragRef.current={mode:'cc11',active:true,anchorIdx,gs:g.minS,ge:g.maxE,span:g.span,previewCurve:curve};paintCC11Lane(curve);};const handleCC11ContextMenu=e=>{if(ccMode!=='cc11')return;const canvas=ccCanvasRef.current;if(!canvas)return;e.preventDefault();const rect=canvas.getBoundingClientRect();const x=e.clientX-rect.left;const y=e.clientY-rect.top;const h=rect.height;const beat=x/pixelsPerBeat-renderBeatOffset;const g=cc11GlobalRange();if(!g||beatg.maxE)return;const x0=(renderBeatOffset+g.minS)*pixelsPerBeat;const x1=(renderBeatOffset+g.maxE)*pixelsPerBeat;const yOf=v=>h-(v/127*(h-20)+10);const curve=(cc11GlobalCurve||[]).slice();let delIdx=-1,delDist=Infinity;curve.forEach((p,i)=>{const ax=x0+p.position_ratio*(x1-x0);const ay=yOf(p.value);const d=Math.hypot(ax-x,ay-y);if(d8)return;curve.splice(delIdx,1);commitCC11Curve(curve);};// Commit CC11 preview khi mouseup/mouseleave — truoc day drag setNotes moi // mousemove (flicker); gio chi cap nhat state 1 lan khi ket thuc drag. @@ -841,7 +843,7 @@ if(window.__setPrHint){window.__setPrHint(prKeyStateRef.current.ctrl?"Ctrl+drag: handleSwitchMidiItem(m.id);},className:"flex items-center justify-center flex-1 h-[26px] min-w-0 border border-zinc-600 rounded-md cursor-pointer outline-none "+(isActive?'bg-yellow-600 text-black font-bold':'bg-zinc-700 text-zinc-300 hover:bg-zinc-600')},React.createElement("span",{className:"text-[13px] leading-none font-sans truncate px-1",title:track?track.name:m._trackName},track?track.name:m._trackName)),React.createElement("button",{onClick:function(e){e.stopPropagation();var prevList=activePlayTrackIds||[];var nextList=prevList.indexOf(m._trackId)!==-1?prevList.filter(function(id){return id!==m._trackId;}):prevList.concat([m._trackId]);setActivePlayTrackIds(nextList);if(onRealtimePlay)onRealtimePlay(nextList);},title:isPlayOn?"Unmute — ghost track play cùng main notes":"Mute (mặc định) — click để play ghost cùng main",className:"w-6 h-[26px] shrink-0 border border-zinc-600 rounded-md cursor-pointer text-[11px] font-bold outline-none flex items-center justify-center "+(isPlayOn?'bg-green-700 text-white':'bg-zinc-800 text-zinc-500 hover:text-zinc-300')},isPlayOn?"\u266A":"M")));});return els;}():null),React.createElement("div",{className:"w-[60px] shrink-0 flex flex-col border-r border-zinc-900 overflow-y-auto",ref:keybedRef,onScroll:handleKeybedScroll,style:{scrollbarWidth:'none',msOverflowStyle:'none'}},renderKeybed()),React.createElement("div",{ref:gridScrollRef,onScroll:handleScroll,className:"flex-1 overflow-auto bg-[#141414] min-w-0"},React.createElement("div",{style:{width:`${viewWidth}px`,height:`${(128-PITCH_START)*NoteHeight}px`},className:"relative"},React.createElement("canvas",{ref:canvasRef,onMouseDown:handleGridMouseDown,onMouseMove:handleGridMouseMove,onMouseUp:handleGridMouseUp,onMouseLeave:handleGridMouseUp,onContextMenu:handleContextMenu,className:"absolute inset-0 cursor-crosshair"}),loopStartBeat!==null&&loopEndBeat!==null&&loopEndBeat>loopStartBeat&&React.createElement("div",{style:{left:`${loopStartBeat*pixelsPerBeat}px`,width:`${(loopEndBeat-loopStartBeat)*pixelsPerBeat}px`,top:0,bottom:0},className:"absolute bg-emerald-500/10 border-l border-r border-emerald-400/50 pointer-events-none"})))),/* 4. CC / VELOCITY LANE (ĐẶT Ở ĐÁY) */showCC&&React.createElement("div",{style:{height:`${ccHeight}px`},className:"bg-[#161616] border-t border-zinc-900 flex shrink-0 relative"},React.createElement("div",{onMouseDown:e=>{e.preventDefault();const startY=e.clientY;const startH=ccHeight;const onMove=ev=>{setCcHeight(Math.max(40,startH+startY-ev.clientY));};const onUp=()=>{document.removeEventListener('mousemove',onMove);document.removeEventListener('mouseup',onUp);};document.addEventListener('mousemove',onMove);document.addEventListener('mouseup',onUp);},className:"absolute top-0 left-0 right-0 h-1.5 cursor-n-resize z-10 hover:bg-purple-600/30"}),React.createElement("div",{className:"w-[120px] shrink-0"}),React.createElement("select",{value:ccMode,onChange:e=>setCcMode(e.target.value),title:"CC control",className:"w-[60px] bg-[#222222] border-r border-zinc-900 text-[10px] text-zinc-200 font-mono shrink-0 font-bold text-center cursor-pointer outline-none"},React.createElement("option",{value:"velocity"},"Vel"),React.createElement("option",{value:"sustain"},"Sus"),React.createElement("option",{value:"modulation"},"Mod"),React.createElement("option",{value:"pitch_bend"},"Bend"),React.createElement("option",{value:"pan"},"Pan"),React.createElement("option",{value:"cc11"},"Expr")),React.createElement("div",{ref:ccWrapperRef,className:"flex-1 overflow-x-hidden min-w-0"},React.createElement("div",{style:{width:`${viewWidth}px`,height:'100%'},className:"relative"},React.createElement("canvas",{ref:ccCanvasRef,onMouseDown:handleCCMouseDown,onMouseMove:handleCCMouseMove,onContextMenu:handleCC11ContextMenu,onMouseUp:commitCC11Drag,onMouseLeave:commitCC11Drag,className:"absolute inset-0"}),loopStartBeat!==null&&loopEndBeat!==null&&loopEndBeat>loopStartBeat&&React.createElement("div",{style:{left:`${loopStartBeat*pixelsPerBeat}px`,width:`${(loopEndBeat-loopStartBeat)*pixelsPerBeat}px`,top:0,bottom:0},className:"absolute bg-emerald-500/10 border-l border-r border-emerald-400/50 pointer-events-none"})))),/* 5. OVERLAY / CONTEXT MENU */arpModal&&React.createElement("div",{className:"absolute inset-0 z-40 flex items-center justify-center bg-black/60",onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation()},React.createElement("div",{className:"bg-zinc-900 border border-zinc-700 rounded-lg p-4 w-72 shadow-2xl"},React.createElement("div",{className:"text-sm font-bold text-cyan-300 mb-3"},"Arpeggiate"),React.createElement("div",{className:"grid grid-cols-2 gap-2 text-xs mb-3"},React.createElement("label",{className:"text-zinc-500"},"Pattern"),React.createElement("select",{value:arpModal.pattern,onChange:e=>setArpModal({...arpModal,pattern:e.target.value}),className:"bg-zinc-800 border border-zinc-700 text-zinc-200 rounded px-1 py-0.5"},['UP','DOWN','UP-DOWN','RANDOM','CHORD'].map(p=>React.createElement("option",{key:p,value:p},p))),React.createElement("label",{className:"text-zinc-500"},"Rate"),React.createElement("select",{value:arpModal.rate,onChange:e=>setArpModal({...arpModal,rate:e.target.value}),className:"bg-zinc-800 border border-zinc-700 text-zinc-200 rounded px-1 py-0.5"},['1/4','1/8','1/16','1/32'].map(r=>React.createElement("option",{key:r,value:r},r))),React.createElement("label",{className:"text-zinc-500"},"Octaves"),React.createElement("input",{type:"number",min:1,max:4,value:arpModal.octaves,onChange:e=>setArpModal({...arpModal,octaves:parseInt(e.target.value)||1}),className:"bg-zinc-800 border border-zinc-700 text-zinc-200 rounded px-1 py-0.5 w-14"}),React.createElement("label",{className:"text-zinc-500"},"Gate %"),React.createElement("input",{type:"number",min:10,max:200,value:arpModal.gate,onChange:e=>setArpModal({...arpModal,gate:parseInt(e.target.value)||80}),className:"bg-zinc-800 border border-zinc-700 text-zinc-200 rounded px-1 py-0.5 w-14"})),React.createElement("div",{className:"flex gap-1 mb-3"},React.createElement("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400"},React.createElement("input",{type:"checkbox",checked:!!arpModal.triplet,onChange:e=>setArpModal({...arpModal,triplet:e.target.checked})}),"Triplet"),React.createElement("label",{className:"flex items-center gap-1 text-[10px] text-zinc-400"},React.createElement("input",{type:"checkbox",checked:!!arpModal.dotted,onChange:e=>setArpModal({...arpModal,dotted:e.target.checked})}),"Dotted")),React.createElement("div",{className:"flex gap-2"},React.createElement("button",{onClick:()=>applyArpeggiate(arpModal),className:"flex-1 px-3 py-1.5 rounded text-xs font-bold bg-cyan-700 hover:bg-cyan-600 text-white"},"Apply"),React.createElement("button",{onClick:()=>setArpModal(null),className:"px-3 py-1.5 rounded text-xs bg-zinc-800 hover:bg-zinc-700 text-zinc-300"},"Cancel")))),strumModal&&React.createElement("div",{className:"absolute inset-0 z-40 flex items-center justify-center bg-black/60",onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation()},React.createElement("div",{className:"bg-zinc-900 border border-zinc-700 rounded-lg p-4 w-72 shadow-2xl"},React.createElement("div",{className:"text-sm font-bold text-cyan-300 mb-3"},"Strum"),React.createElement("div",{className:"grid grid-cols-2 gap-2 text-xs mb-3"},React.createElement("label",{className:"text-zinc-500"},"Strum ms"),React.createElement("input",{type:"number",min:0,max:120,value:strumModal.ms,onChange:e=>setStrumModal({...strumModal,ms:parseInt(e.target.value)||0}),className:"bg-zinc-800 border border-zinc-700 text-zinc-200 rounded px-1 py-0.5 w-16"}),React.createElement("label",{className:"text-zinc-500"},"Direction"),React.createElement("select",{value:strumModal.direction,onChange:e=>setStrumModal({...strumModal,direction:e.target.value}),className:"bg-zinc-800 border border-zinc-700 text-zinc-200 rounded px-1 py-0.5"},['DOWN','UP','ALTERNATE'].map(d=>React.createElement("option",{key:d,value:d},d)))),React.createElement("div",{className:"flex gap-2"},React.createElement("button",{onClick:()=>applyStrum(strumModal),className:"flex-1 px-3 py-1.5 rounded text-xs font-bold bg-cyan-700 hover:bg-cyan-600 text-white"},"Apply"),React.createElement("button",{onClick:()=>setStrumModal(null),className:"px-3 py-1.5 rounded text-xs bg-zinc-800 hover:bg-zinc-700 text-zinc-300"},"Cancel")))),humanizeModal&&React.createElement("div",{className:"absolute inset-0 z-40 flex items-center justify-center bg-black/60",onMouseDown:e=>e.stopPropagation(),onClick:e=>e.stopPropagation()},React.createElement("div",{className:"bg-zinc-900 border border-zinc-700 rounded-lg p-4 w-72 shadow-2xl"},React.createElement("div",{className:"text-sm font-bold text-cyan-300 mb-3"},"Humanize"),React.createElement("div",{className:"grid grid-cols-2 gap-2 text-xs mb-3"},React.createElement("label",{className:"text-zinc-500"},"Timing ±ms"),React.createElement("input",{type:"number",min:0,max:30,value:humanizeModal.timingMs,onChange:e=>setHumanizeModal({...humanizeModal,timingMs:parseInt(e.target.value)||0}),className:"bg-zinc-800 border border-zinc-700 text-zinc-200 rounded px-1 py-0.5 w-16"}),React.createElement("label",{className:"text-zinc-500"},"Vel ±(0-127)"),React.createElement("input",{type:"number",min:0,max:20,value:humanizeModal.velRange,onChange:e=>setHumanizeModal({...humanizeModal,velRange:parseInt(e.target.value)||0}),className:"bg-zinc-800 border border-zinc-700 text-zinc-200 rounded px-1 py-0.5 w-16"}),React.createElement("label",{className:"text-zinc-500"},"Dur ±%"),React.createElement("input",{type:"number",min:0,max:50,value:humanizeModal.durRange,onChange:e=>setHumanizeModal({...humanizeModal,durRange:parseInt(e.target.value)||0}),className:"bg-zinc-800 border border-zinc-700 text-zinc-200 rounded px-1 py-0.5 w-16"})),React.createElement("div",{className:"flex gap-2"},React.createElement("button",{onClick:()=>applyHumanizeModal(humanizeModal),className:"flex-1 px-3 py-1.5 rounded text-xs font-bold bg-cyan-700 hover:bg-cyan-600 text-white"},"Apply"),React.createElement("button",{onClick:()=>setHumanizeModal(null),className:"px-3 py-1.5 rounded text-xs bg-zinc-800 hover:bg-zinc-700 text-zinc-300"},"Cancel")))),scaleMenuPos&&renderScaleContextMenu());};const serializeTracksList=(tracksList,secondsPerBar)=>{return(tracksList||[]).map(t=>{let trackType="AUDIO";if(t.type==='MIDI'||t.type==='soundfont'||t.type==='vst3')trackType="MIDI";else if(t.type==='SECTION')trackType="SECTION";else if(t.sections&&t.sections.length>0)trackType="SECTION";else if(t.midiItems&&t.midiItems.length>0)trackType="MIDI";const items=[];// Serialize EVERY item type present on the track (a track can hold audio // clips + MIDI items + section items at once). The old if/else-if chain // dropped all but one type per track — silent data loss on save. -if(t.clips&&t.clips.length>0){t.clips.forEach(c=>{const durationSec=c.buffer?c.buffer.duration:4.0;const clipFileId=c.serverFileId||t.serverFileId;items.push({id:c.id,name:c.name||"Audio Clip",type:"AUDIO_ITEM",start_bar:c.startTime/secondsPerBar,duration_bars:durationSec/(c.speed||1.0)/secondsPerBar,clip_start_offset_bars:0.0,source_data:{audio_file_url:clipFileId?`/static/audio/uploads/${clipFileId}`:"",sample_rate:c.buffer?c.buffer.sampleRate:44100,channels:c.buffer?c.buffer.numberOfChannels:2,gain:1.0,server_file_id:clipFileId}});});}if(t.midiItems&&t.midiItems.length>0){t.midiItems.forEach(m=>{items.push({id:m.id,name:m.name||"MIDI Item",type:"MIDI_ITEM",start_bar:m.startTime/secondsPerBar,duration_bars:m.duration?m.duration/secondsPerBar:4.0,clip_start_offset_bars:0.0,source_data:{total_buffer_bars:m.duration?m.duration/secondsPerBar:8.0,notes:(m.notes||[]).map(n=>({id:n.id||'note_'+Math.random().toString(36).substr(2,9),pitch:n.pitch||60,start_beat:n.start_beat||0.0,duration_beats:n.duration_beats||1.0,velocity:n.velocity||0.8,pan:n.pan||0.0,expression_curve:(Array.isArray(n.expression_curve)?n.expression_curve:[]).map(p=>({position_ratio:p.position_ratio,value:p.value}))}))}});});}if(t.sections&&t.sections.length>0){t.sections.forEach(s=>{// BỎ section item thiếu sectionId (insertSectionAtPlayhead tạo section +if(t.clips&&t.clips.length>0){t.clips.forEach(c=>{const durationSec=c.buffer?c.buffer.duration:4.0;const clipFileId=c.serverFileId||t.serverFileId;items.push({id:c.id,name:c.name||"Audio Clip",type:"AUDIO_ITEM",start_bar:c.startTime/secondsPerBar,duration_bars:durationSec/(c.speed||1.0)/secondsPerBar,clip_start_offset_bars:0.0,source_data:{audio_file_url:clipFileId?`/static/audio/uploads/${clipFileId}`:"",sample_rate:c.buffer?c.buffer.sampleRate:44100,channels:c.buffer?c.buffer.numberOfChannels:2,gain:1.0,server_file_id:clipFileId}});});}if(t.midiItems&&t.midiItems.length>0){t.midiItems.forEach(m=>{items.push({id:m.id,name:m.name||"MIDI Item",type:"MIDI_ITEM",start_bar:m.startTime/secondsPerBar,duration_bars:m.duration?m.duration/secondsPerBar:4.0,clip_start_offset_bars:0.0,source_data:{total_buffer_bars:m.duration?m.duration/secondsPerBar:8.0,...(Array.isArray(m.cc11_global_curve)&&m.cc11_global_curve.length?{cc11_global_curve:m.cc11_global_curve.map(p=>({position_ratio:p.position_ratio,value:p.value}))}:{}),notes:(m.notes||[]).map(n=>({id:n.id||'note_'+Math.random().toString(36).substr(2,9),pitch:n.pitch||60,start_beat:n.start_beat||0.0,duration_beats:n.duration_beats||1.0,velocity:n.velocity||0.8,pan:n.pan||0.0,expression_curve:(Array.isArray(n.expression_curve)?n.expression_curve:[]).map(p=>({position_ratio:p.position_ratio,value:p.value}))}))}});});}if(t.sections&&t.sections.length>0){t.sections.forEach(s=>{// BỎ section item thiếu sectionId (insertSectionAtPlayhead tạo section // chưa gắn vào tab → s.sectionId undefined). Nếu serialize thật thì // referenced_section_id bị JSON.stringify bỏ → source_data = {} → // schema oneOf fail → lưu project báo lỗi xác thực (bug user gặp). @@ -849,15 +851,15 @@ if(t.clips&&t.clips.length>0){t.clips.forEach(c=>{const durationSec=c.buffer?c.b if(!s.sectionId)return;items.push({id:s.id,name:s.name||"Section Item",type:"SECTION_ITEM",start_bar:s.start/secondsPerBar,duration_bars:s.duration/secondsPerBar,clip_start_offset_bars:0.0,source_data:{referenced_section_id:s.sectionId}});});}return{id:t.id,name:t.name,type:trackType,color:t.color||null,volume_db:t.volumeDb||0.0,pan:t.pan||0.0,mute:t.muted||false,solo:t.solo||false,mastering_bypass:t.audioBypass||false,audio_bypass:t.audioBypass||false,midi_bypass:t.midiBypass||false,fx_active:t.fxActive!==false,instrument_id:t.instrumentId||null,instrument_program:t.instrumentProgram!==undefined?t.instrumentProgram:null,instrument_name:t.instrumentName||null,instrument_source:t.instrument_source||(t.synth_engine?t.synth_engine.type:null),soundfont_id:t.soundfont_id||(t.synth_engine?t.synth_engine.soundfont_id:null),soundfont_bank:t.soundfont_bank!==undefined?t.soundfont_bank:t.synth_engine?t.synth_engine.soundfont_bank:null,soundfont_program:t.soundfont_program!==undefined?t.soundfont_program:t.synth_engine?t.synth_engine.soundfont_program:null,synth_engine:t.synth_engine||undefined,midi_channel:t.midiChannel!==undefined?t.midiChannel:null,fx_chain:(t.fxChain||[]).map(m=>{if(typeof m==='string')return{type:m,active:true};const o={type:m.type,active:m.active!==false};if(m.type==='vst3'){o.path=m.path||'';o.name=m.name||'';o.preset_b64=_capturedPresetByPath[m.path]||m.preset_b64||'';o.bypass=!!m.bypass;}else if(m.params&&Object.keys(m.params).length)o.params=m.params;return o;}),vst_fx_chain:(()=>{const chainVst=(t.fxChain||[]).filter(m=>m&&m.type==='vst3');const vstSrc=chainVst.length?chainVst:t.vstFxChain||[];return vstSrc.map(s=>({type:'vst3',path:s.path||'',name:s.name||'',preset_b64:_capturedPresetByPath[s.path]||s.preset_b64||'',bypass:!!s.bypass}));})(),vst_fx_bypass:!!t.vstFxBypass,vst_gui_open_path:t.id===_persistFxGuiTrackId&&_persistFxGuiOpen&&_persistFxGuiOpen.path?_persistFxGuiOpen.path:t.vstGuiOpenPath||null,vst_gui_open_name:t.id===_persistFxGuiTrackId&&_persistFxGuiOpen&&_persistFxGuiOpen.name?_persistFxGuiOpen.name:t.vstGuiOpenName||null,server_file_id:t.serverFileId||null,items:items};});};const deserializeTracksList=(schemaTracks,secondsPerBar,sectionStore,visitedSections,depth)=>{// Guard CHU TRÌNH: SECTION_ITEM trỏ về section đang được deserialize (hoặc // chu trình A→B→A) → recursion vô hạn → RangeError: Maximum call stack size // exceeded khi restore project. Visited-set chặn cycle; depth chặn lồng sâu. -const visited=visitedSections||new Set();const curDepth=depth||0;if(curDepth>12)return[];return(schemaTracks||[]).map(t=>{const clips=[];const sections=[];const midiItems=[];(t.items||[]).forEach(item=>{if(item.type==="AUDIO_ITEM"){const src=item.source_data||{};const clipFileId=src.server_file_id||(src.audio_file_url?src.audio_file_url.split('/').pop():null)||null;clips.push({id:item.id,name:item.name,startTime:item.start_bar*secondsPerBar,speed:1.0,duration:item.duration_bars*secondsPerBar,serverFileId:clipFileId});}else if(item.type==="MIDI_ITEM"){const src=item.source_data||{};midiItems.push({id:item.id,name:item.name,parent_track_id:t.id,startTime:item.start_bar*secondsPerBar,duration:item.duration_bars*secondsPerBar,length_bars:item.duration_bars||4,notes:(src.notes||[]).map(n=>({id:n.id,pitch:n.pitch||60,start_beat:n.start_beat||0.0,duration_beats:n.duration_beats||1.0,velocity:n.velocity||0.8,pan:n.pan||0.0,...(Array.isArray(n.expression_curve)?{expression_curve:n.expression_curve}:{})}))});}else if(item.type==="SECTION_ITEM"){const src=item.source_data||{};const secId=src.referenced_section_id;const secContainer=sectionStore?sectionStore[secId]:null;const isCycle=secContainer?visited.has(secId):false;sections.push({id:item.id,name:item.name,start:item.start_bar*secondsPerBar,duration:item.duration_bars*secondsPerBar,length_bars:item.duration_bars||4,sectionId:secId,tracks:secContainer&&!isCycle?deserializeTracksList(secContainer.tracks,secondsPerBar,sectionStore,new Set(visited).add(secId),curDepth+1):null});}});return{id:t.id,name:t.name,type:t.type==='MIDI'?'MIDI':t.type==='SECTION'?'SECTION':'audio',volumeDb:t.volume_db||0.0,pan:t.pan||0.0,muted:t.mute||false,solo:t.solo||false,masteringBypass:t.audio_bypass!==undefined?t.audio_bypass:t.mastering_bypass||false,audioBypass:t.audio_bypass!==undefined?t.audio_bypass:t.mastering_bypass||false,midiBypass:t.midi_bypass!==undefined?t.midi_bypass:t.mastering_bypass||false,fxActive:t.fx_active!==undefined?t.fx_active:true,color:t.color||(t.id==='1'?'#0f766e':'#1d4ed8'),startTime:t.start_time||0,height:t.height||140,markers:t.markers||[],serverFileId:t.server_file_id||t.items&&t.items.find(function(i){return i.type==='AUDIO_ITEM';})?.source_data?.server_file_id||t.items&&t.items.find(function(i){return i.type==='AUDIO_ITEM';})?.source_data?.audio_file_url?.split('/').pop()||null,channelInfo:t.channel_info||null,isArmed:t.is_armed||false,monitoringEnabled:t.monitoring_enabled!==false,inputSource:t.input_source?{deviceType:t.input_source.device_type||'NONE',deviceId:t.input_source.device_id||''}:{deviceType:'NONE',deviceId:''},midiChannel:t.midi_channel!=null?t.midi_channel:undefined,is_percussion:t.is_percussion||false,clips:clips,sections:sections,midiItems:midiItems,instrumentId:t.instrumentId!=null?t.instrumentId:t.instrument_id||null,instrumentProgram:t.instrumentProgram!==undefined&&t.instrumentProgram!==null?t.instrumentProgram:t.instrument_program!==null?t.instrument_program:undefined,instrumentName:t.instrument_name||null,instrument_source:t.instrument_source||null,soundfont_id:t.soundfont_id||null,soundfont_bank:t.soundfont_bank!==null?t.soundfont_bank:undefined,soundfont_program:t.soundfont_program!==null?t.soundfont_program:undefined,synth_engine:t.synth_engine||undefined,fxChain:(()=>{const parsed=(t.fx_chain||[]).map(m=>typeof m==='string'?{type:m,active:true}:{type:m.type||m,active:m.active!==false,...(m.params?{params:m.params}:{}),...(m.type==='vst3'?{path:m.path||'',name:m.name||'',preset_b64:m.preset_b64||'',bypass:!!m.bypass}:{})});const seen=new Set(parsed.filter(m=>m.type==='vst3').map(m=>m.path));(t.vst_fx_chain||[]).forEach(s=>{if(s&&s.path&&!seen.has(s.path)){parsed.push({type:'vst3',path:s.path||'',name:s.name||'',preset_b64:s.preset_b64||'',bypass:!!s.bypass,active:true});seen.add(s.path);}});return parsed;})(),vstFxChain:(()=>{const fromChain=(t.fx_chain||[]).filter(m=>m&&m.type==='vst3');const src=fromChain.length?fromChain:t.vst_fx_chain||[];return src.map(s=>({type:s.type||'vst3',path:s.path||'',name:s.name||'',preset_b64:s.preset_b64||'',bypass:!!s.bypass}));})(),vstFxBypass:t.vst_fx_bypass!==undefined?!!t.vst_fx_bypass:false,vstGuiOpenPath:t.vst_gui_open_path||null,vstGuiOpenName:t.vst_gui_open_name||null};});};const serializeProjectToSchema=(projectId,name,bpmVal,tracksList,subTabsList,sessionTabsList,masteringSettings,masterVolume,masterState)=>{const secondsPerBar=60.0/parseFloat(bpmVal||120)*4;const mainTracks=serializeTracksList(tracksList,secondsPerBar);const sectionStore={};// Helper: compute length_bars from tracks content +const visited=visitedSections||new Set();const curDepth=depth||0;if(curDepth>12)return[];return(schemaTracks||[]).map(t=>{const clips=[];const sections=[];const midiItems=[];(t.items||[]).forEach(item=>{if(item.type==="AUDIO_ITEM"){const src=item.source_data||{};const clipFileId=src.server_file_id||(src.audio_file_url?src.audio_file_url.split('/').pop():null)||null;clips.push({id:item.id,name:item.name,startTime:item.start_bar*secondsPerBar,speed:1.0,duration:item.duration_bars*secondsPerBar,serverFileId:clipFileId});}else if(item.type==="MIDI_ITEM"){const src=item.source_data||{};midiItems.push({id:item.id,name:item.name,parent_track_id:t.id,startTime:item.start_bar*secondsPerBar,duration:item.duration_bars*secondsPerBar,length_bars:item.duration_bars||4,notes:(src.notes||[]).map(n=>({id:n.id,pitch:n.pitch||60,start_beat:n.start_beat||0.0,duration_beats:n.duration_beats||1.0,velocity:n.velocity||0.8,pan:n.pan||0.0,...(Array.isArray(n.expression_curve)?{expression_curve:n.expression_curve}:{})})),...(Array.isArray(src.cc11_global_curve)&&src.cc11_global_curve.length?{cc11_global_curve:src.cc11_global_curve}:{})});}else if(item.type==="SECTION_ITEM"){const src=item.source_data||{};const secId=src.referenced_section_id;const secContainer=sectionStore?sectionStore[secId]:null;const isCycle=secContainer?visited.has(secId):false;sections.push({id:item.id,name:item.name,start:item.start_bar*secondsPerBar,duration:item.duration_bars*secondsPerBar,length_bars:item.duration_bars||4,sectionId:secId,tracks:secContainer&&!isCycle?deserializeTracksList(secContainer.tracks,secondsPerBar,sectionStore,new Set(visited).add(secId),curDepth+1):null});}});return{id:t.id,name:t.name,type:t.type==='MIDI'?'MIDI':t.type==='SECTION'?'SECTION':'audio',volumeDb:t.volume_db||0.0,pan:t.pan||0.0,muted:t.mute||false,solo:t.solo||false,masteringBypass:t.audio_bypass!==undefined?t.audio_bypass:t.mastering_bypass||false,audioBypass:t.audio_bypass!==undefined?t.audio_bypass:t.mastering_bypass||false,midiBypass:t.midi_bypass!==undefined?t.midi_bypass:t.mastering_bypass||false,fxActive:t.fx_active!==undefined?t.fx_active:true,color:t.color||(t.id==='1'?'#0f766e':'#1d4ed8'),startTime:t.start_time||0,height:t.height||140,markers:t.markers||[],serverFileId:t.server_file_id||t.items&&t.items.find(function(i){return i.type==='AUDIO_ITEM';})?.source_data?.server_file_id||t.items&&t.items.find(function(i){return i.type==='AUDIO_ITEM';})?.source_data?.audio_file_url?.split('/').pop()||null,channelInfo:t.channel_info||null,isArmed:t.is_armed||false,monitoringEnabled:t.monitoring_enabled!==false,inputSource:t.input_source?{deviceType:t.input_source.device_type||'NONE',deviceId:t.input_source.device_id||''}:{deviceType:'NONE',deviceId:''},midiChannel:t.midi_channel!=null?t.midi_channel:undefined,is_percussion:t.is_percussion||false,clips:clips,sections:sections,midiItems:midiItems,instrumentId:t.instrumentId!=null?t.instrumentId:t.instrument_id||null,instrumentProgram:t.instrumentProgram!==undefined&&t.instrumentProgram!==null?t.instrumentProgram:t.instrument_program!==null?t.instrument_program:undefined,instrumentName:t.instrument_name||null,instrument_source:t.instrument_source||null,soundfont_id:t.soundfont_id||null,soundfont_bank:t.soundfont_bank!==null?t.soundfont_bank:undefined,soundfont_program:t.soundfont_program!==null?t.soundfont_program:undefined,synth_engine:t.synth_engine||undefined,fxChain:(()=>{const parsed=(t.fx_chain||[]).map(m=>typeof m==='string'?{type:m,active:true}:{type:m.type||m,active:m.active!==false,...(m.params?{params:m.params}:{}),...(m.type==='vst3'?{path:m.path||'',name:m.name||'',preset_b64:m.preset_b64||'',bypass:!!m.bypass}:{})});const seen=new Set(parsed.filter(m=>m.type==='vst3').map(m=>m.path));(t.vst_fx_chain||[]).forEach(s=>{if(s&&s.path&&!seen.has(s.path)){parsed.push({type:'vst3',path:s.path||'',name:s.name||'',preset_b64:s.preset_b64||'',bypass:!!s.bypass,active:true});seen.add(s.path);}});return parsed;})(),vstFxChain:(()=>{const fromChain=(t.fx_chain||[]).filter(m=>m&&m.type==='vst3');const src=fromChain.length?fromChain:t.vst_fx_chain||[];return src.map(s=>({type:s.type||'vst3',path:s.path||'',name:s.name||'',preset_b64:s.preset_b64||'',bypass:!!s.bypass}));})(),vstFxBypass:t.vst_fx_bypass!==undefined?!!t.vst_fx_bypass:false,vstGuiOpenPath:t.vst_gui_open_path||null,vstGuiOpenName:t.vst_gui_open_name||null};});};const serializeProjectToSchema=(projectId,name,bpmVal,tracksList,subTabsList,sessionTabsList,masteringSettings,masterVolume,masterState)=>{const secondsPerBar=60.0/parseFloat(bpmVal||120)*4;const mainTracks=serializeTracksList(tracksList,secondsPerBar);const sectionStore={};// Helper: compute length_bars from tracks content const computeLengthBars=(tracksArr,spb)=>{let maxSec=0;(tracksArr||[]).forEach(tr=>{(tr.clips||[]).forEach(c=>{const end=(c.startTime||0)+(c.buffer?c.buffer.duration/(c.speed||1.0):4);if(end>maxSec)maxSec=end;});(tr.midiItems||[]).forEach(m=>{const end=(m.startTime||0)+(m.duration||4);if(end>maxSec)maxSec=end;});});return Math.ceil((maxSec||4)/spb);};// 1. Populate from sessionTabsList (open tabs) (sessionTabsList||[]).forEach(st=>{const serializedTracks=serializeTracksList(st.tracks,secondsPerBar);sectionStore[st.sectionId]={id:st.sectionId,name:st.name,is_root:false,length_bars:computeLengthBars(st.tracks,secondsPerBar),auto_compute_length:true,tracks:serializedTracks,color:st.color||null};});// 2. Also populate from tracksList (closed tabs saved inside Section items) -const scanForSections=tracks=>{(tracks||[]).forEach(t=>{if(t.sections){t.sections.forEach(s=>{const secId=s.sectionId||s.id;if(s.tracks&&!sectionStore[secId]){sectionStore[secId]={id:secId,name:s.name,is_root:false,length_bars:computeLengthBars(s.tracks,secondsPerBar),auto_compute_length:true,tracks:serializeTracksList(s.tracks,secondsPerBar),color:s.color||null};}if(s.tracks){scanForSections(s.tracks);}});}});};scanForSections(tracksList);const subTabs=(subTabsList||[]).map(st=>{return{id:st.id,label:st.label,type:st.type,track_id:st.trackId,target_id:st.target_id,parent_tab_id:st.parent_tab_id,notes:st.notes||[],duration:st.duration||4,instrument_program:st.instrumentProgram,instrument_name:st.instrumentName,instrument_id:st.instrumentId||st.synth_engine&&st.synth_engine.plugin_id||null,synth_engine:st.synth_engine||null,current_time:st.currentTime||0,color:st.color||null};});return{project_id:projectId||'proj_'+Date.now(),metadata:{title:name||"Dự án mới",bpm:parseFloat(bpmVal||120),time_signature_numerator:4,time_signature_denominator:4,sample_rate:44100,zoom:window.__sfTimelineZoom||window.__currentZoom||1.0,loop_selection:!!window.__sfLoopSelection,selection_start:window.__sfLoopSelection&&window.__sfSelectionStart!=null?window.__sfSelectionStart:null,selection_end:window.__sfLoopSelection&&window.__sfSelectionEnd!=null?window.__sfSelectionEnd:null},main_session:{id:"main",name:"MAIN SESSION",is_root:true,length_bars:(()=>{let maxBar=16.0;(mainTracks||[]).forEach(t=>{(t.items||[]).forEach(item=>{const end=(item.start_bar||0)+(item.duration_bars||4);if(end>maxBar)maxBar=end;});});return maxBar;})(),auto_compute_length:true,tracks:mainTracks,...(masteringSettings&&Array.isArray(masteringSettings.vstFxChain)&&masteringSettings.vstFxChain.length>0||typeof masterVolume==='number'&&isFinite(masterVolume)&&masterVolume!==0||masterState&&(masterState.volL!==0||masterState.volR!==0||masterState.muted||!masterState.link)||Array.isArray(window.__masterAutoVol)&&window.__masterAutoVol.length>0?{master:{fx_chain:masteringSettings.vstFxChain.map(s=>({type:s.type||'vst3',path:s.path||'',name:s.name||'',preset_b64:_capturedPresetByPath[s.path]||s.preset_b64||'',bypass:!!s.bypass})),volume_db:typeof masterVolume==='number'&&isFinite(masterVolume)?masterVolume:0,volumeL_db:masterState&&typeof masterState.volL==='number'&&isFinite(masterState.volL)?masterState.volL:typeof masterVolume==='number'&&isFinite(masterVolume)?masterVolume:0,volumeR_db:masterState&&typeof masterState.volR==='number'&&isFinite(masterState.volR)?masterState.volR:typeof masterVolume==='number'&&isFinite(masterVolume)?masterVolume:0,link_lr:masterState?!!masterState.link:false,muted:masterState?!!masterState.muted:false,mute:masterState?!!masterState.muted:false,bypass:!masteringSettings.masterConnected||!!masteringSettings.vstBypass,...(Array.isArray(window.__masterAutoVol)&&window.__masterAutoVol.length>0?{automation:{volume_db:window.__masterAutoVol.map(p=>({time:p.time,db:p.db}))}}:{})}}:{})},sub_tabs:subTabs,section_store:sectionStore,mastering_settings:masteringSettings?{...masteringSettings,// FIX preset VST master mất sau save/load: GUI capture (_capturedPresetByPath) +const scanForSections=tracks=>{(tracks||[]).forEach(t=>{if(t.sections){t.sections.forEach(s=>{const secId=s.sectionId||s.id;if(s.tracks&&!sectionStore[secId]){sectionStore[secId]={id:secId,name:s.name,is_root:false,length_bars:computeLengthBars(s.tracks,secondsPerBar),auto_compute_length:true,tracks:serializeTracksList(s.tracks,secondsPerBar),color:s.color||null};}if(s.tracks){scanForSections(s.tracks);}});}});};scanForSections(tracksList);const subTabs=(subTabsList||[]).map(st=>{return{id:st.id,label:st.label,type:st.type,track_id:st.trackId,target_id:st.target_id,parent_tab_id:st.parent_tab_id,notes:st.notes||[],...(Array.isArray(st.cc11_global_curve)&&st.cc11_global_curve.length?{cc11_global_curve:st.cc11_global_curve.map(p=>({position_ratio:p.position_ratio,value:p.value}))}:{}),duration:st.duration||4,instrument_program:st.instrumentProgram,instrument_name:st.instrumentName,instrument_id:st.instrumentId||st.synth_engine&&st.synth_engine.plugin_id||null,synth_engine:st.synth_engine||null,current_time:st.currentTime||0,color:st.color||null};});return{project_id:projectId||'proj_'+Date.now(),metadata:{title:name||"Dự án mới",bpm:parseFloat(bpmVal||120),time_signature_numerator:4,time_signature_denominator:4,sample_rate:44100,zoom:window.__sfTimelineZoom||window.__currentZoom||1.0,loop_selection:!!window.__sfLoopSelection,selection_start:window.__sfLoopSelection&&window.__sfSelectionStart!=null?window.__sfSelectionStart:null,selection_end:window.__sfLoopSelection&&window.__sfSelectionEnd!=null?window.__sfSelectionEnd:null},main_session:{id:"main",name:"MAIN SESSION",is_root:true,length_bars:(()=>{let maxBar=16.0;(mainTracks||[]).forEach(t=>{(t.items||[]).forEach(item=>{const end=(item.start_bar||0)+(item.duration_bars||4);if(end>maxBar)maxBar=end;});});return maxBar;})(),auto_compute_length:true,tracks:mainTracks,...(masteringSettings&&Array.isArray(masteringSettings.vstFxChain)&&masteringSettings.vstFxChain.length>0||typeof masterVolume==='number'&&isFinite(masterVolume)&&masterVolume!==0||masterState&&(masterState.volL!==0||masterState.volR!==0||masterState.muted||!masterState.link)||Array.isArray(window.__masterAutoVol)&&window.__masterAutoVol.length>0?{master:{fx_chain:masteringSettings.vstFxChain.map(s=>({type:s.type||'vst3',path:s.path||'',name:s.name||'',preset_b64:_capturedPresetByPath[s.path]||s.preset_b64||'',bypass:!!s.bypass})),volume_db:typeof masterVolume==='number'&&isFinite(masterVolume)?masterVolume:0,volumeL_db:masterState&&typeof masterState.volL==='number'&&isFinite(masterState.volL)?masterState.volL:typeof masterVolume==='number'&&isFinite(masterVolume)?masterVolume:0,volumeR_db:masterState&&typeof masterState.volR==='number'&&isFinite(masterState.volR)?masterState.volR:typeof masterVolume==='number'&&isFinite(masterVolume)?masterVolume:0,link_lr:masterState?!!masterState.link:false,muted:masterState?!!masterState.muted:false,mute:masterState?!!masterState.muted:false,bypass:!masteringSettings.masterConnected||!!masteringSettings.vstBypass,...(Array.isArray(window.__masterAutoVol)&&window.__masterAutoVol.length>0?{automation:{volume_db:window.__masterAutoVol.map(p=>({time:p.time,db:p.db}))}}:{})}}:{})},sub_tabs:subTabs,section_store:sectionStore,mastering_settings:masteringSettings?{...masteringSettings,// FIX preset VST master mất sau save/load: GUI capture (_capturedPresetByPath) // trước đây chỉ merge vào main_session.master.fx_chain, còn mastering_settings // (nguồn ưu tiên lúc deserialize) giữ preset cũ/rỗng → load lại mất settings. // Merge cả vstFxChain + chain (entry vst3) để 2 nơi lưu đồng nhất. vstFxChain:(masteringSettings.vstFxChain||[]).map(s=>({...s,preset_b64:_capturedPresetByPath[s.path]||s.preset_b64||''})),chain:(masteringSettings.chain||[]).map(m=>m&&m.type==='vst3'?{...m,preset_b64:_capturedPresetByPath[m.path]||m.preset_b64||''}:m),gui_open_path:_persistMasterGuiOpen&&_persistMasterGuiOpen.path?_persistMasterGuiOpen.path:masteringSettings&&masteringSettings.gui_open_path||null,gui_open_name:_persistMasterGuiOpen&&_persistMasterGuiOpen.name?_persistMasterGuiOpen.name:masteringSettings&&masteringSettings.gui_open_name||null}:null};};const deserializeProjectFromSchema=schemaObj=>{// GUI knob captures are per-project - don't leak presets between projects. -_capturedPresetByPath={};const bpmVal=schemaObj.metadata?schemaObj.metadata.bpm:120;const secondsPerBar=60.0/bpmVal*4;const sectionStore=schemaObj.section_store||{};const restoredTracks=deserializeTracksList(schemaObj.main_session.tracks,secondsPerBar,sectionStore);const restoredSessionTabs=[];Object.keys(sectionStore).forEach(secId=>{const secContainer=sectionStore[secId];const secTracks=deserializeTracksList(secContainer.tracks,secondsPerBar,sectionStore);restoredSessionTabs.push({id:'session_'+secId,name:secContainer.name,sectionId:secId,tracks:secTracks,length_bars:secContainer.length_bars||16.0,auto_compute_length:secContainer.auto_compute_length!==undefined?secContainer.auto_compute_length:true,color:secContainer.color||null});});const restoredSubTabs=(schemaObj.sub_tabs||[]).map(st=>{return{id:st.id,label:st.label,type:st.type,trackId:st.track_id,target_id:st.target_id,parent_tab_id:st.parent_tab_id,notes:st.notes||[],duration:st.duration||4,instrumentProgram:st.instrument_program,instrumentName:st.instrument_name,instrumentId:st.instrument_id||st.synth_engine&&st.synth_engine.plugin_id||null,synth_engine:st.synth_engine||null,currentTime:st.current_time||0,color:st.color||null};});// Migrate mastering settings saved with the OLD imager width scale +_capturedPresetByPath={};const bpmVal=schemaObj.metadata?schemaObj.metadata.bpm:120;const secondsPerBar=60.0/bpmVal*4;const sectionStore=schemaObj.section_store||{};const restoredTracks=deserializeTracksList(schemaObj.main_session.tracks,secondsPerBar,sectionStore);const restoredSessionTabs=[];Object.keys(sectionStore).forEach(secId=>{const secContainer=sectionStore[secId];const secTracks=deserializeTracksList(secContainer.tracks,secondsPerBar,sectionStore);restoredSessionTabs.push({id:'session_'+secId,name:secContainer.name,sectionId:secId,tracks:secTracks,length_bars:secContainer.length_bars||16.0,auto_compute_length:secContainer.auto_compute_length!==undefined?secContainer.auto_compute_length:true,color:secContainer.color||null});});const restoredSubTabs=(schemaObj.sub_tabs||[]).map(st=>{return{id:st.id,label:st.label,type:st.type,trackId:st.track_id,target_id:st.target_id,parent_tab_id:st.parent_tab_id,notes:st.notes||[],cc11_global_curve:st.cc11_global_curve||null,duration:st.duration||4,instrumentProgram:st.instrument_program,instrumentName:st.instrument_name,instrumentId:st.instrument_id||st.synth_engine&&st.synth_engine.plugin_id||null,synth_engine:st.synth_engine||null,currentTime:st.current_time||0,color:st.color||null};});// Migrate mastering settings saved with the OLD imager width scale // (−100..+100, 0 = original width) to the new imager_spec.md scale // (0..200, 0% = MONO, 100% = original, 200% = double width): old value v // meant S × (1 + v/100), which equals the new value (v + 100). Projects @@ -1516,12 +1518,12 @@ const existing=subTabs.find(s=>s.trackId===trackId&&s.startTime===selLeft&&s.end if(isPlaying){// Lưu điểm resume: nếu user bấm Space trong piano roll (play piano roll // → stopAllPlayback dừng main) → khi quay lại MAIN/SECTION resume main // từ đúng vị trí âm (offset + elapsed thật) — hết câm. -mainResumeRef.current={offset:startOffsetTimeRef.current,audioTime:getAudioContext().currentTime};}else{mainResumeRef.current=null;stopAllPlayback();}const ctx=getAudioContext();const silentBuffer=ctx.createBuffer(1,128,ctx.sampleRate);const existing=subTabs.find(s=>s.type==='PIANO_ROLL'&&s.target_id===midiItemId);if(existing){setSubTabs(prev=>prev.map(s=>s.id===existing.id?{...s,buffer:s.buffer||silentBuffer,instrumentProgram:track.instrumentProgram!==undefined?track.instrumentProgram:track.synth_engine?track.synth_engine.soundfont_program:undefined,instrumentName:track.instrumentName,instrumentId:track.instrumentId,synth_engine:track.synth_engine}:s));setActiveTab(existing.id);showToast('Piano Roll cho nốt MIDI đã được mở.','info');return;}const tabId='midi_'+Date.now();const tabLabel=`Piano Roll: ${midiItem.name||'MIDI'}`;const newTab={id:tabId,label:tabLabel,type:'PIANO_ROLL',trackId:trackId,target_id:midiItemId,parent_tab_id:activeTab==='main'?null:activeTab,notes:midiItem.notes||[],duration:midiItem.duration||4,buffer:silentBuffer,instrumentProgram:track.instrumentProgram!==undefined?track.instrumentProgram:track.synth_engine?track.synth_engine.soundfont_program:undefined,instrumentName:track.instrumentName,instrumentId:track.instrumentId,synth_engine:track.synth_engine,currentTime:0,isPlaying:false,isLooping:true,selectionStart:null,selectionEnd:null,viewport_start_bar:0.0,viewport_bar_width:8.0,scroll_y_pitch:60,snap_resolution:snapValue||"1/16",note_selection:[]};setSubTabs(prev=>[...prev,newTab]);setActiveTab(tabId);// Đồng bộ routing SF + mastering ngay khi mở piano roll — preview keybed +mainResumeRef.current={offset:startOffsetTimeRef.current,audioTime:getAudioContext().currentTime};}else{mainResumeRef.current=null;stopAllPlayback();}const ctx=getAudioContext();const silentBuffer=ctx.createBuffer(1,128,ctx.sampleRate);const existing=subTabs.find(s=>s.type==='PIANO_ROLL'&&s.target_id===midiItemId);if(existing){setSubTabs(prev=>prev.map(s=>s.id===existing.id?{...s,buffer:s.buffer||silentBuffer,instrumentProgram:track.instrumentProgram!==undefined?track.instrumentProgram:track.synth_engine?track.synth_engine.soundfont_program:undefined,instrumentName:track.instrumentName,instrumentId:track.instrumentId,synth_engine:track.synth_engine}:s));setActiveTab(existing.id);showToast('Piano Roll cho nốt MIDI đã được mở.','info');return;}const tabId='midi_'+Date.now();const tabLabel=`Piano Roll: ${midiItem.name||'MIDI'}`;const newTab={id:tabId,label:tabLabel,type:'PIANO_ROLL',trackId:trackId,target_id:midiItemId,parent_tab_id:activeTab==='main'?null:activeTab,notes:midiItem.notes||[],cc11_global_curve:midiItem.cc11_global_curve||null,duration:midiItem.duration||4,buffer:silentBuffer,instrumentProgram:track.instrumentProgram!==undefined?track.instrumentProgram:track.synth_engine?track.synth_engine.soundfont_program:undefined,instrumentName:track.instrumentName,instrumentId:track.instrumentId,synth_engine:track.synth_engine,currentTime:0,isPlaying:false,isLooping:true,selectionStart:null,selectionEnd:null,viewport_start_bar:0.0,viewport_bar_width:8.0,scroll_y_pitch:60,snap_resolution:snapValue||"1/16",note_selection:[]};setSubTabs(prev=>[...prev,newTab]);setActiveTab(tabId);// Đồng bộ routing SF + mastering ngay khi mở piano roll — preview keybed // phải đi qua mastering FX của main out (không cần bật/tắt power). setTimeout(()=>{try{if(window.__ensureMasteringRouting)window.__ensureMasteringRouting();}catch(e){}},60);// KHÔNG loadSoundFont ở đây (kể cả nền): sfload SF mới bất đồng bộ làm // WASM heap 256MB đầy → FluidSynth stall → CÂM TOÀN CỤC (mọi âm thanh // chết sau khi mở tab). playNote TỰ load + retry đúng lúc note cần. -};const handleUpdateMidiNotes=(tabId,notes)=>{setSubTabs(prev=>prev.map(s=>s.id===tabId?{...s,notes:notes,isDirty:true}:s));};const handleSaveMidiNotes=(tabId,trackId,midiItemId,updatedNotes)=>{const pianoRollTab=subTabs.find(s=>s.id===tabId);const parentTabId=pianoRollTab?pianoRollTab.parent_tab_id:null;if(parentTabId&&parentTabId.startsWith('session_')){setSessionTabs(prev=>prev.map(s=>{if(s.id!==parentTabId)return s;return{...s,tracks:s.tracks.map(t=>{if(t.id!==trackId)return t;return{...t,midiItems:(t.midiItems||[]).map(m=>{if(m.id!==midiItemId)return m;return{...m,notes:updatedNotes};})};})};}));}else{setTracks(prev=>prev.map(t=>{if(t.id!==trackId)return t;return{...t,midiItems:(t.midiItems||[]).map(m=>{if(m.id!==midiItemId)return m;return{...m,notes:updatedNotes};})};}));}setSubTabs(prev=>prev.map(s=>s.id===tabId?{...s,isDirty:false}:s));showToast('Đã lưu các chỉnh sửa nốt MIDI vào item cha!','success');};// Sync nội dung SECTION-TAB → section item trên MAIN (sec.tracks) — cập nhật +};const handleUpdateMidiNotes=(tabId,notes)=>{setSubTabs(prev=>prev.map(s=>s.id===tabId?{...s,notes:notes,isDirty:true}:s));};const handleSaveMidiNotes=(tabId,trackId,midiItemId,updatedNotes)=>{const pianoRollTab=subTabs.find(s=>s.id===tabId);const parentTabId=pianoRollTab?pianoRollTab.parent_tab_id:null;if(parentTabId&&parentTabId.startsWith('session_')){setSessionTabs(prev=>prev.map(s=>{if(s.id!==parentTabId)return s;return{...s,tracks:s.tracks.map(t=>{if(t.id!==trackId)return t;return{...t,midiItems:(t.midiItems||[]).map(m=>{if(m.id!==midiItemId)return m;return{...m,notes:updatedNotes,cc11_global_curve:pianoRollTab?pianoRollTab.cc11_global_curve||null:null};})};})};}));}else{setTracks(prev=>prev.map(t=>{if(t.id!==trackId)return t;return{...t,midiItems:(t.midiItems||[]).map(m=>{if(m.id!==midiItemId)return m;return{...m,notes:updatedNotes,cc11_global_curve:pianoRollTab?pianoRollTab.cc11_global_curve||null:null};})};}));}setSubTabs(prev=>prev.map(s=>s.id===tabId?{...s,isDirty:false}:s));showToast('Đã lưu các chỉnh sửa nốt MIDI vào item cha!','success');};// Sync nội dung SECTION-TAB → section item trên MAIN (sec.tracks) — cập nhật // canvas section item ngay khi thay đổi nội dung tab (user 07:45 — xóa item // trong SECTION-TAB → canvas section item ở MAIN phải vẽ lại). KHÔNG đổi // duration (0505 — giữ kích thước user resize). diff --git a/app/templates/index.html b/app/templates/index.html index b261919..960ac3b 100644 --- a/app/templates/index.html +++ b/app/templates/index.html @@ -51,7 +51,7 @@ - +