diff --git a/my-patterns/README.md b/my-patterns/README.md index 2f8544be..b7f416c6 100644 --- a/my-patterns/README.md +++ b/my-patterns/README.md @@ -3,18 +3,60 @@ This directory can be used to save your own patterns, which then get made into a pattern swatch. -0. fork and clone the strudel repository -1. run `npm run setup` in the strudel folder -1. Save one or more .txt files in this folder -2. run `npm run repl` in the top-level strudel folder -3. open `http://localhost:3000/swatch/` ! +Example: ## deploy -1. in your fork, go to settings -> pages and select "Github Actions" as source -2. edit `website/public/CNAME` to contain `.github.io/strudel` -3. edit `website/astro.config.mjs` to use site: `https://.github.io` and base `/strudel` -4. go to Actions -> `Build and Deploy` and click `Run workflow` -5. view your patterns at `.github.io/strudel/swatch/` +### 1. fork the [strudel repo on github](https://github.com/tidalcycles/strudel.git) + +### 2. clone your fork to your machine `git clone https://github.com//strudel.git strudel && cd strudel` + +### 3. create a separate branch like `git branch patternuary && git checkout patternuary` + +### 4. save one or more .txt files in the my-patterns folder + +### 5. edit `website/public/CNAME` to contain `.github.io/strudel` + +### 6. edit `website/astro.config.mjs` to use site: `https://.github.io` and base `/strudel`, like this + +```js +export default defineConfig({ + /* ... rest of config ... */ + site: 'https://.github.io', + base: '/strudel', +}); +``` + +### 7. commit & push the changes + +```sh +git add . && git commit -m "site config" && git push --set-upstream origin +``` + +### 8. deploy to github pages + +- go to settings -> pages and select "Github Actions" as source +- go to settings -> environments -> github-pages and press the edit button next to `main` and type in `patternuary` (under "Deployment branches") +- go to Actions -> `Build and Deploy` and click `Run workflow` with branch `patternuary` + +### 9. view your patterns at `.github.io/strudel/swatch/` Alternatively, github pages allows you to use a custom domain, like https://mycooldomain.org/swatch/. [See their documentation for details](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site). + +### 10. optional: automatic deployment + +If you want to automatically deploy your site on push, go to `deploy.yml` and change `workflow_dispatch` to `push`. + +## running locally + +- install dependencies with `npm run setup` +- run dev server with `npm run repl` and open `http://localhost:3000/strudel/swatch/` + +## tests fail? + +Your tests might fail if the code does not follow prettiers format. +In that case, run `npm run codeformat`. To disable that, remove `npm run format-check` from `test.yml` + +## updating your fork + +To update your fork, you can pull the main branch and merge it into your `patternuary` branch. diff --git a/packages/core/animate.mjs b/packages/core/animate.mjs index 4ebb71ff..80e8501b 100644 --- a/packages/core/animate.mjs +++ b/packages/core/animate.mjs @@ -22,11 +22,11 @@ Pattern.prototype.animate = function ({ callback, sync = false, smear = 0.5 } = ctx.fillStyle = clearColor; ctx.fillRect(0, 0, ww, wh); frame.forEach((f) => { - let { x, y, w, h, s, r, a = 0, fill = 'darkseagreen' } = f.value; + let { x, y, w, h, s, r, angle = 0, fill = 'darkseagreen' } = f.value; w *= ww; h *= wh; - if (r !== undefined && a !== undefined) { - const radians = a * 2 * Math.PI; + if (r !== undefined && angle !== undefined) { + const radians = angle * 2 * Math.PI; const [cx, cy] = [(ww - w) / 2, (wh - h) / 2]; x = cx + Math.cos(radians) * r * cx; y = cy + Math.sin(radians) * r * cy; @@ -51,7 +51,7 @@ Pattern.prototype.animate = function ({ callback, sync = false, smear = 0.5 } = return silence; }; -export const { x, y, w, h, a, r, fill, smear } = createParams('x', 'y', 'w', 'h', 'a', 'r', 'fill', 'smear'); +export const { x, y, w, h, angle, r, fill, smear } = createParams('x', 'y', 'w', 'h', 'angle', 'r', 'fill', 'smear'); export const rescale = register('rescale', function (f, pat) { return pat.mul(x(f).w(f).y(f).h(f)); 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/euclid.mjs b/packages/core/euclid.mjs index 6aa2283d..d8560c8e 100644 --- a/packages/core/euclid.mjs +++ b/packages/core/euclid.mjs @@ -46,7 +46,7 @@ const _bjork = function (n, x) { return Math.min(ons, offs) <= 1 ? [n, x] : _bjork(...(ons > offs ? left(n, x) : right(n, x))); }; -const bjork = function (ons, steps) { +export const bjork = function (ons, steps) { const offs = steps - ons; const x = Array(ons).fill([1]); const y = Array(offs).fill([0]); diff --git a/packages/core/pattern.mjs b/packages/core/pattern.mjs index a11841a6..c12cf2b0 100644 --- a/packages/core/pattern.mjs +++ b/packages/core/pattern.mjs @@ -334,7 +334,12 @@ export class Pattern { * silence */ queryArc(begin, end) { - return this.query(new State(new TimeSpan(begin, end))); + try { + return this.query(new State(new TimeSpan(begin, end))); + } catch (err) { + logger(`[query]: ${err.message}`, 'error'); + return []; + } } /** @@ -2060,6 +2065,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/core/signal.mjs b/packages/core/signal.mjs index bd6815e2..7309a19f 100644 --- a/packages/core/signal.mjs +++ b/packages/core/signal.mjs @@ -114,6 +114,14 @@ const timeToRands = (t, n) => timeToRandsPrime(timeToIntSeed(t), n); * */ +/** + * A discrete pattern of numbers from 0 to n-1 + * @example + * run(4).scale('C4 major').note() + * // "0 1 2 3".scale('C4 major').note() + */ +export const run = (n) => saw.range(0, n).floor().segment(n); + /** * A continuous pattern of random numbers, between 0 and 1. * diff --git a/packages/core/test/pattern.test.mjs b/packages/core/test/pattern.test.mjs index 2a91e142..a4c04e80 100644 --- a/packages/core/test/pattern.test.mjs +++ b/packages/core/test/pattern.test.mjs @@ -44,6 +44,7 @@ import { ply, rev, time, + run, } from '../index.mjs'; import { steady } from '../signal.mjs'; @@ -908,6 +909,11 @@ describe('Pattern', () => { ); }); }); + describe('run', () => { + it('Can run', () => { + expect(run(4).firstCycle()).toStrictEqual(sequence(0, 1, 2, 3).firstCycle()); + }); + }); describe('linger', () => { it('Can linger on the first quarter of a cycle', () => { expect(sequence(0, 1, 2, 3, 4, 5, 6, 7).linger(0.25).firstCycle()).toStrictEqual( diff --git a/packages/react/dist/index.cjs.js b/packages/react/dist/index.cjs.js index 5e9d79dc..6837f4d8 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"),de=require("@uiw/react-codemirror"),w=require("@codemirror/view"),V=require("@codemirror/state"),fe=require("@codemirror/lang-javascript"),d=require("@lezer/highlight"),ge=require("@uiw/codemirror-themes"),Z=require("@strudel.cycles/webaudio"),me=require("react-hook-inview"),T=require("@strudel.cycles/core"),he=require("@strudel.cycles/transpiler"),ee=e=>e&&typeof e=="object"&&"default"in e?e:{default:e},f=ee(t),pe=ee(de),ve=ge.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:d.tags.keyword,color:"#c792ea"},{tag:d.tags.operator,color:"#89ddff"},{tag:d.tags.special(d.tags.variableName),color:"#eeffff"},{tag:d.tags.typeName,color:"#c3e88d"},{tag:d.tags.atom,color:"#f78c6c"},{tag:d.tags.number,color:"#c3e88d"},{tag:d.tags.definition(d.tags.variableName),color:"#82aaff"},{tag:d.tags.string,color:"#c3e88d"},{tag:d.tags.special(d.tags.string),color:"#c3e88d"},{tag:d.tags.comment,color:"#7d8799"},{tag:d.tags.variableName,color:"#c792ea"},{tag:d.tags.tagName,color:"#c3e88d"},{tag:d.tags.bracket,color:"#525154"},{tag:d.tags.meta,color:"#ffcb6b"},{tag:d.tags.attributeName,color:"#c792ea"},{tag:d.tags.propertyName,color:"#c792ea"},{tag:d.tags.className,color:"#decb6b"},{tag:d.tags.invalid,color:"#ffffff"}]});const J=V.StateEffect.define(),be=V.StateField.define({create(){return w.Decoration.none},update(e,r){try{for(let o of r.effects)if(o.is(J))if(o.value){const n=w.Decoration.mark({attributes:{style:"background-color: #FFCA2880"}});e=w.Decoration.set([n.range(0,r.newDoc.length)])}else e=w.Decoration.set([]);return e}catch(o){return console.warn("flash error",o),e}},provide:e=>w.EditorView.decorations.from(e)}),te=e=>{e.dispatch({effects:J.of(!0)}),setTimeout(()=>{e.dispatch({effects:J.of(!1)})},200)},z=V.StateEffect.define(),Ee=V.StateField.define({create(){return w.Decoration.none},update(e,r){try{for(let o of r.effects)if(o.is(z)){const n=o.value.map(u=>(u.context.locations||[]).map(({start:m,end:g})=>{const s=u.context.color||"#FFCA28";let l=r.newDoc.line(m.line).from+m.column,p=r.newDoc.line(g.line).from+g.column;const E=r.newDoc.length;return l>E||p>E?void 0:w.Decoration.mark({attributes:{style:`outline: 1.5px solid ${s};`}}).range(l,p)})).flat().filter(Boolean)||[];e=w.Decoration.set(n,!0)}return e}catch{return w.Decoration.set([])}},provide:e=>w.EditorView.decorations.from(e)}),ye=[fe.javascript(),ve,Ee,be];function re({value:e,onChange:r,onViewChanged:o,onSelectionChange:n,options:u,editorDidMount:m}){const g=t.useCallback(p=>{r?.(p)},[r]),s=t.useCallback(p=>{o?.(p)},[o]),l=t.useCallback(p=>{p.selectionSet&&n&&n?.(p.state.selection)},[n]);return f.default.createElement(f.default.Fragment,null,f.default.createElement(pe.default,{value:e,onChange:g,onCreateEditor:s,onUpdate:l,extensions:ye}))}function G(...e){return e.filter(Boolean).join(" ")}function oe({view:e,pattern:r,active:o,getTime:n}){const u=t.useRef([]),m=t.useRef(0);t.useEffect(()=>{if(e)if(r&&o){m.current=0;let g=requestAnimationFrame(function s(){try{const l=n(),E=[Math.max(m.current??l,l-1/10,-.01),l+1/60];m.current=E[1],u.current=u.current.filter(h=>h.whole.end>l);const i=r.queryArc(...E).filter(h=>h.hasOnset());u.current=u.current.concat(i),e.dispatch({effects:z.of(u.current)})}catch{e.dispatch({effects:z.of([])})}g=requestAnimationFrame(s)});return()=>{cancelAnimationFrame(g)}}else u.current=[],e.dispatch({effects:z.of([])})},[r,o,e])}function we(e,r=!1){const o=t.useRef(),n=t.useRef(),u=s=>{if(n.current!==void 0){const l=s-n.current;e(s,l)}n.current=s,o.current=requestAnimationFrame(u)},m=()=>{o.current=requestAnimationFrame(u)},g=()=>{o.current&&cancelAnimationFrame(o.current),delete o.current};return t.useEffect(()=>{o.current&&(g(),m())},[e]),t.useEffect(()=>(r&&m(),g),[]),{start:m,stop:g}}function ke({pattern:e,started:r,getTime:o,onDraw:n,drawTime:u=[-2,2]}){let[m,g]=u;m=Math.abs(m);let s=t.useRef([]),l=t.useRef(null);t.useEffect(()=>{if(e&&r){const i=o(),h=e.queryArc(Math.max(i,0),i+g+.1);s.current=s.current.filter(v=>v.whole.begin{const i=o()+g;if(l.current===null){l.current=i;return}const h=e.queryArc(Math.max(l.current,i-1/10),i);l.current=i,s.current=(s.current||[]).filter(v=>v.whole.end>=i-m-g).concat(h.filter(v=>v.hasOnset())),n(e,i-g,s.current,u)},[e]));return t.useEffect(()=>{r?p():(s.current=[],E())},[r]),{clear:()=>{s.current=[]}}}function ne(e){return t.useEffect(()=>(window.addEventListener("message",e),()=>window.removeEventListener("message",e)),[e]),t.useCallback(r=>window.postMessage(r,"*"),[])}function ae({defaultOutput:e,interval:r,getTime:o,evalOnMount:n=!1,initialCode:u="",autolink:m=!1,beforeEval:g,afterEval:s,editPattern:l,onEvalError:p,onToggle:E,canvasId:i,drawContext:h,drawTime:v=[-2,2]}){const F=t.useMemo(()=>_e(),[]);i=i||`canvas-${F}`;const[S,D]=t.useState(),[N,x]=t.useState(),[y,L]=t.useState(u),[P,A]=t.useState(),[R,O]=t.useState(),[M,H]=t.useState(!1),j=y!==P,q=t.useCallback(c=>!!(c?.context?.onPaint&&h),[h]),{scheduler:C,evaluate:a,start:b,stop:B,pause:I}=t.useMemo(()=>T.repl({interval:r,defaultOutput:e,onSchedulerError:D,onEvalError:c=>{x(c),p?.(c)},getTime:o,drawContext:h,transpiler:he.transpiler,editPattern:l,beforeEval:({code:c})=>{L(c),g?.()},afterEval:({pattern:c,code:k})=>{A(k),O(c),x(),D(),m&&(window.location.hash="#"+encodeURIComponent(btoa(k))),s?.()},onToggle:c=>{H(c),E?.(c)}}),[e,r,o]),se=ne(({data:{from:c,type:k}})=>{k==="start"&&c!==F&&B()}),Q=t.useCallback(async(c=!0)=>{const k=await a(y,c);return se({type:"start",from:F}),k},[a,y]),K=t.useCallback((c,k,W,$)=>{const{onPaint:ie}=c.context||{},ue=typeof h=="function"?h(i):h;ie?.(ue,k,W,$)},[h,i]),U=t.useCallback(c=>{if(q(c)){const[k,W]=v,$=c.queryArc(0,W);K(c,-.001,$,v)}},[v,K,q]),X=t.useRef();t.useEffect(()=>{!X.current&&n&&y&&(X.current=!0,a(y,!1).then(c=>U(c)))},[n,y,a,U]),t.useEffect(()=>()=>{C.stop()},[C]);const ce=async()=>{M?(C.stop(),U(R)):await Q()},le=S||N;return ke({pattern:R,started:q(R)&&M,getTime:()=>C.now(),drawTime:v,onDraw:K}),{id:F,canvasId:i,code:y,setCode:L,error:le,schedulerError:S,scheduler:C,evalError:N,evaluate:a,activateCode:Q,activeCode:P,isDirty:j,pattern:R,started:M,start:b,stop:B,pause:I,togglePlay:ce}}function _e(){return Math.floor((1+Math.random())*65536).toString(16).substring(1)}function Y({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"}),stop:f.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 Me="_container_3i85k_1",Ce="_header_3i85k_5",Fe="_buttons_3i85k_9",De="_button_3i85k_9",Re="_buttonDisabled_3i85k_17",qe="_error_3i85k_21",Se="_body_3i85k_25",_={container:Me,header:Ce,buttons:Fe,button:De,buttonDisabled:Re,error:qe,body:Se},Ae=()=>Z.getAudioContext().currentTime;function Ne({tune:e,hideOutsideView:r=!1,enableKeyboard:o,drawTime:n,punchcard:u,canvasHeight:m=200}){n=n||(u?[0,4]:void 0);const g=!!n,s=t.useCallback(n?a=>document.querySelector("#"+a)?.getContext("2d"):null,[n]),{code:l,setCode:p,evaluate:E,activateCode:i,error:h,isDirty:v,activeCode:F,pattern:S,started:D,scheduler:N,togglePlay:x,stop:y,canvasId:L,id:P}=ae({initialCode:e,defaultOutput:Z.webaudioOutput,editPattern:a=>u?a.punchcard():a,getTime:Ae,evalOnMount:g,drawContext:s,drawTime:n}),[A,R]=t.useState(),[O,M]=me.useInView({threshold:.01}),H=t.useRef(),j=t.useMemo(()=>((M||!r)&&(H.current=!0),M||H.current),[M,r]);oe({view:A,pattern:S,active:D&&!F?.includes("strudel disable-highlighting"),getTime:()=>N.now()}),t.useLayoutEffect(()=>{if(o){const a=async b=>{(b.ctrlKey||b.altKey)&&(b.code==="Enter"?(b.preventDefault(),te(A),await i()):b.code==="Period"&&(y(),b.preventDefault()))};return window.addEventListener("keydown",a,!0),()=>window.removeEventListener("keydown",a,!0)}},[o,S,l,E,y,A]);const[q,C]=t.useState([]);return xe(t.useCallback(a=>{const{data:b}=a.detail;b?.hap?.context?.id===P&&C(I=>I.concat([a.detail]).slice(-10))},[])),f.default.createElement("div",{className:_.container,ref:O},f.default.createElement("div",{className:_.header},f.default.createElement("div",{className:_.buttons},f.default.createElement("button",{className:G(_.button,D?"sc-animate-pulse":""),onClick:()=>x()},f.default.createElement(Y,{type:D?"stop":"play"})),f.default.createElement("button",{className:G(v?_.button:_.buttonDisabled),onClick:()=>i()},f.default.createElement(Y,{type:"refresh"}))),h&&f.default.createElement("div",{className:_.error},h.message)),f.default.createElement("div",{className:_.body},j&&f.default.createElement(re,{value:l,onChange:p,onViewChanged:R})),n&&f.default.createElement("canvas",{id:L,className:"w-full pointer-events-none",height:m,ref:a=>{a&&a.width!==a.clientWidth&&(a.width=a.clientWidth)}}),!!q.length&&f.default.createElement("div",{className:"sc-bg-gray-800 sc-rounded-md sc-p-2"},q.map(({message:a},b)=>f.default.createElement("div",{key:b},a))))}function xe(e){Le(T.logger.key,e)}function Le(e,r,o=!1){t.useEffect(()=>(document.addEventListener(e,r,o),()=>{document.removeEventListener(e,r,o)}),[r])}const Pe=e=>t.useLayoutEffect(()=>(window.addEventListener("keydown",e,!0),()=>window.removeEventListener("keydown",e,!0)),[e]);exports.CodeMirror=re;exports.MiniRepl=Ne;exports.cx=G;exports.flash=te;exports.useHighlighting=oe;exports.useKeydown=Pe;exports.usePostMessage=ne;exports.useStrudel=ae; diff --git a/packages/react/dist/index.es.js b/packages/react/dist/index.es.js index d0027424..4aecb645 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 d, { useCallback as E, useRef as A, useEffect as k, useMemo as Q, useState as _, useLayoutEffect as te } from "react"; +import ue from "@uiw/react-codemirror"; +import { Decoration as M, EditorView as re } from "@codemirror/view"; +import { StateEffect as ne, StateField as oe } from "@codemirror/state"; +import { javascript as de } from "@codemirror/lang-javascript"; +import { tags as u } from "@lezer/highlight"; +import { createTheme as fe } from "@uiw/codemirror-themes"; +import { webaudioOutput as me, getAudioContext as he } from "@strudel.cycles/webaudio"; +import { useInView as ge } from "react-hook-inview"; +import { repl as pe, logger as ve } from "@strudel.cycles/core"; +import { transpiler as be } from "@strudel.cycles/transpiler"; +const Ee = fe({ theme: "dark", settings: { background: "#222", @@ -22,380 +22,421 @@ 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: u.keyword, color: "#c792ea" }, + { tag: u.operator, color: "#89ddff" }, + { tag: u.special(u.variableName), color: "#eeffff" }, + { tag: u.typeName, color: "#c3e88d" }, + { tag: u.atom, color: "#f78c6c" }, + { tag: u.number, color: "#c3e88d" }, + { tag: u.definition(u.variableName), color: "#82aaff" }, + { tag: u.string, color: "#c3e88d" }, + { tag: u.special(u.string), color: "#c3e88d" }, + { tag: u.comment, color: "#7d8799" }, + { tag: u.variableName, color: "#c792ea" }, + { tag: u.tagName, color: "#c3e88d" }, + { tag: u.bracket, color: "#525154" }, + { tag: u.meta, color: "#ffcb6b" }, + { tag: u.attributeName, color: "#c792ea" }, + { tag: u.propertyName, color: "#c792ea" }, + { tag: u.className, color: "#decb6b" }, + { tag: u.invalid, color: "#ffffff" } ] }); -const j = Q.define(), ue = X.define({ +const X = ne.define(), ye = oe.define({ create() { - return y.none; + return M.none; }, - update(e, r) { + update(e, t) { try { - for (let t of r.effects) - if (t.is(j)) - if (t.value) { - const a = y.mark({ attributes: { style: "background-color: #FFCA2880" } }); - e = y.set([a.range(0, r.newDoc.length)]); + for (let r of t.effects) + if (r.is(X)) + if (r.value) { + const n = M.mark({ attributes: { style: "background-color: #FFCA2880" } }); + e = M.set([n.range(0, t.newDoc.length)]); } else - e = y.set([]); + e = M.set([]); return e; - } catch (t) { - return console.warn("flash error", t), e; + } catch (r) { + return console.warn("flash error", r), 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) +}), we = (e) => { + e.dispatch({ effects: X.of(!0) }), setTimeout(() => { + e.dispatch({ effects: X.of(!1) }); }, 200); -}, z = Q.define(), fe = X.define({ +}, B = ne.define(), ke = oe.define({ create() { - return y.none; + return M.none; }, - update(e, r) { + update(e, t) { 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); + for (let r of t.effects) + if (r.is(B)) { + const n = r.value.map( + (l) => (l.context.locations || []).map(({ start: m, end: f }) => { + const c = l.context.color || "#FFCA28"; + let s = t.newDoc.line(m.line).from + m.column, g = t.newDoc.line(f.line).from + f.column; + const b = t.newDoc.length; + return s > b || g > b ? void 0 : M.mark({ attributes: { style: `outline: 1.5px solid ${c};` } }).range(s, g); }) ).flat().filter(Boolean) || []; - e = y.set(a, !0); + e = M.set(n, !0); } return e; } catch { - return y.set([]); + return M.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); - }, - [r] - ), m = N( - (d) => { - t?.(d); + provide: (e) => re.decorations.from(e) +}), Fe = [de(), Ee, ke, ye]; +function _e({ value: e, onChange: t, onViewChanged: r, onSelectionChange: n, options: l, editorDidMount: m }) { + const f = E( + (g) => { + t?.(g); }, [t] - ), n = N( - (d) => { - d.selectionSet && a && a?.(d.state.selection); + ), c = E( + (g) => { + r?.(g); }, - [a] + [r] + ), s = E( + (g) => { + g.selectionSet && n && n?.(g.state.selection); + }, + [n] ); - return /* @__PURE__ */ l.createElement(l.Fragment, null, /* @__PURE__ */ l.createElement(Z, { + return /* @__PURE__ */ d.createElement(d.Fragment, null, /* @__PURE__ */ d.createElement(ue, { value: e, - onChange: u, - onCreateEditor: m, - onUpdate: n, - extensions: me + onChange: f, + onCreateEditor: c, + onUpdate: s, + extensions: Fe })); } -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 Me({ view: e, pattern: t, active: r, getTime: n }) { + const l = A([]), m = A(0); + k(() => { if (e) - if (r && t) { - let u = requestAnimationFrame(function m() { + if (t && r) { + m.current = 0; + let f = requestAnimationFrame(function c() { 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 s = n(), b = [Math.max(m.current ?? s, s - 1 / 10, -0.01), s + 1 / 60]; + m.current = b[1], l.current = l.current.filter((h) => h.whole.end > s); + const i = t.queryArc(...b).filter((h) => h.hasOnset()); + l.current = l.current.concat(i), e.dispatch({ effects: B.of(l.current) }); } catch { - e.dispatch({ effects: z.of([]) }); + e.dispatch({ effects: B.of([]) }); } - u = requestAnimationFrame(m); + f = requestAnimationFrame(c); }); return () => { - cancelAnimationFrame(u); + cancelAnimationFrame(f); }; } else - o.current = [], e.dispatch({ effects: z.of([]) }); - }, [r, t, e]); + l.current = [], e.dispatch({ effects: B.of([]) }); + }, [t, r, 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 Ae(e, t = !1) { + const r = A(), n = A(), l = (c) => { + if (n.current !== void 0) { + const s = c - n.current; + e(c, s); } - a.current = m, t.current = requestAnimationFrame(o); - }, i = () => { - t.current = requestAnimationFrame(o); - }, u = () => { - t.current && cancelAnimationFrame(t.current), delete t.current; + n.current = c, r.current = requestAnimationFrame(l); + }, m = () => { + r.current = requestAnimationFrame(l); + }, f = () => { + r.current && cancelAnimationFrame(r.current), delete r.current; }; - return _(() => { - t.current && (u(), i()); - }, [e]), _(() => (r && i(), u), []), { - start: i, - stop: u + return k(() => { + r.current && (f(), m()); + }, [e]), k(() => (t && m(), f), []), { + start: m, + stop: f }; } -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 Ne({ pattern: e, started: t, getTime: r, onDraw: n, drawTime: l = [-2, 2] }) { + let [m, f] = l; + m = Math.abs(m); + let c = A([]), s = A(null); + k(() => { + if (e && t) { + const i = r(), h = e.queryArc(Math.max(i, 0), i + f + 0.1); + c.current = c.current.filter((p) => p.whole.begin < i), c.current = c.current.concat(h); + } + }, [e, t]); + const { start: g, stop: b } = Ae( + E(() => { + const i = r() + f; + if (s.current === null) { + s.current = i; 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(s.current, i - 1 / 10), i); + s.current = i, c.current = (c.current || []).filter((p) => p.whole.end >= i - m - f).concat(h.filter((p) => p.hasOnset())), n(e, i - f, c.current, l); }, [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(() => { + t ? g() : (c.current = [], b()); + }, [t]), { + clear: () => { + c.current = []; } }; } -function we() { +function Ce(e) { + return k(() => (window.addEventListener("message", e), () => window.removeEventListener("message", e)), [e]), E((t) => window.postMessage(t, "*"), []); +} +function De({ + defaultOutput: e, + interval: t, + getTime: r, + evalOnMount: n = !1, + initialCode: l = "", + autolink: m = !1, + beforeEval: f, + afterEval: c, + editPattern: s, + onEvalError: g, + onToggle: b, + canvasId: i, + drawContext: h, + drawTime: p = [-2, 2] +}) { + const D = Q(() => Re(), []); + i = i || `canvas-${D}`; + const [P, R] = _(), [z, H] = _(), [y, S] = _(l), [V, q] = _(), [x, I] = _(), [N, O] = _(!1), K = y !== V, L = E((a) => !!(a?.context?.onPaint && h), [h]), { scheduler: C, evaluate: o, start: v, stop: j, pause: U } = Q( + () => pe({ + interval: t, + defaultOutput: e, + onSchedulerError: R, + onEvalError: (a) => { + H(a), g?.(a); + }, + getTime: r, + drawContext: h, + transpiler: be, + editPattern: s, + beforeEval: ({ code: a }) => { + S(a), f?.(); + }, + afterEval: ({ pattern: a, code: w }) => { + q(w), I(a), H(), R(), m && (window.location.hash = "#" + encodeURIComponent(btoa(w))), c?.(); + }, + onToggle: (a) => { + O(a), b?.(a); + } + }), + [e, t, r] + ), ce = Ce(({ data: { from: a, type: w } }) => { + w === "start" && a !== D && j(); + }), Y = E( + async (a = !0) => { + const w = await o(y, a); + return ce({ type: "start", from: D }), w; + }, + [o, y] + ), W = E( + (a, w, G, J) => { + const { onPaint: ie } = a.context || {}, le = typeof h == "function" ? h(i) : h; + ie?.(le, w, G, J); + }, + [h, i] + ), $ = E( + (a) => { + if (L(a)) { + const [w, G] = p, J = a.queryArc(0, G); + W(a, -1e-3, J, p); + } + }, + [p, W, L] + ), Z = A(); + k(() => { + !Z.current && n && y && (Z.current = !0, o(y, !1).then((a) => $(a))); + }, [n, y, o, $]), k(() => () => { + C.stop(); + }, [C]); + const ae = async () => { + N ? (C.stop(), $(x)) : await Y(); + }, se = P || z; + return Ne({ + pattern: x, + started: L(x) && N, + getTime: () => C.now(), + drawTime: p, + onDraw: W + }), { + id: D, + canvasId: i, + code: y, + setCode: S, + error: se, + schedulerError: P, + scheduler: C, + evalError: z, + evaluate: o, + activateCode: Y, + activeCode: V, + isDirty: K, + pattern: x, + started: N, + start: v, + stop: j, + pause: U, + togglePlay: ae + }; +} +function Re() { return Math.floor((1 + Math.random()) * 65536).toString(16).substring(1); } -function $({ type: e }) { - return /* @__PURE__ */ l.createElement("svg", { +function ee({ type: e }) { + return /* @__PURE__ */ d.createElement("svg", { xmlns: "http://www.w3.org/2000/svg", className: "sc-h-5 sc-w-5", viewBox: "0 0 20 20", fill: "currentColor" }, { - refresh: /* @__PURE__ */ l.createElement("path", { + refresh: /* @__PURE__ */ d.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: /* @__PURE__ */ l.createElement("path", { + play: /* @__PURE__ */ d.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: /* @__PURE__ */ l.createElement("path", { + pause: /* @__PURE__ */ d.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: /* @__PURE__ */ d.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, - isDirty: v, - activeCode: h, - pattern: p, - started: F, - scheduler: A, - togglePlay: P, - stop: D, - canvasId: b, - id: q - } = Ee({ +const xe = "_container_3i85k_1", Le = "_header_3i85k_5", Pe = "_buttons_3i85k_9", qe = "_button_3i85k_9", ze = "_buttonDisabled_3i85k_17", He = "_error_3i85k_21", Se = "_body_3i85k_25", F = { + container: xe, + header: Le, + buttons: Pe, + button: qe, + buttonDisabled: ze, + error: He, + body: Se +}, Ve = () => he().currentTime; +function Ze({ tune: e, hideOutsideView: t = !1, enableKeyboard: r, drawTime: n, punchcard: l, canvasHeight: m = 200 }) { + n = n || (l ? [0, 4] : void 0); + const f = !!n, c = E( + n ? (o) => document.querySelector("#" + o)?.getContext("2d") : null, + [n] + ), { + code: s, + setCode: g, + evaluate: b, + activateCode: i, + error: h, + isDirty: p, + activeCode: D, + pattern: P, + started: R, + scheduler: z, + togglePlay: H, + stop: y, + 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: me, + editPattern: (o) => l ? o.punchcard() : o, + getTime: Ve, + evalOnMount: f, + drawContext: c, + drawTime: n + }), [q, x] = _(), [I, N] = ge({ 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(() => { - 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())); + }), O = A(), K = Q(() => ((N || !t) && (O.current = !0), N || O.current), [N, t]); + Me({ + view: q, + pattern: P, + active: R && !D?.includes("strudel disable-highlighting"), + getTime: () => z.now() + }), te(() => { + if (r) { + const o = async (v) => { + (v.ctrlKey || v.altKey) && (v.code === "Enter" ? (v.preventDefault(), we(q), await i()) : v.code === "Period" && (y(), v.preventDefault())); }; - return window.addEventListener("keydown", c, !0), () => window.removeEventListener("keydown", c, !0); + return window.addEventListener("keydown", o, !0), () => window.removeEventListener("keydown", o, !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)); + }, [r, P, s, b, y, q]); + const [L, C] = _([]); + return Oe( + E((o) => { + const { data: v } = o.detail; + v?.hap?.context?.id === V && C((U) => U.concat([o.detail]).slice(-10)); }, []) - ), /* @__PURE__ */ l.createElement("div", { - className: E.container, + ), /* @__PURE__ */ d.createElement("div", { + className: F.container, ref: I - }, /* @__PURE__ */ l.createElement("div", { - className: E.header - }, /* @__PURE__ */ l.createElement("div", { - className: E.buttons - }, /* @__PURE__ */ l.createElement("button", { - className: W(E.button, F ? "sc-animate-pulse" : ""), - onClick: () => P() - }, /* @__PURE__ */ l.createElement($, { - type: F ? "pause" : "play" - })), /* @__PURE__ */ l.createElement("button", { - className: W(v ? E.button : E.buttonDisabled), - onClick: () => n() - }, /* @__PURE__ */ l.createElement($, { + }, /* @__PURE__ */ d.createElement("div", { + className: F.header + }, /* @__PURE__ */ d.createElement("div", { + className: F.buttons + }, /* @__PURE__ */ d.createElement("button", { + className: T(F.button, R ? "sc-animate-pulse" : ""), + onClick: () => H() + }, /* @__PURE__ */ d.createElement(ee, { + type: R ? "stop" : "play" + })), /* @__PURE__ */ d.createElement("button", { + className: T(p ? F.button : F.buttonDisabled), + onClick: () => i() + }, /* @__PURE__ */ d.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__ */ d.createElement("div", { + className: F.error + }, h.message)), /* @__PURE__ */ d.createElement("div", { + className: F.body + }, K && /* @__PURE__ */ d.createElement(_e, { + value: s, + onChange: g, + onViewChanged: x + })), n && /* @__PURE__ */ d.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: (o) => { + o && o.width !== o.clientWidth && (o.width = o.clientWidth); } - }), !!H.length && /* @__PURE__ */ l.createElement("div", { + }), !!L.length && /* @__PURE__ */ d.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)))); + }, L.map(({ message: o }, v) => /* @__PURE__ */ d.createElement("div", { + key: v + }, o)))); } -function Ae(e) { - De(ne.key, e); +function Oe(e) { + Be(ve.key, e); } -function De(e, r, t = !1) { - _(() => (document.addEventListener(e, r, t), () => { - document.removeEventListener(e, r, t); - }), [r]); +function Be(e, t, r = !1) { + k(() => (document.addEventListener(e, t, r), () => { + document.removeEventListener(e, t, r); + }), [t]); } -const Ue = (e) => G(() => (window.addEventListener("keydown", e, !0), () => window.removeEventListener("keydown", e, !0)), [e]); +const Te = (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 + _e as CodeMirror, + Ze as MiniRepl, + T as cx, + we as flash, + Me as useHighlighting, + Te as useKeydown, + Ce 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