Compare commits

...

168 Commits

Author SHA1 Message Date
Felix Roos f805560827 dedupe 2026-11-26 23:30:21 +01:00
Felix Roos f8bb10d2a0 format 2026-11-26 23:16:35 +01:00
Felix Roos a160f76d23 pull out control-using pattern functions to controls.mjs 2026-11-26 23:16:17 +01:00
Felix Roos 3fc1cc871c fix import 2026-11-26 23:15:29 +01:00
Felix Roos 2c2c6bc6bf move evaluate back to core, keep strudelScope in pattern package 2026-11-26 22:31:33 +01:00
Felix Roos 089187b9b2 lockfile 2026-11-26 21:27:48 +01:00
Felix Roos dc441e68df fix old core imports to use pattern package 2026-11-26 21:27:39 +01:00
Felix Roos c6253789ab move pattern core to @strudel/pattern 2026-11-26 21:22:14 +01:00
Alex McLean b8b59d911f Merge pull request 'Reimplement reverted vim-mode features' (#2176) from wrbs/strudel:vim-ex-actions into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2176
2026-11-25 20:09:50 +01:00
Alex McLean a5079db6f7 Merge pull request 'Revert "Merge pull request 'Use JsDoc component in Repl' (#2196) from Orasund/strudel:use-jsDoc-component-in-repl into main"' (#2203) from revert-2196 into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2203
2026-11-25 09:18:57 +01:00
alex 36647afbbf Revert "Merge pull request 'Use JsDoc component in Repl' (#2196) from Orasund/strudel:use-jsDoc-component-in-repl into main"
This reverts commit 034f7d4332, reversing
changes made to b11ba9f2d9.
2026-11-25 09:09:13 +01:00
froos d13f040617 Merge pull request 'refactor and document sample-server' (#2159) from diegodorado/strudel:main into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2159
2026-11-24 21:37:38 +01:00
Alex McLean 92b7db3a97 Merge pull request 'Add missing documentation for functions' (#2198) from Orasund/strudel:add-eslint-plugin-jsdoc into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2198
2026-11-24 15:57:30 +01:00
Orasund aad846a45f Add jsdoc/require-description 2026-11-24 15:11:54 +01:00
Orasund 4a060f20f2 Add annotations for computeAvailableFunctions 2026-11-24 13:20:36 +01:00
Alex McLean 3a5d917d7d Merge pull request 'Document pick with a pattern of objects' (#2200) from daltonoscar0/strudel:pick-objects-docs into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2200
2026-11-24 12:50:58 +01:00
Alex McLean 893cd9e051 Merge branch 'main' into add-eslint-plugin-jsdoc 2026-11-24 12:40:00 +01:00
Alex McLean c019be29ac Merge pull request 'Add Reference page to docs' (#2197) from Orasund/strudel:add-reference-page-to-docs into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2197
2026-11-24 12:39:31 +01:00
Alex McLean e263096efa Merge branch 'main' into add-reference-page-to-docs 2026-11-24 12:39:06 +01:00
Alex McLean e74be00a7c Merge pull request 'fix: only use ladder-processor for lowpass filters' (#2201) from CatoPaus/strudel:fix-ladder-hpf into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2201
2026-11-24 12:38:27 +01:00
Orasund d90dd71bd9 Add new test 2026-11-24 11:39:00 +01:00
Orasund a14aaacc4f formatting 2026-11-24 11:07:24 +01:00
Orasund aa3aea4398 Merge branch 'add-eslint-plugin-jsdoc' of https://codeberg.org/Orasund/strudel into add-eslint-plugin-jsdoc 2026-11-24 11:04:55 +01:00
Orasund dcca8e45b1 fix function definitions in jsDocs 2026-11-24 11:03:36 +01:00
Orasund 16b2dba3b1 Use "Reference" instead of "Api Reference" 2026-11-24 09:59:38 +01:00
Alex McLean 041815e466 Merge branch 'main' into add-eslint-plugin-jsdoc 2026-11-24 09:41:26 +01:00
Orasund df27ef6fa9 Merge branch 'main' into add-reference-page-to-docs 2026-11-24 09:28:53 +01:00
CatoPaus f6315df48a Update packages/superdough/superdough.mjs 2026-11-24 09:22:16 +01:00
CatoPaus faf8522de0 fix: resolve numeric ftype for ladder filter. "numeric .ftype(1)" 2026-11-24 09:16:52 +01:00
CatoPaus c7d5ace20a fix: only use ladder-processor for lowpass filters 2026-11-24 08:47:30 +01:00
Orasund 441950898f formating 2026-11-24 06:58:44 +01:00
Orasund bd9d3f475b allow @memberof only with prototype 2026-11-24 06:32:48 +01:00
Oscar Dalton c465eda72f Document pick with a pattern of objects
Closes #2184
2026-11-23 20:45:04 -05:00
Alex McLean 03b0ac7e7b Merge pull request 'First go at AGENTS.md text' (#2192) from add-agents-file into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2192
2026-11-23 21:01:05 +01:00
Alex McLean 034f7d4332 Merge pull request 'Use JsDoc component in Repl' (#2196) from Orasund/strudel:use-jsDoc-component-in-repl into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2196
2026-11-23 20:53:21 +01:00
yaxu 7d195eb63f Update AGENTS.md 2026-11-23 20:51:35 +01:00
yaxu 844ff20ce3 Update AGENTS.md 2026-11-23 20:51:00 +01:00
yaxu f9aceecd5a Update AGENTS.md 2026-11-23 20:50:05 +01:00
Orasund 5604087bc9 fix pnpm-lock file 2026-11-23 19:35:07 +01:00
Orasund bf49b35e59 formating 2026-11-23 16:02:35 +01:00
Orasund 636e97297f Add jsdoc/check-tag-names 2026-11-23 15:58:15 +01:00
Orasund 02a8f9ef36 Add jsdoc/no-undefined-types 2026-11-23 15:51:00 +01:00
Orasund a85d7793ed Add jsdoc/check-param-names 2026-11-23 15:42:08 +01:00
Orasund 9851807be7 Add jsdoc/valid-types 2026-11-23 15:31:19 +01:00
Orasund 4c237e49c3 Add jsdoc/require-param 2026-11-23 15:29:32 +01:00
Orasund f9f5d853b2 Add jsdoc/require-returns 2026-11-23 14:37:31 +01:00
Orasund b87648ef11 Apply jsdoc/check-param-names rule 2026-11-23 13:55:06 +01:00
Orasund daa9065216 Add jsdoc/check-types 2026-11-23 13:32:55 +01:00
Orasund b556b604aa Add eslint-plugin-jsdoc 2026-11-23 13:30:39 +01:00
Orasund 57872d459f Remove dummy implementation of links for JsDoc 2026-11-23 11:50:04 +01:00
Orasund 4b989018a7 formating 2026-11-23 11:32:20 +01:00
Orasund 4530ed9a3a Add Api Reference page to docs 2026-11-23 11:28:15 +01:00
Orasund f331eda10d formating 2026-11-23 08:25:52 +01:00
Orasund 0eeeca8fb1 Use JsDoc component in Repl 2026-11-23 08:21:25 +01:00
Alex McLean b11ba9f2d9 Merge pull request 'websocket-client' (#2188) from websocket-client into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2188
2026-11-22 22:19:56 +01:00
Alex McLean fc271a8879 Merge pull request 'Fix reference documentation for functions with options parameter (pianoroll, spiral and midi)' (#2190) from Orasund/strudel:fix-options-object-in-jdoc into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2190
2026-11-22 22:19:18 +01:00
Alex McLean fdf243acee Merge pull request 'Add return values to reference docs' (#2193) from Orasund/strudel:fix-return-values-in-jsdocs into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2193
2026-11-22 22:18:38 +01:00
Alex McLean 429dbcd80e Merge pull request 'Compatibility with superdirt effects busses' (#1692) from busparts into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1692
2026-11-22 22:18:09 +01:00
alex 6a85f711d2 update superdirt bus magic to match new oscOutput 2026-11-22 20:54:40 +00:00
Orasund eca9f57e68 fix formating 2026-11-22 18:14:55 +01:00
Orasund d87abea11c fix formating 2026-11-22 18:13:40 +01:00
Orasund 08d2a4e3ae Add return values to reference docs 2026-11-22 12:44:19 +01:00
alex 1756713096 draft agents text 2026-11-22 10:48:48 +00:00
Orasund 841abc4827 Fix reference documentation for functions with options parameter (pianoroll, spiral and midi) 2026-11-22 08:05:29 +01:00
alex 46f01053da bus -> sdbus to avoid conflict with superdough's bus control 2026-11-21 16:26:02 +00:00
alex 9feb0f44cf format 2026-11-21 16:20:43 +00:00
alex e12e980e04 Merge branch 'main' of codeberg.org:uzu/strudel into busparts 2026-11-21 16:17:54 +00:00
Alex McLean d25df719df Merge pull request 'Change tidal -> Strudel' (#2182) from magnificaiterata/strudel:main into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2182
2026-11-20 21:43:21 +01:00
alex 62b8ec2402 fix typo 2026-11-20 13:45:53 +00:00
alex 24baaf7933 Merge branch 'websocket-client' of ssh://codeberg.org/uzu/strudel into websocket-client 2026-11-19 16:03:32 +00:00
alex 55dc8650f1 minor change to kick codeberg into action 2026-11-19 16:00:43 +00:00
Alex McLean 3b2208bc36 Merge branch 'main' into websocket-client 2026-11-19 16:58:43 +01:00
alex d6e231a9fd copy + paste error 2026-11-19 15:57:49 +00:00
alex 6c345ed827 simple websocket client thingie 2026-11-19 15:55:40 +00:00
Alex McLean 84ef32eec8 Merge pull request 'feat: Add print widget and docs - by @dtricks' (#2187) from dtricks-feat/print_widget into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2187
2026-11-19 16:40:51 +01:00
alex f111271d40 snapshot and fix test (add _print to mock) 2026-11-19 15:34:35 +00:00
Alex McLean 6e1a5126df Merge branch 'main' into feat/print_widget 2026-11-19 16:13:23 +01:00
magnificaiterata d71526d946 Change tidal -> Strudel
Just learning how to contribute
2026-11-17 15:18:00 +01:00
Alex McLean cac73dc558 Merge pull request 'Merging the Getting Started documentation from two sources (learn and workshop) into one (workshop) and adding redirections.' (#2179) from clpa/strudel:merging-getting-started-doc into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2179
2026-11-15 13:48:16 +01:00
clpa 4068d85e2d prettier 2026-11-14 22:52:30 +01:00
clpa 47a500ca33 updated link to superdirt on Codeberg 2026-11-13 22:58:57 +01:00
clpa 63aeb31644 Merging the Getting Started documentation from two sources (learn and workshop) into one (workshop) and adding redirections 2026-11-13 22:36:56 +01:00
Alex McLean 0cb6341299 Merge pull request 'website/workshop/first-sounds: fix typo' (#2175) from acidbong/first-sounds-typo into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2175
2026-11-08 02:32:27 +01:00
William Robson 7a343930aa Add support for 'gc' vim command for togling comments
Missing keybind from the default codemirror vim stuff, but easy to wire
up ourselves in the same way as the upstream ones are.
2026-11-07 11:49:37 -05:00
William Robson 266e5da109 Add back :w and :q vim ex-command bindings for evaluate/stop
This is ultimately the equivalent of doing

Vim.defineEx('write', 'w', () => strudelMirror.evaluate());
Vim.defineEx('quit', 'q', () => strudelMirror.stop());

but to make it a little more robust it uses a codemirror facet; this
means other editors like prebake won't clash as there's no
editorActions.of() provider there and it'll be a slient no-op for things
like .onEvaluate?.()
2026-11-07 11:49:36 -05:00
Acid Bong 3b06afdc9c website/workshop/first-sounds: fix typo 2026-11-07 12:25:05 +02:00
yaxu 530e9630bf Update README.md 2026-11-01 12:26:55 +01:00
yaxu fdaa559377 Update README.md 2026-10-26 15:13:52 +01:00
Diego Dorado 897ec4971d codeformat 2026-10-26 10:44:31 -03:00
Diego Dorado d784f62d4d nit 2026-10-26 10:44:31 -03:00
Diego Dorado f47caac716 update docs 2026-10-26 10:44:31 -03:00
Diego Dorado 0a88f2608a refactor args parser and cleanup a bit 2026-10-26 10:44:31 -03:00
Diego Dorado 32d295d668 output to sdout instead of writing to file when --json flag is passed 2026-10-26 10:44:31 -03:00
Diego Dorado 7d2d5db95d ignore mise.local.toml 2026-10-26 10:44:31 -03:00
Alex McLean 064cf07e26 Merge pull request 'Minor edit: change "human" to "person"' (#2162) from gamar3is/strudel:main into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2162
2026-10-25 11:02:53 +01:00
gamar3is d5362c208c Minor edit: change "human" to "person"
The use of the term "humans" to refer to people reinforces the anthropomorphisation of LLM's, suggesting they are specific entities instead of tools in a strange sci-fi way. Replacing "humans" with "people" can address this.
2026-10-25 10:56:50 +01:00
Alex McLean 7dd20fee57 Merge pull request 'humane dev policy' (#2158) from post-ai into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2158
2026-10-24 00:45:07 +02:00
yaxu 6b347af304 Clarify scope of llm corner 2026-10-24 00:44:34 +02:00
yaxu 6a64db0bc4 Update POLICY.md 2026-10-24 00:40:53 +02:00
Alex McLean 5ab79f2c6f Merge pull request 'gitignore .vscode except for settings.json' (#2160) from tyow/localstrudel:gitignore-vscode into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2160
2026-10-24 00:37:55 +02:00
tyow 67ce7c8ad6 gitignore .vscode except for settings.json 2026-10-23 17:30:15 -04:00
alex c84e5fd8fa tweaks 2026-10-23 11:45:43 +01:00
Alex McLean e00b6f6216 Merge pull request 'Update contributors in 'getting started' page' (#2157) from contributors into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2157
2026-10-19 21:22:53 +02:00
alex a2811ba35b draft of humane dev policy 2026-10-18 21:10:36 +01:00
yaxu 37097a92af Update website/src/pages/learn/getting-started.mdx 2026-10-18 15:22:41 +02:00
yaxu 669217ee7d Update website/src/pages/learn/getting-started.mdx 2026-10-18 13:02:53 +02:00
Alex McLean 61b6e96a4a Merge pull request 'Fix haps with no onset crashing cyclist, fix no latency' (#2154) from tzwaan/fix-cyclist-cps-2 into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2154
2026-10-16 11:31:09 +02:00
Tijmen Zwaan c33c845562 Use fractional values in cyclist 2026-10-16 11:16:29 +02:00
Tijmen Zwaan 1df7e03668 Fix haps with no onset crashing cyclist, fix no latency 2026-10-16 10:37:22 +02:00
Tijmen Zwaan 276979f48a Fix after rebase 2026-10-16 10:37:22 +02:00
Tijmen Zwaan 7e719c35f2 Fix the lastEnd not being correct when cps slowed down 2026-10-16 10:37:22 +02:00
Tijmen Zwaan a2c5af1673 Fix cps haps sort order being reversed 2026-10-16 10:37:22 +02:00
Tijmen Zwaan 2619144353 Slightly more correct sorting of haps for cps changes 2026-10-16 10:37:22 +02:00
Tijmen Zwaan e8a9974518 Fix Cyclist skipping haps during triggered increases in cps 2026-10-16 10:37:22 +02:00
Alex McLean a458dcf9fd Merge pull request 'revert 3583091e43 "Fix Cyclist skipping haps during triggered increases in cps"' (#2153) from yaxu-patch-1 into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2153
2026-10-16 09:30:19 +02:00
yaxu 8dbf5ce74c revert 3583091e43
revert Merge pull request 'Fix Cyclist skipping haps during triggered increases in cps' (#2103) from tzwaan/fix-cyclist-cps into main

Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2103
2026-10-16 09:25:24 +02:00
Alex McLean 7f02baf93b Merge pull request 'Add open and close signals, useful for making linear envelopes' (#2148) from openclose into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2148
2026-10-16 00:52:42 +02:00
Alex McLean 2cf3ffa507 Merge pull request 'Allow randL to be seeded' (#2152) from tyow/localstrudel:randl-seed-fix into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2152
2026-10-15 23:53:21 +02:00
Alex McLean 3583091e43 Merge pull request 'Fix Cyclist skipping haps during triggered increases in cps' (#2103) from tzwaan/fix-cyclist-cps into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2103
2026-10-15 23:49:48 +02:00
tyow 0ecf60f751 fix #2143 2026-10-15 17:34:22 -04:00
froos 73c57f0f9d Merge pull request 'fix(website): add webaudiofontdata URL to PWA runtime caching' (#2080) from gregocham/strudel:fix/cache-soundfonts-2068 into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2080
2026-10-15 21:56:12 +02:00
Felix Roos cc8c9f1c26 Merge remote-tracking branch 'origin/main' into fix/cache-soundfonts-2068 2026-10-15 21:53:06 +02:00
Felix Roos bcec4695a0 codeformat 2026-10-15 21:52:57 +02:00
froos e782debc15 Merge pull request 'Bug fix: Remove left-over widget id line from block-based evals' (#2150) from glossing/pianoroll-bug into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2150
2026-10-15 21:41:44 +02:00
Aria 459768af2a Bug fix: Remove left-over widget id line from block-based evals 2026-10-15 14:01:28 -05:00
froos 173a1654c8 Merge pull request 'fix hs2js + tidal package' (#2149) from fix-tidal-package into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2149
2026-10-15 17:32:01 +02:00
Felix Roos dedd687a1f Merge remote-tracking branch 'origin/main' into fix-tidal-package 2026-10-15 16:12:59 +02:00
alex be3422c5e6 snapshot new examples 2026-10-15 14:10:39 +01:00
froos 6abb9f85a8 Merge pull request 'remove supradough' (#2147) from remove-supradough into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2147
2026-10-15 15:07:11 +02:00
Felix Roos 4f3ba01afc fix snapshots 2026-10-15 15:01:10 +02:00
alex 382d5df933 Add open and close signals 2026-10-15 13:58:24 +01:00
Felix Roos f440d7869c remove supradough 2026-10-15 14:57:59 +02:00
froos 2e47716d23 Merge pull request 'Revert "Merge pull request 'Repurpose vim shortcuts for usability' (#1624) from dtricks/strudel:feat/vim-shortcuts into main"' (#2145) from unmerge-1624 into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2145
2026-10-15 14:15:05 +02:00
Felix Roos 0ffeb14c58 Merge remote-tracking branch 'origin/main' into unmerge-1624 2026-10-15 14:09:43 +02:00
froos 73b3982b69 Merge pull request 'revert #1821 helix keybindings pr' (#2142) from helix-unmerge into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2142
2026-10-15 14:04:44 +02:00
Felix Roos a18c2b6b80 Merge remote-tracking branch 'origin/main' into helix-unmerge 2026-10-15 14:00:23 +02:00
froos c9b32ec38b Merge pull request 'Revert "Merge pull request 'feature/autocomplete-sound-names' (#1564) from drdozer/strudel:feature/autocomplete-sound-names into main"' (#2144) from unmerge-autocomplete into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2144
2026-10-15 12:12:30 +02:00
froos d3325a2f82 Merge pull request 'revert experimental block-based evaluation' (#2141) from hirnsalat/strudel:unslop into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2141
2026-10-15 10:31:59 +02:00
Felix Roos a2af0cd5cc Revert "Merge pull request 'Repurpose vim shortcuts for usability' (#1624) from dtricks/strudel:feat/vim-shortcuts into main"
This reverts commit 12204c9053, reversing
changes made to f2009a33aa.
2026-10-14 23:10:29 +02:00
Felix Roos 56b279d723 Revert "Merge pull request 'feature/autocomplete-sound-names' (#1564) from drdozer/strudel:feature/autocomplete-sound-names into main"
This reverts commit 98f5a56ef6, reversing
changes made to c727534d29.
2026-10-14 22:40:37 +02:00
Felix Roos 32cccda215 revert #1821 helix keybindings pr 2026-10-14 22:00:06 +02:00
Felix Roos d7b4c6e498 revert line 2026-10-14 21:22:35 +02:00
Tijmen Zwaan 13d404613c Fix after rebase 2026-10-14 21:21:26 +02:00
Tijmen Zwaan f54a1f07d2 Fix the lastEnd not being correct when cps slowed down 2026-10-14 21:21:26 +02:00
Tijmen Zwaan 44e371c99d Fix cps haps sort order being reversed 2026-10-14 21:21:26 +02:00
Tijmen Zwaan c8d0342ecb Slightly more correct sorting of haps for cps changes 2026-10-14 21:21:26 +02:00
Tijmen Zwaan 096e53690f Fix Cyclist skipping haps during triggered increases in cps 2026-10-14 21:21:25 +02:00
Felix Roos dd8d04dc5c fix merge error 2026-10-14 21:16:52 +02:00
hirnsalat 1a52eb4515 revert applyPatternTransformations extraction 2026-10-14 19:42:17 +02:00
hirnsalat 196115a9da fix slider 2026-10-14 19:32:54 +02:00
hirnsalat 3d6f4cf32b Merge branch 'main' into unslop 2026-10-14 19:05:03 +02:00
hirnsalat 2ebf9f7103 Revert "Merge pull request 'block based eval' (#1714) from Dsm0/strudel:block-based-eval-squashed into main"
This reverts commit 70be560a7a, reversing
changes made to 98d613fbdf.
2026-10-14 19:02:33 +02:00
froos a3302cf167 Merge pull request 'dough update' (#2115) from dough-update into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2115
2026-10-13 21:12:47 +02:00
Felix Roos d385ceba39 fix tidal package wasm url for vite build 2026-10-12 18:28:41 +02:00
dtricks 8408af21a6 link font size to global setting 2026-09-17 13:18:44 +02:00
dtricks b1bb29e040 add print widget and docs 2026-09-17 13:03:21 +02:00
karolinaskg e3e3cdfcfc fix(website): add webaudiofontdata URL to PWA runtime caching 2026-06-30 23:39:43 +03:00
alex 9dc19fb9bf Merge branch 'main' into busparts 2025-10-30 21:37:48 +00:00
alex 4a158db9d2 Revert "state twiddles wip"
This reverts commit 55839e7ee8.
2025-10-30 21:28:58 +00:00
alex 55839e7ee8 state twiddles wip 2025-10-26 21:14:11 +00:00
alex 9aaa9bee6b fixes + tidying 2025-10-24 20:51:12 +01:00
alex 1834d689ef fixes + tidying 2025-10-24 20:48:35 +01:00
Alex McLean 77a7a148f0 wip 2025-10-23 21:26:27 +01:00
Alex McLean 52931e879d nearly there 2025-10-23 16:18:47 +01:00
Alex McLean d5c9be1c30 add _processParts() 2025-10-23 15:14:22 +01:00
Alex McLean 2b30ab3008 Merge branch 'main' of ssh://codeberg.org/uzu/strudel into busparts 2025-10-23 14:59:07 +01:00
Alex McLean 13cbeb3f67 wip 2025-10-23 14:58:57 +01:00
alex 352d8659ec wip 2025-10-23 14:02:41 +01:00
153 changed files with 3006 additions and 4932 deletions
+4 -14
View File
@@ -44,20 +44,7 @@ Dirt-Samples
tidal-drum-machines
webaudiofontdata
src-tauri/target
### BEGIN Visual Studio Code ###
# Blanket, recursive exclude for .vscode directory and files
.vscode/**/*
# Unexclude specific files and directories within .vscode
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
### END Visual Studio Code ###
mise.local.toml
# BEGIN JetBrains -> END JetBrains
@@ -145,3 +132,6 @@ fabric.properties
samples/*
!samples/README.md
.idea/
.vscode
!settings.json
+23
View File
@@ -0,0 +1,23 @@
In line with [our humane policy](POLICY.md#post-ai-humane-policy-for-live-coding-development), code and documentation
should not be written by LLM agents. To this end, agents should not
edit the codebase or make any commits that are intended to be
contributed upstream. Likewise, LLM output should not be pasted into
issues, comments, pull requests and so on.
A contributor's personal use of LLMs and related technology is their
own business, whether for research, analysis, bug discovery or other
assistive technology, so long as the output is not included in any
contributions to our projects.
Strudel is [AGPL licensed](LICENSE), and so any code integrated with it also
comes under that license. This should be carefully considered before
distributing software integrated with strudel, including making it
available over a network.
Strudel has purposefully moved away from github.com, as a closed
source platform with ethical issues. Please do not fork strudel back
to that platform, or similar corporate platforms.
Projects using strudel must not use "strudel" in their name, unless
they are 'official' projects, or have the blessing of the strudel
community.
+7 -6
View File
@@ -2,6 +2,10 @@
Thanks for wanting to contribute!!! There are many ways you can add value to this project
## Humane interaction
Please read [POLICY.md](POLICY.md) for important details of our Code of Conduct, and policy around AI/LLM use.
## Move to codeberg
Along with many other live coding projects, we have moved from Microsoft's Github platform to Codeberg for ethical reasons. Please don't fork the project back to github.
@@ -34,7 +38,7 @@ Use one of the Communication Channels listed above.
## Improve the Docs
If you find some weak spots in the [docs](https://strudel.cc/workshop/getting-started/), you can edit each file directly on codeberg. There are "Edit this page" links in the right sidebar that take you to the right place.
If you find some weak spots in the [docs](https://strudel.cc/workshop/getting-started/), you can edit each file directly on codeberg. There are "Edit this page" links in the right sidebar that take you to the right place. If you're unfamiliar with codeberg/git, please ask questions.
## Propose a Feature
@@ -48,11 +52,7 @@ At the time of writing we have a PR backlog, and generally prioritise bugfixes a
### AI/LLM policy
Strudel is a project handmade by humans, with thought and nuance.
If you have used LLMs (so called 'AI'), please detail that in the pull request. We are still developing our response to the onslaught of LLM technology, but for practical and legal reasons are currently not accepting wholly LLM-generated code. We are also not accepting PRs that add LLM features to strudel itself.
There are #llm-chat and #llm-share channels on [our discord](https://discord.com/invite/HGEdXmRkzT). Please do not discuss or share LLM-related things outside of those channels.
Strudel is a project handmade by humans, with thought and nuance. See [Policy](POLICY.md) for our policy on LLM use.
## Creating and sharing a new project using strudel
@@ -254,3 +254,4 @@ ORDER BY created_at ASC;
## Have Fun
Remember to have fun, and that this project is driven by the passion of volunteers!
+41
View File
@@ -0,0 +1,41 @@
# Code of Conduct
## The Short Version
We are dedicated to providing a harassment-free experience for everyone, regardless of gender, gender identity and expression, age, sexual orientation, disability, physical appearance, body size, race, ethnicity, religion (or lack thereof), technology choices, and so on. This applies both in person or via online media.
## The Less Short Version
Harassment includes offensive verbal comments related to gender, gender identity and expression, age, sexual orientation, disability, physical appearance, body size, race, ethnicity, religion, technology choices, deliberate intimidation, stalking, following, disruption of performances, inappropriate physical contact, and unwelcome sexual attention.
If you are being harassed, notice that someone else is being harassed, or have any other concerns, please contact an admin immediately.
If you report an incident of harassment you can expect to be listened to and taken seriously. The admin will take action they deem appropriate in response depending on the scale and severity of the incident. For example:
1. Discuss the perpetrator's behaviour with them and ask them to stop. Explain what they have done and why it is unacceptable. Remind the perpetrator of the code of conduct. Monitor the perpetrator's behaviour and if it improves then they will continue to be welcome.
2. Temporarily exclude the perpetrator from the forum for a cool-off period. Explain what they have done and why it is unacceptable and remind them of the code of conduct. Monitor the person's behaviour and if it improves then they will continue to be welcome.
3. Remove the perpetrator from the forum. Explain what they have done and why it is unacceptable and remind them of the code of conduct.
# Post-AI humane policy for live coding development
Please follow the following policy on AI/LLM use.
## Community
All community members should be treated with respect and kindness. We welcome contributors to the community who are ready to follow this policy as well as the above code of conduct.
## Principles
* We wish to protect the humanity of our communities and projects, to support the motivation and well-being of all of its contributors and users.
* To this end, contributors and other users of our projects should not have to engage with LLM-generated code and text as part of their community work.
* We recognise that LLM-based scraping and generation of (A)GPL code shared by ourselves and others is of questionable legality. For example, under many juristictions, LLM-generated work does not have a copyright holder and can therefore not be licensed under the (A)GPL.
* A contributor's personal use of LLMs and related technology is their own business, whether for research, analysis, bug discovery or other assistive technology, so long as the output is not included in any contributions to our projects.
## In practice
* Contributions including LLM-generated content will be declined.
* LLM-generated text (e.g. commit messages, issue comments, forum posts etc) generated by LLMs will be flagged, and ultimately deleted.
* We encourage asking each other questions and working through problems to promote collective knowledge and creative ideas (never telling each other to "just google it").
* We strongly discourage others from forking/importing our projects into corporate AI platforms, including Microsoft Github.
* All contributions must be submitted by a person who understands the changes, is happy to answer questions about them, and where possible, help maintain the code in the future.
* In community discussion channels (at the time of writing, this refers to the uzu discord server), all discussion (including criticism) of LLM technology and use should be kept to designated channels.
+5 -3
View File
@@ -41,12 +41,14 @@ Licensing info for the default sound banks can be found over on the [dough-sampl
There are many ways to contribute to this project! See [contribution guide](./CONTRIBUTING.md). You can find the full list of contributors [here](https://codeberg.org/uzu/strudel/activity/contributors).
Please see [POLICY.md](POLICY.md) for our code of conduct and humane AI/LLM policy.
## Community
There is a #strudel channel on the TidalCycles discord: <https://discord.com/invite/HGEdXmRkzT>
Strudel is a member of the 'Uzu' family of pattern-based live coding languages, along with TidalCycles and friends.
You can also ask questions and find related discussions on the tidal club forum: <https://club.tidalcycles.org/>
There are a range of strudel channels on the Uzu discord: <https://discord.com/invite/HGEdXmRkzT>
The discord and forum is shared with the haskell (tidal) and python (vortex) siblings of this project.
You can also ask questions and find related discussions on the Uzu web forum: <https://uzu.lurk.org/>
We also have a mastodon account: <a rel="me" href="https://social.toplap.org/@strudel">social.toplap.org/@strudel</a>
+36 -1
View File
@@ -5,6 +5,7 @@ import path from 'node:path';
import { fileURLToPath } from 'node:url';
import js from '@eslint/js';
import { FlatCompat } from '@eslint/eslintrc';
import { jsdoc } from 'eslint-plugin-jsdoc';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
@@ -42,7 +43,6 @@ export default [
'**/hydra.mjs',
'**/jsdoc-synonyms.js',
'packages/hs2js/src/hs2js.mjs',
'packages/supradough/dough-export.mjs',
'**/samples',
],
},
@@ -94,4 +94,39 @@ export default [
},
},
},
jsdoc({
config: 'flat/recommended-error',
rules: {
'jsdoc/no-undefined-types': [
'error',
{ definedTypes: ['Pattern', 'Pattern.prototype', 'Hap', 'KabelsalatExpression'] },
],
'jsdoc/check-tag-names': ['error', { definedTags: ['tags', 'synonyms', 'noAutocomplete', 'superdirtOnly'] }],
'jsdoc/no-restricted-syntax': [
'error',
{
contexts: [
{
//@memberof without a .prototype
comment:
'JsdocBlock:has(JsdocTag[tag="memberof"]:not([name=/\\.prototype(?:\\s|$)/]):not([description=/\\.prototype(?:\\s|$)/]))',
context: 'any',
message: "Use '@memberof <Name>.prototype'. Without, it's considered a static function.",
},
],
},
],
'jsdoc/require-description': 'error',
'jsdoc/no-defaults': 0, //removes defaults with not alternative
'jsdoc/require-jsdoc': 0,
'jsdoc/tag-lines': 0,
'jsdoc/require-returns-description': 0,
'jsdoc/require-param-description': 0,
'jsdoc/no-multi-asterisks': 0,
'jsdoc/multiline-blocks': 0,
'jsdoc/check-alignment': 0,
'jsdoc/reject-any-type': 0,
'jsdoc/reject-function-type': 0,
},
}),
];
+5 -2
View File
@@ -3,9 +3,12 @@
"includePattern": ".+\\.(js(doc|x)?|mjs)$",
"excludePattern": "node_modules|shift-parser|shift-reducer|shift-traverser|dist"
},
"plugins": ["plugins/markdown", "jsdoc/jsdoc-synonyms"],
"plugins": [
"plugins/markdown",
"jsdoc/jsdoc-synonyms"
],
"opts": {
"destination": "./out/",
"recurse": true
}
}
}
+3 -2
View File
@@ -67,14 +67,15 @@
"dependency-tree": "^11.0.1",
"eslint": "^9.19.0",
"eslint-plugin-import": "^2.31.0",
"eslint-plugin-jsdoc": "^65.5.3",
"events": "^3.3.0",
"globals": "^15.14.0",
"jsdoc": "^4.0.4",
"jsdoc-json": "^2.0.2",
"lerna": "^8.1.9",
"prettier": "^3.4.2",
"vitest": "^3.0.4",
"vite-plugin-bundle-audioworklet": "workspace:*"
"vite-plugin-bundle-audioworklet": "workspace:*",
"vitest": "^3.0.4"
},
"engines": {
"node": ">=18.0.0"
+12 -344
View File
@@ -1,11 +1,6 @@
import jsdoc from '../../doc.json';
import { autocompletion } from '@codemirror/autocomplete';
import { h } from './html';
//TODO: fix tonal scale import
// import { Scale } from '@tonaljs/tonal';
// import { soundMap } from '@strudel/webaudio';
let soundMap = undefined;
import { complex } from '@strudel/tonal';
const escapeHtml = (str) => {
const div = document.createElement('div');
@@ -80,53 +75,6 @@ const isValidDoc = (doc) => {
const hasExcludedTags = (doc) =>
['superdirtOnly', 'noAutocomplete'].some((tag) => doc.tags?.find((t) => t.originalTitle === tag));
export function bankCompletions() {
// TODO: FIX IMPORT
const soundDict = soundMap?.get() ?? {};
const banks = new Set();
for (const key of Object.keys(soundDict)) {
const [bank, suffix] = key.split('_');
if (suffix && bank) banks.add(bank);
}
return Array.from(banks)
.sort()
.map((name) => ({ label: name, type: 'bank' }));
}
// Attempt to get all scale names from Tonal TODO: FIX IMPORT
let scaleCompletions = [];
// try {
// scaleCompletions = (Scale.names ? Scale.names() : []).map((name) => ({ label: name, type: 'scale' }));
// } catch (e) {
// console.warn('[autocomplete] Could not load scale names from Tonal:', e);
// }
// Valid mode values for voicing
const modeCompletions = [
{ label: 'below', type: 'mode' },
{ label: 'above', type: 'mode' },
{ label: 'duck', type: 'mode' },
{ label: 'root', type: 'mode' },
];
// Valid chord symbols from ireal dictionary plus empty string for major triads
const chordSymbols = ['', ...Object.keys(complex)].sort();
const chordSymbolCompletions = chordSymbols.map((symbol) => {
if (symbol === '') {
return {
label: 'major',
apply: '',
type: 'chord-symbol',
};
}
return {
label: symbol,
apply: symbol,
type: 'chord-symbol',
};
});
export const getSynonymDoc = (doc, synonym) => {
const synonyms = doc.synonyms || [];
const docLabel = getDocLabel(doc);
@@ -165,299 +113,19 @@ const jsdocCompletions = (() => {
return completions;
})();
// --- Handler functions for each context ---
const pitchNames = [
'C',
'C#',
'Db',
'D',
'D#',
'Eb',
'E',
'E#',
'Fb',
'F',
'F#',
'Gb',
'G',
'G#',
'Ab',
'A',
'A#',
'Bb',
'B',
'B#',
'Cb',
];
// Cached regex patterns for scaleHandler
const SCALE_NO_QUOTES_REGEX = /scale\(\s*$/;
const SCALE_AFTER_COLON_REGEX = /scale\(\s*['"][^'"]*:[^'"]*$/;
const SCALE_PRE_COLON_REGEX = /scale\(\s*['"][^'"]*$/;
const SCALE_PITCH_MATCH_REGEX = /([A-Ga-g][#b]*)?$/;
const SCALE_SPACES_TO_COLON_REGEX = /\s+/g;
function scaleHandler(context) {
// First check for scale context without quotes - block with empty completions
let scaleNoQuotesContext = context.matchBefore(SCALE_NO_QUOTES_REGEX);
if (scaleNoQuotesContext) {
return {
from: scaleNoQuotesContext.to,
options: [],
};
}
// Check for after-colon context first (more specific)
let scaleAfterColonContext = context.matchBefore(SCALE_AFTER_COLON_REGEX);
if (scaleAfterColonContext) {
const text = scaleAfterColonContext.text;
const colonIdx = text.lastIndexOf(':');
if (colonIdx !== -1) {
const fragment = text.slice(colonIdx + 1);
const filteredScales = scaleCompletions.filter((s) => s.label.startsWith(fragment));
const options = filteredScales.map((s) => ({
...s,
apply: s.label.replace(SCALE_SPACES_TO_COLON_REGEX, ':'),
}));
const from = scaleAfterColonContext.from + colonIdx + 1;
return {
from,
options,
};
}
}
// Then check for pre-colon context
let scalePreColonContext = context.matchBefore(SCALE_PRE_COLON_REGEX);
if (scalePreColonContext) {
if (!scalePreColonContext.text.includes(':')) {
if (context.explicit) {
const text = scalePreColonContext.text;
const match = text.match(SCALE_PITCH_MATCH_REGEX);
const fragment = match ? match[0] : '';
const filtered = pitchNames.filter((p) => p.toLowerCase().startsWith(fragment.toLowerCase()));
const from = scalePreColonContext.to - fragment.length;
const options = filtered.map((p) => ({ label: p, type: 'pitch' }));
return { from, options };
} else {
return { from: scalePreColonContext.to, options: [] };
}
}
}
return null;
}
// Cached regex patterns for soundHandler
const SOUND_NO_QUOTES_REGEX = /(s|sound)\(\s*$/;
const SOUND_WITH_QUOTES_REGEX = /(s|sound)\(\s*['"][^'"]*$/;
const SOUND_FRAGMENT_MATCH_REGEX = /(?:[\s[{(<])([\w]*)$/;
function soundHandler(context) {
// First check for sound context without quotes - block with empty completions
let soundNoQuotesContext = context.matchBefore(SOUND_NO_QUOTES_REGEX);
if (soundNoQuotesContext) {
return {
from: soundNoQuotesContext.to,
options: [],
};
}
// Then check for sound context with quotes - provide completions
let soundContext = context.matchBefore(SOUND_WITH_QUOTES_REGEX);
if (!soundContext) return null;
const text = soundContext.text;
const quoteIdx = Math.max(text.lastIndexOf('"'), text.lastIndexOf("'"));
if (quoteIdx === -1) return null;
const inside = text.slice(quoteIdx + 1);
const fragMatch = inside.match(SOUND_FRAGMENT_MATCH_REGEX);
const fragment = fragMatch ? fragMatch[1] : inside;
const soundNames = Object.keys(soundMap?.get() ?? {}).sort();
const filteredSounds = soundNames.filter((name) => name.includes(fragment));
let options = filteredSounds.map((name) => ({ label: name, type: 'sound' }));
const from = soundContext.to - fragment.length;
return {
from,
options,
};
}
// Cached regex patterns for bankHandler
const BANK_NO_QUOTES_REGEX = /bank\(\s*$/;
const BANK_WITH_QUOTES_REGEX = /bank\(\s*['"][^'"]*$/;
function bankHandler(context) {
// First check for bank context without quotes - block with empty completions
let bankNoQuotesContext = context.matchBefore(BANK_NO_QUOTES_REGEX);
if (bankNoQuotesContext) {
return {
from: bankNoQuotesContext.to,
options: [],
};
}
// Then check for bank context with quotes - provide completions
let bankMatch = context.matchBefore(BANK_WITH_QUOTES_REGEX);
if (!bankMatch) return null;
const text = bankMatch.text;
const quoteIdx = Math.max(text.lastIndexOf('"'), text.lastIndexOf("'"));
if (quoteIdx === -1) return null;
const inside = text.slice(quoteIdx + 1);
const fragment = inside;
let banks = bankCompletions();
const filteredBanks = banks.filter((b) => b.label.startsWith(fragment));
const from = bankMatch.to - fragment.length;
return {
from,
options: filteredBanks,
};
}
// Cached regex patterns for modeHandler
const MODE_NO_QUOTES_REGEX = /mode\(\s*$/;
const MODE_AFTER_COLON_REGEX = /mode\(\s*['"][^'"]*:[^'"]*$/;
const MODE_PRE_COLON_REGEX = /mode\(\s*['"][^'"]*$/;
const MODE_FRAGMENT_MATCH_REGEX = /(?:[\s[{(<])([\w:]*)$/;
function modeHandler(context) {
// First check for mode context without quotes - block with empty completions
let modeNoQuotesContext = context.matchBefore(MODE_NO_QUOTES_REGEX);
if (modeNoQuotesContext) {
return {
from: modeNoQuotesContext.to,
options: [],
};
}
// Check for after-colon context first (more specific)
let modeAfterColonContext = context.matchBefore(MODE_AFTER_COLON_REGEX);
if (modeAfterColonContext) {
const text = modeAfterColonContext.text;
const colonIdx = text.lastIndexOf(':');
if (colonIdx !== -1) {
const fragment = text.slice(colonIdx + 1);
// For anchor after colon, we can suggest pitch names
const filtered = pitchNames.filter((p) => p.toLowerCase().startsWith(fragment.toLowerCase()));
const options = filtered.map((p) => ({ label: p, type: 'pitch' }));
const from = modeAfterColonContext.from + colonIdx + 1;
return {
from,
options,
};
}
}
// Then check for pre-colon context
let modeContext = context.matchBefore(MODE_PRE_COLON_REGEX);
if (!modeContext) return null;
const text = modeContext.text;
const quoteIdx = Math.max(text.lastIndexOf('"'), text.lastIndexOf("'"));
if (quoteIdx === -1) return null;
const inside = text.slice(quoteIdx + 1);
const fragMatch = inside.match(MODE_FRAGMENT_MATCH_REGEX);
const fragment = fragMatch ? fragMatch[1] : inside;
const filteredModes = modeCompletions.filter((m) => m.label.startsWith(fragment));
const from = modeContext.to - fragment.length;
return {
from,
options: filteredModes,
};
}
// Cached regex patterns for chordHandler
const CHORD_NO_QUOTES_REGEX = /chord\(\s*$/;
const CHORD_WITH_QUOTES_REGEX = /chord\(\s*['"][^'"]*$/;
const CHORD_FRAGMENT_MATCH_REGEX = /(?:[\s[{(<])([\w#b+^:-]*)$/;
function chordHandler(context) {
// First check for chord context without quotes - block with empty completions
let chordNoQuotesContext = context.matchBefore(CHORD_NO_QUOTES_REGEX);
if (chordNoQuotesContext) {
return {
from: chordNoQuotesContext.to,
options: [],
};
}
// Then check for chord context with quotes - provide completions
let chordContext = context.matchBefore(CHORD_WITH_QUOTES_REGEX);
if (!chordContext) return null;
const text = chordContext.text;
const quoteIdx = Math.max(text.lastIndexOf('"'), text.lastIndexOf("'"));
if (quoteIdx === -1) return null;
const inside = text.slice(quoteIdx + 1);
// Use same fragment matching as sound/mode for expressions like "<G Am>"
const fragMatch = inside.match(CHORD_FRAGMENT_MATCH_REGEX);
const fragment = fragMatch ? fragMatch[1] : inside;
// Check if fragment contains any pitch name at start (for root + symbol)
let rootMatch = null;
let symbolFragment = fragment;
for (const pitch of pitchNames) {
if (fragment.toLowerCase().startsWith(pitch.toLowerCase())) {
rootMatch = pitch;
symbolFragment = fragment.slice(pitch.length);
break;
}
}
if (rootMatch) {
// We have a root, now complete chord symbols
const filteredSymbols = chordSymbolCompletions.filter((s) =>
s.label.toLowerCase().startsWith(symbolFragment.toLowerCase()),
);
// Create completions that replace the entire chord, not just the symbol part
const options = filteredSymbols;
const from = chordContext.to - symbolFragment.length;
return { from, options };
} else {
// No root yet, complete with pitch names
const filteredPitches = pitchNames.filter((p) => p.toLowerCase().startsWith(fragment.toLowerCase()));
const options = filteredPitches.map((p) => ({ label: p, type: 'pitch' }));
const from = chordContext.to - fragment.length;
return { from, options };
}
}
// Cached regex patterns for fallbackHandler
const FALLBACK_WORD_REGEX = /\w*/;
function fallbackHandler(context) {
const word = context.matchBefore(FALLBACK_WORD_REGEX);
if (word && word.from === word.to && !context.explicit) return null;
if (word) {
return {
from: word.from,
options: jsdocCompletions,
};
}
return null;
}
const handlers = [
soundHandler,
bankHandler,
chordHandler,
scaleHandler,
modeHandler,
// this handler *must* be last
fallbackHandler,
];
export const strudelAutocomplete = (context) => {
for (const handler of handlers) {
const result = handler(context);
if (result) {
return result;
}
}
return null;
const word = context.matchBefore(/\w*/);
if (word.from === word.to && !context.explicit) return null;
return {
from: word.from,
options: jsdocCompletions,
/* options: [
{ label: 'match', type: 'keyword' },
{ label: 'hello', type: 'variable', info: '(World)' },
{ label: 'magic', type: 'text', apply: '⠁⭒*.✩.*⭒⠁', detail: 'macro' },
], */
};
};
export const isAutoCompletionEnabled = (enabled) =>
-51
View File
@@ -1,51 +0,0 @@
// Block-based evaluation utilities
export function getBlockRegions(code) {
const chars = code.split('');
let i = 0,
blanks = [],
blockStart = 0,
regions = [];
while (i < chars.length) {
const isBlank = chars[i] === '\n';
if (isBlank) {
blanks.push(i);
} else if (chars[i].trim() !== '') {
if (blanks.length > 1) {
regions.push([blockStart, blanks[0]]);
blockStart = i;
}
blanks = [];
}
i++;
}
regions.push([blockStart, blanks.length ? blanks[0] : i]);
return regions;
}
export function getBlockAt(code, cursor) {
const regions = getBlockRegions(code);
for (const [start, end] of regions) {
if (cursor >= start && cursor <= end) {
return [start, end];
}
}
return null;
}
export const evalBlock = (strudelMirror) => {
const { state } = strudelMirror.editor;
const code = state.doc.toString();
const cursor = state.selection.main.head;
const range = getBlockAt(code, cursor);
if (range) {
const [a, b] = range;
const block = code.slice(a, b);
if (block) {
// Flash the block being evaluated
strudelMirror.flash(200, { from: a, to: b });
strudelMirror.repl.evaluateBlock(block, true, { range });
}
}
return true;
};
+21 -119
View File
@@ -1,5 +1,5 @@
import { closeBrackets } from '@codemirror/autocomplete';
import { indentWithTab, toggleLineComment } from '@codemirror/commands';
import { indentWithTab } from '@codemirror/commands';
import { javascript, javascriptLanguage } from '@codemirror/lang-javascript';
import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language';
import { Compartment, EditorState, Prec } from '@codemirror/state';
@@ -12,19 +12,19 @@ import {
lineNumbers,
} from '@codemirror/view';
import { persistentAtom } from '@nanostores/persistent';
import { logger, registerControl, repl } from '@strudel/core';
import { cleanupDraw, cleanupDrawContext, Drawer } from '@strudel/draw';
import { registerControl, repl } from '@strudel/core';
import { cleanupDraw, Drawer } from '@strudel/draw';
import { isAutoCompletionEnabled } from './autocomplete.mjs';
import { basicSetup } from './basicSetup.mjs';
import { evalBlock } from './block_utilities.mjs';
import { flash, isFlashEnabled } from './flash.mjs';
import { highlightMiniLocations, isPatternHighlightingEnabled, updateMiniLocations } from './highlight.mjs';
import { keybindings } from './keybindings.mjs';
import { jumpToCharacter } from './labelJump.mjs';
import { getSliderWidgets, sliderPlugin, updateSliderWidgets } from './slider.mjs';
import { editorActions, keybindings } from './keybindings.mjs';
import { sliderPlugin, updateSliderWidgets } from './slider.mjs';
import { activateTheme, initTheme, theme } from './themes.mjs';
import { isTooltipEnabled } from './tooltip.mjs';
import { getActiveWidgets, updateWidgets, widgetPlugin } from './widget.mjs';
import { updateWidgets, widgetPlugin } from './widget.mjs';
import { jumpToCharacter } from './labelJump.mjs';
export { toggleBlockComment, toggleBlockCommentByLine, toggleComment, toggleLineComment } from '@codemirror/commands';
@@ -64,7 +64,6 @@ export const defaultSettings = {
isLineWrappingEnabled: false,
isTabIndentationEnabled: false,
isMultiCursorEnabled: false,
isBlockBasedEvalEnabled: false,
theme: 'strudelTheme',
fontFamily: 'monospace',
fontSize: 18,
@@ -76,7 +75,7 @@ export const codemirrorSettings = persistentAtom('codemirror-settings', defaultS
});
// https://codemirror.net/docs/guide/
export function initEditor({ initialCode = '', onChange, onEvaluate, onStop, root, mondo, strudelMirror }) {
export function initEditor({ initialCode = '', onChange, onEvaluate, onStop, root, mondo }) {
const settings = codemirrorSettings.get();
const initialSettings = Object.keys(compartments).map((key) =>
compartments[key].of(extensions[key](parseBooleans(settings[key]))),
@@ -102,30 +101,16 @@ export function initEditor({ initialCode = '', onChange, onEvaluate, onStop, roo
syntaxHighlighting(defaultHighlightStyle),
EditorView.updateListener.of((v) => onChange(v)),
drawSelection({ cursorBlinkRate: 0 }),
editorActions.of({ onEvaluate, onStop }),
Prec.highest(
keymap.of([
{
key: 'Ctrl-Enter',
run: () => {
// issue with referencing settings, this works more reliably
if (strudelMirror?.isBlockBasedEvalEnabled) {
evalBlock(strudelMirror);
return true;
} else {
return onEvaluate?.();
}
},
run: () => onEvaluate?.(),
},
{
key: 'Alt-Enter',
run: () => {
if (strudelMirror?.isBlockBasedEvalEnabled) {
evalBlock(strudelMirror);
return true;
} else {
return onEvaluate?.();
}
},
run: () => onEvaluate?.(),
},
{
key: 'Ctrl-.',
@@ -187,7 +172,6 @@ export class StrudelMirror {
this.onDraw = onDraw || this.draw;
this.id = id || s4();
this.solo = solo;
this.isBlockBasedEvalEnabled = false; // Will be updated via updateSettings()
this.drawer = new Drawer((haps, time, _, painters) => {
const currentFrame = haps.filter((hap) => hap.isActive(time));
@@ -218,12 +202,8 @@ export class StrudelMirror {
cleanupDraw(true, id);
}
},
beforeEval: async ({ blockBased } = {}) => {
// Only clean up all drawings for full evaluation
// Block-based eval should preserve animations (like .scope()) from other blocks
if (!blockBased) {
cleanupDraw(true, id);
}
beforeEval: async () => {
cleanupDraw(true, id);
await this.prebaked;
await replOptions?.beforeEval?.();
},
@@ -233,13 +213,10 @@ export class StrudelMirror {
this.widgets = options.meta?.widgets || [];
const sliders = this.widgets.filter((w) => w.type === 'slider');
updateSliderWidgets(this.editor, sliders);
const widgets = this.widgets.filter((w) => w.type !== 'slider');
// range-aware update for block-based evaluation
const range = options.range && options.range.length >= 2 ? options.range : null;
updateSliderWidgets(this.editor, sliders, range);
updateWidgets(this.editor, widgets, range);
updateMiniLocations(this.editor, this.miniLocations, range);
updateWidgets(this.editor, widgets);
updateMiniLocations(this.editor, this.miniLocations);
replOptions?.afterEval?.(options);
// if no painters are set (.onPaint was not called), then we only need
// the present moment (for highlighting)
@@ -247,14 +224,8 @@ export class StrudelMirror {
this.drawer.setDrawTime(drawTime);
// invalidate drawer after we've set the appropriate drawTime
this.drawer.invalidate(this.repl.scheduler);
// Clean up draw context if a non-inline widget was removed
if (options.widgetRemoved) {
cleanupDrawContext(id);
}
},
});
this.cleanupDrawContext = () => cleanupDrawContext(id);
this.editor = initEditor({
root,
initialCode,
@@ -267,9 +238,7 @@ export class StrudelMirror {
onEvaluate: () => this.evaluate(),
onStop: () => this.stop(),
mondo: replOptions.mondo,
strudelMirror: this,
});
const cmEditor = this.root.querySelector('.cm-editor');
if (cmEditor) {
this.root.style.display = 'block';
@@ -289,39 +258,6 @@ export class StrudelMirror {
}
};
document.addEventListener('start-repl', this.onStartRepl);
// Handle global evaluation requests (e.g., from Vim :w)
this.onEvaluateRequest = (e) => {
try {
if (e.detail.view !== this.editor) {
return; // ignore events from other editors
}
// Evaluate current editor on repl-evaluate
logger('[repl] evaluate via event');
this.evaluate();
e?.cancelable && e.preventDefault?.();
} catch (err) {
console.error('Error handling repl-evaluate event', err);
}
};
document.addEventListener('repl-evaluate', this.onEvaluateRequest);
document.addEventListener('repl-stop', this.onStopRequest);
// Toggle comments requested from Vim (gc)
this.onToggleComment = (e) => {
try {
if (e.detail.view !== this.editor) {
return; // ignore events from other editors
}
// Honor selections; toggleLineComment handles both selections and
// single line
toggleLineComment(this.editor);
e?.cancelable && e.preventDefault?.();
} catch (err) {
console.error('Error handling repl-toggle-comment event', err);
}
};
document.addEventListener('repl-toggle-comment', this.onToggleComment);
}
draw(haps, time, painters) {
painters?.forEach((painter) => painter(this.drawContext, time, haps, this.drawTime));
@@ -345,23 +281,10 @@ export class StrudelMirror {
this.flash();
await this.repl.evaluate(this.code, autostart);
}
async stop() {
this.repl.stop();
this.repl.scheduler.stop();
}
// Listen for global stop requests (e.g., from Vim :q)
onStopRequest = (e) => {
try {
if (e.detail.view !== this.editor) {
return; // ignore events from other editors
}
this.stop();
e?.cancelable && e.preventDefault?.();
} catch (err) {
console.error('Error handling repl-stop event', err);
}
};
async toggle() {
if (this.repl.scheduler.started) {
this.repl.stop();
@@ -369,8 +292,8 @@ export class StrudelMirror {
this.evaluate();
}
}
flash(ms, range) {
flash(this.editor, ms, range);
flash(ms) {
flash(this.editor, ms);
}
highlight(haps, time) {
highlightMiniLocations(this.editor, time, haps);
@@ -402,10 +325,6 @@ export class StrudelMirror {
setLineWrappingEnabled(enabled) {
this.reconfigureExtension('isLineWrappingEnabled', enabled);
}
setBlockBasedEvalEnabled(enabled) {
this.reconfigureExtension('isBlockBasedEvalEnabled', enabled);
}
setBracketMatchingEnabled(enabled) {
this.reconfigureExtension('isBracketMatchingEnabled', enabled);
}
@@ -427,10 +346,6 @@ export class StrudelMirror {
for (let key in extensions) {
this.reconfigureExtension(key, settings[key]);
}
// Update block-based eval setting on the instance
if (settings.isBlockBasedEvalEnabled !== undefined) {
this.isBlockBasedEvalEnabled = parseBooleans(settings.isBlockBasedEvalEnabled);
}
const updated = { ...codemirrorSettings.get(), ...settings };
codemirrorSettings.set(updated);
}
@@ -454,21 +369,8 @@ export class StrudelMirror {
setCode(code) {
this.replaceCode(code, 0, this.editor.state.doc.length);
}
// used for debugging but could serve other purposes
getActiveWidgets() {
return getActiveWidgets(this.editor);
}
getSliderWidgets() {
return getSliderWidgets(this.editor);
}
getMiniLocations() {
return this.miniLocations;
}
clear() {
this.onStartRepl && document.removeEventListener('start-repl', this.onStartRepl);
this.onEvaluateRequest && document.removeEventListener('repl-evaluate', this.onEvaluateRequest);
this.onStopRequest && document.removeEventListener('repl-stop', this.onStopRequest);
this.onToggleComment && document.removeEventListener('repl-toggle-comment', this.onToggleComment);
}
getCursorLocation() {
return this.editor.state.selection.main.head;
@@ -497,7 +399,7 @@ function s4() {
/**
* Overrides the css of highlighted events. Make sure to use single quotes!
* @name markcss
* @tag visualization
* @tags visualization
* @example
* note("c a f e")
* .markcss('text-decoration:underline')
+3 -5
View File
@@ -14,8 +14,7 @@ export const flashField = StateField.define({
const mark = Decoration.mark({
attributes: { style: `background-color: rgba(255,255,255, .4); filter: invert(10%)` },
});
const range = e.value.range || { from: 0, to: tr.newDoc.length };
flash = Decoration.set([mark.range(range.from, range.to)]);
flash = Decoration.set([mark.range(0, tr.newDoc.length)]);
} else {
flash = Decoration.set([]);
}
@@ -30,9 +29,8 @@ export const flashField = StateField.define({
provide: (f) => EditorView.decorations.from(f),
});
export const flash = (view, ms = 200, range) => {
const flashData = range ? { range } : true;
view.dispatch({ effects: setFlash.of(flashData) });
export const flash = (view, ms = 200) => {
view.dispatch({ effects: setFlash.of(true) });
setTimeout(() => {
view.dispatch({ effects: setFlash.of(false) });
}, ms);
+60 -161
View File
@@ -3,9 +3,8 @@ import { Decoration, EditorView } from '@codemirror/view';
export const setMiniLocations = StateEffect.define();
export const showMiniLocations = StateEffect.define();
export const displayMiniLocations = StateEffect.define();
export const updateMiniLocations = (view, locations, range = null) => {
view.dispatch({ effects: setMiniLocations.of({ locations, range }) });
export const updateMiniLocations = (view, locations) => {
view.dispatch({ effects: setMiniLocations.of(locations) });
};
export const highlightMiniLocations = (view, atTime, haps) => {
view.dispatch({ effects: showMiniLocations.of({ atTime, haps }) });
@@ -22,54 +21,23 @@ const miniLocations = StateField.define({
for (let e of tr.effects) {
if (e.is(setMiniLocations)) {
//block-based eval case
if (e.value.range) {
const stateMiniLocations = getMiniLocationsFromDecorations(locations);
const normalized = e.value.locations
.filter(([from]) => from < tr.newDoc.length)
.map(([from, to]) => [from, Math.min(to, tr.newDoc.length)]);
const newIds = new Set(normalized.map((r) => r.join(':')));
const marks = normalized.map((range) => {
const id = range.join(':');
return Decoration.mark({
id,
// this green is only to verify that the decoration moves when the document is edited
// it will be removed later, so the mark is not visible by default
attributes: { style: `background-color: #00CA2880` },
}).range(...range); // -> Decoration
});
const previousMarks = stateMiniLocations
.filter(({ id }) => !newIds.has(id))
.map(({ from, to, id }) =>
// this is called on eval, with the mini locations obtained from the transpiler
// codemirror will automatically remap the marks when the document is edited
// create a mark for each mini location, adding the range to the spec to find it later
const marks = e.value
.filter(([from]) => from < tr.newDoc.length)
.map(([from, to]) => [from, Math.min(to, tr.newDoc.length)])
.map(
(range) =>
Decoration.mark({
id,
id: range.join(':'),
// this green is only to verify that the decoration moves when the document is edited
// it will be removed later, so the mark is not visible by default
attributes: { style: `background-color: #00CA2880` },
}).range(from, to),
);
}).range(...range), // -> Decoration
);
locations = Decoration.set(previousMarks.concat(marks), true); // -> DecorationSet === RangeSet<Decoration>
} else {
// this is called on eval, with the mini locations obtained from the transpiler
// codemirror will automatically remap the marks when the document is edited
// create a mark for each mini location, adding the range to the spec to find it later
const marks = e.value.locations
.filter(([from]) => from < tr.newDoc.length)
.map(([from, to]) => [from, Math.min(to, tr.newDoc.length)])
.map(
(range) =>
Decoration.mark({
id: range.join(':'),
// this green is only to verify that the decoration moves when the document is edited
// it will be removed later, so the mark is not visible by default
attributes: { style: `background-color: #00CA2880` },
}).range(...range), // -> Decoration
);
locations = Decoration.set(marks, true); // -> DecorationSet === RangeSet<Decoration>
}
locations = Decoration.set(marks, true); // -> DecorationSet === RangeSet<Decoration>
}
}
@@ -107,83 +75,12 @@ const visibleMiniLocations = StateField.define({
},
});
const displayMiniLocationsState = StateField.define({
create() {
return true; // default to showing miniLocations
},
update(display, tr) {
for (let e of tr.effects) {
if (e.is(displayMiniLocations)) {
display = e.value;
}
}
return display;
},
});
// // Derive the set of decorations from the miniLocations and visibleLocations
const miniLocationHighlights = EditorView.decorations.compute(
[miniLocations, visibleMiniLocations, displayMiniLocationsState],
(state) => {
// Check if miniLocations display is disabled
const shouldDisplay = state.field(displayMiniLocationsState);
if (!shouldDisplay) {
return Decoration.none; // Return empty decorations if display is disabled
}
const miniLocationHighlights = EditorView.decorations.compute([miniLocations, visibleMiniLocations], (state) => {
const iterator = state.field(miniLocations).iter();
const { haps } = state.field(visibleMiniLocations);
const builder = new RangeSetBuilder();
const iterator = state.field(miniLocations).iter();
const { haps } = state.field(visibleMiniLocations);
const builder = new RangeSetBuilder();
while (iterator.value) {
const {
from,
to,
value: {
spec: { id },
},
} = iterator;
if (haps.has(id)) {
const hap = haps.get(id);
const color = hap.value?.color ?? 'var(--foreground)';
const style = hap.value?.markcss || `outline: solid 2px ${color}`;
// Get explicit channels for color values
/*
const swatch = document.createElement('div');
swatch.style.color = color;
document.body.appendChild(swatch);
let channels = getComputedStyle(swatch)
.color.match(/^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*(\d*(?:\.\d+)?))?\)$/)
.slice(1)
.map((c) => parseFloat(c || 1));
document.body.removeChild(swatch);
// Get percentage of event
const percent = 1 - (atTime - hap.whole.begin) / hap.whole.duration;
channels[3] *= percent;
*/
builder.add(
from,
to,
Decoration.mark({
// attributes: { style: `outline: solid 2px rgba(${channels.join(', ')})` },
attributes: { style },
}),
);
}
iterator.next();
}
return builder.finish();
},
);
const getMiniLocationsFromDecorations = (decorations) => {
const iterator = decorations.iter();
const miniLocationsArray = [];
while (iterator.value) {
const {
from,
@@ -192,48 +89,50 @@ const getMiniLocationsFromDecorations = (decorations) => {
spec: { id },
},
} = iterator;
miniLocationsArray.push({
from,
to,
id,
});
if (haps.has(id)) {
const hap = haps.get(id);
const color = hap.value?.color ?? 'var(--foreground)';
const style = hap.value?.markcss || `outline: solid 2px ${color}`;
// Get explicit channels for color values
/*
const swatch = document.createElement('div');
swatch.style.color = color;
document.body.appendChild(swatch);
let channels = getComputedStyle(swatch)
.color.match(/^rgba?\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})(?:,\s*(\d*(?:\.\d+)?))?\)$/)
.slice(1)
.map((c) => parseFloat(c || 1));
document.body.removeChild(swatch);
// Get percentage of event
const percent = 1 - (atTime - hap.whole.begin) / hap.whole.duration;
channels[3] *= percent;
*/
builder.add(
from,
to,
Decoration.mark({
// attributes: { style: `outline: solid 2px rgba(${channels.join(', ')})` },
attributes: { style },
}),
);
}
iterator.next();
}
return miniLocationsArray;
};
export const getMiniLocations = (state) => {
const decorations = state.field(miniLocations);
return getMiniLocationsFromDecorations(decorations);
};
return builder.finish();
});
export const getActiveMiniLocations = (state) => {
const miniLocations = getMiniLocations(state);
const { haps } = state.field(visibleMiniLocations);
const activeMiniLocations = miniLocations.filter((location) => haps.has(location.id));
return activeMiniLocations;
};
export const highlightExtension = [
miniLocations,
visibleMiniLocations,
displayMiniLocationsState,
miniLocationHighlights,
];
export const highlightExtension = [miniLocations, visibleMiniLocations, miniLocationHighlights];
export const isPatternHighlightingEnabled = (on, config) => {
// NOTE:
// Modified this function to always return the highlightExtension, and instead just toggle whether or not the miniLocations are displayed.
// This is because block based evaluation only updates regions of miniLocations, and those updates need to be kept track of constantly.
// The setTimeout was also removed because it conflicted with the range-specific updates required by
// block based evaluation.
// Not sure if this is the best approach, but for block based eval I can't think of a better way to do it.
if (config) {
// Toggle the display state for miniLocations
config.editor.dispatch({ effects: displayMiniLocations.of(on) });
}
return Prec.highest(highlightExtension);
on &&
config &&
setTimeout(() => {
updateMiniLocations(config.editor, config.miniLocations);
}, 100);
return on ? Prec.highest(highlightExtension) : [];
};
+17 -160
View File
@@ -1,13 +1,14 @@
import { defaultKeymap } from '@codemirror/commands';
import { Prec, EditorState } from '@codemirror/state';
import { defaultKeymap, toggleLineComment } from '@codemirror/commands';
import { Facet, Prec, EditorState } from '@codemirror/state';
import { keymap, ViewPlugin } from '@codemirror/view';
// import { searchKeymap } from '@codemirror/search';
import { emacs } from '@replit/codemirror-emacs';
import { vim, Vim } from '@replit/codemirror-vim';
// import { vim } from './vim_test.mjs';
import { vscodeKeymap } from '@replit/codemirror-vscode-keymap';
import { helix, commands } from 'codemirror-helix';
import { logger } from '@strudel/core';
// Per-editor way to plumb down { onEvaluate, onStop }, provided by initEditor.
export const editorActions = Facet.define({ combine: (values) => values[0] ?? {} });
const vscodePlugin = ViewPlugin.fromClass(
class {
@@ -21,169 +22,25 @@ const vscodePlugin = ViewPlugin.fromClass(
);
const vscodeExtension = (options) => [vscodePlugin].concat(options ?? []);
function replEval(view) {
try {
// Dispatch a dedicated evaluate event first
let handled = false;
try {
const ev = new CustomEvent('repl-evaluate', { detail: { source: 'vim', view }, cancelable: true });
handled = document.dispatchEvent(ev) === false; // false means preventDefault was called
} catch (e) {
console.error('Error dispatching repl-evaluate event', e);
}
if (handled) {
return;
}
// Try Ctrl+Enter first if not handled by custom event
const ctrlEnter = new KeyboardEvent('keydown', {
key: 'Enter',
code: 'Enter',
ctrlKey: true,
bubbles: true,
cancelable: true,
});
view?.dom?.dispatchEvent?.(ctrlEnter);
// If not handled (no handler called preventDefault), try Alt+Enter as
// fallback
if (!ctrlEnter.defaultPrevented) {
const altEnter = new KeyboardEvent('keydown', {
key: 'Enter',
code: 'Enter',
altKey: true,
bubbles: true,
cancelable: true,
});
view?.dom?.dispatchEvent?.(altEnter);
}
} catch (e) {
console.error('Error dispatching repl evaluation event', e);
}
}
function replStop(view) {
try {
// First try dispatching our custom stop event, then fallback to Alt+.
let handled = false;
try {
const ev = new CustomEvent('repl-stop', { detail: { source: 'vim', view }, cancelable: true });
handled = document.dispatchEvent(ev) === false;
} catch (e) {
console.error('Error dispatching repl-stop event', e);
}
if (!handled) {
const altDot = new KeyboardEvent('keydown', {
key: '.',
code: 'Period',
altKey: true,
bubbles: true,
cancelable: true,
});
view?.dom?.dispatchEvent?.(altDot);
}
} catch (e) {
console.error('Error dispatching repl stop event', e);
}
}
// Map Vim :w to trigger the same action as evaluation. We dispatch a custom
// event 'repl-evaluate' that the editor listens for, and also simulate
// Ctrl+Enter/Alt+Enter as a fallback. We log to the Strudel logger so it
// appears in the Console panel.
try {
if (Vim && typeof Vim.defineEx === 'function') {
// Map gc to toggle line comments by dispatching a custom event that our
// CodeMirror integration listens to. This avoids depending on Vim's
// internal actions and works with current selections/visual mode.
try {
Vim.defineAction('strudelToggleComment', (cm) => {
const view = cm.cm6;
try {
const ev = new CustomEvent('repl-toggle-comment', { detail: { source: 'vim', view }, cancelable: true });
document.dispatchEvent(ev);
} catch (e) {
console.error('strudelToggleComment dispatch failed', e);
}
});
Vim.mapCommand('gc', 'action', 'strudelToggleComment', {}, { context: 'normal' });
Vim.mapCommand('gc', 'action', 'strudelToggleComment', {}, { context: 'visual' });
} catch (e) {
console.error('Vim gc mapping failed', e);
}
// :q to pause/stop
Vim.defineEx('quit', 'q', (cm) => {
const view = cm.cm6;
logger('[vim] :q — stopping repl');
replStop(view);
});
// :w to evaluate
Vim.defineEx('write', 'w', (cm) => {
const view = cm.cm6;
try {
view.focus?.();
// Let the app know this came from Vim :w
try {
logger('[vim] :w — evaluating code');
} catch (e) {
console.error('Error logging Vim :w evaluation', e);
}
replEval(view);
} catch (e) {
console.error('Error dispatching :w evaluation event', e);
}
});
}
} catch (e) {
console.error('Vim ex command setup failed (defineEx missing or Vim unavailable)', e);
}
// Map Helix :w to trigger the same action as evaluation. We dispatch a custom
// event 'repl-evaluate' that the editor listens for, and also simulate
// Ctrl+Enter/Alt+Enter as a fallback. We log to the Strudel logger so it
// appears in the Console panel.
const helixCommands = commands.of([
{
// :w to evaluate
name: 'write',
aliases: ['w'],
help: 'Repl-eval',
handler(view, args) {
try {
view?.focus?.(); // Let the app know this came from Helix :w
logger('[helix] :w — evaluating code');
replEval(view);
} catch (e) {
console.error('Error dispatching helix :w evaluation event', e);
}
},
},
{
// :q to pause/stop
name: 'quit',
aliases: ['q'],
help: 'Repl-stop',
handler(view, args) {
try {
view?.focus?.(); // Let the app know this came from Helix :q
logger('[helix] :q — stopping repl');
replStop(view);
} catch (e) {
console.error('Error dispatching helix :q stop event', e);
}
},
},
]);
const keymaps = {
vim,
emacs,
codemirror: () => keymap.of(defaultKeymap),
vscode: vscodeExtension,
helix: () => [helix(), helixCommands],
};
export { Vim } from '@replit/codemirror-vim';
export { Vim }; // export for patterns/prebake to define custom actions
Vim.defineEx('write', 'w', (cm) => cm.cm6.state.facet(editorActions).onEvaluate?.());
Vim.defineEx('quit', 'q', (cm) => cm.cm6.state.facet(editorActions).onStop?.());
Vim.defineOperator('toggleComment', (cm, _args, _ranges, oldAnchor) => {
// By the time an operator runs, vim has selected the motion's range in the
// real editor so we can just call the normal codemirror command
toggleLineComment(cm.cm6);
return oldAnchor;
});
Vim.mapCommand('gc', 'operator', 'toggleComment', {}, { isEdit: true });
export function keybindings(name) {
const active = keymaps[name];
+1 -5
View File
@@ -44,14 +44,10 @@
"@replit/codemirror-emacs": "^6.1.0",
"@replit/codemirror-vim": "^6.3.0",
"@replit/codemirror-vscode-keymap": "^6.0.2",
"codemirror-helix": "^0.5.0",
"@strudel/core": "workspace:*",
"@strudel/draw": "workspace:*",
"@strudel/tonal": "workspace:*",
"@strudel/transpiler": "workspace:*",
"@tonaljs/tonal": "^4.10.0",
"nanostores": "^0.11.3",
"superdough": "workspace:*"
"nanostores": "^0.11.3"
},
"devDependencies": {
"vite": "^6.0.11"
+22 -109
View File
@@ -2,11 +2,11 @@ import { ref, pure } from '@strudel/core';
import { WidgetType, ViewPlugin, Decoration } from '@codemirror/view';
import { StateEffect } from '@codemirror/state';
// Global state storage for all widget types
export let sliderValues = {};
const getSliderID = (from) => `slider_${from}`;
export class SliderWidget extends WidgetType {
constructor(value, min, max, from, to, step, view, id) {
constructor(value, min, max, from, to, step, view) {
super();
this.value = value;
this.min = min;
@@ -16,21 +16,10 @@ export class SliderWidget extends WidgetType {
this.to = to;
this.step = step;
this.view = view;
this.id = id || `${from}:${to}`; // Range-based ID for stability
}
eq(other) {
if (!(other instanceof SliderWidget)) {
return false;
}
return (
this.id === other.id &&
this.from === other.from &&
this.to === other.to &&
this.value === other.value &&
this.min === other.min &&
this.max === other.max
);
eq() {
return false;
}
toDOM() {
@@ -49,7 +38,6 @@ export class SliderWidget extends WidgetType {
slider.from = this.from;
slider.originalFrom = this.originalFrom;
slider.to = this.to;
slider.id = this.id; // Store range-based ID in DOM element
slider.style = 'width:64px;margin-right:4px;transform:translateY(4px)';
this.slider = slider;
slider.addEventListener('input', (e) => {
@@ -61,7 +49,7 @@ export class SliderWidget extends WidgetType {
slider.originalValue = insert;
slider.value = insert;
this.view.dispatch({ changes: change });
const id = slider.id; // Use range-based ID
const id = getSliderID(slider.originalFrom); // matches id generated in transpiler
window.postMessage({ type: 'cm-slider', value: Number(next), id });
});
return wrap;
@@ -74,60 +62,19 @@ export class SliderWidget extends WidgetType {
export const setSliderWidgets = StateEffect.define();
export const setSliderWidgetsInRange = StateEffect.define();
export const updateSliderWidgets = (view, widgets, range = null) => {
if (range) {
// range argument passed for block-based evaluation
view.dispatch({ effects: setSliderWidgetsInRange.of({ widgets, range }) });
} else {
view.dispatch({ effects: setSliderWidgets.of(widgets) });
}
export const updateSliderWidgets = (view, widgets) => {
view.dispatch({ effects: setSliderWidgets.of(widgets) });
};
function getSliders(widgetConfigs, view) {
return (
widgetConfigs
.filter((w) => w.type === 'slider')
// Deduplicate sliders that might appear multiple times (e.g., during paste operations)
.filter((slider, index, self) => index === self.findIndex((s) => s.from === slider.from && s.to === slider.to))
.sort((a, b) => a.from - b.from)
.map(({ from, to, value, min, max, step, id }) => {
return Decoration.widget({
widget: new SliderWidget(value, min, max, from, to, step, view, id),
side: 0,
}).range(from /* , to */);
})
);
}
export function getSliderWidgets(view) {
if (!view || !view.state) {
return [];
}
const sliderPluginInstance = view.plugin(sliderPlugin);
if (!sliderPluginInstance || !sliderPluginInstance.decorations) {
return [];
}
const sliderWidgets = [];
sliderPluginInstance.decorations.between(0, view.state.doc.length, (from, to, decoration) => {
if (decoration.widget instanceof SliderWidget) {
sliderWidgets.push({
type: 'slider',
from: decoration.widget.from,
to: decoration.widget.to,
value: decoration.widget.value,
min: decoration.widget.min,
max: decoration.widget.max,
step: decoration.widget.step,
});
}
});
return sliderWidgets;
return widgetConfigs
.filter((w) => w.type === 'slider')
.map(({ from, to, value, min, max, step }) => {
return Decoration.widget({
widget: new SliderWidget(value, min, max, from, to, step, view),
side: 0,
}).range(from /* , to */);
});
}
export const sliderPlugin = ViewPlugin.fromClass(
@@ -154,42 +101,7 @@ export const sliderPlugin = ViewPlugin.fromClass(
}
}
for (let e of tr.effects) {
if (e.is(setSliderWidgetsInRange)) {
// Block-aware slider update logic
const { widgets, range } = e.value;
const [rangeStart, rangeEnd] = range;
// Get existing slider widgets that should be preserved
const existingSliders = [];
this.decorations.between(0, update.view.state.doc.length, (from, to, decoration) => {
if (decoration.widget instanceof SliderWidget) {
// Preserve sliders outside the evaluation range
// Use strict > for rangeEnd because when code is deleted, slider positions
// map to the deletion boundary (rangeEnd), and those should be removed, not preserved
if (from < rangeStart || from > rangeEnd) {
existingSliders.push({
from,
to,
value: decoration.widget.value,
min: decoration.widget.min,
max: decoration.widget.max,
step: decoration.widget.step,
id: decoration.widget.id || `${from}:${to}`,
type: 'slider',
});
}
}
});
// Merge preserved sliders with new widgets
const mergedWidgets = [...existingSliders, ...widgets]
.filter(
(slider, index, self) => index === self.findIndex((s) => s.type === 'slider' && s.id === slider.id),
)
.sort((a, b) => a.from - b.from);
this.decorations = Decoration.set(getSliders(mergedWidgets, update.view));
} else if (e.is(setSliderWidgets)) {
if (e.is(setSliderWidgets)) {
this.decorations = Decoration.set(getSliders(e.value, update.view));
}
}
@@ -201,15 +113,17 @@ export const sliderPlugin = ViewPlugin.fromClass(
},
);
/* eslint jsdoc/check-param-names: "off" */
/**
* Displays a slider widget to allow the user manipulate a value
*
* @name slider
* @tags external_io, visualization
* @param {number} value Initial value
* @param {number} min Minimum value - optional, defaults to 0
* @param {number} max Maximum value - optional, defaults to 1
* @param {number} step Step size - optional
* @param {number} [min=0] Minimum value - optional, defaults to 0
* @param {number} [max=1] Maximum value - optional, defaults to 1
* @param {number} [step] Step size - optional
* @returns {Pattern}
*/
export let slider = (value) => {
console.warn('slider will only work when the transpiler is used... passing value as is');
@@ -220,7 +134,6 @@ export let sliderWithID = (id, value, min, max) => {
sliderValues[id] = value; // sync state at eval time (code -> state)
return ref(() => sliderValues[id]); // use state at query time
};
// update state when sliders are moved
if (typeof window !== 'undefined') {
window.addEventListener('message', (e) => {
@@ -229,7 +142,7 @@ if (typeof window !== 'undefined') {
// update state when slider is moved
sliderValues[e.data.id] = e.data.value;
} else {
console.error(`slider with id "${e.data.id}" is not registered. Only ${Object.keys(sliderValues)}`);
console.warn(`slider with id "${e.data.id}" is not registered. Only ${Object.keys(sliderValues)}`);
}
}
});
+77 -193
View File
@@ -1,111 +1,55 @@
import { StateEffect, StateField } from '@codemirror/state';
import { Decoration, EditorView, WidgetType, ViewPlugin } from '@codemirror/view';
import { Decoration, EditorView, WidgetType } from '@codemirror/view';
import { getWidgetID, registerWidgetType } from '@strudel/transpiler';
import { Pattern } from '@strudel/core';
export const setWidgets = StateEffect.define();
export const addWidget = StateEffect.define({
map: ({ from, to }, change) => {
return { from: change.mapPos(from), to: change.mapPos(to) };
},
});
export const setWidgetsInRange = StateEffect.define();
export const updateWidgets = (view, widgets, range = null) => {
if (range) {
// range argument passed for block-based evaluation
view.dispatch({ effects: setWidgetsInRange.of({ widgets, range }) });
} else {
view.dispatch({ effects: setWidgets.of(widgets) });
}
export const updateWidgets = (view, widgets) => {
view.dispatch({ effects: addWidget.of(widgets) });
};
function getWidgets(widgetConfigs, view) {
const filtered = widgetConfigs
// Filter to widget configs only (exclude sliders)
.filter((w) => w && w.type && w.type !== 'slider')
// Deduplicate widgets by ID, matching slider behavior for stable widget identity
.filter((widget, index, self) => index === self.findIndex((w) => w.type === widget.type && w.id === widget.id));
// Filter out widgets whose range is encompassed by another widget
// const nonEncompassed = filterEncompassedWidgets(filtered);
return filtered
.sort((a, b) => (a.to || 0) - (b.to || 0))
.map((widgetConfig) => {
try {
function getWidgets(widgetConfigs) {
return (
widgetConfigs
// codemirror throws an error if we don't sort
.sort((a, b) => a.to - b.to)
.map((widgetConfig) => {
return Decoration.widget({
widget: new BlockWidget(widgetConfig, view),
widget: new BlockWidget(widgetConfig),
side: 0,
}).range(widgetConfig.to || widgetConfig.from || 0);
} catch (error) {
console.error('error creating widget', error);
return null;
}
})
.filter(Boolean); // Remove any null results from failed creations
block: true,
}).range(widgetConfig.to);
})
);
}
export const widgetPlugin = ViewPlugin.fromClass(
class {
decorations; //: DecorationSet
constructor(view /* : EditorView */) {
this.decorations = Decoration.set([]);
}
update(update /* : ViewUpdate */) {
update.transactions.forEach((tr) => {
if (tr.docChanged) {
this.decorations = this.decorations.map(tr.changes);
const iterator = this.decorations.iter();
// Apply changes to iterator.from and iterator.to if docChanged
while (iterator.value) {
// when the widgets are moved, we need to tell the dom node the current position
// this is important because the widget functions have to work with the dom node
if (iterator.value?.widget instanceof BlockWidget) {
iterator.value.widget.from = iterator.from;
iterator.value.widget.to = iterator.to;
}
iterator.next();
}
}
for (let e of tr.effects) {
if (e.is(setWidgetsInRange)) {
// Block-aware widget update logic
const { widgets, range } = e.value;
const [rangeStart, rangeEnd] = range;
// Get existing widget widgets that should be preserved
const existingWidgets = [];
this.decorations.between(0, update.view.state.doc.length, (from, to, decoration) => {
if (decoration.widget instanceof BlockWidget) {
// Preserve widgets outside the evaluation range
// Use strict > for rangeEnd because when code is deleted, widget positions
// map to the deletion boundary (rangeEnd), and those should be removed, not preserved
if (from < rangeStart || from > rangeEnd) {
existingWidgets.push({
from: decoration.widget.from,
to: decoration.widget.to,
type: decoration.widget.type,
index: decoration.widget.index,
id: decoration.widget.id,
});
}
}
const widgetField = StateField.define(
/* <DecorationSet> */ {
create() {
return Decoration.none;
},
update(widgets, tr) {
widgets = widgets.map(tr.changes);
for (let e of tr.effects) {
if (e.is(addWidget)) {
try {
widgets = widgets.update({
filter: () => false,
add: getWidgets(e.value),
});
// Merge preserved widgets with new widgets, deduplicating by ID
const mergedWidgets = [...existingWidgets, ...widgets].filter(
(widget, index, self) => index === self.findIndex((w) => w.type === widget.type && w.id === widget.id),
);
this.decorations = Decoration.set(getWidgets(mergedWidgets, update.view));
} else if (e.is(setWidgets)) {
this.decorations = Decoration.set(getWidgets(e.value, update.view));
} catch (error) {
console.log('err', error);
}
}
});
}
},
{
decorations: (v) => v.decorations,
}
return widgets;
},
provide: (f) => EditorView.decorations.from(f),
},
);
@@ -116,116 +60,24 @@ export function setWidget(id, el) {
}
export class BlockWidget extends WidgetType {
constructor(widgetConfig, view) {
constructor(widgetConfig) {
super();
// Graceful handling of invalid configs like sliders
if (!widgetConfig || typeof widgetConfig !== 'object') {
widgetConfig = { type: 'unknown', from: 0, to: 0 };
}
this.from = widgetConfig.from || 0;
this.originalFrom = widgetConfig.from || 0;
this.to = widgetConfig.to || this.from;
this.originalTo = widgetConfig.to || this.from;
this.type = widgetConfig.type || 'unknown';
this.index = widgetConfig.index || 0;
this.view = view;
// Use range-based ID for stability, similar to sliders
this.id = widgetConfig.id || getWidgetID?.(widgetConfig);
this.widgetConfig = widgetConfig;
}
eq(other) {
if (!(other instanceof BlockWidget)) {
return false;
}
return (
this.id === other.id &&
this.from === other.from &&
this.to === other.to &&
this.type === other.type &&
this.index === other.index
);
eq() {
return true;
}
toDOM() {
let wrap = document.createElement('span');
wrap.setAttribute('aria-hidden', 'true');
wrap.className = 'cm-widget-container';
let el = widgetElements[this.id];
if (el) {
// Ensure the element has the correct ID
el.id = this.id;
wrap.appendChild(el);
} else {
// Create a placeholder element if the widget element doesn't exist
// This prevents CodeMirror errors when widget is missing
const placeholder = document.createElement('span');
placeholder.setAttribute('aria-hidden', 'true');
placeholder.className = 'cm-widget-placeholder';
placeholder.style.cssText = 'display: none;'; // Hide placeholder
placeholder.id = this.id;
wrap.appendChild(placeholder);
}
return wrap;
const id = getWidgetID(this.widgetConfig);
const el = widgetElements[id];
return el;
}
ignoreEvent(e) {
return true;
}
}
export function getActiveWidgets(view) {
if (!view || !view.state) {
return [];
}
const widgetPluginInstance = view.plugin(widgetPlugin);
if (!widgetPluginInstance || !widgetPluginInstance.decorations) {
return [];
}
const widgets = [];
widgetPluginInstance.decorations.between(0, view.state.doc.length, (from, to, decoration) => {
if (decoration.widget instanceof BlockWidget) {
widgets.push({
type: decoration.widget.type,
from: decoration.widget.from,
to: decoration.widget.to,
index: decoration.widget.index,
id: decoration.widget.id,
});
}
});
return widgets;
}
export function getAllWidgetIds(view) {
if (!view || !view.state) {
return [];
}
const widgetPluginInstance = view.plugin(widgetPlugin);
if (!widgetPluginInstance || !widgetPluginInstance.decorations) {
return [];
}
const widgetIds = [];
widgetPluginInstance.decorations.between(0, view.state.doc.length, (from, to, decoration) => {
if (decoration.widget instanceof BlockWidget) {
widgetIds.push(decoration.widget.id);
}
});
return widgetIds;
}
export const widgetPlugin = [widgetField];
// widget implementer API to create a new widget type
export function registerWidget(type, fn) {
@@ -252,6 +104,32 @@ function getCanvasWidget(id, options = {}) {
return canvas;
}
function getListWidget(id, options = {}) {
const { width = 600, height = 100 } = options;
let el = document.getElementById(id) || document.createElement('div');
el.style.width = width + 'px';
el.style.height = height + 'px';
el.style.overflowY = 'auto';
el.style.overflowX = 'auto';
el.style.boxSizing = 'border-box';
el.style.padding = '4px';
el.style.fontFamily = 'monospace';
el.style.lineHeight = '1.4';
el.style.whiteSpace = 'pre';
el.style.background = 'var(--background)';
el.style.color = 'var(--foreground)';
el.style.border = '1px solid var(--lineHighlight)';
// reset on every (re-)evaluation instead of persisting scroll state across it
el.replaceChildren();
el.scrollTop = 0;
el.follow = true;
el.onscroll = () => {
el.follow = el.scrollHeight - el.scrollTop - el.clientHeight < 4;
};
setWidget(id, el);
return el;
}
registerWidget('_pianoroll', (id, options = {}, pat) => {
const ctx = getCanvasWidget(id, options).getContext('2d');
return pat.tag(id).pianoroll({ fold: 1, ...options, ctx, id });
@@ -288,3 +166,9 @@ registerWidget('_spectrum', (id, options = {}, pat) => {
const ctx = getCanvasWidget(id, options).getContext('2d');
return pat.spectrum({ ...options, ctx, id });
});
registerWidget('_print', (id, options = {}, pat) => {
options = { width: 600, height: 100, maxLines: 500, ...options };
const el = getListWidget(id, options);
return pat.print({ ...options, el, id });
});
-1
View File
@@ -1,4 +1,3 @@
// eslint-disable-next-line no-undef
// TODO: swap below line with above one when firefox supports esm imports in service workers
// see https://developer.mozilla.org/en-US/docs/Web/API/ServiceWorker?retiredLocale=de#browser_compatibility
// import createClock from './zyklus.mjs';
File diff suppressed because it is too large Load Diff
+89 -24
View File
@@ -5,7 +5,7 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import createClock from './zyklus.mjs';
import { errorLogger, logger } from './logger.mjs';
import { errorLogger, logger } from '@strudel/pattern';
export class Cyclist {
constructor({
@@ -28,31 +28,34 @@ export class Cyclist {
this.started = false;
this.beforeStart = beforeStart;
this.cps = 0.5;
this.num_ticks_since_cps_change = 0;
this.checkpoint = {
// new checkpoints are created when there's a change in cps
cycles: 0, // number of cycles when cps was changed
seconds: 0, // clock phase when cps was changed
};
this.num_ticks_since_checkpoint = 0;
this.lastTick = 0; // absolute time when last tick (clock callback) happened
this.lastBegin = 0; // query begin of last tick
this.lastEnd = 0; // query end of last tick
this.getTime = getTime; // get absolute time
this.num_cycles_at_cps_change = 0;
this.seconds_at_cps_change; // clock phase when cps was changed
this.onToggle = onToggle;
this.latency = latency; // fixed trigger time offset
this.clock = createClock(
getTime,
// called slightly before each cycle
(phase, duration, _, t) => {
if (this.num_ticks_since_cps_change === 0) {
this.num_cycles_at_cps_change = this.lastEnd;
this.seconds_at_cps_change = phase;
if (this.num_ticks_since_checkpoint === 0) {
this.checkpoint = {
cycles: this.lastEnd,
seconds: phase,
};
}
this.num_ticks_since_cps_change++;
const seconds_since_cps_change = this.num_ticks_since_cps_change * duration;
const num_cycles_since_cps_change = seconds_since_cps_change * this.cps;
this.num_ticks_since_checkpoint++;
try {
const begin = this.lastEnd;
var begin = this.lastEnd;
this.lastBegin = begin;
const end = this.num_cycles_at_cps_change + num_cycles_since_cps_change;
var end = this.checkpoint.cycles + this.num_ticks_since_checkpoint * duration * this.cps;
this.lastEnd = end;
this.lastTick = phase;
@@ -62,20 +65,79 @@ export class Cyclist {
return;
}
// query the pattern for events
const haps = this.pattern.queryArc(begin, end, { _cps: this.cps, cyclist: 'cyclist' });
const tickEndTime = phase + duration;
haps.forEach((hap) => {
if (hap.hasOnset()) {
const targetTime =
(hap.whole.begin - this.num_cycles_at_cps_change) / this.cps + this.seconds_at_cps_change + latency;
onSchedule?.(hap, targetTime, this.cps);
var cpsChanged = false;
do {
cpsChanged = false;
// query the pattern for events
const haps = this.pattern
.queryArc(begin, end, { _cps: this.cps, cyclist: 'cyclist' })
.filter((hap) => hap.hasOnset() || hap.context.processParts)
// Sort the haps based on their onset, so cps changes within the
// tick duration happen in the correct order.
.sort((a, b) => {
const aBegin = a.part.begin;
const bBegin = b.part.begin;
// If haps happen at the same time, trigger the haps that cause
// cps changes first, so the durations of the simultaneous haps
// are adjusted accordingly.
if (aBegin.eq(bBegin)) {
if (a.value.cps !== undefined) {
return b.value.cps !== undefined ? 0 : -1;
}
if (b.value.cps !== undefined) {
return 1;
}
return 0;
}
return aBegin.sub(bBegin);
});
haps.forEach((hap) => {
const targetTime = (hap.part.begin - this.checkpoint.cycles) / this.cps + this.checkpoint.seconds;
if (tickEndTime < targetTime) {
// If the targetTime exceeds the tickEndTime, this means
// the cps has slowed down, and the latter haps from the query
// no longer fall within the window of the current tick.
// They'll be scheduled during the next tick.
return;
}
onSchedule?.(hap, targetTime + this.latency, hap.value.cps ?? this.cps);
if (hap.value.cps !== undefined && this.cps != hap.value.cps) {
cpsChanged = true;
this.cps = hap.value.cps;
this.num_ticks_since_cps_change = 0;
this.num_ticks_since_checkpoint = 0;
this.checkpoint = {
cycles: hap.part.begin,
seconds: targetTime,
};
}
});
// If there are any haps in the query that trigger changes to the
// cps that result in the pattern speeding up, the current cycle end
// may not capture all the haps that need to be scheduled.
// If this is the case, we repeat the query + scheduling with a
// newly calculated end time.
// This process can repeat multiple times until no additional
// changes to the cps are triggered.
// In practice, this doesn't happen more than once during a tick.
if (cpsChanged) {
begin = end;
const remainingSecondsSinceCheckpoint = tickEndTime - this.checkpoint.seconds;
const remainingCycles = remainingSecondsSinceCheckpoint * this.cps;
end = this.checkpoint.cycles + remainingCycles;
this.lastEnd = end;
if (end < begin) {
// If the new end is before the old end this means the track
// slowed down, so we don't need to schedule additional haps.
// Otherwise, schedule the remaining events.
break;
}
}
});
} while (cpsChanged);
} catch (e) {
errorLogger(e);
onError?.(e);
@@ -101,8 +163,11 @@ export class Cyclist {
}
async start() {
await this.beforeStart?.();
this.num_ticks_since_cps_change = 0;
this.num_cycles_at_cps_change = 0;
this.checkpoint = {
cycles: 0,
seconds: 0,
};
this.num_ticks_since_checkpoint = 0;
if (!this.pattern) {
throw new Error('Scheduler: no pattern set! call .setPattern first.');
}
@@ -132,7 +197,7 @@ export class Cyclist {
return;
}
this.cps = cps;
this.num_ticks_since_cps_change = 0;
this.num_ticks_since_checkpoint = 0;
}
log(begin, end, haps) {
const onsets = haps.filter((h) => h.hasOnset());
+1 -29
View File
@@ -4,35 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
export const strudelScope = {};
// Make strudelScope available globally so transpiled code can access it
globalThis.strudelScope = strudelScope;
// Track user-defined keys (from block-based eval) so we can clear them without removing strudel functions
export const userDefinedKeys = new Set();
globalThis.userDefinedKeys = userDefinedKeys;
/**
* Clears all user-defined variables and functions from the scope.
* This removes variables created during block-based evaluation.
* @name clearScope
* @example
* // After defining variables in blocks:
* // let myVar = 5
* // function myFunc() { return 10; }
* clearScope() // removes myVar and myFunc from scope
*/
export const clearScope = () => {
for (const key of userDefinedKeys) {
delete strudelScope[key];
delete globalThis[key];
}
userDefinedKeys.clear();
// Return silence if available (for use in pattern expressions), otherwise undefined
return globalThis.silence;
};
// Make clearScope available globally
globalThis.clearScope = clearScope;
import { strudelScope } from '@strudel/pattern';
export const evalScope = async (...args) => {
const results = await Promise.allSettled(args);
+35 -27
View File
@@ -5,37 +5,45 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import * as controls from './controls.mjs'; // legacy
export * from './euclid.mjs';
import Fraction from './fraction.mjs';
import createClock from './zyklus.mjs';
import { logger } from './logger.mjs';
export { Fraction, controls, createClock };
import { Pattern } from '@strudel/pattern';
export { controls, createClock };
export * from '@strudel/pattern';
export * from './controls.mjs';
export * from './cyclist.mjs';
export * from './evaluate.mjs';
export * from './hap.mjs';
export * from './impure.mjs';
export * from './logger.mjs';
export * from './pattern.mjs';
export * from './pick.mjs';
export * from './repl.mjs';
export * from './signal.mjs';
export * from './speak.mjs';
export * from './state.mjs';
export * from './schedulerState.mjs';
export * from './timespan.mjs';
export * from './ui.mjs';
export * from './util.mjs';
export { default as drawLine } from './drawLine.mjs';
// below won't work with runtime.mjs (json import fails)
/* import * as p from './package.json';
export const version = p.version; */
logger('🌀 @strudel/core loaded 🌀');
if (globalThis._strudelLoaded) {
console.warn(
`@strudel/core was loaded more than once...
This might happen when you have multiple versions of strudel installed.
Please check with "npm ls @strudel/core".`,
);
}
globalThis._strudelLoaded = true;
export * from './evaluate.mjs';
import { getClockTime } from './schedulerState.mjs';
// legacy:
Pattern.prototype.onTrigger = function (onTrigger, dominant = true) {
console.warn('onTrigger is deprecated.. use onSchedule(hap, time, cps) instead');
return this.onSchedule((hap, t, cps) => {
const currentTime = getClockTime();
return onTrigger(hap, currentTime, cps, t);
}, dominant);
};
/**
*
* make something happen on event time
* uses browser timeout which is innacurate for audio tasks
* @param {Function} func
* @name onTriggerTime
* @tags external_io
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("bd!8").onTriggerTime((hap) => {console.log(hap)})
*/
Pattern.prototype.onTriggerTime = function (func) {
return this.onSchedule((hap, targetTime) => {
const diff = targetTime - getClockTime();
setTimeout(() => {
func(hap);
}, diff * 1000);
}, false);
};
+1 -2
View File
@@ -4,8 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { logger } from './logger.mjs';
import { ClockCollator, cycleToSeconds } from './util.mjs';
import { logger, ClockCollator, cycleToSeconds } from '@strudel/pattern';
export class NeoCyclist {
constructor({ onSchedule, onToggle, getTime, onTrigger }) {
+2 -1
View File
@@ -31,7 +31,8 @@
},
"homepage": "https://strudel.cc",
"dependencies": {
"fraction.js": "^5.2.1"
"fraction.js": "^5.2.1",
"@strudel/pattern": "workspace:*"
},
"gitHead": "0e26d4e741500f5bae35b023608f062a794905c2",
"devDependencies": {
+43 -300
View File
@@ -1,7 +1,9 @@
import { NeoCyclist } from './neocyclist.mjs';
import { evalScope } from './evaluate.mjs';
import { Cyclist } from './cyclist.mjs';
import { reset_state } from '@strudel/pattern';
import { evaluate as _evaluate } from './evaluate.mjs';
import { errorLogger, logger } from './logger.mjs';
import { errorLogger, logger, register, Pattern, isPattern, silence, stack } from '@strudel/pattern';
import {
setCpsFunc,
setIsStarted,
@@ -10,9 +12,6 @@ import {
setScheduleFunc,
setClockTime,
} from './schedulerState.mjs';
import { evalScope } from './evaluate.mjs';
import { register, Pattern, isPattern, silence, stack } from './pattern.mjs';
import { reset_state } from './impure.mjs';
export function repl({
onSchedule,
@@ -45,7 +44,6 @@ export function repl({
pattern: undefined,
miniLocations: [],
widgets: [],
sliders: [],
pending: false,
started: false,
};
@@ -87,132 +85,11 @@ export function repl({
let allTransform;
let eachTransform;
// Block-based evaluation state
let codeBlocks = {};
let lastActiveVisualizerLabel = null;
// Track which patterns belong to which blocks: { blockRange: [patternKeys] }
let blockPatterns = new Map();
// Helper function to collect properties from all code blocks (handles both labeled and anonymous blocks)
function collectFromBlocks(property) {
return Object.entries(codeBlocks).flatMap(([key, block]) => {
if (key === '$') {
// Anonymous blocks are stored as an array of block objects
return Array.isArray(block) ? block.flatMap((b) => b[property] || []) : [];
}
// Labeled blocks are stored as single block objects
return block[property] || [];
});
}
// Helper function to process a single labeled block
function processLabeledBlock(labels, i, code, options, meta) {
const label = labels[i];
const nextLabel = labels[i + 1] || { index: code.length, end: code.length };
const labelCode = code.slice(label.index, nextLabel.index);
const labelRange = [label.index + options.range[0], label.end + options.range[0]];
// Calculate the full block range (from label start to next label start)
const blockStart = label.index + options.range[0];
const blockEnd = nextLabel.index + options.range[0];
const blockWidgets = (meta?.widgets || []).filter((widget) => {
const widgetPos = widget.from ?? widget.index ?? 0;
return widgetPos >= blockStart && widgetPos < blockEnd;
});
const blockSliders = (meta?.sliders || []).filter((slider) => {
const sliderPos = slider.from ?? slider.index ?? 0;
return sliderPos >= blockStart && sliderPos < blockEnd;
});
const blockMiniLocations = (meta?.miniLocations || []).filter((loc) => {
// const locStart = loc.start ?? loc.from ?? 0;
// mini locations can be either [start, end] arrays or objects with start/from
const locStart = Array.isArray(loc) ? loc[0] : (loc.start ?? loc.from ?? 0);
return locStart >= blockStart && locStart < blockEnd;
});
handleSingleLabelBlock(
label,
labelCode,
{ ...options, range: labelRange },
{ widgets: blockWidgets, sliders: blockSliders, miniLocations: blockMiniLocations },
);
}
// helper
function cleanupConflictingRanges(codeBlocks, currentKey, newRange) {
for (const [existingKey, existingBlock] of Object.entries(codeBlocks)) {
if (existingKey === currentKey) continue;
if (!existingBlock.range) continue;
const [existingStart, existingEnd] = existingBlock.range;
const [newStart, newEnd] = newRange;
// If ranges overlap (not just touch), remove the stale block
if (!(newEnd <= existingStart || newStart >= existingEnd)) {
delete codeBlocks[existingKey];
}
}
}
// helper
function handleSingleLabelBlock(label, code, options, meta) {
// Detect if this block contains a non-inline widget
// The activeVisualizer is now provided by the transpiler for all labels
const activeVisualizer = label.activeVisualizer || null;
if (activeVisualizer !== null) {
lastActiveVisualizerLabel = label.name;
}
// Store the entire code block under the label name
codeBlocks[label.name] = {
code: code,
range: options.range,
labels: [label.name],
miniLocations: meta?.miniLocations || [],
widgets: meta?.widgets || [],
sliders: meta?.sliders || [],
activeVisualizer: activeVisualizer, // Store the widget type if present, null otherwise
};
// Clean up any blocks with conflicting ranges (including declaration blocks)
cleanupConflictingRanges(codeBlocks, label.name, options.range);
}
// helper
// These blocks return silence but may contain mini notation strings that need highlighting
function handleDeclarationBlock(code, options, meta) {
const range = options.range || [];
if (range.length < 2) return;
const blockKey = `_decl:${range[0]}:${range[1]}`;
codeBlocks[blockKey] = {
code: code,
range: range,
labels: [],
miniLocations: meta?.miniLocations || [],
widgets: meta?.widgets || [],
sliders: meta?.sliders || [],
activeVisualizer: null,
};
// Clean up any overlapping declaration blocks
cleanupConflictingRanges(codeBlocks, blockKey, range);
}
const hush = function () {
pPatterns = {};
anonymousIndex = 0;
allTransform = undefined;
eachTransform = undefined;
codeBlocks = {};
blockPatterns.clear();
lastActiveVisualizerLabel = null; // Reset 'all' visualizer tracking
return silence;
};
@@ -233,60 +110,7 @@ export function repl({
setTime(() => scheduler.now()); // TODO: refactor?
setClockTime(() => scheduler.getTime()); // TODO: refactor?
// Helper function to apply pattern transformations (solo, each, all)
// this should be abstracted more
function applyPatternTransforms(pattern) {
const allPatterns = Object.values(pPatterns);
if (allPatterns.length) {
let patterns = [];
let soloActive = false;
for (const [key, value] of Object.entries(pPatterns)) {
// handle soloed patterns ex: S$: s("bd!4")
const isSolod = key.length > 1 && key.startsWith('S');
if (isSolod && soloActive === false) {
// first time we see a soloed pattern, clear existing patterns
patterns = [];
soloActive = true;
}
if (!soloActive || (soloActive && isSolod)) {
const valWithState = value.withState((state) => state.setControls({ id: key }));
patterns.push(valWithState);
}
}
if (eachTransform) {
// Explicit lambda so only element (not index and array) are passed
patterns = patterns.map((x) => eachTransform(x));
}
pattern = stack(...patterns);
} else if (eachTransform) {
pattern = eachTransform(pattern);
}
if (allTransforms.length) {
for (const transform of allTransforms) {
pattern = transform(pattern);
}
}
if (!isPattern(pattern)) {
pattern = silence;
}
return pattern;
}
const stop = () => {
codeBlocks = {};
blockPatterns.clear();
pPatterns = {};
lastActiveVisualizerLabel = null; // Reset 'all' visualizer tracking
updateState({
miniLocations: [],
widgets: [],
sliders: [],
});
scheduler.stop();
};
const stop = () => scheduler.stop();
const start = () => scheduler.start();
const pause = () => scheduler.pause();
const toggle = () => scheduler.toggle();
@@ -302,6 +126,7 @@ export function repl({
* @tags temporal
* @alias setCpm
* @param {number} cpm cycles per minute
* @returns {pattern}
* @example
* setcpm(140/4) // =140 bpm in 4/4
* $: s("bd*4,[- sd]*2").bank('tr707')
@@ -331,7 +156,8 @@ export function repl({
* $: sound("hh*8")
* all(x => x.pianoroll())
* ```
*
* @param {function(Pattern):Pattern} transform
* @returns {Pattern}
* @tags combiners
*/
const all = function (transform) {
@@ -349,6 +175,8 @@ export function repl({
* each(fast("<2 3>"))
* ```
* @tags combiners
* @param {function(Pattern):Pattern} transform
* @returns {pattern}
*/
const each = function (transform) {
eachTransform = transform;
@@ -407,7 +235,7 @@ export function repl({
});
};
const evaluate = async (code, autostart = true) => {
const evaluate = async (code, autostart = true, shouldHush = true) => {
if (!code) {
throw new Error('no code to evaluate');
}
@@ -416,132 +244,47 @@ export function repl({
await injectPatternMethods();
setTime(() => scheduler.now()); // TODO: refactor?
setClockTime(() => scheduler.getTime()); // TODO: refactor?
await beforeEval?.({ code, blockBased: false });
await beforeEval?.({ code });
allTransforms = []; // reset all transforms
codeBlocks = {};
hush();
shouldHush && hush();
if (mondo) {
code = `mondolang\`${code}\``;
}
let { pattern, meta } = await _evaluate(code, transpiler, transpilerOptions);
pattern = applyPatternTransforms(pattern);
logger(`[eval] code updated`);
pattern = await setPattern(pattern, autostart);
updateState({
miniLocations: meta?.miniLocations || [],
widgets: meta?.widgets || [],
sliders: meta?.sliders || [],
activeCode: code,
pattern,
evalError: undefined,
schedulerError: undefined,
pending: false,
});
afterEval?.({ code, pattern, meta, range: undefined, widgetRemoved: false });
return pattern;
} catch (err) {
logger(`[eval] error: ${err.message}`, 'error');
console.error(err);
updateState({ evalError: err, pending: false });
onEvalError?.(err);
}
};
const evaluateBlock = async (code, autostart = true, options = {}) => {
if (!code) {
throw new Error('no code to evaluate');
}
try {
updateState({ code, pending: true });
await injectPatternMethods();
setTime(() => scheduler.now()); // TODO: refactor?
setClockTime(() => scheduler.getTime()); // TODO: refactor?
await beforeEval?.({ code, blockBased: true });
allTransforms = []; // reset all transforms
const transpilerOptionsWithBlock = {
...transpilerOptions,
blockBased: true,
range: options.range || [],
};
if (mondo) {
code = `mondolang\`${code}\``;
}
let { pattern, meta } = await _evaluate(code, transpiler, transpilerOptionsWithBlock);
// Track activeVisualizer cleanup: check if any block's visualizer was removed
let widgetRemoved = false;
const labels = meta.labels || [];
// Check for anonymous labels (labels starting with '$')
const hasAnonymousLabel = labels.some((label) => label.name.startsWith('$'));
// Store code blocks in dictionary using labels as keys
if (hasAnonymousLabel) {
// variable/function declarations that don't return patterns are allowed,
// but anonymous pattern blocks pose an issue for block-based evaluation
// if an anonymous pattern is evaluated multiple times it will just stack and get louder and louder
// it's very common for users to write code prefixed with '$'
// but to modify and override existing patterns, the patterns must be labeled,
// otherwise we'll have no idea of which pattern is being overridden
// (we probably need to update the docs on this)
// we could easily enable it, but it would confuse a lot of people
throw new Error(
'anonymous labels disabled for block based evaluation (see https://strudel.cc/blog/#label-notation)',
);
} else if (labels.length > 0) {
for (let i = 0; i < labels.length; i++) {
// processing transpiler output instead of code is simply to avoid
// extra regex in detecting whether or not an inline widget has been commented out
processLabeledBlock(labels, i, meta.output, options, meta);
}
} else {
// Declaration block (variable/function that returns silence)
// Store it so its miniLocations are preserved for highlighting patterns stored in variables
handleDeclarationBlock(code, options, meta);
}
meta.miniLocations = collectFromBlocks('miniLocations');
meta.widgets = collectFromBlocks('widgets');
meta.sliders = collectFromBlocks('sliders');
// Track activeVisualizer cleanup: check if any block's visualizer was removed
const blocksToUpdate = labels.map((label) => label.name);
// this is the hackiest bit
for (const [key, block] of Object.entries(codeBlocks)) {
if (blocksToUpdate.includes(key)) {
// This block was just updated
if (block.activeVisualizer !== null) {
// Block now has a visualizer, update tracking
lastActiveVisualizerLabel = key;
} else if (lastActiveVisualizerLabel === key) {
// This block lost its visualizer, trigger cleanup
widgetRemoved = true;
lastActiveVisualizerLabel = null;
if (Object.keys(pPatterns).length) {
let patterns = [];
let soloActive = false;
for (const [key, value] of Object.entries(pPatterns)) {
// handle soloed patterns ex: S$: s("bd!4")
const isSolod = key.length > 1 && key.startsWith('S');
if (isSolod && soloActive === false) {
// first time we see a soloed pattern, clear existing patterns
patterns = [];
soloActive = true;
}
if (!soloActive || (soloActive && isSolod)) {
const valWithState = value.withState((state) => state.setControls({ id: key }));
patterns.push(valWithState);
}
}
if (eachTransform) {
// Explicit lambda so only element (not index and array) are passed
patterns = patterns.map((x) => eachTransform(x));
}
pattern = stack(...patterns);
} else if (eachTransform) {
pattern = eachTransform(pattern);
}
if (allTransforms.length) {
for (const transform of allTransforms) {
pattern = transform(pattern);
}
}
pPatterns = Object.fromEntries(
Object.entries(pPatterns).filter(([key]) => {
return Object.keys(codeBlocks).includes(key);
}),
);
pattern = applyPatternTransforms(pattern);
if (!isPattern(pattern)) {
pattern = silence;
}
logger(`[eval] code updated`);
pattern = await setPattern(pattern, autostart);
@@ -556,7 +299,7 @@ export function repl({
pending: false,
});
afterEval?.({ code, pattern, meta, range: options.range, widgetRemoved });
afterEval?.({ code, pattern, meta });
return pattern;
} catch (err) {
logger(`[eval] error: ${err.message}`, 'error');
@@ -567,7 +310,7 @@ export function repl({
};
const setCode = (code) => updateState({ code });
return { scheduler, evaluate, evaluateBlock, start, stop, pause, setCps, setPattern, setCode, toggle, state };
return { scheduler, evaluate, start, stop, pause, setCps, setPattern, setCode, toggle, state };
}
export const getSchedule =
+6 -3
View File
@@ -11,9 +11,10 @@ let scheduleFunc;
let isStarted;
/**
* Get the current cycle time as a number
* @name getTime
* @tags internals
* @returns {Number} the current cycle time as a number
* @returns {number}
*/
export function getTime() {
if (!time) {
@@ -28,9 +29,10 @@ export function setTime(func) {
let clockTime;
/**
* Get the current clock time in seconds (onSchedule time)
* @name getClockTime
* @tags internals
* @returns {Number} the current clock time in seconds (onSchedule time)
* @returns {number}
*/
export function getClockTime() {
if (!clockTime) {
@@ -48,9 +50,10 @@ export function setCpsFunc(func) {
}
/**
* Get the current cycles per second
* @name getCps
* @tags internals
* @returns {Number} the current cycles per second
* @returns {number}
*/
export function getCps() {
return cpsFunc?.();
+116 -1
View File
@@ -7,7 +7,8 @@ This program is free software: you can redistribute it and/or modify it under th
import { s, pan, getControlName } from '../controls.mjs';
import { mini } from '../../mini/mini.mjs';
import { describe, it, expect } from 'vitest';
import Fraction from '../fraction.mjs';
import { Fraction, sequence, pure, fast, stack } from '@strudel/pattern';
import { sameFirst } from '../../pattern/test/pattern.test.mjs';
describe('controls', () => {
it('should support controls', () => {
@@ -44,3 +45,117 @@ describe('controls', () => {
expect(getControlName('cutoff')).toEqual('cutoff');
});
});
describe('chop', () => {
it('Can _chop(2)', () => {
expect(sequence({ sound: 'a' }, { sound: 'b' })._chop(2).firstCycle()).toStrictEqual(
sequence(
{ sound: 'a', begin: 0, end: 0.5 },
{ sound: 'a', begin: 0.5, end: 1 },
{ sound: 'b', begin: 0, end: 0.5 },
{ sound: 'b', begin: 0.5, end: 1 },
).firstCycle(),
);
});
it('Can chop(2,3)', () => {
expect(pure({ sound: 'a' }).fast(2).chop(2, 3).sortHapsByPart().firstCycle()).toStrictEqual(
sequence(
[
{ sound: 'a', begin: 0, end: 0.5 },
{ sound: 'a', begin: 0.5, end: 1 },
],
[
{ sound: 'a', begin: 0, end: 1 / 3 },
{ sound: 'a', begin: 1 / 3, end: 2 / 3 },
{ sound: 'a', begin: 2 / 3, end: 1 },
],
)
.sortHapsByPart()
.firstCycle(),
);
});
it('Can chop chops', () => {
expect(pure({ s: 'bev' }).chop(2).chop(2).firstCycle()).toStrictEqual(pure({ s: 'bev' }).chop(4).firstCycle());
});
});
describe('loopAt', () => {
it('maintains steps', () => {
expect(s('bev').chop(8).loopAt(2)._steps).toStrictEqual(Fraction(4));
});
});
describe('_steps', () => {
it('Is correctly preserved/calculated through transformations', () => {
expect(sequence({ n: 0 }, { n: 1 }, { n: 2 }).chop(4)._steps).toStrictEqual(Fraction(12));
expect(sequence(0, 1, 2, 3).hurry(4)._steps).toStrictEqual(Fraction(4));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).chop(4)._steps).toStrictEqual(Fraction(8));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).striate(4)._steps).toStrictEqual(Fraction(8));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).slice(4, sequence(0, 1, 2, 3))._steps).toStrictEqual(Fraction(4));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).splice(4, sequence(0, 1, 2, 3))._steps).toStrictEqual(
Fraction(4),
);
});
});
describe('hurry', () => {
it('Can speed up patterns and sounds', () => {
sameFirst(s(sequence('a', 'b')).hurry(2), s(sequence('a', 'b')).fast(2).set({ speed: 2 }));
});
});
describe('jux', () => {
it('Can juxtapose', () => {
expect(pure({ a: 1 }).jux(fast(2)).sortHapsByPart().firstCycle()).toStrictEqual(
stack(pure({ a: 1, pan: 0 }), pure({ a: 1, pan: 1 }).fast(2))
.sortHapsByPart()
.firstCycle(),
);
});
});
describe('juxBy', () => {
it('Can juxtapose by half', () => {
expect(pure({ a: 1 }).juxBy(0.5, fast(2)).sortHapsByPart().firstCycle()).toStrictEqual(
stack(pure({ a: 1, pan: 0.25 }), pure({ a: 1, pan: 0.75 }).fast(2))
.sortHapsByPart()
.firstCycle(),
);
});
});
describe('striate', () => {
it('Can striate(2)', () => {
sameFirst(
sequence({ sound: 'a' }).striate(2),
sequence({ sound: 'a', begin: 0, end: 0.5 }, { sound: 'a', begin: 0.5, end: 1 }),
);
});
});
describe('slice', () => {
it('Can slice a sample', () => {
sameFirst(
s('break').slice(4, sequence(0, 1, 2, 3)),
sequence(
{ begin: 0, end: 0.25, s: 'break', _slices: 4 },
{ begin: 0.25, end: 0.5, s: 'break', _slices: 4 },
{ begin: 0.5, end: 0.75, s: 'break', _slices: 4 },
{ begin: 0.75, end: 1, s: 'break', _slices: 4 },
),
);
});
});
describe('splice', () => {
it('Can splice a sample', () => {
sameFirst(
s('break').splice(4, sequence(0, 1, 2, 3)),
sequence(
{ begin: 0, end: 0.25, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.25, end: 0.5, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.5, end: 0.75, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.75, end: 1, s: 'break', _slices: 4, unit: 'c', speed: 1 },
),
);
});
});
+1 -1
View File
@@ -1,5 +1,5 @@
import { listen } from '@tauri-apps/api/event';
import { logger } from '../core/logger.mjs';
import { logger } from '@strudel/core';
// listen for log events from the Tauri backend and log in the UI
await listen('log-event', (e) => {
+5 -4
View File
@@ -21,7 +21,8 @@ let D;
*
* @name initDough
* @tags external_io
* @memberof Pattern
* @memberof Pattern.prototype
* @returns {Promise<void>}
* @example
* await initDough()
* $: chord("<Dm9 Dm11 Dm7>").offset("<-1 0 1 0>").voicing()
@@ -51,12 +52,12 @@ export async function doughOutput(hap, targetTime, cps = 1) {
/**
*
* Uses dough as the audio engine. more info at https://dough.strudel.cc
* Uses dough as the audio engine. more info [here](https://dough.strudel.cc)
*
* @name dough
* @tags external_io
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* $: chord("<Dm9 Dm11 Dm7>").offset("<-1 0 1 0>").voicing()
* .phaser(3).fm(1.4).fmh(1.01)
-10
View File
@@ -78,16 +78,6 @@ export const cleanupDraw = (clearScreen = true, id) => {
stopAllAnimations(id);
};
export const cleanupDrawContext = (replID) => {
const ctx = getDrawContext();
ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);
// clear the big canvas context, ignore inline widgets
Object.keys(animationFrames).forEach(
(id) => (!replID || id.startsWith(replID)) && !id.startsWith('_') && stopAnimationFrame(id),
);
};
Pattern.prototype.onPaint = function (painter) {
return this.withState((state) => {
if (!state.controls.painters) {
+1
View File
@@ -4,3 +4,4 @@ export * from './draw.mjs';
export * from './pianoroll.mjs';
export * from './spiral.mjs';
export * from './pitchwheel.mjs';
export * from './print.mjs';
+1 -1
View File
@@ -16,7 +16,7 @@
"url": "git+https://codeberg.org/uzu/strudel.git"
},
"keywords": [
"titdalcycles",
"tidalcycles",
"strudel",
"pattern",
"livecoding",
+32 -25
View File
@@ -43,31 +43,31 @@ const getValue = (e) => {
* @name pianoroll
* @synonyms punchcard
* @tags visualization
* @param {Object} options Object containing all the optional following parameters as key value pairs:
* @param {integer} cycles number of cycles to be displayed at the same time - defaults to 4
* @param {number} playhead location of the active notes on the time axis - 0 to 1, defaults to 0.5
* @param {boolean} vertical displays the roll vertically - 0 by default
* @param {boolean} labels displays labels on individual notes (see the label function) - 0 by default
* @param {boolean} flipTime reverse the direction of the roll - 0 by default
* @param {boolean} flipValues reverse the relative location of notes on the value axis - 0 by default
* @param {number} overscan lookup X cycles outside of the cycles window to display notes in advance - 1 by default
* @param {boolean} hideNegative hide notes with negative time (before starting playing the pattern) - 0 by default
* @param {boolean} smear notes leave a solid trace - 0 by default
* @param {boolean} fold notes takes the full value axis width - 0 by default
* @param {string} active hexadecimal or CSS color of the active notes - defaults to #FFCA28
* @param {string} inactive hexadecimal or CSS color of the inactive notes - defaults to #7491D2
* @param {string} background hexadecimal or CSS color of the background - defaults to transparent
* @param {string} playheadColor hexadecimal or CSS color of the line representing the play head - defaults to white
* @param {boolean} fill notes are filled with color (otherwise only the label is displayed) - 0 by default
* @param {boolean} fillActive active notes are filled with color - 0 by default
* @param {boolean} stroke notes are shown with colored borders - 0 by default
* @param {boolean} strokeActive active notes are shown with colored borders - 0 by default
* @param {boolean} hideInactive only active notes are shown - 0 by default
* @param {boolean} colorizeInactive use note color for inactive notes - 1 by default
* @param {string} fontFamily define the font used by notes labels - defaults to 'monospace'
* @param {integer} minMidi minimum note value to display on the value axis - defaults to 10
* @param {integer} maxMidi maximum note value to display on the value axis - defaults to 90
* @param {boolean} autorange automatically calculate the minMidi and maxMidi parameters - 0 by default
* @param {object} [options] Object containing all the optional following parameters as key value pairs:
* @param {number} [options.cycles=4] number of cycles to be displayed at the same time - defaults to 4
* @param {number} [options.playhead=0.5] location of the active notes on the time axis - 0 to 1, defaults to 0.5
* @param {boolean} [options.vertical=0] displays the roll vertically - 0 by default
* @param {boolean} [options.labels=0] displays labels on individual notes (see the label function) - 0 by default
* @param {boolean} [options.flipTime=0] reverse the direction of the roll - 0 by default
* @param {boolean} [options.flipValues=0] reverse the relative location of notes on the value axis - 0 by default
* @param {number} [options.overscan=1] lookup X cycles outside of the cycles window to display notes in advance - 1 by default
* @param {boolean} [options.hideNegative=0] hide notes with negative time (before starting playing the pattern) - 0 by default
* @param {boolean} [options.smear=0] notes leave a solid trace - 0 by default
* @param {boolean} [options.fold=0] notes takes the full value axis width - 0 by default
* @param {string} [options.active=#FFCA28] hexadecimal or CSS color of the active notes - defaults to #FFCA28
* @param {string} [options.inactive='#7491D2'] hexadecimal or CSS color of the inactive notes - defaults to #7491D2
* @param {string} [options.background='transparent'] hexadecimal or CSS color of the background - defaults to transparent
* @param {string} [options.playheadColor='white'] hexadecimal or CSS color of the line representing the play head - defaults to white
* @param {boolean} [options.fill=0] notes are filled with color (otherwise only the label is displayed) - 0 by default
* @param {boolean} [options.fillActive=0] active notes are filled with color - 0 by default
* @param {boolean} [options.stroke=0] notes are shown with colored borders - 0 by default
* @param {boolean} [options.strokeActive=0] active notes are shown with colored borders - 0 by default
* @param {boolean} [options.hideInactive=0] only active notes are shown - 0 by default
* @param {boolean} [options.colorizeInactive=1] use note color for inactive notes - 1 by default
* @param {string} [options.fontFamily='monospace'] define the font used by notes labels - defaults to 'monospace'
* @param {number} [options.minMidi=10] minimum note value to display on the value axis - defaults to 10
* @param {number} [options.maxMidi=90] maximum note value to display on the value axis - defaults to 90
* @param {boolean} [options.autorange=0] automatically calculate the minMidi and maxMidi parameters - 0 by default
* @see _pianoroll
* @example
* note("c2 a2 eb2")
@@ -299,8 +299,15 @@ Pattern.prototype.punchcard = function (options) {
* Displays a vertical pianoroll with event labels.
* Supports all the same options as pianoroll.
*
* @param {object} options
* @param {number} options.vertical
* @param {number} options.labels
* @param {number} options.stroke
* @param {number} options.fillActive
* @param {string} options.active
* @name wordfall
* @tags visualization
* @returns {Pattern}
*/
Pattern.prototype.wordfall = function (options) {
return this.punchcard({ vertical: 1, labels: 1, stroke: 0, fillActive: 1, active: 'white', ...options });
+10 -8
View File
@@ -148,14 +148,16 @@ export function pitchwheel({
* Renders a pitch circle to visualize frequencies within one octave
* @name pitchwheel
* @tags visualization
* @param {number} hapcircles
* @param {number} circle
* @param {number} edo
* @param {string} root
* @param {number} thickness
* @param {number} hapRadius
* @param {string} mode
* @param {number} margin
* @param {object} options
* @param {number} options.hapcircles
* @param {number} options.circle
* @param {number} options.edo
* @param {string} options.root
* @param {number} options.thickness
* @param {number} options.hapRadius
* @param {string} options.mode
* @param {number} options.margin
* @returns {Pattern}
* @example
* n("0 .. 12").scale("C:chromatic")
* .s("sawtooth")
+100
View File
@@ -0,0 +1,100 @@
/*
print.mjs - prints hap values to the console or a scrollable inline widget
Copyright (C) 2022 Strudel contributors - see
<https://codeberg.org/uzu/strudel/src/branch/main/packages/draw/print.mjs> This
program is free software: you can redistribute it and/or modify it under the
terms of the GNU Affero General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option) any later
version. This program is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
more details. You should have received a copy of the GNU Affero General Public
License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { logger, Pattern, stringifyValues } from '@strudel/core';
const printed = {};
// counts .print() calls within one synchronous evaluation, then resets for the
// next
let printIndex = 0;
let printIndexResetQueued = false;
function nextPrintIndex() {
const index = printIndex++;
if (!printIndexResetQueued) {
printIndexResetQueued = true;
queueMicrotask(() => {
printIndex = 0;
printIndexResetQueued = false;
});
}
return index;
}
function formatTime(hap, round, padding) {
const begin = hap.wholeOrPart().begin;
if (round === 0) {
return String(begin.sam().valueOf()).padEnd(padding);
}
const factor = 10 ** round;
const time = Math.round(begin.valueOf() * factor) / factor;
return String(time).padEnd(padding + round + 1);
}
function appendLine(el, text, maxLines) {
const line = document.createElement('div');
line.textContent = text;
el.appendChild(line);
while (el.childElementCount > maxLines) {
el.removeChild(el.firstChild);
}
if (el.follow) {
el.scrollTop = el.scrollHeight;
}
}
/**
* Prints the values of a pattern's events. Without a leading underscore, prints
* to the existing console panel, labeled with its position among other
* `print()` calls, e.g. `[print(line:1)]`. With the `_` prefix, it shows a
* scrollable widget inside the code instead, and its content resets on
* every (re-)evaluation.
*
* @name print
* @tags visualization
* @param {object} options object that may have the following arguments
* @param {number} options.width widget width in px, `_print` only. defaults to 600
* @param {number} options.height widget height in px, `_print` only. defaults to 100
* @param {number} options.maxLines max lines kept, `_print` only. defaults to 500
* @param {number} options.round decimal digits for the event time. defaults to 4. `0`
* shows only the cycle
* @param {number} options.padding integer digits reserved for the cycle, so it stays
* aligned once cycles reach 10 or 100. defaults to 3
* @returns {Pattern}
* @example
* s("bd sd hh cp").print()
* @example
* s("bd sd hh*2 cp")._print({ round: 5 })
*/
Pattern.prototype.print = function (options = {}) {
const { el, id = 1, maxLines = 500, round = 4, padding = 3 } = options;
if (!el) {
const label = `print(line:${nextPrintIndex() + 1})`;
return this.onTrigger((hap) => {
logger(`[${label}] ${formatTime(hap, round, padding)}: ${stringifyValues(hap.value, true)}`);
}, false);
}
printed[id] = new WeakSet();
return this.draw(
(haps) => {
haps
.filter((hap) => !printed[id].has(hap))
.forEach((hap) => {
printed[id].add(hap);
appendLine(el, `${formatTime(hap, round, padding)}: ${stringifyValues(hap.value, true)}`, maxLines);
});
},
{ lookbehind: 0, lookahead: 0, id },
);
};
+17 -16
View File
@@ -130,22 +130,23 @@ function drawSpiral(options) {
*
* @name spiral
* @tags visualization
* @param {Object} options Object containing all the optional following parameters as key value pairs:
* @param {number} stretch controls the rotations per cycle ratio, where 1 = 1 cycle / 360 degrees
* @param {number} size the diameter of the spiral
* @param {number} thickness line thickness
* @param {string} cap style of line ends: butt (default), round, square
* @param {string} inset number of rotations before spiral starts (default 3)
* @param {string} playheadColor color of playhead, defaults to white
* @param {number} playheadLength length of playhead in rotations, defaults to 0.02
* @param {number} playheadThickness thickness of playheadrotations, defaults to thickness
* @param {number} padding space around spiral
* @param {number} steady steadyness of spiral vs playhead. 1 = spiral doesn't move, playhead does.
* @param {number} activeColor color of active segment. defaults to foreground of theme
* @param {number} inactiveColor color of inactive segments. defaults to gutterForeground of theme
* @param {boolean} colorizeInactive wether or not to colorize inactive segments, defaults to 0
* @param {boolean} fade wether or not past and future should fade out. defaults to 1
* @param {boolean} logSpiral wether or not the spiral should be logarithmic. defaults to 0
* @param {object} options Object containing all the optional following parameters as key value pairs:
* @param {number} options.stretch controls the rotations per cycle ratio, where 1 = 1 cycle / 360 degrees
* @param {number} options.size the diameter of the spiral
* @param {number} options.thickness line thickness
* @param {string} options.cap style of line ends: butt (default), round, square
* @param {string} options.inset number of rotations before spiral starts (default 3)
* @param {string} options.playheadColor color of playhead, defaults to white
* @param {number} options.playheadLength length of playhead in rotations, defaults to 0.02
* @param {number} options.playheadThickness thickness of playheadrotations, defaults to thickness
* @param {number} options.padding space around spiral
* @param {number} options.steady steadyness of spiral vs playhead. 1 = spiral doesn't move, playhead does.
* @param {number} options.activeColor color of active segment. defaults to foreground of theme
* @param {number} options.inactiveColor color of inactive segments. defaults to gutterForeground of theme
* @param {boolean} options.colorizeInactive wether or not to colorize inactive segments, defaults to 0
* @param {boolean} options.fade wether or not past and future should fade out. defaults to 1
* @param {boolean} options.logSpiral wether or not the spiral should be logarithmic. defaults to 0
* @returns {Pattern}
* @example
* note("c2 a2 eb2")
* .euclid(5,8)
+1 -1
View File
@@ -38,7 +38,7 @@ const pitchesCache = new Map();
*
* @name edoScale
* @param {string} scale Definition of EDO scale.
* @returns Pattern
* @returns {Pattern}
* @example
* n("0 2 4 6 4 2").edoScale("C:LLsLLLs:2:1")
* @example
+1 -1
View File
@@ -16,7 +16,7 @@
"url": "git+https://codeberg.org/uzu/strudel.git"
},
"keywords": [
"titdalcycles",
"tidalcycles",
"strudel",
"pattern",
"livecoding",
+2 -2
View File
@@ -29,10 +29,10 @@
},
"homepage": "https://codeberg.org/uzu/strudel/",
"dependencies": {
"web-tree-sitter": "^0.24.7"
"web-tree-sitter": "^0.24.7",
"tree-sitter-haskell": "^0.23.1"
},
"devDependencies": {
"tree-sitter-haskell": "^0.23.1",
"vite": "^6.0.11"
},
"engines": {
+9 -3
View File
@@ -1,6 +1,8 @@
import Parser from 'web-tree-sitter';
import treeSitterWasm from 'web-tree-sitter/tree-sitter.wasm?url';
import grammarWasm from 'tree-sitter-haskell/tree-sitter-haskell.wasm?url';
let base = '/';
let base;
export function setBase(path) {
base = path;
}
@@ -10,11 +12,15 @@ let isReady = false,
async function _loadParser() {
await Parser.init({
locateFile(scriptName, scriptDirectory) {
return `${base}${scriptName}`;
if (base) {
return `${base}${scriptName}`;
}
return treeSitterWasm;
},
});
parser = new Parser();
const Lang = await Parser.Language.load(`${base}tree-sitter-haskell.wasm`);
let grammarUrl = base ? `${base}tree-sitter-haskell.wasm` : grammarWasm;
const Lang = await Parser.Language.load(grammarUrl);
parser.setLanguage(Lang);
isReady = true;
return parser;
+2 -1
View File
@@ -15,7 +15,7 @@ import { getDevice } from './util.mjs';
*/
export class MidiInput {
/**
*
* Constructs a new Midi input device
* @param {string | number} input MIDI device name or index defaulting to 0
*/
constructor(input) {
@@ -34,6 +34,7 @@ export class MidiInput {
* Implementation for the cc() factory function tied to this specific input.
* @param {number} cc MIDI CC number
* @param {number | undefined} chan MIDI channel (1-16) or undefined for all channels
* @returns {Pattern}
*/
createCC(cc, chan) {
const lookupMap = chan === undefined ? this._refs : this._refsByChan[chan];
+10
View File
@@ -113,6 +113,7 @@ function githubPath(base, subpath = '') {
/**
* configures the default midimap, which is used when no "midimap" port is set
* @param {*} mapping
* @tags external_io, midi
* @example
* defaultmidimap({ lpf: 74 })
@@ -127,6 +128,7 @@ let loadCache = {};
/**
* Adds midimaps to the registry. Inside each midimap, control names (e.g. lpf) are mapped to cc numbers.
* @param {string | object} map
* @tags external_io, midi
* @example
* midimaps({ mymap: { lpf: 74 } })
@@ -290,6 +292,12 @@ function sendNote(note, velocity, duration, device, midichan, timeMs) {
* @tags external_io
* @param {string | number} midiport MIDI device name or index defaulting to 0
* @param {object} options Additional MIDI configuration options
* @param {boolean} options.isController sending notes for midi controllers. Default is false
* @param {number} options.noteOffsetMs note-off offset to prevent glitching in ms. Default is 10 or firefox and 1 otherwise
* @param {number} options.midichannel default is 1
* @param {number} options.velocity default is 0.9
* @param {number} options.gain default is 1
* @param {string} options.midimap default is 'default'
* @example
* note("c4").midichan(1).midi('IAC Driver Bus 1')
*/
@@ -476,6 +484,8 @@ Pattern.prototype.midi = function (midiport, options = {}) {
/**
* Initialize a midi input device
* @param {string} input
* @returns {MidiInput}
*/
async function _initializeInput(input) {
if (isPattern(input)) {
+1 -1
View File
@@ -16,7 +16,7 @@
"url": "git+https://codeberg.org/uzu/strudel.git"
},
"keywords": [
"titdalcycles",
"tidalcycles",
"strudel",
"pattern",
"livecoding",
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, bench } from 'vitest';
import { calculateSteps } from '../../core/index.mjs';
import { calculateSteps } from '@strudel/pattern';
import { mini } from '../index.mjs';
describe('mini', () => {
+2 -2
View File
@@ -5,8 +5,8 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import * as krill from './krill-parser.js';
import * as strudel from '@strudel/core';
import Fraction, { lcm } from '@strudel/core/fraction.mjs';
import * as strudel from '@strudel/pattern';
import { Fraction, lcm } from '@strudel/pattern';
const randOffset = 0.0003;
+1 -1
View File
@@ -32,7 +32,7 @@
},
"homepage": "https://codeberg.org/uzu/strudel#readme",
"dependencies": {
"@strudel/core": "workspace:*"
"@strudel/pattern": "workspace:*"
},
"devDependencies": {
"peggy": "^4.2.0",
+2 -2
View File
@@ -5,8 +5,8 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import { getLeafLocation, getLeafLocations, mini, mini2ast } from '../mini.mjs';
import '@strudel/core/euclid.mjs';
import { Fraction } from '@strudel/core/index.mjs';
import '@strudel/pattern';
import { Fraction } from '@strudel/pattern';
import { describe, expect, it } from 'vitest';
describe('mini', () => {
+16 -16
View File
@@ -1,11 +1,11 @@
// motion.mjs
import { signal } from '../core/signal.mjs';
import { signal } from '@strudel/core';
/**
* The accelerometer's x-axis value ranges from 0 to 1.
* @name accelerationX
* @return {Pattern}
* @returns {Pattern}
* @synonyms accX
* @tags external_io
* @example
@@ -16,7 +16,7 @@ import { signal } from '../core/signal.mjs';
/**
* The accelerometer's y-axis value ranges from 0 to 1.
* @name accelerationY
* @return {Pattern}
* @returns {Pattern}
* @synonyms accY
* @tags external_io
* @example
@@ -27,7 +27,7 @@ import { signal } from '../core/signal.mjs';
/**
* The accelerometer's z-axis value ranges from 0 to 1.
* @name accelerationZ
* @return {Pattern}
* @returns {Pattern}
* @synonyms accZ
* @tags external_io
* @example
@@ -38,7 +38,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's gravity x-axis value ranges from 0 to 1.
* @name gravityX
* @return {Pattern}
* @returns {Pattern}
* @synonyms gravX
* @tags external_io
* @example
@@ -49,7 +49,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's gravity y-axis value ranges from 0 to 1.
* @name gravityY
* @return {Pattern}
* @returns {Pattern}
* @synonyms gravY
* @tags external_io
* @example
@@ -60,7 +60,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's gravity z-axis value ranges from 0 to 1.
* @name gravityZ
* @return {Pattern}
* @returns {Pattern}
* @synonyms gravZ
* @tags external_io
* @example
@@ -71,7 +71,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's rotation around the alpha-axis value ranges from 0 to 1.
* @name rotationAlpha
* @return {Pattern}
* @returns {Pattern}
* @synonyms rotA, rotZ, rotationZ
* @tags external_io
* @example
@@ -82,7 +82,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's rotation around the beta-axis value ranges from 0 to 1.
* @name rotationBeta
* @return {Pattern}
* @returns {Pattern}
* @synonyms rotB, rotX, rotationX
* @tags external_io
* @example
@@ -93,7 +93,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's rotation around the gamma-axis value ranges from 0 to 1.
* @name rotationGamma
* @return {Pattern}
* @returns {Pattern}
* @synonyms rotG, rotY, rotationY
* @tags external_io
* @example
@@ -104,7 +104,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's orientation alpha value ranges from 0 to 1.
* @name orientationAlpha
* @return {Pattern}
* @returns {Pattern}
* @synonyms oriA, oriZ, orientationZ
* @tags external_io
* @example
@@ -115,7 +115,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's orientation beta value ranges from 0 to 1.
* @name orientationBeta
* @return {Pattern}
* @returns {Pattern}
* @synonyms oriB, oriX, orientationX
* @tags external_io
* @example
@@ -126,7 +126,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's orientation gamma value ranges from 0 to 1.
* @name orientationGamma
* @return {Pattern}
* @returns {Pattern}
* @synonyms oriG, oriY, orientationY
* @tags external_io
* @example
@@ -137,7 +137,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's absolute orientation alpha value ranges from 0 to 1.
* @name absoluteOrientationAlpha
* @return {Pattern}
* @returns {Pattern}
* @synonyms absOriA, absOriZ, absoluteOrientationZ
* @tags external_io
* @example
@@ -148,7 +148,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's absolute orientation beta value ranges from 0 to 1.
* @name absoluteOrientationBeta
* @return {Pattern}
* @returns {Pattern}
* @synonyms absOriB, absOriX, absoluteOrientationX
* @tags external_io
* @example
@@ -159,7 +159,7 @@ import { signal } from '../core/signal.mjs';
/**
* The device's absolute orientation gamma value ranges from 0 to 1.
* @name absoluteOrientationGamma
* @return {Pattern}
* @returns {Pattern}
* @synonyms absOriG, absOriY, absoluteOrientationY
* @tags external_io
* @example
+1 -1
View File
@@ -16,7 +16,7 @@
"url": "git+https://codeberg.org/uzu/strudel.git"
},
"keywords": [
"titdalcycles",
"tidalcycles",
"strudel",
"pattern",
"livecoding",
+1 -1
View File
@@ -16,7 +16,7 @@
"url": "git+https://codeberg.org/uzu/strudel.git"
},
"keywords": [
"titdalcycles",
"tidalcycles",
"strudel",
"pattern",
"livecoding",
+66 -7
View File
@@ -52,13 +52,13 @@ export function parseControlsFromHap(hap, cps) {
controls.unit === 'c' && controls.speed != null && (controls.speed = controls.speed / cps);
const channels = controls.channels;
channels != undefined && (controls.channels = JSON.stringify(channels));
return controls;
}
let timeOrigin = performance.timeOrigin;
export async function oscOutput(hap, targetTime, cps = 1) {
const ws = await connect();
function getOscTimestamp(targetTime) {
const timeMs = getClockBridge().getPerformanceTime(targetTime);
if (!timeMs) {
logger('[osc] clockbridge not ready');
@@ -72,21 +72,76 @@ export async function oscOutput(hap, targetTime, cps = 1) {
// shift time after microsleep
timeOrigin -= deprivation;
}
const ts = timeOrigin + timeMs;
return timeOrigin + timeMs;
}
export async function oscOutput(hap, targetTime, cps = 1) {
const ws = await connect();
const ts = getOscTimestamp(targetTime);
if (!ts) {
return;
}
const controls = parseControlsFromHap(hap, cps);
const keyvals = Object.entries(controls).flat();
const msg = { address: '/dirt/play', args: keyvals, timestamp: ts };
if ('oschost' in hap.value) {
msg['host'] = hap.value['oschost'];
msg.oschost = hap.value.oschost;
}
if ('oscport' in hap.value) {
msg['port'] = hap.value['oscport'];
msg.oscport = hap.value.oscport;
}
ws.send(JSON.stringify(msg));
}
export async function superdirtOutput(hap, targetTime, cps = 1) {
const ws = await connect();
const ts = getOscTimestamp(targetTime);
if (!ts) {
return;
}
const controls = parseControlsFromHap(hap, cps);
const oschost = hap.value.oschost ?? '127.0.0.1';
const oscport = hap.value.oscport ?? 57120;
const bushost = oschost;
const busport = 57110;
// send SuperDirt bus/control messages first
for (const [key, busIdVal] of Object.entries(controls)) {
if (key.startsWith('^')) {
ws.send(
JSON.stringify({
oschost: bushost,
oscport: busport,
address: '/c_set',
args: busIdVal,
timestamp: ts,
}),
);
// so they aren't sent with trigger messages
delete controls[key];
}
}
// only trigger samples on haps that actually begin here
if (hap.hasOnset()) {
const keyvals = Object.entries(controls).flat();
ws.send(
JSON.stringify({
oschost,
oscport,
address: '/dirt/play',
args: keyvals,
timestamp: ts,
}),
);
}
}
/**
*
* Sends each hap as an OSC message, which can be picked up by SuperCollider or any other OSC-enabled software.
@@ -94,10 +149,14 @@ export async function oscOutput(hap, targetTime, cps = 1) {
*
* @name osc
* @tags external_io
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const osc = register('osc', (pat) => {
ensureMinimalOutput();
return pat.onSchedule(oscOutput);
});
export const superdirt = register('superdirt', (pat) => {
ensureMinimalOutput();
return pat._processParts().onSchedule(superdirtOutput);
});
+9 -13
View File
@@ -12,18 +12,13 @@ import { WebSocketServer } from 'ws';
import osc from 'osc';
const WS_PORT = 8080; // WebSocket server port
const OSC_REMOTE_IP = '127.0.0.1';
const OSC_REMOTE_PORT = 57120;
const udpPort = new osc.UDPPort({
localAddress: '0.0.0.0',
localPort: 0,
remoteAddress: OSC_REMOTE_IP,
remotePort: OSC_REMOTE_PORT,
});
udpPort.open();
console.log(`[Sending OSC] ${OSC_REMOTE_IP}:${OSC_REMOTE_PORT}`);
udpPort.on('error', (e) => {
console.log('Error: ', e);
@@ -36,23 +31,24 @@ wss.on('connection', (ws) => {
console.log('New WebSocket connection');
ws.on('message', (message) => {
let osc_host = '127.0.0.1';
let osc_port = 57120;
let oschost = '127.0.0.1';
let oscport = 57120;
try {
const data = JSON.parse(message);
if ('host' in data) {
osc_host = data['host'];
if ('oschost' in data) {
oschost = data['oschost'];
delete data['oschost'];
}
if ('port' in data) {
osc_port = data['port'];
if ('oscport' in data) {
oscport = data['oscport'];
delete data['oscport'];
}
let msg = { address: data['address'], args: data['args'] };
if ('timestamp' in data) {
msg = { timeTag: osc.timeTag(0, data['timestamp']), packets: [msg] };
}
udpPort.send(msg, osc_host, osc_port);
udpPort.send(msg, oschost, oscport);
} catch (err) {
console.error('Error parsing message:', err);
}
+2 -4
View File
@@ -1,7 +1,5 @@
/* import { tauriOscOutput } from '../desktopbridge/oscbridge.mjs';
import { isTauri } from '../desktopbridge/utils.mjs'; */
import { oscOutput } from './osc.mjs';
// const output = /* isTauri() ? tauriOscOutput : */ oscOutput;
const output = /* isTauri() ? tauriOscOutput : */ oscOutput;
export const superdirtOutput = (hap, targetTime, cps) => output(hap, targetTime, cps);
export { superdirtOutput } from './osc.mjs';
@@ -16,9 +16,9 @@ import Fraction, { gcd } from './fraction.mjs';
* - "." silence
*
* @tags visualization
* @param {Pattern} pattern the pattern to use
* @param {Pattern} pat the pattern to use
* @param {number} chars max number of characters (approximately)
* @returns string
* @returns {string}
* @example
* const line = drawLine("0 [1 2 3]", 10); // |0--123|0--123
* console.log(line);
@@ -64,12 +64,12 @@ export const bjorklund = function (ons, steps) {
*
* A negative number of steps changes it into `euclidLegato`.
*
* @memberof Pattern
* @memberof Pattern.prototype
* @name euclid
* @tags temporal
* @param {number} pulses the number of onsets/beats
* @param {number} steps the number of steps to fill
* @returns Pattern
* @returns {Pattern}
* @example
* // The Cuban tresillo pattern.
* note("c3").euclid(3,8)
@@ -77,13 +77,13 @@ export const bjorklund = function (ons, steps) {
/**
* Like `euclid`, but has an additional parameter for 'rotating' the resulting sequence.
* @memberof Pattern
* @memberof Pattern.prototype
* @name euclidRot
* @tags temporal
* @param {number} pulses the number of onsets/beats
* @param {number} steps the number of steps to fill
* @param {number} rotation offset in steps
* @returns Pattern
* @returns {Pattern}
* @example
* // A Samba rhythm necklace from Brazil
* note("c3").euclidRot(3,16,14)
@@ -194,7 +194,7 @@ export const { euclidrot, euclidRot } = register(['euclidrot', 'euclidRot'], fun
*
* A negative number of steps changes it into `euclid`.
* @name euclidLegato
* @memberof Pattern
* @memberof Pattern.prototype
* @tags temporal
* @param {number} pulses the number of onsets/beats
* @param {number} steps the number of steps to fill
@@ -215,7 +215,7 @@ export const euclidLegato = register(['euclidLegato'], function (pulses, steps,
*
* A negative number of steps changes it into `euclidRot`.
* @name euclidLegatoRot
* @memberof Pattern
* @memberof Pattern.prototype
* @tags temporal
* @param {number} pulses the number of onsets/beats
* @param {number} steps the number of steps to fill
@@ -237,7 +237,7 @@ export const euclidLegatoRot = register(['euclidLegatoRot'], function (pulses, s
* Inspired by the work of Malcom Braff.
* @name euclidish
* @synonyms eish
* @memberof Pattern
* @memberof Pattern.prototype
* @tags temporal
* @param {number} pulses the number of onsets
* @param {number} steps the number of steps to fill
@@ -16,7 +16,7 @@ export class Hap {
then the whole will be returned as None, in which case the given
value will have been sampled from the point halfway between the
start and end of the 'part' timespan.
The context is to store a list of source code locations causing the event.
The context is to store metadata, including a list of source code locations causing the event.
The word 'Event' is more or less a reserved word in javascript, hence this
class is named called 'Hap'.
@@ -161,6 +161,10 @@ export class Hap {
return new Hap(this.whole, this.part, this.value, context);
}
withContext(f) {
return new Hap(this.whole, this.part, this.value, f(this.context));
}
ensureObjectValue() {
/* if (isNote(hap.value)) {
// supports primitive hap values that look like notes
+32
View File
@@ -0,0 +1,32 @@
/*
index.mjs - <short description TODO>
Copyright (C) 2025 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/index.mjs>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
export * from './euclid.mjs';
import Fraction, { lcm } from './fraction.mjs';
import { logger } from './logger.mjs';
export { Fraction, lcm };
export * from './hap.mjs';
export * from './impure.mjs';
export * from './logger.mjs';
export * from './pattern.mjs';
export * from './pick.mjs';
export * from './signal.mjs';
export * from './state.mjs';
export * from './timespan.mjs';
export * from './util.mjs';
export { default as drawLine } from './drawLine.mjs';
// below won't work with runtime.mjs (json import fails)
/* import * as p from './package.json';
export const version = p.version; */
logger('🌀 @strudel/pattern loaded 🌀');
if (globalThis._strudelLoaded) {
console.warn(
`@strudel/pattern was loaded more than once...
This might happen when you have multiple versions of strudel installed.
Please check with "npm ls @strudel/pattern".`,
);
}
globalThis._strudelLoaded = true;
@@ -5,7 +5,7 @@ let debounce = 1000,
lastTime;
export function errorLogger(e, origin = 'cyclist') {
if (process.env.NODE_ENV === 'development') {
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {
console.error(e);
}
logger(`[${origin}] error: ${e.message}`);
+44
View File
@@ -0,0 +1,44 @@
{
"name": "@strudel/pattern",
"version": "1.2.6",
"description": "Port of Tidal Cycles to JavaScript. This package contains only the pattern representation.",
"main": "index.mjs",
"type": "module",
"publishConfig": {
"main": "dist/index.mjs"
},
"scripts": {
"test": "vitest run",
"bench": "vitest bench",
"build": "vite build",
"prepublishOnly": "pnpm build"
},
"repository": {
"type": "git",
"url": "git+https://codeberg.org/uzu/strudel.git"
},
"keywords": [
"tidalcycles",
"strudel",
"pattern",
"livecoding",
"algorave"
],
"author": "Alex McLean <alex@slab.org> (https://slab.org)",
"license": "AGPL-3.0-or-later",
"bugs": {
"url": "https://codeberg.org/uzu/strudel/issues"
},
"homepage": "https://strudel.cc",
"dependencies": {
"fraction.js": "^5.2.1"
},
"gitHead": "0e26d4e741500f5bae35b023608f062a794905c2",
"devDependencies": {
"vite": "^6.0.11",
"vitest": "^3.0.4"
},
"engines": {
"node": ">=18.0.0"
}
}
File diff suppressed because it is too large Load Diff
@@ -28,6 +28,7 @@ const _pick = function (lookup, pat, modulo = true) {
/** * Picks patterns (or plain values) either from a list (by index) or a lookup table (by name).
* Similar to `inhabit`, but maintains the structure of the original patterns.
* The lookup can also be a pattern of objects, such as a pattern of controls, in which case each of its events is used as the lookup table.
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
@@ -40,6 +41,10 @@ const _pick = function (lookup, pat, modulo = true) {
* sound("<0!2 [0,1] 1>".pick(["bd(3,8)", "sd sd"]))
* @example
* s("<a!2 [a,b] b>".pick({a: "bd(3,8)", b: "sd sd"}))
* @example
* // pick a field out of a pattern of objects
* const pat = sound("bd cp").speed("<2 3>")
* pat.fast("speed".pick(pat))
*/
export const pick = function (lookup, pat) {
@@ -72,7 +77,7 @@ export const pickmod = register('pickmod', function (lookup, pat) {
* @tags combiners, functional
* @param {Pattern} pat
* @param {Pattern} lookup a pattern of indices or names
* @param {function[] | object} lookup the array or lookup object of functions from which to pull
* @param {Function[] | object} lookup the array or lookup object of functions from which to pull
* @returns {Pattern}
* @example
* s("bd [rim hh]").pickF("<0 1 2>", [rev,jux(rev),fast(2)])
@@ -92,7 +97,7 @@ export const pickF = register('pickF', function (pickPattern, lookup, pat) {
* @tags combiners
* @param {Pattern} pat
* @param {Pattern} lookup a pattern of indices or names
* @param {function[] | object} lookup the array or lookup object of functions from which to pull
* @param {Function[] | object} lookup the array or lookup object of functions from which to pull
* @returns {Pattern}
*/
export const pickmodF = register('pickmodF', function (pickPattern, lookup, pat) {
@@ -42,7 +42,7 @@ export const signal = (func) => {
/**
* A sawtooth signal between 0 and 1.
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
* @example
* note("<c3 [eb3,g3] g2 [g3,bb3]>*8")
@@ -57,7 +57,7 @@ export const saw = signal((t) => _mod(t, 1));
/**
* A sawtooth signal between -1 and 1 (like `saw`, but bipolar).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const saw2 = saw.toBipolar();
@@ -65,7 +65,7 @@ export const saw2 = saw.toBipolar();
/**
* A sawtooth signal between 1 and 0 (like `saw`, but flipped).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
* @example
* note("<c3 [eb3,g3] g2 [g3,bb3]>*8")
@@ -80,7 +80,7 @@ export const isaw = signal((t) => 1 - _mod(t, 1));
/**
* A sawtooth signal between 1 and -1 (like `saw2`, but flipped).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const isaw2 = isaw.toBipolar();
@@ -88,14 +88,14 @@ export const isaw2 = isaw.toBipolar();
/**
* A sine signal between -1 and 1 (like `sine`, but bipolar).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const sine2 = signal((t) => Math.sin(Math.PI * 2 * t));
/**
* A sine signal between 0 and 1.
* @return {Pattern}
* @returns {Pattern}
* @tags generators
* @example
* n(sine.segment(16).range(0,15))
@@ -107,7 +107,7 @@ export const sine = sine2.fromBipolar();
/**
* A cosine signal between 0 and 1.
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
* @example
* n(stack(sine,cosine).segment(16).range(0,15))
@@ -119,14 +119,14 @@ export const cosine = sine._early(Fraction(1).div(4));
/**
* A cosine signal between -1 and 1 (like `cosine`, but bipolar).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const cosine2 = sine2._early(Fraction(1).div(4));
/**
* A square signal between 0 and 1.
* @return {Pattern}
* @returns {Pattern}
* @tags generators
* @example
* n(square.segment(4).range(0,7)).scale("C:minor")
@@ -137,7 +137,7 @@ export const square = signal((t) => Math.floor(_mod(t * 2, 2)));
/**
* A square signal between -1 and 1 (like `square`, but bipolar).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const square2 = square.toBipolar();
@@ -145,7 +145,7 @@ export const square2 = square.toBipolar();
/**
* A square signal between 1 and 0 (like `square` but flipped).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const isquare = signal((t) => 1 - Math.floor(_mod(t * 2, 2)));
@@ -153,7 +153,7 @@ export const isquare = signal((t) => 1 - Math.floor(_mod(t * 2, 2)));
/**
* A square signal between 1 and -1 (like `isquare`, but bipolar).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const isquare2 = isquare.toBipolar();
@@ -161,7 +161,7 @@ export const isquare2 = isquare.toBipolar();
/**
* A triangle signal between 0 and 1.
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
* @example
* n(tri.segment(8).range(0,7)).scale("C:minor")
@@ -172,7 +172,7 @@ export const tri = fastcat(saw, isaw);
/**
* A triangle signal between -1 and 1 (like `tri`, but bipolar).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const tri2 = fastcat(saw2, isaw2);
@@ -180,7 +180,7 @@ export const tri2 = fastcat(saw2, isaw2);
/**
* An inverted triangle signal between 1 and 0 (like `tri`, but flipped).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
* @example
* n(itri.segment(8).range(0,7)).scale("C:minor")
@@ -191,7 +191,7 @@ export const itri = fastcat(isaw, saw);
/**
* An inverted triangle signal between -1 and 1 (like `itri`, but bipolar).
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const itri2 = fastcat(isaw2, saw2);
@@ -199,7 +199,7 @@ export const itri2 = fastcat(isaw2, saw2);
/**
* A signal representing the cycle time.
*
* @return {Pattern}
* @returns {Pattern}
* @tags generators
*/
export const time = signal(id);
@@ -208,7 +208,7 @@ export const time = signal(id);
* The mouse's x position value ranges from 0 to 1.
* @name mousex
* @synonyms mouseX
* @return {Pattern}
* @returns {Pattern}
* @tags external_io
* @example
* n(mousex.segment(4).range(0,7)).scale("C:minor")
@@ -219,7 +219,7 @@ export const time = signal(id);
* The mouse's y position value ranges from 0 to 1.
* @name mousey
* @synonyms mouseY
* @return {Pattern}
* @returns {Pattern}
* @tags external_io
* @example
* n(mousey.segment(4).range(0,7)).scale("C:minor")
@@ -324,7 +324,8 @@ export const getRandsAtTime = (t, n = 1, seed = 0) => {
*
* @name useRNG
* @tags generators, math
* @param {string} mod - Mode. One of 'legacy', 'precise'
* @param {string} mode One of 'legacy', 'precise'
* @returns {void}
* @example
* useRNG('legacy')
* // Repeats every 300 cycles
@@ -335,7 +336,9 @@ export const useRNG = (mode = 'legacy') => (RNG_MODE = mode);
/**
* A discrete pattern of numbers from 0 to n-1
* @param {number} n
* @tags generators
* @returns {Pattern}
* @example
* n(run(4)).scale("C4:pentatonic")
* // n("0 1 2 3").scale("C4:pentatonic")
@@ -348,6 +351,7 @@ export const run = (n) => saw.range(0, n).round().segment(n);
* @name binary
* @tags generators
* @param {number} n - input number to convert to binary
* @returns {Pattern}
* @example
* "hh".s().struct(binary(5))
* // "hh".s().struct("1 0 1")
@@ -364,6 +368,7 @@ export const binary = (n) => {
* @tags generators
* @param {number} n - input number to convert to binary
* @param {number} nBits - pattern length, defaults to 16
* @returns {Pattern}
* @example
* "hh".s().struct(binaryN(55532, 16))
* // "hh".s().struct("1 1 0 1 1 0 0 0 1 1 1 0 1 1 0 0")
@@ -381,6 +386,8 @@ export const binaryN = (n, nBits = 16) => {
* @name binaryL
* @tags generators
* @param {number} n - input number to convert to binary
* @returns {Pattern}
* @example
* s("saw").seg(8)
* .partials(binaryL(irand(4096).add(1)))
*/
@@ -396,6 +403,7 @@ export const binaryL = (n) => {
* @tags generators
* @param {number} n - input number to convert to binary
* @param {number} nBits - pattern length, defaults to 16
* @returns {Pattern}
*/
export const binaryNL = (n, nBits = 16) => {
return reify(n)
@@ -415,12 +423,13 @@ export const binaryNL = (n, nBits = 16) => {
* @name randL
* @tags generators
* @param {number} n Number of random numbers to sample
* @returns {Pattern}
* @example
* s("saw").seg(16).n(irand(12)).scale("F1:minor")
* .partials(randL(8))
*/
export const randL = (n) => {
return signal((t) => (nVal) => getRandsAtTime(t, nVal).map(Math.abs)).appLeft(reify(n));
return signal((t, controls) => (nVal) => getRandsAtTime(t, nVal, controls.randSeed).map(Math.abs)).appLeft(reify(n));
};
export const randrun = (n) => {
@@ -477,7 +486,7 @@ export const scramble = register('scramble', (n, pat) => {
* @tags math
* @param {Function} func Function from seed (or undefined) to seed (or undefined)
* @param {Pattern} pat Pattern to update
* @returns Pattern
* @returns {Pattern}
*/
export const withSeed = (func, pat) => {
return new Pattern((state) => {
@@ -528,7 +537,8 @@ export const _brandBy = (p) => rand.fmap((x) => x < p);
*
* @name brandBy
* @tags generators
* @param {number} probability - a number between 0 and 1
* @param {number} pPat probability - a number between 0 and 1
* @returns {Pattern}
* @example
* s("hh*10").pan(brandBy(0.2))
*/
@@ -551,7 +561,8 @@ export const _irand = (i) => rand.fmap((x) => Math.trunc(x * i));
*
* @name irand
* @tags generators
* @param {number} n max value (exclusive)
* @param {number} ipat max value (exclusive)
* @returns {Pattern}
* @example
* // randomly select scale notes from 0 - 7 (= C to C)
* n(irand(8)).struct("x x*2 x x*3").scale("C:minor")
@@ -624,6 +635,7 @@ export const chooseIn = (...xs) => chooseInWith(rand, xs);
* the range 0 .. 1.
* @tags temporal
* @param {...any} xs
* @memberof Pattern.prototype
* @returns {Pattern}
*/
Pattern.prototype.choose = function (...xs) {
@@ -635,6 +647,7 @@ Pattern.prototype.choose = function (...xs) {
* in the range -1 .. 1
* @tags temporal
* @param {...any} xs
* @memberof Pattern.prototype
* @returns {Pattern}
*/
Pattern.prototype.choose2 = function (...xs) {
@@ -643,6 +656,7 @@ Pattern.prototype.choose2 = function (...xs) {
/**
* Picks one of the elements at random each cycle.
* @param {...any} xs
* @tags temporal
* @synonyms randcat
* @returns {Pattern}
@@ -696,6 +710,7 @@ export const wchoose = (...pairs) => wchooseWith(rand, ...pairs);
/**
* Picks one of the elements at random each cycle by giving a probability to each element
* @param {...any} pairs
* @tags temporal
* @synonyms wrandcat
* @returns {Pattern}
@@ -772,7 +787,7 @@ export const berlin = signal((t, controls) => _berlin(t, controls.randSeed));
* @name degradeByWith
* @param {Pattern|number} test
* @param {Pattern|number} testAgainst
* @memberof Pattern
* @memberof Pattern.prototype
* @tags temporal
* @returns {Pattern}
* @example
@@ -794,9 +809,9 @@ export const degradeByWith = register('degradeByWith', (withPat, x, pat) => {
*
* @tags temporal
* @name degradeBy
* @memberof Pattern
* @memberof Pattern.prototype
* @param {number} amount - a number between 0 and 1
* @returns Pattern
* @returns {Pattern}
* @example
* s("hh*8").degradeBy(0.2)
* @example
@@ -820,8 +835,8 @@ export const degradeBy = register(
*
* @tags temporal
* @name degrade
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("hh*8").degrade()
* @example
@@ -837,9 +852,9 @@ export const degrade = register('degrade', (pat) => pat._degradeBy(0.5), true, t
*
* @tags temporal
* @name undegradeBy
* @memberof Pattern
* @memberof Pattern.prototype
* @param {number} amount - a number between 0 and 1
* @returns Pattern
* @returns {Pattern}
* @example
* s("hh*8").undegradeBy(0.2)
* @example
@@ -866,8 +881,8 @@ export const undegradeBy = register(
*
* @tags temporal
* @name undegrade
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("hh*8").undegrade()
* @example
@@ -885,10 +900,10 @@ export const undegrade = register('undegrade', (pat) => pat._undegradeBy(0.5), t
*
* @tags temporal
* @name sometimesBy
* @memberof Pattern
* @memberof Pattern.prototype
* @param {number | Pattern} probability - a number between 0 and 1
* @param {function} function - the transformation to apply
* @returns Pattern
* @param {Function} function - the transformation to apply
* @returns {Pattern}
* @example
* s("hh*8").sometimesBy(.4, x=>x.speed("0.5"))
*/
@@ -905,9 +920,9 @@ export const sometimesBy = register('sometimesBy', function (patx, func, pat) {
*
* @tags temporal
* @name sometimes
* @memberof Pattern
* @param {function} function - the transformation to apply
* @returns Pattern
* @memberof Pattern.prototype
* @param {Function} function - the transformation to apply
* @returns {Pattern}
* @example
* s("hh*8").sometimes(x=>x.speed("0.5"))
*/
@@ -921,10 +936,10 @@ export const sometimes = register('sometimes', function (func, pat) {
* Similar to `sometimesBy`
*
* @name someCyclesBy
* @memberof Pattern
* @memberof Pattern.prototype
* @param {number | Pattern} probability - a number between 0 and 1
* @param {function} function - the transformation to apply
* @returns Pattern
* @param {Function} function - the transformation to apply
* @returns {Pattern}
* @tags temporal
* @example
* s("bd,hh*8").someCyclesBy(.3, x=>x.speed("0.5"))
@@ -946,8 +961,8 @@ export const someCyclesBy = register('someCyclesBy', function (patx, func, pat)
* Shorthand for `.someCyclesBy(0.5, fn)`
*
* @name someCycles
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @tags temporal
* @example
* s("bd,hh*8").someCycles(x=>x.speed("0.5"))
@@ -961,8 +976,8 @@ export const someCycles = register('someCycles', function (func, pat) {
* Shorthand for `.sometimesBy(0.75, fn)`
*
* @name often
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @tags temporal
* @example
* s("hh*8").often(x=>x.speed("0.5"))
@@ -976,8 +991,8 @@ export const often = register('often', function (func, pat) {
* Shorthand for `.sometimesBy(0.25, fn)`
*
* @name rarely
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @tags temporal
* @example
* s("hh*8").rarely(x=>x.speed("0.5"))
@@ -992,8 +1007,8 @@ export const rarely = register('rarely', function (func, pat) {
*
* @tags temporal
* @name almostNever
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("hh*8").almostNever(x=>x.speed("0.5"))
*/
@@ -1007,8 +1022,8 @@ export const almostNever = register('almostNever', function (func, pat) {
*
* @tags temporal
* @name almostAlways
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("hh*8").almostAlways(x=>x.speed("0.5"))
*/
@@ -1022,8 +1037,8 @@ export const almostAlways = register('almostAlways', function (func, pat) {
*
* @tags temporal
* @name never
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("hh*8").never(x=>x.speed("0.5"))
*/
@@ -1037,8 +1052,8 @@ export const never = register('never', function (_, pat) {
*
* @tags temporal
* @name always
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("hh*8").always(x=>x.speed("0.5"))
*/
@@ -1066,8 +1081,8 @@ export function _keyDown(keyname) {
*
* @tags external_io
* @name whenKey
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("bd(5,8)").whenKey("Control:j", x => x.segment(16).color("red")).whenKey("Control:i", x => x.fast(2).color("blue"))
*/
@@ -1083,8 +1098,8 @@ export const whenKey = register('whenKey', function (input, func, pat) {
*
* @tags external_io
* @name keyDown
* @memberof Pattern
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* keyDown("Control:j").pick([s("bd(5,8)"), s("cp(3,8)")])
*/
@@ -1143,3 +1158,26 @@ export const perx = new Pattern(function (state) {
const n = Fraction(1).div(state.span.duration);
return [new Hap(undefined, state.span, Math.log(n) / Math.log(2) + 1)];
});
/**
* A signal that goes from `0` to `1` over one cycle, and then stays at `1` forever.
* Mainly useful in combination with other functions that reset the cycle. See also
* `close`.
* @tags temporal
* @example
* sound("bd sd [- bd] sd".fast(2))
* .lpf(open.slow(4).range(300,3000)) // close envelope over 4 cycles
* .restart("x/4") // restart every 4 cycles
*/
export const open = signal((t) => t.min(1));
/**
* The same as `open`, but goes from `1` to `0` over one cycle, and then
* stays on `0` forever.
* @tags temporal
* @example
* sound("bd sd [- bd] sd".fast(2))
* .lpf(close.slow(4).range(300,3000)) // close envelope over 4 cycles
* .restart("x/4") // restart every 4 cycles
*/
export const close = signal((t) => Fraction(1).sub(t).max(0));
@@ -58,11 +58,12 @@ import {
arp,
} from '../index.mjs';
import { log, logValues, stackCenter } from '../pattern.mjs';
import { reify, stackCenter } from '../pattern.mjs';
import { steady } from '../signal.mjs';
import { n, s } from '../controls.mjs';
let n = (value) => reify(value).fmap((v) => ({ n: v }));
let s = (value) => reify(value).fmap((v) => ({ s: v }));
const st = (begin, end) => new State(ts(begin, end));
const ts = (begin, end) => new TimeSpan(Fraction(begin), Fraction(end));
@@ -71,7 +72,7 @@ const hap = (whole, part, value, context = {}) => new Hap(whole, part, value, co
const third = Fraction(1, 3);
const twothirds = Fraction(2, 3);
const sameFirst = (a, b) => {
export const sameFirst = (a, b) => {
return expect(a.sortHapsByPart().firstCycle()).toStrictEqual(b.sortHapsByPart().firstCycle());
};
@@ -876,24 +877,6 @@ describe('Pattern', () => {
);
});
});
describe('jux', () => {
it('Can juxtapose', () => {
expect(pure({ a: 1 }).jux(fast(2)).sortHapsByPart().firstCycle()).toStrictEqual(
stack(pure({ a: 1, pan: 0 }), pure({ a: 1, pan: 1 }).fast(2))
.sortHapsByPart()
.firstCycle(),
);
});
});
describe('juxBy', () => {
it('Can juxtapose by half', () => {
expect(pure({ a: 1 }).juxBy(0.5, fast(2)).sortHapsByPart().firstCycle()).toStrictEqual(
stack(pure({ a: 1, pan: 0.25 }), pure({ a: 1, pan: 0.75 }).fast(2))
.sortHapsByPart()
.firstCycle(),
);
});
});
describe('_squeezeJoin', () => {
it('Can squeeze', () => {
expect(
@@ -931,46 +914,6 @@ describe('Pattern', () => {
expect(sequence(1, 2, 3).ply(2).early(8).firstCycle().length).toBe(6);
});
});
describe('striate', () => {
it('Can striate(2)', () => {
sameFirst(
sequence({ sound: 'a' }).striate(2),
sequence({ sound: 'a', begin: 0, end: 0.5 }, { sound: 'a', begin: 0.5, end: 1 }),
);
});
});
describe('chop', () => {
it('Can _chop(2)', () => {
expect(sequence({ sound: 'a' }, { sound: 'b' })._chop(2).firstCycle()).toStrictEqual(
sequence(
{ sound: 'a', begin: 0, end: 0.5 },
{ sound: 'a', begin: 0.5, end: 1 },
{ sound: 'b', begin: 0, end: 0.5 },
{ sound: 'b', begin: 0.5, end: 1 },
).firstCycle(),
);
});
it('Can chop(2,3)', () => {
expect(pure({ sound: 'a' }).fast(2).chop(2, 3).sortHapsByPart().firstCycle()).toStrictEqual(
sequence(
[
{ sound: 'a', begin: 0, end: 0.5 },
{ sound: 'a', begin: 0.5, end: 1 },
],
[
{ sound: 'a', begin: 0, end: 1 / 3 },
{ sound: 'a', begin: 1 / 3, end: 2 / 3 },
{ sound: 'a', begin: 2 / 3, end: 1 },
],
)
.sortHapsByPart()
.firstCycle(),
);
});
it('Can chop chops', () => {
expect(pure({ s: 'bev' }).chop(2).chop(2).firstCycle()).toStrictEqual(pure({ s: 'bev' }).chop(4).firstCycle());
});
});
describe('range', () => {
it('Can be patterned', () => {
expect(sequence(0, 0).range(sequence(0, 0.5), 1).firstCycle()).toStrictEqual(sequence(0, 0.5).firstCycle());
@@ -1053,11 +996,6 @@ describe('Pattern', () => {
sameFirst(sequence('a', 'b', 'c', 'd').press(), sequence(silence, 'a', silence, 'b', silence, 'c', silence, 'd'));
});
});
describe('hurry', () => {
it('Can speed up patterns and sounds', () => {
sameFirst(s(sequence('a', 'b')).hurry(2), s(sequence('a', 'b')).fast(2).speed(2));
});
});
/*describe('composable functions', () => {
it('Can compose functions', () => {
sameFirst(sequence(3, 4).fast(2).rev().fast(2), fast(2).rev().fast(2)(sequence(3, 4)));
@@ -1076,32 +1014,6 @@ describe('Pattern', () => {
});
});
*/
describe('slice', () => {
it('Can slice a sample', () => {
sameFirst(
s('break').slice(4, sequence(0, 1, 2, 3)),
sequence(
{ begin: 0, end: 0.25, s: 'break', _slices: 4 },
{ begin: 0.25, end: 0.5, s: 'break', _slices: 4 },
{ begin: 0.5, end: 0.75, s: 'break', _slices: 4 },
{ begin: 0.75, end: 1, s: 'break', _slices: 4 },
),
);
});
});
describe('splice', () => {
it('Can splice a sample', () => {
sameFirst(
s('break').splice(4, sequence(0, 1, 2, 3)),
sequence(
{ begin: 0, end: 0.25, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.25, end: 0.5, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.5, end: 0.75, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.75, end: 1, s: 'break', _slices: 4, unit: 'c', speed: 1 },
),
);
});
});
describe('chunk', () => {
it('Processes each cycle of the source pattern multiple times, once for each chunk', () => {
expect(sequence(0, 1, 2, 3).slow(2).chunk(2, add(10)).fast(4).firstCycleValues).toStrictEqual([
@@ -1169,6 +1081,15 @@ describe('Pattern', () => {
),
);
});
it('Can pick values from a pattern of objects', () => {
const pat = slowcat({ s: 'bd', speed: 2 }, { s: 'cp', speed: 3 });
expect(
pure('speed')
.pick(pat)
.queryArc(0, 2)
.map((hap) => hap.value),
).toStrictEqual([2, 3]);
});
});
describe('pickmod', () => {
it('Wraps indexes', () => {
@@ -1180,24 +1101,15 @@ describe('Pattern', () => {
);
});
});
describe('_steps', () => {
it('Is correctly preserved/calculated through transformations', () => {
expect(sequence(0, 1, 2, 3).linger(4)._steps).toStrictEqual(Fraction(4));
expect(sequence(0, 1, 2, 3).iter(4)._steps).toStrictEqual(Fraction(4));
expect(sequence(0, 1, 2, 3).fast(4)._steps).toStrictEqual(Fraction(4));
expect(sequence(0, 1, 2, 3).hurry(4)._steps).toStrictEqual(Fraction(4));
expect(sequence(0, 1, 2, 3).rev()._steps).toStrictEqual(Fraction(4));
expect(sequence(1).segment(10)._steps).toStrictEqual(Fraction(10));
expect(sequence(1, 0, 1).invert()._steps).toStrictEqual(Fraction(3));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).chop(4)._steps).toStrictEqual(Fraction(8));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).striate(4)._steps).toStrictEqual(Fraction(8));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).slice(4, sequence(0, 1, 2, 3))._steps).toStrictEqual(
Fraction(4),
);
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).splice(4, sequence(0, 1, 2, 3))._steps).toStrictEqual(
Fraction(4),
);
expect(sequence({ n: 0 }, { n: 1 }, { n: 2 }).chop(4)._steps).toStrictEqual(Fraction(12));
expect(
pure((x) => x + 1)
.setSteps(3)
@@ -1310,11 +1222,6 @@ describe('Pattern', () => {
);
});
});
describe('loopAt', () => {
it('maintains steps', () => {
expect(s('bev').chop(8).loopAt(2)._steps).toStrictEqual(Fraction(4));
});
});
describe('bite', () => {
it('works with uneven patterns', () => {
sameFirst(
@@ -1396,7 +1303,7 @@ describe('Pattern', () => {
describe('logValues', () => {
it('logs values to console', () => {
const mockConsoleLog = vi.spyOn(console, 'log').mockImplementation(() => {});
const pattern = pure('a').note('c#').logValues();
const pattern = pure({ s: 'bd', speed: 2 }).logValues();
const haps = pattern.queryArc(0, 1);
// Force a trigger
@@ -1405,7 +1312,7 @@ describe('Pattern', () => {
});
expect(mockConsoleLog).toHaveBeenCalledWith(
'%c[hap] value:a note:c#',
'%c[hap] s:bd speed:2',
'background-color: black;color:white;border-radius:15px',
);
mockConsoleLog.mockRestore();
@@ -6,7 +6,7 @@ This program is free software: you can redistribute it and/or modify it under th
import Fraction from 'fraction.js';
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect } from 'vitest';
import {
saw,
@@ -25,7 +25,7 @@ import {
perx,
cyclesPer,
} from '../signal.mjs';
import { fastcat, sequence, State, TimeSpan, Hap, note } from '../index.mjs';
import { fastcat, sequence, State, TimeSpan, Hap, seq } from '../index.mjs';
const st = (begin, end) => new State(ts(begin, end));
const ts = (begin, end) => new TimeSpan(Fraction(begin), Fraction(end));
@@ -122,6 +122,6 @@ describe('perx', () => {
describe('shuffle', () => {
it('returns original pattern if input is 1', () => {
expect(note('c d e f').sound('piano').shuffle(1).firstCycle()).toEqual(note('c d e f').sound('piano').firstCycle());
expect(seq(1, 2, 3, 4).shuffle(1).firstCycle()).toEqual(seq(1, 2, 3, 4).firstCycle());
});
});
@@ -6,7 +6,6 @@ This program is free software: you can redistribute it and/or modify it under th
import { describe, it, expect } from 'vitest';
import { map, valued, mul } from '../value.mjs';
import { n } from '../controls.mjs';
describe('Value', () => {
it('unionWith', () => {
@@ -72,8 +72,11 @@ export const getEventOffsetMs = (targetTimeSeconds, currentTimeSeconds) => {
const pcs = ['C', 'Db', 'D', 'Eb', 'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B'];
/**
* converts midi values into notes
* @param {number} n
* @deprecated only used in workshop (first-notes)
* @noAutocomplete
* @returns {string}
*/
export const midi2note = (n) => {
const oct = Math.floor(n / 12) - 1;
@@ -131,8 +134,8 @@ export const getPlayableNoteValue = (hap) => {
* @name getFrequency
* @tags pitch
* @synonyms getFreq
* @param {Hap | note | number} input
* @returns {Number}
* @param {Hap | note | number} hap input
* @returns {number}
* @example
* i("4 8 9 10 - - 5 7 9 11 - -").tune("tranh3")
* .mul(getFreq('c3'))
+20
View File
@@ -0,0 +1,20 @@
import { defineConfig } from 'vite';
import { dependencies } from './package.json';
import { resolve } from 'path';
// https://vitejs.dev/config/
export default defineConfig({
base: './',
plugins: [],
build: {
lib: {
entry: resolve(__dirname, 'index.mjs'),
formats: ['es'],
fileName: (ext) => ({ es: 'index.mjs' })[ext],
},
rollupOptions: {
external: [...Object.keys(dependencies)],
},
target: 'esnext',
},
});
+2 -1
View File
@@ -43,7 +43,8 @@
"@strudel/soundfonts": "workspace:*",
"@strudel/tonal": "workspace:*",
"@strudel/transpiler": "workspace:*",
"@strudel/webaudio": "workspace:*"
"@strudel/webaudio": "workspace:*",
"@strudel/websocket": "workspace:*"
},
"devDependencies": {
"@rollup/plugin-replace": "^6.0.2",
+1
View File
@@ -15,6 +15,7 @@ export async function prebake() {
import('@strudel/hydra'),
import('@strudel/soundfonts'),
import('@strudel/midi'),
import('@strudel/websocket'),
// import('@strudel/xen'),
// import('@strudel/serial'),
// import('@strudel/csound'),
+20 -3
View File
@@ -21,12 +21,29 @@ LOG=1 npx @strudel/sampler # adds logging
PORT=5555 npx @strudel/sampler # changes port
```
## static json
### --json
when running with `--json`, you will simply get the json logged back:
```sh
npx --yes @strudel/sampler --json > strudel.json
npx @strudel/sampler --json > strudel.json
```
this is useful if you want to create a sample pack from the current folder.
### `--dir`
specifies the directory to serve. defaults to cwd
```sh
npx @strudel/sampler --dir ~/Music/samples
```
### `--flat`
with `--flat`, each file gets its own name, not grouped by directory.
```sh
npx @strudel/sampler --flat
```
this is useful if you want to create a sample pack from the current folder.
+28 -53
View File
@@ -1,21 +1,40 @@
#!/usr/bin/env node
import cowsay from 'cowsay';
import { createReadStream, existsSync, writeFileSync } from 'fs';
import { createReadStream, existsSync } from 'fs';
import { readdir } from 'fs/promises';
import http from 'http';
import { join, resolve, sep } from 'path';
import readline from 'readline';
import os from 'os';
const LOG = !!process.env.LOG || false;
const PORT = process.env.PORT || 5432;
const VALID_AUDIO_EXTENSIONS = ['wav', 'mp3', 'ogg'];
const isAudioFile = (f) => {
const args = {};
// parse args
for (const arg of process.argv.slice(2)) {
if (arg === '--json') args.json = true;
if (arg === '--flat') args.flat = true;
if (arg === '--dir') args.dir = process.argv[process.argv.indexOf(arg) + 1];
}
const directory = resolve(args.dir || process.cwd());
const banks = await getBanks(directory, args.flat);
// if --json, output banks and exit
if (args.json) {
// stringify in expanded format
const json = JSON.stringify(banks, null, 2);
process.stdout.write(json + '\n');
process.exit(0);
}
function isAudioFile(f) {
const ext = f.split('.').slice(-1)[0].toLowerCase();
return VALID_AUDIO_EXTENSIONS.includes(ext);
};
}
async function getFilesInDirectory(directory) {
let files = [];
@@ -41,11 +60,11 @@ async function getFilesInDirectory(directory) {
return files;
}
async function getBanks(directory, flat = false) {
let files = await getFilesInDirectory(directory);
let banks = {};
async function getBanks(directory, flat) {
const banks = {};
const files = await getFilesInDirectory(directory);
directory = directory.split(sep).join('/');
files = files.map((path) => {
files.forEach((path) => {
path = path.split(sep).join('/');
const subDir = path.replace(directory, '');
const subDirFlat = subDir.replaceAll('/', '_').slice(1); // remove initial underscore
@@ -55,50 +74,7 @@ async function getBanks(directory, flat = false) {
banks[bank].push(subDir);
return subDir;
});
return { banks, files };
}
const args = process.argv.slice(2);
function getArgValue(flag) {
const i = args.indexOf(flag);
if (i !== -1) {
const nextIsFlag = args[i + 1]?.startsWith('--') ?? true;
if (nextIsFlag) return true;
return args[i + 1];
}
}
function getInput(query) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) =>
rl.question(query, (response) => {
rl.close();
resolve(response);
}),
);
}
let directory = getArgValue('--dir') || process.cwd();
directory = resolve(directory);
if (args.includes('--json')) {
const { banks } = await getBanks(directory, getArgValue('--flat'));
const json = JSON.stringify(banks);
const outFile = resolve(directory, 'strudel.json');
if (existsSync(outFile)) {
const answer = await getInput(`Warning: File already exists at ${outFile}. Overwrite? (y/N): `);
if (answer.toLowerCase() !== 'y') {
console.log('Aborted.');
process.exit(0);
}
}
writeFileSync(outFile, json, 'utf8');
console.log(`Wrote json to ${outFile}`);
process.exit(0);
return banks;
}
console.log(
@@ -111,7 +87,6 @@ console.log(
const server = http.createServer(async (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
const { banks, files } = await getBanks(directory, getArgValue('--flat'));
if (req.url === '/') {
res.setHeader('Content-Type', 'application/json');
return res.end(JSON.stringify(banks));
+1 -1
View File
@@ -16,7 +16,7 @@
"url": "git+https://codeberg.org/uzu/strudel.git"
},
"keywords": [
"titdalcycles",
"tidalcycles",
"strudel",
"pattern",
"livecoding",
+1 -1
View File
@@ -250,7 +250,7 @@ export function createFilter(context, start, end, params, cps, cycle) {
} = params;
let frequencyParam, filter;
if (model === 'ladder') {
if (model === 'ladder' && type === 'lowpass') {
filter = getWorklet(context, 'ladder-processor', { frequency, q, drive });
frequencyParam = filter.parameters.get('frequency');
} else {
+4
View File
@@ -36,6 +36,8 @@ class OLAProcessor extends AudioWorkletProcessor {
/** Handles dynamic reallocation of input/output channels buffer
* (channel numbers may vary during lifecycle)
* @param {*} inputs
* @param {*} outputs
* @tags internals
**/
reallocateChannelsIfNeeded(inputs, outputs) {
@@ -92,6 +94,7 @@ class OLAProcessor extends AudioWorkletProcessor {
/**
* Read next web audio block to input buffers
* @param {*} inputs
* @tags internals
**/
readInputs(inputs) {
@@ -114,6 +117,7 @@ class OLAProcessor extends AudioWorkletProcessor {
}
/** Write next web audio block from output buffers
* @param {*} outputs
* @tags internals
**/
writeOutputs(outputs) {
+4 -4
View File
@@ -37,11 +37,11 @@ function humanFileSize(bytes, si) {
* Note: `must` be called with await, otherwise you'll get a pending Promise object.
*
* @name getDuration
* @synonym getDur
* @synonyms getDur
* @tags samples
* @param {string} sampleName
* @param {number} (optional) n
*
* @param {string} s sampleName
* @param {number} [n]
* @returns {Promise<object>}
* @example
* // Set a patterns cycle length to exactly the length of the sample
* samples('github:tidalcycles/dirt-samples')
+6 -6
View File
@@ -41,7 +41,7 @@ export let maxPolyphony = DEFAULT_MAX_POLYPHONY;
*
* @name setMaxPolyphony
* @tags superdough
* @param {number} Max polyphony. Defaults to 128
* @param {number} polyphony Max polyphony. Defaults to 128
* @example
* setMaxPolyphony(4)
* n(irand(24).seg(8)).scale("C#3:minor").room(1).release(4).gain(0.5)
@@ -75,7 +75,7 @@ export function applyGainCurve(val) {
*
* @name setGainCurve
* @tags amplitude, superdough
* @param {Function} function to apply to all gain values
* @param {Function} newGainCurveFunc function to apply to all gain values
* @example
* setGainCurve((x) => x * x) // quadratic gain
* s("bd*4").gain(0.5) // equivalent to 0.25 gain normally
@@ -128,9 +128,8 @@ async function aliasBankPath(path) {
* Register an alias for a bank of sounds.
* Optionally accepts a single argument map of bank aliases.
* Optionally accepts a single argument string of a path to a JSON file containing bank aliases.
* @param {string} bank - The bank to alias
* @param {string} alias - The alias to use for the bank
*
* @param {...any} args either one or two arguments. first argument is bank to alias. Second argument is alias to use for the bank.
* @returns {void}
* @tags samples
*/
export async function aliasBank(...args) {
@@ -676,7 +675,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
chain.connect(initialGain);
// filter
const ftype = getFilterType(value.ftype);
const ftype = getFilterType(fx.ftype ?? value.ftype);
const filt = (params) => createFilter(ac, t, end, params, cps, cycle);
if (fx.cutoff !== undefined) {
@@ -701,6 +700,7 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
};
const lpParams = pickAndRename(fx, lpMap);
lpParams.type = 'lowpass';
lpParams.model = ftype;
const { filter: lpf1, lfo: lfo1 } = filt(lpParams);
fxNodes['lpf'] = [lpf1];
fxNodes['lpf_lfo'] = [lfo1];
+3
View File
@@ -112,6 +112,9 @@ export function getCommonSampleInfo(hapValue, bank) {
/** Selects entries from `source` and renames them via `map`
* @tags internals
* @param {object} source
* @param {*} map
* @returns {*}
*/
export const pickAndRename = (source, map) => {
return Object.fromEntries(Object.entries(map).map(([newKey, oldKey]) => [newKey, source[oldKey]]));
+5
View File
@@ -185,8 +185,13 @@ export function registerWaveTable(key, tables, params) {
/**
* Loads a collection of wavetables to use with `s`
*
* @param {string} url
* @param {*} frameLen
* @param {string} json
* @param {object} options
* @name tables
* @tags wavetable
* @returns {void}
*/
export const tables = async (url, frameLen, json, options = {}) => {
if (json !== undefined) return _processTables(json, url, frameLen);
+2
View File
@@ -647,6 +647,7 @@ class PhaseVocoderProcessor extends OLAProcessor {
}
/** Apply Hann window in-place
* @param {number[]} input
* @tags internals
*/
applyHannWindow(input) {
@@ -695,6 +696,7 @@ class PhaseVocoderProcessor extends OLAProcessor {
}
/** Shift peaks and regions of influence by pitchFactor into new specturm
* @param {number} pitchFactor
* @tags internals
*/
shiftPeaks(pitchFactor) {
-1
View File
@@ -1 +0,0 @@
pattern.wav
-3
View File
@@ -1,3 +0,0 @@
# supradough
platform agnostic synth and sampler intended for live coding. a reimplementation of superdough.
-123
View File
@@ -1,123 +0,0 @@
// this is a poc of how a pattern can be rendered as a wav file using node
// run via: node dough-export.mjs
import fs from 'node:fs';
import WavEncoder from 'wav-encoder';
import { evalScope } from '@strudel/core';
import { miniAllStrings } from '@strudel/mini';
import { Dough } from './dough.mjs';
await evalScope(
import('@strudel/core'),
import('@strudel/mini'),
import('@strudel/tonal'),
// import('@strudel/tonal'),
);
miniAllStrings(); // allows using single quotes for mini notation / skip transpilation
let sampleRate = 48000,
cps = 0.4;
/* await doughsamples('github:eddyflux/crate');
await doughsamples('github:eddyflux/wax'); */
let pat = note('c,eb,g,<bb c4 d4 eb4>')
.s('sine')
.press()
.add(note(24))
.fmi(3)
.fmh(5.01)
.dec(0.4)
.delay('.6:<.12 .22>:.8')
.jux(press)
.rarely(add(note('12')))
.lpf(400)
.lpq(0.2)
.lpd(0.4)
.lpenv(3)
.fmdecay(0.4)
.fmenv(1)
.postgain(0.6)
.stack(s('<pink white>*8').dec(0.07).rarely(ply('2')).delay(0.5).hpf(sine.range(200, 2000).slow(4)).hpq(0.2))
.stack(
s('[- white@3]*2')
.dec(0.4)
.hpf('<2000!3 <4000 8000>>*4')
.hpq(0.6)
.ply('<1 2>*4')
.postgain(0.5)
.delay(0.5)
.jux(rev)
.lpf(5000),
)
.stack(
note('<c2 - [- f1] ->*2')
.s('square')
.lpf(sine.range(100, 300).slow(4))
.lpe(1)
.segment(8)
.lpd(0.3)
.lpq(0.2)
.dec(0.2)
.speed('<1 2>')
.ply('<1 2>')
.postgain(1),
)
.stack(
chord('<Cm Cm7 Cm9 Cm11 Fm Fm7 Fm9 Fm11>')
.voicing()
.s('<sine>')
.clip(1)
.rel(0.4)
.vib('4:.2')
.gain(0.7)
.hpf(1200)
.fm(0.5)
.att(1)
.lpa(0.5)
.lpf(200)
.lpenv(4)
.chorus(0.8),
)
.slow(1 / cps);
let cycles = 30;
let seconds = cycles + 1; // 1s release tail
const haps = pat.queryArc(0, cycles);
const dough = new Dough(sampleRate);
console.log('spawn voices...');
haps.forEach((hap) => {
hap.value._begin = Number(hap.whole.begin);
hap.value._duration = hap.duration /* / cps */;
dough.scheduleSpawn(hap.value);
});
console.log(`render ${seconds}s long buffer, each dot is 1 second:`);
const buffers = [new Float32Array(seconds * sampleRate), new Float32Array(seconds * sampleRate)];
let t = performance.now();
while (dough.t <= buffers[0].length) {
dough.update();
buffers[0][dough.t] = dough.out[0];
buffers[1][dough.t] = dough.out[1];
if (dough.t % sampleRate === 0) {
process.stdout.write('.');
}
}
const took = (performance.now() - t) / 1000;
const load = (took / seconds) * 100;
const speed = (seconds / took).toFixed(2);
console.log('');
console.log(`done!
rendered ${seconds}s in ${took.toFixed(2)}s
speed: ${speed}x
load: ${load.toFixed(2)}%`);
const patternAudio = {
sampleRate,
channelData: buffers,
};
WavEncoder.encode(patternAudio).then((buffer) => {
fs.writeFileSync('pattern.wav', new Float32Array(buffer));
});
-39
View File
@@ -1,39 +0,0 @@
import { Dough } from './dough.mjs';
const clamp = (num, min, max) => Math.min(Math.max(num, min), max);
class DoughProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.dough = new Dough(sampleRate, currentTime);
this.port.onmessage = (event) => {
if (event.data.spawn) {
this.dough.scheduleSpawn(event.data.spawn);
} else if (event.data.sample) {
this.dough.loadSample(event.data.sample, event.data.channels, event.data.sampleRate);
} else if (event.data.samples) {
event.data.samples.forEach(([name, channels, sampleRate]) => {
this.dough.loadSample(name, channels, sampleRate);
});
} else {
console.log('unrecognized event type', event.data);
}
};
}
process(inputs, outputs, params) {
if (this.disconnected) {
return false;
}
const output = outputs[0];
for (let i = 0; i < output[0].length; i++) {
this.dough.update();
for (let c = 0; c < output.length; c++) {
//prevent speaker blowout via clipping if threshold exceeds
output[c][i] = clamp(this.dough.out[c], -1, 1);
}
}
return true; // keep the audio processing going
}
}
registerProcessor('dough-processor', DoughProcessor);
File diff suppressed because it is too large Load Diff
-5
View File
@@ -1,5 +0,0 @@
// import _workletUrl from './dough-worklet.mjs?url'; // only for dev (breaks for production build)
import _workletUrl from './dough-worklet.mjs?audioworklet'; // only for prod (breaks in development?!)
export * from './dough.mjs';
export const workletUrl = _workletUrl;
+1
View File
@@ -3,6 +3,7 @@
"version": "0.2.0",
"private": true,
"description": "Experimental Tidal Code interpreter",
"main": "tidal.mjs",
"module": "tidal.mjs",
"repository": {
"type": "git",
+2 -2
View File
@@ -1,9 +1,9 @@
import './tonal.mjs';
import './voicings.mjs';
import './ireal.mjs';
export * from './tonal.mjs';
export * from './voicings.mjs';
export * from './ireal.mjs';
import './ireal.mjs';
export const packageName = '@strudel/tonal';
+6 -5
View File
@@ -102,8 +102,8 @@ function scaleOffset(scale, offset, note) {
*
* @tags tonal
* @param {string | number} amount Either number of semitones or interval string.
* @returns Pattern
* @memberof Pattern
* @returns {Pattern}
* @memberof Pattern.prototype
* @name transpose
* @synonyms trans
* @example
@@ -160,11 +160,11 @@ export const { transpose, trans } = register(['transpose', 'trans'], function tr
* Transposes notes inside the scale by the number of steps.
* Expected to be called on a Pattern which already has a {@link Pattern#scale}
*
* @memberof Pattern
* @memberof Pattern.prototype
* @name scaleTranspose
* @tags tonal
* @param {offset} offset number of steps inside the scale
* @returns Pattern
* @returns {Pattern}
* @synonyms scaleTrans, strans
* @example
* "-8 [2,4,6]"
@@ -255,7 +255,8 @@ function _getNearestScaleNote(scaleName, note, preferHigher = true) {
* @name scale
* @tags tonal
* @param {string} scale Name of scale
* @returns Pattern
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* n("0 2 4 6 4 2").scale("C:major")
* @example

Some files were not shown because too many files have changed in this diff Show More