Compare commits

..

134 Commits

Author SHA1 Message Date
Tijmen Zwaan 7af792116a Remove deprecated pattern functions 2026-12-05 05:03:25 +01:00
Tijmen Zwaan 978ca86100 Add link to steady to pure comment 2026-12-05 01:29:15 +01:00
Tijmen Zwaan 3c7f6b556d Fix some errors in the top-comments in some of the files 2026-12-05 01:20:03 +01:00
Tijmen Zwaan eaa8cc7849 Move commented-out weave and weaveWith to time-structure 2026-12-05 01:13:23 +01:00
Tijmen Zwaan c9caa3108d Run codeformatter 2026-12-05 01:13:23 +01:00
Tijmen Zwaan 1f225d9560 Rename pattern-misc => misc 2026-12-05 01:13:23 +01:00
Tijmen Zwaan 11f9a1f8ed Rename pattern-atoms => atoms 2026-12-05 01:13:23 +01:00
Tijmen Zwaan 84d2a7d168 Rename pattern-deprecated => deprecated 2026-12-05 00:53:02 +01:00
Tijmen Zwaan 1b01c3290d Rename pattern-stepwise => stepwise 2026-12-05 00:44:41 +01:00
Tijmen Zwaan 63dfa21d49 Rename pattern-structural-temporal => time-structure 2026-12-05 00:44:22 +01:00
Tijmen Zwaan 7268daa84d Rename pattern-combinators => composers 2026-12-05 00:42:04 +01:00
Tijmen Zwaan 7d18a16ee9 Rename pattern-composers => operators 2026-12-05 00:41:06 +01:00
Tijmen Zwaan a3fbdc4676 Rename pattern-numerical => values 2026-12-05 00:40:28 +01:00
Tijmen Zwaan 53d99bc669 Move steady to atoms 2026-12-05 00:28:56 +01:00
Tijmen Zwaan f15bd03787 Move multi prototype assignment to combiners and stepwise 2026-12-05 00:22:57 +01:00
Tijmen Zwaan eed20de27f Move layer, superimpose to structural-temporal 2026-12-05 00:22:31 +01:00
Tijmen Zwaan 5bb415ae68 Move arp, arpWith to structural-temporal 2026-12-05 00:21:47 +01:00
Tijmen Zwaan 1cb8abd2bb Split pattern.mjs into multiple files 2026-12-04 17:18:47 +01:00
Tijmen Zwaan 152b80ce44 Remove outdated snapshots 2026-12-04 17:18:47 +01:00
Felix Roos 24c3ca0489 hotfix: make @strudel/dough private for now (fails on publish) 2026-12-04 17:02:16 +01:00
Felix Roos ef38980b12 Publish
- @strudel/codemirror@1.4.0
 - @strudel/core@1.3.0
 - @strudel/csound@1.4.0
 - @strudel/dough@1.4.0
 - @strudel/draw@1.3.0
 - @strudel/edo@0.2.0
 - @strudel/gamepad@1.3.0
 - @strudel/hydra@1.3.0
 - @strudel/kabelsalat@1.3.0
 - @strudel/midi@1.4.0
 - @strudel/mini@1.3.0
 - @strudel/mondo@1.2.0
 - @strudel/motion@1.3.0
 - @strudel/mqtt@1.3.0
 - @strudel/osc@1.4.0
 - @strudel/pattern@1.3.0
 - @strudel/repl@1.4.0
 - @strudel/sampler@0.3.0
 - @strudel/serial@1.3.0
 - @strudel/soundfonts@1.4.0
 - superdough@1.4.0
 - @strudel/tonal@1.3.0
 - @strudel/transpiler@1.3.0
 - @strudel/web@1.4.0
 - @strudel/webaudio@1.4.0
 - @strudel/websocket@1.1.0
 - @strudel/xen@1.3.0
2026-12-04 16:59:07 +01:00
froos 6274001515 Merge pull request 'fix default handling on eval' (#2234) from fix-set-default into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2234
2026-12-04 16:54:37 +01:00
Felix Roos 3dde9f49e4 fix default handling on eval 2026-12-04 16:25:29 +01:00
froos 5c4064c3ad Merge pull request 'modernize examples' (#2232) from modernize-examples into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2232
2026-12-04 14:47:45 +01:00
Felix Roos fff2610a19 modernize examples 2026-12-04 14:28:32 +01:00
Alex McLean 4613c1d4a8 Merge pull request 'clarify how we make changes live on *.strudel.cc' (#2229) from update-contributing into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2229
2026-12-04 13:13:41 +01:00
froos 8315a8269c Merge pull request 'prompt to update' (#2231) from prompt-to-update into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2231
2026-12-04 11:53:47 +01:00
froos 8248ee411c Merge pull request 'fix: supabase lockmanager error in ff' (#2230) from fix-supabase-error into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2230
2026-12-04 10:48:23 +01:00
Felix Roos 9605a9478a promopt to update 2026-12-04 10:47:53 +01:00
Felix Roos c4cec8dd18 fix: supabase lockmanager error in ff 2026-12-04 10:33:01 +01:00
alex 4033919a8a clarify how we make changes live on *.strudel.cc 2026-12-04 09:32:53 +00:00
froos 217fac5e11 Merge pull request 'Use JsDoc component in Repl' (#2204) from Orasund/strudel:use-jsDoc-component-in-repl into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2204
2026-12-04 09:58:57 +01:00
froos 207c9d5470 Merge branch 'main' into use-jsDoc-component-in-repl 2026-12-04 09:45:53 +01:00
tzwaan 7a1075b746 Merge pull request 'Fix scheduler comments' (#2225) from fix-scheduler-comments into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2225
2026-12-04 03:51:06 +01:00
Tijmen Zwaan 34b7a81c8b Fix scheduler comments 2026-12-04 03:49:40 +01:00
tzwaan b30e3ad88f Merge pull request 'Fix Longnames in Jsdocs and document more functions' (#2220) from Orasund/strudel:fix-longnames-in-jsdoc into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2220
2026-12-04 03:47:59 +01:00
Orasund 70b44f6694 add tests for pick 2026-12-04 02:24:02 +01:00
Orasund fdc5db6b9b Merge branch 'main' into fix-longnames-in-jsdoc 2026-12-04 02:00:23 +01:00
Orasund b49981aea6 apply suggestions 2026-12-04 01:59:26 +01:00
tzwaan 0c38bfaf99 Merge pull request 'Propagate exceptions in test and fix some bugs' (#2224) from propagate-exceptions-in-tests into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2224
2026-12-04 00:26:00 +01:00
Tijmen Zwaan d6ce044ccb rename controls.testRun to controls.propagateExceptions 2026-12-03 23:38:51 +01:00
Tijmen Zwaan 255314f7fa Fix Hap filterHaps example 2026-12-03 23:30:53 +01:00
Tijmen Zwaan acf4628a16 Fix getCurrentKeyboardState if window is not defined (e.g. in tests) 2026-12-03 23:23:54 +01:00
Tijmen Zwaan 2a35745f73 Allow exceptions to propagate in testRuns 2026-12-03 23:23:20 +01:00
tzwaan 787f44bb38 Merge pull request 'Add secondsPer signal' (#2221) from seconds-per into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2221
2026-12-03 21:05:06 +01:00
Orasund db62b8b6aa fix regex for short name of links 2026-12-03 20:56:21 +01:00
Orasund dc1fe808c0 fix pages 2026-12-03 18:40:11 +01:00
Orasund a61418c54c apply suggestions 2026-12-03 17:58:49 +01:00
alex 2feba92516 merge 2026-12-03 16:45:32 +00:00
Orasund 2b001170de Merge branch 'main' into fix-longnames-in-jsdoc 2026-12-03 17:42:57 +01:00
Alex McLean fe06a1e59e Merge pull request 'Fix fm synth' (#2070) from wrightwriter/strudel:fm-fix into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2070
2026-12-03 17:39:19 +01:00
Alex McLean a4b83a364b Merge branch 'main' into fm-fix 2026-12-03 17:33:42 +01:00
Alex McLean 1d8d0dae8c Merge pull request 'goabd synth (goa trance kick)' (#2084) from pulu/strudel:goabd into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2084
2026-12-03 17:21:57 +01:00
Alex McLean d3a6cef369 Merge pull request 'Update undocumented.mjs script' (#2172) from aschultz/strudel-dev:users/aschultz/docs into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2172
2026-12-03 17:03:09 +01:00
Alex McLean d0de54a880 Merge branch 'main' into users/aschultz/docs 2026-12-03 17:02:10 +01:00
Alex McLean d1a4c3c60e Merge branch 'main' into goabd 2026-12-03 16:59:32 +01:00
miranda 118de38551 implement goabd synth 2026-12-03 17:52:24 +02:00
Alex McLean 8bde1314c5 Merge pull request 'cleanup: Remove unrelated npmjs mondo dependency' (#1925) from robojumper/strudel:cleanup/unneeded-mondo-dependency into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/1925
2026-12-03 15:38:22 +01:00
Alex McLean f13dbe00e1 Merge branch 'main' into cleanup/unneeded-mondo-dependency 2026-12-03 15:34:26 +01:00
Alex McLean 68598a674b Merge pull request 'Doc fixes from #1270 by @matthewkaney' (#2223) from pr-1270-doc into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2223
2026-12-03 12:39:21 +01:00
alex db2835c5cb delint 2026-12-03 11:36:33 +00:00
alex f92d6a0a03 doc fixes from #1270 by @matthewkaney 2026-12-03 11:33:30 +00:00
Alex McLean 31730842a7 Merge pull request 'Update AGENTS.md - discourage LLMs from accessing codeberg.org' (#2222) from yaxu-patch-2 into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2222
2026-12-03 10:57:10 +01:00
yaxu 9e92aba3de Update AGENTS.md 2026-12-03 10:56:29 +01:00
Alex McLean 789376d151 Merge pull request 'Add Api Documentation for Hap' (#2218) from Orasund/strudel:document-hap into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2218
2026-12-03 08:13:05 +01:00
Alex McLean 0fc0996d5c Merge branch 'main' into document-hap 2026-12-03 08:09:28 +01:00
Orasund e000020a9f add snapshot for example 2026-12-03 05:45:43 +01:00
Orasund 926cd6b772 fix up typos 2026-12-03 05:40:33 +01:00
Orasund b1b026b56c add snapshot for new test of beat 2026-12-03 05:16:43 +01:00
Orasund 49926243f6 codeformat 2026-12-03 05:10:52 +01:00
Orasund b298ac7b53 fix regression test for beat 2026-12-03 05:10:16 +01:00
Tijmen Zwaan cd7c88e768 Add secondsPer signal 2026-12-03 05:03:17 +01:00
Orasund 4694c59d74 add __beat back in 2026-12-02 21:30:39 +01:00
Orasund 9e00181020 fix tests 2026-12-02 21:27:07 +01:00
Orasund ad98f1050d enable jsdoc/require-description again 2026-12-02 20:59:14 +01:00
Orasund e1e156296a formatting 2026-12-02 20:30:32 +01:00
Orasund 4db94e163c document beat 2026-12-02 20:30:04 +01:00
Orasund 438eb553bd add beat 2026-12-02 19:28:32 +01:00
Orasund 379c075d56 Merge branch 'main' into fix-longnames-in-jsdoc 2026-12-02 06:28:21 +01:00
Alex McLean a261d47b4e Merge pull request 'trigger warm builds manually, add hot.strudel.cc to take over automatic build from main' (#2219) from hot-main into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2219
2026-12-01 17:34:55 +01:00
alex 8b1d68e494 trigger warm builds manually, add hot.strudel.cc to take over automatic build from main 2026-12-01 16:32:26 +00:00
Orasund 6e550f5a6c Add some more definitions 2026-12-01 16:06:05 +01:00
Orasund 2271593c06 add State to the list of known types 2026-12-01 13:13:36 +01:00
Orasund 7dd9cacc37 codeformat 2026-12-01 13:06:30 +01:00
Orasund 446f8468c4 document missing fields 2026-12-01 13:04:21 +01:00
Orasund 28a6c304cd Link to Haps in references 2026-12-01 12:52:47 +01:00
Orasund 2668f4be2c formating 2026-12-01 10:44:51 +01:00
Orasund 4ddd09cf64 readded dropped replacement setting target blank for links in repo 2026-12-01 10:44:10 +01:00
Orasund 96f8c545ae Add @global annotations 2026-12-01 10:31:29 +01:00
tzwaan 1686ff877c Merge pull request 'Add automated cps support to wav export' (#2105) from tzwaan/wav-export-cps-support into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2105
2026-12-01 00:21:03 +01:00
Tijmen Zwaan 83b1c89d25 Move export checkpoint utils and tests to webaudio package 2026-12-01 00:17:49 +01:00
Tijmen Zwaan 1743f65e61 Add automated cps support to wav export 2026-11-30 23:33:50 +01:00
tzwaan bb4b8bb27e Merge pull request 'Add smooth function' (#2199) from tzwaan/smooth into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2199
2026-11-30 23:32:58 +01:00
Tijmen Zwaan bdac0eccbd Add note support to smooth 2026-11-30 23:29:50 +01:00
Tijmen Zwaan 6333fa1ddf Smooth lastHap query does not need a margin 2026-11-30 23:29:50 +01:00
Tijmen Zwaan 41e6084823 Add smooth function 2026-11-30 23:29:50 +01:00
tzwaan fe9a75c9b6 Merge pull request 'Fix notes being dropped by swingBy' (#2205) from swingby-fix into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2205
2026-11-30 23:29:14 +01:00
Tijmen Zwaan cd7c1dbd97 Fix notes being dropped by swingBy 2026-11-30 23:26:51 +01:00
tzwaan 25b9fd991a Merge pull request 'Add stack cut, similar to cut' (#2189) from tzwaan/stack-cut into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2189
2026-11-30 23:25:35 +01:00
Tijmen Zwaan 375b25afd7 Add stack cut, similar to cut 2026-11-30 23:22:18 +01:00
Orasund d3d311e105 Add documentation for Hap 2026-11-30 22:39:10 +01:00
yaxu afc7f1aab1 hotfix: Fix hot 2026-11-30 20:25:43 +01:00
Orasund 4b3c6f90a5 Merge branch 'main' into use-jsDoc-component-in-repl 2026-11-30 18:44:16 +01:00
froos 5e82110522 Merge pull request 'kabelsalat adapter via new superdough effect registry' (#2161) from kabelsalat-adapter into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2161
2026-11-30 18:30:05 +01:00
froos 4616b374f3 Merge pull request 'move pattern core to @strudel/pattern' (#2209) from pattern-package-for-real into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2209
2026-11-30 18:16:59 +01:00
Orasund 08e9e3893e document more functions 2026-11-29 22:56:22 +01:00
Alex McLean 98b71bcb4d Merge pull request 'replace markdown link with html' (#2211) from paulrudy/strudel:main into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2211
2026-11-27 23:24:41 +01:00
Alex McLean cf7dae5d7f Merge branch 'main' into main 2026-11-27 23:24:14 +01:00
Alex McLean b3d9eab3b6 Merge pull request 'remove log' (#2212) from remove-log into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2212
2026-11-27 11:54:41 +01:00
paulrudy c799a686c0 replace markdown link with html 2026-11-26 23:02:18 -08:00
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
Orasund 9e5e172931 fix more longnames 2026-11-26 17:45:15 +01:00
Orasund 1f5b8d6bcc Fix JsDoc Longnames 2026-11-26 11:56:58 +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
Orasund 11e64428dd Merge branch 'main' into use-jsDoc-component-in-repl 2026-11-25 19:35:20 +01:00
Orasund 551e8aed5e Use JsDoc component in Repl 2026-11-25 15:19:04 +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
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
aschultz 5f88fab5d0 Formatting 2026-11-04 16:58:18 -08:00
aschultz 207fa00eac Update undocumented script to use latest ECMA version, generate Posix paths for the keys even on Windows, and skip processing .json files. 2026-11-04 16:53:45 -08:00
Felix Roos 3c32b3b0aa Merge remote-tracking branch 'origin/main' into kabelsalat-adapter 2026-10-15 16:12:39 +02:00
Felix Roos c492e21e1d move kabelsalat to separate package + add registerChainEffect in
superdough to load it
2026-10-12 18:11:00 +02:00
wright 88b7d14487 Fix fm synth 2026-06-16 22:40:19 +03:00
wright 3ac25f7960 Add ctrl-shift-z as shortcut for redo 2026-06-15 20:15:59 +03:00
robojumper 8b3ae4c514 Remove unrelated npmjs mondo dependency 2026-01-17 16:19:21 +01:00
135 changed files with 8038 additions and 5784 deletions
+41
View File
@@ -0,0 +1,41 @@
name: Build and Deploy labeled serve-hot PRs
on:
pull_request_target:
types: [labeled]
# Allow one concurrent deployment
concurrency:
group: "warm-pages"
cancel-in-progress: false
jobs:
build:
if: ${{ github.event.label.name == 'serve-hot' }}
runs-on: docker
container: node:22-bookworm
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
allow-unsafe-pr-checkout: true
- uses: pnpm/action-setup@v4
- name: Install Dependencies
run: pnpm install
- name: Build
run: pnpm build
- name: Deploy
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
run: |
eval $(ssh-agent -s)
echo "$SSH_PRIVATE_KEY" | ssh-add -
apt update && apt install -y rsync
mkdir -p ~/.ssh
ssh-keyscan matrix.toplap.org > ~/.ssh/known_hosts
rsync -atv --delete --delete-after --progress \
./website/dist/ \
strudel@matrix.toplap.org:/home/strudel/deploy/pr-${{ github.event.pull_request.number }}.hot.strudel.cc
+11 -15
View File
@@ -1,23 +1,23 @@
name: Build and Deploy hot PRs
name: Build and Deploy to hot.strudel.cc on merge
on:
pull_request_target:
types: [labeled]
push:
branches:
- main
# Allow one concurrent deployment
concurrency:
group: "warm-pages"
cancel-in-progress: false
group: "pages"
cancel-in-progress: true
jobs:
build:
if: ${{ github.event.label.name == 'serve-hot' }}
runs-on: docker
container: node:22-bookworm
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha }}
- uses: pnpm/action-setup@v4
- name: Install Dependencies
@@ -27,14 +27,10 @@ jobs:
run: pnpm build
- name: Deploy
env:
SSH_PRIVATE_KEY: ${{ secrets.SSH_PRIVATE_KEY }}
run: |
eval $(ssh-agent -s)
echo "$SSH_PRIVATE_KEY" | ssh-add -
apt update && apt install -y rsync
mkdir -p ~/.ssh
ssh-keyscan matrix.toplap.org > ~/.ssh/known_hosts
rsync -atv --delete --delete-after --progress \
./website/dist/ \
strudel@matrix.toplap.org:/home/strudel/deploy/pr-${{ github.event.pull_request.number }}.hot.strudel.cc
mkdir ~/.ssh
ssh-keyscan matrix.toplap.org > ~/.ssh/known_hosts
rsync -atv --delete --delete-after --progress ./website/dist/ strudel@matrix.toplap.org:/home/strudel/deploy/hot.strudel.cc
@@ -1,9 +1,6 @@
name: Build and Deploy to warm (strudel.cc)
on:
push:
branches:
- main
on: [workflow_dispatch]
# Allow one concurrent deployment
concurrency:
+5
View File
@@ -18,6 +18,11 @@ 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.
Strudel's git repo is hosted by codeberg, which attempts to block bots
including LLMs from accessing it, to avoid being overloaded. Agents
should not try to circumvent this, instead encouraging developers
to engage with the strudel community directly.
Projects using strudel must not use "strudel" in their name, unless
they are 'official' projects, or have the blessing of the strudel
community.
+9
View File
@@ -136,6 +136,15 @@ There are also eslint extensions / plugins for most editors.
When opening a PR, the CI runner will (once approved by a human) check the code style and eslint, as well as run all tests. You can run the same check with `pnpm check`.
## Publishing a change live on *.strudel.cc
There are a few steps to a contribution to strudel making it to https://strudel.cc/
1. If a maintainer adds a 'serve-hot' label to a pull request on codeberg, it is built and exposed as http://pr-1000.hot.strudel.cc (where 1000 is the pr number). This allows changes to be tried out live, without building locally. However, because it's plain http, some webaudio things etc won't work. A maintainer with server access can assign a certificate for https via a manual process if needed.
2. When a pull request is merged into the main branch by a maintainer, it is automatically built and served under https://hot.strudel.cc/
3. Then a maintainer can trigger an action on codeberg to rebuild https://strudel.cc/ (also known as https://warm.strudel.cc/) from the main branch. This [currently makes strudel refresh for all users](https://codeberg.org/uzu/strudel/pulls/2130), and is intended to happen around once a week, early in the week (when fewer people will be performing with it!), or more often for urgent fixes.
4. There is also https://cold.strudel.cc/, which is intended to reflect the last package release to npm.
## Package Workflow
The project is split into multiple [packages](https://codeberg.org/uzu/strudel/src/branch/main/packages) with independent versioning.
+4 -4
View File
@@ -1,22 +1,22 @@
import { queryCode, testCycles } from '../test/runtime.mjs';
import * as tunes from '../website/src/repl/tunes.mjs';
import { describe, bench } from 'vitest';
import { calculateSteps } from '../packages/core/index.mjs';
import { setCalculateSteps } from '../packages/core/index.mjs';
const tuneKeys = Object.keys(tunes);
describe('renders tunes', () => {
tuneKeys.forEach((key) => {
describe(key, () => {
calculateSteps(true);
setCalculateSteps(true);
bench(`+steps`, async () => {
await queryCode(tunes[key], testCycles[key] || 1);
});
calculateSteps(false);
setCalculateSteps(false);
bench(`-steps`, async () => {
await queryCode(tunes[key], testCycles[key] || 1);
});
calculateSteps(true);
setCalculateSteps(true);
});
});
});
+15 -3
View File
@@ -95,11 +95,12 @@ export default [
},
},
jsdoc({
files: ['packages/**/*.{js,mjs}'],
config: 'flat/recommended-error',
rules: {
'jsdoc/no-undefined-types': [
'error',
{ definedTypes: ['Pattern', 'Pattern.prototype', 'Hap', 'KabelsalatExpression'] },
{ definedTypes: ['Pattern', 'Pattern.prototype', 'Hap', 'KabelsalatExpression', 'TimeSpan', 'State'] },
],
'jsdoc/check-tag-names': ['error', { definedTags: ['tags', 'synonyms', 'noAutocomplete', 'superdirtOnly'] }],
'jsdoc/no-restricted-syntax': [
@@ -111,13 +112,18 @@ export default [
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.",
message: "Use '@memberof <Name>.prototype' instead.",
},
{
context: 'FunctionDeclaration',
comment: 'JsdocBlock:not(:has(JsdocTag[tag=/^(global|memberof)$/]))',
message: 'JSDoc block should be explicitly labeled as @global or @memberof.',
},
],
},
],
'jsdoc/require-description': 'error',
'jsdoc/no-defaults': 0, //removes defaults with not alternative
'jsdoc/no-defaults': 0, //removes defaults with no alternative
'jsdoc/require-jsdoc': 0,
'jsdoc/tag-lines': 0,
'jsdoc/require-returns-description': 0,
@@ -129,4 +135,10 @@ export default [
'jsdoc/reject-function-type': 0,
},
}),
jsdoc({
files: ['packages/core/**/*.{js,mjs}', 'packages/pattern/**/*.{js,mjs}'],
rules: {
'jsdoc/require-jsdoc': ['warn', { publicOnly: {}, enableFixer: false }],
},
}),
];
+17 -9
View File
@@ -1,16 +1,19 @@
import { readFile } from 'node:fs/promises';
import { dirname, resolve } from 'path';
import { dirname, resolve, win32, posix } from 'path';
import { fileURLToPath } from 'url';
import { parse } from 'acorn';
import dependencyTree from 'dependency-tree';
import { platform } from 'node:process';
const __dirname = dirname(fileURLToPath(import.meta.url));
const packageRoot = resolve(__dirname, '..');
function getExports(code) {
// parse it with acorn
let ast;
try {
ast = parse(code, {
ecmaVersion: 11,
ecmaVersion: 'latest',
sourceType: 'module',
});
} catch (err) {
@@ -64,21 +67,26 @@ async function getUndocumented(path, docs) {
}
}
function getPackageRelativePosixPath(path) {
path = path.replace(packageRoot, '');
if (platform === 'win32') {
path = path.replaceAll(win32.sep, posix.sep);
}
return path;
}
// read doc.json file
const { docs } = JSON.parse(await readFile(resolve(__dirname, '..', 'doc.json'), 'utf8'));
const excludedFileTypes = /\.json$/;
const paths = dependencyTree.toList({
filename: 'index.mjs',
// filename: 'packages/core/index.mjs',
directory: resolve(__dirname),
filter: (path) => !path.includes('node_modules'),
directory: packageRoot,
filter: (path) => !path.includes('node_modules') && !excludedFileTypes.test(path),
});
// const paths = ['../packages/core/pattern.mjs', '../packages/core/hap.mjs'].map((rel) => resolve(__dirname, rel));
const undocumented = Object.fromEntries(
await Promise.all(
paths.map(async (path) => [path.replace(resolve(__dirname, '..'), ''), await getUndocumented(path, docs)]),
),
await Promise.all(paths.map(async (path) => [getPackageRelativePosixPath(path), await getUndocumented(path, docs)])),
);
console.log(JSON.stringify(undocumented, null, 2));
+1 -1
View File
@@ -80,4 +80,4 @@
"engines": {
"node": ">=18.0.0"
}
}
}
+10 -4
View File
@@ -1,5 +1,5 @@
import { closeBrackets } from '@codemirror/autocomplete';
import { indentWithTab } from '@codemirror/commands';
import { indentWithTab, toggleLineComment, redo } from '@codemirror/commands';
import { javascript, javascriptLanguage } from '@codemirror/lang-javascript';
import { bracketMatching, defaultHighlightStyle, syntaxHighlighting } from '@codemirror/language';
import { Compartment, EditorState, Prec } from '@codemirror/state';
@@ -19,7 +19,7 @@ import { isAutoCompletionEnabled } from './autocomplete.mjs';
import { basicSetup } from './basicSetup.mjs';
import { flash, isFlashEnabled } from './flash.mjs';
import { highlightMiniLocations, isPatternHighlightingEnabled, updateMiniLocations } from './highlight.mjs';
import { keybindings } from './keybindings.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';
@@ -101,6 +101,7 @@ 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([
{
@@ -111,6 +112,10 @@ export function initEditor({ initialCode = '', onChange, onEvaluate, onStop, roo
key: 'Alt-Enter',
run: () => onEvaluate?.(),
},
{
key: 'Ctrl-Shift-z',
run: redo,
},
{
key: 'Ctrl-.',
run: () => onStop?.(),
@@ -201,10 +206,10 @@ export class StrudelMirror {
cleanupDraw(true, id);
}
},
beforeEval: async () => {
beforeEval: async (bag) => {
cleanupDraw(true, id);
await this.prebaked;
await replOptions?.beforeEval?.();
await replOptions?.beforeEval?.(bag);
},
afterEval: (options) => {
// remember for when highlighting is toggled on
@@ -399,6 +404,7 @@ function s4() {
* Overrides the css of highlighted events. Make sure to use single quotes!
* @name markcss
* @tags visualization
* @memberof Pattern.prototype
* @example
* note("c a f e")
* .markcss('text-decoration:underline')
+18 -4
View File
@@ -1,12 +1,15 @@
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 } from '@replit/codemirror-vim';
import { vim, Vim } from '@replit/codemirror-vim';
// import { vim } from './vim_test.mjs';
import { vscodeKeymap } from '@replit/codemirror-vscode-keymap';
// 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 {
constructor() {}
@@ -26,7 +29,18 @@ const keymaps = {
vscode: vscodeExtension,
};
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 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/codemirror",
"version": "1.3.0",
"version": "1.4.0",
"description": "Codemirror Extensions for Strudel",
"main": "index.mjs",
"publishConfig": {
File diff suppressed because it is too large Load Diff
+1 -1
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({
+1 -1
View File
@@ -4,7 +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 = {};
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);
};
-35
View File
@@ -1,35 +0,0 @@
export const logKey = 'strudel.log';
let debounce = 1000,
lastMessage,
lastTime;
export function errorLogger(e, origin = 'cyclist') {
if (process.env.NODE_ENV === 'development') {
console.error(e);
}
logger(`[${origin}] error: ${e.message}`);
}
export function logger(message, type, data = {}) {
let t = performance.now();
if (lastMessage === message && t - lastTime < debounce) {
return;
}
lastMessage = message;
lastTime = t;
console.log(`%c${message}`, 'background-color: black;color:white;border-radius:15px');
if (typeof document !== 'undefined' && typeof CustomEvent !== 'undefined') {
document.dispatchEvent(
new CustomEvent(logKey, {
detail: {
message,
type,
data,
},
}),
);
}
}
logger.key = logKey;
+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
@@ -1,6 +1,6 @@
{
"name": "@strudel/core",
"version": "1.2.6",
"version": "1.3.0",
"description": "Port of Tidal Cycles to JavaScript",
"main": "index.mjs",
"type": "module",
@@ -31,6 +31,7 @@
},
"homepage": "https://strudel.cc",
"dependencies": {
"@strudel/pattern": "workspace:*",
"fraction.js": "^5.2.1"
},
"gitHead": "0e26d4e741500f5bae35b023608f062a794905c2",
File diff suppressed because it is too large Load Diff
+25 -4
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,10 +12,29 @@ 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';
/**
* Creates a new Repl
* @global
* @param {object} options
* @param {*} options.onSchedule
* @param {*} options.defaultOutput
* @param {*} options.onEvalError
* @param {*} options.beforeEval
* @param {*} options.beforeStart
* @param {*} options.afterEval
* @param {*} options.getTime
* @param {*} options.transpiler
* @param {*} options.onToggle
* @param {*} options.editPattern
* @param {*} options.onUpdateState
* @param {*} options.sync = false
* @param {*} options.setInterval
* @param {*} options.clearInterval
* @param {*} options.id
* @param {*} options.mondo = false
* @returns {object}
*/
export function repl({
onSchedule,
defaultOutput,
+45
View File
@@ -12,6 +12,7 @@ let isStarted;
/**
* Get the current cycle time as a number
* @global
* @name getTime
* @tags internals
* @returns {number}
@@ -23,6 +24,12 @@ export function getTime() {
return time();
}
/**
* define how the cycle time should be computed
* @global
* @param {function():number} func
* @tags internals
*/
export function setTime(func) {
time = func;
}
@@ -30,6 +37,7 @@ export function setTime(func) {
let clockTime;
/**
* Get the current clock time in seconds (onSchedule time)
* @global
* @name getClockTime
* @tags internals
* @returns {number}
@@ -41,16 +49,28 @@ export function getClockTime() {
return clockTime();
}
/**
* define how the clock time should be computed
* @global
* @param {function():number} func
*/
export function setClockTime(func) {
clockTime = func;
}
/**
* define how Cycles per seconds are computed
* @global
* @tags internals
* @param {function():number} func
*/
export function setCpsFunc(func) {
cpsFunc = func;
}
/**
* Get the current cycles per second
* @global
* @name getCps
* @tags internals
* @returns {number}
@@ -59,26 +79,51 @@ export function getCps() {
return cpsFunc?.();
}
/**
* Set the currently running pattern
* @param {Pattern} pat
*/
export function setPattern(pat) {
pattern = pat;
}
/**
* Get the currently running pattern
* @returns {Pattern}
*/
export function getPattern() {
return pattern;
}
/**
* Set the function that applies a function for a given time and cps
* @param {function(Pattern,number,number)} func
*/
export function setScheduleFunc(func) {
scheduleFunc = func;
}
/**
* Gets the function that applies a function for a given time and cps
* @returns {function(Pattern,number,number)} taking a Pattern, the current time and cps as inputs
*/
export function getScheduleFunc() {
return scheduleFunc;
}
/**
* start/stop the scheduler
* @param {boolean | undefined} val
*/
export function setIsStarted(val) {
isStarted = !!val;
}
/**
* Has the scheduler started?
In the repl, this returns true only after the full pattern code has successfully executed without errors, including any prebake files, or if the scheduler was already running from a previous pattern update.
* @returns {boolean}
*/
export function getIsStarted() {
return isStarted;
}
+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 },
),
);
});
});
+13
View File
@@ -1,6 +1,19 @@
// will move to https://github.com/felixroos/zyklus
// TODO: started flag
/**
* Creates a Web Audio Clock
* @global
* @param {Function} getTime
* @param {Function} callback
* @param {number} [duration]
* @param {number} [interval]
* @param {number} [overlap]
* @param {Function} [setInterval]
* @param {Function} [clearInterval]
* @param {boolean} round
* @returns {object}
*/
function createClock(
getTime,
callback, // called slightly before each cycle
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/csound",
"version": "1.3.0",
"version": "1.4.0",
"description": "csound bindings for strudel",
"main": "index.mjs",
"type": "module",
+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) => {
+2 -1
View File
@@ -1,6 +1,7 @@
{
"name": "@strudel/dough",
"version": "1.3.2",
"version": "1.4.0",
"private": true,
"description": "dough synth integration for strudel",
"main": "dough.mjs",
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/draw",
"version": "1.2.6",
"version": "1.3.0",
"description": "Helpers for drawing with Strudel",
"main": "index.mjs",
"type": "module",
+1
View File
@@ -308,6 +308,7 @@ Pattern.prototype.punchcard = function (options) {
* @name wordfall
* @tags visualization
* @returns {Pattern}
* @memberof Pattern.prototype
*/
Pattern.prototype.wordfall = function (options) {
return this.punchcard({ vertical: 1, labels: 1, stroke: 0, fillActive: 1, active: 'white', ...options });
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/edo",
"version": "0.1.0",
"version": "0.2.0",
"description": "Equal division of the octave (EDO) scale functions for strudel",
"main": "index.mjs",
"publishConfig": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/gamepad",
"version": "1.2.6",
"version": "1.3.0",
"description": "Gamepad Inputs for strudel",
"main": "index.mjs",
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/hydra",
"version": "1.2.6",
"version": "1.3.0",
"description": "Hydra integration for strudel",
"main": "hydra.mjs",
"type": "module",
+41
View File
@@ -0,0 +1,41 @@
import { registerChainEffect, getFrequencyFromValue, getWorklet, logger, registerWorklet } from 'superdough';
import workletUrl from './worklet.mjs?audioworklet';
let kabel;
async function initKabelsalat() {
const { SalatRepl } = await import('@kabelsalat/web');
logger('[kabelsalat] ready');
kabel = new SalatRepl({ localScope: true });
return kabel;
}
initKabelsalat().catch((err) => {
logger(`kabelsalat init failed: ${err}`);
});
const compileKabel = (code) => {
if (!kabel) {
throw new Error('kabelsalat still loading');
}
const node = kabel.evaluate(code);
return node.compile({ log: false });
};
registerWorklet(workletUrl);
registerChainEffect('workletSrc', ({ audioContext, fx, value, chainID, start, gateEnd, releaseEnd }) => {
const workletSrc = fx.workletSrc
.replace(/\bpat\[(\d+)\]/g, (_, i) => fx.workletInputs[i])
.replaceAll('sFreq', getFrequencyFromValue(value))
.replaceAll('sGate', `cc('strudel-gate-${chainID}')`);
const { src, ugens, registers } = compileKabel(workletSrc);
const workletNode = getWorklet(audioContext, 'generic-processor', {}, { outputChannelCount: [2] });
workletNode.port.postMessage({
src,
schema: { ugens, registers },
start,
gateEnd,
end: releaseEnd,
});
return workletNode;
});
+43
View File
@@ -0,0 +1,43 @@
{
"name": "@strudel/kabelsalat",
"version": "1.3.0",
"description": "kabelsalat integration for superdough",
"main": "kabelsalat.mjs",
"type": "module",
"publishConfig": {
"main": "dist/kabelsalat.mjs"
},
"scripts": {
"build": "vite build",
"prepublishOnly": "npm run build"
},
"repository": {
"type": "git",
"url": "git+https://codeberg.org/uzu/strudel.git"
},
"keywords": [
"titdalcycles",
"strudel",
"pattern",
"livecoding",
"algorave"
],
"author": "Felix Roos <flix91@gmail.com>",
"license": "AGPL-3.0-or-later",
"bugs": {
"url": "https://codeberg.org/uzu/strudel/issues"
},
"homepage": "https://codeberg.org/uzu/strudel#readme",
"dependencies": {
"@kabelsalat/lib": "^0.4.1",
"@kabelsalat/web": "^0.4.1",
"superdough": "workspace:*"
},
"devDependencies": {
"vite": "^6.0.11",
"vite-plugin-bundle-audioworklet": "workspace:*"
},
"engines": {
"node": ">=18.0.0"
}
}
+20
View File
@@ -0,0 +1,20 @@
import { defineConfig } from 'vite';
import { resolve } from 'path';
import bundleAudioWorkletPlugin from 'vite-plugin-bundle-audioworklet';
import { dependencies } from './package.json';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [bundleAudioWorkletPlugin()],
build: {
lib: {
entry: resolve(__dirname, 'kabelsalat.mjs'),
formats: ['es'],
fileName: (ext) => ({ es: 'kabelsalat.mjs' })[ext],
},
rollupOptions: {
external: [...Object.keys(dependencies)],
},
target: 'esnext',
},
});
+83
View File
@@ -0,0 +1,83 @@
import * as ugens from '@kabelsalat/lib/src/ugens.js';
const blockSize = 128;
const UGENS = new Map(Object.entries(ugens));
class GenericProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.playPos = 0;
const channels = 16;
this.outputs = new Array(channels).fill(0);
this.sources = new Array(channels).fill(0);
this.gateEnded = false;
this.started = false;
this.port.onmessage = (event) => {
let {
src,
schema: { ugens, registers },
start,
gateEnd,
end,
} = event.data;
this.start = start;
this.gateEnd = gateEnd;
this.end = end;
this.registers = new Array(registers).fill(0);
this.src = `o.fill(0); // reset outputs\n${src}`;
this.nodes = [];
for (let i = 0; i < ugens.length; i++) {
const ugen = ugens[i];
const nodeClass = UGENS.get(ugen.type);
const node = new nodeClass(i, ugen, sampleRate);
if (node.type === 'cc' && ugen.inputs?.[0]?.includes('strudel-gate')) {
node.setValue(1);
this.gateNode = node;
}
this.nodes[i] = node;
}
this.genSample = new Function(
'time',
'nodes',
'input',
'r', // registers
'o', // outputs
's', // sources
this.src,
);
};
}
process(inputs, outputs) {
const input = inputs[0]?.[0];
if (currentTime >= this.end) {
return false;
} else if (this.genSample === undefined || currentTime < this.start) {
// pending
return true;
}
this.started = true;
if (!this.gateEnded && currentTime > this.gateEnd) {
this.gateNode?.setValue(0);
this.gateEnded = true;
}
const output = outputs[0];
const outL = output[0];
const outR = output[1];
for (let n = 0; n < blockSize; n++) {
this.genSample(this.playPos, this.nodes, input ? input[n] : 0, this.registers, this.outputs, this.sources);
const left = this.outputs[0];
const right = this.outputs[1];
// Spread to stereo if possible; else mixdown to mono
if (outR) {
outL[n] = left;
outR[n] = right;
} else {
outL[n] = 0.5 * (left + right);
}
this.playPos += 1 / sampleRate;
}
return true;
}
}
registerProcessor('generic-processor', GenericProcessor);
+6 -2
View File
@@ -113,6 +113,7 @@ function githubPath(base, subpath = '') {
/**
* configures the default midimap, which is used when no "midimap" port is set
* @global
* @param {*} mapping
* @tags external_io, midi
* @example
@@ -128,6 +129,7 @@ let loadCache = {};
/**
* Adds midimaps to the registry. Inside each midimap, control names (e.g. lpf) are mapped to cc numbers.
* @global
* @param {string | object} map
* @tags external_io, midi
* @example
@@ -484,6 +486,7 @@ Pattern.prototype.midi = function (midiport, options = {}) {
/**
* Initialize a midi input device
* @global
* @param {string} input
* @returns {MidiInput}
*/
@@ -526,9 +529,10 @@ const midiInputs = {};
* The output is a function that accepts a midi cc value to query as well as (optionally) a midi channel
*
* @name midin
* @global
* @tags external_io, midi
* @param {string | number} input MIDI device name or index defaulting to 0
* @returns {function(number, number=): Pattern} A function from (cc, channel?) to a pattern.
* @returns {Promise<function(number, number=): Pattern>} A function from (cc, channel?) to a pattern.
* When queried, the pattern will produces the most recently received midi value (normalized to 0 to 1)
* that came through that cc number (and channel, if provided)
* @example
@@ -558,7 +562,7 @@ export async function midin(input) {
* @name midikeys
* @tags external_io, midi
* @param {string | number} input MIDI device name or index defaulting to 0
* @returns {function((number | Pattern)=): Pattern} A function that produces a pattern.
* @returns {Promise<function((number | Pattern)=): Pattern>} A function that produces a pattern.
* When queried, the pattern will produces the most recently played midi notes and velocities,
* lasting for the specified duration
* @example
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/midi",
"version": "1.3.0",
"version": "1.4.0",
"description": "Midi API for strudel",
"main": "index.mjs",
"type": "module",
+2
View File
@@ -8,6 +8,7 @@ import { Input, Output } from 'webmidi';
/**
* Get a string listing device names for error messages.
* @global
* @param {Input[] | Output[]} devices
* @returns {string}
*/
@@ -18,6 +19,7 @@ export function getMidiDeviceNamesString(devices) {
/**
* Look up a device by index or name. Otherwise return a default device, or fail if none are connected.
*
* @global
* @param {string | number} indexOrName
* @param {Input[] | Output[]} devices
* @returns {Input | Output | undefined}
+4 -4
View File
@@ -1,10 +1,10 @@
import { describe, bench } from 'vitest';
import { calculateSteps } from '../../core/index.mjs';
import { setCalculateSteps } from '@strudel/pattern';
import { mini } from '../index.mjs';
describe('mini', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -13,7 +13,7 @@ describe('mini', () => {
{ time: 1000 },
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -21,5 +21,5 @@ describe('mini', () => {
},
{ time: 1000 },
);
calculateSteps(true);
setCalculateSteps(true);
});
+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;
+2 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/mini",
"version": "1.2.6",
"version": "1.3.0",
"description": "Mini notation for strudel",
"main": "index.mjs",
"type": "module",
@@ -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', () => {
+1 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/mondo",
"version": "1.1.6",
"version": "1.2.0",
"description": "mondo notation for strudel",
"main": "mondough.mjs",
"type": "module",
@@ -37,7 +37,6 @@
"mondolang": "workspace:*"
},
"devDependencies": {
"mondo": "*",
"vite": "^6.0.11",
"vitest": "^3.0.4"
},
+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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {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
* @returns {Pattern}
* @type {Pattern}
* @synonyms absOriG, absOriY, absoluteOrientationY
* @tags external_io
* @example
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/motion",
"version": "1.2.6",
"version": "1.3.0",
"description": "DeviceMotion API for strudel",
"main": "index.mjs",
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/mqtt",
"version": "1.2.6",
"version": "1.3.0",
"description": "MQTT API for strudel",
"main": "mqtt.mjs",
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/osc",
"version": "1.3.2",
"version": "1.4.0",
"description": "OSC messaging for strudel",
"main": "osc.mjs",
"bin": "./server.js",
+94
View File
@@ -0,0 +1,94 @@
/*
atoms.mjs - The most basic pattern construction functions
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/atoms.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 Hap from './hap.mjs';
import Fraction from './fraction.mjs';
import { Pattern, isPattern } from './pattern.mjs';
/**
* Does absolutely nothing, but with a given metrical 'steps'
* @name gap
* @tags generators
* @param {number} steps
* @returns {Pattern}
* @example
* gap(3) // "~@3"
*/
export const gap = (steps) => new Pattern(() => [], steps);
/**
* Does absolutely nothing..
* @name silence
* @tags generators
* @example
* silence // "~"
*/
export const silence = gap(1);
/**
* Like silence, but with a 'steps' (relative duration) of 0
* @name nothing
* @tags generators
* @example
* nothing
*/
export const nothing = gap(0);
/**
* A discrete value that repeats once per cycle.
* See also {@link steady}
*
* @global
* @param {number} value
* @tags generators
* @returns {Pattern}
* @example
* pure('e4') // "e4"
* @noAutocomplete
*/
export function pure(value) {
function query(state) {
return state.span.spanCycles.map((subspan) => new Hap(Fraction(subspan.begin).wholeCycle(), subspan, value));
}
const result = new Pattern(query, 1);
result.__pure = value;
return result;
}
/**
* A `signal` consisting of a constant value. Similar to {@link pure}, except that function
* creates a pattern with one event per cycle, whereas 'steady' patterns don't have
* a discrete structure.
*
* @param {*} value The constant value of the resulting pattern
* @returns {Pattern}
*/
export function steady(value) {
return new Pattern((state) => [new Hap(undefined, state.span, value)]);
}
let stringParser;
// parser is expected to turn a string into a pattern
// if set, the reify function will parse all strings with it
// intended to use with mini to automatically interpret all strings as mini notation
export const setStringParser = (parser) => (stringParser = parser);
/**
* Turns something into a pattern via pure(), unless it's already a pattern. If a string parser is set via {@link setStringParser}, that is used to reify strings.
* @param {*} thing
* @returns {Pattern}
*/
export function reify(thing) {
// Turns something into a pattern, unless it's already a pattern
if (isPattern(thing)) {
return thing;
}
if (stringParser && typeof thing === 'string') {
return stringParser(thing);
}
return pure(thing);
}
@@ -1,11 +1,11 @@
import { describe, bench } from 'vitest';
import { calculateSteps, sequence, stack } from '../index.mjs';
import { setCalculateSteps, sequence, stack } from '../index.mjs';
const pat64 = sequence(...Array(64).keys());
describe('steps', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -14,7 +14,7 @@ describe('steps', () => {
{ time: 1000 },
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -25,7 +25,7 @@ describe('steps', () => {
});
describe('stack', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -34,7 +34,7 @@ describe('stack', () => {
{ time: 1000 },
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -43,4 +43,4 @@ describe('stack', () => {
{ time: 1000 },
);
});
calculateSteps(true);
setCalculateSteps(true);
@@ -1,13 +1,13 @@
import { describe, bench } from 'vitest';
import { calculateSteps, rand, useRNG } from '../index.mjs';
import { setCalculateSteps, rand, useRNG } from '../index.mjs';
const testingResolution = 128;
const _generateRandomPattern = () => rand.iter(testingResolution).fast(testingResolution).firstCycle();
describe('old random', () => {
calculateSteps(true);
setCalculateSteps(true);
bench(
'+tactus',
() => {
@@ -22,7 +22,7 @@ describe('old random', () => {
},
);
calculateSteps(false);
setCalculateSteps(false);
bench(
'-tactus',
() => {
@@ -39,11 +39,11 @@ describe('old random', () => {
});
describe('random', () => {
calculateSteps(true);
setCalculateSteps(true);
bench('+tactus', _generateRandomPattern, { time: 1000 });
calculateSteps(false);
setCalculateSteps(false);
bench('-tactus', _generateRandomPattern, { time: 1000 });
});
calculateSteps(true);
setCalculateSteps(true);
+248
View File
@@ -0,0 +1,248 @@
/*
composers.mjs - Top-level functions that combine multiple patterns into a single pattern
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/composers.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 Fraction, { lcm } from './fraction.mjs';
import { getCalculateSteps, Pattern } from './pattern.mjs';
import { reify, silence, pure } from './atoms.mjs';
import { _mod, flatten, curry } from './util.mjs';
import { errorLogger } from './logger.mjs';
/**
* The given items are played at the same time at the same length.
*
* @param {...any} pats
* @tags combiners
* @returns {Pattern}
* @name stack
* @memberof Pattern.prototype
* @synonyms polyrhythm, pr
* @example
* stack("g3", "b3", ["e4", "d4"]).note()
* // "g3,b3,[e4 d4]".note()
*
* @example
* // As a chained function:
* s("hh*4").stack(
* note("c4(5,8)")
* )
*/
export function stack(...pats) {
// Array test here is to avoid infinite recursions..
pats = pats.map((pat) => (Array.isArray(pat) ? sequence(...pat) : reify(pat)));
const query = (state) =>
flatten(
pats.map((pat) => {
if (state.controls.propagateExceptions) {
// In tests, we want exceptions to propagate to actually catch problems
// and to see the proper stack trace in the test result.
return pat.query(state);
} else {
try {
// An error occurring in one part of the stack should not break
// playback of the other parts of the stack.
return pat.query(state);
} catch (e) {
errorLogger(e);
return [];
}
}
}),
);
const result = new Pattern(query);
if (getCalculateSteps()) {
result._steps = lcm(...pats.map((pat) => pat._steps));
}
return result;
}
// aliases
export const polyrhythm = stack;
export const pr = stack;
/**
* Takes a list of patterns, and returns a pattern of lists.
* @global
* @param {Pattern[]} pats
* @returns {Pattern}
* @tags temporal
*/
export function sequenceP(pats) {
let result = pure([]);
for (const pat of pats) {
result = result.bind((list) => pat.fmap((v) => list.concat([v])));
}
return result;
}
export function sequence(...pats) {
return fastcat(...pats);
}
/** Like **cat**, but the items are crammed into one cycle.
* @tags combiners
* @synonyms fastcat, sequence
* @example
* seq("e5", "b4", ["d5", "c5"]).note()
* // "e5 b4 [d5 c5]".note()
*
* @example
* // As a chained function:
* s("hh*4").seq(
* note("c4(5,8)")
* )
*/
export function seq(...pats) {
return fastcat(...pats);
}
/**
* Concatenation: combines a list of patterns, switching between them successively, one per cycle.
*
* @param {...any} pats
* @tags combiners
* @returns {Pattern}
* @synonyms cat
* @example
* slowcat("e5", "b4", ["d5", "c5"])
*
*/
export function slowcat(...pats) {
// Array test here is to avoid infinite recursions..
pats = pats.map((pat) => (Array.isArray(pat) ? fastcat(...pat) : reify(pat)));
if (!pats.length) {
return silence;
} else if (pats.length == 1) {
return pats[0];
}
const query = function (state) {
const span = state.span;
const pat_n = _mod(span.begin.sam(), pats.length);
const pat = pats[pat_n];
// A bit of maths to make sure that cycles from constituent patterns aren't skipped.
// For example if three patterns are slowcat-ed, the fourth cycle of the result should
// be the second (rather than fourth) cycle from the first pattern.
const offset = span.begin.floor().sub(span.begin.div(pats.length).floor());
return pat.withHapTime((t) => t.add(offset)).query(state.setSpan(span.withTime((t) => t.sub(offset))));
};
const steps = getCalculateSteps() ? lcm(...pats.map((x) => x._steps)) : undefined;
return new Pattern(query).splitQueries().setSteps(steps);
}
/** Concatenation: combines a list of patterns, switching between them successively, one per cycle. Unlike slowcat, this version will skip cycles.
* @global
* @tags combiners
* @param {...any} pats The items to concatenate
* @returns {Pattern}
*/
export function slowcatPrime(...pats) {
if (!pats.length) {
return silence;
}
pats = pats.map(reify);
const query = function (state) {
const pat_n = _mod(Math.floor(state.span.begin), pats.length);
const pat = pats[pat_n];
return pat.query(state);
};
return new Pattern(query).splitQueries();
}
/** The given items are con**cat**enated, where each one takes one cycle.
*
* @tags combiners
* @param {...any} pats The items to concatenate
* @synonyms slowcat
* @returns {Pattern}
* @example
* cat("e5", "b4", ["d5", "c5"]).note()
* // "<e5 b4 [d5 c5]>".note()
*
* @example
* // As a chained function:
* s("hh*4").cat(
* note("c4(5,8)")
* )
*/
export function cat(...pats) {
return slowcat(...pats);
}
/**
* Similarly to `arrange`, allows you to arrange multiple patterns together over multiple cycles.
* Unlike `arrange`, you specify a start and stop time for each pattern rather than duration, which
* means that patterns can overlap.
* @param {...any} parts
* @tags combiners
* @returns {Pattern}
* @example
* seqPLoop(
* [0, 2, "bd(3,8)"],
* [1, 3, "cp(3,8)"]
* ).sound()
*/
export function seqPLoop(...parts) {
let total = Fraction(0);
const pats = [];
for (let part of parts) {
if (part.length == 2) {
part.unshift(total);
}
total = part[1];
}
return stack(
...parts.map(([start, stop, pat]) =>
pure(reify(pat)).compress(Fraction(start).div(total), Fraction(stop).div(total)),
),
)
.slow(total)
.innerJoin(); // or resetJoin or restartJoin ??
}
export function fastcat(...pats) {
let result = slowcat(...pats);
if (pats.length > 1) {
result = result._fast(pats.length);
result._steps = pats.length;
}
if (pats.length == 1 && pats[0].__steps_source) {
pats._steps = pats[0]._steps;
}
return result;
}
/**
* Turns a list of patterns into a single pattern which outputs list-values
*
* @param {Pattern[]} pats
* @name parray
* @tags combiners
* @returns {Pattern}
*/
export const parray = (pats) => {
const pack = (...xs) => xs;
let acc = pure(curry(pack, null, pats.length));
for (const p of pats) acc = acc.appBoth(reify(p));
return acc;
};
const multiPatternFunctions = {
stack,
sequence,
seq,
cat,
fastcat,
slowcat,
slowcatPrime,
};
for (const [name, func] of Object.entries(multiPatternFunctions)) {
Pattern.prototype[name] = function (...pats) {
return func(this, ...pats);
};
}
@@ -15,10 +15,11 @@ import Fraction, { gcd } from './fraction.mjs';
* - "-" hold previous value
* - "." silence
*
* @tags visualization
* @tags internal, visualization
* @param {Pattern} pat the pattern to use
* @param {number} chars max number of characters (approximately)
* @returns {string}
* @global
* @example
* const line = drawLine("0 [1 2 3]", 10); // |0--123|0--123
* console.log(line);
@@ -10,9 +10,12 @@ https://rohandrape.net/?t=hmt
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 { timeCat, register, silence, stack, pure, _morph } from './pattern.mjs';
import { silence } from './atoms.mjs';
import { register } from './register.mjs';
import { timeCat } from './stepwise.mjs';
import { _morph } from './time-structure.mjs';
import { rotate, flatten, splitAt, zipWith } from './util.mjs';
import Fraction, { lcm } from './fraction.mjs';
import Fraction from './fraction.mjs';
const left = function (n, x) {
const [ons, offs] = n;
@@ -6,22 +6,40 @@ This program is free software: you can redistribute it and/or modify it under th
import Fraction from './fraction.mjs';
import { stringifyValues } from './util.mjs';
/**
* @tags internal
* @class Event class, representing a discrete or samples event (or "happening").
* This might be a fragment of an event, in which case the
* timespan will be smaller than the 'whole' timespan, otherwise the
* two timespans will be the same.
*
* The word "Event" is more or less a reserved word in javascript, hence this
* class is named called `Hap`.
*/
export class Hap {
/*
Event class, representing a value active during the timespan
'part'. This might be a fragment of an event, in which case the
timespan will be smaller than the 'whole' timespan, otherwise the
two timespans will be the same. The 'part' must never extend outside of the
'whole'. If the event represents a continuously changing value
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 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'.
*/
/**
* Create a hap. Create a hap. Haps and patterns are considered immutable, but you can create a new pattern with modified haps with functions like {@link Pattern#withHaps} and {@link Pattern#withValue}.
*
* @param {TimeSpan | undefined} whole timespan. If the event represents a continuously changing value
* then the whole will be returned as None, in which case the given value will have been sampled from
* the the start of the `part` timespan.
* @param {TimeSpan} part of the timespan. May never extend outside of the `whole`.
* @param {function(State):* | *} value active during the timespan `part`. Must be a function if `stateful` is set to `true`.
* @param {object} [context={}] - The context is to store metadata. When two patterns are combined, their context objects are merged.
* @param {Array<{ start: number, end: number }>} [context.locations] - list of source code locations causing the event
* @param {string[]} [context.tags] Metadata about the Hap
* @param {boolean} [stateful=false] - (experimental) if true the value depends on the state.
*
* @example
* // Keep only haps whose full `whole` timespan is at least half a cycle long
* s("bd, sd*2, hh*4")
* .filterHaps((hap) => hap.whole !== undefined && hap.whole.duration >= 0.5);
*
* @example
* // Keep only haps that begin within the first half of a cycle
* note("c3 d3 e3 f3")
* .filterHaps((hap) => hap.part.begin < 0.5);
*/
constructor(whole, part, value, context = {}, stateful = false) {
this.whole = whole;
this.part = part;
@@ -1,10 +1,12 @@
/*
stateful.mjs - File of shame for stateful, impure and otherwise illegal pattern methods
Copyright (C) 2025 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/index.mjs>
impure.mjs - File of shame for stateful, impure and otherwise illegal pattern methods
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/impure.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 { register, reify, Pattern } from './pattern.mjs';
import { Pattern } from './pattern.mjs';
import { reify } from './atoms.mjs';
import { register } from './register.mjs';
let timelines = {};
+40
View File
@@ -0,0 +1,40 @@
/*
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 './register.mjs';
export * from './operators.mjs';
export * from './composers.mjs';
export * from './time-structure.mjs';
export * from './values.mjs';
export * from './atoms.mjs';
export * from './misc.mjs';
export * from './stepwise.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;
+47
View File
@@ -0,0 +1,47 @@
/*
logger.mjs - Error logger for strudel
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/logger.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 const logKey = 'strudel.log';
let debounce = 1000,
lastMessage,
lastTime;
/**
* Logs an error to the system and/or Strudel REPL console.
* @global
* @param {*} e
* @param {string} origin
*/
export function errorLogger(e, origin = 'cyclist') {
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {
console.error(e);
}
logger(`[${origin}] error: ${e.message}`);
}
export function logger(message, type, data = {}) {
let t = performance.now();
if (lastMessage === message && t - lastTime < debounce) {
return;
}
lastMessage = message;
lastTime = t;
console.log(`%c${message}`, 'background-color: black;color:white;border-radius:15px');
if (typeof document !== 'undefined' && typeof CustomEvent !== 'undefined') {
document.dispatchEvent(
new CustomEvent(logKey, {
detail: {
message,
type,
data,
},
}),
);
}
}
logger.key = logKey;
+195
View File
@@ -0,0 +1,195 @@
/*
misc.mjs - Miscellaneous pattern functions that should probably be moved to a different package
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/misc.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 { Pattern } from './pattern.mjs';
import { pure, reify } from './atoms.mjs';
import { parray } from './composers.mjs';
import { curry } from './util.mjs';
// These functions are related to superdough / kabelsalat / or general IO (e.g. sliders)
// This entire file should probably not live in the Pattern package,
// but move either to core or superdough.
/** exposes a custom value at query time. basically allows mutating state without evaluation
* @param {function():Pattern} accessor
* @returns {Pattern}
* @tags internals
*/
export const ref = (accessor) =>
pure(1)
.withValue(() => reify(accessor()))
.innerJoin();
const _ensureListPattern = (list) => {
if (Array.isArray(list)) {
return parray(list);
}
return reify(list);
};
/**
* Scale the magnitude of the harmonics of one of the core synths ('sine', 'tri', 'saw', ..)
*
* Can also be used to create a new synth via `s('user').partials(...)`
*
* @name partials
* @tags superdough
* @param {number[] | Pattern} list [0, 1] magnitudes for partials. 0th entry is the fundamental harmonic (i.e. DC offset is skipped)
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* s("user").seg(16).n(irand(8)).scale("A:major")
* .partials([1, 0, 1, 0, 0, 1])
* @example
* s("saw").seg(8).n(irand(12)).scale("G#:minor")
* .partials(binaryL(irand(256).add("1")))
*/
Pattern.prototype.partials = function (list) {
return this.withValue((v) => (l) => ({ ...v, partials: l })).appLeft(_ensureListPattern(list));
};
// Also create a top-level function
export const partials = (list) => {
return _ensureListPattern(list).as('partials');
};
/**
* Rotates the harmonics of one of the core synths ('sine', 'tri', 'saw', 'user', ..) by a list of phases
*
* @name phases
* @tags superdough
* @param {number[] | Pattern} list of [0, 1) phases for partials. 0th entry is the fundamental phase (i.e. DC offset is skipped)
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* // Phase cancellation
* s("saw").seg(8).n(irand(12)).scale("G#1:minor")
* .partials(partials([1, 1, 1]))
* .superimpose(x => x.phases([0.5, 0.5, 0.5]))
*/
Pattern.prototype.phases = function (list) {
return this.withValue((v) => (l) => ({ ...v, phases: l })).appLeft(_ensureListPattern(list));
};
// Also create a top-level function
export const phases = (list) => {
return _ensureListPattern(list).as('phases');
};
/**
* Establishes an FX chain. Can be called by chaining .FX(fx1).FX(fx2)..
* calls and/or in a single .FX(fx1, fx2, ..) call. The fx1, .. are _patterns_ which
* establish the controls of the given effect. See examples.
* @param {...any} effects
* @name FX
* @tags superdough
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* $: s("[sbd <hh [bd | lt | oh]>]*4").dec(.4)
* .FX(
* phaser(0.5).gain(2),
* bpf(800),
* distort(1.3),
* room(0.2),
* delay(0.5).gain(1.25),
* distort(0.3),
* ).fxr(1.7) // sets release time of effects (like delay)
* @example
* $: s("saw").fm(0.5)
* .delay(0.3) // outer effects are applied *last*
* .FX(coarse(4)) // first coarse
* .FX(lpf(500).lpe(4).lpa(1).lpd(2)) // then lpf
* .FX(distort(1)) // then distort
*/
Pattern.prototype.FX = function (...effects) {
effects = effects.map(reify);
return this.withValue((v) => (vEff) => {
const currFX = v.FX ?? [];
return { ...v, FX: currFX.concat(vEff) };
}).appLeft(parray(effects));
};
const _asArrayPattern = (pats) => {
const pack = (...xs) => xs;
let acc = pure(curry(pack, null, pats.length));
for (const p of pats) acc = acc.appLeft(p);
return acc;
};
/**
* Produces a [Kabelsalat](https://kabel.salat.dev/) modular sound engine.
* This can be used as either an effect (by including `audioin()` at the beginning
* of your kabel expression) or as a sound source (via any expression which doesn't
* start with `audioin()`).
*
* Some helpers you have available to you:
* * Strudel mini notation works fine in K(..) via "" or ``
* * More complex Strudel expressions (like "0 1 2".fast(4) or irand(24)) can be
* written by wrapping them in `S(..)` inside your Kabel code
* * We expose Strudel's note frequency under `sFreq` and Strudel's gate
* information under `sGate`
* * You can use more complex multi-line expressions (like `let x = a; let y = b; x.lpf(y);`)
* by wrapping them inside a function in K (see example).
*
* @name K
* @tags generators, superdough
* @param {KabelsalatExpression | Function} expr Kabelsalat graph definition
* @memberof Pattern.prototype
* @returns {Pattern}
*
* @example
* note("A c e".fast(4)).transpose("<0 2 4 6 8>")
* .scale("F:minor").transpose("12")
* .s("saw")
* .K(
* // audioin().mul(sGate.adsr(0.001, 0.3, 0, 0.2)) // as effect
* saw(saw(sFreq / "2!3 16").mul(8).add(sFreq).lag("0!3 0.1")).mul(0.3) // as source
* .mul(sGate.adsr(0, 0.15, 0.5, "0.1!3 1"))
* .lpf(sGate.adsr(0, 0.2, 0.3, 0.2).mul(1).add(0))
* .add(x => x.delay(S("0.3 0.2".fast(2))).mul(0.7))
* .add(x => x.delay("0.03 [0.08 0.01] 0.01 0.013").mul(0.77)).mul(0.7)
* .add(x => x.delay(.13).mul(0.7))
* .out()
* )
*
* @example
* n("<0 1 <2 3 2 4>>*16")
* .scale("G#2:minor").sometimes(x => x.transpose("12 | 24"))
* .K(() => {
* const att = S(rand.range(0, 0.05))
* const dec = S(rand.range(0.05, 0.2))
* let f = n(sFreq);
* const mod = sine(f).mul("0.1 | 0.2 | 0.3")
* .add("[[1.5 1] | 1 | 2 | 4 | [6 4@3]]*2")
* saw(f.mul(mod))
* .mul(sGate.ad(att, dec))
* .add(x => x.delay(0.4).mul(0.3))
* .out()
* }).fxr(1).room(0.3)
*/
/**
* Creates a worklet effect. Typically derived by writing K(...) in the REPL which will parse
* Kabelsalat code.
*
* @name worklet
* @param {string} src Source code of the worklet update function
* @param {...number | ...Pattern} inputs Worklet inputs
* @memberof Pattern.prototype
* @returns {Pattern}
* @noAutocomplete
*/
Pattern.prototype.worklet = function (src, ...inputs) {
inputs = inputs.map(reify);
return this.outerBind((v) => {
return _asArrayPattern(inputs).withValue((vInput) => {
const currInputs = v.workletInputs ?? [];
return { ...v, workletSrc: src, workletInputs: currInputs.concat(vInput) };
});
});
};
export const worklet = (...args) => pure({}).worklet(...args);
+518
View File
@@ -0,0 +1,518 @@
/*
operators.mjs - Pattern operator functions with multiple alignments
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/operators.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 { isFraction } from './fraction.mjs';
import { Pattern } from './pattern.mjs';
import { reify } from './atoms.mjs';
import { sequence } from './composers.mjs';
import { numeralArgs, _mod, curry } from './util.mjs';
import { unionWithObj } from './value.mjs';
//////////////////////////////////////////////////////////////////////
// compose matrix functions
const ALIGNMENTS = {
in(self, other, func) {
return self.fmap(func).appLeft(reify(other));
},
out(self, other, func) {
return self.fmap(func).appRight(reify(other));
},
mix(self, other, func) {
return self.fmap(func).appBoth(reify(other));
},
squeeze(self, other, func) {
const otherPat = reify(other);
return self.fmap((a) => otherPat.fmap((b) => func(a)(b))).squeezeJoin();
},
squeezeOut(self, other, func) {
const otherPat = reify(other);
return otherPat.fmap((a) => self.fmap((b) => func(b)(a))).squeezeJoin();
},
reset(self, other, func) {
const otherPat = reify(other);
return otherPat.fmap((b) => self.fmap((a) => func(a)(b))).resetJoin();
},
restart(self, other, func) {
const otherPat = reify(other);
return otherPat.fmap((b) => self.fmap((a) => func(a)(b))).restartJoin();
},
poly(self, other, func) {
const otherPat = reify(other);
return self.fmap((b) => otherPat.fmap((a) => func(a)(b))).polyJoin();
},
};
let DEFAULT_ALIGNMENT = 'in';
const ALIGNMENT_KEYS = Object.keys(ALIGNMENTS).map((how) => how.toLowerCase());
/**
* Sets the default method of combining events from two patterns (aka [alignment](https://strudel.cc/technical-manual/alignment/)) in Strudel.
* The default method is 'in', meaning that patterns to the left will (typically) dictate the event timings when combined with patterns to the right.
* By changing alignment to 'out', the opposite will happen. With 'mix', they will combine their event timings.
*
* Note that we say the _default_ method, because alignments can also be set explicitly with calls like
* 'add.mix', 'set.squeeze', etc.
*
* @param {string} alignment Default join method to use. Options: 'in', 'out', 'mix', 'squeeze', 'squeezeout', 'reset', 'restart', 'poly'
* @tags combiners
* @example
* setDefaultJoin('mix') // also try 'in', 'out', 'squeeze', etc.
* s("saw").vel("1 0.5").note("F A C E").delay("0 0.2 0.3")
*/
export const setDefaultJoin = (alignment) => {
alignment = alignment?.toLowerCase();
if (DEFAULT_ALIGNMENT !== alignment && ALIGNMENT_KEYS.includes(alignment)) {
DEFAULT_ALIGNMENT = alignment;
setupAlignments();
}
};
// pattern operators
const OPERATORS = {
/**
* When called on a pattern `a`, with a input pattern `b` (`a.set(b)`),
* combines `a` and `b` such that anything defined in `b`
* and anything defined in `a` that is *not* defined in `b`
* will be in the resulting pattern.
*
* The structure is maintained from `a`,
* because the default pattern alignment is `in`,
* see the section on `Pattern Alignment`
* in the technical manual in the docs
*
* This is the inverse of `keep`
*
* See examples below
* @name set
* @param {Pattern} a
* @param {Pattern} b
* @returns {Pattern}
* @memberof Pattern.prototype
* @tags internals, combiners
* @example
* // because input pattern has `s` set,
* // it overrides the "sine" declared earlier
* note("c a f e").s("sine").set(s("triangle"))
*/
set: [(a, b) => b],
/**
* When called on a pattern `a`, with a input pattern `b` (`a.keep(b)`),
* combines `a` and `b` such that anything defined in `a`,
* and anything defined in `b` that is *not* defined in `a`
* will be in the resulting pattern
*
* The structure is maintained from `a`,
* because the default pattern alignment is `in`,
* see the section on `Pattern Alignment`
* in the technical manual in the docs
*
* This is the inverse of `set`
*
* See examples below
* @name keep
* @param {Pattern} a
* @memberof Pattern.prototype
* @returns {Pattern}
* @tags internals, combiners
* @example
* // notes, already defined, will stay "c a f e",
* // while "s", not defined, will be set to "piano"
* note("c a f e").keep(note("e f a c").s("piano"))
*/
keep: [(a) => a],
keepif: [(a, b) => (b ? a : undefined)],
// numerical functions
/**
*
* Assumes a pattern of numbers. Adds the given number to each item in the pattern.
* @name add
* @memberof Pattern.prototype
* @tags math
* @example
* // Here, the triad 0, 2, 4 is shifted by different amounts
* n("0 2 4".add("<0 3 4 0>")).scale("C:major")
* // Without add, the equivalent would be:
* // n("<[0 2 4] [3 5 7] [4 6 8] [0 2 4]>").scale("C:major")
* @example
* // You can also use add with notes:
* note("c3 e3 g3".add("<0 5 7 0>"))
* // Behind the scenes, the notes are converted to midi numbers:
* // note("48 52 55".add("<0 5 7 0>"))
*/
add: [numeralArgs((a, b) => a + b)], // support string concatenation
/**
*
* Like add, but the given numbers are subtracted.
* @name sub
* @memberof Pattern.prototype
* @tags math
* @example
* n("0 2 4".sub("<0 1 2 3>")).scale("C4:minor")
* // See add for more information.
*/
sub: [numeralArgs((a, b) => a - b)],
/**
*
* Multiplies each number by the given factor.
* @name mul
* @memberof Pattern.prototype
* @tags math
* @example
* "<1 1.5 [1.66, <2 2.33>]>*4".mul(150).freq()
*/
mul: [numeralArgs((a, b) => a * b)],
/**
*
* Divides each number by the given factor.
* @name div
* @memberof Pattern.prototype
* @tags math
*/
div: [numeralArgs((a, b) => a / b)],
/**
*
* Divides each number by the given factor and returns the remainder
* @name mod
* @memberof Pattern.prototype
* @tags math
*/
mod: [numeralArgs(_mod)],
/**
*
* Raises each number to the power of the given factor
* @name pow
* @memberof Pattern.prototype
* @tags math
*/
pow: [numeralArgs(Math.pow)],
/**
*
* Performs a bitwise `and` on each number and the given factor
* @name band
* @memberof Pattern.prototype
* @tags math
*/
band: [numeralArgs((a, b) => a & b)],
/**
*
* Performs a bitwise `or` on each number and the given factor
* @name bor
* @memberof Pattern.prototype
* @tags math
*/
bor: [numeralArgs((a, b) => a | b)],
/**
*
* Performs a bitwise `xor` on each number and the given factor
* @name bxor
* @memberof Pattern.prototype
* @tags math
*/
bxor: [numeralArgs((a, b) => a ^ b)],
/**
*
* Performs a bitwise `left shift` on each number by the given factor
* @name blshift
* @memberof Pattern.prototype
* @tags math
*/
blshift: [numeralArgs((a, b) => a << b)],
/**
*
* Performs a bitwise `right shift` on each number by the given factor
* @name brshift
* @memberof Pattern.prototype
* @tags math
*/
brshift: [numeralArgs((a, b) => a >> b)],
// TODO - force numerical comparison if both look like numbers?
/**
* performs a < b
* @name lt
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
lt: [(a, b) => a < b],
/**
* performs a > b
* @name gt
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
gt: [(a, b) => a > b],
/**
* performs a <= b
* @name lte
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
lte: [(a, b) => a <= b],
/**
* performs a >= b
* @name gte
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
gte: [(a, b) => a >= b],
/**
* performs a == b
* @name eq
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
eq: [(a, b) => a == b],
/**
* performs a === b (strictly equal)
* @name eqt
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
eqt: [(a, b) => a === b],
/**
* performs a != b
* @name ne
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
ne: [(a, b) => a != b],
/**
* performs a !== b (strictly not equal)
* @name net
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
net: [(a, b) => a !== b],
/**
* performs a && b
* @name and
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
and: [(a, b) => a && b],
/**
* performs a || b
* @name or
* @memberof Pattern.prototype
* @tags math
* @param {any} a
* @param {any} b
* @returns {Pattern} with boolean value(s)
*/
or: [(a, b) => a || b],
// bitwise ops
func: [(a, b) => b(a)],
};
const setupAlignments = () => {
// generate methods to do what and how
for (const [what, [op, preprocess]] of Object.entries(OPERATORS)) {
// make plain version, e.g. pat._add(value) adds that plain value
// to all the values in pat
Pattern.prototype['_' + what] = function (value) {
return this.fmap((x) => op(x, value));
};
// make patternified monster version
Object.defineProperty(Pattern.prototype, what, {
// Set to configurable so we can update if the default alignment changes
configurable: true,
// a getter that returns a function, so 'pat' can be
// accessed by closures that are methods of that function..
get: function () {
const pat = this;
// wrap the 'in' function as default behaviour
const wrapper = (...other) => pat[what][DEFAULT_ALIGNMENT](...other);
// add methods to that function for each behaviour
for (const [alignment, alignmentFunc] of Object.entries(ALIGNMENTS)) {
wrapper[alignment.toLowerCase()] = function (...other) {
var howpat = pat;
other = sequence(other);
if (preprocess) {
howpat = preprocess(howpat);
other = preprocess(other);
}
var result;
// hack to remove undefs when doing 'keepif'
if (what === 'keepif') {
// avoid union, as we want to throw away the value of 'b' completely
result = alignmentFunc(howpat, other, (a) => (b) => op(a, b));
result = result.removeUndefineds();
} else {
result = alignmentFunc(howpat, other, (a) => (b) => _composeOp(a, b, op));
}
return result;
};
}
wrapper.squeezein = wrapper.squeeze;
return wrapper;
},
});
}
};
function _nonArrayObject(x) {
return !Array.isArray(x) && typeof x === 'object' && !isFraction(x);
}
function _composeOp(a, b, func) {
if (_nonArrayObject(a) || _nonArrayObject(b)) {
if (!_nonArrayObject(a)) {
a = { value: a };
}
if (!_nonArrayObject(b)) {
b = { value: b };
}
return unionWithObj(a, b, func);
}
return func(a, b);
}
// Make composers
setupAlignments();
// Default op to 'set', e.g. pat.squeeze(pat2) = pat.set.squeeze(pat2)
for (const alignment of ALIGNMENT_KEYS) {
Pattern.prototype[alignment] = function (...args) {
return this.set[alignment](args);
};
}
// binary composers
/**
* Applies the given structure to the pattern:
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* note("c,eb,g")
* .struct("x ~ x ~ ~ x ~ x ~ ~ ~ x ~ x ~ ~")
* .slow(2)
*/
Pattern.prototype.struct = function (...args) {
return this.keepif.out(...args);
};
Pattern.prototype.structAll = function (...args) {
return this.keep.out(...args);
};
/**
* Returns silence when mask is 0 or "~"
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* note("c [eb,g] d [eb,g]").mask("<1 [0 1]>")
*/
Pattern.prototype.mask = function (...args) {
return this.keepif.in(...args);
};
Pattern.prototype.maskAll = function (...args) {
return this.keep.in(...args);
};
/**
* Resets the pattern to the start of the cycle for each onset of the reset pattern.
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* s("[<bd lt> sd]*2, hh*8").reset("<x@3 x(5,8)>")
*/
Pattern.prototype.reset = function (...args) {
return this.keepif.reset(...args);
};
Pattern.prototype.resetAll = function (...args) {
return this.keep.reset(...args);
};
/**
* Restarts the pattern for each onset of the restart pattern.
* While reset will only reset the current cycle, restart will start from cycle 0.
*
* @param {...any} args
* @tags temporal
* @returns {Pattern}
* @example
* s("[<bd lt> sd]*2, hh*8").restart("<x@3 x(5,8)>")
*/
Pattern.prototype.restart = function (...args) {
return this.keepif.restart(...args);
};
Pattern.prototype.restartAll = function (...args) {
return this.keep.restart(...args);
};
export const mask = curry((a, b) => reify(b).mask(a));
export const struct = curry((a, b) => reify(b).struct(a));
export const superimpose = curry((a, b) => reify(b).superimpose(...a));
export const withValue = curry((a, b) => reify(b).withValue(a));
export const bind = curry((a, b) => reify(b).bind(a));
export const innerBind = curry((a, b) => reify(b).innerBind(a));
export const outerBind = curry((a, b) => reify(b).outerBind(a));
export const squeezeBind = curry((a, b) => reify(b).squeezeBind(a));
export const stepBind = curry((a, b) => reify(b).stepBind(a));
export const polyBind = curry((a, b) => reify(b).polyBind(a));
// operators
export const set = curry((a, b) => reify(b).set(a));
export const keep = curry((a, b) => reify(b).keep(a));
export const keepif = curry((a, b) => reify(b).keepif(a));
export const add = curry((a, b) => reify(b).add(a));
export const sub = curry((a, b) => reify(b).sub(a));
export const mul = curry((a, b) => reify(b).mul(a));
export const div = curry((a, b) => reify(b).div(a));
export const mod = curry((a, b) => reify(b).mod(a));
export const pow = curry((a, b) => reify(b).pow(a));
export const band = curry((a, b) => reify(b).band(a));
export const bor = curry((a, b) => reify(b).bor(a));
export const bxor = curry((a, b) => reify(b).bxor(a));
export const blshift = curry((a, b) => reify(b).blshift(a));
export const brshift = curry((a, b) => reify(b).brshift(a));
export const lt = curry((a, b) => reify(b).lt(a));
export const gt = curry((a, b) => reify(b).gt(a));
export const lte = curry((a, b) => reify(b).lte(a));
export const gte = curry((a, b) => reify(b).gte(a));
export const eq = curry((a, b) => reify(b).eq(a));
export const eqt = curry((a, b) => reify(b).eqt(a));
export const ne = curry((a, b) => reify(b).ne(a));
export const net = curry((a, b) => reify(b).net(a));
export const and = curry((a, b) => reify(b).and(a));
export const or = curry((a, b) => reify(b).or(a));
export const func = curry((a, b) => reify(b).func(a));
+44
View File
@@ -0,0 +1,44 @@
{
"name": "@strudel/pattern",
"version": "1.3.0",
"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"
}
}
+918
View File
@@ -0,0 +1,918 @@
/*
pattern.mjs - Core pattern representation for strudel
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pattern.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 TimeSpan from './timespan.mjs';
import Fraction, { lcm } from './fraction.mjs';
import Hap from './hap.mjs';
import State from './state.mjs';
import { removeUndefineds, flatten, id, parseNumeral, stringifyValues } from './util.mjs';
import drawLine from './drawLine.mjs';
import { errorLogger, logger } from './logger.mjs';
let __steps = true;
// Set whether pattern steps should be calculated in relevant operations.
// Only used in benchmarking.
export function setCalculateSteps(x) {
__steps = x ? true : false;
}
// Get whether pattern steps should be calculated in relevant operations.
export function getCalculateSteps() {
return __steps;
}
/**
* checks if the given thing is an pattern
* @param {*} thing
* @returns {boolean}
*/
export function isPattern(thing) {
// thing?.constructor?.name !== 'Pattern' // <- this will fail when code is mangled
const is = thing instanceof Pattern || thing?._Pattern;
// TODO: find out how to check wrong core dependency. below will never work !thing === 'undefined'
// wrapping it in (..) will result other checks to log that warning (e.g. isPattern('kalimba'))
/* if (!thing instanceof Pattern) {
console.warn(
`Found Pattern that fails "instanceof Pattern" check.
This may happen if you are using multiple versions of @strudel/core.
Please check by running "npm ls @strudel/core".`,
);
console.log(thing);
} */
return is;
}
/** @class Class representing a pattern. */
export class Pattern {
/**
* Create a pattern. As an end user, you will most likely not create a Pattern directly.
*
* @param {Function} query - The function that maps a `State` to an array of `Hap`.
* @param {number | undefined} [steps=undefined]
* @noAutocomplete
*/
constructor(query, steps = undefined) {
this.query = query;
this._Pattern = true; // this property is used to detectinstance of another Pattern
this._steps = steps; // in terms of number of steps per cycle
}
get _steps() {
return this.__steps;
}
set _steps(steps) {
this.__steps = steps === undefined ? undefined : Fraction(steps);
}
_processParts() {
return this.withHap((hap) => hap.withContext((c) => ({ ...c, processParts: true })));
}
setSteps(steps) {
// TODO shouldn't this be pure and return a new pattern?
this._steps = steps;
return this;
}
withSteps(f) {
if (!getCalculateSteps()) {
return this;
}
return new Pattern(this.query, this._steps === undefined ? undefined : f(this._steps));
}
get hasSteps() {
return this._steps !== undefined;
}
//////////////////////////////////////////////////////////////////////
// Haskell-style functor, applicative and monadic operations
/**
* Returns a new pattern, with the function applied to the value of
* each {@link Hap}. It has the alias `fmap`.
* @tags functional
* @synonyms fmap
* @param {Function} func to to apply to the value
* @returns {Pattern}
* @example
* "0 1 2".withValue(v => v + 10).log()
*/
withValue(func) {
const result = new Pattern((state) => this.query(state).map((hap) => hap.withValue(func)));
result._steps = this._steps;
return result;
}
// runs func on query state
withState(func) {
return new Pattern((state) => this.query(func(state)));
}
fmap(func) {
return this.withValue(func);
}
/**
* Assumes 'this' is a pattern of functions, and given a function to
* resolve wholes, applies a given pattern of values to that
* pattern of functions.
* @tags functional
* @param {Function} whole_func
* @param {Function} pat_val
* @noAutocomplete
* @returns {Pattern}
*/
appWhole(whole_func, pat_val) {
const pat_func = this;
const query = function (state) {
const hap_funcs = pat_func.query(state);
const hap_vals = pat_val.query(state);
const apply = function (hap_func, hap_val) {
const s = hap_func.part.intersection(hap_val.part);
if (s == undefined) {
return undefined;
}
return new Hap(
whole_func(hap_func.whole, hap_val.whole),
s,
hap_func.value(hap_val.value),
hap_val.combineContext(hap_func),
);
};
return flatten(
hap_funcs.map((hap_func) => removeUndefineds(hap_vals.map((hap_val) => apply(hap_func, hap_val)))),
);
};
return new Pattern(query);
}
/**
* When this method is called on a pattern of functions, it matches its haps
* with those in the given pattern of values. A new pattern is returned, with
* each matching value applied to the corresponding function.
*
* In this `_appBoth` variant, where timespans of the function and value haps
* are not the same but do intersect, the resulting hap has a timespan of the
* intersection. This applies to both the part and the whole timespan.
* @tags functional
* @param {Pattern} pat_val
* @noAutocomplete
* @returns {Pattern}
*/
appBoth(pat_val) {
const pat_func = this;
// Tidal's <*>
const whole_func = function (span_a, span_b) {
if (span_a == undefined || span_b == undefined) {
return undefined;
}
return span_a.intersection_e(span_b);
};
const result = pat_func.appWhole(whole_func, pat_val);
if (getCalculateSteps()) {
result._steps = lcm(pat_val._steps, pat_func._steps);
}
return result;
}
/**
* As with `appBoth`, but the `whole` timespan is not the intersection,
* but the timespan from the function of patterns that this method is called
* on. In practice, this means that the pattern structure, including onsets,
* are preserved from the pattern of functions (often referred to as the left
* hand or inner pattern).
* @tags functional
* @param {Pattern} pat_val
* @noAutocomplete
* @returns {Pattern}
*/
appLeft(pat_val) {
const pat_func = this;
const query = function (state) {
const haps = [];
for (const hap_func of pat_func.query(state)) {
const hap_vals = pat_val.query(state.setSpan(hap_func.wholeOrPart()));
for (const hap_val of hap_vals) {
const new_whole = hap_func.whole;
const new_part = hap_func.part.intersection(hap_val.part);
if (new_part) {
const new_value = hap_func.value(hap_val.value);
const new_context = hap_val.combineContext(hap_func);
const hap = new Hap(new_whole, new_part, new_value, new_context);
haps.push(hap);
}
}
}
return haps;
};
const result = new Pattern(query);
result._steps = this._steps;
return result;
}
/**
* As with `appLeft`, but `whole` timespans are instead taken from the
* pattern of values, i.e. structure is preserved from the right hand/outer
* pattern.
* @tags functional
* @param {Pattern} pat_val
* @noAutocomplete
* @returns {Pattern}
*/
appRight(pat_val) {
const pat_func = this;
const query = function (state) {
const haps = [];
for (const hap_val of pat_val.query(state)) {
const hap_funcs = pat_func.query(state.setSpan(hap_val.wholeOrPart()));
for (const hap_func of hap_funcs) {
const new_whole = hap_val.whole;
const new_part = hap_func.part.intersection(hap_val.part);
if (new_part) {
const new_value = hap_func.value(hap_val.value);
const new_context = hap_val.combineContext(hap_func);
const hap = new Hap(new_whole, new_part, new_value, new_context);
haps.push(hap);
}
}
}
return haps;
};
const result = new Pattern(query);
result._steps = pat_val._steps;
return result;
}
bindWhole(choose_whole, func) {
const pat_val = this;
const query = function (state) {
const withWhole = function (a, b) {
return new Hap(
choose_whole(a.whole, b.whole),
b.part,
b.value,
Object.assign({}, a.context, b.context, {
locations: (a.context.locations || []).concat(b.context.locations || []),
}),
);
};
const match = function (a) {
return func(a.value)
.query(state.setSpan(a.part))
.map((b) => withWhole(a, b));
};
return flatten(pat_val.query(state).map((a) => match(a)));
};
return new Pattern(query);
}
bind(func) {
const whole_func = function (a, b) {
if (a == undefined || b == undefined) {
return undefined;
}
return a.intersection_e(b);
};
return this.bindWhole(whole_func, func);
}
join() {
// Flattens a pattern of patterns into a pattern, where wholes are
// the intersection of matched inner and outer haps.
return this.bind(id);
}
outerBind(func) {
return this.bindWhole((a) => a, func).setSteps(this._steps);
}
outerJoin() {
// Flattens a pattern of patterns into a pattern, where wholes are
// taken from outer haps.
return this.outerBind(id);
}
innerBind(func) {
return this.bindWhole((_, b) => b, func);
}
innerJoin() {
// Flattens a pattern of patterns into a pattern, where wholes are
// taken from inner haps.
return this.innerBind(id);
}
// Flatterns patterns of patterns, by retriggering/resetting inner patterns at onsets of outer pattern haps
resetJoin(restart = false) {
const pat_of_pats = this;
return new Pattern((state) => {
return (
pat_of_pats
// drop continuous haps from the outer pattern.
.discreteOnly()
.query(state)
.map((outer_hap) => {
return (
outer_hap.value
// reset = align the inner pattern cycle start to outer pattern haps
// restart = align the inner pattern cycle zero to outer pattern haps
.late(restart ? outer_hap.whole.begin : outer_hap.whole.begin.cyclePos())
.query(state)
.map((inner_hap) =>
new Hap(
// Supports continuous haps in the inner pattern
inner_hap.whole ? inner_hap.whole.intersection(outer_hap.whole) : undefined,
inner_hap.part.intersection(outer_hap.part),
inner_hap.value,
).setContext(outer_hap.combineContext(inner_hap)),
)
// Drop haps that didn't intersect
.filter((hap) => hap.part)
);
})
.flat()
);
});
}
restartJoin() {
return this.resetJoin(true);
}
// Like the other joins above, joins a pattern of patterns of values, into a flatter
// pattern of values. In this case it takes whole cycles of the inner pattern to fit each event
// in the outer pattern.
squeezeJoin() {
// A pattern of patterns, which we call the 'outer' pattern, with patterns
// as values which we call the 'inner' patterns.
const pat_of_pats = this;
function query(state) {
// Get the events with the inner patterns. Ignore continuous events (without 'wholes')
const haps = pat_of_pats.discreteOnly().query(state);
// A function to map over the events from the outer pattern.
function flatHap(outerHap) {
// Get the inner pattern, slowed and shifted so that the 'whole'
// timespan of the outer event corresponds to the first cycle of the
// inner event
const inner_pat = outerHap.value._focusSpan(outerHap.wholeOrPart());
// Get the inner events, from the timespan of the outer event's part
const innerHaps = inner_pat.query(state.setSpan(outerHap.part));
// A function to map over the inner events, to combine them with the
// outer event
function munge(outer, inner) {
let whole = undefined;
if (inner.whole && outer.whole) {
whole = inner.whole.intersection(outer.whole);
if (!whole) {
// The wholes are present, but don't intersect
return undefined;
}
}
const part = inner.part.intersection(outer.part);
if (!part) {
// The parts don't intersect
return undefined;
}
const context = inner.combineContext(outer);
return new Hap(whole, part, inner.value, context);
}
return innerHaps.map((innerHap) => munge(outerHap, innerHap));
}
const result = flatten(haps.map(flatHap));
// remove undefineds
return result.filter((x) => x);
}
return new Pattern(query);
}
squeezeBind(func) {
return this.fmap(func).squeezeJoin();
}
polyJoin = function () {
const pp = this;
return pp.fmap((p) => p.extend(pp._steps.div(p._steps))).outerJoin();
};
polyBind(func) {
return this.fmap(func).polyJoin();
}
//////////////////////////////////////////////////////////////////////
// Utility methods mainly for internal use
/**
* Query {@link Hap}s inside the given time span.
*
* @tags internals
* @param {Fraction | number} begin from time
* @param {Fraction | number} end to time
* @param {object} [controls]
* @returns {Hap[]}
* @example
* const pattern = sequence('a', ['b', 'c'])
* const haps = pattern.queryArc(0, 1)
* console.log(haps)
* silence
* @noAutocomplete
*/
queryArc(begin, end, controls = {}) {
if (controls.propagateExceptions) {
// In tests, we want exceptions to propagate to actually catch problems
// and to see the proper stack trace in the test result.
return this.query(new State(new TimeSpan(begin, end), controls));
} else {
try {
return this.query(new State(new TimeSpan(begin, end), controls));
} catch (err) {
errorLogger(err, 'query');
return [];
}
}
}
/**
* Returns a new pattern, with queries split at cycle boundaries. This makes
* some calculations easier to express, as all haps are then constrained to
* happen within a cycle.
* @tags internals
* @returns {Pattern}
* @noAutocomplete
*/
splitQueries() {
const pat = this;
const q = (state) => {
return flatten(state.span.spanCycles.map((subspan) => pat.query(state.setSpan(subspan))));
};
return new Pattern(q);
}
/**
* Returns a new pattern, where the given function is applied to the query
* timespan before passing it to the original pattern.
* @tags internals
* @param {function(TimeSpan):TimeSpan} func the function to apply
* @returns {Pattern}
* @noAutocomplete
*/
withQuerySpan(func) {
return new Pattern((state) => this.query(state.withSpan(func)));
}
withQuerySpanMaybe(func) {
const pat = this;
return new Pattern((state) => {
const newState = state.withSpan(func);
if (!newState.span) {
return [];
}
return pat.query(newState);
});
}
/**
* As with `withQuerySpan`, but the function is applied to both the
* begin and end time of the query timespan.
* @tags internals
* @param {Function} func the function to apply
* @returns {Pattern}
* @noAutocomplete
*/
withQueryTime(func) {
return new Pattern((state) => this.query(state.withSpan((span) => span.withTime(func))));
}
/**
* Similar to {@link Pattern#withQuerySpan}, but the function is applied to the timespans
* of all {@link Hap}s returned by pattern queries (both `part` timespans, and where
* present, `whole` timespans).
* @tags internals
* @param {function(TimeSpan):TimeSpan} func
* @returns {Pattern}
* @noAutocomplete
*/
withHapSpan(func) {
return new Pattern((state) => this.query(state).map((hap) => hap.withSpan(func)));
}
/**
* As with {@link Pattern#withHapSpan}, but the function is applied to both the
* begin and end time of the {@link Hap} timespans.
* @tags internals
* @param {function(TimeSpan):TimeSpan} func the function to apply
* @returns {Pattern}
* @noAutocomplete
*/
withHapTime(func) {
return this.withHapSpan((span) => span.withTime(func));
}
/**
* Returns a new pattern with the given function applied to the list of {@link Hap}s returned by every query.
*
* As an end user, you will most likely not need to use this; look at {@link Pattern#withContext}, {@link Pattern#withHapSpan}, etc. instead.
* @tags internals
* @param {Function} func
* @returns {Pattern}
* @noAutocomplete
* @example
* note("[a b, c d] a b c d").s("gm_piano").withHaps(x=>{
* if (x.length > 1) {
* x = x.map(hap => hap.withValue(val => {
* return {
* n: 1,
* // select gm_piano:1 sample
* ...val
* }
* }));
* }
* return x
* })
*/
withHaps(func) {
const result = new Pattern((state) => func(this.query(state), state));
result._steps = this._steps;
return result;
}
/**
* As with {@link Pattern#withHaps}, but applies the function to every {@link Hap}, rather than every list of haps.
*
* As an end user, you will most likely not need to use this; look at {@link Pattern#withContext}, {@link Pattern#withHapSpan}, etc. instead.
* @tags internals
* @param {Function} func
* @returns {Pattern}
* @noAutocomplete
* @example
* note("c a f e").withHap(x=>{
* if (x.value.note == 'c') {
* x.value.s = 'gm_piano'
* }
* else {
* x.value.s = 'gm_piano'
* x.value.n = 2
* }
* return x
* })
*/
withHap(func) {
return this.withHaps((haps) => haps.map(func));
}
/**
* Returns a new pattern with the context field set to every {@link Hap} set to the given value.
* @tags internals
* @param {*} context
* @returns {Pattern}
* @noAutocomplete
*/
setContext(context) {
return this.withHap((hap) => hap.setContext(context));
}
/**
* Returns a new pattern with the given function applied to the context field of every {@link Hap}.
* @tags internals
* @param {Function} func
* @returns {Pattern}
* @noAutocomplete
*/
withContext(func) {
const result = this.withHap((hap) => hap.setContext(func(hap.context)));
if (this.__pure !== undefined) {
result.__pure = this.__pure;
result.__pure_loc = this.__pure_loc;
}
return result;
}
/**
* Returns a new pattern with the `context` field of every {@link Hap} set to an empty object.
* @tags internals
* @returns {Pattern}
* @noAutocomplete
*/
stripContext() {
return this.withHap((hap) => hap.setContext({}));
}
/**
* Returns a new pattern with the given location information added to the
* context of every {@link Hap}.
* @tags internals
* @param {number} start start offset
* @param {number} end end offset
* @returns {Pattern}
* @noAutocomplete
*/
withLoc(start, end) {
const location = {
start,
end,
};
const result = this.withContext((context) => {
const locations = (context.locations || []).concat([location]);
return { ...context, locations };
});
if (this.__pure) {
result.__pure = this.__pure;
result.__pure_loc = location;
}
return result;
}
/**
* Returns a new Pattern, which only returns {@link Hap}s that meet the given test.
* @tags internals
* @param {function(Hap):boolean} hap_test - a function which returns false for {@link Hap}s to be removed from the pattern
* @returns {Pattern}
* @example
* s("bd*8").velocity(rand).filterHaps((h) => (h.whole.begin % 1) < h.value.velocity)
*/
filterHaps(hap_test) {
return new Pattern((state) => this.query(state).filter(hap_test));
}
/**
* As with {@link Pattern#filterHaps}, but the function is applied to values
* inside haps.
* @tags internals
* @param {Function} value_test
* @returns {Pattern}
* @example
* const drums = s("bd sd bd sd")
* kick: drums.filterValues((v) => v.s === 'bd').duck(2)
* snare: drums.filterValues((v) => v.s === 'sd')
* bass: s("saw!4").note("G#1").lpf(80).lpenv(4).orbit(2)
*/
filterValues(value_test) {
return new Pattern((state) => this.query(state).filter((hap) => value_test(hap.value))).setSteps(this._steps);
}
/**
* Returns a new pattern, with haps containing undefined values removed from
* query results.
* @tags internals
* @returns {Pattern}
* @noAutocomplete
*/
removeUndefineds() {
return this.filterValues((val) => val != undefined);
}
/**
* Returns a new pattern, with all {@link Hap}s without onsets filtered out.
*
* A hap with an onset is one with a `whole` timespan that begins at the same time
* as its `part` timespan.
* @tags internals
* @returns {Pattern}
* @noAutocomplete
*/
onsetsOnly() {
return this.filterHaps((hap) => hap.hasOnset());
}
/**
* Returns a new pattern, with 'continuous' {@link Hap}s (those without 'whole'
* timespans) removed from query results.
* @tags internals
* @returns {Pattern}
* @noAutocomplete
*/
discreteOnly() {
// removes continuous haps that don't have a 'whole' timespan
return this.filterHaps((hap) => hap.whole);
}
/**
* Combines adjacent {@link Hap}s with the same value and whole. Only
* intended for use in tests.
* @tags internals
* @noAutocomplete
* @returns {Pattern}
*/
defragmentHaps() {
// remove continuous haps
const pat = this.discreteOnly();
return pat.withHaps((haps) => {
const result = [];
for (var i = 0; i < haps.length; ++i) {
var searching = true;
var a = haps[i];
while (searching) {
const a_value = JSON.stringify(haps[i].value);
var found = false;
for (var j = i + 1; j < haps.length; j++) {
const b = haps[j];
if (a.whole.equals(b.whole)) {
if (a.part.begin.eq(b.part.end)) {
if (a_value === JSON.stringify(b.value)) {
// eat the matching hap into 'a'
a = new Hap(a.whole, new TimeSpan(b.part.begin, a.part.end), a.value);
haps.splice(j, 1);
// restart the search
found = true;
break;
}
} else if (b.part.begin.eq(a.part.end)) {
if (a_value == JSON.stringify(b.value)) {
// eat the matching hap into 'a'
a = new Hap(a.whole, new TimeSpan(a.part.begin, b.part.end), a.value);
haps.splice(j, 1);
// restart the search
found = true;
break;
}
}
}
}
searching = found;
}
result.push(a);
}
return result;
});
}
/**
* Queries the pattern for the first cycle, returning {@link Hap}s. Mainly of use when
* debugging a pattern.
* @tags internals
* @param {boolean} with_context - set to true, otherwise the context field
* will be stripped from the resulting haps.
* @returns {Hap[]}
* @noAutocomplete
*/
firstCycle(with_context = false) {
var self = this;
if (!with_context) {
self = self.stripContext();
}
return self.query(new State(new TimeSpan(Fraction(0), Fraction(1))));
}
/**
* Accessor for a list of values returned by querying the first cycle.
* @tags internals
* @noAutocomplete
* @returns {number[]}
*/
get firstCycleValues() {
return this.firstCycle().map((hap) => hap.value);
}
/**
* More human-readable version of the `firstCycleValues` accessor.
* @tags internals
* @noAutocomplete
* @returns {string[]}
*/
get showFirstCycle() {
return this.firstCycle().map(
(hap) => `${hap.value}: ${hap.whole.begin.toFraction()} - ${hap.whole.end.toFraction()}`,
);
}
/**
* Returns a new pattern, which returns {@link Hap}s sorted in temporal order. Mainly
* of use when comparing two patterns for equality, in tests.
* @tags internals
* @returns {Pattern}
* @noAutocomplete
*/
sortHapsByPart() {
return this.withHaps((haps) =>
haps.sort((a, b) =>
a.part.begin
.sub(b.part.begin)
.or(a.part.end.sub(b.part.end))
.or(a.whole.begin.sub(b.whole.begin).or(a.whole.end.sub(b.whole.end))),
),
);
}
/**
* Creates a new pattern with all values parsed as numerals.
* @returns {Pattern}
* @tags internals
*/
asNumber() {
return this.fmap(parseNumeral);
}
//////////////////////////////////////////////////////////////////////
// Context methods - ones that deal with metadata
/**
* Attaches a function that is called for each hap onset.
* @param {Function} onSchedule
* @param {boolean} [dominant]
* @name onSchedule
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("bd sd").onSchedule((hap, time, cps) => {
* console.log('hap scheduled', time, cps);
* })
*/
onSchedule(onSchedule, dominant = true) {
return this.withHap((hap) =>
hap.setContext({
...hap.context,
onSchedule: (scheduleHap, t, cps) => {
// run previously set trigger, if it exists
hap.context.onSchedule?.(scheduleHap, t, cps);
onSchedule(scheduleHap, t, cps);
},
// if dominantSchedule is set to true, the default output (webaudio) will be disabled
// when using multiple triggers, you cannot flip this flag to false again!
// example: x.csound('CooLSynth').log() as well as x.log().csound('CooLSynth') should work the same
dominantSchedule: hap.context.dominantSchedule || dominant,
}),
);
}
/**
* Writes the content of the current event to the console (visible in the side menu).
* @param {Function} [func]
* @param {Function} [getData]
* @tags visualization
* @name log
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("bd sd").log()
*/
log(func = (hap) => `[hap] ${hap.showWhole(true)}`, getData = (hap) => ({ hap })) {
return this.onSchedule((...args) => {
logger(func(...args), undefined, getData(...args));
}, false);
}
/**
* A simplified version of `log` which writes all "values" (various configurable parameters)
* within the event to the console (visible in the side menu).
* @param {Function} func
* @tags visualization
* @name logValues
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("bd sd").gain("0.25 0.5 1").n("2 1 0").logValues()
*/
logValues(func = (value) => `[hap] ${stringifyValues(value, true)}`) {
return this.log((hap) => func(hap.value));
}
//////////////////////////////////////////////////////////////////////
// Visualisation
drawLine() {
console.log(drawLine(this));
return this;
}
//////////////////////////////////////////////////////////////////////
// methods relating to breaking patterns into subcycles
// Breaks a pattern into a pattern of patterns, according to the structure of the given binary pattern.
unjoin(pieces, func = id) {
return pieces.withHap((hap) =>
hap.withValue((v) => (v ? func(this.ribbon(hap.whole.begin, hap.whole.duration)) : this)),
);
}
/**
* Breaks a pattern into pieces according to the structure of a given pattern.
* True values in the given pattern cause the corresponding subcycle of the
* source pattern to be looped, and for an (optional) given function to be
* applied. False values result in the corresponding part of the source pattern
* to be played unchanged.
* @param {Pattern} pieces
* @param {Pattern} func
* @tags temporal
* @name into
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* sound("bd sd ht lt").into("1 0", hurry(2))
*/
into(pieces, func) {
return this.unjoin(pieces, func).innerJoin();
}
}
@@ -1,10 +1,12 @@
/*
pick.mjs - methods that use one pattern to pick events from other patterns.
Copyright (C) 2024 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/signal.mjs>
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/pick.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 { Pattern, reify, silence, register } from './pattern.mjs';
import { Pattern } from './pattern.mjs';
import { reify, silence } from './atoms.mjs';
import { register } from './register.mjs';
import { _mod, clamp, objectMap } from './util.mjs';
@@ -26,12 +28,22 @@ const _pick = function (lookup, pat, modulo = true) {
});
};
export const pick = function (lookup, pat) {
// backward compatibility - the args used to be flipped
if (Array.isArray(pat)) {
[pat, lookup] = [lookup, pat];
}
return __pick(lookup, pat);
};
/** * 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
* @name pick
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* note("<0 1 2!2 3>".pick(["g a", "e f", "f g f g" , "g c d"]))
@@ -46,15 +58,6 @@ const _pick = function (lookup, pat, modulo = true) {
* const pat = sound("bd cp").speed("<2 3>")
* pat.fast("speed".pick(pat))
*/
export const pick = function (lookup, pat) {
// backward compatibility - the args used to be flipped
if (Array.isArray(pat)) {
[pat, lookup] = [lookup, pat];
}
return __pick(lookup, pat);
};
const __pick = register('pick', function (lookup, pat) {
return _pick(lookup, pat, false).innerJoin();
});
@@ -66,9 +69,10 @@ const __pick = register('pick', function (lookup, pat) {
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickmod
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickmod = register('pickmod', function (lookup, pat) {
return _pick(lookup, pat, true).innerJoin();
});
@@ -78,6 +82,8 @@ export const pickmod = register('pickmod', function (lookup, pat) {
* @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
* @name pickF
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("bd [rim hh]").pickF("<0 1 2>", [rev,jux(rev),fast(2)])
@@ -98,6 +104,8 @@ export const pickF = register('pickF', function (pickPattern, lookup, pat) {
* @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
* @name pickmodF
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickmodF = register('pickmodF', function (pickPattern, lookup, pat) {
@@ -108,6 +116,7 @@ export const pickmodF = register('pickmodF', function (pickPattern, lookup, pat)
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* note("<0*4 1 2*2 3*3>".pickOut(["g a", "e f", "f g f g" , "g c d"]))
@@ -121,6 +130,7 @@ export const pickOut = register('pickOut', function (lookup, pat) {
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickmodOut = register('pickmodOut', function (lookup, pat) {
@@ -131,26 +141,30 @@ export const pickmodOut = register('pickmodOut', function (lookup, pat) {
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickRestart
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickRestart = register('pickRestart', function (lookup, pat) {
return _pick(lookup, pat, false).restartJoin();
});
/** * The same as `pickRestart`, but if you pick a number greater than the size of the list,
* it wraps around, rather than sticking at the maximum value.
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @returns {Pattern}
* @example
* "<a@2 b@2 c@2 d@2>".pickRestart({
a: n("0 1 2 0"),
b: n("2 3 4 ~"),
c: n("[4 5] [4 3] 2 0"),
d: n("0 -3 0 ~")
}).scale("C:major").s("piano")
*/
/** The same as `pickRestart`, but if you pick a number greater than the size of the list,
* it wraps around, rather than sticking at the maximum value.
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickmodRestart
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* "<a@2 b@2 c@2 d@2>".pickRestart({
a: n("0 1 2 0"),
b: n("2 3 4 ~"),
c: n("[4 5] [4 3] 2 0"),
d: n("0 -3 0 ~")
}).scale("C:major").s("piano")
*/
export const pickmodRestart = register('pickmodRestart', function (lookup, pat) {
return _pick(lookup, pat, true).restartJoin();
});
@@ -159,6 +173,8 @@ export const pickmodRestart = register('pickmodRestart', function (lookup, pat)
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickReset
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickReset = register('pickReset', function (lookup, pat) {
@@ -170,6 +186,8 @@ export const pickReset = register('pickReset', function (lookup, pat) {
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @name pickmodReset
* @memberof Pattern.prototype
* @returns {Pattern}
*/
export const pickmodReset = register('pickmodReset', function (lookup, pat) {
@@ -183,6 +201,7 @@ export const pickmodReset = register('pickmodReset', function (lookup, pat) {
* @synonyms pickSqueeze
* @param {Pattern} pat
* @param {*} xs
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* let a = s("bd(3,8)")
@@ -206,6 +225,7 @@ export const { inhabit, pickSqueeze } = register(['inhabit', 'pickSqueeze'], fun
* @tags combiners
* @param {Pattern} pat
* @param {*} xs
* @memberof Pattern.prototype
* @returns {Pattern}
*/
+124
View File
@@ -0,0 +1,124 @@
/*
register.mjs - Register is used to dynamically define new extension methods onto the pattern prototype
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/register.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 { isPattern, Pattern } from './pattern.mjs';
import { reify } from './atoms.mjs';
import { sequence } from './composers.mjs';
import { curry } from './util.mjs';
export const strudelScope = {};
/**
* Registers a new pattern method. The method is added to the Pattern class + the standalone function is returned from register.
*
* @tags functional
* @param {string | string[]} name name of the function, or an array of names to be used as synonyms
* @param {Function} func function with 1 or more params, where last is the current pattern
* @param {boolean} [patternify=false] defaults to true; if set to false, you will have more control over the arguments to `func` as they will be
* in their raw form and it will be up to you to patternify them and/or query them for values
* @param {boolean} [preserveSteps=false]
* @param {function(Pattern):Pattern} [join=(x) => x.innerJoin()]
* @returns {object}
* @example
* const vlpf = register('vlpf', (freq, pat) => {
* return pat.fmap((v) => ({...v, cutoff: freq * (v.velocity ?? 1) }));
* })
* s("saw").seg(8).velocity(rand).vlpf(800)
*
*/
export function register(name, func, patternify = true, preserveSteps = false, join = (x) => x.innerJoin()) {
if (isPattern(name)) {
throw new Error(
'Name argument for register is a pattern, try using single quotes (\'name\') instead of double quotes ("name")',
);
}
if (Array.isArray(name)) {
const result = {};
for (const name_item of name) {
result[name_item] = register(name_item, func, patternify, preserveSteps, join);
}
return result;
}
const arity = func.length;
var pfunc; // the patternified function
if (patternify) {
pfunc = function (...args) {
args = args.map(reify);
const pat = args[args.length - 1];
let result;
if (arity === 1) {
result = func(pat);
} else {
const firstArgs = args.slice(0, -1);
if (firstArgs.every((arg) => arg.__pure != undefined)) {
const pureArgs = firstArgs.map((arg) => arg.__pure);
const pureLocs = firstArgs.filter((arg) => arg.__pure_loc).map((arg) => arg.__pure_loc);
result = func(...pureArgs, pat);
result = result.withContext((context) => {
const locations = (context.locations || []).concat(pureLocs);
return { ...context, locations };
});
} else {
const [left, ...right] = firstArgs;
let mapFn = (...args) => {
return func(...args, pat);
};
mapFn = curry(mapFn, null, arity - 1);
result = join(right.reduce((acc, p) => acc.appLeft(p), left.fmap(mapFn)));
}
}
if (preserveSteps) {
result._steps = pat._steps;
}
return result;
};
} else {
pfunc = function (...args) {
args = args.map(reify);
const result = func(...args);
if (preserveSteps) {
result._steps = args[args.length - 1]._steps;
}
return result;
};
}
Pattern.prototype[name] = function (...args) {
// For methods that take a single argument (plus 'this'), allow
// multiple arguments but sequence them
if (arity === 2 && args.length !== 1) {
args = [sequence(...args)];
} else if (arity !== args.length + 1) {
throw new Error(`.${name}() expects ${arity - 1} inputs but got ${args.length}.`);
}
args = args.map(reify);
return pfunc(...args, this);
};
if (arity > 1) {
// There are patternified args, so lets make an unpatternified
// version, prefixed by '_'
Pattern.prototype['_' + name] = function (...args) {
const result = func(...args, this);
if (preserveSteps) {
result.setSteps(this._steps);
}
return result;
};
}
// toplevel functions get curried as well as patternified
// because pfunc uses spread args, we need to state the arity explicitly!
const curried = curry(pfunc, null, arity);
strudelScope[name] = curried;
return curried;
}
@@ -4,20 +4,19 @@ Copyright (C) 2024 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 { Hap } from './hap.mjs';
import { Pattern, fastcat, pure, register, reify, silence, stack, sequenceP, isPattern } from './pattern.mjs';
import { _mod } from './util.mjs';
import Fraction from './fraction.mjs';
import TimeSpan from './timespan.mjs';
import { Hap } from './hap.mjs';
import { Pattern, isPattern } from './pattern.mjs';
import { pure, reify, silence } from './atoms.mjs';
import { fastcat, stack, sequence, sequenceP } from './composers.mjs';
import { register } from './register.mjs';
import { _mod, noteToMidi } from './util.mjs';
import { id, keyAlias, getCurrentKeyboardState } from './util.mjs';
export function steady(value) {
// A continuous value
return new Pattern((state) => [new Hap(undefined, state.span, value)]);
}
/**
* Creates a signal given by the input function
* Creates a "signal", an unstructured pattern consisting of a single value that changes over time.
*
* @name signal
* @param {*} func
@@ -204,27 +203,6 @@ export const itri2 = fastcat(isaw2, saw2);
*/
export const time = signal(id);
/**
* The mouse's x position value ranges from 0 to 1.
* @name mousex
* @synonyms mouseX
* @returns {Pattern}
* @tags external_io
* @example
* n(mousex.segment(4).range(0,7)).scale("C:minor")
*
*/
/**
* The mouse's y position value ranges from 0 to 1.
* @name mousey
* @synonyms mouseY
* @returns {Pattern}
* @tags external_io
* @example
* n(mousey.segment(4).range(0,7)).scale("C:minor")
*
*/
let _mouseY = 0,
_mouseX = 0;
if (typeof window !== 'undefined') {
@@ -235,8 +213,29 @@ if (typeof window !== 'undefined') {
});
}
/**
* The mouse's y position value ranges from 0 to 1.
* @name mousey
* @synonyms mouseY
* @type {Pattern}
* @tags external_io
* @example
* n(mousey.segment(4).range(0,7)).scale("C:minor")
*
*/
export const mousey = signal(() => _mouseY);
export const mouseY = signal(() => _mouseY);
/**
* The mouse's x position value ranges from 0 to 1.
* @name mousex
* @synonyms mouseX
* @type {Pattern}
* @tags external_io
* @example
* n(mousex.segment(4).range(0,7)).scale("C:minor")
*
*/
export const mousex = signal(() => _mouseX);
export const mouseX = signal(() => _mouseX);
@@ -505,6 +504,7 @@ export const withSeed = (func, pat) => {
* @name seed
* @tags math
* @param {number} n A new seed. Can be any number.
* @memberof Pattern.prototype
* @example
* $: s("hh*4").degrade();
* $: s("bd*4").degrade().seed(1); // Will degrade different events from the hi-hat
@@ -627,12 +627,19 @@ export const chooseInWith = (pat, xs) => {
*/
export const choose = (...xs) => chooseWith(rand, xs);
/**
* As with {choose}, but the structure comes from the chosen values, rather
* than the pattern you're using to choose with.
* @param {...any} xs
* @returns {Pattern} - a continuous pattern.
*/
export const chooseIn = (...xs) => chooseInWith(rand, xs);
/**
* Chooses from the given list of values (or patterns of values), according
* to the pattern that the method is called on. The pattern should be in
* the range 0 .. 1.
* @name choose
* @tags temporal
* @param {...any} xs
* @memberof Pattern.prototype
@@ -645,6 +652,7 @@ Pattern.prototype.choose = function (...xs) {
/**
* As with choose, but the pattern that this method is called on should be
* in the range -1 .. 1
* @name choose2
* @tags temporal
* @param {...any} xs
* @memberof Pattern.prototype
@@ -778,12 +786,10 @@ export const perlin = signal((t, controls) => _perlin(t, controls.randSeed));
export const berlin = signal((t, controls) => _berlin(t, controls.randSeed));
/**
* `degradeByWith` is like `degradeBy`, but with control over the random or other signal used to filter out the events.
*
* `degradeByWith` is like `degradeBy`, but with control over the signal used to degrade the pattern.
* It removes events from a pattern given a signal of numbers and a cutoff value for interpreting that pattern as true or false.
* `degradeBy(x)` is essentially `degradeByWith(rand, x)`
*
* This allows you to do things other than with `rand`, see examples below
*
* @name degradeByWith
* @param {Pattern|number} test
* @param {Pattern|number} testAgainst
@@ -1047,7 +1053,6 @@ export const never = register('never', function (_, pat) {
});
/**
*
* Shorthand for `.sometimesBy(1, fn)` (always calls fn)
*
* @tags temporal
@@ -1061,13 +1066,19 @@ export const always = register('always', function (func, pat) {
return func(pat);
});
//keyname: string | Array<string>
//keyname reference: https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
/**
* checks if a key is down
* @param {string | Array<string>} keyname reference: https://developer.mozilla.org/en-US/docs/Web/API/UI_Events/Keyboard_event_key_values
* @returns {boolean}
*/
export function _keyDown(keyname) {
if (Array.isArray(keyname) === false) {
keyname = [keyname];
}
const keyState = getCurrentKeyboardState();
if (keyState === undefined) {
return false;
}
return keyname.every((x) => {
const keyName = keyAlias.get(x) ?? x;
return keyState[keyName];
@@ -1103,7 +1114,6 @@ export const whenKey = register('whenKey', function (input, func, pat) {
* @example
* keyDown("Control:j").pick([s("bd(5,8)"), s("cp(3,8)")])
*/
export const keyDown = register('keyDown', function (pat) {
return pat.fmap(_keyDown);
});
@@ -1116,6 +1126,7 @@ export const keyDown = register('keyDown', function (pat) {
* See also its reciprocal, `per`, also known as `perCycle`.
*
* @tags temporal
* @type {Pattern}
* @example
* // Shorter events are lower in pitch
* sound("saw saw [saw saw] saw")
@@ -1128,14 +1139,34 @@ export const cyclesPer = new Pattern(function (state) {
return [new Hap(undefined, state.span, state.span.duration)];
});
/**
* A pattern measuring the duration of events, in seconds per event.
* `secondsPer` doesn't have structure itself, but takes structue, and therefore
* event durations, from the pattern that it is combined with.
* For example `secondsPer.struct("1 1 [1 1] 1")` with `cps = 1` would give the same as `"0.25 0.25 [0.125 0.125] 0.25"`.
*
* @tags temporal
* @synonyms sper
* @example
* note("f a [c d] e")
* .dec(secondsPer.mul(1))
*/
export const secondsPer = new Pattern(function (state) {
return [new Hap(undefined, state.span, state.span.duration.div(state.controls?._cps ?? 0.5))];
});
export const sper = secondsPer;
/**
* A pattern measuring the 'shortness' of events, or in other words, the duration of pattern events,
* in events per cycle. `per` doesn't have structure itself, but takes structure, and therefore
* event durations, from the pattern that it is combined with.
* For example `per.struct("1 1 [1 1] 1")` would give the same as `"4 4 [8 8] 4"`.
* See also its reciprocal, `cyclesPer`.
* @global
* @tags temporal
* @synonyms perCycle
* @type {Pattern}
* @example
* // Shorter events are more distorted
* n("0 0*2 0 0*2 0 [0 0 0]@2").sound("bd")
@@ -1153,6 +1184,7 @@ export const perCycle = per;
* returned value increases by one. `perx.struct("1 1 [1 [1 1]] 1")` would therefore be
* the same as `"3 3 [4 [5 5]] 3"`.
* @tags temporal
* @type {Pattern}
*/
export const perx = new Pattern(function (state) {
const n = Fraction(1).div(state.span.duration);
@@ -1164,6 +1196,7 @@ export const perx = new Pattern(function (state) {
* Mainly useful in combination with other functions that reset the cycle. See also
* `close`.
* @tags temporal
* @type {Pattern}
* @example
* sound("bd sd [- bd] sd".fast(2))
* .lpf(open.slow(4).range(300,3000)) // close envelope over 4 cycles
@@ -1175,9 +1208,157 @@ 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
* @type {Pattern}
* @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));
/**
* Turns a pattern of numbers into a continuous signal.
* Each number in the pattern specifies the value at its onset, and over the
* duration of the hap, it will linearly transition to the value of the next hap.
*
* Alternatively, the end value of a hap can be specified explicitly using
* array notation, in which case there will be a hard jump from the end value
* of the hap, and the begin value of the next hap.
*
* Similar to other signals like `saw` or `perlin`, this signal should be sampled
* at regular intervals to actually get the desired result.
*
* @name smooth
* @tags generators
* @example
* n(smooth("0 8").seg(16))
* .scale('C major')
* @example
* n(smooth("0:8").seg(8))
* .scale('C major')
* @example
* n("<0 0 0 3 0 4 0 7>*16").scale("e2:phrygian")
* .s("saw").lpf(100).lpq(7)
* .lpenv(smooth("<0 1@3 2 3 5 [8 [3 5] 2]*4@4 2:8 2:8 2:8 8>"))
*
*/
export const smooth = register('smooth', (pat) => {
return new Pattern((state) => {
const haps = pat.query(state);
if (!haps.length) {
return haps;
}
// Find the last hap in the query
const lastHap = haps.reduce((max, hap) => (hap.whole.end.gt(max.whole.end) ? hap : max));
let onsetHaps = [
...haps,
// Because the last hap in our query also needs to transition to the next value,
// we query to find the next hap after the current last hap.
// If that hap is outside of the smooth margin, we simply assume that there is no next hap (e.g. a rest).
...pat.query(state.withSpan((span) => new TimeSpan(lastHap.whole.end, lastHap.whole.end))),
]
// sort by onsets
.sort((a, b) => a.whole.begin.compare(b.whole.begin))
// Make onsets unique
.filter((x, i, arr) => i === arr.length - 1 || x.whole.begin.ne(arr[i + 1].whole.begin));
const newHaps = [];
for (const hap of haps) {
// Find the next onset
const next = onsetHaps.find((onsetHap) => onsetHap.whole.begin.eq(hap.whole.end));
newHaps.push(__smoothHap(state.span.begin, hap, next));
}
return newHaps;
});
});
function __smoothHap(time, hapA, hapB) {
let a, b, context;
if (Array.isArray(hapA.value)) {
// Hap with array notation determines both start and end values.
a = hapA.value[0];
b = hapA.value[1];
context = hapA.context;
} else {
a = hapA.value;
if (hapB === undefined) {
// With no hapB given, we simply copy the value of hapA so the value
// remains the same throughout the hap.
// E.g. smooth("0 1 -") will transition from 0 to 1 and then stay at 1 until the rest.
b = hapA.value;
context = hapA.context;
} else {
// Otherwise, transition to the value at the start of hapB.
b = Array.isArray(hapB.value) ? hapB.value[0] : hapB.value;
context = hapA.combineContext(hapB);
}
}
if (typeof a === 'string') {
a = noteToMidi(a);
}
if (typeof b === 'string') {
b = noteToMidi(b);
}
const progress = time.sub(hapA.whole.begin).div(hapA.whole.end.sub(hapA.whole.begin));
return new Hap(hapA.whole, hapA.part, a + (b - a) * (progress.lt(0) ? 0 : progress), context);
}
/**
* Creates a pattern of numbers in base b from a number or pattern of numbers
* limited to d digits long from the right
*
* @name base
* @tags generators
* @param {number | Pattern | number[]} n - number to convert
* @param {number | Pattern} b - base to convert to (defaults to 10)
* @param {number | Pattern} d - max number of digits to produce for each n (defaults to 0 for all)
* @returns {number | Pattern}
* @example
* $: note(base("7175 543", 10, 3)).scale("c:major").s("saw")
* // $: note("1 7 5 5 4 3").scale("c:major").s("saw")
*/
export const base = (n, b = 10, d = 0) => {
if (Array.isArray(n)) {
n = sequence(n);
}
n = reify(n);
b = reify(b);
d = reify(d);
return d
.withValue((e) => {
return b
.withValue((c) => {
return n
.withValue((v) => {
let digits = [];
let value = v;
while (value > 0) {
digits.unshift(value % c);
value = Math.floor(value / c);
}
if (e) {
const l = digits.length;
if (l > e) {
digits = digits.slice(-1 * e);
}
/*
if (l < e){
for (let i = l; i < e; i++) {
digits.unshift("~");//0); //Would like to be padding this but ~- doesn't work
}
console.log("digits", digits);
}
*/
}
return sequence(digits);
})
.squeezeJoin();
})
.squeezeJoin();
})
.squeezeJoin();
};
+743
View File
@@ -0,0 +1,743 @@
/*
stepwise.mjs - Stepwise pattern functions
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/stepwise.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 Fraction, { lcm } from './fraction.mjs';
import TimeSpan from './timespan.mjs';
import Hap from './hap.mjs';
import { flatten, uniqsortr, pairs, removeUndefineds } from './util.mjs';
import { Pattern, getCalculateSteps } from './pattern.mjs';
import { reify, gap, silence, nothing } from './atoms.mjs';
import { register } from './register.mjs';
import { fastcat, slowcat, stack, sequence } from './composers.mjs';
// Like register, but defaults to stepJoin
export function stepRegister(name, func, patternify = true, preserveSteps = false, join = (x) => x.stepJoin()) {
return register(name, func, patternify, preserveSteps, join);
}
//////////////////////////////////////////////////////////////////////
// Stepwise functions
Pattern.prototype.stepJoin = function () {
const pp = this;
const first_t = stepcat(..._retime(_slices(pp.queryArc(0, 1))))._steps;
const q = function (state) {
const shifted = pp.early(state.span.begin.sam());
const haps = shifted.query(state.setSpan(new TimeSpan(Fraction(0), Fraction(1))));
const pat = stepcat(..._retime(_slices(haps)));
return pat.query(state);
};
return new Pattern(q, first_t);
};
Pattern.prototype.stepBind = function (func) {
return this.fmap(func).stepJoin();
};
export function _retime(timedHaps) {
const occupied_perc = timedHaps.filter((t, pat) => pat.hasSteps).reduce((a, b) => a.add(b), Fraction(0));
const occupied_steps = removeUndefineds(timedHaps.map((t, pat) => pat._steps)).reduce(
(a, b) => a.add(b),
Fraction(0),
);
const total_steps = occupied_perc.eq(0) ? undefined : occupied_steps.div(occupied_perc);
function adjust(dur, pat) {
if (pat._steps === undefined) {
return [dur.mulmaybe(total_steps), pat];
}
return [pat._steps, pat];
}
return timedHaps.map((x) => adjust(...x));
}
export function _slices(haps) {
// slices evs = map (\s -> ((snd s - fst s), stack $ map value $ fit s evs))
// $ pairs $ sort $ nubOrd $ 0:1:concatMap (\ev -> start (part ev):stop (part ev):[]) evs
const breakpoints = flatten(haps.map((hap) => [hap.part.begin, hap.part.end]));
const unique = uniqsortr([Fraction(0), Fraction(1), ...breakpoints]);
const slicespans = pairs(unique);
return slicespans.map((s) => [
s[1].sub(s[0]),
stack(..._fitslice(new TimeSpan(...s), haps).map((x) => x.value.withHap((h) => h.setContext(h.combineContext(x))))),
]);
}
export function _fitslice(span, haps) {
return removeUndefineds(haps.map((hap) => _match(span, hap)));
}
export function _match(span, hap_p) {
const subspan = span.intersection(hap_p.part);
if (subspan == undefined) {
return undefined;
}
return new Hap(hap_p.whole, subspan, hap_p.value, hap_p.context);
}
function _sequenceCount(x) {
if (Array.isArray(x)) {
if (x.length == 0) {
return [silence, 0];
}
if (x.length == 1) {
return _sequenceCount(x[0]);
}
return [fastcat(...x.map((a) => _sequenceCount(a)[0])), x.length];
}
return [reify(x), 1];
}
export function _polymeterListSteps(steps, ...args) {
const seqs = args.map((a) => _sequenceCount(a));
if (seqs.length == 0) {
return silence;
}
if (steps == 0) {
steps = seqs[0][1];
}
const pats = [];
for (const seq of seqs) {
if (seq[1] == 0) {
continue;
}
if (steps == seq[1]) {
pats.push(seq[0]);
} else {
pats.push(seq[0]._fast(Fraction(steps).div(Fraction(seq[1]))));
}
}
return stack(...pats);
}
/**
* *Experimental*
*
* Aligns the steps of the patterns, creating polymeters. The patterns are repeated until they all fit the cycle. For example, in the below the first pattern is repeated twice, and the second is repeated three times, to fit the lowest common multiple of six steps.
* @param {...any} args
* @tags stepwise
* @synonyms pm
* @returns {Pattern}
* @example
* // The same as note("{c eb g, c2 g2}%6")
* polymeter("c eb g", "c2 g2").note()
*
*/
export function polymeter(...args) {
if (Array.isArray(args[0])) {
// Support old behaviour
return _polymeterListSteps(0, ...args);
}
// TODO currently ignoring arguments without steps...
args = args.filter((arg) => arg.hasSteps);
if (args.length == 0) {
return silence;
}
const steps = lcm(...args.map((x) => x._steps));
if (steps.eq(Fraction(0))) {
return nothing;
}
const result = stack(...args.map((x) => x.pace(steps)));
result._steps = steps;
return result;
}
export const pm = polymeter;
/** 'Concatenates' patterns like `fastcat`, but proportional to a number of steps per cycle.
* The steps can either be inferred from the pattern, or provided as a [length, pattern] pair.
* Has the alias `timecat`.
* @global
* @param {...any} timepats
* @name stepcat
* @tags stepwise
* @synonyms timeCat, timecat
* @returns {Pattern}
* @example
* stepcat([3,"e3"],[1, "g3"]).note()
* // the same as "e3@3 g3".note()
* @example
* stepcat("bd sd cp","hh hh").sound()
* // the same as "bd sd cp hh hh".sound()
*/
export function stepcat(...timepats) {
if (timepats.length === 0) {
return nothing;
}
const findsteps = (x) => (Array.isArray(x) ? x : [x._steps ?? 1, x]);
timepats = timepats.map(findsteps);
if (timepats.find((x) => x[0] === undefined)) {
const times = timepats.map((a) => a[0]).filter((x) => x !== undefined);
if (times.length === 0) {
return fastcat(...timepats.map((x) => x[1]));
}
if (times.length === timepats.length) {
return nothing;
}
const avg = times.reduce((a, b) => a.add(b), Fraction(0)).div(times.length);
for (let timepat of timepats) {
if (timepat[0] === undefined) {
timepat[0] = avg;
}
}
}
if (timepats.length == 1) {
const result = reify(timepats[0][1]);
return result.withSteps((_) => timepats[0][0]);
}
const total = timepats.map((a) => a[0]).reduce((a, b) => a.add(b), Fraction(0));
let begin = Fraction(0);
const pats = [];
for (const [time, pat] of timepats) {
if (Fraction(time).eq(0)) {
continue;
}
const end = begin.add(time);
pats.push(reify(pat)._compress(begin.div(total), end.div(total)));
begin = end;
}
const result = stack(...pats);
result._steps = total;
return result;
}
// Aliases for `stepcat`
export const timecat = stepcat;
export const timeCat = stepcat;
/**
* Allows to arrange multiple patterns together over multiple cycles.
* Takes a variable number of arrays with two elements specifying the number of cycles and the pattern to use.
*
* @global
* @param {...any} sections
* @tags combiners
* @returns {Pattern}
* @example
* arrange(
* [4, "<c a f e>(3,8)"],
* [2, "<g a>(5,8)"]
* ).note()
*/
export function arrange(...sections) {
const total = sections.reduce((sum, [cycles]) => sum + cycles, 0);
sections = sections.map(([cycles, section]) => [cycles, section.fast(cycles)]);
return stepcat(...sections).slow(total);
}
function _stackWith(func, pats) {
pats = pats.map((pat) => (Array.isArray(pat) ? sequence(...pat) : reify(pat)));
if (pats.length === 0) {
return silence;
}
if (pats.length === 1) {
return pats[0];
}
const [left, ...right] = pats.map((pat) => pat._steps);
const steps = getCalculateSteps() ? left.maximum(...right) : undefined;
return stack(...func(steps, pats));
}
/**
* The input patterns are aligned to the left, with silence padded to the shorter pattern(s) in the final steps if there's a stepcount disparity. See also `stackRight` and `stackCenter/stackCentre`
*
* @param {...any} pats
* @name stackLeft
* @tags temporal, stepwise, combiners
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackLeft("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackLeft("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackLeft(...pats) {
return _stackWith(
(steps, pats) => pats.map((pat) => (pat._steps.eq(steps) ? pat : stepcat(pat, gap(steps.sub(pat._steps))))),
pats,
);
}
/**
* The input patterns are aligned to the right, with silence padded to the shorter pattern(s) in the initial steps if there's a stepcount disparity. See also `stackLeft` and `stackCenter/stackCentre`
*
* @param {...any} pats
* @name stackRight
* @tags temporal, stepwise, combiners
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackRight("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackRight("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackRight(...pats) {
return _stackWith(
(steps, pats) => pats.map((pat) => (pat._steps.eq(steps) ? pat : stepcat(gap(steps.sub(pat._steps)), pat))),
pats,
);
}
/**
* The input patterns are aligned to the right, with silence padded to the shorter pattern(s) in the initial steps if there's a stepcount disparity. See also `stackLeft` and `stackRight`
* @param {...any} pats
* @name stackCenter
* @tags temporal, stepwise, combiners
* @synonyms stackCentre
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackCenter("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackCenter("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackCenter(...pats) {
return _stackWith(
(steps, pats) =>
pats.map((pat) => {
if (pat._steps.eq(steps)) {
return pat;
}
const g = gap(steps.sub(pat._steps).div(2));
return stepcat(g, pat, g);
}),
pats,
);
}
export function stackCentre(...pats) {
return stackCenter(...pats);
}
/**
* Shorthand for `pm(patterns).pace(m)` where m is the max step count in the input patterns
* @param {...any} pats
* @name stackRepeat
* @tags temporal, stepwise, combiners
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* stackRepeat("0 1 2 3", "3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
* @example
* // chainable
* "0 1 2 3".stackRepeat("3 4", "[4 5 6] 7 8 9 10").scale("c:minor").note()
*/
export function stackRepeat(...pats) {
return stackBy(reify('repeat'), ...pats);
}
export function stackBy(by, ...pats) {
const [left, ...right] = pats.map((pat) => pat._steps);
const steps = left.maximum(...right);
const lookup = {
centre: stackCentre,
left: stackLeft,
right: stackRight,
expand: stack,
repeat: (...args) => polymeter(...args).pace(steps),
};
return by
.inhabit(lookup)
.fmap((func) => func(...pats))
.innerJoin()
.setSteps(steps);
}
/**
* *Experimental*
*
* Speeds a pattern up or down, to fit to the given number of steps per cycle.
* @tags stepwise
* @name pace
* @memberof Pattern.prototype
* @example
* sound("bd sd cp").pace(4)
* // The same as sound("{bd sd cp}%4") or sound("<bd sd cp>*4")
*/
export const pace = register('pace', function (targetSteps, pat) {
if (pat._steps === undefined) {
return pat;
}
if (pat._steps.eq(Fraction(0))) {
// avoid divide by zero..
return nothing;
}
return pat._fast(Fraction(targetSteps).div(pat._steps)).setSteps(targetSteps);
});
/**
* *Experimental*
*
* Concatenates patterns stepwise, according to an inferred 'steps per cycle'.
* Similar to `stepcat`, but if an argument is a list, the whole pattern will alternate between the elements in the list.
*
* @global
* @param {...any} groups
* @tags stepwise
* @returns {Pattern}
* @example
* stepalt(["bd cp", "mt"], "bd").sound()
* // The same as "bd cp bd mt bd".sound()
*/
export function stepalt(...groups) {
groups = groups.map((a) => (Array.isArray(a) ? a.map(reify) : [reify(a)]));
const cycles = lcm(...groups.map((x) => Fraction(x.length)));
let result = [];
for (let cycle = 0; cycle < cycles; ++cycle) {
result.push(...groups.map((x) => (x.length == 0 ? silence : x[cycle % x.length])));
}
result = result.filter((x) => x.hasSteps && x._steps > 0);
const steps = result.reduce((a, b) => a.add(b._steps), Fraction(0));
result = stepcat(...result);
result._steps = steps;
return result;
}
/**
* *Experimental*
*
* Takes the given number of steps from a pattern (dropping the rest).
* A positive number will take steps from the start of a pattern, and a negative number from the end.
* @tags stepwise
* @name take
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* "bd cp ht mt".take("2").sound()
* // The same as "bd cp".sound()
* @example
* "bd cp ht mt".take("1 2 3").sound()
* // The same as "bd bd cp bd cp ht".sound()
* @example
* "bd cp ht mt".take("-1 -2 -3").sound()
* // The same as "mt ht mt cp ht mt".sound()
*/
export const take = stepRegister('take', function (i, pat) {
if (!pat.hasSteps) {
return nothing;
}
if (pat._steps.lte(0)) {
return nothing;
}
i = Fraction(i);
if (i.eq(0)) {
return nothing;
}
const flip = i < 0;
if (flip) {
i = i.abs();
}
const frac = i.div(pat._steps);
if (frac.lte(0)) {
return nothing;
}
if (frac.gte(1)) {
return pat;
}
if (flip) {
return pat.zoom(Fraction(1).sub(frac), 1);
}
return pat.zoom(0, frac);
});
/**
* *Experimental*
*
* Drops the given number of steps from a pattern.
* A positive number will drop steps from the start of a pattern, and a negative number from the end.
* @name drop
* @tags stepwise
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* "tha dhi thom nam".drop("1").sound().bank("mridangam")
* @example
* "tha dhi thom nam".drop("-1").sound().bank("mridangam")
* @example
* "tha dhi thom nam".drop("0 1 2 3").sound().bank("mridangam")
* @example
* "tha dhi thom nam".drop("0 -1 -2 -3").sound().bank("mridangam")
*/
export const drop = stepRegister('drop', function (i, pat) {
if (!pat.hasSteps) {
return nothing;
}
i = Fraction(i);
if (i.lt(0)) {
return pat.take(pat._steps.add(i));
}
return pat.take(Fraction(0).sub(pat._steps.sub(i)));
});
/**
* *Experimental*
*
* `extend` is similar to `fast` in that it increases its density, but it also increases the step count
* accordingly. So `stepcat("a b".extend(2), "c d")` would be the same as `"a b a b c d"`, whereas
* `stepcat("a b".fast(2), "c d")` would be the same as `"[a b] [a b] c d"`.
* @name extend
* @tags stepwise
* @memberof Pattern.prototype
* @example
* stepcat(
* sound("bd bd - <cp hh>").extend(2),
* sound("bd - sd -")
* ).pace(8)
*/
export const extend = stepRegister('extend', function (factor, pat) {
return pat.fast(factor).expand(factor);
});
/**
* *Experimental*
*
* `replicate` is similar to `extend`, except that `replicate` will "replicate" the thing being extended. This will only differ from `extend` when the input pattern differs from cycle to cycle.
*
* @tags stepwise
* @memberof Pattern.prototype
* @example
* stepcat(
* sound("bd bd - <cp hh>").replicate(2),
* sound("bd - sd -")
* ).pace(8)
*/
export const replicate = stepRegister('replicate', function (factor, pat) {
return pat.repeatCycles(factor).fast(factor).expand(factor);
});
/**
* *Experimental*
*
* Expands the step size of the pattern by the given factor.
* @name expand
* @tags stepwise
* @memberof Pattern.prototype
* @example
* sound("tha dhi thom nam").bank("mridangam").expand("3 2 1 1 2 3").pace(8)
*/
export const expand = stepRegister('expand', function (factor, pat) {
return pat.withSteps((t) => t.mul(Fraction(factor)));
});
/**
* *Experimental*
*
* Contracts the step size of the pattern by the given factor. See also `expand`.
* @tags stepwise
* @name contract
* @memberof Pattern.prototype
* @example
* sound("tha dhi thom nam").bank("mridangam").contract("3 2 1 1 2 3").pace(8)
*/
export const contract = stepRegister('contract', function (factor, pat) {
return pat.withSteps((t) => t.div(Fraction(factor)));
});
Pattern.prototype.shrinklist = function (amount) {
const pat = this;
if (!pat.hasSteps) {
return [pat];
}
let [amountv, times] = Array.isArray(amount) ? amount : [amount, pat._steps];
amountv = Fraction(amountv);
if (times === 0 || amountv === 0) {
return [pat];
}
const fromstart = amountv > 0;
const ranges = [];
if (fromstart) {
const seg = Fraction(1).div(pat._steps).mul(amountv);
for (let i = 0; i < times; ++i) {
const s = seg.mul(i);
if (s.gt(1)) {
break;
}
ranges.push([s, 1]);
}
} else {
amountv = Fraction(0).sub(amountv);
const seg = Fraction(1).div(pat._steps).mul(amountv);
for (let i = 0; i < times; ++i) {
const e = Fraction(1).sub(seg.mul(i));
if (e.lt(0)) {
break;
}
ranges.push([Fraction(0), e]);
}
}
return ranges.map((x) => pat.zoom(...x));
};
export const shrinklist = (amount, pat) => pat.shrinklist(amount);
Pattern.prototype.growlist = function (amount) {
return this.shrinklist(amount).reverse();
};
export const growlist = (amount, pat) => pat.growlist(amount);
/**
* *Experimental*
*
* Progressively shrinks the pattern by 'n' steps until there's nothing left, or if a second value is given (using mininotation list syntax with `:`),
* that number of times.
* A positive number will progressively drop steps from the start of a pattern, and a negative number from the end.
* @tags stepwise
* @returns {Pattern}
* @name shrink
* @memberof Pattern.prototype
* @example
* "tha dhi thom nam".shrink("1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".shrink("-1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".shrink("1 -1").sound().bank("mridangam").pace(4)
* @example
* note("0 1 2 3 4 5 6 7".scale("C:ritusen")).sound("folkharp")
* .shrink("1 -1").pace(8)
*
*/
export const shrink = register(
'shrink',
function (amount, pat) {
if (!pat.hasSteps) {
return nothing;
}
const list = pat.shrinklist(amount);
const result = stepcat(...list);
// TODO is this calculation needed?
result._steps = list.reduce((a, b) => a.add(b._steps), Fraction(0));
return result;
},
true,
false,
(x) => x.stepJoin(),
);
/**
* *Experimental*
*
* Progressively grows the pattern by 'n' steps until the full pattern is played, or if a second value is given (using mininotation list syntax with `:`),
* that number of times.
* A positive number will progressively grow steps from the start of a pattern, and a negative number from the end.
* @tags stepwise
* @returns {Pattern}
* @name grow
* @memberof Pattern.prototype
* @example
* "tha dhi thom nam".grow("1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".grow("-1").sound()
* .bank("mridangam")
* @example
* "tha dhi thom nam".grow("1 -1").sound().bank("mridangam").pace(4)
* @example
* note("0 1 2 3 4 5 6 7".scale("C:ritusen")).sound("folkharp")
* .grow("1 -1").pace(8)
*/
export const grow = register(
'grow',
function (amount, pat) {
if (!pat.hasSteps) {
return nothing;
}
const list = pat.shrinklist(Fraction(0).sub(amount));
list.reverse();
const result = stepcat(...list);
// TODO is this calculation needed?
result._steps = list.reduce((a, b) => a.add(b._steps), Fraction(0));
return result;
},
true,
false,
(x) => x.stepJoin(),
);
/**
* *Experimental*
*
* Inserts a pattern into a list of patterns. On the first repetition it will be inserted at the end of the list, then moved backwards through the list
* on successive repetitions. The patterns are added together stepwise, with all repetitions taking place over a single cycle. Using `pace` to set the
* number of steps per cycle is therefore usually recommended.
*
* @param {Pattern} pat
* @param {...any} many
* @tags stepwise
* @returns {Pattern}
* @name tour
* @memberof Pattern.prototype
* @example
* "[c g]".tour("e f", "e f g", "g f e c").note()
* .sound("folkharp")
* .pace(8)
*/
export const tour = function (pat, ...many) {
return pat.tour(...many);
};
Pattern.prototype.tour = function (...many) {
return stepcat(
...[].concat(
...many.map((x, i) => [...many.slice(0, many.length - i), this, ...many.slice(many.length - i)]),
this,
...many,
),
);
};
/**
* *Experimental*
*
* 'zips' together the steps of the provided patterns. This can create a long repetition, taking place over a single, dense cycle.
* Using `pace` to set the number of steps per cycle is therefore usually recommended.
*
* @param {...any} pats
* @global
* @tags stepwise
* @returns {Pattern}
* @example
* zip("e f", "e f g", "g [f e] a f4 c").note()
* .sound("folkharp")
* .pace(8)
*/
export const zip = function (...pats) {
pats = pats.filter((pat) => pat.hasSteps);
const zipped = slowcat(...pats.map((pat) => pat._slow(pat._steps)));
const steps = lcm(...pats.map((x) => x._steps));
return zipped._fast(steps).setSteps(steps);
};
const multiPatternFunctions = {
stackLeft,
stackRight,
stackCenter,
stackCentre,
stackRepeat,
};
for (const [name, func] of Object.entries(multiPatternFunctions)) {
Pattern.prototype[name] = function (...pats) {
return func(this, ...pats);
};
}
@@ -4,7 +4,8 @@ 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 { fastcat, stack, slowcat, silence, pure } from '../pattern.mjs';
import { silence, pure } from '../atoms.mjs';
import { slowcat, fastcat, stack } from '../composers.mjs';
import { describe, it, expect } from 'vitest';
import drawLine from '../drawLine.mjs';
@@ -1,6 +1,6 @@
import { bjorklund } from '../euclid.mjs';
import { describe, expect, it } from 'vitest';
import { fastcat } from '../pattern.mjs';
import { fastcat } from '../composers.mjs';
describe('bjorklund', () => {
it('should apply bjorklundlund to ons and steps', () => {
@@ -52,17 +52,18 @@ import {
stackLeft,
stackRight,
stackCentre,
stackCenter,
stepcat,
steady,
sometimes,
expand,
arp,
} from '../index.mjs';
import { log, logValues, stackCenter } from '../pattern.mjs';
import { reify } from '../atoms.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([
@@ -1189,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)
@@ -1319,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(
@@ -1405,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
@@ -1414,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,
@@ -24,8 +24,9 @@ import {
per,
perx,
cyclesPer,
smooth,
} from '../signal.mjs';
import { fastcat, sequence, State, TimeSpan, Hap, note } from '../index.mjs';
import { fastcat, sequence, State, TimeSpan, Hap, seq, pure, silence } from '../index.mjs';
const st = (begin, end) => new State(ts(begin, end));
const ts = (begin, end) => new TimeSpan(Fraction(begin), Fraction(end));
@@ -122,6 +123,21 @@ 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());
});
});
describe('smooth', () => {
it('"0 1" equals a tri wave', () => {
sameFirst(smooth(fastcat(0, 1)).seg(64), tri.seg(64));
});
it('"0:1" equals a saw wave', () => {
sameFirst(smooth(pure([0, 1])).seg(64), saw.seg(64));
});
it('supports rests', () => {
sameFirst(smooth(fastcat(0, 1, silence)).seg(64), fastcat(saw, 1, silence).seg(64));
});
it('supports notes', () => {
sameFirst(smooth(fastcat('c2', 'c3')).seg(64), fastcat(tri.range(36, 48)).seg(64));
});
});
@@ -4,7 +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 { pure } from '../pattern.mjs';
import { pure } from '../atoms.mjs';
import {
_mod,
compose,
@@ -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', () => {
File diff suppressed because it is too large Load Diff
@@ -212,6 +212,11 @@ export function curry(func, overload, arity = func.length) {
return fn;
}
/**
* parses a number. supports midi notes as strings
* @param {number | string} numOrString
* @returns {number}
*/
export function parseNumeral(numOrString) {
const asNumber = Number(numOrString);
if (!isNaN(asNumber)) {
@@ -223,10 +228,20 @@ export function parseNumeral(numOrString) {
throw new Error(`cannot parse as numeral: "${numOrString}"`);
}
/**
* map over the arguments of a function
* @param {Function} fn
* @param {Function} mapFn
* @returns {Function}
*/
export function mapArgs(fn, mapFn) {
return (...args) => fn(...args.map(mapFn));
}
/** converts the arguments of a function into numbers
* @param {Function} fn
* @returns {Function}
*/
export function numeralArgs(fn) {
return mapArgs(fn, parseNumeral);
}
@@ -328,7 +343,12 @@ export const sol2note = (n, notation = 'letters') => {
return note + oct;
};
// Remove duplicates from list
/**
* Remove duplicates from list
* @template T
* @param {T[]} a
* @returns {T[]}
*/
export function uniq(a) {
var seen = {};
return a.filter(function (item) {
@@ -336,14 +356,26 @@ export function uniq(a) {
});
}
// Remove duplicates from list, sorting in the process. Mutates argument!
/**
* Remove duplicate primitives from list, sorting in the process. Mutates argument!
* Use {@link uniqsortr} for objects instead.
* @template T
* @param {T[]} a (only primitives)
* @returns {T[]}
*/
export function uniqsort(a) {
return a.sort().filter(function (item, pos, ary) {
return !pos || item != ary[pos - 1];
});
}
// rational version
/**
* Remove duplicate objects from list, sorting in the process. Mutates argument!
* Use {@link uniqsort} for primitives instead.
* @template T
* @param {T[]} a (only objects)
* @returns {T[]}
*/
export function uniqsortr(a) {
return a
.sort((x, y) => x.compare(y))
@@ -375,22 +407,47 @@ export function base64ToUnicode(base64String) {
return decodedText;
}
/**
* converts unicode text into a URL hash
* @ignore
* @param {string} code
* @returns {string}
*/
export function code2hash(code) {
return encodeURIComponent(unicodeToBase64(code));
//return '#' + encodeURIComponent(btoa(code));
}
/**
* converts the URL hash into unicode text
* @ignore
* @param {string} hash
* @returns {string}
*/
export function hash2code(hash) {
return base64ToUnicode(decodeURIComponent(hash));
//return atob(decodeURIComponent(codeParam || ''));
}
/**
* maps over the entries of an object
* @param {object} obj
* @param {Function} fn
* @returns {object}
*/
export function objectMap(obj, fn) {
if (Array.isArray(obj)) {
return obj.map(fn);
}
return Object.fromEntries(Object.entries(obj).map(([k, v], i) => [k, fn(v, k, i)]));
}
/**
* converts the cycle into seconds
* @param {number} cycle
* @param {number} cps
* @returns {number} `cycle / cps`
*/
export function cycleToSeconds(cycle, cps) {
return cycle / cps;
}
@@ -454,6 +511,10 @@ export class ClockCollator {
}
}
/**
* The total time that strudel has been running
* @returns {number}
*/
export function getPerformanceTimeSeconds() {
return performance.now() * 0.001;
}
@@ -474,21 +535,24 @@ export const keyAlias = new Map([
]);
let keyState;
/**
* returns the all the keys currently being pressed or released
* @returns {object | void}
*/
export function getCurrentKeyboardState() {
if (keyState == null) {
if (typeof window === 'undefined') {
return;
}
keyState = {};
// Listen for the keydown event to mark the key as pressed
window.addEventListener('keydown', (event) => {
keyState[event.key] = true; // Mark the key as pressed
});
if (typeof window !== 'undefined') {
// Listen for the keydown event to mark the key as pressed
window.addEventListener('keydown', (event) => {
keyState[event.key] = true; // Mark the key as pressed
});
// Listen for the keyup event to mark the key as released
window.addEventListener('keyup', (event) => {
keyState[event.key] = false; // Mark the key as released
});
// Listen for the keyup event to mark the key as released
window.addEventListener('keyup', (event) => {
keyState[event.key] = false; // Mark the key as released
});
}
}
return { ...keyState }; // Return a shallow copy of the key state object
@@ -514,8 +578,13 @@ export function getCurrentKeyboardState() {
// return lcm((x * y) / gcd(x, y), ...z);
// };
// Takes values -- typically derived from events, i.e. `hap`s -- and renders them
// into a readable format
/**
* Takes values -- typically derived from events, i.e. `hap`s -- and renders them
* into a readable format
* @param {*} value
* @param {boolean} [compact=false] creates a compacter version
* @returns {boolean}
*/
export function stringifyValues(value, compact = false) {
return typeof value === 'object'
? compact
@@ -7,6 +7,12 @@ This program is free software: you can redistribute it and/or modify it under th
import { curry } from './util.mjs';
import { logger } from './logger.mjs';
/** combine two objects into one
* @param {object} a
* @param {object} b
* @param {Function} func
* @returns {object}
*/
export function unionWithObj(a, b, func) {
if (b?.value !== undefined && Object.keys(b).length === 1) {
// https://codeberg.org/uzu/strudel/issues/1026
+145
View File
@@ -0,0 +1,145 @@
/*
values.mjs - Functions that alter the values of patterns, but not their structure.
Copyright (C) 2026 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/values.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 { register } from './register.mjs';
//////////////////////////////////////////////////////////////////////
// Numerical transformations
/**
* Assumes a numerical pattern. Returns a new pattern with all values rounded
* to the nearest integer.
* @name round
* @tags math
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* n("0.5 1.5 2.5".round()).scale("C:major")
*/
export const round = register('round', function (pat) {
return pat.asNumber().fmap((v) => Math.round(v));
});
/**
* Assumes a numerical pattern. Returns a new pattern with all values set to
* their mathematical floor. E.g. `3.7` replaced with to `3`, and `-4.2`
* replaced with `-5`.
* @name floor
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* note("42 42.1 42.5 43".floor())
*/
export const floor = register('floor', function (pat) {
return pat.asNumber().fmap((v) => Math.floor(v));
});
export const log2 = register('log2', (pat) => pat.asNumber().fmap((v) => Math.log2(v)));
/**
* Assumes a numerical pattern. Returns a new pattern with all values set to
* their mathematical ceiling. E.g. `3.2` replaced with `4`, and `-4.2`
* replaced with `-4`.
* @name ceil
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* note("42 42.1 42.5 43".ceil())
*/
export const ceil = register('ceil', function (pat) {
return pat.asNumber().fmap((v) => Math.ceil(v));
});
/**
* Assumes a numerical pattern, containing unipolar values in the range 0 ..
* 1. Returns a new pattern with values scaled to the bipolar range -1 .. 1
* @tags math
* @returns {Pattern}
* @noAutocomplete
* @memberof Pattern.prototype
*/
export const toBipolar = register('toBipolar', function (pat) {
return pat.fmap((x) => x * 2 - 1);
});
/**
* Assumes a numerical pattern, containing bipolar values in the range -1 .. 1
* Returns a new pattern with values scaled to the unipolar range 0 .. 1
* @tags math
* @returns {Pattern}
* @noAutocomplete
* @memberof Pattern.prototype
*/
export const fromBipolar = register('fromBipolar', function (pat) {
return pat.fmap((x) => (x + 1) / 2);
});
/**
* Assumes a numerical pattern, containing unipolar values in the range 0 .. 1.
* Returns a new pattern with values scaled to the given min/max range.
* Most useful in combination with continuous patterns.
* @name range
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* s("[bd sd]*2,hh*8")
* .cutoff(sine.range(500,4000))
*/
export const range = register('range', function (min, max, pat) {
return pat.mul(max - min).add(min);
});
/**
* Assumes a numerical pattern, containing unipolar values in the range 0 .. 1
* Returns a new pattern with values scaled to the given min/max range,
* following an exponential curve.
* @name rangex
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* s("[bd sd]*2,hh*8")
* .cutoff(sine.rangex(500,4000))
*/
export const rangex = register('rangex', function (min, max, pat) {
return pat._range(Math.log(min), Math.log(max)).fmap(Math.exp);
});
/**
* Assumes a numerical pattern, containing bipolar values in the range -1 .. 1
* Returns a new pattern with values scaled to the given min/max range.
* @name range2
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* s("[bd sd]*2,hh*8")
* .cutoff(sine2.range2(500,4000))
*/
export const range2 = register('range2', function (min, max, pat) {
return pat.fromBipolar()._range(min, max);
});
/**
* Allows dividing numbers via list notation using ":".
* Returns a new pattern with just numbers.
* @name ratio
* @memberof Pattern.prototype
* @tags math
* @returns {Pattern}
* @example
* ratio("1, 5:4, 3:2").mul(110)
* .freq().s("piano")
*/
export const ratio = register('ratio', (pat) =>
pat.fmap((v) => {
if (!Array.isArray(v)) {
return v;
}
return v.slice(1).reduce((acc, n) => acc / n, v[0]);
}),
);
+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',
},
});
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/repl",
"version": "1.3.0",
"version": "1.4.0",
"description": "Strudel REPL as a Web Component",
"module": "index.mjs",
"publishConfig": {
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/sampler",
"version": "0.2.4",
"version": "0.3.0",
"description": "",
"keywords": [
"tidalcycles",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/serial",
"version": "1.2.6",
"version": "1.3.0",
"description": "Webserial API for strudel",
"main": "serial.mjs",
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/soundfonts",
"version": "1.3.0",
"version": "1.4.0",
"description": "Soundsfont support for strudel",
"main": "index.mjs",
"publishConfig": {
+2 -1
View File
@@ -442,7 +442,8 @@ export function applyFM(param, value, begin) {
} else {
control = `fmi${i}${j}`;
}
const amt = value[control];
// If we can't find fm3/fm2/fm1/etc, fall back to fm32/fm21/fm10/etc
const amt = value[control] ?? (i === j + 1 ? value[`fmi${i}${j}`] : undefined);
if (!amt) continue;
let io = [];
for (let [isMod, idx] of [
+1 -3
View File
@@ -1,6 +1,6 @@
{
"name": "superdough",
"version": "1.3.0",
"version": "1.4.0",
"description": "simple web audio synth and sampler intended for live coding. inspired by superdirt and webdirt.",
"main": "index.mjs",
"type": "module",
@@ -36,8 +36,6 @@
"vite-plugin-bundle-audioworklet": "workspace:*"
},
"dependencies": {
"@kabelsalat/lib": "^0.4.1",
"@kabelsalat/web": "^0.4.1",
"nanostores": "^0.11.3"
},
"engines": {
+21 -1
View File
@@ -35,7 +35,7 @@ function humanFileSize(bytes, si) {
* Has optional param `n` (for instance, the `2` in `s("casio:2")`)
*
* Note: `must` be called with await, otherwise you'll get a pending Promise object.
*
* @global
* @name getDuration
* @synonyms getDur
* @tags samples
@@ -260,6 +260,7 @@ export async function fetchSampleMap(url) {
/**
* Loads a collection of samples to use with `s`
* @tags samples
* @global
* @example
* samples('github:tidalcycles/dirt-samples');
* s("[bd ~]*2, [~ hh]*2, ~ sd")
@@ -288,12 +289,14 @@ export const samples = async (sampleMap, baseUrl = sampleMap._base || '', option
};
const cutGroups = [];
const scutGroups = [];
export async function onTriggerSample(t, value, onended, bank, resolveUrl) {
let {
s,
nudge = 0, // TODO: is this in seconds?
cut,
scut,
loop,
clip = undefined, // if set, samples will be cut off when the hap ends
n = 0,
@@ -372,6 +375,23 @@ export async function onTriggerSample(t, value, onended, bank, resolveUrl) {
cutGroups[cut] = handle;
}
// scut groups
if (scut !== undefined) {
if (scutGroups[scut] === undefined) {
scutGroups[scut] = { t, handles: [] };
}
const prevGroup = scutGroups[scut];
if (prevGroup.t !== t) {
for (const prev of prevGroup.handles) {
prev.node.gain.setValueAtTime(1, time);
prev.node.gain.linearRampToValueAtTime(0, time + 0.01);
}
scutGroups[scut] = { t, handles: [] };
}
scutGroups[scut].handles.push(handle);
}
return handle;
}
+25 -31
View File
@@ -16,7 +16,6 @@ import {
gainNode,
getCompressor,
getDistortion,
getFrequencyFromValue,
getLfo,
getWorklet,
releaseAudioNode,
@@ -40,6 +39,7 @@ export let maxPolyphony = DEFAULT_MAX_POLYPHONY;
* start to die out in first-in-first-out order once the max polyphony has been hit
*
* @name setMaxPolyphony
* @global
* @tags superdough
* @param {number} polyphony Max polyphony. Defaults to 128
* @example
@@ -63,6 +63,11 @@ export function registerSound(key, onTrigger, data = {}) {
soundMap.setKey(key, { onTrigger, data });
}
const chainEffects = {};
export function registerChainEffect(name, effect) {
chainEffects[name] = effect;
}
let gainCurveFunc = (val) => val;
export function applyGainCurve(val) {
@@ -72,7 +77,7 @@ export function applyGainCurve(val) {
/**
* Apply a function to all gains provided in patterns. Can be used to rescale gain to be
* quadratic, exponential, etc. rather than linear
*
* @global
* @name setGainCurve
* @tags amplitude, superdough
* @param {Function} newGainCurveFunc function to apply to all gain values
@@ -126,9 +131,10 @@ async function aliasBankPath(path) {
/**
* Register an alias for a bank of sounds.
* @global
* @param {...any} args either one or two arguments. first argument is bank to alias. Second argument is alias to use for the bank.
* 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 {...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
*/
@@ -149,6 +155,7 @@ export async function aliasBank(...args) {
/**
* Register an alias for a sound.
* @global
* @tags samples
* @param {string} original - The original sound name
* @param {string} alias - The alias to use for the sound
@@ -259,14 +266,6 @@ export function loadWorklets() {
return workletsLoading;
}
let kabel;
async function initKabelsalat() {
const { SalatRepl } = await import('@kabelsalat/web');
logger('[kabelsalat] ready');
kabel = new SalatRepl({ localScope: true });
return kabel;
}
// this function should be called on first user interaction (to avoid console warning)
export async function initAudio(options = {}) {
const {
@@ -313,7 +312,6 @@ export async function initAudio(options = {}) {
} catch (err) {
console.warn('could not load AudioWorklet effects', err);
}
await initKabelsalat();
logger('[superdough] ready');
}
let audioReady;
@@ -449,14 +447,6 @@ class Chain {
}
}
const compileKabel = (code) => {
if (!kabel) {
throw new Error('kabelsalat not loaded');
}
const node = kabel.evaluate(code);
return node.compile({ log: false });
};
export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5) => {
// mapping from main FX and numbered FX chains to nodes
const nodes = { main: {} };
@@ -632,17 +622,21 @@ export const superdough = async (value, t, hapDuration, cps = 0.5, cycle = 0.5)
gain *= velocity; // velocity currently only multiplies with gain. it might do other things in the future
delaytime = delaytime ?? cycleToSeconds(delaysync, cps);
// Kabelsalat
if (fx.workletSrc !== undefined) {
const workletNode = getWorklet(ac, 'generic-processor', {}, { outputChannelCount: [2] });
chain.connect(workletNode);
const workletSrc = fx.workletSrc
.replace(/\bpat\[(\d+)\]/g, (_, i) => fx.workletInputs[i])
.replaceAll('sFreq', getFrequencyFromValue(value))
.replaceAll('sGate', `cc('strudel-gate-${chainID}')`);
/* global compileKabel */
const { src, ugens, registers } = compileKabel(workletSrc);
workletNode.port.postMessage({ src, schema: { ugens, registers }, start: t, gateEnd: end, end: endWithRelease });
// custom chain effect sink (used for kabelsalat)
for (let key in chainEffects) {
const effect = chainEffects[key];
if (fx[key] !== undefined) {
const node = effect({
audioContext: ac,
fx,
chainID,
value,
start: t,
gateEnd: end,
releaseEnd: endWithRelease,
});
node && chain.connect(node);
}
}
if (fx.stretch !== undefined) {
+83
View File
@@ -404,6 +404,89 @@ export function registerSynthSounds() {
{ prebake: true, type: 'input' },
);
registerSound(
'goabd',
(t, value, onended) => {
const {
duration,
attack = 0,
hold = 0.2,
decay = 0.25,
sustain = 0,
release = 0,
pdecay = 1,
penv = 84,
pcurve = 0.85,
clip,
} = value;
const ctx = getAudioContext();
const soundGain = 0.5;
const mixGain = 1;
const freq = getFrequencyFromValue(value, 24);
const f = getWorklet(ctx, 'goabd-freq-env-processor', {
begin: t,
end: t + pdecay,
freq0: freq * Math.pow(2, penv / 12),
freq1: freq,
pcurve: pcurve,
});
const o = ctx.createOscillator();
o.type = 'sine';
o.frequency.value = 0;
f.connect(o.frequency);
const g = gainNode(soundGain);
let soundDuration = attack + hold + decay;
if (sustain > 0) {
soundDuration = Math.max(soundDuration, duration) + release;
}
if (attack > 0) {
g.gain.setValueAtTime(0.0001, t);
g.gain.exponentialRampToValueAtTime(soundGain, t + attack);
} else {
g.gain.setValueAtTime(soundGain, t);
}
if (hold > 0) {
g.gain.setValueAtTime(soundGain, t + attack + hold);
}
g.gain.exponentialRampToValueAtTime(Math.max(0.0001, sustain), t + soundDuration - release);
g.gain.exponentialRampToValueAtTime(0.0001, t + soundDuration);
o.start(t);
const mix = gainNode(mixGain);
onceEnded(o, () => {
releaseAudioNode(f);
releaseAudioNode(o);
releaseAudioNode(g);
releaseAudioNode(mix);
onended();
});
const node = o.connect(g).connect(mix);
// prevent clicking
let mixDuration = soundDuration;
if (clip != null) {
mixDuration = Math.min(clip * duration, mixDuration);
}
const mixEnd = t + mixDuration;
mix.gain.setValueAtTime(mixGain, mixEnd - 0.01);
mix.gain.linearRampToValueAtTime(0, mixEnd);
o.stop(mixEnd);
return {
node,
nodes: { source: [o] },
stop: (endTime) => {
o.stop(endTime);
},
};
},
{ type: 'synth', prebake: true },
);
[...noises].forEach((s) => {
registerSound(
s,
+1
View File
@@ -111,6 +111,7 @@ export function getCommonSampleInfo(hapValue, bank) {
}
/** Selects entries from `source` and renames them via `map`
* @global
* @tags internals
* @param {object} source
* @param {*} map
+1 -1
View File
@@ -184,7 +184,7 @@ export function registerWaveTable(key, tables, params) {
/**
* Loads a collection of wavetables to use with `s`
*
* @global
* @param {string} url
* @param {*} frameLen
* @param {string} json
+45 -81
View File
@@ -5,9 +5,6 @@
import OLAProcessor from './ola-processor';
import FFT from './fft.js';
import { getDistortionAlgorithm } from './helpers.mjs';
import * as ugens from '@kabelsalat/lib/src/ugens.js';
const UGENS = new Map(Object.entries(ugens));
const blockSize = 128;
const PI = Math.PI;
@@ -853,6 +850,8 @@ registerProcessor('pulse-oscillator', PulseOscillatorProcessor);
/** BYTE BEATS
* @tags internals
* @global
* @typedef Chyx
*/
const chyx = {
/*bit*/ bitC: function (x, y, z) {
@@ -986,6 +985,49 @@ class ByteBeatProcessor extends AudioWorkletProcessor {
registerProcessor('byte-beat-processor', ByteBeatProcessor);
class GoaBdFreqEnvProcessor extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [
{ name: 'begin', defaultValue: 0 },
{ name: 'end', defaultValue: 0 },
{ name: 'freq0', defaultValue: 55 * 64 },
{ name: 'freq1', defaultValue: 55 },
{ name: 'pcurve', defaultValue: 0.5 },
];
}
constructor() {
super();
this.p0 = 0.006699687;
this.p1 = 0.00001884606;
this.time = 0;
}
process(_inputs, outputs, params) {
const begin = params['begin'][0];
const end = params['end'][0];
if (currentTime >= end) {
return false;
}
if (currentTime <= begin) {
return true;
}
const out = outputs[0][0];
const freq0 = params['freq0'][0];
const freq1 = params['freq1'][0];
const pcurve = params['pcurve'][0];
const p = (1 - pcurve) * this.p0 + pcurve * this.p1;
const dt = (INVSR * 1) / (end - begin);
for (let i = 0; i < out.length; i++) {
out[i] = freq1 + (freq0 - freq1) / (1 + this.time / p);
this.time += dt;
}
return true;
}
}
registerProcessor('goabd-freq-env-processor', GoaBdFreqEnvProcessor);
class EnvelopeProcessor extends AudioWorkletProcessor {
static get parameterDescriptors() {
return [
@@ -1494,81 +1536,3 @@ class TransientProcessor extends AudioWorkletProcessor {
}
registerProcessor('transient-processor', TransientProcessor);
class GenericProcessor extends AudioWorkletProcessor {
constructor() {
super();
this.playPos = 0;
const channels = 16;
this.outputs = new Array(channels).fill(0);
this.sources = new Array(channels).fill(0);
this.gateEnded = false;
this.started = false;
this.port.onmessage = (event) => {
let {
src,
schema: { ugens, registers },
start,
gateEnd,
end,
} = event.data;
this.start = start;
this.gateEnd = gateEnd;
this.end = end;
this.registers = new Array(registers).fill(0);
this.src = `o.fill(0); // reset outputs\n${src}`;
this.nodes = [];
for (let i = 0; i < ugens.length; i++) {
const ugen = ugens[i];
const nodeClass = UGENS.get(ugen.type);
const node = new nodeClass(i, ugen, sampleRate);
if (node.type === 'cc' && ugen.inputs?.[0]?.includes('strudel-gate')) {
node.setValue(1);
this.gateNode = node;
}
this.nodes[i] = node;
}
this.genSample = new Function(
'time',
'nodes',
'input',
'r', // registers
'o', // outputs
's', // sources
this.src,
);
};
}
process(inputs, outputs) {
const input = inputs[0]?.[0];
if (currentTime >= this.end) {
return false;
} else if (this.genSample === undefined || currentTime < this.start) {
// pending
return true;
}
this.started = true;
if (!this.gateEnded && currentTime > this.gateEnd) {
this.gateNode?.setValue(0);
this.gateEnded = true;
}
const output = outputs[0];
const outL = output[0];
const outR = output[1];
for (let n = 0; n < blockSize; n++) {
this.genSample(this.playPos, this.nodes, input ? input[n] : 0, this.registers, this.outputs, this.sources);
const left = this.outputs[0];
const right = this.outputs[1];
// Spread to stereo if possible; else mixdown to mono
if (outR) {
outL[n] = left;
outR[n] = right;
} else {
outL[n] = 0.5 * (left + right);
}
this.playPos += 1 / sampleRate;
}
return true;
}
}
registerProcessor('generic-processor', GenericProcessor);
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/tonal",
"version": "1.2.6",
"version": "1.3.0",
"description": "Tonal functions for strudel",
"main": "index.mjs",
"publishConfig": {
+1
View File
@@ -196,6 +196,7 @@ export const rootNotes = register('rootNotes', function (octave, pat) {
* @name voicing
* @tags tonal
* @returns {Pattern}
* @memberof Pattern.prototype
* @example
* n("0 1 2 3").chord("<C Am F G>").voicing()
*/
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/transpiler",
"version": "1.2.6",
"version": "1.3.0",
"description": "Transpiler for strudel user code. Converts syntactically correct but semantically meaningless JS into evaluatable strudel code.",
"main": "index.mjs",
"type": "module",
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/web",
"version": "1.3.0",
"version": "1.4.0",
"description": "Easy to setup, opiniated bundle of Strudel for the browser.",
"module": "web.mjs",
"publishConfig": {
+37 -3
View File
@@ -12,7 +12,10 @@ import { initAudioOnFirstClick, registerSynthSounds, webaudioRepl } from '@strud
import { evaluate as _evaluate, transpiler } from '@strudel/transpiler';
import { miniAllStrings } from '@strudel/mini';
// init logic
/**
* init logic
* @global
*/
export async function defaultPrebake() {
const loadModules = evalScope(
evalScope,
@@ -30,6 +33,28 @@ export async function defaultPrebake() {
let initDone;
let repl;
/** initiates strudel
* @global
* @param {object} options
* @param {*} options.onSchedule
* @param {*} options.defaultOutput
* @param {*} options.onEvalError
* @param {*} options.beforeEval
* @param {*} options.beforeStart
* @param {*} options.afterEval
* @param {*} options.getTime
* @param {*} options.transpiler
* @param {*} options.onToggle
* @param {*} options.editPattern
* @param {*} options.onUpdateState
* @param {*} options.sync = false
* @param {*} options.setInterval
* @param {*} options.clearInterval
* @param {*} options.id
* @param {*} options.mondo = false
* @param {*} options.prebake
* @returns {object}
*/
export function initStrudel(options = {}) {
initAudioOnFirstClick();
options.miniAllStrings !== false && miniAllStrings();
@@ -58,12 +83,21 @@ Pattern.prototype.play = function () {
return this;
};
// stop playback
/**
* stop playback
* @global
*/
export function hush() {
repl.stop();
}
// evaluate and play the given code using the transpiler
/**
* evaluate and play the given code using the transpiler
* @global
* @param {*} code
* @param {*} autoplay
* @returns {*}
*/
export async function evaluate(code, autoplay = true) {
return repl.evaluate(code, autoplay);
}
+4 -2
View File
@@ -1,6 +1,6 @@
{
"name": "@strudel/webaudio",
"version": "1.3.0",
"version": "1.4.0",
"description": "Web Audio helpers for Strudel",
"main": "index.mjs",
"type": "module",
@@ -35,10 +35,12 @@
"dependencies": {
"@strudel/core": "workspace:*",
"@strudel/draw": "workspace:*",
"@strudel/pattern": "workspace:*",
"superdough": "workspace:*"
},
"devDependencies": {
"vite": "^6.0.11"
"vite": "^6.0.11",
"vitest": "^3.0.4"
},
"engines": {
"node": ">=18.0.0"

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