diff --git a/packages/core/draw.mjs b/packages/core/draw.mjs index 7260e654..4bfd3257 100644 --- a/packages/core/draw.mjs +++ b/packages/core/draw.mjs @@ -59,3 +59,9 @@ export const cleanupDraw = (clearScreen = true) => { clearInterval(window.strudelScheduler); } }; + +Pattern.prototype.onPaint = function (onPaint) { + // this is evil! TODO: add pattern.context + this.context = { onPaint }; + return this; +}; diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index a11841a6..5e8bc786 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -2060,6 +2060,7 @@ export const velocity = register('velocity', function (velocity, pat) { */ // TODO - fix export const legato = register('legato', function (value, pat) { + value = Fraction(value); return pat.withHapSpan((span) => new TimeSpan(span.begin, span.begin.add(span.end.sub(span.begin).mul(value)))); }); diff --git a/packages/core/pianoroll.mjs b/packages/core/pianoroll.mjs index 34ce1d4b..eecb274f 100644 --- a/packages/core/pianoroll.mjs +++ b/packages/core/pianoroll.mjs @@ -283,3 +283,15 @@ export function pianoroll({ ctx.stroke(); return this; } + +function getOptions(drawTime, options = {}) { + let [lookbehind, lookahead] = drawTime; + lookbehind = Math.abs(lookbehind); + const cycles = lookahead + lookbehind; + const playhead = lookbehind / cycles; + return { fold: 1, ...options, cycles, playhead }; +} + +Pattern.prototype.punchcard = function (options) { + return this.onPaint((ctx, time, haps, drawTime) => pianoroll({ ctx, time, haps, ...getOptions(drawTime, options) })); +}; diff --git a/packages/core/repl.mjs b/packages/core/repl.mjs index c71019ac..045f2102 100644 --- a/packages/core/repl.mjs +++ b/packages/core/repl.mjs @@ -12,8 +12,8 @@ export function repl({ afterEval, getTime, transpiler, - editPattern, onToggle, + editPattern, }) { const scheduler = new Cyclist({ interval, @@ -35,7 +35,7 @@ export function repl({ getTime, onToggle, }); - setTime(() => scheduler.getPhase()); // TODO: refactor? + setTime(() => scheduler.now()); // TODO: refactor? const evaluate = async (code, autostart = true) => { if (!code) { throw new Error('no code to evaluate'); diff --git a/packages/react/dist/index.cjs.js b/packages/react/dist/index.cjs.js index 5e9d79dc..9e5132ee 100644 --- a/packages/react/dist/index.cjs.js +++ b/packages/react/dist/index.cjs.js @@ -1 +1 @@ -"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const t=require("react"),ee=require("@uiw/react-codemirror"),E=require("@codemirror/view"),H=require("@codemirror/state"),te=require("@codemirror/lang-javascript"),i=require("@lezer/highlight"),re=require("@uiw/codemirror-themes"),B=require("@strudel.cycles/core"),W=require("@strudel.cycles/webaudio"),ae=require("react-hook-inview"),oe=require("@strudel.cycles/transpiler"),$=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},u=$(t),ne=$(ee),se=re.createTheme({theme:"dark",settings:{background:"#222",foreground:"#75baff",caret:"#ffcc00",selection:"rgba(128, 203, 196, 0.5)",selectionMatch:"#036dd626",lineHighlight:"#00000050",gutterBackground:"transparent",gutterForeground:"#8a919966"},styles:[{tag:i.tags.keyword,color:"#c792ea"},{tag:i.tags.operator,color:"#89ddff"},{tag:i.tags.special(i.tags.variableName),color:"#eeffff"},{tag:i.tags.typeName,color:"#c3e88d"},{tag:i.tags.atom,color:"#f78c6c"},{tag:i.tags.number,color:"#c3e88d"},{tag:i.tags.definition(i.tags.variableName),color:"#82aaff"},{tag:i.tags.string,color:"#c3e88d"},{tag:i.tags.special(i.tags.string),color:"#c3e88d"},{tag:i.tags.comment,color:"#7d8799"},{tag:i.tags.variableName,color:"#c792ea"},{tag:i.tags.tagName,color:"#c3e88d"},{tag:i.tags.bracket,color:"#525154"},{tag:i.tags.meta,color:"#ffcb6b"},{tag:i.tags.attributeName,color:"#c792ea"},{tag:i.tags.propertyName,color:"#c792ea"},{tag:i.tags.className,color:"#decb6b"},{tag:i.tags.invalid,color:"#ffffff"}]});const j=H.StateEffect.define(),ce=H.StateField.define({create(){return E.Decoration.none},update(e,a){try{for(let r of a.effects)if(r.is(j))if(r.value){const s=E.Decoration.mark({attributes:{style:"background-color: #FFCA2880"}});e=E.Decoration.set([s.range(0,a.newDoc.length)])}else e=E.Decoration.set([]);return e}catch(r){return console.warn("flash error",r),e}},provide:e=>E.EditorView.decorations.from(e)}),J=e=>{e.dispatch({effects:j.of(!0)}),setTimeout(()=>{e.dispatch({effects:j.of(!1)})},200)},P=H.StateEffect.define(),ie=H.StateField.define({create(){return E.Decoration.none},update(e,a){try{for(let r of a.effects)if(r.is(P)){const s=r.value.map(n=>(n.context.locations||[]).map(({start:l,end:d})=>{const m=n.context.color||"#FFCA28";let o=a.newDoc.line(l.line).from+l.column,f=a.newDoc.line(d.line).from+d.column;const b=a.newDoc.length;return o>b||f>b?void 0:E.Decoration.mark({attributes:{style:`outline: 1.5px solid ${m};`}}).range(o,f)})).flat().filter(Boolean)||[];e=E.Decoration.set(s,!0)}return e}catch{return E.Decoration.set([])}},provide:e=>E.EditorView.decorations.from(e)}),le=[te.javascript(),se,ie,ce];function G({value:e,onChange:a,onViewChanged:r,onSelectionChange:s,options:n,editorDidMount:l}){const d=t.useCallback(f=>{a?.(f)},[a]),m=t.useCallback(f=>{r?.(f)},[r]),o=t.useCallback(f=>{f.selectionSet&&s&&s?.(f.state.selection)},[s]);return u.default.createElement(u.default.Fragment,null,u.default.createElement(ne.default,{value:e,onChange:d,onCreateEditor:m,onUpdate:o,extensions:le}))}function O(...e){return e.filter(Boolean).join(" ")}function Q({view:e,pattern:a,active:r,getTime:s}){const n=t.useRef([]),l=t.useRef();t.useEffect(()=>{if(e)if(a&&r){let d=requestAnimationFrame(function m(){try{const o=s(),b=[Math.max(l.current||o,o-1/10,0),o+1/60];l.current=b[1],n.current=n.current.filter(p=>p.whole.end>o);const v=a.queryArc(...b).filter(p=>p.hasOnset());n.current=n.current.concat(v),e.dispatch({effects:P.of(n.current)})}catch{e.dispatch({effects:P.of([])})}d=requestAnimationFrame(m)});return()=>{cancelAnimationFrame(d)}}else n.current=[],e.dispatch({effects:P.of([])})},[a,r,e])}function ue(e,a=!1){const r=t.useRef(),s=t.useRef(),n=m=>{if(s.current!==void 0){const o=m-s.current;e(m,o)}s.current=m,r.current=requestAnimationFrame(n)},l=()=>{r.current=requestAnimationFrame(n)},d=()=>{r.current&&cancelAnimationFrame(r.current),delete r.current};return t.useEffect(()=>{r.current&&(d(),l())},[e]),t.useEffect(()=>(a&&l(),d),[]),{start:l,stop:d}}function de({pattern:e,started:a,getTime:r,onDraw:s}){let n=t.useRef([]),l=t.useRef(null);const{start:d,stop:m}=ue(t.useCallback(()=>{const o=r();if(l.current===null){l.current=o;return}const f=e.queryArc(Math.max(l.current,o-1/10),o),b=4;l.current=o,n.current=(n.current||[]).filter(v=>v.whole.end>o-b).concat(f.filter(v=>v.hasOnset())),s(o,n.current)},[e]));t.useEffect(()=>{a?d():(n.current=[],m())},[a])}function X(e){return t.useEffect(()=>(window.addEventListener("message",e),()=>window.removeEventListener("message",e)),[e]),t.useCallback(a=>window.postMessage(a,"*"),[])}function Y({defaultOutput:e,interval:a,getTime:r,evalOnMount:s=!1,initialCode:n="",autolink:l=!1,beforeEval:d,afterEval:m,editPattern:o,onEvalError:f,onToggle:b,canvasId:v}){const p=t.useMemo(()=>fe(),[]);v=v||`canvas-${p}`;const[k,D]=t.useState(),[q,F]=t.useState(),[w,N]=t.useState(n),[C,T]=t.useState(),[z,R]=t.useState(),[S,V]=t.useState(!1),x=w!==C,{scheduler:M,evaluate:c,start:g,stop:_,pause:I}=t.useMemo(()=>B.repl({interval:a,defaultOutput:e,onSchedulerError:D,onEvalError:h=>{F(h),f?.(h)},getTime:r,transpiler:oe.transpiler,beforeEval:({code:h})=>{N(h),d?.()},editPattern:o?h=>o(h,p):void 0,afterEval:({pattern:h,code:L})=>{T(L),R(h),F(),D(),l&&(window.location.hash="#"+encodeURIComponent(btoa(L))),m?.()},onToggle:h=>{V(h),b?.(h)}}),[e,a,r]),Z=X(({data:{from:h,type:L}})=>{L==="start"&&h!==p&&_()}),A=t.useCallback(async(h=!0)=>{await c(w,h),Z({type:"start",from:p})},[c,w]),K=t.useRef();return t.useEffect(()=>{!K.current&&s&&w&&(K.current=!0,A())},[A,s,w]),t.useEffect(()=>()=>{M.stop()},[M]),{id:p,canvasId:v,code:w,setCode:N,error:k||q,schedulerError:k,scheduler:M,evalError:q,evaluate:c,activateCode:A,activeCode:C,isDirty:x,pattern:z,started:S,start:g,stop:_,pause:I,togglePlay:async()=>{S?M.pause():await A()}}}function fe(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}function U({type:e}){return u.default.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",className:"sc-h-5 sc-w-5",viewBox:"0 0 20 20",fill:"currentColor"},{refresh:u.default.createElement("path",{fillRule:"evenodd",d:"M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z",clipRule:"evenodd"}),play:u.default.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z",clipRule:"evenodd"}),pause:u.default.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z",clipRule:"evenodd"})}[e])}const ge="_container_3i85k_1",me="_header_3i85k_5",he="_buttons_3i85k_9",pe="_button_3i85k_9",ve="_buttonDisabled_3i85k_17",be="_error_3i85k_21",Ee="_body_3i85k_25",y={container:ge,header:me,buttons:he,button:pe,buttonDisabled:ve,error:be,body:Ee},we=()=>W.getAudioContext().currentTime;function ye({tune:e,hideOutsideView:a=!1,enableKeyboard:r,withCanvas:s=!1,canvasHeight:n=200}){const{code:l,setCode:d,evaluate:m,activateCode:o,error:f,isDirty:b,activeCode:v,pattern:p,started:k,scheduler:D,togglePlay:q,stop:F,canvasId:w,id:N}=Y({initialCode:e,defaultOutput:W.webaudioOutput,getTime:we,editPattern:(c,g)=>c.withContext(_=>({..._,id:g}))});de({pattern:p,started:s&&k,getTime:()=>D.now(),onDraw:(c,g)=>{const _=document.querySelector("#"+w).getContext("2d");B.pianoroll({ctx:_,time:c,haps:g,autorange:1,fold:1,playhead:1})}});const[C,T]=t.useState(),[z,R]=ae.useInView({threshold:.01}),S=t.useRef(),V=t.useMemo(()=>((R||!a)&&(S.current=!0),R||S.current),[R,a]);Q({view:C,pattern:p,active:k&&!v?.includes("strudel disable-highlighting"),getTime:()=>D.getPhase()}),t.useLayoutEffect(()=>{if(r){const c=async g=>{(g.ctrlKey||g.altKey)&&(g.code==="Enter"?(g.preventDefault(),J(C),await o()):g.code==="Period"&&(F(),g.preventDefault()))};return window.addEventListener("keydown",c,!0),()=>window.removeEventListener("keydown",c,!0)}},[r,p,l,m,F,C]);const[x,M]=t.useState([]);return ke(t.useCallback(c=>{const{data:g}=c.detail;g?.hap?.context?.id===N&&M(I=>I.concat([c.detail]).slice(-10))},[])),u.default.createElement("div",{className:y.container,ref:z},u.default.createElement("div",{className:y.header},u.default.createElement("div",{className:y.buttons},u.default.createElement("button",{className:O(y.button,k?"sc-animate-pulse":""),onClick:()=>q()},u.default.createElement(U,{type:k?"pause":"play"})),u.default.createElement("button",{className:O(b?y.button:y.buttonDisabled),onClick:()=>o()},u.default.createElement(U,{type:"refresh"}))),f&&u.default.createElement("div",{className:y.error},f.message)),u.default.createElement("div",{className:y.body},V&&u.default.createElement(G,{value:l,onChange:d,onViewChanged:T})),s&&u.default.createElement("canvas",{id:w,className:"w-full pointer-events-none",height:n,ref:c=>{c&&c.width!==c.clientWidth&&(c.width=c.clientWidth)}}),!!x.length&&u.default.createElement("div",{className:"sc-bg-gray-800 sc-rounded-md sc-p-2"},x.map(({message:c},g)=>u.default.createElement("div",{key:g},c))))}function ke(e){_e(B.logger.key,e)}function _e(e,a,r=!1){t.useEffect(()=>(document.addEventListener(e,a,r),()=>{document.removeEventListener(e,a,r)}),[a])}const Ce=e=>t.useLayoutEffect(()=>(window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)),[e]);exports.CodeMirror=G;exports.MiniRepl=ye;exports.cx=O;exports.flash=J;exports.useHighlighting=Q;exports.useKeydown=Ce;exports.usePostMessage=X;exports.useStrudel=Y; +"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const t=require("react"),ue=require("@uiw/react-codemirror"),w=require("@codemirror/view"),O=require("@codemirror/state"),de=require("@codemirror/lang-javascript"),i=require("@lezer/highlight"),fe=require("@uiw/codemirror-themes"),Z=require("@strudel.cycles/webaudio"),ge=require("react-hook-inview"),T=require("@strudel.cycles/core"),me=require("@strudel.cycles/transpiler"),ee=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},u=ee(t),he=ee(ue),pe=fe.createTheme({theme:"dark",settings:{background:"#222",foreground:"#75baff",caret:"#ffcc00",selection:"rgba(128, 203, 196, 0.5)",selectionMatch:"#036dd626",lineHighlight:"#00000050",gutterBackground:"transparent",gutterForeground:"#8a919966"},styles:[{tag:i.tags.keyword,color:"#c792ea"},{tag:i.tags.operator,color:"#89ddff"},{tag:i.tags.special(i.tags.variableName),color:"#eeffff"},{tag:i.tags.typeName,color:"#c3e88d"},{tag:i.tags.atom,color:"#f78c6c"},{tag:i.tags.number,color:"#c3e88d"},{tag:i.tags.definition(i.tags.variableName),color:"#82aaff"},{tag:i.tags.string,color:"#c3e88d"},{tag:i.tags.special(i.tags.string),color:"#c3e88d"},{tag:i.tags.comment,color:"#7d8799"},{tag:i.tags.variableName,color:"#c792ea"},{tag:i.tags.tagName,color:"#c3e88d"},{tag:i.tags.bracket,color:"#525154"},{tag:i.tags.meta,color:"#ffcb6b"},{tag:i.tags.attributeName,color:"#c792ea"},{tag:i.tags.propertyName,color:"#c792ea"},{tag:i.tags.className,color:"#decb6b"},{tag:i.tags.invalid,color:"#ffffff"}]});const $=O.StateEffect.define(),ve=O.StateField.define({create(){return w.Decoration.none},update(e,o){try{for(let r of o.effects)if(r.is($))if(r.value){const n=w.Decoration.mark({attributes:{style:"background-color: #FFCA2880"}});e=w.Decoration.set([n.range(0,o.newDoc.length)])}else e=w.Decoration.set([]);return e}catch(r){return console.warn("flash error",r),e}},provide:e=>w.EditorView.decorations.from(e)}),te=e=>{e.dispatch({effects:$.of(!0)}),setTimeout(()=>{e.dispatch({effects:$.of(!1)})},200)},V=O.StateEffect.define(),be=O.StateField.define({create(){return w.Decoration.none},update(e,o){try{for(let r of o.effects)if(r.is(V)){const n=r.value.map(l=>(l.context.locations||[]).map(({start:m,end:d})=>{const a=l.context.color||"#FFCA28";let s=o.newDoc.line(m.line).from+m.column,p=o.newDoc.line(d.line).from+d.column;const E=o.newDoc.length;return s>E||p>E?void 0:w.Decoration.mark({attributes:{style:`outline: 1.5px solid ${a};`}}).range(s,p)})).flat().filter(Boolean)||[];e=w.Decoration.set(n,!0)}return e}catch{return w.Decoration.set([])}},provide:e=>w.EditorView.decorations.from(e)}),Ee=[de.javascript(),pe,be,ve];function re({value:e,onChange:o,onViewChanged:r,onSelectionChange:n,options:l,editorDidMount:m}){const d=t.useCallback(p=>{o?.(p)},[o]),a=t.useCallback(p=>{r?.(p)},[r]),s=t.useCallback(p=>{p.selectionSet&&n&&n?.(p.state.selection)},[n]);return u.default.createElement(u.default.Fragment,null,u.default.createElement(he.default,{value:e,onChange:d,onCreateEditor:a,onUpdate:s,extensions:Ee}))}function J(...e){return e.filter(Boolean).join(" ")}function oe({view:e,pattern:o,active:r,getTime:n}){const l=t.useRef([]),m=t.useRef(0);t.useEffect(()=>{if(e)if(o&&r){m.current=0;let d=requestAnimationFrame(function a(){try{const s=n(),E=[Math.max(m.current??s,s-1/10,-.01),s+1/60];m.current=E[1],l.current=l.current.filter(h=>h.whole.end>s);const c=o.queryArc(...E).filter(h=>h.hasOnset());l.current=l.current.concat(c),e.dispatch({effects:V.of(l.current)})}catch{e.dispatch({effects:V.of([])})}d=requestAnimationFrame(a)});return()=>{cancelAnimationFrame(d)}}else l.current=[],e.dispatch({effects:V.of([])})},[o,r,e])}function ye(e,o=!1){const r=t.useRef(),n=t.useRef(),l=a=>{if(n.current!==void 0){const s=a-n.current;e(a,s)}n.current=a,r.current=requestAnimationFrame(l)},m=()=>{r.current=requestAnimationFrame(l)},d=()=>{r.current&&cancelAnimationFrame(r.current),delete r.current};return t.useEffect(()=>{r.current&&(d(),m())},[e]),t.useEffect(()=>(o&&m(),d),[]),{start:m,stop:d}}function we({pattern:e,started:o,getTime:r,onDraw:n,drawTime:l=[-2,2]}){let[m,d]=l;m=Math.abs(m);let a=t.useRef([]),s=t.useRef(null);t.useEffect(()=>{if(e){const c=r(),h=e.queryArc(Math.max(c,0),c+d+.1);a.current=a.current.filter(b=>b.whole.begin{const c=r()+d;if(s.current===null){s.current=c;return}const h=e.queryArc(Math.max(s.current,c-1/10),c);s.current=c,a.current=(a.current||[]).filter(b=>b.whole.end>=c-m-d).concat(h.filter(b=>b.hasOnset())),n(e,c-d,a.current,l)},[e]));return t.useEffect(()=>{o?p():(a.current=[],E())},[o]),{clear:()=>{a.current=[]}}}function ne(e){return t.useEffect(()=>(window.addEventListener("message",e),()=>window.removeEventListener("message",e)),[e]),t.useCallback(o=>window.postMessage(o,"*"),[])}function ae({defaultOutput:e,interval:o,getTime:r,evalOnMount:n=!1,initialCode:l="",autolink:m=!1,beforeEval:d,afterEval:a,editPattern:s,onEvalError:p,onToggle:E,canvasId:c,drawContext:h,drawTime:b=[-2,2]}){const D=t.useMemo(()=>ke(),[]);c=c||`canvas-${D}`;const[q,R]=t.useState(),[N,L]=t.useState(),[y,x]=t.useState(l),[H,S]=t.useState(),[A,j]=t.useState(),[C,P]=t.useState(!1),B=y!==H,{scheduler:_,evaluate:F,start:f,stop:v,pause:G}=t.useMemo(()=>T.repl({interval:o,defaultOutput:e,onSchedulerError:R,onEvalError:g=>{L(g),p?.(g)},getTime:r,drawContext:h,transpiler:me.transpiler,editPattern:s,beforeEval:({code:g})=>{x(g),d?.()},afterEval:({pattern:g,code:k})=>{S(k),j(g),L(),R(),m&&(window.location.hash="#"+encodeURIComponent(btoa(k))),a?.()},onToggle:g=>{P(g),E?.(g)}}),[e,o,r]),I=ne(({data:{from:g,type:k}})=>{k==="start"&&g!==D&&v()}),Q=t.useCallback(async(g=!0)=>{const k=await F(y,g);return I({type:"start",from:D}),k},[F,y]),z=t.useCallback((g,k,U,W)=>{const{onPaint:le}=g.context||{},ie=typeof h=="function"?h(c):h;le?.(ie,k,U,W)},[h,c]),K=t.useCallback(g=>{if(h&&z){const[k,U]=b,W=g.queryArc(0,U);z(g,-.001,W,b)}},[h,b,z]),X=t.useRef();t.useEffect(()=>{!X.current&&n&&y&&(X.current=!0,F(y,!1).then(g=>K(g)))},[n,y,F,K]),t.useEffect(()=>()=>{_.stop()},[_]);const se=async()=>{C?(_.stop(),K(A)):await Q()},ce=q||N;return we({pattern:A,started:h&&C,getTime:()=>_.now(),drawTime:b,onDraw:z}),{id:D,canvasId:c,code:y,setCode:x,error:ce,schedulerError:q,scheduler:_,evalError:N,evaluate:F,activateCode:Q,activeCode:H,isDirty:B,pattern:A,started:C,start:f,stop:v,pause:G,togglePlay:se}}function ke(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}function Y({type:e}){return u.default.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",className:"sc-h-5 sc-w-5",viewBox:"0 0 20 20",fill:"currentColor"},{refresh:u.default.createElement("path",{fillRule:"evenodd",d:"M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z",clipRule:"evenodd"}),play:u.default.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z",clipRule:"evenodd"}),pause:u.default.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z",clipRule:"evenodd"}),stop:u.default.createElement("path",{fillRule:"evenodd",d:"M2 10a8 8 0 1116 0 8 8 0 01-16 0zm5-2.25A.75.75 0 017.75 7h4.5a.75.75 0 01.75.75v4.5a.75.75 0 01-.75.75h-4.5a.75.75 0 01-.75-.75v-4.5z",clipRule:"evenodd"})}[e])}const _e="_container_3i85k_1",Me="_header_3i85k_5",Ce="_buttons_3i85k_9",Fe="_button_3i85k_9",De="_buttonDisabled_3i85k_17",Re="_error_3i85k_21",qe="_body_3i85k_25",M={container:_e,header:Me,buttons:Ce,button:Fe,buttonDisabled:De,error:Re,body:qe},Se=()=>Z.getAudioContext().currentTime;function Ae({tune:e,hideOutsideView:o=!1,enableKeyboard:r,drawTime:n,punchcard:l,canvasHeight:m=200}){n=n||(l?[0,4]:void 0);const d=!!n,a=t.useCallback(n?f=>document.querySelector("#"+f)?.getContext("2d"):null,[n]),{code:s,setCode:p,evaluate:E,activateCode:c,error:h,isDirty:b,activeCode:D,pattern:q,started:R,scheduler:N,togglePlay:L,stop:y,canvasId:x,id:H}=ae({initialCode:e,defaultOutput:Z.webaudioOutput,editPattern:f=>l?f.punchcard():f,getTime:Se,evalOnMount:d,drawContext:a,drawTime:n}),[S,A]=t.useState(),[j,C]=ge.useInView({threshold:.01}),P=t.useRef(),B=t.useMemo(()=>((C||!o)&&(P.current=!0),C||P.current),[C,o]);oe({view:S,pattern:q,active:R&&!D?.includes("strudel disable-highlighting"),getTime:()=>N.now()}),t.useLayoutEffect(()=>{if(r){const f=async v=>{(v.ctrlKey||v.altKey)&&(v.code==="Enter"?(v.preventDefault(),te(S),await c()):v.code==="Period"&&(y(),v.preventDefault()))};return window.addEventListener("keydown",f,!0),()=>window.removeEventListener("keydown",f,!0)}},[r,q,s,E,y,S]);const[_,F]=t.useState([]);return Ne(t.useCallback(f=>{const{data:v}=f.detail;v?.hap?.context?.id===H&&F(I=>I.concat([f.detail]).slice(-10))},[])),u.default.createElement("div",{className:M.container,ref:j},u.default.createElement("div",{className:M.header},u.default.createElement("div",{className:M.buttons},u.default.createElement("button",{className:J(M.button,R?"sc-animate-pulse":""),onClick:()=>L()},u.default.createElement(Y,{type:R?"stop":"play"})),u.default.createElement("button",{className:J(b?M.button:M.buttonDisabled),onClick:()=>c()},u.default.createElement(Y,{type:"refresh"}))),h&&u.default.createElement("div",{className:M.error},h.message)),u.default.createElement("div",{className:M.body},B&&u.default.createElement(re,{value:s,onChange:p,onViewChanged:A})),n&&u.default.createElement("canvas",{id:x,className:"w-full pointer-events-none",height:m,ref:f=>{f&&f.width!==f.clientWidth&&(f.width=f.clientWidth)}}),!!_.length&&u.default.createElement("div",{className:"sc-bg-gray-800 sc-rounded-md sc-p-2"},_.map(({message:f},v)=>u.default.createElement("div",{key:v},f))))}function Ne(e){Le(T.logger.key,e)}function Le(e,o,r=!1){t.useEffect(()=>(document.addEventListener(e,o,r),()=>{document.removeEventListener(e,o,r)}),[o])}const xe=e=>t.useLayoutEffect(()=>(window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)),[e]);exports.CodeMirror=re;exports.MiniRepl=Ae;exports.cx=J;exports.flash=te;exports.useHighlighting=oe;exports.useKeydown=xe;exports.usePostMessage=ne;exports.useStrudel=ae; diff --git a/packages/react/dist/index.es.js b/packages/react/dist/index.es.js index d0027424..b0152c74 100644 --- a/packages/react/dist/index.es.js +++ b/packages/react/dist/index.es.js @@ -1,15 +1,15 @@ -import l, { useCallback as N, useRef as k, useEffect as _, useMemo as K, useState as w, useLayoutEffect as G } from "react"; -import Z from "@uiw/react-codemirror"; -import { Decoration as y, EditorView as J } from "@codemirror/view"; -import { StateEffect as Q, StateField as X } from "@codemirror/state"; -import { javascript as ee } from "@codemirror/lang-javascript"; -import { tags as s } from "@lezer/highlight"; -import { createTheme as te } from "@uiw/codemirror-themes"; -import { repl as re, logger as ne, pianoroll as oe } from "@strudel.cycles/core"; -import { webaudioOutput as ae, getAudioContext as ce } from "@strudel.cycles/webaudio"; -import { useInView as se } from "react-hook-inview"; -import { transpiler as ie } from "@strudel.cycles/transpiler"; -const le = te({ +import l, { useCallback as y, useRef as N, useEffect as k, useMemo as J, useState as M, useLayoutEffect as te } from "react"; +import le from "@uiw/react-codemirror"; +import { Decoration as A, EditorView as re } from "@codemirror/view"; +import { StateEffect as ne, StateField as oe } from "@codemirror/state"; +import { javascript as ue } from "@codemirror/lang-javascript"; +import { tags as i } from "@lezer/highlight"; +import { createTheme as de } from "@uiw/codemirror-themes"; +import { webaudioOutput as fe, getAudioContext as me } from "@strudel.cycles/webaudio"; +import { useInView as he } from "react-hook-inview"; +import { repl as ge, logger as pe } from "@strudel.cycles/core"; +import { transpiler as ve } from "@strudel.cycles/transpiler"; +const be = de({ theme: "dark", settings: { background: "#222", @@ -22,241 +22,280 @@ const le = te({ gutterForeground: "#8a919966" }, styles: [ - { tag: s.keyword, color: "#c792ea" }, - { tag: s.operator, color: "#89ddff" }, - { tag: s.special(s.variableName), color: "#eeffff" }, - { tag: s.typeName, color: "#c3e88d" }, - { tag: s.atom, color: "#f78c6c" }, - { tag: s.number, color: "#c3e88d" }, - { tag: s.definition(s.variableName), color: "#82aaff" }, - { tag: s.string, color: "#c3e88d" }, - { tag: s.special(s.string), color: "#c3e88d" }, - { tag: s.comment, color: "#7d8799" }, - { tag: s.variableName, color: "#c792ea" }, - { tag: s.tagName, color: "#c3e88d" }, - { tag: s.bracket, color: "#525154" }, - { tag: s.meta, color: "#ffcb6b" }, - { tag: s.attributeName, color: "#c792ea" }, - { tag: s.propertyName, color: "#c792ea" }, - { tag: s.className, color: "#decb6b" }, - { tag: s.invalid, color: "#ffffff" } + { tag: i.keyword, color: "#c792ea" }, + { tag: i.operator, color: "#89ddff" }, + { tag: i.special(i.variableName), color: "#eeffff" }, + { tag: i.typeName, color: "#c3e88d" }, + { tag: i.atom, color: "#f78c6c" }, + { tag: i.number, color: "#c3e88d" }, + { tag: i.definition(i.variableName), color: "#82aaff" }, + { tag: i.string, color: "#c3e88d" }, + { tag: i.special(i.string), color: "#c3e88d" }, + { tag: i.comment, color: "#7d8799" }, + { tag: i.variableName, color: "#c792ea" }, + { tag: i.tagName, color: "#c3e88d" }, + { tag: i.bracket, color: "#525154" }, + { tag: i.meta, color: "#ffcb6b" }, + { tag: i.attributeName, color: "#c792ea" }, + { tag: i.propertyName, color: "#c792ea" }, + { tag: i.className, color: "#decb6b" }, + { tag: i.invalid, color: "#ffffff" } ] }); -const j = Q.define(), ue = X.define({ +const Q = ne.define(), Ee = oe.define({ create() { - return y.none; + return A.none; }, update(e, r) { try { for (let t of r.effects) - if (t.is(j)) + if (t.is(Q)) if (t.value) { - const a = y.mark({ attributes: { style: "background-color: #FFCA2880" } }); - e = y.set([a.range(0, r.newDoc.length)]); + const n = A.mark({ attributes: { style: "background-color: #FFCA2880" } }); + e = A.set([n.range(0, r.newDoc.length)]); } else - e = y.set([]); + e = A.set([]); return e; } catch (t) { return console.warn("flash error", t), e; } }, - provide: (e) => J.decorations.from(e) -}), de = (e) => { - e.dispatch({ effects: j.of(!0) }), setTimeout(() => { - e.dispatch({ effects: j.of(!1) }); + provide: (e) => re.decorations.from(e) +}), ye = (e) => { + e.dispatch({ effects: Q.of(!0) }), setTimeout(() => { + e.dispatch({ effects: Q.of(!1) }); }, 200); -}, z = Q.define(), fe = X.define({ +}, I = ne.define(), we = oe.define({ create() { - return y.none; + return A.none; }, update(e, r) { try { for (let t of r.effects) - if (t.is(z)) { - const a = t.value.map( - (o) => (o.context.locations || []).map(({ start: i, end: u }) => { - const m = o.context.color || "#FFCA28"; - let n = r.newDoc.line(i.line).from + i.column, d = r.newDoc.line(u.line).from + u.column; - const v = r.newDoc.length; - return n > v || d > v ? void 0 : y.mark({ attributes: { style: `outline: 1.5px solid ${m};` } }).range(n, d); + if (t.is(I)) { + const n = t.value.map( + (s) => (s.context.locations || []).map(({ start: m, end: u }) => { + const o = s.context.color || "#FFCA28"; + let c = r.newDoc.line(m.line).from + m.column, g = r.newDoc.line(u.line).from + u.column; + const b = r.newDoc.length; + return c > b || g > b ? void 0 : A.mark({ attributes: { style: `outline: 1.5px solid ${o};` } }).range(c, g); }) ).flat().filter(Boolean) || []; - e = y.set(a, !0); + e = A.set(n, !0); } return e; } catch { - return y.set([]); + return A.set([]); } }, - provide: (e) => J.decorations.from(e) -}), me = [ee(), le, fe, ue]; -function ge({ value: e, onChange: r, onViewChanged: t, onSelectionChange: a, options: o, editorDidMount: i }) { - const u = N( - (d) => { - r?.(d); + provide: (e) => re.decorations.from(e) +}), ke = [ue(), be, we, Ee]; +function Fe({ value: e, onChange: r, onViewChanged: t, onSelectionChange: n, options: s, editorDidMount: m }) { + const u = y( + (g) => { + r?.(g); }, [r] - ), m = N( - (d) => { - t?.(d); + ), o = y( + (g) => { + t?.(g); }, [t] - ), n = N( - (d) => { - d.selectionSet && a && a?.(d.state.selection); + ), c = y( + (g) => { + g.selectionSet && n && n?.(g.state.selection); }, - [a] + [n] ); - return /* @__PURE__ */ l.createElement(l.Fragment, null, /* @__PURE__ */ l.createElement(Z, { + return /* @__PURE__ */ l.createElement(l.Fragment, null, /* @__PURE__ */ l.createElement(le, { value: e, onChange: u, - onCreateEditor: m, - onUpdate: n, - extensions: me + onCreateEditor: o, + onUpdate: c, + extensions: ke })); } -function W(...e) { +function T(...e) { return e.filter(Boolean).join(" "); } -function pe({ view: e, pattern: r, active: t, getTime: a }) { - const o = k([]), i = k(); - _(() => { +function _e({ view: e, pattern: r, active: t, getTime: n }) { + const s = N([]), m = N(0); + k(() => { if (e) if (r && t) { - let u = requestAnimationFrame(function m() { + m.current = 0; + let u = requestAnimationFrame(function o() { try { - const n = a(), v = [Math.max(i.current || n, n - 1 / 10, 0), n + 1 / 60]; - i.current = v[1], o.current = o.current.filter((p) => p.whole.end > n); - const h = r.queryArc(...v).filter((p) => p.hasOnset()); - o.current = o.current.concat(h), e.dispatch({ effects: z.of(o.current) }); + const c = n(), b = [Math.max(m.current ?? c, c - 1 / 10, -0.01), c + 1 / 60]; + m.current = b[1], s.current = s.current.filter((h) => h.whole.end > c); + const a = r.queryArc(...b).filter((h) => h.hasOnset()); + s.current = s.current.concat(a), e.dispatch({ effects: I.of(s.current) }); } catch { - e.dispatch({ effects: z.of([]) }); + e.dispatch({ effects: I.of([]) }); } - u = requestAnimationFrame(m); + u = requestAnimationFrame(o); }); return () => { cancelAnimationFrame(u); }; } else - o.current = [], e.dispatch({ effects: z.of([]) }); + s.current = [], e.dispatch({ effects: I.of([]) }); }, [r, t, e]); } -function he(e, r = !1) { - const t = k(), a = k(), o = (m) => { - if (a.current !== void 0) { - const n = m - a.current; - e(m, n); +function Me(e, r = !1) { + const t = N(), n = N(), s = (o) => { + if (n.current !== void 0) { + const c = o - n.current; + e(o, c); } - a.current = m, t.current = requestAnimationFrame(o); - }, i = () => { - t.current = requestAnimationFrame(o); + n.current = o, t.current = requestAnimationFrame(s); + }, m = () => { + t.current = requestAnimationFrame(s); }, u = () => { t.current && cancelAnimationFrame(t.current), delete t.current; }; - return _(() => { - t.current && (u(), i()); - }, [e]), _(() => (r && i(), u), []), { - start: i, + return k(() => { + t.current && (u(), m()); + }, [e]), k(() => (r && m(), u), []), { + start: m, stop: u }; } -function ve({ pattern: e, started: r, getTime: t, onDraw: a }) { - let o = k([]), i = k(null); - const { start: u, stop: m } = he( - N(() => { - const n = t(); - if (i.current === null) { - i.current = n; +function Ae({ pattern: e, started: r, getTime: t, onDraw: n, drawTime: s = [-2, 2] }) { + let [m, u] = s; + m = Math.abs(m); + let o = N([]), c = N(null); + k(() => { + if (e) { + const a = t(), h = e.queryArc(Math.max(a, 0), a + u + 0.1); + o.current = o.current.filter((v) => v.whole.begin < a), o.current = o.current.concat(h); + } + }, [e]); + const { start: g, stop: b } = Me( + y(() => { + const a = t() + u; + if (c.current === null) { + c.current = a; return; } - const d = e.queryArc(Math.max(i.current, n - 1 / 10), n), v = 4; - i.current = n, o.current = (o.current || []).filter((h) => h.whole.end > n - v).concat(d.filter((h) => h.hasOnset())), a(n, o.current); + const h = e.queryArc(Math.max(c.current, a - 1 / 10), a); + c.current = a, o.current = (o.current || []).filter((v) => v.whole.end >= a - m - u).concat(h.filter((v) => v.hasOnset())), n(e, a - u, o.current, s); }, [e]) ); - _(() => { - r ? u() : (o.current = [], m()); - }, [r]); -} -function be(e) { - return _(() => (window.addEventListener("message", e), () => window.removeEventListener("message", e)), [e]), N((r) => window.postMessage(r, "*"), []); -} -function Ee({ - defaultOutput: e, - interval: r, - getTime: t, - evalOnMount: a = !1, - initialCode: o = "", - autolink: i = !1, - beforeEval: u, - afterEval: m, - editPattern: n, - onEvalError: d, - onToggle: v, - canvasId: h -}) { - const p = K(() => we(), []); - h = h || `canvas-${p}`; - const [F, A] = w(), [P, D] = w(), [b, q] = w(o), [x, V] = w(), [I, R] = w(), [L, B] = w(!1), H = b !== x, { scheduler: M, evaluate: c, start: f, stop: C, pause: O } = K( - () => re({ - interval: r, - defaultOutput: e, - onSchedulerError: A, - onEvalError: (g) => { - D(g), d?.(g); - }, - getTime: t, - transpiler: ie, - beforeEval: ({ code: g }) => { - q(g), u?.(); - }, - editPattern: n ? (g) => n(g, p) : void 0, - afterEval: ({ pattern: g, code: T }) => { - V(T), R(g), D(), A(), i && (window.location.hash = "#" + encodeURIComponent(btoa(T))), m?.(); - }, - onToggle: (g) => { - B(g), v?.(g); - } - }), - [e, r, t] - ), Y = be(({ data: { from: g, type: T } }) => { - T === "start" && g !== p && C(); - }), S = N( - async (g = !0) => { - await c(b, g), Y({ type: "start", from: p }); - }, - [c, b] - ), U = k(); - return _(() => { - !U.current && a && b && (U.current = !0, S()); - }, [S, a, b]), _(() => () => { - M.stop(); - }, [M]), { - id: p, - canvasId: h, - code: b, - setCode: q, - error: F || P, - schedulerError: F, - scheduler: M, - evalError: P, - evaluate: c, - activateCode: S, - activeCode: x, - isDirty: H, - pattern: I, - started: L, - start: f, - stop: C, - pause: O, - togglePlay: async () => { - L ? M.pause() : await S(); + return k(() => { + r ? g() : (o.current = [], b()); + }, [r]), { + clear: () => { + o.current = []; } }; } -function we() { +function Ne(e) { + return k(() => (window.addEventListener("message", e), () => window.removeEventListener("message", e)), [e]), y((r) => window.postMessage(r, "*"), []); +} +function De({ + defaultOutput: e, + interval: r, + getTime: t, + evalOnMount: n = !1, + initialCode: s = "", + autolink: m = !1, + beforeEval: u, + afterEval: o, + editPattern: c, + onEvalError: g, + onToggle: b, + canvasId: a, + drawContext: h, + drawTime: v = [-2, 2] +}) { + const R = J(() => Ce(), []); + a = a || `canvas-${R}`; + const [L, x] = M(), [H, P] = M(), [E, S] = M(s), [V, q] = M(), [z, K] = M(), [D, O] = M(!1), j = E !== V, { scheduler: F, evaluate: C, start: d, stop: p, pause: X } = J( + () => ge({ + interval: r, + defaultOutput: e, + onSchedulerError: x, + onEvalError: (f) => { + P(f), g?.(f); + }, + getTime: t, + drawContext: h, + transpiler: ve, + editPattern: c, + beforeEval: ({ code: f }) => { + S(f), u?.(); + }, + afterEval: ({ pattern: f, code: w }) => { + q(w), K(f), P(), x(), m && (window.location.hash = "#" + encodeURIComponent(btoa(w))), o?.(); + }, + onToggle: (f) => { + O(f), b?.(f); + } + }), + [e, r, t] + ), U = Ne(({ data: { from: f, type: w } }) => { + w === "start" && f !== R && p(); + }), Y = y( + async (f = !0) => { + const w = await C(E, f); + return U({ type: "start", from: R }), w; + }, + [C, E] + ), B = y( + (f, w, $, G) => { + const { onPaint: se } = f.context || {}, ie = typeof h == "function" ? h(a) : h; + se?.(ie, w, $, G); + }, + [h, a] + ), W = y( + (f) => { + if (h && B) { + const [w, $] = v, G = f.queryArc(0, $); + B(f, -1e-3, G, v); + } + }, + [h, v, B] + ), Z = N(); + k(() => { + !Z.current && n && E && (Z.current = !0, C(E, !1).then((f) => W(f))); + }, [n, E, C, W]), k(() => () => { + F.stop(); + }, [F]); + const ce = async () => { + D ? (F.stop(), W(z)) : await Y(); + }, ae = L || H; + return Ae({ + pattern: z, + started: h && D, + getTime: () => F.now(), + drawTime: v, + onDraw: B + }), { + id: R, + canvasId: a, + code: E, + setCode: S, + error: ae, + schedulerError: L, + scheduler: F, + evalError: H, + evaluate: C, + activateCode: Y, + activeCode: V, + isDirty: j, + pattern: z, + started: D, + start: d, + stop: p, + pause: X, + togglePlay: ce + }; +} +function Ce() { return Math.floor((1 + Math.random()) * 65536).toString(16).substring(1); } -function $({ type: e }) { +function ee({ type: e }) { return /* @__PURE__ */ l.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", className: "sc-h-5 sc-w-5", @@ -277,125 +316,127 @@ function $({ type: e }) { fillRule: "evenodd", d: "M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z", clipRule: "evenodd" + }), + stop: /* @__PURE__ */ l.createElement("path", { + fillRule: "evenodd", + d: "M2 10a8 8 0 1116 0 8 8 0 01-16 0zm5-2.25A.75.75 0 017.75 7h4.5a.75.75 0 01.75.75v4.5a.75.75 0 01-.75.75h-4.5a.75.75 0 01-.75-.75v-4.5z", + clipRule: "evenodd" }) }[e]); } -const ye = "_container_3i85k_1", ke = "_header_3i85k_5", _e = "_buttons_3i85k_9", Fe = "_button_3i85k_9", Ce = "_buttonDisabled_3i85k_17", Ne = "_error_3i85k_21", xe = "_body_3i85k_25", E = { - container: ye, - header: ke, - buttons: _e, - button: Fe, - buttonDisabled: Ce, - error: Ne, - body: xe -}, Me = () => ce().currentTime; -function je({ tune: e, hideOutsideView: r = !1, enableKeyboard: t, withCanvas: a = !1, canvasHeight: o = 200 }) { - const { - code: i, - setCode: u, - evaluate: m, - activateCode: n, - error: d, +const Re = "_container_3i85k_1", xe = "_header_3i85k_5", Le = "_buttons_3i85k_9", qe = "_button_3i85k_9", ze = "_buttonDisabled_3i85k_17", He = "_error_3i85k_21", Pe = "_body_3i85k_25", _ = { + container: Re, + header: xe, + buttons: Le, + button: qe, + buttonDisabled: ze, + error: He, + body: Pe +}, Se = () => me().currentTime; +function Ye({ tune: e, hideOutsideView: r = !1, enableKeyboard: t, drawTime: n, punchcard: s, canvasHeight: m = 200 }) { + n = n || (s ? [0, 4] : void 0); + const u = !!n, o = y( + n ? (d) => document.querySelector("#" + d)?.getContext("2d") : null, + [n] + ), { + code: c, + setCode: g, + evaluate: b, + activateCode: a, + error: h, isDirty: v, - activeCode: h, - pattern: p, - started: F, - scheduler: A, + activeCode: R, + pattern: L, + started: x, + scheduler: H, togglePlay: P, - stop: D, - canvasId: b, - id: q - } = Ee({ + stop: E, + canvasId: S, + id: V + } = De({ initialCode: e, - defaultOutput: ae, - getTime: Me, - editPattern: (c, f) => c.withContext((C) => ({ ...C, id: f })) - }); - ve({ - pattern: p, - started: a && F, - getTime: () => A.now(), - onDraw: (c, f) => { - const C = document.querySelector("#" + b).getContext("2d"); - oe({ ctx: C, time: c, haps: f, autorange: 1, fold: 1, playhead: 1 }); - } - }); - const [x, V] = w(), [I, R] = se({ + defaultOutput: fe, + editPattern: (d) => s ? d.punchcard() : d, + getTime: Se, + evalOnMount: u, + drawContext: o, + drawTime: n + }), [q, z] = M(), [K, D] = he({ threshold: 0.01 - }), L = k(), B = K(() => ((R || !r) && (L.current = !0), R || L.current), [R, r]); - pe({ - view: x, - pattern: p, - active: F && !h?.includes("strudel disable-highlighting"), - getTime: () => A.getPhase() - }), G(() => { + }), O = N(), j = J(() => ((D || !r) && (O.current = !0), D || O.current), [D, r]); + _e({ + view: q, + pattern: L, + active: x && !R?.includes("strudel disable-highlighting"), + getTime: () => H.now() + }), te(() => { if (t) { - const c = async (f) => { - (f.ctrlKey || f.altKey) && (f.code === "Enter" ? (f.preventDefault(), de(x), await n()) : f.code === "Period" && (D(), f.preventDefault())); + const d = async (p) => { + (p.ctrlKey || p.altKey) && (p.code === "Enter" ? (p.preventDefault(), ye(q), await a()) : p.code === "Period" && (E(), p.preventDefault())); }; - return window.addEventListener("keydown", c, !0), () => window.removeEventListener("keydown", c, !0); + return window.addEventListener("keydown", d, !0), () => window.removeEventListener("keydown", d, !0); } - }, [t, p, i, m, D, x]); - const [H, M] = w([]); - return Ae( - N((c) => { - const { data: f } = c.detail; - f?.hap?.context?.id === q && M((O) => O.concat([c.detail]).slice(-10)); + }, [t, L, c, b, E, q]); + const [F, C] = M([]); + return Ve( + y((d) => { + const { data: p } = d.detail; + p?.hap?.context?.id === V && C((U) => U.concat([d.detail]).slice(-10)); }, []) ), /* @__PURE__ */ l.createElement("div", { - className: E.container, - ref: I + className: _.container, + ref: K }, /* @__PURE__ */ l.createElement("div", { - className: E.header + className: _.header }, /* @__PURE__ */ l.createElement("div", { - className: E.buttons + className: _.buttons }, /* @__PURE__ */ l.createElement("button", { - className: W(E.button, F ? "sc-animate-pulse" : ""), + className: T(_.button, x ? "sc-animate-pulse" : ""), onClick: () => P() - }, /* @__PURE__ */ l.createElement($, { - type: F ? "pause" : "play" + }, /* @__PURE__ */ l.createElement(ee, { + type: x ? "stop" : "play" })), /* @__PURE__ */ l.createElement("button", { - className: W(v ? E.button : E.buttonDisabled), - onClick: () => n() - }, /* @__PURE__ */ l.createElement($, { + className: T(v ? _.button : _.buttonDisabled), + onClick: () => a() + }, /* @__PURE__ */ l.createElement(ee, { type: "refresh" - }))), d && /* @__PURE__ */ l.createElement("div", { - className: E.error - }, d.message)), /* @__PURE__ */ l.createElement("div", { - className: E.body - }, B && /* @__PURE__ */ l.createElement(ge, { - value: i, - onChange: u, - onViewChanged: V - })), a && /* @__PURE__ */ l.createElement("canvas", { - id: b, + }))), h && /* @__PURE__ */ l.createElement("div", { + className: _.error + }, h.message)), /* @__PURE__ */ l.createElement("div", { + className: _.body + }, j && /* @__PURE__ */ l.createElement(Fe, { + value: c, + onChange: g, + onViewChanged: z + })), n && /* @__PURE__ */ l.createElement("canvas", { + id: S, className: "w-full pointer-events-none", - height: o, - ref: (c) => { - c && c.width !== c.clientWidth && (c.width = c.clientWidth); + height: m, + ref: (d) => { + d && d.width !== d.clientWidth && (d.width = d.clientWidth); } - }), !!H.length && /* @__PURE__ */ l.createElement("div", { + }), !!F.length && /* @__PURE__ */ l.createElement("div", { className: "sc-bg-gray-800 sc-rounded-md sc-p-2" - }, H.map(({ message: c }, f) => /* @__PURE__ */ l.createElement("div", { - key: f - }, c)))); + }, F.map(({ message: d }, p) => /* @__PURE__ */ l.createElement("div", { + key: p + }, d)))); } -function Ae(e) { - De(ne.key, e); +function Ve(e) { + Oe(pe.key, e); } -function De(e, r, t = !1) { - _(() => (document.addEventListener(e, r, t), () => { +function Oe(e, r, t = !1) { + k(() => (document.addEventListener(e, r, t), () => { document.removeEventListener(e, r, t); }), [r]); } -const Ue = (e) => G(() => (window.addEventListener("keydown", e, !0), () => window.removeEventListener("keydown", e, !0)), [e]); +const Ze = (e) => te(() => (window.addEventListener("keydown", e, !0), () => window.removeEventListener("keydown", e, !0)), [e]); export { - ge as CodeMirror, - je as MiniRepl, - W as cx, - de as flash, - pe as useHighlighting, - Ue as useKeydown, - be as usePostMessage, - Ee as useStrudel + Fe as CodeMirror, + Ye as MiniRepl, + T as cx, + ye as flash, + _e as useHighlighting, + Ze as useKeydown, + Ne as usePostMessage, + De as useStrudel }; diff --git a/packages/react/src/components/Icon.tsx b/packages/react/src/components/Icon.tsx index 0ae722a3..28a8a374 100644 --- a/packages/react/src/components/Icon.tsx +++ b/packages/react/src/components/Icon.tsx @@ -26,6 +26,13 @@ export function Icon({ type }) { clipRule="evenodd" /> ), + stop: ( + + ), }[type] } diff --git a/packages/react/src/components/MiniRepl.jsx b/packages/react/src/components/MiniRepl.jsx index 70ebe22c..6b647dfb 100644 --- a/packages/react/src/components/MiniRepl.jsx +++ b/packages/react/src/components/MiniRepl.jsx @@ -1,11 +1,9 @@ -import { pianoroll } from '@strudel.cycles/core'; import { getAudioContext, webaudioOutput } from '@strudel.cycles/webaudio'; import React, { useLayoutEffect, useMemo, useRef, useState, useCallback, useEffect } from 'react'; import { useInView } from 'react-hook-inview'; import 'tailwindcss/tailwind.css'; import cx from '../cx'; import useHighlighting from '../hooks/useHighlighting.mjs'; -import usePatternFrame from '../hooks/usePatternFrame.mjs'; import useStrudel from '../hooks/useStrudel.mjs'; import CodeMirror6, { flash } from './CodeMirror6'; import { Icon } from './Icon'; @@ -15,7 +13,13 @@ import { logger } from '@strudel.cycles/core'; const getTime = () => getAudioContext().currentTime; -export function MiniRepl({ tune, hideOutsideView = false, enableKeyboard, withCanvas = false, canvasHeight = 200 }) { +export function MiniRepl({ tune, hideOutsideView = false, enableKeyboard, drawTime, punchcard, canvasHeight = 200 }) { + drawTime = drawTime || (punchcard ? [0, 4] : undefined); + const evalOnMount = !!drawTime; + const drawContext = useCallback( + !!drawTime ? (canvasId) => document.querySelector('#' + canvasId)?.getContext('2d') : null, + [drawTime], + ); const { code, setCode, @@ -34,25 +38,13 @@ export function MiniRepl({ tune, hideOutsideView = false, enableKeyboard, withCa } = useStrudel({ initialCode: tune, defaultOutput: webaudioOutput, + editPattern: (pat) => (punchcard ? pat.punchcard() : pat), getTime, - editPattern: (pat, id) => { - return pat.withContext((ctx) => ({ ...ctx, id })); - }, + evalOnMount, + drawContext, + drawTime, }); - usePatternFrame({ - pattern, - started: withCanvas && started, - getTime: () => scheduler.now(), - onDraw: (time, haps) => { - const ctx = document.querySelector('#' + canvasId).getContext('2d'); - pianoroll({ ctx, time, haps, autorange: 1, fold: 1, playhead: 1 }); - }, - }); - - /* useEffect(() => { - init && activateCode(); - }, [init, activateCode]); */ const [view, setView] = useState(); const [ref, isVisible] = useInView({ threshold: 0.01, @@ -68,7 +60,7 @@ export function MiniRepl({ tune, hideOutsideView = false, enableKeyboard, withCa view, pattern, active: started && !activeCode?.includes('strudel disable-highlighting'), - getTime: () => scheduler.getPhase(), + getTime: () => scheduler.now(), }); // set active pattern on ctrl+enter @@ -110,7 +102,7 @@ export function MiniRepl({ tune, hideOutsideView = false, enableKeyboard, withCa