diff --git a/packages/react/dist/index.cjs.js b/packages/react/dist/index.cjs.js index 55eeacd9..3f7bda78 100644 --- a/packages/react/dist/index.cjs.js +++ b/packages/react/dist/index.cjs.js @@ -1,3 +1,3 @@ -"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var a=require("react"),oe=require("react-codemirror6"),y=require("@codemirror/view"),F=require("@codemirror/state"),ae=require("@codemirror/lang-javascript"),c=require("@codemirror/highlight"),re=require("react-hook-inview"),ne=require("@strudel.cycles/eval"),se=require("@strudel.cycles/core/util.mjs"),p=require("@strudel.cycles/tone"),j=require("@strudel.cycles/core"),v=require("@strudel.cycles/midi");function ce(e){return e&&typeof e=="object"&&"default"in e?e:{default:e}}var f=ce(a);const le="#abb2bf",ie="#7d8799",ue="#ffffff",de="#21252b",W="rgba(0, 0, 0, 0.5)",fe="transparent",P="#353a42",ge="rgba(128, 203, 196, 0.5)",O="#ffcc00",me=y.EditorView.theme({"&":{color:"#ffffff",backgroundColor:fe,fontSize:"15px","z-index":11},".cm-content":{caretColor:O,lineHeight:"22px"},".cm-line":{background:"#2C323699"},"&.cm-focused .cm-cursor":{backgroundColor:O,width:"3px"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:ge},".cm-panels":{backgroundColor:de,color:"#ffffff"},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:W},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847",outline:"1px solid #515a6b"},".cm-gutters":{background:"transparent",color:"#676e95",border:"none"},".cm-activeLineGutter":{backgroundColor:W},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:P},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:P,borderBottomColor:P},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:W,color:le}}},{dark:!0}),be=c.HighlightStyle.define([{tag:c.tags.keyword,color:"#c792ea"},{tag:c.tags.operator,color:"#89ddff"},{tag:c.tags.special(c.tags.variableName),color:"#eeffff"},{tag:c.tags.typeName,color:"#f07178"},{tag:c.tags.atom,color:"#f78c6c"},{tag:c.tags.number,color:"#ff5370"},{tag:c.tags.definition(c.tags.variableName),color:"#82aaff"},{tag:c.tags.string,color:"#c3e88d"},{tag:c.tags.special(c.tags.string),color:"#f07178"},{tag:c.tags.comment,color:ie},{tag:c.tags.variableName,color:"#f07178"},{tag:c.tags.tagName,color:"#ff5370"},{tag:c.tags.bracket,color:"#a2a1a4"},{tag:c.tags.meta,color:"#ffcb6b"},{tag:c.tags.attributeName,color:"#c792ea"},{tag:c.tags.propertyName,color:"#c792ea"},{tag:c.tags.className,color:"#decb6b"},{tag:c.tags.invalid,color:ue}]),pe=[me,be],V=F.StateEffect.define(),he=F.StateField.define({create(){return y.Decoration.none},update(e,o){try{for(let r of o.effects)if(r.is(V))if(r.value){const i=y.Decoration.mark({attributes:{style:"background-color: #FFCA2880"}});e=y.Decoration.set([i.range(0,o.newDoc.length)])}else e=y.Decoration.set([]);return e}catch(r){return console.warn("flash error",r),e}},provide:e=>y.EditorView.decorations.from(e)}),ve=e=>{e.dispatch({effects:V.of(!0)}),setTimeout(()=>{e.dispatch({effects:V.of(!1)})},200)},B=F.StateEffect.define(),ye=F.StateField.define({create(){return y.Decoration.none},update(e,o){try{for(let r of o.effects)r.is(B)&&(e=y.Decoration.set(r.value.flatMap(i=>(i.context.locations||[]).map(({start:g,end:l})=>{const u=i.context.color||"#FFCA28";let m=o.newDoc.line(g.line).from+g.column,s=o.newDoc.line(l.line).from+l.column;const n=o.newDoc.length;return m>n||s>n?void 0:y.Decoration.mark({attributes:{style:`outline: 1px solid ${u}`}}).range(m,s)})).filter(Boolean),!0));return e}catch{return e}},provide:e=>y.EditorView.decorations.from(e)});function Q({value:e,onChange:o,onViewChanged:r,onCursor:i,options:g,editorDidMount:l}){return f.default.createElement(f.default.Fragment,null,f.default.createElement(oe.CodeMirror,{onViewChange:r,style:{display:"flex",flexDirection:"column",flex:"1 0 auto"},value:e,onChange:o,extensions:[ae.javascript(),pe,ye,he]}))}function U(e){const{onEvent:o,onQuery:r,onSchedule:i,ready:g=!0,onDraw:l}=e,[u,m]=a.useState(!1),s=1,n=()=>Math.floor(p.Tone.getTransport().seconds/s),C=(b=n())=>{const k=new j.TimeSpan(b,b+1),D=r?.(new j.State(k))||[];i?.(D,b);const H=k.begin.valueOf();p.Tone.getTransport().cancel(H);const N=(b+1)*s-.5,R=Math.max(p.Tone.getTransport().seconds,N)+.1;p.Tone.getTransport().schedule(()=>{C(b+1)},R),D?.filter(h=>h.part.begin.equals(h.whole?.begin)).forEach(h=>{p.Tone.getTransport().schedule(M=>{o(M,h,p.Tone.getContext().currentTime),p.Tone.Draw.schedule(()=>{l?.(M,h)},M)},h.part.begin.valueOf())})};a.useEffect(()=>{g&&C()},[o,i,r,l,g]);const S=async()=>{m(!0),await p.Tone.start(),p.Tone.getTransport().start("+0.1")},w=()=>{p.Tone.getTransport().pause(),m(!1)};return{start:S,stop:w,onEvent:o,started:u,setStarted:m,toggle:()=>u?w():S(),query:C,activeCycle:n}}function G(e){return a.useEffect(()=>(window.addEventListener("message",e),()=>window.removeEventListener("message",e)),[e]),a.useCallback(o=>window.postMessage(o,"*"),[])}let Ce=()=>Math.floor((1+Math.random())*65536).toString(16).substring(1);const we=e=>encodeURIComponent(btoa(e));function J({tune:e,defaultSynth:o,autolink:r=!0,onEvent:i,onDraw:g}){const l=a.useMemo(()=>Ce(),[]),[u,m]=a.useState(e),[s,n]=a.useState(),[C,S]=a.useState(""),[w,T]=a.useState(),[b,k]=a.useState(!1),[D,H]=a.useState(""),[N,R]=a.useState(),h=a.useMemo(()=>u!==s||w,[u,s,w]),M=a.useCallback(d=>S(t=>t+`${t?` +"use strict";Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});var o=require("react"),ae=require("react-codemirror6"),C=require("@codemirror/view"),W=require("@codemirror/state"),re=require("@codemirror/lang-javascript"),s=require("@codemirror/highlight"),ne=require("react-hook-inview"),se=require("@strudel.cycles/eval"),ce=require("@strudel.cycles/core/util.mjs"),v=require("@strudel.cycles/tone"),O=require("@strudel.cycles/core"),w=require("@strudel.cycles/midi");function le(e){return e&&typeof e=="object"&&"default"in e?e:{default:e}}var g=le(o);const ie="#abb2bf",ue="#7d8799",de="#ffffff",fe="#21252b",V="rgba(0, 0, 0, 0.5)",ge="transparent",A="#353a42",me="rgba(128, 203, 196, 0.5)",I="#ffcc00",be=C.EditorView.theme({"&":{color:"#ffffff",backgroundColor:ge,fontSize:"15px","z-index":11},".cm-content":{caretColor:I,lineHeight:"22px"},".cm-line":{background:"#2C323699"},"&.cm-focused .cm-cursor":{backgroundColor:I,width:"3px"},"&.cm-focused .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:me},".cm-panels":{backgroundColor:fe,color:"#ffffff"},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:V},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847",outline:"1px solid #515a6b"},".cm-gutters":{background:"transparent",color:"#676e95",border:"none"},".cm-activeLineGutter":{backgroundColor:V},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:A},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:A,borderBottomColor:A},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:V,color:ie}}},{dark:!0}),pe=s.HighlightStyle.define([{tag:s.tags.keyword,color:"#c792ea"},{tag:s.tags.operator,color:"#89ddff"},{tag:s.tags.special(s.tags.variableName),color:"#eeffff"},{tag:s.tags.typeName,color:"#f07178"},{tag:s.tags.atom,color:"#f78c6c"},{tag:s.tags.number,color:"#ff5370"},{tag:s.tags.definition(s.tags.variableName),color:"#82aaff"},{tag:s.tags.string,color:"#c3e88d"},{tag:s.tags.special(s.tags.string),color:"#f07178"},{tag:s.tags.comment,color:ue},{tag:s.tags.variableName,color:"#f07178"},{tag:s.tags.tagName,color:"#ff5370"},{tag:s.tags.bracket,color:"#a2a1a4"},{tag:s.tags.meta,color:"#ffcb6b"},{tag:s.tags.attributeName,color:"#c792ea"},{tag:s.tags.propertyName,color:"#c792ea"},{tag:s.tags.className,color:"#decb6b"},{tag:s.tags.invalid,color:de}]),he=[be,pe],z=W.StateEffect.define(),ve=W.StateField.define({create(){return C.Decoration.none},update(e,a){try{for(let r of a.effects)if(r.is(z))if(r.value){const u=C.Decoration.mark({attributes:{style:"background-color: #FFCA2880"}});e=C.Decoration.set([u.range(0,a.newDoc.length)])}else e=C.Decoration.set([]);return e}catch(r){return console.warn("flash error",r),e}},provide:e=>C.EditorView.decorations.from(e)}),Q=e=>{e.dispatch({effects:z.of(!0)}),setTimeout(()=>{e.dispatch({effects:z.of(!1)})},200)},L=W.StateEffect.define(),ye=W.StateField.define({create(){return C.Decoration.none},update(e,a){try{for(let r of a.effects)r.is(L)&&(e=C.Decoration.set(r.value.flatMap(u=>(u.context.locations||[]).map(({start:d,end:c})=>{const i=u.context.color||"#FFCA28";let m=a.newDoc.line(d.line).from+d.column,l=a.newDoc.line(c.line).from+c.column;const n=a.newDoc.length;return m>n||l>n?void 0:C.Decoration.mark({attributes:{style:`outline: 1px solid ${i}`}}).range(m,l)})).filter(Boolean),!0));return e}catch{return e}},provide:e=>C.EditorView.decorations.from(e)});function U({value:e,onChange:a,onViewChanged:r,onCursor:u,options:d,editorDidMount:c}){return g.default.createElement(g.default.Fragment,null,g.default.createElement(ae.CodeMirror,{onViewChange:r,style:{display:"flex",flexDirection:"column",flex:"1 0 auto"},value:e,onChange:a,extensions:[re.javascript(),he,ye,ve]}))}function G(e){const{onEvent:a,onQuery:r,onSchedule:u,ready:d=!0,onDraw:c}=e,[i,m]=o.useState(!1),l=1,n=()=>Math.floor(v.Tone.getTransport().seconds/l),E=(b=n())=>{const D=new O.TimeSpan(b,b+1),q=r?.(new O.State(D))||[];u?.(q,b);const P=D.begin.valueOf();v.Tone.getTransport().cancel(P);const y=(b+1)*l-.5,R=Math.max(v.Tone.getTransport().seconds,y)+.1;v.Tone.getTransport().schedule(()=>{E(b+1)},R),q?.filter(p=>p.part.begin.equals(p.whole?.begin)).forEach(p=>{v.Tone.getTransport().schedule(h=>{a(h,p,v.Tone.getContext().currentTime),v.Tone.Draw.schedule(()=>{c?.(h,p)},h)},p.part.begin.valueOf())})};o.useEffect(()=>{d&&E()},[a,u,r,c,d]);const T=async()=>{m(!0),await v.Tone.start(),v.Tone.getTransport().start("+0.1")},x=()=>{v.Tone.getTransport().pause(),m(!1)};return{start:T,stop:x,onEvent:a,started:i,setStarted:m,toggle:()=>i?x():T(),query:E,activeCycle:n}}function J(e){return o.useEffect(()=>(window.addEventListener("message",e),()=>window.removeEventListener("message",e)),[e]),o.useCallback(a=>window.postMessage(a,"*"),[])}let we=()=>Math.floor((1+Math.random())*65536).toString(16).substring(1);const Ce=e=>encodeURIComponent(btoa(e));function X({tune:e,defaultSynth:a,autolink:r=!0,onEvent:u,onDraw:d}){const c=o.useMemo(()=>we(),[]),[i,m]=o.useState(e),[l,n]=o.useState(),[E,T]=o.useState(""),[x,_]=o.useState(),[b,D]=o.useState(!1),[q,P]=o.useState(""),[y,R]=o.useState(),p=o.useMemo(()=>i!==l||x,[i,l,x]),h=o.useCallback(f=>T(t=>t+`${t?` -`:""}${d}`),[]),X=a.useMemo(()=>{if(s&&!s.includes("strudel disable-highlighting"))return(d,t)=>g?.(d,t,s)},[s,g]),x=U({onDraw:X,onEvent:a.useCallback((d,t,Z)=>{try{i?.(t),t.context.logs?.length&&t.context.logs.forEach(M);const{onTrigger:_,velocity:ee}=t.context;if(_)_(d,t,Z,1);else if(o){const te=se.getPlayableNoteValue(t);o.triggerAttackRelease(te,t.duration.valueOf(),d,ee)}else throw new Error("no defaultSynth passed to useRepl.")}catch(_){console.warn(_),_.message="unplayable event: "+_?.message,M(_.message)}},[i,M,o]),onQuery:a.useCallback(d=>{try{return N?.query(d)||[]}catch(t){return console.warn(t),t.message="query error: "+t.message,T(t),[]}},[N]),onSchedule:a.useCallback((d,t)=>Y(d,t),[]),ready:!!N&&!!s}),L=G(({data:{from:d,type:t}})=>{t==="start"&&d!==l&&(x.setStarted(!1),n(void 0))}),z=a.useCallback(async(d=u)=>{if(s&&!h){T(void 0),x.start();return}try{k(!0);const t=await ne.evaluate(d);x.start(),L({type:"start",from:l}),R(()=>t.pattern),r&&(window.location.hash="#"+encodeURIComponent(btoa(u))),H(we(u)),T(void 0),n(d),k(!1)}catch(t){t.message="evaluation error: "+t.message,console.warn(t),T(t)}},[s,h,u,x,r,l,L]),Y=(d,t)=>{d.length};return{pending:b,code:u,setCode:m,pattern:N,error:w,cycle:x,setPattern:R,dirty:h,log:C,togglePlay:()=>{x.started?x.stop():z()},setActiveCode:n,activateCode:z,activeCode:s,pushLog:M,hash:D}}function A(...e){return e.filter(Boolean).join(" ")}let q=[],I;function K({view:e,pattern:o,active:r}){a.useEffect(()=>{if(e)if(o&&r){let g=function(){try{const l=p.Tone.getTransport().seconds,m=[Math.max(I||l,l-1/10),l+1/60];I=l+1/60,q=q.filter(n=>n.whole.end>l);const s=o.queryArc(...m).filter(n=>n.hasOnset());q=q.concat(s),e.dispatch({effects:B.of(q)})}catch{e.dispatch({effects:B.of([])})}i=requestAnimationFrame(g)},i=requestAnimationFrame(g);return()=>{cancelAnimationFrame(i)}}else q=[],e.dispatch({effects:B.of([])})},[o,r,e])}const ke="_container_10e1g_1",Me="_header_10e1g_5",Ee="_buttons_10e1g_9",Te="_button_10e1g_9",xe="_buttonDisabled_10e1g_17",_e="_error_10e1g_21",Se="_body_10e1g_25";var E={container:ke,header:Me,buttons:Ee,button:Te,buttonDisabled:xe,error:_e,body:Se};function $({type:e}){return f.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:f.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:f.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:f.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])}function De({tune:e,defaultSynth:o,hideOutsideView:r=!1}){const{code:i,setCode:g,pattern:l,activateCode:u,error:m,cycle:s,dirty:n,togglePlay:C}=J({tune:e,defaultSynth:o,autolink:!1}),[S,w]=a.useState(),[T,b]=re.useInView({threshold:.01}),k=a.useRef(),D=a.useMemo(()=>((b||!r)&&(k.current=!0),b||k.current),[b,r]);return K({view:S,pattern:l,active:s.started}),f.default.createElement("div",{className:E.container,ref:T},f.default.createElement("div",{className:E.header},f.default.createElement("div",{className:E.buttons},f.default.createElement("button",{className:A(E.button,s.started?"sc-animate-pulse":""),onClick:()=>C()},f.default.createElement($,{type:s.started?"pause":"play"})),f.default.createElement("button",{className:A(n?E.button:E.buttonDisabled),onClick:()=>u()},f.default.createElement($,{type:"refresh"}))),m&&f.default.createElement("div",{className:E.error},m.message)),f.default.createElement("div",{className:E.body},D&&f.default.createElement(Q,{value:i,onChange:g,onViewChanged:w})))}function Ne(e){const{ready:o,connected:r,disconnected:i}=e,[g,l]=a.useState(!0),[u,m]=a.useState(v.WebMidi?.outputs||[]);return a.useEffect(()=>{v.enableWebMidi().then(()=>{v.WebMidi.addListener("connected",n=>{m([...v.WebMidi.outputs]),r?.(v.WebMidi,n)}),v.WebMidi.addListener("disconnected",n=>{m([...v.WebMidi.outputs]),i?.(v.WebMidi,n)}),o?.(v.WebMidi),l(!1)}).catch(n=>{if(n){console.error(n),console.warn("Web Midi could not be enabled..");return}})},[o,r,i,u]),{loading:g,outputs:u,outputByName:n=>v.WebMidi.getOutputByName(n)}}exports.CodeMirror=Q;exports.MiniRepl=De;exports.cx=A;exports.flash=ve;exports.useCycle=U;exports.useHighlighting=K;exports.usePostMessage=G;exports.useRepl=J;exports.useWebMidi=Ne; +`:""}${f}`),[]),H=o.useMemo(()=>{if(l&&!l.includes("strudel disable-highlighting"))return(f,t)=>d?.(f,t,l)},[l,d]),k=G({onDraw:H,onEvent:o.useCallback((f,t,ee)=>{try{u?.(t),t.context.logs?.length&&t.context.logs.forEach(h);const{onTrigger:N,velocity:te}=t.context;if(N)N(f,t,ee,1);else if(a){const oe=ce.getPlayableNoteValue(t);a.triggerAttackRelease(oe,t.duration.valueOf(),f,te)}else throw new Error("no defaultSynth passed to useRepl.")}catch(N){console.warn(N),N.message="unplayable event: "+N?.message,h(N.message)}},[u,h,a]),onQuery:o.useCallback(f=>{try{return y?.query(f)||[]}catch(t){return console.warn(t),t.message="query error: "+t.message,_(t),[]}},[y]),onSchedule:o.useCallback((f,t)=>Z(f,t),[]),ready:!!y&&!!l}),F=J(({data:{from:f,type:t}})=>{t==="start"&&f!==c&&(k.setStarted(!1),n(void 0))}),M=o.useCallback(async(f=i)=>{if(l&&!p){_(void 0),k.start();return}try{D(!0);const t=await se.evaluate(f);k.start(),F({type:"start",from:c}),R(()=>t.pattern),r&&(window.location.hash="#"+encodeURIComponent(btoa(i))),P(Ce(i)),_(void 0),n(f),D(!1)}catch(t){t.message="evaluation error: "+t.message,console.warn(t),_(t)}},[l,p,i,k,r,c,F]),Z=(f,t)=>{f.length};return{pending:b,code:i,setCode:m,pattern:y,error:x,cycle:k,setPattern:R,dirty:p,log:E,togglePlay:()=>{k.started?k.stop():M()},setActiveCode:n,activateCode:M,activeCode:l,pushLog:h,hash:q}}function j(...e){return e.filter(Boolean).join(" ")}let B=[],$;function Y({view:e,pattern:a,active:r}){o.useEffect(()=>{if(e)if(a&&r){let d=function(){try{const c=v.Tone.getTransport().seconds,m=[Math.max($||c,c-1/10),c+1/60];$=c+1/60,B=B.filter(n=>n.whole.end>c);const l=a.queryArc(...m).filter(n=>n.hasOnset());B=B.concat(l),e.dispatch({effects:L.of(B)})}catch{e.dispatch({effects:L.of([])})}u=requestAnimationFrame(d)},u=requestAnimationFrame(d);return()=>{cancelAnimationFrame(u)}}else B=[],e.dispatch({effects:L.of([])})},[a,r,e])}const ke="_container_10e1g_1",Me="_header_10e1g_5",Ee="_buttons_10e1g_9",Te="_button_10e1g_9",xe="_buttonDisabled_10e1g_17",_e="_error_10e1g_21",Se="_body_10e1g_25";var S={container:ke,header:Me,buttons:Ee,button:Te,buttonDisabled:xe,error:_e,body:Se};function K({type:e}){return g.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:g.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:g.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:g.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])}function De({tune:e,defaultSynth:a,hideOutsideView:r=!1,theme:u,init:d,onEvent:c,enableKeyboard:i}){const{code:m,setCode:l,pattern:n,activeCode:E,activateCode:T,evaluateOnly:x,error:_,cycle:b,dirty:D,togglePlay:q,stop:P}=X({tune:e,defaultSynth:a,autolink:!1,onEvent:c});o.useEffect(()=>{d&&x()},[e,d]);const[y,R]=o.useState(),[p,h]=ne.useInView({threshold:.01}),H=o.useRef(),k=o.useMemo(()=>((h||!r)&&(H.current=!0),h||H.current),[h,r]);return Y({view:y,pattern:n,active:b.started&&!E?.includes("strudel disable-highlighting")}),o.useLayoutEffect(()=>{if(i){const F=async M=>{(M.ctrlKey||M.altKey)&&(M.code==="Enter"?(M.preventDefault(),Q(y),await T()):M.code==="Period"&&(b.stop(),M.preventDefault()))};return window.addEventListener("keydown",F,!0),()=>window.removeEventListener("keydown",F,!0)}},[i,n,m,T,b,y]),g.default.createElement("div",{className:S.container,ref:p},g.default.createElement("div",{className:S.header},g.default.createElement("div",{className:S.buttons},g.default.createElement("button",{className:j(S.button,b.started?"sc-animate-pulse":""),onClick:()=>q()},g.default.createElement(K,{type:b.started?"pause":"play"})),g.default.createElement("button",{className:j(D?S.button:S.buttonDisabled),onClick:()=>T()},g.default.createElement(K,{type:"refresh"}))),_&&g.default.createElement("div",{className:S.error},_.message)),g.default.createElement("div",{className:S.body},k&&g.default.createElement(U,{value:m,onChange:l,onViewChanged:R})))}function Ne(e){const{ready:a,connected:r,disconnected:u}=e,[d,c]=o.useState(!0),[i,m]=o.useState(w.WebMidi?.outputs||[]);return o.useEffect(()=>{w.enableWebMidi().then(()=>{w.WebMidi.addListener("connected",n=>{m([...w.WebMidi.outputs]),r?.(w.WebMidi,n)}),w.WebMidi.addListener("disconnected",n=>{m([...w.WebMidi.outputs]),u?.(w.WebMidi,n)}),a?.(w.WebMidi),c(!1)}).catch(n=>{if(n){console.error(n),console.warn("Web Midi could not be enabled..");return}})},[a,r,u,i]),{loading:d,outputs:i,outputByName:n=>w.WebMidi.getOutputByName(n)}}exports.CodeMirror=U;exports.MiniRepl=De;exports.cx=j;exports.flash=Q;exports.useCycle=G;exports.useHighlighting=Y;exports.usePostMessage=J;exports.useRepl=X;exports.useWebMidi=Ne; diff --git a/packages/react/dist/index.es.js b/packages/react/dist/index.es.js index a0269039..f97ec673 100644 --- a/packages/react/dist/index.es.js +++ b/packages/react/dist/index.es.js @@ -1,4 +1,4 @@ -import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react'; +import React, { useState, useEffect, useCallback, useMemo, useRef, useLayoutEffect } from 'react'; import { CodeMirror as CodeMirror$1 } from 'react-codemirror6'; import { EditorView, Decoration } from '@codemirror/view'; import { StateEffect, StateField } from '@codemirror/state'; @@ -563,12 +563,16 @@ function Icon({ type }) { }[type]); } -function MiniRepl({ tune, defaultSynth, hideOutsideView = false }) { - const { code, setCode, pattern, activateCode, error, cycle, dirty, togglePlay } = useRepl({ +function MiniRepl({ tune, defaultSynth, hideOutsideView = false, theme, init, onEvent, enableKeyboard }) { + const { code, setCode, pattern, activeCode, activateCode, evaluateOnly, error, cycle, dirty, togglePlay, stop } = useRepl({ tune, defaultSynth, - autolink: false + autolink: false, + onEvent }); + useEffect(() => { + init && evaluateOnly(); + }, [tune, init]); const [view, setView] = useState(); const [ref, isVisible] = useInView({ threshold: 0.01 @@ -580,7 +584,25 @@ function MiniRepl({ tune, defaultSynth, hideOutsideView = false }) { } return isVisible || wasVisible.current; }, [isVisible, hideOutsideView]); - useHighlighting({ view, pattern, active: cycle.started }); + useHighlighting({ view, pattern, active: cycle.started && !activeCode?.includes("strudel disable-highlighting") }); + useLayoutEffect(() => { + if (enableKeyboard) { + const handleKeyPress = async (e) => { + if (e.ctrlKey || e.altKey) { + if (e.code === "Enter") { + e.preventDefault(); + flash(view); + await activateCode(); + } else if (e.code === "Period") { + cycle.stop(); + e.preventDefault(); + } + } + }; + window.addEventListener("keydown", handleKeyPress, true); + return () => window.removeEventListener("keydown", handleKeyPress, true); + } + }, [enableKeyboard, pattern, code, activateCode, cycle, view]); return /* @__PURE__ */ React.createElement("div", { className: styles.container, ref diff --git a/packages/react/src/components/MiniRepl.jsx b/packages/react/src/components/MiniRepl.jsx index 244911ae..bb75aca7 100644 --- a/packages/react/src/components/MiniRepl.jsx +++ b/packages/react/src/components/MiniRepl.jsx @@ -1,20 +1,25 @@ -import React, { useState, useMemo, useRef } from 'react'; +import React, { useState, useMemo, useRef, useEffect, useLayoutEffect } from 'react'; import { useInView } from 'react-hook-inview'; import useRepl from '../hooks/useRepl.mjs'; import cx from '../cx'; import useHighlighting from '../hooks/useHighlighting.mjs'; -import CodeMirror6 from './CodeMirror6'; +import CodeMirror6, { flash } from './CodeMirror6'; import 'tailwindcss/tailwind.css'; import './style.css'; import styles from './MiniRepl.module.css'; import { Icon } from './Icon'; -export function MiniRepl({ tune, defaultSynth, hideOutsideView = false }) { - const { code, setCode, pattern, activateCode, error, cycle, dirty, togglePlay } = useRepl({ - tune, - defaultSynth, - autolink: false, - }); +export function MiniRepl({ tune, defaultSynth, hideOutsideView = false, theme, init, onEvent, enableKeyboard }) { + const { code, setCode, pattern, activeCode, activateCode, evaluateOnly, error, cycle, dirty, togglePlay, stop } = + useRepl({ + tune, + defaultSynth, + autolink: false, + onEvent, + }); + useEffect(() => { + init && evaluateOnly(); + }, [tune, init]); const [view, setView] = useState(); const [ref, isVisible] = useInView({ threshold: 0.01, @@ -26,7 +31,28 @@ export function MiniRepl({ tune, defaultSynth, hideOutsideView = false }) { } return isVisible || wasVisible.current; }, [isVisible, hideOutsideView]); - useHighlighting({ view, pattern, active: cycle.started }); + useHighlighting({ view, pattern, active: cycle.started && !activeCode?.includes('strudel disable-highlighting') }); + + // set active pattern on ctrl+enter + useLayoutEffect(() => { + if (enableKeyboard) { + const handleKeyPress = async (e) => { + if (e.ctrlKey || e.altKey) { + if (e.code === 'Enter') { + e.preventDefault(); + flash(view); + await activateCode(); + } else if (e.code === 'Period') { + cycle.stop(); + e.preventDefault(); + } + } + }; + window.addEventListener('keydown', handleKeyPress, true); + return () => window.removeEventListener('keydown', handleKeyPress, true); + } + }, [enableKeyboard, pattern, code, activateCode, cycle, view]); + return (