mirror of
https://codeberg.org/uzu/strudel
synced 2026-07-14 14:53:45 -04:00
Compare commits
391 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 185abf1fc1 | |||
| 37efdd9ce1 | |||
| f4039d3666 | |||
| 7000a4cead | |||
| 5aa983b45b | |||
| 800989419b | |||
| 362679954a | |||
| 2732d64beb | |||
| 88684d6d9e | |||
| 9afddf0850 | |||
| a2d7d6e81f | |||
| 49bcb5e19f | |||
| 3744ea6218 | |||
| b2c6d87633 | |||
| e4f538b674 | |||
| ea0e0b4396 | |||
| 1ac784dc7a | |||
| d980c9ca4c | |||
| c0d6e36113 | |||
| 6a2a60df0d | |||
| ee9b89b6d5 | |||
| 8261802078 | |||
| 68cc109933 | |||
| 1015bb0fdc | |||
| 7da94dd109 | |||
| 171808cf2c | |||
| 78d14cdfea | |||
| 19982a2ffb | |||
| 79904560fc | |||
| 28aee1c58d | |||
| d4512f360b | |||
| 48d0ffe868 | |||
| 62af12f3b9 | |||
| efa4bfef2f | |||
| fc3ead4c01 | |||
| ca9c813b40 | |||
| e3b0f47c40 | |||
| bf13e42092 | |||
| 4345fda9bc | |||
| 4059e9faa9 | |||
| 95fcce1bcf | |||
| 86cde9716a | |||
| 6e315a50ed | |||
| 6dda6bac66 | |||
| 500c0b6534 | |||
| db75dca118 | |||
| d5ab1a3471 | |||
| d5f37e2cbe | |||
| a120a9895b | |||
| e9c1db020f | |||
| ded90733f6 | |||
| c64485db99 | |||
| 08cd319a0b | |||
| 896ec69329 | |||
| afa5d6e704 | |||
| bde7e79a38 | |||
| 32e64bbb6e | |||
| 0974540e5f | |||
| e06963e616 | |||
| a675815529 | |||
| 3d48135b32 | |||
| 8f09e7f097 | |||
| e8b09f1124 | |||
| 57ba353594 | |||
| b695e090cd | |||
| 69ecb7b54f | |||
| f57fe182ed | |||
| 10ee11c886 | |||
| 45842b1f05 | |||
| 9ca5f9ad48 | |||
| bb00036a30 | |||
| 4a2a540500 | |||
| 09217216dc | |||
| 22a64c4931 | |||
| 93f520b941 | |||
| c84714dc3a | |||
| a7aa09a13e | |||
| efa1cdfcb2 | |||
| 70695daae8 | |||
| 62fdba0600 | |||
| 5733e00908 | |||
| e56abaefd7 | |||
| c71e893e8e | |||
| 3992356517 | |||
| dbb84ef129 | |||
| 8781fa2e33 | |||
| 605a1365d3 | |||
| ebb1bbc966 | |||
| d4518f7a6e | |||
| 68c9008019 | |||
| cafde1e910 | |||
| 41f5f3fe6e | |||
| cf12ecfa34 | |||
| 4fa668927f | |||
| 24d2b5b4bd | |||
| 4da2e003e1 | |||
| 205debde9c | |||
| ba6c7b0901 | |||
| 8e5d02fd25 | |||
| 11d3251c67 | |||
| 9ec5787b4d | |||
| 027c669ad7 | |||
| 405c12ba3f | |||
| 64fd53a8e5 | |||
| 069d63e3cf | |||
| 66049e0e25 | |||
| db7ef01dbb | |||
| 1a6b649fd6 | |||
| 548619775e | |||
| 4b79a75f39 | |||
| 28912fff97 | |||
| 98a83ddcc0 | |||
| e9d965ce7a | |||
| b7624813cc | |||
| 734e451bd9 | |||
| 7a96436085 | |||
| 670af8fb1b | |||
| 0abd062e5c | |||
| 1286468d5a | |||
| 0f3da5be4a | |||
| 9170269e06 | |||
| 8bb460701f | |||
| c0a7173ca4 | |||
| 949e15d8c6 | |||
| 0caedeb481 | |||
| 83ca8d95be | |||
| 8483868783 | |||
| 6961388545 | |||
| 8ef1ae5202 | |||
| 26b8f93cea | |||
| a576523976 | |||
| cf21c4085b | |||
| 204f655d6d | |||
| fb14865785 | |||
| 5cd052cc59 | |||
| af49c4117c | |||
| dd736130a0 | |||
| cee8bda676 | |||
| 6420a72ceb | |||
| 380e7c7899 | |||
| 16b4058a8b | |||
| e3fba0257f | |||
| cb8b65f6f3 | |||
| 3944a8ed54 | |||
| 2ceafe6379 | |||
| 9f058bd88a | |||
| 1dd0ff13d8 | |||
| 6061f10230 | |||
| ea59fafb52 | |||
| 2ff71126de | |||
| 6d522e1743 | |||
| b37f3c819d | |||
| 1b41994e5f | |||
| 4fd4b0d713 | |||
| 7b43ed702e | |||
| 56cd77942b | |||
| 37dc723b4b | |||
| d7ea37c917 | |||
| c1d2bf9b9f | |||
| 36f837730a | |||
| b8f0a1dd82 | |||
| 2d1b62a978 | |||
| 0792d0d59d | |||
| 8c6da1a658 | |||
| 26be10f937 | |||
| ef4d9a13ed | |||
| 320d987ede | |||
| 51a4c4d13b | |||
| aaf3ae5f9c | |||
| 858f4f74b3 | |||
| 3feed90039 | |||
| b46330fc7a | |||
| 5ca7ce1f75 | |||
| d1d9b37ec7 | |||
| 823115c4ec | |||
| 8fe3fda27f | |||
| 63fffd7493 | |||
| 243a350e2b | |||
| 8c09e7ba36 | |||
| d89502f91f | |||
| 847602f933 | |||
| 8fcf8fe39c | |||
| d59eec9296 | |||
| b9122ebc34 | |||
| 38e066ee49 | |||
| 232a04a1a2 | |||
| dcb145635c | |||
| c9b73c68a6 | |||
| 08f7925ea9 | |||
| ed79ec7940 | |||
| 869a44dd04 | |||
| 6a9e9ebc4c | |||
| f18a2a11fa | |||
| 9aaaa755c7 | |||
| 818cd9044b | |||
| 006ca12b6d | |||
| b5f9ab7c20 | |||
| 0981f95f16 | |||
| f64ef32eaa | |||
| 7a19659c9e | |||
| b1202fcd55 | |||
| b8f991eddb | |||
| d0013f55a2 | |||
| 7efaff4f6f | |||
| bc7a84e462 | |||
| 61657bd1b1 | |||
| fc63f4f89c | |||
| 2c44c252d7 | |||
| 613fc6e3ef | |||
| 0a9604d10e | |||
| 1cabedc65e | |||
| 4e5a0d9e02 | |||
| bf373d894d | |||
| e6bbad84c1 | |||
| 4de477d46c | |||
| 264cab3c9b | |||
| 7f9ef59bea | |||
| 8ebbef4cbb | |||
| 0c98a84242 | |||
| 2bbdd21b2f | |||
| 794cfe949b | |||
| 6a5010a2d6 | |||
| 61559fee9d | |||
| 2118a20408 | |||
| b0bc20cb83 | |||
| 2cd77b075b | |||
| 03450c6085 | |||
| 5d3c522da2 | |||
| bf1ba6efc0 | |||
| 67ad82d52e | |||
| f437d976f8 | |||
| c94443faaa | |||
| c6d57f6a56 | |||
| 09b06da403 | |||
| df73ce8a60 | |||
| 8b22c2e04f | |||
| b4f4d6cea2 | |||
| cdf7b2acf1 | |||
| 94651731a5 | |||
| 56424d29a3 | |||
| c5083b2aef | |||
| 1b06795ffe | |||
| 6679cd60ce | |||
| 843a3c16ba | |||
| df40204a57 | |||
| 210910eb6e | |||
| ef427758da | |||
| def6bbf683 | |||
| 5f37a4a21c | |||
| dc869987f9 | |||
| b98d2201e5 | |||
| 8dd6440bb8 | |||
| a2d83c48eb | |||
| a0ae8f4a07 | |||
| 719dcbcd4d | |||
| caa207e868 | |||
| 306004ecd2 | |||
| bcac3c5b84 | |||
| ccc90108df | |||
| b9781915a4 | |||
| 1890e65b75 | |||
| 2f4da3ed52 | |||
| 27a6ac0c0b | |||
| b81a66f07e | |||
| bc43fc9585 | |||
| 4f7c013c78 | |||
| 09b15a07c6 | |||
| 4340f024d3 | |||
| 98e9780819 | |||
| a45d63595f | |||
| 5fbd1453b4 | |||
| f827201ee0 | |||
| 485a96962a | |||
| 98a104f731 | |||
| ff987f14d7 | |||
| 4dd08268dc | |||
| c18a13d4fc | |||
| 7a79995727 | |||
| 01eca562c5 | |||
| f491d0c0c4 | |||
| edf2287e13 | |||
| fcaab633c1 | |||
| 33b6579b5d | |||
| 72a8e4bc22 | |||
| c67b02b7b0 | |||
| 486cd00384 | |||
| caea7bb39d | |||
| e8fb7ee683 | |||
| e4ee4211c8 | |||
| 3fa3ebee14 | |||
| 8e531f400e | |||
| 5727c0dc8a | |||
| f599088cdf | |||
| d78da55f54 | |||
| 9052ff71e6 | |||
| 713da887ca | |||
| ad5950697e | |||
| 85d0d06cab | |||
| be6ec558e3 | |||
| dd2f60810a | |||
| 6c0b86d8f4 | |||
| 517ada6dbf | |||
| 0a098e3008 | |||
| c40078ffc9 | |||
| 729e0afdbe | |||
| eab86840d3 | |||
| 43aa2247f1 | |||
| afe17a507e | |||
| e621020474 | |||
| ac2aa7f288 | |||
| 805bd7e930 | |||
| f9bf2122b7 | |||
| 4e3e533e13 | |||
| 611c429912 | |||
| e2898ee5bf | |||
| e1a532500e | |||
| 4cf412b93d | |||
| 54c9c434e0 | |||
| de19f3e5fe | |||
| 8304993481 | |||
| 4c838aeaca | |||
| 4ec1145dce | |||
| 547d925065 | |||
| 874633051b | |||
| 2293f1ba15 | |||
| 483c3f61b5 | |||
| 83263968f2 | |||
| f279c61792 | |||
| 9717c696d8 | |||
| 94a594c777 | |||
| f1ae8a17cf | |||
| add9c43827 | |||
| d3f6a5c296 | |||
| 4aea78b7c0 | |||
| 4313fe670d | |||
| 2e8a1b67ea | |||
| e73044c533 | |||
| 418f09e364 | |||
| 08f207a396 | |||
| 4f57060708 | |||
| 1507724ecd | |||
| 4bc2f64b24 | |||
| 839ba31dfb | |||
| 2341452d91 | |||
| 7ab263b514 | |||
| 45b5b5960f | |||
| 1b8ec1f01c | |||
| c92cb1c096 | |||
| 8f31fbe275 | |||
| aa76419eda | |||
| 21503c0c38 | |||
| d957b19f55 | |||
| 122c4242ce | |||
| e769ed2fd8 | |||
| c722904831 | |||
| c93faa9564 | |||
| ce6495a46d | |||
| 04f2b905af | |||
| b668a2c0d2 | |||
| 5fc8f10602 | |||
| a27f399a9e | |||
| ff5d14fb63 | |||
| 27fb2d2d5b | |||
| 0b9d59bf0e | |||
| 23e059a065 | |||
| 45c7b29a96 | |||
| 3e6c3fda60 | |||
| 1a1363ef77 | |||
| b5c51e231b | |||
| 22711dd7be | |||
| 1ba4d3d5d1 | |||
| 823ab73585 | |||
| 66c444efac | |||
| b688b8921a | |||
| 00550ddab5 | |||
| 42fedec088 | |||
| ff3bc0e8c2 | |||
| dde7dff870 | |||
| 25ffc9cf96 | |||
| eca92cf5b5 | |||
| 372bdf8be7 | |||
| c7c90b0647 | |||
| 14c2da4fa2 | |||
| 64275cfd22 | |||
| f0b099d9f7 | |||
| c99d957bc8 | |||
| 51b14d55ec | |||
| f92d9994df | |||
| 431e1b87bd | |||
| ad3a324719 | |||
| 8c9e178206 |
@@ -0,0 +1,17 @@
|
||||
krill-parser.js
|
||||
krill.pegjs
|
||||
.eslintrc.json
|
||||
server.js
|
||||
tidal-sniffer.js
|
||||
*.jsx
|
||||
tunejs.js
|
||||
out/**
|
||||
postcss.config.js
|
||||
postcss.config.cjs
|
||||
tailwind.config.js
|
||||
tailwind.config.cjs
|
||||
vite.config.js
|
||||
/**/dist/**/*
|
||||
!**/*.mjs
|
||||
**/*.tsx
|
||||
**/*.ts
|
||||
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"env": {
|
||||
"browser": true,
|
||||
"es2021": true
|
||||
},
|
||||
"extends": ["eslint:recommended"],
|
||||
"overrides": [],
|
||||
"parserOptions": {
|
||||
"ecmaVersion": "latest",
|
||||
"sourceType": "module"
|
||||
},
|
||||
"plugins": [],
|
||||
"rules": {
|
||||
"no-unused-vars": ["warn", { "destructuredArrayIgnorePattern": ".", "ignoreRestSiblings": false }]
|
||||
}
|
||||
}
|
||||
@@ -24,10 +24,10 @@ jobs:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: 16
|
||||
node-version: 18
|
||||
cache: "npm"
|
||||
- name: Install Dependencies
|
||||
run: npm ci && cd repl && npm ci && cd ../tutorial && npm ci
|
||||
run: npm ci && cd website && npm ci
|
||||
|
||||
- name: Build
|
||||
run: npm run build
|
||||
@@ -39,7 +39,7 @@ jobs:
|
||||
uses: actions/upload-pages-artifact@v1
|
||||
with:
|
||||
# Upload entire repository
|
||||
path: "./out"
|
||||
path: "./website/dist"
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
id: deployment
|
||||
|
||||
@@ -10,10 +10,12 @@ jobs:
|
||||
node-version: [18]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: 'npm'
|
||||
- run: npm install
|
||||
- run: npm test
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/setup-node@v3
|
||||
with:
|
||||
node-version: ${{ matrix.node-version }}
|
||||
cache: "npm"
|
||||
- run: npm install
|
||||
- run: npm run format-check
|
||||
- run: npm run lint
|
||||
- run: npm test
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
*.md
|
||||
*.json
|
||||
*.yml
|
||||
*.
|
||||
**/out
|
||||
**/dist
|
||||
packages/mini/krill-parser.js
|
||||
packages/xen/tunejs.js
|
||||
paper
|
||||
+14
-15
@@ -1,16 +1,15 @@
|
||||
{
|
||||
"printWidth": 120,
|
||||
"useTabs": false,
|
||||
"tabWidth": 2,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"jsxSingleQuote": false,
|
||||
"trailingComma": "all",
|
||||
"bracketSpacing": true,
|
||||
"jsxBracketSameLine": false,
|
||||
"arrowParens": "always",
|
||||
"proseWrap": "preserve",
|
||||
"htmlWhitespaceSensitivity": "css",
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
|
||||
"printWidth": 120,
|
||||
"useTabs": false,
|
||||
"tabWidth": 2,
|
||||
"semi": true,
|
||||
"singleQuote": true,
|
||||
"jsxSingleQuote": false,
|
||||
"trailingComma": "all",
|
||||
"bracketSpacing": true,
|
||||
"jsxBracketSameLine": false,
|
||||
"arrowParens": "always",
|
||||
"proseWrap": "preserve",
|
||||
"htmlWhitespaceSensitivity": "css",
|
||||
"endOfLine": "lf"
|
||||
}
|
||||
|
||||
Vendored
+2
-1
@@ -5,5 +5,6 @@
|
||||
],
|
||||
"yaml.schemas": {
|
||||
"https://json.schemastore.org/github-workflow.json": "file:///home/felix/projects/strudel/.github/workflows/deploy.yml"
|
||||
}
|
||||
},
|
||||
"testing.automaticallyOpenPeekView": "never"
|
||||
}
|
||||
+5
-7
@@ -12,8 +12,8 @@ To get in touch with the contributors, either
|
||||
|
||||
## Ask a Question
|
||||
|
||||
If you have any questions about strudel, make sure you've read the
|
||||
[tutorial](https://strudel.tidalcycles.org/tutorial/) to find out if it answers your question.
|
||||
If you have any questions about strudel, make sure you've glanced through the
|
||||
[docs](https://strudel.tidalcycles.org/learn/) to find out if it answers your question.
|
||||
If not, use one of the Communication Channels above!
|
||||
|
||||
Don't be afraid to ask! Your question might be of great value for other people too.
|
||||
@@ -29,12 +29,10 @@ If you made some music with strudel, you can give back some love and share what
|
||||
Your creation could also be part of the random selection in the REPL if you want.
|
||||
Use one of the Communication Channels listed above.
|
||||
|
||||
## Improve the Tutorial
|
||||
## Improve the Docs
|
||||
|
||||
If you find some weak spots in the [tutorial](https://strudel.tidalcycles.org/),
|
||||
you are welcome to improve them by editing [this file](https://github.com/tidalcycles/strudel/blob/main/tutorial/tutorial.mdx).
|
||||
|
||||
This will even work without setting up a development environment, only a github account is required.
|
||||
If you find some weak spots in the [docs](https://strudel.tidalcycles.org/learn/getting-started),
|
||||
you can edit each file directly on github via the "Edit this page" link located in the right sidebar.
|
||||
|
||||
## Propose a Feature
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
An experiment in making a [Tidal](https://github.com/tidalcycles/tidal/) using web technologies. This software is slowly stabilising, but please continue to tread carefully.
|
||||
|
||||
- Try it here: <https://strudel.tidalcycles.org/>
|
||||
- Tutorial: <https://strudel.tidalcycles.org/tutorial/>
|
||||
- Docs: <https://strudel.tidalcycles.org/learn/>
|
||||
- Technical Blog Post: <https://loophole-letters.vercel.app/strudel>
|
||||
|
||||
## Running Locally
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// this barrel export is currently only used to find undocumented exports
|
||||
export * from './packages/core/index.mjs';
|
||||
export * from './packages/csound/index.mjs';
|
||||
export * from './packages/embed/index.mjs';
|
||||
export * from './packages/eval/index.mjs';
|
||||
export * from './packages/midi/index.mjs';
|
||||
export * from './packages/mini/index.mjs';
|
||||
export * from './packages/osc/index.mjs';
|
||||
export * from './packages/react/index.mjs';
|
||||
export * from './packages/serial/index.mjs';
|
||||
export * from './packages/soundfonts/index.mjs';
|
||||
export * from './packages/tonal/index.mjs';
|
||||
export * from './packages/tone/index.mjs';
|
||||
export * from './packages/transpiler/index.mjs';
|
||||
export * from './packages/webaudio/index.mjs';
|
||||
export * from './packages/webdirt/index.mjs';
|
||||
export * from './packages/xen/index.mjs';
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"source": {
|
||||
"includePattern": ".+\\.(js(doc|x)?|mjs)$",
|
||||
"excludePattern": "node_modules|shift-parser|shift-reducer|shift-traverser"
|
||||
"excludePattern": "node_modules|shift-parser|shift-reducer|shift-traverser|dist"
|
||||
},
|
||||
"plugins": ["plugins/markdown"],
|
||||
"opts": {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
# my-patterns
|
||||
|
||||
This directory can be used to save your own patterns, which then get
|
||||
made into a pattern swatch.
|
||||
|
||||
0. fork and clone the strudel repository
|
||||
1. run `npm run setup` in the strudel folder
|
||||
1. Save one or more .txt files in this folder
|
||||
2. run `npm run repl` in the top-level strudel folder
|
||||
3. open `http://localhost:3000/swatch/` !
|
||||
|
||||
## deploy
|
||||
|
||||
1. in your fork, go to settings -> pages and select "Github Actions" as source
|
||||
2. edit `website/public/CNAME` to contain `<your-username>.github.io/strudel`
|
||||
3. edit `website/astro.config.mjs` to use site: `https://<your-username>.github.io` and base `/strudel`
|
||||
4. go to Actions -> `Build and Deploy` and click `Run workflow`
|
||||
5. view your patterns at `<your-username>.github.io/strudel/swatch/`
|
||||
|
||||
Alternatively, github pages allows you to use a custom domain, like https://mycooldomain.org/swatch/. [See their documentation for details](https://docs.github.com/en/pages/configuring-a-custom-domain-for-your-github-pages-site).
|
||||
Generated
+4927
-5442
File diff suppressed because it is too large
Load Diff
+21
-10
@@ -1,23 +1,30 @@
|
||||
{
|
||||
"name": "@strudel.cycles/monorepo",
|
||||
"version": "0.0.4",
|
||||
"version": "0.5.0",
|
||||
"private": true,
|
||||
"description": "Port of tidalcycles to javascript",
|
||||
"scripts": {
|
||||
"pretest": "cd tutorial && npm run jsdoc-json",
|
||||
"pretest": "npm run jsdoc-json",
|
||||
"prebuild": "npm run jsdoc-json",
|
||||
"test": "vitest run --version",
|
||||
"test-ui": "vitest --ui",
|
||||
"test-coverage": "vitest --coverage",
|
||||
"bootstrap": "lerna bootstrap",
|
||||
"setup": "npm i && npm run bootstrap && cd repl && npm i && cd ../tutorial && npm i",
|
||||
"snapshot": "cd repl && npm run snapshot",
|
||||
"repl": "cd repl && npm run dev",
|
||||
"setup": "npm i && npm run jsdoc-json && npm run bootstrap && cd website && npm i",
|
||||
"snapshot": "vitest run -u --silent",
|
||||
"repl": "cd website && npm run dev",
|
||||
"osc": "cd packages/osc && npm run server",
|
||||
"build": "rm -rf out && cd repl && npm run build && cd ../tutorial && npm run build",
|
||||
"preview": "npx serve ./out",
|
||||
"build": "cd website && npm run build",
|
||||
"preview": "cd website && npm run preview",
|
||||
"deploy": "NODE_DEBUG=gh-pages gh-pages -d out",
|
||||
"jsdoc": "jsdoc packages/ -c jsdoc.config.json",
|
||||
"jsdoc-json": "jsdoc packages/ --template ./node_modules/jsdoc-json --destination doc.json -c jsdoc.config.json"
|
||||
"jsdoc-json": "jsdoc packages/ --template ./node_modules/jsdoc-json --destination doc.json -c jsdoc.config.json",
|
||||
"lint": "eslint . --ext mjs,js --quiet",
|
||||
"codeformat": "prettier --write .",
|
||||
"format-check": "prettier --check .",
|
||||
"report-undocumented": "npm run jsdoc-json && node undocumented.mjs > undocumented.json",
|
||||
"check": "npm run format-check && npm run lint && npm run test",
|
||||
"iclc": "cd paper && pandoc --template=pandoc/iclc.html --citeproc --number-sections iclc2023.md -o iclc2023.html && pandoc --template=pandoc/iclc.latex --citeproc --number-sections iclc2023.md -o iclc2023.pdf"
|
||||
},
|
||||
"workspaces": [
|
||||
"packages/*"
|
||||
@@ -40,15 +47,19 @@
|
||||
},
|
||||
"homepage": "https://strudel.tidalcycles.org",
|
||||
"devDependencies": {
|
||||
"@vitest/ui": "^0.21.1",
|
||||
"@vitest/ui": "^0.25.7",
|
||||
"c8": "^7.12.0",
|
||||
"canvas": "^2.11.0",
|
||||
"dependency-tree": "^9.0.0",
|
||||
"eslint": "^8.28.0",
|
||||
"events": "^3.3.0",
|
||||
"gh-pages": "^4.0.0",
|
||||
"jsdoc": "^3.6.10",
|
||||
"jsdoc-json": "^2.0.2",
|
||||
"jsdoc-to-markdown": "^7.1.1",
|
||||
"lerna": "^4.0.0",
|
||||
"prettier": "^2.8.1",
|
||||
"rollup-plugin-visualizer": "^5.8.1",
|
||||
"vitest": "^0.21.1"
|
||||
"vitest": "^0.25.7"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
import { controls, Pattern, getDrawContext, silence, register, pure } from './index.mjs';
|
||||
const { createParams } = controls;
|
||||
|
||||
let clearColor = '#22222210';
|
||||
|
||||
Pattern.prototype.animate = function ({ callback, sync = false, smear = 0.5 } = {}) {
|
||||
window.frame && cancelAnimationFrame(window.frame);
|
||||
const ctx = getDrawContext();
|
||||
const { clientWidth: ww, clientHeight: wh } = ctx.canvas;
|
||||
let smearPart = smear === 0 ? '99' : Number((1 - smear) * 100).toFixed(0);
|
||||
smearPart = smearPart.length === 1 ? `0${smearPart}` : smearPart;
|
||||
clearColor = `#200010${smearPart}`;
|
||||
const render = (t) => {
|
||||
let frame;
|
||||
/* if (sync) {
|
||||
t = scheduler.now();
|
||||
frame = this.queryArc(t, t);
|
||||
} else { */
|
||||
t = Math.round(t);
|
||||
frame = this.slow(1000).queryArc(t, t);
|
||||
// }
|
||||
ctx.fillStyle = clearColor;
|
||||
ctx.fillRect(0, 0, ww, wh);
|
||||
frame.forEach((f) => {
|
||||
let { x, y, w, h, s, r, a = 0, fill = 'darkseagreen' } = f.value;
|
||||
w *= ww;
|
||||
h *= wh;
|
||||
if (r !== undefined && a !== undefined) {
|
||||
const radians = a * 2 * Math.PI;
|
||||
const [cx, cy] = [(ww - w) / 2, (wh - h) / 2];
|
||||
x = cx + Math.cos(radians) * r * cx;
|
||||
y = cy + Math.sin(radians) * r * cy;
|
||||
} else {
|
||||
x *= ww - w;
|
||||
y *= wh - h;
|
||||
}
|
||||
const val = { ...f.value, x, y, w, h };
|
||||
ctx.fillStyle = fill;
|
||||
if (s === 'rect') {
|
||||
ctx.fillRect(x, y, w, h);
|
||||
} else if (s === 'ellipse') {
|
||||
ctx.beginPath();
|
||||
ctx.ellipse(x + w / 2, y + h / 2, w / 2, h / 2, 0, 0, 2 * Math.PI);
|
||||
ctx.fill();
|
||||
}
|
||||
callback && callback(ctx, val, f);
|
||||
});
|
||||
window.frame = requestAnimationFrame(render);
|
||||
};
|
||||
window.frame = requestAnimationFrame(render);
|
||||
return silence;
|
||||
};
|
||||
|
||||
export const { x, y, w, h, a, r, fill, smear } = createParams('x', 'y', 'w', 'h', 'a', 'r', 'fill', 'smear');
|
||||
|
||||
export const rescale = register('rescale', function (f, pat) {
|
||||
return pat.mul(x(f).w(f).y(f).h(f));
|
||||
});
|
||||
|
||||
export const moveXY = register('moveXY', function (dx, dy, pat) {
|
||||
return pat.add(x(dx).y(dy));
|
||||
});
|
||||
|
||||
export const zoomIn = register('zoomIn', function (f, pat) {
|
||||
const d = pure(1).sub(f).div(2);
|
||||
return pat.rescale(f).move(d, d);
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
export const colorMap = {
|
||||
aliceblue: '#f0f8ff',
|
||||
antiquewhite: '#faebd7',
|
||||
aqua: '#00ffff',
|
||||
aquamarine: '#7fffd4',
|
||||
azure: '#f0ffff',
|
||||
beige: '#f5f5dc',
|
||||
bisque: '#ffe4c4',
|
||||
black: '#000000',
|
||||
blanchedalmond: '#ffebcd',
|
||||
blue: '#0000ff',
|
||||
blueviolet: '#8a2be2',
|
||||
brown: '#a52a2a',
|
||||
burlywood: '#deb887',
|
||||
cadetblue: '#5f9ea0',
|
||||
chartreuse: '#7fff00',
|
||||
chocolate: '#d2691e',
|
||||
coral: '#ff7f50',
|
||||
cornflowerblue: '#6495ed',
|
||||
cornsilk: '#fff8dc',
|
||||
crimson: '#dc143c',
|
||||
cyan: '#00ffff',
|
||||
darkblue: '#00008b',
|
||||
darkcyan: '#008b8b',
|
||||
darkgoldenrod: '#b8860b',
|
||||
darkgray: '#a9a9a9',
|
||||
darkgreen: '#006400',
|
||||
darkgrey: '#a9a9a9',
|
||||
darkkhaki: '#bdb76b',
|
||||
darkmagenta: '#8b008b',
|
||||
darkolivegreen: '#556b2f',
|
||||
darkorange: '#ff8c00',
|
||||
darkorchid: '#9932cc',
|
||||
darkred: '#8b0000',
|
||||
darksalmon: '#e9967a',
|
||||
darkseagreen: '#8fbc8f',
|
||||
darkslateblue: '#483d8b',
|
||||
darkslategray: '#2f4f4f',
|
||||
darkslategrey: '#2f4f4f',
|
||||
darkturquoise: '#00ced1',
|
||||
darkviolet: '#9400d3',
|
||||
deeppink: '#ff1493',
|
||||
deepskyblue: '#00bfff',
|
||||
dimgray: '#696969',
|
||||
dimgrey: '#696969',
|
||||
dodgerblue: '#1e90ff',
|
||||
firebrick: '#b22222',
|
||||
floralwhite: '#fffaf0',
|
||||
forestgreen: '#228b22',
|
||||
fuchsia: '#ff00ff',
|
||||
gainsboro: '#dcdcdc',
|
||||
ghostwhite: '#f8f8ff',
|
||||
gold: '#ffd700',
|
||||
goldenrod: '#daa520',
|
||||
gray: '#808080',
|
||||
green: '#008000',
|
||||
greenyellow: '#adff2f',
|
||||
grey: '#808080',
|
||||
honeydew: '#f0fff0',
|
||||
hotpink: '#ff69b4',
|
||||
indianred: '#cd5c5c',
|
||||
indigo: '#4b0082',
|
||||
ivory: '#fffff0',
|
||||
khaki: '#f0e68c',
|
||||
lavender: '#e6e6fa',
|
||||
lavenderblush: '#fff0f5',
|
||||
lawngreen: '#7cfc00',
|
||||
lemonchiffon: '#fffacd',
|
||||
lightblue: '#add8e6',
|
||||
lightcoral: '#f08080',
|
||||
lightcyan: '#e0ffff',
|
||||
lightgoldenrodyellow: '#fafad2',
|
||||
lightgray: '#d3d3d3',
|
||||
lightgreen: '#90ee90',
|
||||
lightgrey: '#d3d3d3',
|
||||
lightpink: '#ffb6c1',
|
||||
lightsalmon: '#ffa07a',
|
||||
lightseagreen: '#20b2aa',
|
||||
lightskyblue: '#87cefa',
|
||||
lightslategray: '#778899',
|
||||
lightslategrey: '#778899',
|
||||
lightsteelblue: '#b0c4de',
|
||||
lightyellow: '#ffffe0',
|
||||
lime: '#00ff00',
|
||||
limegreen: '#32cd32',
|
||||
linen: '#faf0e6',
|
||||
magenta: '#ff00ff',
|
||||
maroon: '#800000',
|
||||
mediumaquamarine: '#66cdaa',
|
||||
mediumblue: '#0000cd',
|
||||
mediumorchid: '#ba55d3',
|
||||
mediumpurple: '#9370db',
|
||||
mediumseagreen: '#3cb371',
|
||||
mediumslateblue: '#7b68ee',
|
||||
mediumspringgreen: '#00fa9a',
|
||||
mediumturquoise: '#48d1cc',
|
||||
mediumvioletred: '#c71585',
|
||||
midnightblue: '#191970',
|
||||
mintcream: '#f5fffa',
|
||||
mistyrose: '#ffe4e1',
|
||||
moccasin: '#ffe4b5',
|
||||
navajowhite: '#ffdead',
|
||||
navy: '#000080',
|
||||
oldlace: '#fdf5e6',
|
||||
olive: '#808000',
|
||||
olivedrab: '#6b8e23',
|
||||
orange: '#ffa500',
|
||||
orangered: '#ff4500',
|
||||
orchid: '#da70d6',
|
||||
palegoldenrod: '#eee8aa',
|
||||
palegreen: '#98fb98',
|
||||
paleturquoise: '#afeeee',
|
||||
palevioletred: '#db7093',
|
||||
papayawhip: '#ffefd5',
|
||||
peachpuff: '#ffdab9',
|
||||
peru: '#cd853f',
|
||||
pink: '#ffc0cb',
|
||||
plum: '#dda0dd',
|
||||
powderblue: '#b0e0e6',
|
||||
purple: '#800080',
|
||||
red: '#ff0000',
|
||||
rosybrown: '#bc8f8f',
|
||||
royalblue: '#4169e1',
|
||||
saddlebrown: '#8b4513',
|
||||
salmon: '#fa8072',
|
||||
sandybrown: '#f4a460',
|
||||
seagreen: '#2e8b57',
|
||||
seashell: '#fff5ee',
|
||||
sienna: '#a0522d',
|
||||
silver: '#c0c0c0',
|
||||
skyblue: '#87ceeb',
|
||||
slateblue: '#6a5acd',
|
||||
slategray: '#708090',
|
||||
slategrey: '#708090',
|
||||
snow: '#fffafa',
|
||||
springgreen: '#00ff7f',
|
||||
steelblue: '#4682b4',
|
||||
tan: '#d2b48c',
|
||||
teal: '#008080',
|
||||
thistle: '#d8bfd8',
|
||||
tomato: '#ff6347',
|
||||
turquoise: '#40e0d0',
|
||||
violet: '#ee82ee',
|
||||
wheat: '#f5deb3',
|
||||
white: '#ffffff',
|
||||
whitesmoke: '#f5f5f5',
|
||||
yellow: '#ffff00',
|
||||
yellowgreen: '#9acd32',
|
||||
};
|
||||
|
||||
export function convertColorToNumber(color) {
|
||||
// Convert color to lowercase for easier matching
|
||||
color = color.toLowerCase();
|
||||
|
||||
// If the color is a hex code, convert it to a number
|
||||
if (color[0] === '#') {
|
||||
return convertHexToNumber(color);
|
||||
}
|
||||
|
||||
// If the color is a named color, return the corresponding number
|
||||
if (colorMap[color] !== undefined) {
|
||||
return convertHexToNumber(colorMap[color]);
|
||||
}
|
||||
|
||||
// If the color is not recognized, return null
|
||||
return -1;
|
||||
}
|
||||
|
||||
export function convertHexToNumber(hex) {
|
||||
// Remove the leading '#' from the hex code
|
||||
hex = hex.slice(1);
|
||||
|
||||
// Convert the hex code to a number
|
||||
return parseInt(hex, 16);
|
||||
}
|
||||
+93
-38
@@ -51,6 +51,7 @@ const generic_params = [
|
||||
*
|
||||
* @name accelerate
|
||||
* @param {number | Pattern} amount acceleration.
|
||||
* @superdirtOnly
|
||||
* @example
|
||||
* s("sax").accelerate("<0 1 2 4 8 16>").slow(2).osc()
|
||||
*
|
||||
@@ -75,19 +76,20 @@ const generic_params = [
|
||||
*
|
||||
* @name amp
|
||||
* @param {number | Pattern} amount gain.
|
||||
* @superdirtOnly
|
||||
* @example
|
||||
* s("bd*8").amp(".1*2 .5 .1*2 .5 .1 .5").osc()
|
||||
*
|
||||
*/
|
||||
['f', 'amp', 'like @gain@, but linear.'],
|
||||
// TODO: find out why 0 does not work, and it generally seems not right
|
||||
/*
|
||||
/**
|
||||
* A pattern of numbers to specify the attack time of an envelope applied to each sample.
|
||||
* [More info about envelopes](/learn/synths-samples-effects/#envelope)
|
||||
*
|
||||
* @name attack
|
||||
* @param {number | Pattern} attack time in seconds.
|
||||
* @example
|
||||
* n("c5 e5").s('superpiano').attack("<0 .1>").osc()
|
||||
* note("c3 e3").attack("<0 .1 .5>")
|
||||
*
|
||||
*/
|
||||
[
|
||||
@@ -107,18 +109,36 @@ const generic_params = [
|
||||
*/
|
||||
['f', 'bank', 'selects sound bank to use'],
|
||||
|
||||
// TODO: find out how this works?
|
||||
/*
|
||||
* Envelope decay time = the time it takes after the attack time to reach the sustain level.
|
||||
/**
|
||||
* Gain envelope decay time = the time it takes after the attack time to reach the sustain level.
|
||||
* [More info about envelopes](/learn/synths-samples-effects/#envelope)
|
||||
*
|
||||
* @name decay
|
||||
* @param {number | Pattern} time decay time in seconds
|
||||
* @example
|
||||
* s("sax").cut(1).decay("<.1 .2 .3 .4>").sustain(0).osc()
|
||||
* note("c3 e3").decay("<.1 .2 .3 .4>").sustain(0)
|
||||
*
|
||||
*/
|
||||
['f', 'decay', ''],
|
||||
/**
|
||||
* Gain envelope sustain level. [More info about envelopes](/learn/synths-samples-effects/#envelope)
|
||||
*
|
||||
* @name sustain
|
||||
* @param {number | Pattern} gain sustain level between 0 and 1
|
||||
* @example
|
||||
* note("c3 e3").decay(.2).sustain("<0 .1 .4 .6 1>")
|
||||
*
|
||||
*/
|
||||
['f', 'sustain', ''],
|
||||
/**
|
||||
* Gain envelope release time. [More info about envelopes](/learn/synths-samples-effects/#envelope)
|
||||
*
|
||||
* @name release
|
||||
* @param {number | Pattern} time release time in seconds
|
||||
* @example
|
||||
* note("c3 e3 g3 c4").release("<0 .1 .4 .6 1>/2")
|
||||
*
|
||||
*/
|
||||
[
|
||||
'f',
|
||||
'release',
|
||||
@@ -135,22 +155,26 @@ const generic_params = [
|
||||
*
|
||||
* @name bandf
|
||||
* @param {number | Pattern} frequency center frequency
|
||||
* @synonyms bpf
|
||||
* @example
|
||||
* s("bd sd,hh*3").bandf("<1000 2000 4000 8000>")
|
||||
*
|
||||
*/
|
||||
['f', 'bandf', 'A pattern of numbers from 0 to 1. Sets the center frequency of the band-pass filter.'],
|
||||
['f', 'bpf', ''],
|
||||
// TODO: in tidal, it seems to be normalized
|
||||
/**
|
||||
* Sets the q-factor of the band-pass filter
|
||||
*
|
||||
* @name bandq
|
||||
* @param {number | Pattern} q q factor
|
||||
* @synonyms bpq
|
||||
* @example
|
||||
* s("bd sd").bandf(500).bandq("<0 1 2 3>")
|
||||
*
|
||||
*/
|
||||
['f', 'bandq', 'a pattern of anumbers from 0 to 1. Sets the q-factor of the band-pass filter.'],
|
||||
['f', 'bpq', ''],
|
||||
/**
|
||||
* a pattern of numbers from 0 to 1. Skips the beginning of each sample, e.g. `0.25` to cut off the first quarter from each sample.
|
||||
*
|
||||
@@ -204,7 +228,7 @@ const generic_params = [
|
||||
* "c4 eb4 g4 bb4".legato("<0.125 .25 .5 .75 1 2 4>")
|
||||
*
|
||||
*/
|
||||
['f', 'legato', 'controls the amount of overlap between two adjacent sounds'],
|
||||
// ['f', 'legato', 'controls the amount of overlap between two adjacent sounds'],
|
||||
// ['f', 'clhatdecay', ''],
|
||||
/**
|
||||
* bit crusher effect.
|
||||
@@ -249,7 +273,7 @@ const generic_params = [
|
||||
* @name cut
|
||||
* @param {number | Pattern} group cut group number
|
||||
* @example
|
||||
* s("bd sax").cut(1).osc()
|
||||
* s("rd*4").cut(1)
|
||||
*
|
||||
*/
|
||||
[
|
||||
@@ -262,53 +286,50 @@ const generic_params = [
|
||||
*
|
||||
* @name cutoff
|
||||
* @param {number | Pattern} frequency audible between 0 and 20000
|
||||
* @synonyms lpf
|
||||
* @example
|
||||
* s("bd sd,hh*3").cutoff("<4000 2000 1000 500 200 100>")
|
||||
*
|
||||
*/
|
||||
// TODO: add lpf synonym
|
||||
['f', 'cutoff', 'a pattern of numbers from 0 to 1. Applies the cutoff frequency of the low-pass filter.'],
|
||||
['f', 'lpf'],
|
||||
/**
|
||||
* Applies the cutoff frequency of the high-pass filter.
|
||||
*
|
||||
* @name hcutoff
|
||||
* @param {number | Pattern} frequency audible between 0 and 20000
|
||||
* @synonyms hpf
|
||||
* @example
|
||||
* s("bd sd,hh*4").hcutoff("<4000 2000 1000 500 200 100>")
|
||||
*
|
||||
*/
|
||||
// TODO: add hpf synonym
|
||||
[
|
||||
'f',
|
||||
'hcutoff',
|
||||
'a pattern of numbers from 0 to 1. Applies the cutoff frequency of the high-pass filter. Also has alias @hpf@',
|
||||
],
|
||||
['f', 'hcutoff', ''],
|
||||
['f', 'hpf', ''],
|
||||
/**
|
||||
* Applies the resonance of the high-pass filter.
|
||||
*
|
||||
* @name hresonance
|
||||
* @param {number | Pattern} q resonance factor between 0 and 50
|
||||
* @synonyms hpq
|
||||
* @example
|
||||
* s("bd sd,hh*4").hcutoff(2000).hresonance("<0 10 20 30>")
|
||||
*
|
||||
*/
|
||||
[
|
||||
'f',
|
||||
'hresonance',
|
||||
'a pattern of numbers from 0 to 1. Applies the resonance of the high-pass filter. Has alias @hpq@',
|
||||
],
|
||||
['f', 'hpq', ''],
|
||||
['f', 'hresonance', ''],
|
||||
// TODO: add hpq synonym
|
||||
/**
|
||||
* Applies the cutoff frequency of the low-pass filter.
|
||||
*
|
||||
* @name resonance
|
||||
* @param {number | Pattern} q resonance factor between 0 and 50
|
||||
* @synonyms lpq
|
||||
* @example
|
||||
* s("bd sd,hh*4").cutoff(2000).resonance("<0 10 20 30>")
|
||||
*
|
||||
*/
|
||||
['f', 'resonance', 'a pattern of numbers from 0 to 1. Specifies the resonance of the low-pass filter.'],
|
||||
// TODO: add lpq synonym?
|
||||
['f', 'lpq'],
|
||||
['f', 'resonance', ''],
|
||||
/**
|
||||
* DJ filter, below 0.5 is low pass filter, above is high pass filter.
|
||||
*
|
||||
@@ -321,17 +342,36 @@ const generic_params = [
|
||||
['f', 'djf', 'DJ filter, below 0.5 is low pass filter, above is high pass filter.'],
|
||||
// ['f', 'cutoffegint', ''],
|
||||
// TODO: does not seem to work
|
||||
/*
|
||||
/**
|
||||
* Sets the level of the delay signal.
|
||||
*
|
||||
* @name delay
|
||||
* @param {number | Pattern} level between 0 and 1
|
||||
* @example
|
||||
* s("bd").delay("<0 .5 .75 1>").osc()
|
||||
* s("bd").delay("<0 .25 .5 1>")
|
||||
*
|
||||
*/
|
||||
['f', 'delay', 'a pattern of numbers from 0 to 1. Sets the level of the delay signal.'],
|
||||
/**
|
||||
* Sets the level of the signal that is fed back into the delay.
|
||||
* Caution: Values >= 1 will result in a signal that gets louder and louder! Don't do it
|
||||
*
|
||||
* @name delayfeedback
|
||||
* @param {number | Pattern} feedback between 0 and 1
|
||||
* @example
|
||||
* s("bd").delay(.25).delayfeedback("<.25 .5 .75 1>").slow(2)
|
||||
*
|
||||
*/
|
||||
['f', 'delayfeedback', 'a pattern of numbers from 0 to 1. Sets the amount of delay feedback.'],
|
||||
/**
|
||||
* Sets the time of the delay effect.
|
||||
*
|
||||
* @name delaytime
|
||||
* @param {number | Pattern} seconds between 0 and Infinity
|
||||
* @example
|
||||
* s("bd").delay(.25).delaytime("<.125 .25 .5 1>").slow(2)
|
||||
*
|
||||
*/
|
||||
['f', 'delaytime', 'a pattern of numbers from 0 to 1. Sets the length of the delay.'],
|
||||
/* // TODO: test
|
||||
* Specifies whether delaytime is calculated relative to cps.
|
||||
@@ -400,7 +440,7 @@ const generic_params = [
|
||||
* @example
|
||||
* freq("220 110 440 110").s("superzow").osc()
|
||||
* @example
|
||||
* freq("110".mulOut(".5 1.5 .6 [2 3]")).s("superzow").osc()
|
||||
* freq("110".mul.out(".5 1.5 .6 [2 3]")).s("superzow").osc()
|
||||
*
|
||||
*/
|
||||
['f', 'freq', ''],
|
||||
@@ -484,11 +524,15 @@ const generic_params = [
|
||||
// ['f', 'ophatdecay', ''],
|
||||
// TODO: example
|
||||
/**
|
||||
* a pattern of numbers. An `orbit` is a global parameter context for patterns. Patterns with the same orbit will share hardware output bus offset and global effects, e.g. reverb and delay. The maximum number of orbits is specified in the superdirt startup, numbers higher than maximum will wrap around.
|
||||
* An `orbit` is a global parameter context for patterns. Patterns with the same orbit will share the same global effects.
|
||||
*
|
||||
* @name orbit
|
||||
* @param {number | Pattern} number
|
||||
*
|
||||
* @example
|
||||
* stack(
|
||||
* s("hh*3").delay(.5).delaytime(.25).orbit(1),
|
||||
* s("~ sd").delay(.5).delaytime(.125).orbit(2)
|
||||
* )
|
||||
*/
|
||||
[
|
||||
'i',
|
||||
@@ -562,7 +606,7 @@ const generic_params = [
|
||||
// TODO: detune? https://tidalcycles.org/docs/patternlib/tutorials/synthesizers/#supersquare
|
||||
['f', 'semitone', ''],
|
||||
// TODO: dedup with synth param, see https://tidalcycles.org/docs/reference/synthesizers/#superpiano
|
||||
['f', 'velocity', ''],
|
||||
// ['f', 'velocity', ''],
|
||||
['f', 'voice', ''], // TODO: synth param
|
||||
/**
|
||||
* Sets the level of reverb.
|
||||
@@ -570,21 +614,22 @@ const generic_params = [
|
||||
* @name room
|
||||
* @param {number | Pattern} level between 0 and 1
|
||||
* @example
|
||||
* s("bd sd").room("<0 .2 .4 .6 .8 1>").osc()
|
||||
* s("bd sd").room("<0 .2 .4 .6 .8 1>")
|
||||
*
|
||||
*/
|
||||
['f', 'room', 'a pattern of numbers from 0 to 1. Sets the level of reverb.'],
|
||||
/**
|
||||
* Sets the room size of the reverb, see {@link room}.
|
||||
*
|
||||
* @name size
|
||||
* @param {number | Pattern} size between 0 and 1
|
||||
* @name roomsize
|
||||
* @synonyms size
|
||||
* @param {number | Pattern} size between 0 and 10
|
||||
* @example
|
||||
* s("bd sd").room(.8).size("<0 .2 .4 .6 .8 1>").osc()
|
||||
* s("bd sd").room(.8).roomsize("<0 1 2 4 8>")
|
||||
*
|
||||
*/
|
||||
// TODO: find out why :
|
||||
// s("bd sd").room(.8).size("<0 .2 .4 .6 .8 [1,0]>").osc()
|
||||
// s("bd sd").room(.8).roomsize("<0 .2 .4 .6 .8 [1,0]>").osc()
|
||||
// .. does not work. Is it because room is only one effect?
|
||||
[
|
||||
'f',
|
||||
@@ -620,9 +665,9 @@ const generic_params = [
|
||||
* @name speed
|
||||
* @param {number | Pattern} speed -inf to inf, negative numbers play the sample backwards.
|
||||
* @example
|
||||
* s("bd").speed("<1 2 4 1 -2 -4>").osc()
|
||||
* s("bd").speed("<1 2 4 1 -2 -4>")
|
||||
* @example
|
||||
* speed("1 1.5*2 [2 1.1]").s("sax").cut(1).osc()
|
||||
* speed("1 1.5*2 [2 1.1]").s("piano").clip(1)
|
||||
*
|
||||
*/
|
||||
[
|
||||
@@ -775,18 +820,28 @@ const _setter = (func, name) =>
|
||||
};
|
||||
|
||||
generic_params.forEach(([type, name, description]) => {
|
||||
controls[name] = (...pats) => _name(name, ...pats);
|
||||
controls[name] = function (...pats) {
|
||||
const result = _name(name, ...pats);
|
||||
|
||||
// Add a function for composing this control with another pattern
|
||||
result.__as_function = function (pat) {
|
||||
return pat[name](...pats);
|
||||
};
|
||||
return result;
|
||||
};
|
||||
Pattern.__registered.push(name);
|
||||
Pattern.prototype[name] = _setter(controls[name], name);
|
||||
});
|
||||
|
||||
// create custom param
|
||||
controls.createParam = (name) => {
|
||||
const func = (...pats) => _name(name, ...pats);
|
||||
Pattern.__registered.push(name);
|
||||
Pattern.prototype[name] = _setter(func, name);
|
||||
return (...pats) => _name(name, ...pats);
|
||||
};
|
||||
|
||||
controls.createParams = (...names) =>
|
||||
names.reduce((acc, name) => Object.assign(acc, { [name]: createParam(name) }), {});
|
||||
names.reduce((acc, name) => Object.assign(acc, { [name]: controls.createParam(name) }), {});
|
||||
|
||||
export default controls;
|
||||
|
||||
+23
-17
@@ -5,16 +5,16 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
*/
|
||||
|
||||
import createClock from './zyklus.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
|
||||
export class Cyclist {
|
||||
worker;
|
||||
pattern;
|
||||
started = false;
|
||||
cps = 1; // TODO
|
||||
getTime;
|
||||
phase = 0;
|
||||
constructor({ interval, onTrigger, onError, getTime, latency = 0.1 }) {
|
||||
constructor({ interval, onTrigger, onToggle, onError, getTime, latency = 0.1 }) {
|
||||
this.started = false;
|
||||
this.cps = 1; // TODO
|
||||
this.phase = 0;
|
||||
this.getTime = getTime;
|
||||
this.onToggle = onToggle;
|
||||
this.latency = latency;
|
||||
const round = (x) => Math.round(x * 1000) / 1000;
|
||||
this.clock = createClock(
|
||||
getTime,
|
||||
@@ -28,9 +28,7 @@ export class Cyclist {
|
||||
const time = getTime();
|
||||
try {
|
||||
const haps = this.pattern.queryArc(begin, end); // get Haps
|
||||
// console.log('haps', haps.map((hap) => hap.value.n).join(' '));
|
||||
haps.forEach((hap) => {
|
||||
// console.log('hap', hap.value.n, hap.part.begin);
|
||||
if (hap.part.begin.equals(hap.whole.begin)) {
|
||||
const deadline = hap.whole.begin + this.origin - time + latency;
|
||||
const duration = hap.duration * 1;
|
||||
@@ -38,7 +36,7 @@ export class Cyclist {
|
||||
}
|
||||
});
|
||||
} catch (e) {
|
||||
console.warn('scheduler error', e);
|
||||
logger(`[cyclist] error: ${e.message}`);
|
||||
onError?.(e);
|
||||
}
|
||||
}, // called slightly before each cycle
|
||||
@@ -46,24 +44,32 @@ export class Cyclist {
|
||||
);
|
||||
}
|
||||
getPhase() {
|
||||
return this.phase;
|
||||
return this.getTime() - this.origin - this.latency;
|
||||
}
|
||||
now() {
|
||||
return this.getTime() - this.origin + this.clock.minLatency;
|
||||
}
|
||||
setStarted(v) {
|
||||
this.started = v;
|
||||
this.onToggle?.(v);
|
||||
}
|
||||
start() {
|
||||
if (!this.pattern) {
|
||||
throw new Error('Scheduler: no pattern set! call .setPattern first.');
|
||||
}
|
||||
logger('[cyclist] start');
|
||||
this.clock.start();
|
||||
this.started = true;
|
||||
this.setStarted(true);
|
||||
}
|
||||
pause() {
|
||||
this.clock.stop();
|
||||
delete this.origin;
|
||||
this.started = false;
|
||||
logger('[cyclist] pause');
|
||||
this.clock.pause();
|
||||
this.setStarted(false);
|
||||
}
|
||||
stop() {
|
||||
delete this.origin;
|
||||
logger('[cyclist] stop');
|
||||
this.clock.stop();
|
||||
this.started = false;
|
||||
this.setStarted(false);
|
||||
}
|
||||
setPattern(pat, autostart = false) {
|
||||
this.pattern = pat;
|
||||
|
||||
@@ -4,8 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
||||
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 { Tone } from './tone.mjs';
|
||||
import { Pattern } from '@strudel.cycles/core';
|
||||
import { Pattern, getTime, State, TimeSpan } from './index.mjs';
|
||||
|
||||
export const getDrawContext = (id = 'test-canvas') => {
|
||||
let canvas = document.querySelector('#' + id);
|
||||
@@ -28,7 +27,7 @@ Pattern.prototype.draw = function (callback, { from, to, onQuery }) {
|
||||
let cycle,
|
||||
events = [];
|
||||
const animate = (time) => {
|
||||
const t = Tone.getTransport().seconds;
|
||||
const t = getTime();
|
||||
if (from !== undefined && to !== undefined) {
|
||||
const currentCycle = Math.floor(t);
|
||||
if (cycle !== currentCycle) {
|
||||
@@ -50,9 +49,9 @@ Pattern.prototype.draw = function (callback, { from, to, onQuery }) {
|
||||
return this;
|
||||
};
|
||||
|
||||
export const cleanupDraw = () => {
|
||||
export const cleanupDraw = (clearScreen = true) => {
|
||||
const ctx = getDrawContext();
|
||||
ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
|
||||
clearScreen && ctx.clearRect(0, 0, window.innerWidth, window.innerHeight);
|
||||
if (window.strudelAnimation) {
|
||||
cancelAnimationFrame(window.strudelAnimation);
|
||||
}
|
||||
@@ -60,3 +59,9 @@ export const cleanupDraw = () => {
|
||||
clearInterval(window.strudelScheduler);
|
||||
}
|
||||
};
|
||||
|
||||
Pattern.prototype.onPaint = function (onPaint) {
|
||||
// this is evil! TODO: add pattern.context
|
||||
this.context = { onPaint };
|
||||
return this;
|
||||
};
|
||||
+102
-29
@@ -1,47 +1,97 @@
|
||||
/*
|
||||
euclid.mjs - <short description TODO>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/strudel/blob/main/packages/core/euclid.mjs>
|
||||
euclid.mjs - Bjorklund/Euclidean/Diaspora rhythms
|
||||
Copyright (C) 2023 Rohan Drape and strudel contributors
|
||||
|
||||
See <https://github.com/tidalcycles/strudel/blob/main/packages/core/euclid.mjs> for authors of this file.
|
||||
|
||||
The Bjorklund algorithm implementation is ported from the Haskell Music Theory Haskell module by Rohan Drape -
|
||||
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 { Pattern, timeCat } from './pattern.mjs';
|
||||
import bjork from 'bjork';
|
||||
import { rotate } from './util.mjs';
|
||||
import { Pattern, timeCat, register, silence } from './pattern.mjs';
|
||||
import { rotate, flatten } from './util.mjs';
|
||||
import Fraction from './fraction.mjs';
|
||||
|
||||
const euclid = (pulses, steps, rotation = 0) => {
|
||||
const b = bjork(steps, pulses);
|
||||
if (rotation) {
|
||||
return rotate(b, -rotation);
|
||||
}
|
||||
return b;
|
||||
const splitAt = function (index, value) {
|
||||
return [value.slice(0, index), value.slice(index)];
|
||||
};
|
||||
|
||||
const zipWith = (f, xs, ys) => xs.map((n, i) => f(n, ys[i]));
|
||||
|
||||
const left = function (n, x) {
|
||||
const [ons, offs] = n;
|
||||
const [xs, ys] = x;
|
||||
const [_xs, __xs] = splitAt(offs, xs);
|
||||
return [
|
||||
[offs, ons - offs],
|
||||
[zipWith((a, b) => a.concat(b), _xs, ys), __xs],
|
||||
];
|
||||
};
|
||||
|
||||
const right = function (n, x) {
|
||||
const [ons, offs] = n;
|
||||
const [xs, ys] = x;
|
||||
const [_ys, __ys] = splitAt(ons, ys);
|
||||
const result = [
|
||||
[ons, offs - ons],
|
||||
[zipWith((a, b) => a.concat(b), xs, _ys), __ys],
|
||||
];
|
||||
return result;
|
||||
};
|
||||
|
||||
const _bjork = function (n, x) {
|
||||
const [ons, offs] = n;
|
||||
return Math.min(ons, offs) <= 1 ? [n, x] : _bjork(...(ons > offs ? left(n, x) : right(n, x)));
|
||||
};
|
||||
|
||||
export const bjork = function (ons, steps) {
|
||||
const offs = steps - ons;
|
||||
const x = Array(ons).fill([1]);
|
||||
const y = Array(offs).fill([0]);
|
||||
const result = _bjork([ons, offs], [x, y]);
|
||||
return flatten(result[1][0]).concat(flatten(result[1][1]));
|
||||
};
|
||||
|
||||
/**
|
||||
* Changes the structure of the pattern to form an euclidean rhythm.
|
||||
* Euclidian rhythms are rhythms obtained using the greatest common divisor of two numbers.
|
||||
* They were described in 2004 by Godfried Toussaint, a canadian computer scientist.
|
||||
* Euclidian rhythms are really useful for computer/algorithmic music because they can accurately
|
||||
* describe a large number of rhythms used in the most important music world traditions.
|
||||
* Euclidian rhythms are rhythms obtained using the greatest common
|
||||
* divisor of two numbers. They were described in 2004 by Godfried
|
||||
* Toussaint, a canadian computer scientist. Euclidian rhythms are
|
||||
* really useful for computer/algorithmic music because they can
|
||||
* describe a large number of rhythms with a couple of numbers.
|
||||
*
|
||||
* @memberof Pattern
|
||||
* @name euclid
|
||||
* @param {number} pulses the number of onsets / beats
|
||||
* @param {number} steps the number of steps to fill
|
||||
* @param {number} rotation (optional) offset in steps
|
||||
* @returns Pattern
|
||||
* @example
|
||||
* // The Cuban tresillo pattern.
|
||||
* note("c3").euclid(3,8)
|
||||
*/
|
||||
|
||||
/**
|
||||
* Like `euclid`, but has an additional parameter for 'rotating' the resulting sequence.
|
||||
* @memberof Pattern
|
||||
* @name euclidRot
|
||||
* @param {number} pulses the number of onsets / beats
|
||||
* @param {number} steps the number of steps to fill
|
||||
* @param {number} rotation offset in steps
|
||||
* @returns Pattern
|
||||
* @example
|
||||
* // A Samba rhythm necklace from Brazil
|
||||
* note("c3").euclidRot(3,16,14)
|
||||
*/
|
||||
|
||||
/**
|
||||
* @example // A thirteenth century Persian rhythm called Khafif-e-ramal.
|
||||
* note("c3").euclid(2,5)
|
||||
* @example // The archetypal pattern of the Cumbia from Colombia, as well as a Calypso rhythm from Trinidad.
|
||||
* note("c3").euclid(3,4)
|
||||
* @example // Another thirteenth century Persian rhythm by the name of Khafif-e-ramal, as well as a Rumanian folk-dance rhythm.
|
||||
* note("c3").euclid(3,5,2)
|
||||
* note("c3").euclidRot(3,5,2)
|
||||
* @example // A Ruchenitza rhythm used in a Bulgarian folk-dance.
|
||||
* note("c3").euclid(3,7)
|
||||
* @example // The Cuban tresillo pattern.
|
||||
@@ -71,34 +121,57 @@ const euclid = (pulses, steps, rotation = 0) => {
|
||||
* @example // A common West African bell pattern.
|
||||
* note("c3").euclid(7,12)
|
||||
* @example // A Samba rhythm necklace from Brazil.
|
||||
* note("c3").euclid(7,16,14)
|
||||
* note("c3").euclidRot(7,16,14)
|
||||
* @example // A rhythm necklace used in the Central African Republic.
|
||||
* note("c3").euclid(9,16)
|
||||
* @example // A rhythm necklace of the Aka Pygmies of Central Africa.
|
||||
* note("c3").euclid(11,24,14)
|
||||
* note("c3").euclidRot(11,24,14)
|
||||
* @example // Another rhythm necklace of the Aka Pygmies of the upper Sangha.
|
||||
* note("c3").euclid(13,24,5)
|
||||
* note("c3").euclidRot(13,24,5)
|
||||
*/
|
||||
Pattern.prototype.euclid = function (pulses, steps, rotation = 0) {
|
||||
return this.struct(euclid(pulses, steps, rotation));
|
||||
|
||||
const _euclidRot = function (pulses, steps, rotation) {
|
||||
const b = bjork(pulses, steps);
|
||||
if (rotation) {
|
||||
return rotate(b, -rotation);
|
||||
}
|
||||
return b;
|
||||
};
|
||||
|
||||
export const euclid = register('euclid', function (pulses, steps, pat) {
|
||||
return pat.struct(_euclidRot(pulses, steps, 0));
|
||||
});
|
||||
|
||||
export const { euclidrot, euclidRot } = register(['euclidrot', 'euclidRot'], function (pulses, steps, rotation, pat) {
|
||||
return pat.struct(_euclidRot(pulses, steps, rotation));
|
||||
});
|
||||
|
||||
/**
|
||||
* Similar to `.euclid`, but each pulse is held until the next pulse, so there will be no gaps.
|
||||
* Similar to `euclid`, but each pulse is held until the next pulse,
|
||||
* so there will be no gaps.
|
||||
* @name euclidLegato
|
||||
* @memberof Pattern
|
||||
* @example
|
||||
* n("g2").decay(.1).sustain(.3).euclidLegato(3,8)
|
||||
*/
|
||||
Pattern.prototype.euclidLegato = function (pulses, steps, rotation = 0) {
|
||||
const bin_pat = euclid(pulses, steps, rotation);
|
||||
const firstOne = bin_pat.indexOf(1);
|
||||
const gapless = rotate(bin_pat, firstOne)
|
||||
|
||||
const _euclidLegato = function (pulses, steps, rotation, pat) {
|
||||
if (pulses < 1) {
|
||||
return silence;
|
||||
}
|
||||
const bin_pat = _euclidRot(pulses, steps, rotation);
|
||||
const gapless = bin_pat
|
||||
.join('')
|
||||
.split('1')
|
||||
.slice(1)
|
||||
.map((s) => [s.length + 1, true]);
|
||||
return this.struct(timeCat(...gapless)).late(Fraction(firstOne).div(steps));
|
||||
return pat.struct(timeCat(...gapless));
|
||||
};
|
||||
|
||||
export default euclid;
|
||||
export const euclidLegato = register(['euclidLegato'], function (pulses, steps, pat) {
|
||||
return _euclidLegato(pulses, steps, 0, pat);
|
||||
});
|
||||
|
||||
export const euclidLegatoRot = register(['euclidLegatoRot'], function (pulses, steps, rotation, pat) {
|
||||
return _euclidLegato(pulses, steps, rotation, pat);
|
||||
});
|
||||
|
||||
@@ -4,9 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
||||
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 * as strudel from '@strudel.cycles/core';
|
||||
|
||||
const { isPattern, Pattern } = strudel;
|
||||
import { isPattern } from './index.mjs';
|
||||
|
||||
let scoped = false;
|
||||
export const evalScope = async (...args) => {
|
||||
@@ -21,7 +19,14 @@ export const evalScope = async (...args) => {
|
||||
console.warn(`evalScope: module with index ${i} could not be loaded:`, result.reason);
|
||||
}
|
||||
});
|
||||
Object.assign(globalThis, ...modules, Pattern.prototype.bootstrap());
|
||||
// Object.assign(globalThis, ...modules);
|
||||
// below is a fix for above commented out line
|
||||
// same error as https://github.com/vitest-dev/vitest/issues/1807 when running this on astro server
|
||||
modules.forEach((module) => {
|
||||
Object.entries(module).forEach(([name, value]) => {
|
||||
globalThis[name] = value;
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
function safeEval(str, options = {}) {
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Buildless Vanilla Strudel REPL</title>
|
||||
</head>
|
||||
<body style="margin: 0; background: #222">
|
||||
<div style="display: grid; height: 100vh">
|
||||
<textarea
|
||||
id="text"
|
||||
style="font-size: 2em; border: 0; color: white; background: transparent; outline: none; padding: 20px"
|
||||
spellcheck="false"
|
||||
></textarea>
|
||||
</div>
|
||||
<button
|
||||
id="start"
|
||||
style="
|
||||
position: absolute;
|
||||
border-radius: 10px;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
padding: 20px;
|
||||
border: 2px solid white;
|
||||
background: transparent;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
"
|
||||
>
|
||||
evaluate
|
||||
</button>
|
||||
<div id="output"></div>
|
||||
<script type="module">
|
||||
import { controls, repl, evalScope } from 'https://cdn.skypack.dev/@strudel.cycles/core@0.3.2';
|
||||
import { mini } from 'https://cdn.skypack.dev/@strudel.cycles/mini@0.3.2';
|
||||
import { transpiler } from 'https://cdn.skypack.dev/@strudel.cycles/transpiler@0.3.2';
|
||||
import { getAudioContext, webaudioOutput } from 'https://cdn.skypack.dev/@strudel.cycles/webaudio@0.3.3';
|
||||
|
||||
const ctx = getAudioContext();
|
||||
const input = document.getElementById('text');
|
||||
input.innerHTML = getTune();
|
||||
|
||||
evalScope(
|
||||
controls,
|
||||
import('https://cdn.skypack.dev/@strudel.cycles/core@0.3.2'),
|
||||
import('https://cdn.skypack.dev/@strudel.cycles/mini@0.3.2'),
|
||||
import('https://cdn.skypack.dev/@strudel.cycles/tonal@0.3.3'),
|
||||
import('https://cdn.skypack.dev/@strudel.cycles/webaudio@0.3.3'),
|
||||
);
|
||||
|
||||
const { evaluate } = repl({
|
||||
defaultOutput: webaudioOutput,
|
||||
getTime: () => ctx.currentTime,
|
||||
transpiler,
|
||||
});
|
||||
document.getElementById('start').addEventListener('click', () => {
|
||||
ctx.resume();
|
||||
evaluate(input.value);
|
||||
});
|
||||
|
||||
function getTune() {
|
||||
return `await samples('github:tidalcycles/Dirt-Samples/master')
|
||||
|
||||
stack(
|
||||
// amen
|
||||
n("0 1 2 3 4 5 6 7")
|
||||
.sometimes(x=>x.ply(2))
|
||||
.rarely(x=>x.speed("2 | -2"))
|
||||
.sometimesBy(.4, x=>x.delay(".5"))
|
||||
.s("amencutup")
|
||||
.slow(2)
|
||||
.room(.5)
|
||||
,
|
||||
// bass
|
||||
sine.add(saw.slow(4)).range(0,7).segment(8)
|
||||
.superimpose(x=>x.add(.1))
|
||||
.scale('G0 minor').note()
|
||||
.s("sawtooth").decay(.1).sustain(0)
|
||||
.gain(.4).cutoff(perlin.range(300,3000).slow(8)).resonance(10)
|
||||
.degradeBy("0 0.1 .5 .1")
|
||||
.rarely(add(note("12")))
|
||||
,
|
||||
// chord
|
||||
note("Bb3,D4".superimpose(x=>x.add(.2)))
|
||||
.s('sawtooth').cutoff(1000).struct("<~@3 [~ x]>")
|
||||
.decay(.05).sustain(.0).delay(.8).delaytime(.125).room(.8)
|
||||
,
|
||||
// alien
|
||||
s("breath").room(1).shape(.6).chop(16).rev().mask("<x ~@7>")
|
||||
,
|
||||
n("0 1").s("east").delay(.5).degradeBy(.8).speed(rand.range(.5,1.5))
|
||||
).reset("<x@7 x(5,8)>")`;
|
||||
}
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -16,7 +16,7 @@ evalScope(
|
||||
import('@strudel.cycles/tonal'),
|
||||
);
|
||||
|
||||
setStringParser(mini)
|
||||
setStringParser(mini);
|
||||
|
||||
const { evaluate } = repl({
|
||||
defaultOutput: webaudioOutput,
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Buildless Vanilla Strudel REPL</title>
|
||||
</head>
|
||||
<body style="margin: 0; background: #222">
|
||||
<div style="display: grid; height: 100vh">
|
||||
<textarea
|
||||
id="text"
|
||||
style="font-size: 2em; border: 0; color: white; background: transparent; outline: none; padding: 20px"
|
||||
spellcheck="false"
|
||||
>
|
||||
// LOADING</textarea
|
||||
>
|
||||
</div>
|
||||
<button
|
||||
id="start"
|
||||
style="
|
||||
position: absolute;
|
||||
border-radius: 10px;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
padding: 20px;
|
||||
border: 2px solid white;
|
||||
background: transparent;
|
||||
color: white;
|
||||
cursor: pointer;
|
||||
"
|
||||
>
|
||||
evaluate
|
||||
</button>
|
||||
<div id="output"></div>
|
||||
<script type="module">
|
||||
import { controls, repl, evalScope } from 'https://cdn.skypack.dev/@strudel.cycles/core@0.4.1';
|
||||
import { transpiler } from 'https://cdn.skypack.dev/@strudel.cycles/transpiler@0.4.1';
|
||||
|
||||
const modules = [
|
||||
import('https://cdn.skypack.dev/@strudel.cycles/core@0.4.1'),
|
||||
import('https://cdn.skypack.dev/@strudel.cycles/mini@0.4.1'),
|
||||
];
|
||||
|
||||
const input = document.getElementById('text');
|
||||
|
||||
Promise.all(modules).then(() => {
|
||||
input.innerHTML = `note("<c3 [d3 e3]>").cutoff(1000)`;
|
||||
document.getElementById('start').addEventListener('click', () => {
|
||||
evaluate(input.value);
|
||||
});
|
||||
});
|
||||
evalScope(controls, ...modules);
|
||||
|
||||
const { evaluate } = repl({
|
||||
defaultOutput: (hap, deadline, duration) => {
|
||||
console.log(deadline, duration, hap.value);
|
||||
},
|
||||
getTime: () => Date.now() / 1000,
|
||||
transpiler,
|
||||
beforeEval: (code) => console.log('evaluate', code),
|
||||
afterEval: (code) => {},
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -55,7 +55,8 @@ Fraction.prototype.min = function (other) {
|
||||
return this.lt(other) ? this : other;
|
||||
};
|
||||
|
||||
Fraction.prototype.show = function () {
|
||||
Fraction.prototype.show = function (/* excludeWhole = false */) {
|
||||
// return this.toFraction(excludeWhole);
|
||||
return this.s * this.n + '/' + this.d;
|
||||
};
|
||||
|
||||
@@ -73,7 +74,7 @@ const fraction = (n) => {
|
||||
-> those farey sequences turn out to make pattern querying ~20 times slower! always use strings!
|
||||
-> still, some optimizations could be done: .mul .div .add .sub calls still use numbers
|
||||
*/
|
||||
n = String(n);
|
||||
// n = String(n); // this is actually faster but imprecise...
|
||||
}
|
||||
return Fraction(n);
|
||||
};
|
||||
|
||||
+33
-6
@@ -79,15 +79,42 @@ export class Hap {
|
||||
);
|
||||
}
|
||||
|
||||
show() {
|
||||
return (
|
||||
'(' + (this.whole == undefined ? '~' : this.whole.show()) + ', ' + this.part.show() + ', ' + this.value + ')'
|
||||
);
|
||||
show(compact = false) {
|
||||
const value =
|
||||
typeof this.value === 'object'
|
||||
? compact
|
||||
? JSON.stringify(this.value).slice(1, -1).replaceAll('"', '').replaceAll(',', ' ')
|
||||
: JSON.stringify(this.value)
|
||||
: this.value;
|
||||
var spans = '';
|
||||
if (this.whole == undefined) {
|
||||
spans = '~' + this.part.show;
|
||||
} else {
|
||||
var is_whole = this.whole.begin.equals(this.part.begin) && this.whole.end.equals(this.part.end);
|
||||
if (!this.whole.begin.equals(this.part.begin)) {
|
||||
spans = this.whole.begin.show() + ' ⇜ ';
|
||||
}
|
||||
if (!is_whole) {
|
||||
spans += '(';
|
||||
}
|
||||
spans += this.part.show();
|
||||
if (!is_whole) {
|
||||
spans += ')';
|
||||
}
|
||||
if (!this.whole.end.equals(this.part.end)) {
|
||||
spans += ' ⇝ ' + this.whole.end.show();
|
||||
}
|
||||
}
|
||||
return '[ ' + spans + ' | ' + value + ' ]';
|
||||
}
|
||||
|
||||
showWhole() {
|
||||
showWhole(compact = false) {
|
||||
return `${this.whole == undefined ? '~' : this.whole.show()}: ${
|
||||
typeof this.value === 'object' ? JSON.stringify(this.value) : this.value
|
||||
typeof this.value === 'object'
|
||||
? compact
|
||||
? JSON.stringify(this.value).slice(1, -1).replaceAll('"', '').replaceAll(',', ' ')
|
||||
: JSON.stringify(this.value)
|
||||
: this.value
|
||||
}`;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
import controls from './controls.mjs';
|
||||
export * from './euclid.mjs';
|
||||
import Fraction from './fraction.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
export { Fraction, controls };
|
||||
export * from './hap.mjs';
|
||||
export * from './pattern.mjs';
|
||||
@@ -17,15 +18,18 @@ export * from './util.mjs';
|
||||
export * from './speak.mjs';
|
||||
export * from './evaluate.mjs';
|
||||
export * from './repl.mjs';
|
||||
export * from './logger.mjs';
|
||||
export * from './time.mjs';
|
||||
export * from './draw.mjs';
|
||||
export * from './animate.mjs';
|
||||
export * from './pianoroll.mjs';
|
||||
export * from './ui.mjs';
|
||||
export { default as drawLine } from './drawLine.mjs';
|
||||
export { default as gist } from './gist.js';
|
||||
// below won't work with runtime.mjs (json import fails)
|
||||
/* import * as p from './package.json';
|
||||
export const version = p.version; */
|
||||
console.log(
|
||||
'%c // 🌀 @strudel.cycles/core loaded 🌀', // keep "//" for runnable snapshot source..
|
||||
'background-color: black;color:white;padding:4px;border-radius:15px',
|
||||
);
|
||||
logger('🌀 @strudel.cycles/core loaded 🌀');
|
||||
if (globalThis._strudelLoaded) {
|
||||
console.warn(
|
||||
`@strudel.cycles/core was loaded more than once...
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
export const logKey = 'strudel.log';
|
||||
|
||||
export function logger(message, type, data = {}) {
|
||||
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;
|
||||
Generated
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/core",
|
||||
"version": "0.3.2",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/core",
|
||||
"version": "0.3.2",
|
||||
"version": "0.5.0",
|
||||
"description": "Port of Tidal Cycles to JavaScript",
|
||||
"main": "index.mjs",
|
||||
"type": "module",
|
||||
@@ -25,7 +25,6 @@
|
||||
},
|
||||
"homepage": "https://strudel.tidalcycles.org",
|
||||
"dependencies": {
|
||||
"bjork": "^0.0.1",
|
||||
"fraction.js": "^4.2.0"
|
||||
},
|
||||
"gitHead": "0e26d4e741500f5bae35b023608f062a794905c2"
|
||||
|
||||
+1585
-1251
File diff suppressed because it is too large
Load Diff
@@ -4,13 +4,27 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
||||
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 '@strudel.cycles/core';
|
||||
import { Pattern, toMidi, getDrawContext, freqToMidi, isNote } from './index.mjs';
|
||||
|
||||
const scale = (normalized, min, max) => normalized * (max - min) + min;
|
||||
const getValue = (e) => {
|
||||
let value = typeof e.value === 'object' ? e.value.note ?? e.value.n : e.value;
|
||||
if (typeof value === 'string') {
|
||||
value = toMidi(value);
|
||||
let { value } = e;
|
||||
if (typeof e.value !== 'object') {
|
||||
value = { value };
|
||||
}
|
||||
let { note, n, freq, s } = value;
|
||||
if (freq) {
|
||||
return freqToMidi(freq);
|
||||
}
|
||||
note = note ?? n;
|
||||
if (typeof note === 'string') {
|
||||
return toMidi(note);
|
||||
}
|
||||
if (typeof note === 'number') {
|
||||
return note;
|
||||
}
|
||||
if (s) {
|
||||
return '_' + s;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
@@ -48,9 +62,6 @@ Pattern.prototype.pianoroll = function ({
|
||||
from = 0;
|
||||
to = timeframeProp;
|
||||
}
|
||||
if (!autorange && fold) {
|
||||
console.warn('disabling autorange has no effect when fold is enabled');
|
||||
}
|
||||
const timeAxis = vertical ? h : w;
|
||||
const valueAxis = vertical ? w : h;
|
||||
let timeRange = vertical ? [timeAxis, 0] : [0, timeAxis]; // pixel range for time
|
||||
@@ -138,10 +149,149 @@ Pattern.prototype.pianoroll = function ({
|
||||
maxMidi = max;
|
||||
valueExtent = maxMidi - minMidi + 1;
|
||||
}
|
||||
foldValues = values.sort((a, b) => a - b);
|
||||
foldValues = values.sort((a, b) => String(a).localeCompare(String(b)));
|
||||
barThickness = fold ? valueAxis / foldValues.length : valueAxis / valueExtent;
|
||||
},
|
||||
},
|
||||
);
|
||||
return this;
|
||||
};
|
||||
|
||||
// this function allows drawing a pianoroll without ties to Pattern.prototype
|
||||
// it will probably replace the above in the future
|
||||
export function pianoroll({
|
||||
time,
|
||||
haps,
|
||||
cycles = 4,
|
||||
playhead = 0.5,
|
||||
flipTime = 0,
|
||||
flipValues = 0,
|
||||
hideNegative = false,
|
||||
// inactive = '#C9E597',
|
||||
// inactive = '#FFCA28',
|
||||
inactive = '#7491D2',
|
||||
active = '#FFCA28',
|
||||
// background = '#2A3236',
|
||||
background = 'transparent',
|
||||
smear = 0,
|
||||
playheadColor = 'white',
|
||||
minMidi = 10,
|
||||
maxMidi = 90,
|
||||
autorange = 0,
|
||||
timeframe: timeframeProp,
|
||||
fold = 0,
|
||||
vertical = 0,
|
||||
ctx,
|
||||
} = {}) {
|
||||
const w = ctx.canvas.width;
|
||||
const h = ctx.canvas.height;
|
||||
let from = -cycles * playhead;
|
||||
let to = cycles * (1 - playhead);
|
||||
|
||||
if (timeframeProp) {
|
||||
console.warn('timeframe is deprecated! use from/to instead');
|
||||
from = 0;
|
||||
to = timeframeProp;
|
||||
}
|
||||
const timeAxis = vertical ? h : w;
|
||||
const valueAxis = vertical ? w : h;
|
||||
let timeRange = vertical ? [timeAxis, 0] : [0, timeAxis]; // pixel range for time
|
||||
const timeExtent = to - from; // number of seconds that fit inside the canvas frame
|
||||
const valueRange = vertical ? [0, valueAxis] : [valueAxis, 0]; // pixel range for values
|
||||
let valueExtent = maxMidi - minMidi + 1; // number of "slots" for values, overwritten if autorange true
|
||||
let barThickness = valueAxis / valueExtent; // pixels per value, overwritten if autorange true
|
||||
let foldValues = [];
|
||||
flipTime && timeRange.reverse();
|
||||
flipValues && valueRange.reverse();
|
||||
|
||||
// onQuery
|
||||
const { min, max, values } = haps.reduce(
|
||||
({ min, max, values }, e) => {
|
||||
const v = getValue(e);
|
||||
return {
|
||||
min: v < min ? v : min,
|
||||
max: v > max ? v : max,
|
||||
values: values.includes(v) ? values : [...values, v],
|
||||
};
|
||||
},
|
||||
{ min: Infinity, max: -Infinity, values: [] },
|
||||
);
|
||||
if (autorange) {
|
||||
minMidi = min;
|
||||
maxMidi = max;
|
||||
valueExtent = maxMidi - minMidi + 1;
|
||||
}
|
||||
// foldValues = values.sort((a, b) => a - b);
|
||||
foldValues = values.sort((a, b) => String(a).localeCompare(String(b)));
|
||||
barThickness = fold ? valueAxis / foldValues.length : valueAxis / valueExtent;
|
||||
|
||||
ctx.fillStyle = background;
|
||||
ctx.globalAlpha = 1; // reset!
|
||||
if (!smear) {
|
||||
ctx.clearRect(0, 0, w, h);
|
||||
ctx.fillRect(0, 0, w, h);
|
||||
}
|
||||
/* const inFrame = (event) =>
|
||||
(!hideNegative || event.whole.begin >= 0) && event.whole.begin <= time + to && event.whole.end >= time + from; */
|
||||
haps
|
||||
// .filter(inFrame)
|
||||
.forEach((event) => {
|
||||
const isActive = event.whole.begin <= time && event.whole.end > time;
|
||||
const color = event.value?.color || event.context?.color;
|
||||
ctx.fillStyle = color || inactive;
|
||||
ctx.strokeStyle = color || active;
|
||||
ctx.globalAlpha = event.context.velocity ?? 1;
|
||||
const timePx = scale((event.whole.begin - (flipTime ? to : from)) / timeExtent, ...timeRange);
|
||||
let durationPx = scale(event.duration / timeExtent, 0, timeAxis);
|
||||
const value = getValue(event);
|
||||
const valuePx = scale(
|
||||
fold ? foldValues.indexOf(value) / foldValues.length : (Number(value) - minMidi) / valueExtent,
|
||||
...valueRange,
|
||||
);
|
||||
let margin = 0;
|
||||
const offset = scale(time / timeExtent, ...timeRange);
|
||||
let coords;
|
||||
if (vertical) {
|
||||
coords = [
|
||||
valuePx + 1 - (flipValues ? barThickness : 0), // x
|
||||
timeAxis - offset + timePx + margin + 1 - (flipTime ? 0 : durationPx), // y
|
||||
barThickness - 2, // width
|
||||
durationPx - 2, // height
|
||||
];
|
||||
} else {
|
||||
coords = [
|
||||
timePx - offset + margin + 1 - (flipTime ? durationPx : 0), // x
|
||||
valuePx + 1 - (flipValues ? 0 : barThickness), // y
|
||||
durationPx - 2, // widith
|
||||
barThickness - 2, // height
|
||||
];
|
||||
}
|
||||
isActive ? ctx.strokeRect(...coords) : ctx.fillRect(...coords);
|
||||
});
|
||||
ctx.globalAlpha = 1; // reset!
|
||||
const playheadPosition = scale(-from / timeExtent, ...timeRange);
|
||||
// draw playhead
|
||||
ctx.strokeStyle = playheadColor;
|
||||
ctx.beginPath();
|
||||
if (vertical) {
|
||||
ctx.moveTo(0, playheadPosition);
|
||||
ctx.lineTo(valueAxis, playheadPosition);
|
||||
} else {
|
||||
ctx.moveTo(playheadPosition, 0);
|
||||
ctx.lineTo(playheadPosition, valueAxis);
|
||||
}
|
||||
ctx.stroke();
|
||||
return this;
|
||||
}
|
||||
|
||||
function getOptions(drawTime, options = {}) {
|
||||
let [lookbehind, lookahead] = drawTime;
|
||||
lookbehind = Math.abs(lookbehind);
|
||||
const cycles = lookahead + lookbehind;
|
||||
const playhead = lookbehind / cycles;
|
||||
return { fold: 1, ...options, cycles, playhead };
|
||||
}
|
||||
|
||||
Pattern.prototype.punchcard = function (options) {
|
||||
return this.onPaint((ctx, time, haps, drawTime) => pianoroll({ ctx, time, haps, ...getOptions(drawTime, options) }));
|
||||
};
|
||||
+50
-11
@@ -1,23 +1,62 @@
|
||||
import { Cyclist } from './cyclist.mjs';
|
||||
import { evaluate as _evaluate } from './evaluate.mjs';
|
||||
import { logger } from './logger.mjs';
|
||||
import { setTime } from './time.mjs';
|
||||
|
||||
export function repl({ interval, defaultOutput, onSchedulerError, onEvalError, onEval, getTime, transpiler }) {
|
||||
const scheduler = new Cyclist({ interval, onTrigger: defaultOutput, onError: onSchedulerError, getTime });
|
||||
const evaluate = async (code) => {
|
||||
export function repl({
|
||||
interval,
|
||||
defaultOutput,
|
||||
onSchedulerError,
|
||||
onEvalError,
|
||||
beforeEval,
|
||||
afterEval,
|
||||
getTime,
|
||||
transpiler,
|
||||
onToggle,
|
||||
editPattern,
|
||||
}) {
|
||||
const scheduler = new Cyclist({
|
||||
interval,
|
||||
onTrigger: async (hap, deadline, duration) => {
|
||||
try {
|
||||
if (!hap.context.onTrigger || !hap.context.dominantTrigger) {
|
||||
await defaultOutput(hap, deadline, duration);
|
||||
}
|
||||
if (hap.context.onTrigger) {
|
||||
const cps = 1;
|
||||
// call signature of output / onTrigger is different...
|
||||
await hap.context.onTrigger(getTime() + deadline, hap, getTime(), cps);
|
||||
}
|
||||
} catch (err) {
|
||||
logger(`[cyclist] error: ${err.message}`, 'error');
|
||||
}
|
||||
},
|
||||
onError: onSchedulerError,
|
||||
getTime,
|
||||
onToggle,
|
||||
});
|
||||
setTime(() => scheduler.now()); // TODO: refactor?
|
||||
const evaluate = async (code, autostart = true) => {
|
||||
if (!code) {
|
||||
throw new Error('no code to evaluate');
|
||||
}
|
||||
try {
|
||||
const { pattern } = await _evaluate(code, transpiler);
|
||||
scheduler.setPattern(pattern, true);
|
||||
onEval?.({
|
||||
pattern,
|
||||
code,
|
||||
});
|
||||
beforeEval?.({ code });
|
||||
let { pattern } = await _evaluate(code, transpiler);
|
||||
|
||||
logger(`[eval] code updated`);
|
||||
pattern = editPattern?.(pattern) || pattern;
|
||||
scheduler.setPattern(pattern, autostart);
|
||||
afterEval?.({ code, pattern });
|
||||
return pattern;
|
||||
} catch (err) {
|
||||
console.warn(`eval error: ${err.message}`);
|
||||
// console.warn(`[repl] eval error: ${err.message}`);
|
||||
logger(`[eval] error: ${err.message}`, 'error');
|
||||
onEvalError?.(err);
|
||||
}
|
||||
};
|
||||
return { scheduler, evaluate };
|
||||
const stop = () => scheduler.stop();
|
||||
const start = () => scheduler.start();
|
||||
const pause = () => scheduler.pause();
|
||||
return { scheduler, evaluate, start, stop, pause };
|
||||
}
|
||||
|
||||
+54
-88
@@ -5,7 +5,7 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
*/
|
||||
|
||||
import { Hap } from './hap.mjs';
|
||||
import { Pattern, fastcat, reify, silence, stack, isPattern } from './pattern.mjs';
|
||||
import { Pattern, fastcat, reify, silence, stack, register } from './pattern.mjs';
|
||||
import Fraction from './fraction.mjs';
|
||||
import { id } from './util.mjs';
|
||||
|
||||
@@ -20,7 +20,7 @@ export const signal = (func) => {
|
||||
};
|
||||
|
||||
export const isaw = signal((t) => 1 - (t % 1));
|
||||
export const isaw2 = isaw._toBipolar();
|
||||
export const isaw2 = isaw.toBipolar();
|
||||
|
||||
/**
|
||||
* A sawtooth signal between 0 and 1.
|
||||
@@ -33,7 +33,7 @@ export const isaw2 = isaw._toBipolar();
|
||||
*
|
||||
*/
|
||||
export const saw = signal((t) => t % 1);
|
||||
export const saw2 = saw._toBipolar();
|
||||
export const saw2 = saw.toBipolar();
|
||||
|
||||
export const sine2 = signal((t) => Math.sin(Math.PI * 2 * t));
|
||||
|
||||
@@ -45,7 +45,7 @@ export const sine2 = signal((t) => Math.sin(Math.PI * 2 * t));
|
||||
* sine.segment(16).range(0,15).slow(2).scale('C minor').note()
|
||||
*
|
||||
*/
|
||||
export const sine = sine2._fromBipolar();
|
||||
export const sine = sine2.fromBipolar();
|
||||
|
||||
/**
|
||||
* A cosine signal between 0 and 1.
|
||||
@@ -67,7 +67,7 @@ export const cosine2 = sine2._early(Fraction(1).div(4));
|
||||
*
|
||||
*/
|
||||
export const square = signal((t) => Math.floor((t * 2) % 2));
|
||||
export const square2 = square._toBipolar();
|
||||
export const square2 = square.toBipolar();
|
||||
|
||||
/**
|
||||
* A triangle signal between 0 and 1.
|
||||
@@ -127,7 +127,7 @@ export const rand = signal(timeToRand);
|
||||
/**
|
||||
* A continuous pattern of random numbers, between -1 and 1
|
||||
*/
|
||||
export const rand2 = rand._toBipolar();
|
||||
export const rand2 = rand.toBipolar();
|
||||
|
||||
export const _brandBy = (p) => rand.fmap((x) => x < p);
|
||||
export const brandBy = (pPat) => reify(pPat).fmap(_brandBy).innerJoin();
|
||||
@@ -201,7 +201,7 @@ Pattern.prototype.choose = function (...xs) {
|
||||
* @returns {Pattern}
|
||||
*/
|
||||
Pattern.prototype.choose2 = function (...xs) {
|
||||
return chooseWith(this._fromBipolar(), xs);
|
||||
return chooseWith(this.fromBipolar(), xs);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -258,9 +258,9 @@ export const perlinWith = (pat) => {
|
||||
*/
|
||||
export const perlin = perlinWith(time.fmap((v) => Number(v)));
|
||||
|
||||
Pattern.prototype._degradeByWith = function (withPat, x) {
|
||||
return this.fmap((a) => (_) => a).appLeft(withPat._filterValues((v) => v > x));
|
||||
};
|
||||
export const degradeByWith = register('degradeByWith', (withPat, x, pat) =>
|
||||
pat.fmap((a) => (_) => a).appLeft(withPat.filterValues((v) => v > x)),
|
||||
);
|
||||
|
||||
/**
|
||||
* Randomly removes events from the pattern by a given amount.
|
||||
@@ -276,9 +276,9 @@ Pattern.prototype._degradeByWith = function (withPat, x) {
|
||||
* @example
|
||||
* s("[hh?0.2]*8")
|
||||
*/
|
||||
Pattern.prototype._degradeBy = function (x) {
|
||||
return this._degradeByWith(rand, x);
|
||||
};
|
||||
export const degradeBy = register('degradeBy', function (x, pat) {
|
||||
return pat._degradeByWith(rand, x);
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -292,9 +292,7 @@ Pattern.prototype._degradeBy = function (x) {
|
||||
* @example
|
||||
* s("[hh?]*8")
|
||||
*/
|
||||
Pattern.prototype.degrade = function () {
|
||||
return this._degradeBy(0.5);
|
||||
};
|
||||
export const degrade = register('degrade', (pat) => pat._degradeBy(0.5));
|
||||
|
||||
/**
|
||||
* Inverse of {@link Pattern#degradeBy}: Randomly removes events from the pattern by a given amount.
|
||||
@@ -309,26 +307,14 @@ Pattern.prototype.degrade = function () {
|
||||
* @example
|
||||
* s("hh*8").undegradeBy(0.2)
|
||||
*/
|
||||
Pattern.prototype._undegradeBy = function (x) {
|
||||
return this._degradeByWith(
|
||||
export const undegradeBy = register('undegradeBy', function (x, pat) {
|
||||
return pat._degradeByWith(
|
||||
rand.fmap((r) => 1 - r),
|
||||
x,
|
||||
);
|
||||
};
|
||||
});
|
||||
|
||||
Pattern.prototype.undegrade = function () {
|
||||
return this._undegradeBy(0.5);
|
||||
};
|
||||
|
||||
Pattern.prototype._sometimesBy = function (x, func) {
|
||||
return stack(this._degradeBy(x), func(this._undegradeBy(1 - x)));
|
||||
};
|
||||
|
||||
// https://github.com/tidalcycles/strudel/discussions/198
|
||||
/* Pattern.prototype._sometimesBy = function (x, other) {
|
||||
other = typeof other === 'function' ? other(this._undegradeBy(1 - x)) : reify(other)._undegradeBy(1 - x);
|
||||
return stack(this._degradeBy(x), other);
|
||||
}; */
|
||||
export const undegrade = register('undegrade', (pat) => pat._undegradeBy(0.5));
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -343,24 +329,12 @@ Pattern.prototype._sometimesBy = function (x, func) {
|
||||
* @example
|
||||
* s("hh(3,8)").sometimesBy(.4, x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.sometimesBy = function (patx, func) {
|
||||
const pat = this;
|
||||
return reify(patx)
|
||||
.fmap((x) => pat._sometimesBy(x, func))
|
||||
.innerJoin();
|
||||
};
|
||||
|
||||
// why does this exist? it is identical to sometimesBy
|
||||
Pattern.prototype._sometimesByPre = function (x, func) {
|
||||
return stack(this._degradeBy(x), func(this).undegradeBy(1 - x));
|
||||
};
|
||||
|
||||
Pattern.prototype.sometimesByPre = function (patx, func) {
|
||||
const pat = this;
|
||||
export const sometimesBy = register('sometimesBy', function (patx, func, pat) {
|
||||
return reify(patx)
|
||||
.fmap((x) => pat._sometimesByPre(x, func))
|
||||
.fmap((x) => stack(pat._degradeBy(x), func(pat._undegradeBy(1 - x))))
|
||||
.innerJoin();
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -373,20 +347,9 @@ Pattern.prototype.sometimesByPre = function (patx, func) {
|
||||
* @example
|
||||
* s("hh*4").sometimes(x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.sometimes = function (func) {
|
||||
return this._sometimesBy(0.5, func);
|
||||
};
|
||||
|
||||
Pattern.prototype.sometimesPre = function (func) {
|
||||
return this._sometimesByPre(0.5, func);
|
||||
};
|
||||
|
||||
Pattern.prototype._someCyclesBy = function (x, func) {
|
||||
return stack(
|
||||
this._degradeByWith(rand._segment(1), x),
|
||||
func(this._degradeByWith(rand.fmap((r) => 1 - r)._segment(1), 1 - x)),
|
||||
);
|
||||
};
|
||||
export const sometimes = register('sometimes', function (func, pat) {
|
||||
return pat._sometimesBy(0.5, func);
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -401,12 +364,17 @@ Pattern.prototype._someCyclesBy = function (x, func) {
|
||||
* @example
|
||||
* s("hh(3,8)").someCyclesBy(.3, x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.someCyclesBy = function (patx, func) {
|
||||
const pat = this;
|
||||
|
||||
export const someCyclesBy = register('someCyclesBy', function (patx, func, pat) {
|
||||
return reify(patx)
|
||||
.fmap((x) => pat._someCyclesBy(x, func))
|
||||
.fmap((x) =>
|
||||
stack(
|
||||
pat._degradeByWith(rand._segment(1), x),
|
||||
func(pat._degradeByWith(rand.fmap((r) => 1 - r)._segment(1), 1 - x)),
|
||||
),
|
||||
)
|
||||
.innerJoin();
|
||||
};
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -418,9 +386,9 @@ Pattern.prototype.someCyclesBy = function (patx, func) {
|
||||
* @example
|
||||
* s("hh(3,8)").someCycles(x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.someCycles = function (func) {
|
||||
return this._someCyclesBy(0.5, func);
|
||||
};
|
||||
export const someCycles = register('someCycles', function (func, pat) {
|
||||
return pat._someCyclesBy(0.5, func);
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -432,9 +400,9 @@ Pattern.prototype.someCycles = function (func) {
|
||||
* @example
|
||||
* s("hh*8").often(x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.often = function (func) {
|
||||
return this.sometimesBy(0.75, func);
|
||||
};
|
||||
export const often = register('often', function (func, pat) {
|
||||
return pat.sometimesBy(0.75, func);
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -446,9 +414,9 @@ Pattern.prototype.often = function (func) {
|
||||
* @example
|
||||
* s("hh*8").rarely(x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.rarely = function (func) {
|
||||
return this.sometimesBy(0.25, func);
|
||||
};
|
||||
export const rarely = register('rarely', function (func, pat) {
|
||||
return pat.sometimesBy(0.25, func);
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -460,9 +428,9 @@ Pattern.prototype.rarely = function (func) {
|
||||
* @example
|
||||
* s("hh*8").almostNever(x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.almostNever = function (func) {
|
||||
return this.sometimesBy(0.1, func);
|
||||
};
|
||||
export const almostNever = register('almostNever', function (func, pat) {
|
||||
return pat.sometimesBy(0.1, func);
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -474,9 +442,9 @@ Pattern.prototype.almostNever = function (func) {
|
||||
* @example
|
||||
* s("hh*8").almostAlways(x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.almostAlways = function (func) {
|
||||
return this.sometimesBy(0.9, func);
|
||||
};
|
||||
export const almostAlways = register('almostAlways', function (func, pat) {
|
||||
return pat.sometimesBy(0.9, func);
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -488,9 +456,9 @@ Pattern.prototype.almostAlways = function (func) {
|
||||
* @example
|
||||
* s("hh*8").never(x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.never = function (func) {
|
||||
return this;
|
||||
};
|
||||
export const never = register('never', function (_, pat) {
|
||||
return pat;
|
||||
});
|
||||
|
||||
/**
|
||||
*
|
||||
@@ -502,8 +470,6 @@ Pattern.prototype.never = function (func) {
|
||||
* @example
|
||||
* s("hh*8").always(x=>x.speed("0.5"))
|
||||
*/
|
||||
Pattern.prototype.always = function (func) {
|
||||
return func(this);
|
||||
};
|
||||
|
||||
Pattern.prototype.patternified.push('degradeBy', 'undegradeBy');
|
||||
export const always = register('always', function (func, pat) {
|
||||
return func(pat);
|
||||
});
|
||||
|
||||
+6
-13
@@ -4,7 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
||||
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, patternify2 } from './index.mjs';
|
||||
import { register } from './index.mjs';
|
||||
|
||||
let synth;
|
||||
try {
|
||||
@@ -16,7 +16,7 @@ try {
|
||||
let allVoices = synth?.getVoices();
|
||||
// console.log('voices', allVoices);
|
||||
|
||||
function speak(words, lang, voice) {
|
||||
function triggerSpeech(words, lang, voice) {
|
||||
synth.cancel();
|
||||
const utterance = new SpeechSynthesisUtterance(words);
|
||||
utterance.lang = lang;
|
||||
@@ -31,15 +31,8 @@ function speak(words, lang, voice) {
|
||||
speechSynthesis.speak(utterance);
|
||||
}
|
||||
|
||||
Pattern.prototype._speak = function (lang, voice) {
|
||||
return this._withHap((hap) => {
|
||||
const onTrigger = (time, hap) => {
|
||||
speak(hap.value, lang, voice);
|
||||
};
|
||||
return hap.setContext({ ...hap.context, onTrigger });
|
||||
export const speak = register('speak', function (lang, voice, pat) {
|
||||
return pat.onTrigger((_, hap) => {
|
||||
triggerSpeech(hap.value, lang, voice);
|
||||
});
|
||||
};
|
||||
|
||||
Pattern.prototype.speak = function (lang, voice) {
|
||||
return patternify2(Pattern.prototype._speak)(reify(lang), reify(voice), this);
|
||||
};
|
||||
});
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
pure,
|
||||
stack,
|
||||
fastcat,
|
||||
firstOf,
|
||||
slowcat,
|
||||
cat,
|
||||
sequence,
|
||||
@@ -49,7 +50,7 @@ import { steady } from '../signal.mjs';
|
||||
|
||||
import controls from '../controls.mjs';
|
||||
|
||||
const { n } = controls;
|
||||
const { n, s } = controls;
|
||||
const st = (begin, end) => new State(ts(begin, end));
|
||||
const ts = (begin, end) => new TimeSpan(Fraction(begin), Fraction(end));
|
||||
const hap = (whole, part, value, context = {}) => new Hap(whole, part, value, context);
|
||||
@@ -58,7 +59,7 @@ const third = Fraction(1, 3);
|
||||
const twothirds = Fraction(2, 3);
|
||||
|
||||
const sameFirst = (a, b) => {
|
||||
return expect(a._sortHapsByPart().firstCycle()).toStrictEqual(b._sortHapsByPart().firstCycle());
|
||||
return expect(a.sortHapsByPart().firstCycle()).toStrictEqual(b.sortHapsByPart().firstCycle());
|
||||
};
|
||||
|
||||
describe('TimeSpan', () => {
|
||||
@@ -153,35 +154,46 @@ describe('Pattern', () => {
|
||||
).toBe(7);
|
||||
});
|
||||
});
|
||||
describe('out()', () => {
|
||||
it('is an alias for set.out()', () => {
|
||||
sameFirst(sequence(1, 2).out(5, 6, 7, 8), sequence(1, 2).set.out(5, 6, 7, 8));
|
||||
});
|
||||
});
|
||||
describe('add()', () => {
|
||||
it('works as toplevel function', () => {
|
||||
expect(add(pure(4), pure(5)).query(st(0, 1))[0].value).toBe(9);
|
||||
});
|
||||
it('works as toplevel function, with bare values for arguments', () => {
|
||||
expect(add(4, 5).query(st(0, 1))[0].value).toBe(9);
|
||||
});
|
||||
it('can structure In()', () => {
|
||||
expect(pure(3).add(pure(4)).query(st(0, 1))[0].value).toBe(7);
|
||||
expect(pure(3).addIn(pure(4)).query(st(0, 1))[0].value).toBe(7);
|
||||
expect(pure(3).add.in(pure(4)).query(st(0, 1))[0].value).toBe(7);
|
||||
});
|
||||
it('can structure Out()', () => {
|
||||
sameFirst(sequence(1, 2).addOut(4), sequence(5, 6).struct(true));
|
||||
sameFirst(sequence(1, 2).add.out(4), sequence(5, 6).struct(true));
|
||||
});
|
||||
it('can Mix() structure', () => {
|
||||
expect(sequence(1, 2).addMix(silence, 5, silence).firstCycle()).toStrictEqual([
|
||||
expect(sequence(1, 2).add.mix(silence, 5, silence).firstCycle()).toStrictEqual([
|
||||
new Hap(ts(1 / 3, 1 / 2), ts(1 / 3, 1 / 2), 6),
|
||||
new Hap(ts(1 / 2, 2 / 3), ts(1 / 2, 2 / 3), 7),
|
||||
]);
|
||||
});
|
||||
it('can Trig() structure', () => {
|
||||
sameFirst(
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).addTrig(20, 30).early(2),
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).add.trig(20, 30).early(2),
|
||||
sequence(26, 27, 36, 37),
|
||||
);
|
||||
});
|
||||
it('can Trigzero() structure', () => {
|
||||
sameFirst(
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).addTrigzero(20, 30).early(2),
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).add.trigzero(20, 30).early(2),
|
||||
sequence(21, 22, 31, 32),
|
||||
);
|
||||
});
|
||||
it('can Squeeze() structure', () => {
|
||||
sameFirst(
|
||||
sequence(1, [2, 3]).addSqueeze(sequence(10, 20, 30)),
|
||||
sequence(1, [2, 3]).add.squeeze(sequence(10, 20, 30)),
|
||||
sequence(
|
||||
[11, 21, 31],
|
||||
[
|
||||
@@ -193,7 +205,7 @@ describe('Pattern', () => {
|
||||
});
|
||||
it('can SqueezeOut() structure', () => {
|
||||
sameFirst(
|
||||
sequence(1, [2, 3]).addSqueezeOut(10, 20, 30),
|
||||
sequence(1, [2, 3]).add.squeezeout(10, 20, 30),
|
||||
sequence([11, [12, 13]], [21, [22, 23]], [31, [32, 33]]),
|
||||
);
|
||||
});
|
||||
@@ -204,32 +216,32 @@ describe('Pattern', () => {
|
||||
describe('keep()', () => {
|
||||
it('can structure In()', () => {
|
||||
expect(pure(3).keep(pure(4)).query(st(0, 1))[0].value).toBe(3);
|
||||
expect(pure(3).keepIn(pure(4)).query(st(0, 1))[0].value).toBe(3);
|
||||
expect(pure(3).keep.in(pure(4)).query(st(0, 1))[0].value).toBe(3);
|
||||
});
|
||||
it('can structure Out()', () => {
|
||||
sameFirst(sequence(1, 2).keepOut(4), sequence(1, 2).struct(true));
|
||||
sameFirst(sequence(1, 2).keep.out(4), sequence(1, 2).struct(true));
|
||||
});
|
||||
it('can Mix() structure', () => {
|
||||
expect(sequence(1, 2).keepMix(silence, 5, silence).firstCycle()).toStrictEqual([
|
||||
expect(sequence(1, 2).keep.mix(silence, 5, silence).firstCycle()).toStrictEqual([
|
||||
new Hap(ts(1 / 3, 1 / 2), ts(1 / 3, 1 / 2), 1),
|
||||
new Hap(ts(1 / 2, 2 / 3), ts(1 / 2, 2 / 3), 2),
|
||||
]);
|
||||
});
|
||||
it('can Trig() structure', () => {
|
||||
sameFirst(
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).keepTrig(20, 30).early(2),
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).keep.trig(20, 30).early(2),
|
||||
sequence(6, 7, 6, 7),
|
||||
);
|
||||
});
|
||||
it('can Trigzero() structure', () => {
|
||||
sameFirst(
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).keepTrigzero(20, 30).early(2),
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).keep.trigzero(20, 30).early(2),
|
||||
sequence(1, 2, 1, 2),
|
||||
);
|
||||
});
|
||||
it('can Squeeze() structure', () => {
|
||||
sameFirst(
|
||||
sequence(1, [2, 3]).keepSqueeze(sequence(10, 20, 30)),
|
||||
sequence(1, [2, 3]).keep.squeeze(sequence(10, 20, 30)),
|
||||
sequence(
|
||||
[1, 1, 1],
|
||||
[
|
||||
@@ -240,38 +252,38 @@ describe('Pattern', () => {
|
||||
);
|
||||
});
|
||||
it('can SqueezeOut() structure', () => {
|
||||
sameFirst(sequence(1, [2, 3]).keepSqueezeOut(10, 20, 30), sequence([1, [2, 3]], [1, [2, 3]], [1, [2, 3]]));
|
||||
sameFirst(sequence(1, [2, 3]).keep.squeezeout(10, 20, 30), sequence([1, [2, 3]], [1, [2, 3]], [1, [2, 3]]));
|
||||
});
|
||||
});
|
||||
describe('keepif()', () => {
|
||||
it('can structure In()', () => {
|
||||
sameFirst(sequence(3, 4).keepif(true, false), sequence(3, silence));
|
||||
sameFirst(sequence(3, 4).keepifIn(true, false), sequence(3, silence));
|
||||
sameFirst(sequence(3, 4).keepif.in(true, false), sequence(3, silence));
|
||||
});
|
||||
it('can structure Out()', () => {
|
||||
sameFirst(pure(1).keepifOut(true, false), sequence(1, silence));
|
||||
sameFirst(pure(1).keepif.out(true, false), sequence(1, silence));
|
||||
});
|
||||
it('can Mix() structure', () => {
|
||||
expect(sequence(1, 2).keepifMix(false, true, false).firstCycle()).toStrictEqual([
|
||||
expect(sequence(1, 2).keepif.mix(false, true, false).firstCycle()).toStrictEqual([
|
||||
new Hap(ts(1 / 3, 1 / 2), ts(1 / 3, 1 / 2), 1),
|
||||
new Hap(ts(1 / 2, 2 / 3), ts(1 / 2, 2 / 3), 2),
|
||||
]);
|
||||
});
|
||||
it('can Trig() structure', () => {
|
||||
sameFirst(
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).keepifTrig(false, true).early(2),
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).keepif.trig(false, true).early(2),
|
||||
sequence(silence, silence, 6, 7),
|
||||
);
|
||||
});
|
||||
it('can Trigzero() structure', () => {
|
||||
sameFirst(
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).keepifTrigzero(false, true).early(2),
|
||||
slowcat(sequence(1, 2, 3, 4), 5, sequence(6, 7, 8, 9), 10).keepif.trigzero(false, true).early(2),
|
||||
sequence(silence, silence, 1, 2),
|
||||
);
|
||||
});
|
||||
it('can Squeeze() structure', () => {
|
||||
sameFirst(
|
||||
sequence(1, [2, 3]).keepifSqueeze(sequence(true, true, false)),
|
||||
sequence(1, [2, 3]).keepif.squeeze(sequence(true, true, false)),
|
||||
sequence(
|
||||
[1, 1, silence],
|
||||
[
|
||||
@@ -282,7 +294,7 @@ describe('Pattern', () => {
|
||||
);
|
||||
});
|
||||
it('can SqueezeOut() structure', () => {
|
||||
sameFirst(sequence(1, [2, 3]).keepifSqueezeOut(true, true, false), sequence([1, [2, 3]], [1, [2, 3]], silence));
|
||||
sameFirst(sequence(1, [2, 3]).keepif.squeezeout(true, true, false), sequence([1, [2, 3]], [1, [2, 3]], silence));
|
||||
});
|
||||
});
|
||||
describe('sub()', () => {
|
||||
@@ -322,13 +334,13 @@ describe('Pattern', () => {
|
||||
});
|
||||
describe('setOut()', () => {
|
||||
it('Can set things with structure from second pattern', () => {
|
||||
sameFirst(sequence(1, 2).setOut(4), pure(4).mask(true, true));
|
||||
sameFirst(sequence(1, 2).set.out(4), pure(4).mask(true, true));
|
||||
});
|
||||
});
|
||||
describe('setSqueeze()', () => {
|
||||
it('Can squeeze one pattern inside the haps of another', () => {
|
||||
sameFirst(
|
||||
sequence(1, [2, 3]).setSqueeze(sequence('a', 'b', 'c')),
|
||||
sequence(1, [2, 3]).set.squeeze(sequence('a', 'b', 'c')),
|
||||
sequence(
|
||||
['a', 'b', 'c'],
|
||||
[
|
||||
@@ -338,7 +350,7 @@ describe('Pattern', () => {
|
||||
),
|
||||
);
|
||||
sameFirst(
|
||||
sequence(1, [2, 3]).setSqueeze('a', 'b', 'c'),
|
||||
sequence(1, [2, 3]).set.squeeze('a', 'b', 'c'),
|
||||
sequence(
|
||||
['a', 'b', 'c'],
|
||||
[
|
||||
@@ -382,7 +394,7 @@ describe('Pattern', () => {
|
||||
);
|
||||
});
|
||||
it('copes with breaking up events across cycles', () => {
|
||||
expect(pure('a').slow(2)._fastGap(2)._setContext({}).query(st(0, 2))).toStrictEqual([
|
||||
expect(pure('a').slow(2)._fastGap(2).setContext({}).query(st(0, 2))).toStrictEqual([
|
||||
hap(ts(0, 1), ts(0, 0.5), 'a'),
|
||||
hap(ts(0.5, 1.5), ts(1, 1.5), 'a'),
|
||||
]);
|
||||
@@ -406,8 +418,8 @@ describe('Pattern', () => {
|
||||
);
|
||||
});
|
||||
it('defaults to accepting sequences', () => {
|
||||
expect(sequence(1, 2, 3).fast(sequence(1.5, 2)).firstCycle()).toStrictEqual(
|
||||
sequence(1, 2, 3).fast(1.5, 2).firstCycle(),
|
||||
expect(sequence('a', 'b', 'c').fast(sequence(1.5, 2)).sortHapsByPart().firstCycle()).toStrictEqual(
|
||||
sequence('a', 'b', 'c').fast(1.5, 2).sortHapsByPart().firstCycle(),
|
||||
);
|
||||
});
|
||||
it('works as a static function', () => {
|
||||
@@ -446,8 +458,8 @@ describe('Pattern', () => {
|
||||
});
|
||||
describe('slow()', () => {
|
||||
it('Supports zero-length queries', () => {
|
||||
expect(steady('a').slow(1)._setContext({}).queryArc(0, 0)).toStrictEqual(
|
||||
steady('a')._setContext({}).queryArc(0, 0),
|
||||
expect(steady('a').slow(1).setContext({}).queryArc(0, 0)).toStrictEqual(
|
||||
steady('a').setContext({}).queryArc(0, 0),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -465,7 +477,7 @@ describe('Pattern', () => {
|
||||
it('Filters true', () => {
|
||||
expect(
|
||||
pure(true)
|
||||
._filterValues((x) => x)
|
||||
.filterValues((x) => x)
|
||||
.firstCycle().length,
|
||||
).toBe(1);
|
||||
});
|
||||
@@ -490,7 +502,7 @@ describe('Pattern', () => {
|
||||
pure(10)
|
||||
.when(slowcat(true, false), (x) => x.add(3))
|
||||
.fast(4)
|
||||
._sortHapsByPart()
|
||||
.sortHapsByPart()
|
||||
.firstCycle(),
|
||||
).toStrictEqual(fastcat(13, 10, 13, 10).firstCycle());
|
||||
});
|
||||
@@ -577,26 +589,36 @@ describe('Pattern', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('every()', () => {
|
||||
describe('firstOf()', () => {
|
||||
it('Can apply a function every 3rd time', () => {
|
||||
expect(
|
||||
pure('a')
|
||||
.every(3, (x) => x._fast(2))
|
||||
.firstOf(3, (x) => x._fast(2))
|
||||
._fast(3)
|
||||
.firstCycle(),
|
||||
).toStrictEqual(sequence(sequence('a', 'a'), 'a', 'a').firstCycle());
|
||||
});
|
||||
it('works with currying', () => {
|
||||
expect(pure('a').every(3, fast(2))._fast(3).firstCycle()).toStrictEqual(
|
||||
it('Works as a toplevel function', () => {
|
||||
expect(firstOf(3, fast(2), pure('a'))._fast(3).firstCycle()).toStrictEqual(
|
||||
sequence(sequence('a', 'a'), 'a', 'a').firstCycle(),
|
||||
);
|
||||
expect(sequence(3, 4, 5).every(3, add(3)).fast(5).firstCycle()).toStrictEqual(
|
||||
});
|
||||
it('Works as a toplevel function, with a patterned first argument', () => {
|
||||
expect(firstOf(pure(3), fast(2), pure('a'))._fast(3).firstCycle()).toStrictEqual(
|
||||
sequence(sequence('a', 'a'), 'a', 'a').firstCycle(),
|
||||
);
|
||||
});
|
||||
it('works with currying', () => {
|
||||
expect(pure('a').firstOf(3, fast(2))._fast(3).firstCycle()).toStrictEqual(
|
||||
sequence(sequence('a', 'a'), 'a', 'a').firstCycle(),
|
||||
);
|
||||
expect(sequence(3, 4, 5).firstOf(3, add(3)).fast(5).firstCycle()).toStrictEqual(
|
||||
sequence(6, 7, 8, 3, 4, 5, 3, 4, 5, 6, 7, 8, 3, 4, 5).firstCycle(),
|
||||
);
|
||||
expect(sequence(3, 4, 5).every(2, sub(1)).fast(5).firstCycle()).toStrictEqual(
|
||||
expect(sequence(3, 4, 5).firstOf(2, sub(1)).fast(5).firstCycle()).toStrictEqual(
|
||||
sequence(2, 3, 4, 3, 4, 5, 2, 3, 4, 3, 4, 5, 2, 3, 4).firstCycle(),
|
||||
);
|
||||
expect(sequence(3, 4, 5).every(3, add(3)).every(2, sub(1)).fast(2).firstCycle()).toStrictEqual(
|
||||
expect(sequence(3, 4, 5).firstOf(3, add(3)).firstOf(2, sub(1)).fast(2).firstCycle()).toStrictEqual(
|
||||
sequence(5, 6, 7, 3, 4, 5).firstCycle(),
|
||||
);
|
||||
});
|
||||
@@ -692,7 +714,7 @@ describe('Pattern', () => {
|
||||
it('Can set the hap context', () => {
|
||||
expect(
|
||||
pure('a')
|
||||
._setContext([
|
||||
.setContext([
|
||||
[
|
||||
[0, 1],
|
||||
[1, 2],
|
||||
@@ -713,13 +735,13 @@ describe('Pattern', () => {
|
||||
it('Can update the hap context', () => {
|
||||
expect(
|
||||
pure('a')
|
||||
._setContext([
|
||||
.setContext([
|
||||
[
|
||||
[0, 1],
|
||||
[1, 2],
|
||||
],
|
||||
])
|
||||
._withContext((c) => [
|
||||
.withContext((c) => [
|
||||
...c,
|
||||
[
|
||||
[3, 4],
|
||||
@@ -743,7 +765,7 @@ describe('Pattern', () => {
|
||||
});
|
||||
describe('apply', () => {
|
||||
it('Can apply a function', () => {
|
||||
expect(sequence('a', 'b')._apply(fast(2)).firstCycle()).toStrictEqual(sequence('a', 'b').fast(2).firstCycle());
|
||||
expect(sequence('a', 'b').apply(fast(2)).firstCycle()).toStrictEqual(sequence('a', 'b').fast(2).firstCycle());
|
||||
}),
|
||||
it('Can apply a pattern of functions', () => {
|
||||
expect(sequence('a', 'b').apply(fast(2)).firstCycle()).toStrictEqual(sequence('a', 'b').fast(2).firstCycle());
|
||||
@@ -784,18 +806,18 @@ describe('Pattern', () => {
|
||||
});
|
||||
describe('jux', () => {
|
||||
it('Can juxtapose', () => {
|
||||
expect(pure({ a: 1 }).jux(fast(2))._sortHapsByPart().firstCycle()).toStrictEqual(
|
||||
expect(pure({ a: 1 }).jux(fast(2)).sortHapsByPart().firstCycle()).toStrictEqual(
|
||||
stack(pure({ a: 1, pan: 0 }), pure({ a: 1, pan: 1 }).fast(2))
|
||||
._sortHapsByPart()
|
||||
.sortHapsByPart()
|
||||
.firstCycle(),
|
||||
);
|
||||
});
|
||||
});
|
||||
describe('juxBy', () => {
|
||||
it('Can juxtapose by half', () => {
|
||||
expect(pure({ a: 1 }).juxBy(0.5, fast(2))._sortHapsByPart().firstCycle()).toStrictEqual(
|
||||
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()
|
||||
.sortHapsByPart()
|
||||
.firstCycle(),
|
||||
);
|
||||
});
|
||||
@@ -805,7 +827,7 @@ describe('Pattern', () => {
|
||||
expect(
|
||||
sequence('a', ['a', 'a'])
|
||||
.fmap((a) => fastcat('b', 'c'))
|
||||
._squeezeJoin()
|
||||
.squeezeJoin()
|
||||
.firstCycle(),
|
||||
).toStrictEqual(
|
||||
sequence(
|
||||
@@ -820,7 +842,7 @@ describe('Pattern', () => {
|
||||
it('Squeezes to the correct cycle', () => {
|
||||
expect(
|
||||
pure(time.struct(true))
|
||||
._squeezeJoin()
|
||||
.squeezeJoin()
|
||||
.queryArc(3, 4)
|
||||
.map((x) => x.value),
|
||||
).toStrictEqual([Fraction(3.5)]);
|
||||
@@ -857,7 +879,7 @@ describe('Pattern', () => {
|
||||
);
|
||||
});
|
||||
it('Can chop(2,3)', () => {
|
||||
expect(pure({ sound: 'a' }).fast(2).chop(2, 3)._sortHapsByPart().firstCycle()).toStrictEqual(
|
||||
expect(pure({ sound: 'a' }).fast(2).chop(2, 3).sortHapsByPart().firstCycle()).toStrictEqual(
|
||||
sequence(
|
||||
[
|
||||
{ sound: 'a', begin: 0, end: 0.5 },
|
||||
@@ -869,7 +891,7 @@ describe('Pattern', () => {
|
||||
{ sound: 'a', begin: 2 / 3, end: 1 },
|
||||
],
|
||||
)
|
||||
._sortHapsByPart()
|
||||
.sortHapsByPart()
|
||||
.firstCycle(),
|
||||
);
|
||||
});
|
||||
@@ -893,4 +915,25 @@ describe('Pattern', () => {
|
||||
);
|
||||
});
|
||||
});
|
||||
describe('alignments', () => {
|
||||
it('Can squeeze arguments', () => {
|
||||
expect(sequence(1, 2).add.squeeze(4, 5).firstCycle()).toStrictEqual(sequence(5, 6, 6, 7).firstCycle());
|
||||
});
|
||||
});
|
||||
describe('defragmentHaps', () => {
|
||||
it('Can merge two touching haps with same whole and value', () => {
|
||||
expect(stack(pure('a').mask(1, 0), pure('a').mask(0, 1)).defragmentHaps().firstCycle().length).toStrictEqual(1);
|
||||
});
|
||||
it('Doesnt merge two overlapping haps', () => {
|
||||
expect(stack(pure('a').mask(1, 1, 0), pure('a').mask(0, 1)).defragmentHaps().firstCycle().length).toStrictEqual(
|
||||
2,
|
||||
);
|
||||
});
|
||||
it('Doesnt merge two touching haps with different values', () => {
|
||||
expect(stack(pure('a').mask(1, 0), pure('b').mask(0, 1)).defragmentHaps().firstCycle().length).toStrictEqual(2);
|
||||
});
|
||||
it('Doesnt merge two touching haps with different wholes', () => {
|
||||
expect(stack(sequence('a', silence), pure('a').mask(0, 1)).defragmentHaps().firstCycle().length).toStrictEqual(2);
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -10,7 +10,8 @@ import {
|
||||
tokenizeNote,
|
||||
toMidi,
|
||||
fromMidi,
|
||||
mod,
|
||||
freqToMidi,
|
||||
_mod,
|
||||
compose,
|
||||
getFrequency,
|
||||
getPlayableNoteValue,
|
||||
@@ -32,9 +33,12 @@ describe('isNote', () => {
|
||||
expect(isNote(note)).toBe(true);
|
||||
});
|
||||
});
|
||||
it('should recognize notes without octave', () => {
|
||||
expect(isNote('C')).toBe(true);
|
||||
expect(isNote('Bb')).toBe(true);
|
||||
});
|
||||
it('should not recognize invalid notes', () => {
|
||||
expect(isNote('H5')).toBe(false);
|
||||
expect(isNote('C')).toBe(false);
|
||||
expect(isNote('X')).toBe(false);
|
||||
expect(isNote(1)).toBe(false);
|
||||
});
|
||||
@@ -94,6 +98,12 @@ describe('fromMidi', () => {
|
||||
expect(fromMidi(57)).toEqual(220);
|
||||
});
|
||||
});
|
||||
describe('freqToMidi', () => {
|
||||
it('should turn frequency into midi', () => {
|
||||
expect(freqToMidi(440)).toEqual(69);
|
||||
expect(freqToMidi(220)).toEqual(57);
|
||||
});
|
||||
});
|
||||
describe('getFrequency', () => {
|
||||
const happify = (val, context = {}) => pure(val).firstCycle()[0].setContext(context);
|
||||
it('should turn note into frequency', () => {
|
||||
@@ -118,22 +128,22 @@ describe('getFrequency', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('mod', () => {
|
||||
describe('_mod', () => {
|
||||
it('should work like regular modulo with positive numbers', () => {
|
||||
expect(mod(0, 3)).toEqual(0);
|
||||
expect(mod(1, 3)).toEqual(1);
|
||||
expect(mod(2, 3)).toEqual(2);
|
||||
expect(mod(3, 3)).toEqual(0);
|
||||
expect(mod(4, 3)).toEqual(1);
|
||||
expect(mod(4, 2)).toEqual(0);
|
||||
expect(_mod(0, 3)).toEqual(0);
|
||||
expect(_mod(1, 3)).toEqual(1);
|
||||
expect(_mod(2, 3)).toEqual(2);
|
||||
expect(_mod(3, 3)).toEqual(0);
|
||||
expect(_mod(4, 3)).toEqual(1);
|
||||
expect(_mod(4, 2)).toEqual(0);
|
||||
});
|
||||
it('should work with negative numbers', () => {
|
||||
expect(mod(-1, 3)).toEqual(2);
|
||||
expect(mod(-2, 3)).toEqual(1);
|
||||
expect(mod(-3, 3)).toEqual(0);
|
||||
expect(mod(-4, 3)).toEqual(2);
|
||||
expect(mod(-5, 3)).toEqual(1);
|
||||
expect(mod(-3, 2)).toEqual(1);
|
||||
expect(_mod(-1, 3)).toEqual(2);
|
||||
expect(_mod(-2, 3)).toEqual(1);
|
||||
expect(_mod(-3, 3)).toEqual(0);
|
||||
expect(_mod(-4, 3)).toEqual(2);
|
||||
expect(_mod(-5, 3)).toEqual(1);
|
||||
expect(_mod(-3, 2)).toEqual(1);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -182,6 +192,7 @@ describe('parseNumeral', () => {
|
||||
expect(parseNumeral(1.5)).toBe(1.5);
|
||||
});
|
||||
it('should parse notes', () => {
|
||||
expect(parseNumeral('c')).toBe(48);
|
||||
expect(parseNumeral('c4')).toBe(60);
|
||||
expect(parseNumeral('c#4')).toBe(61);
|
||||
expect(parseNumeral('db4')).toBe(61);
|
||||
|
||||
@@ -6,6 +6,8 @@ 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 controls from '../controls.mjs';
|
||||
const { n } = controls;
|
||||
|
||||
describe('Value', () => {
|
||||
it('unionWith', () => {
|
||||
@@ -21,4 +23,8 @@ describe('Value', () => {
|
||||
expect(valued(mul).ap(3).ap(3).value).toEqual(9);
|
||||
expect(valued(3).mul(3).value).toEqual(9);
|
||||
});
|
||||
it('union bare numbers for numeral props', () => {
|
||||
expect(n(3).cutoff(500).add(10).firstCycleValues).toEqual([{ n: 13, cutoff: 510 }]);
|
||||
expect(n(3).cutoff(500).mul(2).firstCycleValues).toEqual([{ n: 6, cutoff: 1000 }]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
let time;
|
||||
export function getTime() {
|
||||
if (!time) {
|
||||
throw new Error('no time set! use setTime to define a time source');
|
||||
}
|
||||
return time();
|
||||
}
|
||||
|
||||
export function setTime(func) {
|
||||
time = func;
|
||||
}
|
||||
@@ -20,9 +20,9 @@ export class TimeSpan {
|
||||
|
||||
// Support zero-width timespans
|
||||
if (begin.equals(end)) {
|
||||
return([new TimeSpan(begin, end)]);
|
||||
return [new TimeSpan(begin, end)];
|
||||
}
|
||||
|
||||
|
||||
while (end.gt(begin)) {
|
||||
// If begin and end are in the same cycle, we're done.
|
||||
if (begin.sam().equals(end_sam)) {
|
||||
@@ -110,7 +110,7 @@ export class TimeSpan {
|
||||
}
|
||||
|
||||
show() {
|
||||
return this.begin.show() + ' -> ' + this.end.show();
|
||||
return this.begin.show() + ' → ' + this.end.show();
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -4,19 +4,14 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
||||
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 { Tone } from './tone.mjs';
|
||||
|
||||
export const hideHeader = () => {
|
||||
document.getElementById('header').style = 'display:none';
|
||||
};
|
||||
import { getTime } from './time.mjs';
|
||||
|
||||
function frame(callback) {
|
||||
if (window.strudelAnimation) {
|
||||
cancelAnimationFrame(window.strudelAnimation);
|
||||
}
|
||||
const animate = (animationTime) => {
|
||||
const toneTime = Tone.getTransport().seconds;
|
||||
callback(animationTime, toneTime);
|
||||
callback(animationTime, getTime());
|
||||
window.strudelAnimation = requestAnimationFrame(animate);
|
||||
};
|
||||
requestAnimationFrame(animate);
|
||||
@@ -51,6 +46,7 @@ export const cleanupUi = () => {
|
||||
const container = document.getElementById('code');
|
||||
if (container) {
|
||||
container.style = '';
|
||||
container.className = 'grow relative'; // has to match App.tsx
|
||||
// TODO: find a way to remove that duplication..
|
||||
container.className = 'grow flex text-gray-100 relative overflow-auto cursor-text pb-0'; // has to match App.tsx
|
||||
}
|
||||
};
|
||||
+57
-8
@@ -4,8 +4,11 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
||||
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';
|
||||
|
||||
// returns true if the given string is a note
|
||||
export const isNote = (name) => /^[a-gA-G][#b]*[0-9]$/.test(name);
|
||||
export const isNoteWithOctave = (name) => /^[a-gA-G][#bs]*[0-9]$/.test(name);
|
||||
export const isNote = (name) => /^[a-gA-G][#bs]*[0-9]?$/.test(name);
|
||||
export const tokenizeNote = (note) => {
|
||||
if (typeof note !== 'string') {
|
||||
return [];
|
||||
@@ -19,7 +22,7 @@ export const tokenizeNote = (note) => {
|
||||
|
||||
// turns the given note into its midi number representation
|
||||
export const toMidi = (note) => {
|
||||
const [pc, acc, oct] = tokenizeNote(note);
|
||||
const [pc, acc, oct = 3] = tokenizeNote(note);
|
||||
if (!pc) {
|
||||
throw new Error('not a note: "' + note + '"');
|
||||
}
|
||||
@@ -31,6 +34,30 @@ export const fromMidi = (n) => {
|
||||
return Math.pow(2, (n - 69) / 12) * 440;
|
||||
};
|
||||
|
||||
export const freqToMidi = (freq) => {
|
||||
return (12 * Math.log(freq / 440)) / Math.LN2 + 69;
|
||||
};
|
||||
|
||||
export const valueToMidi = (value, fallbackValue) => {
|
||||
if (typeof value !== 'object') {
|
||||
throw new Error('valueToMidi: expected object value');
|
||||
}
|
||||
let { freq, note } = value;
|
||||
if (typeof freq === 'number') {
|
||||
return freqToMidi(freq);
|
||||
}
|
||||
if (typeof note === 'string') {
|
||||
return toMidi(note);
|
||||
}
|
||||
if (typeof note === 'number') {
|
||||
return note;
|
||||
}
|
||||
if (!fallbackValue) {
|
||||
throw new Error('valueToMidi: expected freq or note to be set');
|
||||
}
|
||||
return fallbackValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* @deprecated does not appear to be referenced or invoked anywhere in the codebase
|
||||
*/
|
||||
@@ -50,14 +77,17 @@ export const midi2note = (n) => {
|
||||
return pc + oct;
|
||||
};
|
||||
|
||||
// modulo that works with negative numbers e.g. mod(-1, 3) = 2
|
||||
// const mod = (n: number, m: number): number => (n < 0 ? mod(n + m, m) : n % m);
|
||||
export const mod = (n, m) => ((n % m) + m) % m;
|
||||
// modulo that works with negative numbers e.g. _mod(-1, 3) = 2. Works on numbers (rather than patterns of numbers, as @mod@ from pattern.mjs does)
|
||||
export const _mod = (n, m) => ((n % m) + m) % m;
|
||||
|
||||
export const getPlayableNoteValue = (hap) => {
|
||||
let { value: note, context } = hap;
|
||||
let { value, context } = hap;
|
||||
let note = value;
|
||||
if (typeof note === 'object' && !Array.isArray(note)) {
|
||||
note = note.note || note.n || note.value;
|
||||
if (note === undefined) {
|
||||
throw new Error(`cannot find a playable note for ${JSON.stringify(value)}`);
|
||||
}
|
||||
}
|
||||
// if value is number => interpret as midi number as long as its not marked as frequency
|
||||
if (typeof note === 'number' && context.type !== 'frequency') {
|
||||
@@ -113,14 +143,33 @@ export const constant = (a, b) => a;
|
||||
|
||||
export const listRange = (min, max) => Array.from({ length: max - min + 1 }, (_, i) => i + min);
|
||||
|
||||
export function curry(func, overload) {
|
||||
export function curry(func, overload, arity = func.length) {
|
||||
const fn = function curried(...args) {
|
||||
if (args.length >= func.length) {
|
||||
if (args.length >= arity) {
|
||||
return func.apply(this, args);
|
||||
} else {
|
||||
const partial = function (...args2) {
|
||||
return curried.apply(this, args.concat(args2));
|
||||
};
|
||||
|
||||
if (args.length == arity - 1) {
|
||||
// The penultimate arg.. so add some composition magic
|
||||
// TODO - To make this useful, we also need to add stub functions for every pattern method to
|
||||
// do the actual composing
|
||||
for (const r of Pattern.__registered) {
|
||||
partial[r] = function (...args) {
|
||||
const result = new Pattern(() => []);
|
||||
result.__compose = function (pat) {
|
||||
return partial(pat)[r](...args);
|
||||
};
|
||||
return result;
|
||||
};
|
||||
}
|
||||
partial.__compose = function (pat) {
|
||||
return partial(pat);
|
||||
};
|
||||
}
|
||||
|
||||
if (overload) {
|
||||
overload(partial, args);
|
||||
}
|
||||
|
||||
@@ -7,6 +7,13 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
import { curry } from './util.mjs';
|
||||
|
||||
export function unionWithObj(a, b, func) {
|
||||
if (typeof b?.value === 'number') {
|
||||
// https://github.com/tidalcycles/strudel/issues/262
|
||||
const numKeys = Object.keys(a).filter((k) => typeof a[k] === 'number');
|
||||
const numerals = Object.fromEntries(numKeys.map((k) => [k, b.value]));
|
||||
b = Object.assign(b, numerals);
|
||||
delete b.value;
|
||||
}
|
||||
const common = Object.keys(a).filter((k) => Object.keys(b).includes(k));
|
||||
return Object.assign({}, a, b, Object.fromEntries(common.map((k) => [k, func(a[k], b[k])])));
|
||||
}
|
||||
|
||||
@@ -31,10 +31,11 @@ function createClock(
|
||||
};
|
||||
let intervalID;
|
||||
const start = () => {
|
||||
clear(); // just in case start was called more than once
|
||||
onTick();
|
||||
intervalID = setInterval(onTick, interval * 1000);
|
||||
};
|
||||
const clear = () => clearInterval(intervalID);
|
||||
const clear = () => intervalID !== undefined && clearInterval(intervalID);
|
||||
const pause = () => clear();
|
||||
const stop = () => {
|
||||
tick = 0;
|
||||
@@ -43,6 +44,6 @@ function createClock(
|
||||
};
|
||||
const getPhase = () => phase;
|
||||
// setCallback
|
||||
return { setDuration, start, stop, pause, duration, getPhase };
|
||||
return { setDuration, start, stop, pause, duration, getPhase, minLatency };
|
||||
}
|
||||
export default createClock;
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import { getFrequency, logger, register } from '@strudel.cycles/core';
|
||||
import { getAudioContext } from '@strudel.cycles/webaudio';
|
||||
import csd from './project.csd?raw';
|
||||
// import livecodeOrc from './livecode.orc?raw';
|
||||
import presetsOrc from './presets.orc?raw';
|
||||
|
||||
let csoundLoader, _csound;
|
||||
|
||||
// initializes csound + can be used to reevaluate given instrument code
|
||||
export async function loadCSound(code = '') {
|
||||
await init();
|
||||
if (code) {
|
||||
code = `${code}`;
|
||||
// ^ ^
|
||||
// wrapping in backticks makes sure it works when calling as templated function
|
||||
await _csound?.evalCode(code);
|
||||
}
|
||||
}
|
||||
export const loadcsound = loadCSound;
|
||||
export const loadCsound = loadCSound;
|
||||
|
||||
export const csound = register('csound', (instrument, pat) => {
|
||||
instrument = instrument || 'triangle';
|
||||
init(); // not async to support csound inside other patterns + to be able to call pattern methods after it
|
||||
// TODO: find a alternative way to wait for csound to load (to wait with first time playback)
|
||||
return pat.onTrigger((time, hap) => {
|
||||
if (!_csound) {
|
||||
logger('[csound] not loaded yet', 'warning');
|
||||
return;
|
||||
}
|
||||
if (typeof hap.value !== 'object') {
|
||||
throw new Error('csound only support objects as hap values');
|
||||
}
|
||||
let { gain = 0.8 } = hap.value;
|
||||
gain *= 0.2;
|
||||
|
||||
const freq = Math.round(getFrequency(hap));
|
||||
const controls = Object.entries({ ...hap.value, freq })
|
||||
.flat()
|
||||
.join('/');
|
||||
// TODO: find out how to send a precise ctx based time
|
||||
// http://www.csounds.com/manual/html/i.html
|
||||
const params = [
|
||||
`"${instrument}"`, // p1: instrument name
|
||||
time - getAudioContext().currentTime, //.toFixed(precision), // p2: starting time in arbitrary unit called beats
|
||||
hap.duration + 0, // p3: duration in beats
|
||||
// instrument specific params:
|
||||
freq, //.toFixed(precision), // p4: frequency
|
||||
gain, // p5: gain
|
||||
`"${controls}"`, // p6 controls as string (like superdirt osc message)
|
||||
];
|
||||
const msg = `i ${params.join(' ')}`;
|
||||
_csound.inputMessage(msg);
|
||||
});
|
||||
});
|
||||
|
||||
function eventLogger(type, args) {
|
||||
const [msg] = args;
|
||||
if (
|
||||
type === 'message' &&
|
||||
(['[commit: HEAD]'].includes(msg) ||
|
||||
msg.startsWith('--Csound version') ||
|
||||
msg.startsWith('libsndfile') ||
|
||||
msg.startsWith('sr =') ||
|
||||
msg.startsWith('0dBFS') ||
|
||||
msg.startsWith('audio buffered') ||
|
||||
msg.startsWith('writing') ||
|
||||
msg.startsWith('SECTION 1:'))
|
||||
) {
|
||||
// ignore
|
||||
return;
|
||||
}
|
||||
let logType = 'info';
|
||||
if (msg.startsWith('error:')) {
|
||||
logType = 'error';
|
||||
}
|
||||
logger(`[csound] ${msg || ''}`, logType);
|
||||
}
|
||||
|
||||
async function load() {
|
||||
if (window.__csound__) {
|
||||
// Allows using some other csound instance.
|
||||
// In that case, the external Csound is responsible
|
||||
// for compiling an orchestra and starting to perform.
|
||||
logger('[load] Using external Csound', 'warning');
|
||||
_csound = window.__csound__;
|
||||
return _csound;
|
||||
} else {
|
||||
const { Csound } = await import('@csound/browser');
|
||||
_csound = await Csound({ audioContext: getAudioContext() });
|
||||
_csound.removeAllListeners('message');
|
||||
['message'].forEach((k) => _csound.on(k, (...args) => eventLogger(k, args)));
|
||||
await _csound.setOption('-m0d'); // see -m flag https://csound.com/docs/manual/CommandFlags.html
|
||||
await _csound.setOption('--sample-accurate');
|
||||
await _csound.compileCsdText(csd);
|
||||
// await _csound.compileOrc(livecodeOrc);
|
||||
await _csound.compileOrc(presetsOrc);
|
||||
await _csound.start();
|
||||
return _csound;
|
||||
}
|
||||
}
|
||||
|
||||
async function init() {
|
||||
csoundLoader = csoundLoader || load();
|
||||
return csoundLoader;
|
||||
}
|
||||
|
||||
let orcCache = {};
|
||||
export async function loadOrc(url) {
|
||||
await init();
|
||||
if (typeof url !== 'string') {
|
||||
throw new Error('loadOrc: expected url string');
|
||||
}
|
||||
if (url.startsWith('github:')) {
|
||||
const [_, path] = url.split('github:');
|
||||
url = `https://raw.githubusercontent.com/${path}`;
|
||||
}
|
||||
if (!orcCache[url]) {
|
||||
orcCache[url] = fetch(url)
|
||||
.then((res) => res.text())
|
||||
.then((code) => _csound.compileOrc(code));
|
||||
}
|
||||
await orcCache[url];
|
||||
}
|
||||
|
||||
/**
|
||||
* Sends notes to Csound for rendering with MIDI semantics. The hap value is
|
||||
* translated to these Csound pfields:
|
||||
*
|
||||
* p1 -- Csound instrument either as a number (1-based, can be a fraction),
|
||||
* or as a string name.
|
||||
* p2 -- time in beats (usually seconds) from start of performance.
|
||||
* p3 -- duration in beats (usually seconds).
|
||||
* p4 -- MIDI key number (as a real number, not an integer but in [0, 127].
|
||||
* p5 -- MIDI velocity (as a real number, not an integer but in [0, 127].
|
||||
* p6 -- Strudel controls, as a string.
|
||||
*/
|
||||
export const csoundm = register('csoundm', (instrument, pat) => {
|
||||
let p1 = instrument;
|
||||
if (typeof instrument === 'string') {
|
||||
p1 = `"{instrument}"`;
|
||||
}
|
||||
init(); // not async to support csound inside other patterns + to be able to call pattern methods after it
|
||||
return pat.onTrigger((tidal_time, hap) => {
|
||||
if (!_csound) {
|
||||
logger('[csound] not loaded yet', 'warning');
|
||||
return;
|
||||
}
|
||||
if (typeof hap.value !== 'object') {
|
||||
throw new Error('csound only support objects as hap values');
|
||||
}
|
||||
// Time in seconds counting from now.
|
||||
const p2 = tidal_time - getAudioContext().currentTime;
|
||||
const p3 = hap.duration.valueOf() + 0;
|
||||
const frequency = getFrequency(hap);
|
||||
// Translate frequency to MIDI key number _without_ rounding.
|
||||
const C4 = 261.62558;
|
||||
let octave = Math.log(frequency / C4) / Math.log(2.0) + 8.0;
|
||||
const p4 = octave * 12.0 - 36.0;
|
||||
// We prefer floating point precision, but over the MIDI range [0, 127].
|
||||
const p5 = 127 * (hap.context?.velocity ?? 0.9);
|
||||
// The Strudel controls as a string.
|
||||
const p6 = Object.entries({ ...hap.value, frequency })
|
||||
.flat()
|
||||
.join('/');
|
||||
const i_statement = `i ${p1} ${p2} ${p3} ${p4} ${p5} "${p6}"`;
|
||||
console.log('[csoundm]:', i_statement);
|
||||
_csound.inputMessage(i_statement);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,32 @@
|
||||
{
|
||||
"name": "@strudel.cycles/csound",
|
||||
"version": "0.5.1",
|
||||
"description": "csound bindings for strudel",
|
||||
"main": "csound.mjs",
|
||||
"scripts": {
|
||||
"test": "echo \"No tests present.\" && exit 0"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "git+https://github.com/tidalcycles/strudel.git"
|
||||
},
|
||||
"keywords": [
|
||||
"tidalcycles",
|
||||
"strudel",
|
||||
"pattern",
|
||||
"livecoding",
|
||||
"algorave"
|
||||
],
|
||||
"author": "Felix Roos <flix91@gmail.com>",
|
||||
"contributors": [
|
||||
"Alex McLean <alex@slab.org>"
|
||||
],
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"bugs": {
|
||||
"url": "https://github.com/tidalcycles/strudel/issues"
|
||||
},
|
||||
"homepage": "https://github.com/tidalcycles/strudel#readme",
|
||||
"dependencies": {
|
||||
"@csound/browser": "^6.18.3"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
; returns value of given key in given "string map"
|
||||
; keymap("freq", "note/c3/freq/220/gain/0.5")
|
||||
; yields "220"
|
||||
opcode keymap, S, SS
|
||||
Skey, Smap xin
|
||||
idelimiter = strindex(Smap, strcat(Skey, "/"))
|
||||
ifrom = idelimiter + strlen(Skey) + 1
|
||||
Svalue = strsub(Smap, ifrom, strlen(Smap))
|
||||
Svalue = strsub(Svalue, 0, strindex(Svalue, "/"))
|
||||
xout Svalue
|
||||
endop
|
||||
|
||||
; TODO add incredibly dope synths
|
||||
instr organ
|
||||
iduration = p3
|
||||
ifreq = p4
|
||||
igain = p5
|
||||
ioct = octcps(ifreq)
|
||||
|
||||
asig = vco2(igain, ifreq, 12, .5) ; my edit
|
||||
kpwm = oscili(.1, 5)
|
||||
asig = vco2(igain, ifreq, 4, .5 + kpwm)
|
||||
asig += vco2(igain/4, ifreq * 2)
|
||||
|
||||
; filter
|
||||
; idepth = 2
|
||||
; acut = transegr:a(0, .005, 0, idepth, .06, -4.2, 0.001, .01, -4.2, 0) ; filter envelope
|
||||
; asig = zdf_2pole(asig, cpsoct(ioct + acut), 0.5)
|
||||
|
||||
; amp envelope
|
||||
iattack = .001
|
||||
irelease = .05
|
||||
asig *= linsegr:a(0, iattack, 1, iduration, 1, irelease, 0)
|
||||
|
||||
out(asig, asig)
|
||||
|
||||
endin
|
||||
|
||||
instr triangle
|
||||
iduration = p3
|
||||
ifreq = p4
|
||||
igain = p5
|
||||
ioct = octcps(ifreq)
|
||||
|
||||
asig = vco2(igain, ifreq, 12, .5)
|
||||
|
||||
; amp envelope
|
||||
iattack = .001
|
||||
irelease = .05
|
||||
asig *= linsegr:a(0, iattack, 1, iduration, 1, irelease, 0)
|
||||
|
||||
out(asig, asig)
|
||||
endin
|
||||
|
||||
instr pad
|
||||
iduration = p3
|
||||
ifreq = p4
|
||||
igain = p5
|
||||
ioct = octcps(ifreq)
|
||||
|
||||
asig = vco2(igain, ifreq, 0)
|
||||
|
||||
; amp envelope
|
||||
iattack = .5
|
||||
irelease = .1
|
||||
asig *= linsegr:a(0, iattack, 1, iduration, 1, irelease, 0)
|
||||
|
||||
idepth = 2
|
||||
acut = transegr:a(0, .005, 0, idepth, .06, -4.2, 0.001, .01, -4.2, 0)
|
||||
asig = zdf_2pole(asig, 1000, 2)
|
||||
|
||||
out(asig, asig)
|
||||
endin
|
||||
|
||||
|
||||
gisine ftgen 0, 0, 4096, 10, 1
|
||||
|
||||
instr bow
|
||||
kpres = 2
|
||||
krat = 0.16
|
||||
kvibf = 6.12723
|
||||
|
||||
kvib linseg 0, 0.5, 0, 1, 1, p3-0.5, 1
|
||||
kvamp = kvib * 0.01
|
||||
asig wgbow .7, p4, kpres, krat, kvibf, kvamp, gisine
|
||||
asig = asig*p5
|
||||
outs asig, asig
|
||||
endin
|
||||
|
||||
|
||||
instr Meta
|
||||
Smap = strget(p6)
|
||||
Sinstrument = keymap("s", Smap)
|
||||
schedule(Sinstrument, 0, p3, p4, p5)
|
||||
; TODO find a way to pipe Sinstrument through effects
|
||||
endin
|
||||
@@ -0,0 +1,10 @@
|
||||
<CsoundSynthesizer>
|
||||
<CsInstruments>
|
||||
|
||||
sr=48000
|
||||
ksmps=64
|
||||
nchnls=2
|
||||
0dbfs=1
|
||||
|
||||
</CsInstruments>
|
||||
</CsoundSynthesizer>
|
||||
Generated
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/eval",
|
||||
"version": "0.3.2",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/eval",
|
||||
"version": "0.3.2",
|
||||
"version": "0.5.0",
|
||||
"description": "Code evaluator for strudel",
|
||||
"main": "index.mjs",
|
||||
"type": "module",
|
||||
@@ -28,7 +28,7 @@
|
||||
},
|
||||
"homepage": "https://github.com/tidalcycles/strudel#readme",
|
||||
"dependencies": {
|
||||
"@strudel.cycles/core": "^0.3.2",
|
||||
"@strudel.cycles/core": "^0.5.0",
|
||||
"estraverse": "^5.3.0",
|
||||
"shift-ast": "^7.0.0",
|
||||
"shift-codegen": "^8.1.0",
|
||||
|
||||
@@ -225,9 +225,8 @@ function isPatternArg(parents) {
|
||||
function hasModifierCall(parent) {
|
||||
// TODO: modifiers are more than composables, for example every is not composable but should be seen as modifier..
|
||||
// need all prototypes of Pattern
|
||||
return (
|
||||
parent?.type === 'StaticMemberExpression' && Object.keys(Pattern.prototype.composable).includes(parent.property)
|
||||
);
|
||||
return parent?.type === 'StaticMemberExpression';
|
||||
// && Object.keys(Pattern.prototype.composable).includes(parent.property)
|
||||
}
|
||||
const factories = Object.keys(Pattern.prototype.factories).concat(['mini']);
|
||||
|
||||
|
||||
@@ -13,7 +13,7 @@ const { fastcat, evalScope } = strudel;
|
||||
|
||||
describe('evaluate', async () => {
|
||||
await evalScope({ mini }, strudel);
|
||||
const ev = async (code) => (await evaluate(code)).pattern._firstCycleValues;
|
||||
const ev = async (code) => (await evaluate(code)).pattern.firstCycleValues;
|
||||
it('Should evaluate strudel functions', async () => {
|
||||
expect(await ev('pure("c3")')).toEqual(['c3']);
|
||||
expect(await ev('cat("c3")')).toEqual(['c3']);
|
||||
|
||||
+83
-46
@@ -4,14 +4,23 @@ Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/st
|
||||
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 { isNote } from 'tone';
|
||||
import * as _WebMidi from 'webmidi';
|
||||
import { Pattern, isPattern } from '@strudel.cycles/core';
|
||||
import { Tone } from '@strudel.cycles/tone';
|
||||
import { Pattern, isPattern, isNote, getPlayableNoteValue, logger } from '@strudel.cycles/core';
|
||||
import { getAudioContext } from '@strudel.cycles/webaudio';
|
||||
|
||||
// if you use WebMidi from outside of this package, make sure to import that instance:
|
||||
export const { WebMidi } = _WebMidi;
|
||||
|
||||
export function enableWebMidi() {
|
||||
function supportsMidi() {
|
||||
return typeof navigator.requestMIDIAccess === 'function';
|
||||
}
|
||||
|
||||
export function enableWebMidi(options = {}) {
|
||||
const { onReady, onConnected, onDisconnected } = options;
|
||||
|
||||
if (!supportsMidi()) {
|
||||
throw new Error('Your Browser does not support WebMIDI.');
|
||||
}
|
||||
return new Promise((resolve, reject) => {
|
||||
if (WebMidi.enabled) {
|
||||
// if already enabled, just resolve WebMidi
|
||||
@@ -22,6 +31,14 @@ export function enableWebMidi() {
|
||||
if (err) {
|
||||
reject(err);
|
||||
}
|
||||
WebMidi.addListener('connected', (e) => {
|
||||
onConnected?.(WebMidi);
|
||||
});
|
||||
// Reacting when a device becomes unavailable
|
||||
WebMidi.addListener('disconnected', (e) => {
|
||||
onDisconnected?.(WebMidi, e);
|
||||
});
|
||||
onReady?.(WebMidi);
|
||||
resolve(WebMidi);
|
||||
});
|
||||
});
|
||||
@@ -29,55 +46,75 @@ export function enableWebMidi() {
|
||||
// const outputByName = (name: string) => WebMidi.getOutputByName(name);
|
||||
const outputByName = (name) => WebMidi.getOutputByName(name);
|
||||
|
||||
let midiReady;
|
||||
|
||||
// output?: string | number, outputs: typeof WebMidi.outputs
|
||||
function getDevice(output, outputs) {
|
||||
if (!outputs.length) {
|
||||
throw new Error(`🔌 No MIDI devices found. Connect a device or enable IAC Driver.`);
|
||||
}
|
||||
if (typeof output === 'number') {
|
||||
return outputs[output];
|
||||
}
|
||||
if (typeof output === 'string') {
|
||||
return outputByName(output);
|
||||
}
|
||||
return outputs[0];
|
||||
}
|
||||
|
||||
// Pattern.prototype.midi = function (output: string | number, channel = 1) {
|
||||
Pattern.prototype.midi = function (output, channel = 1) {
|
||||
if (isPattern(output?.constructor?.name)) {
|
||||
if (!supportsMidi()) {
|
||||
throw new Error(`🎹 WebMidi is not enabled. Supported Browsers: https://caniuse.com/?search=webmidi`);
|
||||
}
|
||||
/* await */ enableWebMidi({
|
||||
onConnected: ({ outputs }) =>
|
||||
logger(`Midi device connected! Available: ${outputs.map((o) => `'${o.name}'`).join(', ')}`),
|
||||
onDisconnected: ({ outputs }) =>
|
||||
logger(`Midi device disconnected! Available: ${outputs.map((o) => `'${o.name}'`).join(', ')}`),
|
||||
onReady: ({ outputs }) => {
|
||||
const device = getDevice(output, outputs);
|
||||
const otherOutputs = outputs
|
||||
.filter((o) => o.name !== device.name)
|
||||
.map((o) => `'${o.name}'`)
|
||||
.join(' | ');
|
||||
midiReady = true;
|
||||
logger(`Midi connected! Using "${device.name}". ${otherOutputs ? `Also available: ${otherOutputs}` : ''}`);
|
||||
},
|
||||
});
|
||||
if (isPattern(output)) {
|
||||
throw new Error(
|
||||
`.midi does not accept Pattern input. Make sure to pass device name with single quotes. Example: .midi('${
|
||||
WebMidi.outputs?.[0]?.name || 'IAC Driver Bus 1'
|
||||
}')`,
|
||||
);
|
||||
}
|
||||
return this._withHap((hap) => {
|
||||
// const onTrigger = (time: number, hap: any) => {
|
||||
const onTrigger = (time, hap) => {
|
||||
let note = hap.value;
|
||||
const velocity = hap.context?.velocity ?? 0.9;
|
||||
if (!isNote(note)) {
|
||||
throw new Error('not a note: ' + note);
|
||||
}
|
||||
if (!WebMidi.enabled) {
|
||||
throw new Error(`🎹 WebMidi is not enabled. Supported Browsers: https://caniuse.com/?search=webmidi`);
|
||||
}
|
||||
if (!WebMidi.outputs.length) {
|
||||
throw new Error(`🔌 No MIDI devices found. Connect a device or enable IAC Driver.`);
|
||||
}
|
||||
let device;
|
||||
if (typeof output === 'number') {
|
||||
device = WebMidi.outputs[output];
|
||||
} else if (typeof output === 'string') {
|
||||
device = outputByName(output);
|
||||
} else {
|
||||
device = WebMidi.outputs[0];
|
||||
}
|
||||
if (!device) {
|
||||
throw new Error(
|
||||
`🔌 MIDI device '${output ? output : ''}' not found. Use one of ${WebMidi.outputs
|
||||
.map((o) => `'${o.name}'`)
|
||||
.join(' | ')}`,
|
||||
);
|
||||
}
|
||||
// console.log('midi', value, output);
|
||||
const timingOffset = WebMidi.time - Tone.getContext().currentTime * 1000;
|
||||
time = time * 1000 + timingOffset;
|
||||
// const inMs = '+' + (time - Tone.getContext().currentTime) * 1000;
|
||||
// await enableWebMidi()
|
||||
device.playNote(note, channel, {
|
||||
time,
|
||||
duration: hap.duration.valueOf() * 1000 - 5,
|
||||
velocity,
|
||||
});
|
||||
};
|
||||
return hap.setContext({ ...hap.context, onTrigger });
|
||||
return this.onTrigger((time, hap) => {
|
||||
let note = getPlayableNoteValue(hap);
|
||||
const velocity = hap.context?.velocity ?? 0.9;
|
||||
if (!isNote(note)) {
|
||||
throw new Error('not a note: ' + note);
|
||||
}
|
||||
if (!midiReady) {
|
||||
return;
|
||||
}
|
||||
const device = getDevice(output, WebMidi.outputs);
|
||||
if (!device) {
|
||||
throw new Error(
|
||||
`🔌 MIDI device '${output ? output : ''}' not found. Use one of ${WebMidi.outputs
|
||||
.map((o) => `'${o.name}'`)
|
||||
.join(' | ')}`,
|
||||
);
|
||||
}
|
||||
// console.log('midi', value, output);
|
||||
const timingOffset = WebMidi.time - getAudioContext().currentTime * 1000;
|
||||
time = time * 1000 + timingOffset;
|
||||
// const inMs = '+' + (time - Tone.getContext().currentTime) * 1000;
|
||||
// await enableWebMidi()
|
||||
device.playNote(note, channel, {
|
||||
time,
|
||||
duration: hap.duration.valueOf() * 1000 - 5,
|
||||
attack: velocity,
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
Generated
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/midi",
|
||||
"version": "0.3.3",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/midi",
|
||||
"version": "0.3.3",
|
||||
"version": "0.5.0",
|
||||
"description": "Midi API for strudel",
|
||||
"main": "index.mjs",
|
||||
"repository": {
|
||||
@@ -21,7 +21,7 @@
|
||||
},
|
||||
"homepage": "https://github.com/tidalcycles/strudel#readme",
|
||||
"dependencies": {
|
||||
"@strudel.cycles/tone": "^0.3.3",
|
||||
"@strudel.cycles/tone": "^0.5.0",
|
||||
"tone": "^14.7.77",
|
||||
"webmidi": "^3.0.21"
|
||||
}
|
||||
|
||||
@@ -32,7 +32,7 @@ yields:
|
||||
|
||||
## Mini Notation API
|
||||
|
||||
See "Mini Notation" in the [Strudel Tutorial](https://strudel.tidalcycles.org/tutorial/)
|
||||
See "Mini Notation" in the [Strudel Tutorial](https://strudel.tidalcycles.org/learn/mini-notation)
|
||||
|
||||
## Building the Parser
|
||||
|
||||
|
||||
+449
-361
File diff suppressed because it is too large
Load Diff
+80
-56
@@ -5,13 +5,20 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
*/
|
||||
|
||||
// Some terminology:
|
||||
// a sequence = a serie of elements placed between quotes
|
||||
// a stack = a serie of vertically aligned slices sharing the same overall length
|
||||
// a slice = a serie of horizontally aligned elements
|
||||
// a choose = a serie of elements, one of which is chosen at random
|
||||
// mini(notation) = a series of elements placed between quotes
|
||||
// a stack = a series of vertically aligned slices sharing the same overall length
|
||||
// a sequence = a series of horizontally aligned elements
|
||||
// a choose = a series of elements, one of which is chosen at random
|
||||
|
||||
|
||||
{
|
||||
var AtomStub = function(source)
|
||||
{
|
||||
this.type_ = "atom";
|
||||
this.source_ = source;
|
||||
this.location_ = location();
|
||||
}
|
||||
|
||||
var PatternStub = function(source, alignment)
|
||||
{
|
||||
this.type_ = "pattern";
|
||||
@@ -90,82 +97,99 @@ quote = '"' / "'"
|
||||
|
||||
// single step definition (e.g bd)
|
||||
step_char = [0-9a-zA-Z~] / "-" / "#" / "." / "^" / "_" / ":"
|
||||
step = ws chars:step_char+ ws { return chars.join("") }
|
||||
step = ws chars:step_char+ ws { return new AtomStub(chars.join("")) }
|
||||
|
||||
// define a sub cycle e.g. [1 2, 3 [4]]
|
||||
sub_cycle = ws "[" ws s:stack_or_choose ws "]" ws { return s}
|
||||
sub_cycle = ws "[" ws s:stack_or_choose ws "]" ws { return s }
|
||||
|
||||
// define a timeline e.g <1 3 [3 5]>. We simply defer to a stack and change the alignement
|
||||
timeline = ws "<" ws sc:single_cycle ws ">" ws
|
||||
{ sc.arguments_.alignment = "t"; return sc;}
|
||||
// define a polymeter e.g. {1 2, 3 4 5}
|
||||
polymeter = ws "{" ws s:polymeter_stack ws "}" stepsPerCycle:polymeter_steps? ws
|
||||
{ s.arguments_.stepsPerCycle = stepsPerCycle ; return s; }
|
||||
|
||||
polymeter_steps = "%"a:slice
|
||||
{ return a }
|
||||
|
||||
// define a step-per-cycle timeline e.g <1 3 [3 5]>. We simply defer to a sequence and
|
||||
// change the alignment to slowcat
|
||||
slow_sequence = ws "<" ws s:sequence ws ">" ws
|
||||
{ s.arguments_.alignment = 'slowcat'; return s; }
|
||||
|
||||
// a slice is either a single step or a sub cycle
|
||||
slice = step / sub_cycle / timeline
|
||||
slice = step / sub_cycle / polymeter / slow_sequence
|
||||
|
||||
// slice modifier affects the timing/size of a slice (e.g. [a b c]@3)
|
||||
// at this point, we assume we can represent them as regular sequence operators
|
||||
slice_modifier = slice_weight / slice_bjorklund / slice_slow / slice_fast / slice_fixed_step / slice_replicate / slice_degrade
|
||||
slice_op = op_weight / op_bjorklund / op_slow / op_fast / op_replicate / op_degrade
|
||||
|
||||
slice_weight = "@" a:number
|
||||
{ return { weight: a} }
|
||||
op_weight = "@" a:number
|
||||
{ return x => x.options_['weight'] = a }
|
||||
|
||||
slice_replicate = "!"a:number
|
||||
{ return { replicate: a } }
|
||||
op_replicate = "!"a:number
|
||||
{ return x => x.options_['reps'] = a }
|
||||
|
||||
slice_bjorklund = "(" ws p:number ws comma ws s:number ws comma? ws r:number? ws ")"
|
||||
{ return { operator : { type_: "bjorklund", arguments_ :{ pulse: p, step:s, rotation:r || 0 } } } }
|
||||
op_bjorklund = "(" ws p:slice_with_ops ws comma ws s:slice_with_ops ws comma? ws r:slice_with_ops? ws ")"
|
||||
{ return x => x.options_['ops'].push({ type_: "bjorklund", arguments_ :{ pulse: p, step:s, rotation:r }}) }
|
||||
|
||||
slice_slow = "/"a:number
|
||||
{ return { operator : { type_: "stretch", arguments_ :{ amount:a } } } }
|
||||
op_slow = "/"a:slice
|
||||
{ return x => x.options_['ops'].push({ type_: "stretch", arguments_ :{ amount:a, type: 'slow' }}) }
|
||||
|
||||
slice_fast = "*"a:number
|
||||
{ return { operator : { type_: "stretch", arguments_ :{ amount:"1/"+a } } } }
|
||||
op_fast = "*"a:slice
|
||||
{ return x => x.options_['ops'].push({ type_: "stretch", arguments_ :{ amount:a, type: 'fast' }}) }
|
||||
|
||||
slice_fixed_step = "%"a:number
|
||||
{ return { operator : { type_: "fixed-step", arguments_ :{ amount:a } } } }
|
||||
|
||||
slice_degrade = "?"a:number?
|
||||
{ return { operator : { type_: "degradeBy", arguments_ :{ amount:(a? a : 0.5) } } } }
|
||||
op_degrade = "?"a:number?
|
||||
{ return x => x.options_['ops'].push({ type_: "degradeBy", arguments_ :{ amount:a } }) }
|
||||
|
||||
// a slice with an modifier applied i.e [bd@4 sd@3]@2 hh]
|
||||
slice_with_modifier = s:slice o:slice_modifier?
|
||||
{ return new ElementStub(s, o);}
|
||||
slice_with_ops = s:slice ops:slice_op*
|
||||
{ const result = new ElementStub(s, {ops: [], weight: 1, reps: 1});
|
||||
for (const op of ops) {
|
||||
op(result);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// a single cycle is a combination of one or more successive slices (as an array). If we
|
||||
// have only one element, we skip the array and return the element itself
|
||||
single_cycle = s:(slice_with_modifier)+
|
||||
{ return new PatternStub(s,"h"); }
|
||||
// a sequence is a combination of one or more successive slices (as an array)
|
||||
sequence = s:(slice_with_ops)+
|
||||
{ return new PatternStub(s, 'fastcat'); }
|
||||
|
||||
// a stack is a serie of vertically aligned single cycles, separated by a comma
|
||||
stack_tail = tail:(comma @single_cycle)+
|
||||
{ return { alignment: 'v', list: tail }; }
|
||||
// a stack is a series of vertically aligned sequence, separated by a comma
|
||||
stack_tail = tail:(comma @sequence)+
|
||||
{ return { alignment: 'stack', list: tail }; }
|
||||
|
||||
// a choose is a serie of pipe-separated single cycles, one of which is chosen
|
||||
// at random each time through the pattern
|
||||
choose_tail = tail:(pipe @single_cycle)+
|
||||
{ return { alignment: 'r', list: tail }; }
|
||||
// a choose is a series of pipe-separated sequence, one of which is
|
||||
// chosen at random, each cycle
|
||||
choose_tail = tail:(pipe @sequence)+
|
||||
{ return { alignment: 'rand', list: tail }; }
|
||||
|
||||
// if the stack contains only one element, we don't create a stack but return the
|
||||
// underlying element
|
||||
stack_or_choose = head:single_cycle tail:(stack_tail / choose_tail)?
|
||||
stack_or_choose = head:sequence tail:(stack_tail / choose_tail)?
|
||||
{ if (tail && tail.list.length > 0) { return new PatternStub([head, ...tail.list], tail.alignment); } else { return head; } }
|
||||
|
||||
// a sequence is a quoted stack
|
||||
sequence = ws quote sc:stack_or_choose quote
|
||||
polymeter_stack = head:sequence tail:stack_tail?
|
||||
{ return new PatternStub(tail ? [head, ...tail.list] : [head], 'polymeter'); }
|
||||
|
||||
|
||||
// Mini-notation innards ends
|
||||
// ---------->8---------->8---------->8---------->8---------->8----------
|
||||
// Experimental haskellish parser begins
|
||||
|
||||
// mini-notation = a quoted stack
|
||||
mini = ws quote sc:stack_or_choose quote
|
||||
{ return sc; }
|
||||
|
||||
// ------------------ operators ---------------------------
|
||||
|
||||
operator = scale / slow / fast / target / bjorklund / struct / rotR / rotL
|
||||
|
||||
struct = "struct" ws s:sequence_or_operator
|
||||
{ return { name: "struct", args: { sequence:s }}}
|
||||
struct = "struct" ws s:mini_or_operator
|
||||
{ return { name: "struct", args: { mini:s }}}
|
||||
|
||||
target = "target" ws quote s:step quote
|
||||
{ return { name: "target", args : { name:s}}}
|
||||
|
||||
bjorklund = "euclid" ws p:int ws s:int ws r:int?
|
||||
{ return { name: "bjorklund", args :{ pulse: parseInt(p), step:parseInt(s) }}}
|
||||
{ return { name: "bjorklund", args :{ pulse: p, step:parseInt(s) }}}
|
||||
|
||||
slow = "slow" ws a:number
|
||||
{ return { name: "stretch", args :{ amount: a}}}
|
||||
@@ -189,27 +213,27 @@ comment = '//' p:([^\n]*)
|
||||
group_operator = cat
|
||||
|
||||
// cat is another form of timeline
|
||||
cat = "cat" ws "[" ws s:sequence_or_operator ss:(comma v:sequence_or_operator { return v})* ws "]"
|
||||
{ ss.unshift(s); return new PatternStub(ss,"t"); }
|
||||
cat = "cat" ws "[" ws s:mini_or_operator ss:(comma v:mini_or_operator { return v})* ws "]"
|
||||
{ ss.unshift(s); return new PatternStub(ss, 'slowcat'); }
|
||||
|
||||
// ------------------ high level sequence ---------------------------
|
||||
// ------------------ high level mini ---------------------------
|
||||
|
||||
sequence_or_group =
|
||||
mini_or_group =
|
||||
group_operator /
|
||||
sequence
|
||||
mini
|
||||
|
||||
sequence_or_operator =
|
||||
sg:sequence_or_group ws (comment)*
|
||||
mini_or_operator =
|
||||
sg:mini_or_group ws (comment)*
|
||||
{return sg}
|
||||
/ o:operator ws "$" ws soc:sequence_or_operator
|
||||
/ o:operator ws "$" ws soc:mini_or_operator
|
||||
{ return new OperatorStub(o.name,o.args,soc)}
|
||||
|
||||
sequ_or_operator_or_comment =
|
||||
sc: sequence_or_operator
|
||||
sc: mini_or_operator
|
||||
{ return sc }
|
||||
/ comment
|
||||
|
||||
sequence_definition = s:sequ_or_operator_or_comment
|
||||
mini_definition = s:sequ_or_operator_or_comment
|
||||
|
||||
// ---------------------- statements ----------------------------
|
||||
|
||||
@@ -227,4 +251,4 @@ hush = "hush"
|
||||
|
||||
// ---------------------- statements ----------------------------
|
||||
|
||||
statement = sequence_definition / command
|
||||
statement = mini_definition / command
|
||||
|
||||
+127
-104
@@ -6,131 +6,158 @@ 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.cycles/core';
|
||||
// import { addMiniLocations } from '@strudel.cycles/eval/shapeshifter.mjs';
|
||||
|
||||
const { pure, Pattern, Fraction, stack, slowcat, sequence, timeCat, silence, reify } = strudel;
|
||||
|
||||
var _seedState = 0;
|
||||
/* var _seedState = 0;
|
||||
const randOffset = 0.0002;
|
||||
|
||||
function _nextSeed() {
|
||||
return _seedState++;
|
||||
}
|
||||
} */
|
||||
|
||||
const applyOptions = (parent) => (pat, i) => {
|
||||
const applyOptions = (parent, code) => (pat, i) => {
|
||||
const ast = parent.source_[i];
|
||||
const options = ast.options_;
|
||||
const operator = options?.operator;
|
||||
if (operator) {
|
||||
switch (operator.type_) {
|
||||
case 'stretch':
|
||||
const speed = Fraction(operator.arguments_.amount).inverse();
|
||||
return reify(pat).fast(speed);
|
||||
case 'bjorklund':
|
||||
return pat.euclid(operator.arguments_.pulse, operator.arguments_.step, operator.arguments_.rotation);
|
||||
case 'degradeBy':
|
||||
return reify(pat)._degradeByWith(
|
||||
const ops = options?.ops;
|
||||
if (ops) {
|
||||
for (const op of ops) {
|
||||
switch (op.type_) {
|
||||
case 'stretch': {
|
||||
const legalTypes = ['fast', 'slow'];
|
||||
const { type, amount } = op.arguments_;
|
||||
if (!legalTypes.includes(type)) {
|
||||
throw new Error(`mini: stretch: type must be one of ${legalTypes.join('|')} but got ${type}`);
|
||||
}
|
||||
pat = strudel.reify(pat)[type](patternifyAST(amount, code));
|
||||
break;
|
||||
}
|
||||
case 'bjorklund': {
|
||||
if (op.arguments_.rotation) {
|
||||
pat = pat.euclidRot(
|
||||
patternifyAST(op.arguments_.pulse, code),
|
||||
patternifyAST(op.arguments_.step, code),
|
||||
patternifyAST(op.arguments_.rotation, code),
|
||||
);
|
||||
} else {
|
||||
pat = pat.euclid(patternifyAST(op.arguments_.pulse, code), patternifyAST(op.arguments_.step, code));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'degradeBy': {
|
||||
// TODO: find out what is right here
|
||||
// example:
|
||||
/*
|
||||
stack(
|
||||
s("hh*8").degrade(),
|
||||
s("[ht*8]?")
|
||||
)
|
||||
*/
|
||||
// above example will only be in sync when _degradeBy is used...
|
||||
// it also seems that the nextSeed will create undeterministic behaviour
|
||||
// as it uses a global _seedState. This is probably the reason for
|
||||
// https://github.com/tidalcycles/strudel/issues/245
|
||||
|
||||
// this is how it was:
|
||||
/*
|
||||
return strudel.reify(pat)._degradeByWith(
|
||||
strudel.rand.early(randOffset * _nextSeed()).segment(1),
|
||||
operator.arguments_.amount,
|
||||
);
|
||||
// TODO: case 'fixed-step': "%"
|
||||
op.arguments_.amount ?? 0.5,
|
||||
);
|
||||
*/
|
||||
pat = strudel.reify(pat).degradeBy(op.arguments_.amount === null ? 0.5 : op.arguments_.amount);
|
||||
break;
|
||||
}
|
||||
default: {
|
||||
console.warn(`operator "${op.type_}" not implemented`);
|
||||
}
|
||||
}
|
||||
}
|
||||
console.warn(`operator "${operator.type_}" not implemented`);
|
||||
}
|
||||
if (options?.weight) {
|
||||
// weight is handled by parent
|
||||
return pat;
|
||||
}
|
||||
// TODO: bjorklund e.g. "c3(5,8)"
|
||||
const unimplemented = Object.keys(options || {}).filter((key) => key !== 'operator');
|
||||
if (unimplemented.length) {
|
||||
console.warn(
|
||||
`option${unimplemented.length > 1 ? 's' : ''} ${unimplemented.map((o) => `"${o}"`).join(', ')} not implemented`,
|
||||
);
|
||||
}
|
||||
|
||||
return pat;
|
||||
};
|
||||
|
||||
function resolveReplications(ast) {
|
||||
// the general idea here: x!3 = [x*3]@3
|
||||
// could this be made easier?!
|
||||
ast.source_ = ast.source_.map((child) => {
|
||||
const { replicate, ...options } = child.options_ || {};
|
||||
if (replicate) {
|
||||
return {
|
||||
...child,
|
||||
options_: { ...options, weight: replicate },
|
||||
source_: {
|
||||
type_: 'pattern',
|
||||
arguments_: {
|
||||
alignment: 'h',
|
||||
},
|
||||
source_: [
|
||||
{
|
||||
type_: 'element',
|
||||
source_: child.source_,
|
||||
location_: child.location_,
|
||||
options_: {
|
||||
operator: {
|
||||
type_: 'stretch',
|
||||
arguments_: { amount: Fraction(replicate).inverse().toString() },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
}
|
||||
return child;
|
||||
});
|
||||
ast.source_ = strudel.flatten(
|
||||
ast.source_.map((child) => {
|
||||
const { reps } = child.options_ || {};
|
||||
if (!reps) {
|
||||
return [child];
|
||||
}
|
||||
delete child.options_.reps;
|
||||
return Array(reps).fill(child);
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
export function patternifyAST(ast) {
|
||||
export function patternifyAST(ast, code) {
|
||||
switch (ast.type_) {
|
||||
case 'pattern':
|
||||
case 'pattern': {
|
||||
resolveReplications(ast);
|
||||
const children = ast.source_.map(patternifyAST).map(applyOptions(ast));
|
||||
const children = ast.source_.map((child) => patternifyAST(child, code)).map(applyOptions(ast, code));
|
||||
const alignment = ast.arguments_.alignment;
|
||||
if (alignment === 'v') {
|
||||
return stack(...children);
|
||||
if (alignment === 'stack') {
|
||||
return strudel.stack(...children);
|
||||
}
|
||||
if (alignment === 'r') {
|
||||
return strudel.chooseInWith(strudel.rand.early(randOffset * _nextSeed()).segment(1), children);
|
||||
if (alignment === 'polymeter') {
|
||||
// polymeter
|
||||
const stepsPerCycle = ast.arguments_.stepsPerCycle
|
||||
? patternifyAST(ast.arguments_.stepsPerCycle, code).fmap((x) => strudel.Fraction(x))
|
||||
: strudel.pure(strudel.Fraction(children.length > 0 ? children[0].__weight : 1));
|
||||
|
||||
const aligned = children.map((child) => child.fast(stepsPerCycle.fmap((x) => x.div(child.__weight || 1))));
|
||||
return strudel.stack(...aligned);
|
||||
}
|
||||
if (alignment === 'rand') {
|
||||
// https://github.com/tidalcycles/strudel/issues/245#issuecomment-1345406422
|
||||
// return strudel.chooseInWith(strudel.rand.early(randOffset * _nextSeed()).segment(1), children);
|
||||
return strudel.chooseCycles(...children);
|
||||
}
|
||||
const weightedChildren = ast.source_.some((child) => !!child.options_?.weight);
|
||||
if (!weightedChildren && alignment === 't') {
|
||||
return slowcat(...children);
|
||||
if (!weightedChildren && alignment === 'slowcat') {
|
||||
return strudel.slowcat(...children);
|
||||
}
|
||||
if (weightedChildren) {
|
||||
const pat = timeCat(...ast.source_.map((child, i) => [child.options_?.weight || 1, children[i]]));
|
||||
if (alignment === 't') {
|
||||
const weightSum = ast.source_.reduce((sum, child) => sum + (child.options_?.weight || 1), 0);
|
||||
const weightSum = ast.source_.reduce((sum, child) => sum + (child.options_?.weight || 1), 0);
|
||||
const pat = strudel.timeCat(...ast.source_.map((child, i) => [child.options_?.weight || 1, children[i]]));
|
||||
if (alignment === 'slowcat') {
|
||||
return pat._slow(weightSum); // timecat + slow
|
||||
}
|
||||
pat.__weight = weightSum;
|
||||
return pat;
|
||||
}
|
||||
return sequence(...children);
|
||||
case 'element':
|
||||
const pat = strudel.sequence(...children);
|
||||
pat.__weight = children.length;
|
||||
return pat;
|
||||
}
|
||||
case 'element': {
|
||||
return patternifyAST(ast.source_, code);
|
||||
}
|
||||
case 'atom': {
|
||||
if (ast.source_ === '~') {
|
||||
return silence;
|
||||
return strudel.silence;
|
||||
}
|
||||
if (typeof ast.source_ !== 'object') {
|
||||
/* if (!addMiniLocations) {
|
||||
return ast.source_;
|
||||
} */
|
||||
if (!ast.location_) {
|
||||
console.warn('no location for', ast);
|
||||
return ast.source_;
|
||||
}
|
||||
const { start, end } = ast.location_;
|
||||
const value = !isNaN(Number(ast.source_)) ? Number(ast.source_) : ast.source_;
|
||||
// the following line expects the shapeshifter append .withMiniLocation
|
||||
// because location_ is only relative to the mini string, but we need it relative to whole code
|
||||
return pure(value).withLocation([start.line, start.column, start.offset], [end.line, end.column, end.offset]);
|
||||
if (!ast.location_) {
|
||||
console.warn('no location for', ast);
|
||||
return ast.source_;
|
||||
}
|
||||
return patternifyAST(ast.source_);
|
||||
const { start, end } = ast.location_;
|
||||
const value = !isNaN(Number(ast.source_)) ? Number(ast.source_) : ast.source_;
|
||||
// the following line expects the shapeshifter append .withMiniLocation
|
||||
// because location_ is only relative to the mini string, but we need it relative to whole code
|
||||
// make sure whitespaces are not part of the highlight:
|
||||
const actual = code?.split('').slice(start.offset, end.offset).join('');
|
||||
const [offsetStart = 0, offsetEnd = 0] = actual
|
||||
? actual.split(ast.source_).map((p) => p.split('').filter((c) => c === ' ').length)
|
||||
: [];
|
||||
return strudel
|
||||
.pure(value)
|
||||
.withLocation(
|
||||
[start.line, start.column + offsetStart, start.offset + offsetStart],
|
||||
[start.line, end.column - offsetEnd, end.offset - offsetEnd],
|
||||
);
|
||||
}
|
||||
case 'stretch':
|
||||
return patternifyAST(ast.source_).slow(ast.arguments_.amount);
|
||||
return patternifyAST(ast.source_, code).slow(patternifyAST(ast.arguments_.amount, code));
|
||||
/* case 'scale':
|
||||
let [tonic, scale] = Scale.tokenize(ast.arguments_.scale);
|
||||
const intervals = Scale.get(scale).intervals;
|
||||
@@ -152,37 +179,33 @@ export function patternifyAST(ast) {
|
||||
}); */
|
||||
/* case 'struct':
|
||||
// TODO:
|
||||
return silence; */
|
||||
return strudel.silence; */
|
||||
default:
|
||||
console.warn(`node type "${ast.type_}" not implemented -> returning silence`);
|
||||
return silence;
|
||||
return strudel.silence;
|
||||
}
|
||||
}
|
||||
|
||||
// mini notation only (wraps in "")
|
||||
export const mini = (...strings) => {
|
||||
const pats = strings.map((str) => {
|
||||
const ast = krill.parse(`"${str}"`);
|
||||
return patternifyAST(ast);
|
||||
const code = `"${str}"`;
|
||||
const ast = krill.parse(code);
|
||||
return patternifyAST(ast, code);
|
||||
});
|
||||
return sequence(...pats);
|
||||
return strudel.sequence(...pats);
|
||||
};
|
||||
|
||||
// includes haskell style (raw krill parsing)
|
||||
export const h = (string) => {
|
||||
const ast = krill.parse(string);
|
||||
// console.log('ast', ast);
|
||||
return patternifyAST(ast);
|
||||
return patternifyAST(ast, string);
|
||||
};
|
||||
|
||||
// shorthand for mini
|
||||
Pattern.prototype.define('mini', mini, { composable: true });
|
||||
Pattern.prototype.define('m', mini, { composable: true });
|
||||
Pattern.prototype.define('h', h, { composable: true });
|
||||
|
||||
export function minify(thing) {
|
||||
if (typeof thing === 'string') {
|
||||
return mini(thing);
|
||||
}
|
||||
return reify(thing);
|
||||
return strudel.reify(thing);
|
||||
}
|
||||
|
||||
Generated
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/mini",
|
||||
"version": "0.3.3",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/mini",
|
||||
"version": "0.3.3",
|
||||
"version": "0.5.0",
|
||||
"description": "Mini notation for strudel",
|
||||
"main": "index.mjs",
|
||||
"type": "module",
|
||||
@@ -26,9 +26,9 @@
|
||||
},
|
||||
"homepage": "https://github.com/tidalcycles/strudel#readme",
|
||||
"dependencies": {
|
||||
"@strudel.cycles/core": "^0.3.2",
|
||||
"@strudel.cycles/eval": "^0.3.2",
|
||||
"@strudel.cycles/tone": "^0.3.3"
|
||||
"@strudel.cycles/core": "^0.5.0",
|
||||
"@strudel.cycles/eval": "^0.5.0",
|
||||
"@strudel.cycles/tone": "^0.5.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"peggy": "^2.0.1"
|
||||
|
||||
@@ -9,8 +9,8 @@ import '@strudel.cycles/core/euclid.mjs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
|
||||
describe('mini', () => {
|
||||
const minV = (v) => mini(v)._firstCycleValues;
|
||||
const minS = (v) => mini(v)._showFirstCycle;
|
||||
const minV = (v) => mini(v).sortHapsByPart().firstCycleValues;
|
||||
const minS = (v) => mini(v).sortHapsByPart().showFirstCycle;
|
||||
it('supports single elements', () => {
|
||||
expect(minV('a')).toEqual(['a']);
|
||||
});
|
||||
@@ -21,6 +21,21 @@ describe('mini', () => {
|
||||
expect(minS('a b')).toEqual(['a: 0 - 1/2', 'b: 1/2 - 1']);
|
||||
expect(minS('a b c')).toEqual(['a: 0 - 1/3', 'b: 1/3 - 2/3', 'c: 2/3 - 1']);
|
||||
});
|
||||
it('supports fast', () => {
|
||||
expect(minS('a*3 b')).toEqual(minS('[a a a] b'));
|
||||
});
|
||||
it('supports patterned fast', () => {
|
||||
expect(minS('[a*<3 5>]*2')).toEqual(minS('[a a a] [a a a a a]'));
|
||||
});
|
||||
it('supports slow', () => {
|
||||
expect(minS('[a a a]/3 b')).toEqual(minS('a b'));
|
||||
});
|
||||
it('supports patterned slow', () => {
|
||||
expect(minS('[a a a a a a a a]/[2 4]')).toEqual(minS('[a a] a'));
|
||||
});
|
||||
it('supports patterned fast', () => {
|
||||
expect(minS('[a*<3 5>]*2')).toEqual(minS('[a a a] [a a a a a]'));
|
||||
});
|
||||
it('supports slowcat', () => {
|
||||
expect(minV('<a b>')).toEqual(['a']);
|
||||
});
|
||||
@@ -36,6 +51,16 @@ describe('mini', () => {
|
||||
expect(minS('c3 [d3 e3]')).toEqual(['c3: 0 - 1/2', 'd3: 1/2 - 3/4', 'e3: 3/4 - 1']);
|
||||
expect(minS('c3 [d3 [e3 f3]]')).toEqual(['c3: 0 - 1/2', 'd3: 1/2 - 3/4', 'e3: 3/4 - 7/8', 'f3: 7/8 - 1']);
|
||||
});
|
||||
it('supports curly brackets', () => {
|
||||
expect(minS('{a b, c d e}*3')).toEqual(minS('[a b a b a b, c d e c d e]'));
|
||||
expect(minS('{a b, c [d e] f}*3')).toEqual(minS('[a b a b a b, c [d e] f c [d e] f]'));
|
||||
expect(minS('{a b c, d e}*2')).toEqual(minS('[a b c a b c, d e d e d e]'));
|
||||
});
|
||||
it('supports curly brackets with explicit step-per-cycle', () => {
|
||||
expect(minS('{a b, c d e}%3')).toEqual(minS('[a b a, c d e]'));
|
||||
expect(minS('{a b, c d e}%5')).toEqual(minS('[a b a b a, c d e c d]'));
|
||||
expect(minS('{a b, c d e}%6')).toEqual(minS('[a b a b a b, c d e c d e]'));
|
||||
});
|
||||
it('supports commas', () => {
|
||||
expect(minS('c3,e3,g3')).toEqual(['c3: 0 - 1', 'e3: 0 - 1', 'g3: 0 - 1']);
|
||||
expect(minS('[c3,e3,g3] f3')).toEqual(['c3: 0 - 1/2', 'e3: 0 - 1/2', 'g3: 0 - 1/2', 'f3: 1/2 - 1']);
|
||||
@@ -46,10 +71,48 @@ describe('mini', () => {
|
||||
});
|
||||
it('supports replication', () => {
|
||||
expect(minS('a!3 b')).toEqual(['a: 0 - 1/4', 'a: 1/4 - 1/2', 'a: 1/2 - 3/4', 'b: 3/4 - 1']);
|
||||
expect(minS('[<a b c>]!3 d')).toEqual(minS('<a b c> <a b c> <a b c> d'));
|
||||
});
|
||||
it('supports euclidean rhythms', () => {
|
||||
expect(minS('a(3, 8)')).toEqual(['a: 0 - 1/8', 'a: 3/8 - 1/2', 'a: 3/4 - 7/8']);
|
||||
});
|
||||
it('supports patterning euclidean rhythms', () => {
|
||||
expect(minS('[a(<3 5>, <8 16>)]*2')).toEqual(minS('a(3,8) a(5,16)'));
|
||||
});
|
||||
it("reproduces Toussaint's example euclidean algorithms", () => {
|
||||
const checkEuclid = function (spec, target) {
|
||||
expect(minS(`x(${spec[0]},${spec[1]})`)).toEqual(minS(target));
|
||||
};
|
||||
checkEuclid([1, 2], 'x ~');
|
||||
checkEuclid([1, 3], 'x ~ ~');
|
||||
checkEuclid([1, 4], 'x ~ ~ ~');
|
||||
checkEuclid([4, 12], 'x ~ ~ x ~ ~ x ~ ~ x ~ ~');
|
||||
checkEuclid([2, 5], 'x ~ x ~ ~');
|
||||
// checkEuclid([3, 4], "x ~ x x"); // Toussaint is wrong..
|
||||
checkEuclid([3, 4], 'x x x ~'); // correction
|
||||
checkEuclid([3, 5], 'x ~ x ~ x');
|
||||
checkEuclid([3, 7], 'x ~ x ~ x ~ ~');
|
||||
checkEuclid([3, 8], 'x ~ ~ x ~ ~ x ~');
|
||||
checkEuclid([4, 7], 'x ~ x ~ x ~ x');
|
||||
checkEuclid([4, 9], 'x ~ x ~ x ~ x ~ ~');
|
||||
checkEuclid([4, 11], 'x ~ ~ x ~ ~ x ~ ~ x ~');
|
||||
// checkEuclid([5, 6], "x ~ x x x x"); // Toussaint is wrong..
|
||||
checkEuclid([5, 6], 'x x x x x ~'); // correction
|
||||
checkEuclid([5, 7], 'x ~ x x ~ x x');
|
||||
checkEuclid([5, 8], 'x ~ x x ~ x x ~');
|
||||
checkEuclid([5, 9], 'x ~ x ~ x ~ x ~ x');
|
||||
checkEuclid([5, 11], 'x ~ x ~ x ~ x ~ x ~ ~');
|
||||
checkEuclid([5, 12], 'x ~ ~ x ~ x ~ ~ x ~ x ~');
|
||||
// checkEuclid([5, 16], "x ~ ~ x ~ ~ x ~ ~ x ~ ~ x ~ ~ ~ ~"); // Toussaint is wrong..
|
||||
checkEuclid([5, 16], 'x ~ ~ x ~ ~ x ~ ~ x ~ ~ x ~ ~ ~'); // correction
|
||||
// checkEuclid([7, 8], "x ~ x x x x x x"); // Toussaint is wrong..
|
||||
checkEuclid([7, 8], 'x x x x x x x ~'); // Correction
|
||||
checkEuclid([7, 12], 'x ~ x x ~ x ~ x x ~ x ~');
|
||||
checkEuclid([7, 16], 'x ~ ~ x ~ x ~ x ~ ~ x ~ x ~ x ~');
|
||||
checkEuclid([9, 16], 'x ~ x x ~ x ~ x ~ x x ~ x ~ x ~');
|
||||
checkEuclid([11, 24], 'x ~ ~ x ~ x ~ x ~ x ~ x ~ ~ x ~ x ~ x ~ x ~ x ~');
|
||||
checkEuclid([13, 24], 'x ~ x x ~ x ~ x ~ x ~ x ~ x x ~ x ~ x ~ x ~ x ~');
|
||||
});
|
||||
it('supports the ? operator', () => {
|
||||
expect(
|
||||
mini('a?')
|
||||
@@ -77,7 +140,7 @@ describe('mini', () => {
|
||||
expect(haps.length < 230).toBe(true);
|
||||
// 'Had too many cycles remaining after degradeBy 0.8');
|
||||
});
|
||||
it('supports the random choice operator ("|") with nesting', () => {
|
||||
/*it('supports the random choice operator ("|") with nesting', () => {
|
||||
const numCycles = 900;
|
||||
const haps = mini('a | [b | c] | [d | e | f]').queryArc(0, numCycles);
|
||||
// Should have about 1/3 a, 1/6 each of b | c, and 1/9 each of d | e | f.
|
||||
@@ -103,5 +166,5 @@ describe('mini', () => {
|
||||
// PRNG, this test should succeed
|
||||
expect(chisq <= 15.086).toBe(true);
|
||||
// assert(chisq <= 15.086, chisq + ' was expected to be less than 15.086 under chi-squared test');
|
||||
});
|
||||
});*/
|
||||
});
|
||||
|
||||
@@ -36,4 +36,4 @@ s("<bd sd> hh").osc()
|
||||
|
||||
or just [click here](http://localhost:3000/#cygiPGJkIHNkPiBoaCIpLm9zYygp)...
|
||||
|
||||
You can read more about [how to use Superdirt with Strudel the Tutorial](https://strudel.tidalcycles.org/tutorial/#superdirt-api)
|
||||
You can read more about [how to use Superdirt with Strudel the Tutorial](https://strudel.tidalcycles.org/learn/outputs#superdirt-api)
|
||||
|
||||
+47
-26
@@ -5,10 +5,34 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
*/
|
||||
|
||||
import OSC from 'osc-js';
|
||||
import { parseNumeral, Pattern } from '@strudel.cycles/core';
|
||||
import { logger, parseNumeral, Pattern } from '@strudel.cycles/core';
|
||||
|
||||
let connection; // Promise<OSC>
|
||||
function connect() {
|
||||
if (!connection) {
|
||||
// make sure this runs only once
|
||||
connection = new Promise((resolve, reject) => {
|
||||
const osc = new OSC();
|
||||
osc.open();
|
||||
osc.on('open', () => {
|
||||
const url = osc.options?.plugin?.socket?.url;
|
||||
logger(`[osc] connected${url ? ` to ${url}` : ''}`);
|
||||
resolve(osc);
|
||||
});
|
||||
osc.on('close', () => {
|
||||
connection = undefined; // allows new connection afterwards
|
||||
console.log('[osc] disconnected');
|
||||
reject('OSC connection closed');
|
||||
});
|
||||
osc.on('error', (err) => reject(err));
|
||||
}).catch((err) => {
|
||||
connection = undefined;
|
||||
throw new Error('Could not connect to OSC server. Is it running?');
|
||||
});
|
||||
}
|
||||
return connection;
|
||||
}
|
||||
|
||||
const comm = new OSC();
|
||||
comm.open();
|
||||
const latency = 0.1;
|
||||
let startedAt = -1;
|
||||
|
||||
@@ -20,28 +44,25 @@ let startedAt = -1;
|
||||
* @memberof Pattern
|
||||
* @returns Pattern
|
||||
*/
|
||||
Pattern.prototype.osc = function () {
|
||||
return this._withHap((hap) => {
|
||||
const onTrigger = (time, hap, currentTime, cps) => {
|
||||
const cycle = hap.wholeOrPart().begin.valueOf();
|
||||
const delta = hap.duration.valueOf();
|
||||
// time should be audio time of onset
|
||||
// currentTime should be current time of audio context (slightly before time)
|
||||
if (startedAt < 0) {
|
||||
startedAt = Date.now() - currentTime * 1000;
|
||||
}
|
||||
const controls = Object.assign({}, { cps, cycle, delta }, hap.value);
|
||||
// make sure n and note are numbers
|
||||
controls.n && (controls.n = parseNumeral(controls.n));
|
||||
controls.note && (controls.note = parseNumeral(controls.note));
|
||||
|
||||
const keyvals = Object.entries(controls).flat();
|
||||
const ts = Math.floor(startedAt + (time + latency) * 1000);
|
||||
const message = new OSC.Message('/dirt/play', ...keyvals);
|
||||
const bundle = new OSC.Bundle([message], ts);
|
||||
bundle.timestamp(ts); // workaround for https://github.com/adzialocha/osc-js/issues/60
|
||||
comm.send(bundle);
|
||||
};
|
||||
return hap.setContext({ ...hap.context, onTrigger });
|
||||
Pattern.prototype.osc = async function () {
|
||||
const osc = await connect();
|
||||
return this.onTrigger((time, hap, currentTime, cps = 1) => {
|
||||
const cycle = hap.wholeOrPart().begin.valueOf();
|
||||
const delta = hap.duration.valueOf();
|
||||
// time should be audio time of onset
|
||||
// currentTime should be current time of audio context (slightly before time)
|
||||
if (startedAt < 0) {
|
||||
startedAt = Date.now() - currentTime * 1000;
|
||||
}
|
||||
const controls = Object.assign({}, { cps, cycle, delta }, hap.value);
|
||||
// make sure n and note are numbers
|
||||
controls.n && (controls.n = parseNumeral(controls.n));
|
||||
controls.note && (controls.note = parseNumeral(controls.note));
|
||||
const keyvals = Object.entries(controls).flat();
|
||||
const ts = Math.floor(startedAt + (time + latency) * 1000);
|
||||
const message = new OSC.Message('/dirt/play', ...keyvals);
|
||||
const bundle = new OSC.Bundle([message], ts);
|
||||
bundle.timestamp(ts); // workaround for https://github.com/adzialocha/osc-js/issues/60
|
||||
osc.send(bundle);
|
||||
});
|
||||
};
|
||||
|
||||
Generated
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/osc",
|
||||
"version": "0.2.0",
|
||||
"version": "0.4.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
{
|
||||
"name": "@strudel.cycles/osc",
|
||||
"version": "0.2.0",
|
||||
"version": "0.4.0",
|
||||
"description": "OSC messaging for strudel",
|
||||
"main": "osc.mjs",
|
||||
"scripts": {
|
||||
"test": "echo \"No tests present.\" && exit 0",
|
||||
"server": "node server.js",
|
||||
"tidal-sniffer": "node tidal-sniffer.js",
|
||||
"client": "npx serve -p 4321"
|
||||
"client": "npx serve -p 4321",
|
||||
"build": "npx pkg server.js --targets node16-macos-x64,node16-win-x64,node16-linux-x64 --out-path bin"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
@@ -31,5 +32,8 @@
|
||||
"homepage": "https://github.com/tidalcycles/strudel#readme",
|
||||
"dependencies": {
|
||||
"osc-js": "^2.4.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"pkg": "^5.7.0"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,8 +25,6 @@ const config = {
|
||||
},
|
||||
};
|
||||
|
||||
|
||||
|
||||
const osc = new OSC({ plugin: new OSC.BridgePlugin(config) });
|
||||
|
||||
osc.open(); // start a WebSocket server on port 8080
|
||||
|
||||
Vendored
+1
-3
File diff suppressed because one or more lines are too long
Vendored
+356
-382
@@ -1,17 +1,15 @@
|
||||
import y, { useCallback as T, useState as w, useEffect as q, useMemo as R, useRef as I, useLayoutEffect as j } from "react";
|
||||
import Y from "@uiw/react-codemirror";
|
||||
import { Decoration as A, EditorView as K } from "@codemirror/view";
|
||||
import { StateEffect as U, StateField as Q } from "@codemirror/state";
|
||||
import { javascript as Z } from "@codemirror/lang-javascript";
|
||||
import { tags as m } from "@lezer/highlight";
|
||||
import { createTheme as ee } from "@uiw/codemirror-themes";
|
||||
import { useInView as te } from "react-hook-inview";
|
||||
import { evaluate as G } from "@strudel.cycles/eval";
|
||||
import { Tone as M } from "@strudel.cycles/tone";
|
||||
import { TimeSpan as oe, State as re } from "@strudel.cycles/core";
|
||||
import { webaudioOutputTrigger as ne } from "@strudel.cycles/webaudio";
|
||||
import { WebMidi as N, enableWebMidi as se } from "@strudel.cycles/midi";
|
||||
const ae = ee({
|
||||
import d, { useCallback as E, useRef as A, useEffect as k, useMemo as Q, useState as _, useLayoutEffect as te } from "react";
|
||||
import ue from "@uiw/react-codemirror";
|
||||
import { Decoration as M, EditorView as re } from "@codemirror/view";
|
||||
import { StateEffect as ne, StateField as oe } from "@codemirror/state";
|
||||
import { javascript as de } from "@codemirror/lang-javascript";
|
||||
import { tags as u } from "@lezer/highlight";
|
||||
import { createTheme as fe } from "@uiw/codemirror-themes";
|
||||
import { webaudioOutput as me, getAudioContext as he } from "@strudel.cycles/webaudio";
|
||||
import { useInView as ge } from "react-hook-inview";
|
||||
import { repl as pe, logger as ve } from "@strudel.cycles/core";
|
||||
import { transpiler as be } from "@strudel.cycles/transpiler";
|
||||
const Ee = fe({
|
||||
theme: "dark",
|
||||
settings: {
|
||||
background: "#222",
|
||||
@@ -19,450 +17,426 @@ const ae = ee({
|
||||
caret: "#ffcc00",
|
||||
selection: "rgba(128, 203, 196, 0.5)",
|
||||
selectionMatch: "#036dd626",
|
||||
lineHighlight: "#8a91991a",
|
||||
lineHighlight: "#00000050",
|
||||
gutterBackground: "transparent",
|
||||
gutterForeground: "#676e95"
|
||||
gutterForeground: "#8a919966"
|
||||
},
|
||||
styles: [
|
||||
{ tag: m.keyword, color: "#c792ea" },
|
||||
{ tag: m.operator, color: "#89ddff" },
|
||||
{ tag: m.special(m.variableName), color: "#eeffff" },
|
||||
{ tag: m.typeName, color: "#f07178" },
|
||||
{ tag: m.atom, color: "#f78c6c" },
|
||||
{ tag: m.number, color: "#ff5370" },
|
||||
{ tag: m.definition(m.variableName), color: "#82aaff" },
|
||||
{ tag: m.string, color: "#c3e88d" },
|
||||
{ tag: m.special(m.string), color: "#f07178" },
|
||||
{ tag: m.comment, color: "#7d8799" },
|
||||
{ tag: m.variableName, color: "#f07178" },
|
||||
{ tag: m.tagName, color: "#ff5370" },
|
||||
{ tag: m.bracket, color: "#a2a1a4" },
|
||||
{ tag: m.meta, color: "#ffcb6b" },
|
||||
{ tag: m.attributeName, color: "#c792ea" },
|
||||
{ tag: m.propertyName, color: "#c792ea" },
|
||||
{ tag: m.className, color: "#decb6b" },
|
||||
{ tag: m.invalid, color: "#ffffff" }
|
||||
{ tag: u.keyword, color: "#c792ea" },
|
||||
{ tag: u.operator, color: "#89ddff" },
|
||||
{ tag: u.special(u.variableName), color: "#eeffff" },
|
||||
{ tag: u.typeName, color: "#c3e88d" },
|
||||
{ tag: u.atom, color: "#f78c6c" },
|
||||
{ tag: u.number, color: "#c3e88d" },
|
||||
{ tag: u.definition(u.variableName), color: "#82aaff" },
|
||||
{ tag: u.string, color: "#c3e88d" },
|
||||
{ tag: u.special(u.string), color: "#c3e88d" },
|
||||
{ tag: u.comment, color: "#7d8799" },
|
||||
{ tag: u.variableName, color: "#c792ea" },
|
||||
{ tag: u.tagName, color: "#c3e88d" },
|
||||
{ tag: u.bracket, color: "#525154" },
|
||||
{ tag: u.meta, color: "#ffcb6b" },
|
||||
{ tag: u.attributeName, color: "#c792ea" },
|
||||
{ tag: u.propertyName, color: "#c792ea" },
|
||||
{ tag: u.className, color: "#decb6b" },
|
||||
{ tag: u.invalid, color: "#ffffff" }
|
||||
]
|
||||
});
|
||||
const z = U.define(), ce = Q.define({
|
||||
const X = ne.define(), ye = oe.define({
|
||||
create() {
|
||||
return A.none;
|
||||
return M.none;
|
||||
},
|
||||
update(e, o) {
|
||||
update(e, t) {
|
||||
try {
|
||||
for (let r of o.effects)
|
||||
if (r.is(z))
|
||||
for (let r of t.effects)
|
||||
if (r.is(X))
|
||||
if (r.value) {
|
||||
const n = A.mark({ attributes: { style: "background-color: #FFCA2880" } });
|
||||
e = A.set([n.range(0, o.newDoc.length)]);
|
||||
const n = M.mark({ attributes: { style: "background-color: #FFCA2880" } });
|
||||
e = M.set([n.range(0, t.newDoc.length)]);
|
||||
} else
|
||||
e = A.set([]);
|
||||
e = M.set([]);
|
||||
return e;
|
||||
} catch (r) {
|
||||
return console.warn("flash error", r), e;
|
||||
}
|
||||
},
|
||||
provide: (e) => K.decorations.from(e)
|
||||
}), ie = (e) => {
|
||||
e.dispatch({ effects: z.of(!0) }), setTimeout(() => {
|
||||
e.dispatch({ effects: z.of(!1) });
|
||||
provide: (e) => re.decorations.from(e)
|
||||
}), we = (e) => {
|
||||
e.dispatch({ effects: X.of(!0) }), setTimeout(() => {
|
||||
e.dispatch({ effects: X.of(!1) });
|
||||
}, 200);
|
||||
}, O = U.define(), le = Q.define({
|
||||
}, B = ne.define(), ke = oe.define({
|
||||
create() {
|
||||
return A.none;
|
||||
return M.none;
|
||||
},
|
||||
update(e, o) {
|
||||
update(e, t) {
|
||||
try {
|
||||
for (let r of o.effects)
|
||||
if (r.is(O)) {
|
||||
for (let r of t.effects)
|
||||
if (r.is(B)) {
|
||||
const n = r.value.map(
|
||||
(s) => (s.context.locations || []).map(({ start: i, end: a }) => {
|
||||
const t = s.context.color || "#FFCA28";
|
||||
let l = o.newDoc.line(i.line).from + i.column, c = o.newDoc.line(a.line).from + a.column;
|
||||
const f = o.newDoc.length;
|
||||
return l > f || c > f ? void 0 : A.mark({ attributes: { style: `outline: 1.5px solid ${t};` } }).range(l, c);
|
||||
(l) => (l.context.locations || []).map(({ start: m, end: f }) => {
|
||||
const c = l.context.color || "#FFCA28";
|
||||
let s = t.newDoc.line(m.line).from + m.column, g = t.newDoc.line(f.line).from + f.column;
|
||||
const b = t.newDoc.length;
|
||||
return s > b || g > b ? void 0 : M.mark({ attributes: { style: `outline: 1.5px solid ${c};` } }).range(s, g);
|
||||
})
|
||||
).flat().filter(Boolean) || [];
|
||||
e = A.set(n, !0);
|
||||
e = M.set(n, !0);
|
||||
}
|
||||
return e;
|
||||
} catch {
|
||||
return A.set([]);
|
||||
return M.set([]);
|
||||
}
|
||||
},
|
||||
provide: (e) => K.decorations.from(e)
|
||||
}), ue = [Z(), ae, le, ce];
|
||||
function de({ value: e, onChange: o, onViewChanged: r, onSelectionChange: n, options: s, editorDidMount: i }) {
|
||||
const a = T(
|
||||
(c) => {
|
||||
o?.(c);
|
||||
provide: (e) => re.decorations.from(e)
|
||||
}), Fe = [de(), Ee, ke, ye];
|
||||
function _e({ value: e, onChange: t, onViewChanged: r, onSelectionChange: n, options: l, editorDidMount: m }) {
|
||||
const f = E(
|
||||
(g) => {
|
||||
t?.(g);
|
||||
},
|
||||
[o]
|
||||
), t = T(
|
||||
(c) => {
|
||||
r?.(c);
|
||||
[t]
|
||||
), c = E(
|
||||
(g) => {
|
||||
r?.(g);
|
||||
},
|
||||
[r]
|
||||
), l = T(
|
||||
(c) => {
|
||||
c.selectionSet && n && n?.(c.state.selection);
|
||||
), s = E(
|
||||
(g) => {
|
||||
g.selectionSet && n && n?.(g.state.selection);
|
||||
},
|
||||
[n]
|
||||
);
|
||||
return /* @__PURE__ */ y.createElement(y.Fragment, null, /* @__PURE__ */ y.createElement(Y, {
|
||||
return /* @__PURE__ */ d.createElement(d.Fragment, null, /* @__PURE__ */ d.createElement(ue, {
|
||||
value: e,
|
||||
onChange: a,
|
||||
onCreateEditor: t,
|
||||
onUpdate: l,
|
||||
extensions: ue
|
||||
onChange: f,
|
||||
onCreateEditor: c,
|
||||
onUpdate: s,
|
||||
extensions: Fe
|
||||
}));
|
||||
}
|
||||
function fe(e) {
|
||||
const { onEvent: o, onQuery: r, onSchedule: n, ready: s = !0, onDraw: i } = e, [a, t] = w(!1), l = 1, c = () => Math.floor(M.getTransport().seconds / l), f = (g = c()) => {
|
||||
const C = new oe(g, g + 1), v = r?.(new re(C)) || [];
|
||||
n?.(v, g);
|
||||
const h = C.begin.valueOf();
|
||||
M.getTransport().cancel(h);
|
||||
const D = (g + 1) * l - 0.5, _ = Math.max(M.getTransport().seconds, D) + 0.1;
|
||||
M.getTransport().schedule(() => {
|
||||
f(g + 1);
|
||||
}, _), v?.filter((E) => E.part.begin.equals(E.whole?.begin)).forEach((E) => {
|
||||
M.getTransport().schedule((L) => {
|
||||
o(L, E, M.getContext().currentTime), M.Draw.schedule(() => {
|
||||
i?.(L, E);
|
||||
}, L);
|
||||
}, E.part.begin.valueOf());
|
||||
});
|
||||
};
|
||||
q(() => {
|
||||
s && f();
|
||||
}, [o, n, r, i, s]);
|
||||
const p = async () => {
|
||||
t(!0), await M.start(), M.getTransport().start("+0.1");
|
||||
}, d = () => {
|
||||
M.getTransport().pause(), t(!1);
|
||||
};
|
||||
return {
|
||||
start: p,
|
||||
stop: d,
|
||||
onEvent: o,
|
||||
started: a,
|
||||
setStarted: t,
|
||||
toggle: () => a ? d() : p(),
|
||||
query: f,
|
||||
activeCycle: c
|
||||
};
|
||||
}
|
||||
function ge(e) {
|
||||
return q(() => (window.addEventListener("message", e), () => window.removeEventListener("message", e)), [e]), T((o) => window.postMessage(o, "*"), []);
|
||||
}
|
||||
let he = () => Math.floor((1 + Math.random()) * 65536).toString(16).substring(1);
|
||||
const me = (e) => encodeURIComponent(btoa(e));
|
||||
function pe({ tune: e, autolink: o = !0, onEvent: r, onDraw: n }) {
|
||||
const s = R(() => he(), []), [i, a] = w(e), [t, l] = w(), [c, f] = w(""), [p, d] = w(), [k, g] = w(!1), [C, v] = w(""), [h, D] = w(), _ = R(() => i !== t || p, [i, t, p]), E = T((b) => f((u) => u + `${u ? `
|
||||
|
||||
` : ""}${b}`), []), L = R(() => {
|
||||
if (t && !t.includes("strudel disable-highlighting"))
|
||||
return (b, u) => n?.(b, u, t);
|
||||
}, [t, n]), H = R(() => t && t.includes("strudel hide-header"), [t]), x = R(() => t && t.includes("strudel hide-console"), [t]), P = fe({
|
||||
onDraw: L,
|
||||
onEvent: T(
|
||||
(b, u, X) => {
|
||||
try {
|
||||
r?.(u), u.context.logs?.length && u.context.logs.forEach(E);
|
||||
const { onTrigger: S = ne } = u.context;
|
||||
S(b, u, X, 1);
|
||||
} catch (S) {
|
||||
console.warn(S), S.message = "unplayable event: " + S?.message, E(S.message);
|
||||
}
|
||||
},
|
||||
[r, E]
|
||||
),
|
||||
onQuery: T(
|
||||
(b) => {
|
||||
try {
|
||||
return h?.query(b) || [];
|
||||
} catch (u) {
|
||||
return console.warn(u), u.message = "query error: " + u.message, d(u), [];
|
||||
}
|
||||
},
|
||||
[h]
|
||||
),
|
||||
onSchedule: T((b, u) => J(b), []),
|
||||
ready: !!h && !!t
|
||||
}), B = ge(({ data: { from: b, type: u } }) => {
|
||||
u === "start" && b !== s && (P.setStarted(!1), l(void 0));
|
||||
}), V = T(
|
||||
async (b = i) => {
|
||||
if (t && !_) {
|
||||
d(void 0), P.start();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
g(!0);
|
||||
const u = await G(b);
|
||||
P.start(), B({ type: "start", from: s }), D(() => u.pattern), o && (window.location.hash = "#" + encodeURIComponent(btoa(i))), v(me(i)), d(void 0), l(b), g(!1);
|
||||
} catch (u) {
|
||||
u.message = "evaluation error: " + u.message, console.warn(u), d(u);
|
||||
}
|
||||
},
|
||||
[t, _, i, P, o, s, B]
|
||||
), J = (b, u) => {
|
||||
b.length;
|
||||
};
|
||||
return {
|
||||
hideHeader: H,
|
||||
hideConsole: x,
|
||||
pending: k,
|
||||
code: i,
|
||||
setCode: a,
|
||||
pattern: h,
|
||||
error: p,
|
||||
cycle: P,
|
||||
setPattern: D,
|
||||
dirty: _,
|
||||
log: c,
|
||||
togglePlay: () => {
|
||||
P.started ? P.stop() : V();
|
||||
},
|
||||
setActiveCode: l,
|
||||
activateCode: V,
|
||||
activeCode: t,
|
||||
pushLog: E,
|
||||
hash: C
|
||||
};
|
||||
}
|
||||
function $(...e) {
|
||||
function T(...e) {
|
||||
return e.filter(Boolean).join(" ");
|
||||
}
|
||||
function ye({ view: e, pattern: o, active: r, getTime: n }) {
|
||||
const s = I([]), i = I();
|
||||
q(() => {
|
||||
function Me({ view: e, pattern: t, active: r, getTime: n }) {
|
||||
const l = A([]), m = A(0);
|
||||
k(() => {
|
||||
if (e)
|
||||
if (o && r) {
|
||||
let t = function() {
|
||||
if (t && r) {
|
||||
m.current = 0;
|
||||
let f = requestAnimationFrame(function c() {
|
||||
try {
|
||||
const l = n(), f = [Math.max(i.current || l, l - 1 / 10), l + 1 / 60];
|
||||
i.current = l + 1 / 60, s.current = s.current.filter((d) => d.whole.end > l);
|
||||
const p = o.queryArc(...f).filter((d) => d.hasOnset());
|
||||
s.current = s.current.concat(p), e.dispatch({ effects: O.of(s.current) });
|
||||
const s = n(), b = [Math.max(m.current ?? s, s - 1 / 10, -0.01), s + 1 / 60];
|
||||
m.current = b[1], l.current = l.current.filter((h) => h.whole.end > s);
|
||||
const i = t.queryArc(...b).filter((h) => h.hasOnset());
|
||||
l.current = l.current.concat(i), e.dispatch({ effects: B.of(l.current) });
|
||||
} catch {
|
||||
e.dispatch({ effects: O.of([]) });
|
||||
e.dispatch({ effects: B.of([]) });
|
||||
}
|
||||
a = requestAnimationFrame(t);
|
||||
}, a = requestAnimationFrame(t);
|
||||
f = requestAnimationFrame(c);
|
||||
});
|
||||
return () => {
|
||||
cancelAnimationFrame(a);
|
||||
cancelAnimationFrame(f);
|
||||
};
|
||||
} else
|
||||
s.current = [], e.dispatch({ effects: O.of([]) });
|
||||
}, [o, r, e]);
|
||||
l.current = [], e.dispatch({ effects: B.of([]) });
|
||||
}, [t, r, e]);
|
||||
}
|
||||
const be = "_container_3i85k_1", we = "_header_3i85k_5", ve = "_buttons_3i85k_9", Ee = "_button_3i85k_9", ke = "_buttonDisabled_3i85k_17", Ce = "_error_3i85k_21", Me = "_body_3i85k_25", F = {
|
||||
container: be,
|
||||
header: we,
|
||||
buttons: ve,
|
||||
button: Ee,
|
||||
buttonDisabled: ke,
|
||||
error: Ce,
|
||||
body: Me
|
||||
};
|
||||
function W({ type: e }) {
|
||||
return /* @__PURE__ */ y.createElement("svg", {
|
||||
function Ae(e, t = !1) {
|
||||
const r = A(), n = A(), l = (c) => {
|
||||
if (n.current !== void 0) {
|
||||
const s = c - n.current;
|
||||
e(c, s);
|
||||
}
|
||||
n.current = c, r.current = requestAnimationFrame(l);
|
||||
}, m = () => {
|
||||
r.current = requestAnimationFrame(l);
|
||||
}, f = () => {
|
||||
r.current && cancelAnimationFrame(r.current), delete r.current;
|
||||
};
|
||||
return k(() => {
|
||||
r.current && (f(), m());
|
||||
}, [e]), k(() => (t && m(), f), []), {
|
||||
start: m,
|
||||
stop: f
|
||||
};
|
||||
}
|
||||
function Ne({ pattern: e, started: t, getTime: r, onDraw: n, drawTime: l = [-2, 2] }) {
|
||||
let [m, f] = l;
|
||||
m = Math.abs(m);
|
||||
let c = A([]), s = A(null);
|
||||
k(() => {
|
||||
if (e && t) {
|
||||
const i = r(), h = e.queryArc(Math.max(i, 0), i + f + 0.1);
|
||||
c.current = c.current.filter((p) => p.whole.begin < i), c.current = c.current.concat(h);
|
||||
}
|
||||
}, [e, t]);
|
||||
const { start: g, stop: b } = Ae(
|
||||
E(() => {
|
||||
const i = r() + f;
|
||||
if (s.current === null) {
|
||||
s.current = i;
|
||||
return;
|
||||
}
|
||||
const h = e.queryArc(Math.max(s.current, i - 1 / 10), i);
|
||||
s.current = i, c.current = (c.current || []).filter((p) => p.whole.end >= i - m - f).concat(h.filter((p) => p.hasOnset())), n(e, i - f, c.current, l);
|
||||
}, [e])
|
||||
);
|
||||
return k(() => {
|
||||
t ? g() : (c.current = [], b());
|
||||
}, [t]), {
|
||||
clear: () => {
|
||||
c.current = [];
|
||||
}
|
||||
};
|
||||
}
|
||||
function Ce(e) {
|
||||
return k(() => (window.addEventListener("message", e), () => window.removeEventListener("message", e)), [e]), E((t) => window.postMessage(t, "*"), []);
|
||||
}
|
||||
function De({
|
||||
defaultOutput: e,
|
||||
interval: t,
|
||||
getTime: r,
|
||||
evalOnMount: n = !1,
|
||||
initialCode: l = "",
|
||||
autolink: m = !1,
|
||||
beforeEval: f,
|
||||
afterEval: c,
|
||||
editPattern: s,
|
||||
onEvalError: g,
|
||||
onToggle: b,
|
||||
canvasId: i,
|
||||
drawContext: h,
|
||||
drawTime: p = [-2, 2]
|
||||
}) {
|
||||
const D = Q(() => Re(), []);
|
||||
i = i || `canvas-${D}`;
|
||||
const [P, R] = _(), [z, H] = _(), [y, S] = _(l), [V, q] = _(), [x, I] = _(), [N, O] = _(!1), K = y !== V, L = E((a) => !!(a?.context?.onPaint && h), [h]), { scheduler: C, evaluate: o, start: v, stop: j, pause: U } = Q(
|
||||
() => pe({
|
||||
interval: t,
|
||||
defaultOutput: e,
|
||||
onSchedulerError: R,
|
||||
onEvalError: (a) => {
|
||||
H(a), g?.(a);
|
||||
},
|
||||
getTime: r,
|
||||
drawContext: h,
|
||||
transpiler: be,
|
||||
editPattern: s,
|
||||
beforeEval: ({ code: a }) => {
|
||||
S(a), f?.();
|
||||
},
|
||||
afterEval: ({ pattern: a, code: w }) => {
|
||||
q(w), I(a), H(), R(), m && (window.location.hash = "#" + encodeURIComponent(btoa(w))), c?.();
|
||||
},
|
||||
onToggle: (a) => {
|
||||
O(a), b?.(a);
|
||||
}
|
||||
}),
|
||||
[e, t, r]
|
||||
), ce = Ce(({ data: { from: a, type: w } }) => {
|
||||
w === "start" && a !== D && j();
|
||||
}), Y = E(
|
||||
async (a = !0) => {
|
||||
const w = await o(y, a);
|
||||
return ce({ type: "start", from: D }), w;
|
||||
},
|
||||
[o, y]
|
||||
), W = E(
|
||||
(a, w, G, J) => {
|
||||
const { onPaint: ie } = a.context || {}, le = typeof h == "function" ? h(i) : h;
|
||||
ie?.(le, w, G, J);
|
||||
},
|
||||
[h, i]
|
||||
), $ = E(
|
||||
(a) => {
|
||||
if (L(a)) {
|
||||
const [w, G] = p, J = a.queryArc(0, G);
|
||||
W(a, -1e-3, J, p);
|
||||
}
|
||||
},
|
||||
[p, W, L]
|
||||
), Z = A();
|
||||
k(() => {
|
||||
!Z.current && n && y && (Z.current = !0, o(y, !1).then((a) => $(a)));
|
||||
}, [n, y, o, $]), k(() => () => {
|
||||
C.stop();
|
||||
}, [C]);
|
||||
const ae = async () => {
|
||||
N ? (C.stop(), $(x)) : await Y();
|
||||
}, se = P || z;
|
||||
return Ne({
|
||||
pattern: x,
|
||||
started: L(x) && N,
|
||||
getTime: () => C.now(),
|
||||
drawTime: p,
|
||||
onDraw: W
|
||||
}), {
|
||||
id: D,
|
||||
canvasId: i,
|
||||
code: y,
|
||||
setCode: S,
|
||||
error: se,
|
||||
schedulerError: P,
|
||||
scheduler: C,
|
||||
evalError: z,
|
||||
evaluate: o,
|
||||
activateCode: Y,
|
||||
activeCode: V,
|
||||
isDirty: K,
|
||||
pattern: x,
|
||||
started: N,
|
||||
start: v,
|
||||
stop: j,
|
||||
pause: U,
|
||||
togglePlay: ae
|
||||
};
|
||||
}
|
||||
function Re() {
|
||||
return Math.floor((1 + Math.random()) * 65536).toString(16).substring(1);
|
||||
}
|
||||
function ee({ type: e }) {
|
||||
return /* @__PURE__ */ d.createElement("svg", {
|
||||
xmlns: "http://www.w3.org/2000/svg",
|
||||
className: "sc-h-5 sc-w-5",
|
||||
viewBox: "0 0 20 20",
|
||||
fill: "currentColor"
|
||||
}, {
|
||||
refresh: /* @__PURE__ */ y.createElement("path", {
|
||||
refresh: /* @__PURE__ */ d.createElement("path", {
|
||||
fillRule: "evenodd",
|
||||
d: "M4 2a1 1 0 011 1v2.101a7.002 7.002 0 0111.601 2.566 1 1 0 11-1.885.666A5.002 5.002 0 005.999 7H9a1 1 0 010 2H4a1 1 0 01-1-1V3a1 1 0 011-1zm.008 9.057a1 1 0 011.276.61A5.002 5.002 0 0014.001 13H11a1 1 0 110-2h5a1 1 0 011 1v5a1 1 0 11-2 0v-2.101a7.002 7.002 0 01-11.601-2.566 1 1 0 01.61-1.276z",
|
||||
clipRule: "evenodd"
|
||||
}),
|
||||
play: /* @__PURE__ */ y.createElement("path", {
|
||||
play: /* @__PURE__ */ d.createElement("path", {
|
||||
fillRule: "evenodd",
|
||||
d: "M10 18a8 8 0 100-16 8 8 0 000 16zM9.555 7.168A1 1 0 008 8v4a1 1 0 001.555.832l3-2a1 1 0 000-1.664l-3-2z",
|
||||
clipRule: "evenodd"
|
||||
}),
|
||||
pause: /* @__PURE__ */ y.createElement("path", {
|
||||
pause: /* @__PURE__ */ d.createElement("path", {
|
||||
fillRule: "evenodd",
|
||||
d: "M18 10a8 8 0 11-16 0 8 8 0 0116 0zM7 8a1 1 0 012 0v4a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v4a1 1 0 102 0V8a1 1 0 00-1-1z",
|
||||
clipRule: "evenodd"
|
||||
}),
|
||||
stop: /* @__PURE__ */ d.createElement("path", {
|
||||
fillRule: "evenodd",
|
||||
d: "M2 10a8 8 0 1116 0 8 8 0 01-16 0zm5-2.25A.75.75 0 017.75 7h4.5a.75.75 0 01.75.75v4.5a.75.75 0 01-.75.75h-4.5a.75.75 0 01-.75-.75v-4.5z",
|
||||
clipRule: "evenodd"
|
||||
})
|
||||
}[e]);
|
||||
}
|
||||
function Be({ tune: e, hideOutsideView: o = !1, init: r, onEvent: n, enableKeyboard: s }) {
|
||||
const { code: i, setCode: a, pattern: t, activeCode: l, activateCode: c, evaluateOnly: f, error: p, cycle: d, dirty: k, togglePlay: g, stop: C } = pe({
|
||||
tune: e,
|
||||
autolink: !1,
|
||||
onEvent: n
|
||||
});
|
||||
q(() => {
|
||||
r && f();
|
||||
}, [e, r]);
|
||||
const [v, h] = w(), [D, _] = te({
|
||||
const xe = "_container_3i85k_1", Le = "_header_3i85k_5", Pe = "_buttons_3i85k_9", qe = "_button_3i85k_9", ze = "_buttonDisabled_3i85k_17", He = "_error_3i85k_21", Se = "_body_3i85k_25", F = {
|
||||
container: xe,
|
||||
header: Le,
|
||||
buttons: Pe,
|
||||
button: qe,
|
||||
buttonDisabled: ze,
|
||||
error: He,
|
||||
body: Se
|
||||
}, Ve = () => he().currentTime;
|
||||
function Ze({ tune: e, hideOutsideView: t = !1, enableKeyboard: r, drawTime: n, punchcard: l, canvasHeight: m = 200 }) {
|
||||
n = n || (l ? [0, 4] : void 0);
|
||||
const f = !!n, c = E(
|
||||
n ? (o) => document.querySelector("#" + o)?.getContext("2d") : null,
|
||||
[n]
|
||||
), {
|
||||
code: s,
|
||||
setCode: g,
|
||||
evaluate: b,
|
||||
activateCode: i,
|
||||
error: h,
|
||||
isDirty: p,
|
||||
activeCode: D,
|
||||
pattern: P,
|
||||
started: R,
|
||||
scheduler: z,
|
||||
togglePlay: H,
|
||||
stop: y,
|
||||
canvasId: S,
|
||||
id: V
|
||||
} = De({
|
||||
initialCode: e,
|
||||
defaultOutput: me,
|
||||
editPattern: (o) => l ? o.punchcard() : o,
|
||||
getTime: Ve,
|
||||
evalOnMount: f,
|
||||
drawContext: c,
|
||||
drawTime: n
|
||||
}), [q, x] = _(), [I, N] = ge({
|
||||
threshold: 0.01
|
||||
}), E = I(), L = R(() => ((_ || !o) && (E.current = !0), _ || E.current), [_, o]);
|
||||
return ye({
|
||||
view: v,
|
||||
pattern: t,
|
||||
active: d.started && !l?.includes("strudel disable-highlighting"),
|
||||
getTime: () => M.getTransport().seconds
|
||||
}), j(() => {
|
||||
if (s) {
|
||||
const H = async (x) => {
|
||||
(x.ctrlKey || x.altKey) && (x.code === "Enter" ? (x.preventDefault(), ie(v), await c()) : x.code === "Period" && (d.stop(), x.preventDefault()));
|
||||
}), O = A(), K = Q(() => ((N || !t) && (O.current = !0), N || O.current), [N, t]);
|
||||
Me({
|
||||
view: q,
|
||||
pattern: P,
|
||||
active: R && !D?.includes("strudel disable-highlighting"),
|
||||
getTime: () => z.now()
|
||||
}), te(() => {
|
||||
if (r) {
|
||||
const o = async (v) => {
|
||||
(v.ctrlKey || v.altKey) && (v.code === "Enter" ? (v.preventDefault(), we(q), await i()) : v.code === "Period" && (y(), v.preventDefault()));
|
||||
};
|
||||
return window.addEventListener("keydown", H, !0), () => window.removeEventListener("keydown", H, !0);
|
||||
return window.addEventListener("keydown", o, !0), () => window.removeEventListener("keydown", o, !0);
|
||||
}
|
||||
}, [s, t, i, c, d, v]), /* @__PURE__ */ y.createElement("div", {
|
||||
}, [r, P, s, b, y, q]);
|
||||
const [L, C] = _([]);
|
||||
return Oe(
|
||||
E((o) => {
|
||||
const { data: v } = o.detail;
|
||||
v?.hap?.context?.id === V && C((U) => U.concat([o.detail]).slice(-10));
|
||||
}, [])
|
||||
), /* @__PURE__ */ d.createElement("div", {
|
||||
className: F.container,
|
||||
ref: D
|
||||
}, /* @__PURE__ */ y.createElement("div", {
|
||||
ref: I
|
||||
}, /* @__PURE__ */ d.createElement("div", {
|
||||
className: F.header
|
||||
}, /* @__PURE__ */ y.createElement("div", {
|
||||
}, /* @__PURE__ */ d.createElement("div", {
|
||||
className: F.buttons
|
||||
}, /* @__PURE__ */ y.createElement("button", {
|
||||
className: $(F.button, d.started ? "sc-animate-pulse" : ""),
|
||||
onClick: () => g()
|
||||
}, /* @__PURE__ */ y.createElement(W, {
|
||||
type: d.started ? "pause" : "play"
|
||||
})), /* @__PURE__ */ y.createElement("button", {
|
||||
className: $(k ? F.button : F.buttonDisabled),
|
||||
onClick: () => c()
|
||||
}, /* @__PURE__ */ y.createElement(W, {
|
||||
}, /* @__PURE__ */ d.createElement("button", {
|
||||
className: T(F.button, R ? "sc-animate-pulse" : ""),
|
||||
onClick: () => H()
|
||||
}, /* @__PURE__ */ d.createElement(ee, {
|
||||
type: R ? "stop" : "play"
|
||||
})), /* @__PURE__ */ d.createElement("button", {
|
||||
className: T(p ? F.button : F.buttonDisabled),
|
||||
onClick: () => i()
|
||||
}, /* @__PURE__ */ d.createElement(ee, {
|
||||
type: "refresh"
|
||||
}))), p && /* @__PURE__ */ y.createElement("div", {
|
||||
}))), h && /* @__PURE__ */ d.createElement("div", {
|
||||
className: F.error
|
||||
}, p.message)), /* @__PURE__ */ y.createElement("div", {
|
||||
}, h.message)), /* @__PURE__ */ d.createElement("div", {
|
||||
className: F.body
|
||||
}, L && /* @__PURE__ */ y.createElement(de, {
|
||||
value: i,
|
||||
onChange: a,
|
||||
onViewChanged: h
|
||||
})));
|
||||
}
|
||||
function Te(e, o, r = 0.05, n = 0.1, s = 0.1) {
|
||||
let i = 0, a = 0, t = 10 ** 4, l = 0.01;
|
||||
const c = (h) => r = h(r);
|
||||
s = s || n / 2;
|
||||
const f = () => {
|
||||
const h = e(), D = h + n + s;
|
||||
for (a === 0 && (a = h + l); a < D; )
|
||||
a = Math.round(a * t) / t, a >= h && o(a, r, i), a < h && console.log("TOO LATE", a), a += r, i++;
|
||||
};
|
||||
let p;
|
||||
const d = () => {
|
||||
f(), p = setInterval(f, n * 1e3);
|
||||
}, k = () => clearInterval(p);
|
||||
return { setDuration: c, start: d, stop: () => {
|
||||
i = 0, a = 0, k();
|
||||
}, pause: () => k(), duration: r, getPhase: () => a };
|
||||
}
|
||||
class _e {
|
||||
worker;
|
||||
pattern;
|
||||
started = !1;
|
||||
cps = 1;
|
||||
getTime;
|
||||
phase = 0;
|
||||
constructor({ interval: o, onTrigger: r, onError: n, getTime: s, latency: i = 0.1 }) {
|
||||
this.getTime = s;
|
||||
const a = (t) => Math.round(t * 1e3) / 1e3;
|
||||
this.clock = Te(
|
||||
s,
|
||||
(t, l, c) => {
|
||||
c === 0 && (this.origin = t);
|
||||
const f = a(t - this.origin);
|
||||
this.phase = f - i;
|
||||
const p = a(f + l), d = s();
|
||||
try {
|
||||
this.pattern.queryArc(f, p).forEach((g) => {
|
||||
if (g.part.begin.equals(g.whole.begin)) {
|
||||
const C = g.whole.begin + this.origin - d + i, v = g.duration * 1;
|
||||
r?.(g, C, v);
|
||||
}
|
||||
});
|
||||
} catch (k) {
|
||||
console.warn("scheduler error", k), n?.(k);
|
||||
}
|
||||
},
|
||||
o
|
||||
);
|
||||
}
|
||||
getPhase() {
|
||||
return this.phase;
|
||||
}
|
||||
start() {
|
||||
if (!this.pattern)
|
||||
throw new Error("Scheduler: no pattern set! call .setPattern first.");
|
||||
this.clock.start(), this.started = !0;
|
||||
}
|
||||
pause() {
|
||||
this.clock.stop(), delete this.origin, this.started = !1;
|
||||
}
|
||||
stop() {
|
||||
delete this.origin, this.clock.stop(), this.started = !1;
|
||||
}
|
||||
setPattern(o) {
|
||||
this.pattern = o;
|
||||
}
|
||||
setCps(o = 1) {
|
||||
this.cps = o;
|
||||
}
|
||||
log(o, r, n) {
|
||||
const s = n.filter((i) => i.hasOnset());
|
||||
console.log(`${o.toFixed(4)} - ${r.toFixed(4)} ${Array(s.length).fill("I").join("")}`);
|
||||
}
|
||||
}
|
||||
function Ve({ defaultOutput: e, interval: o, getTime: r, code: n, evalOnMount: s = !1 }) {
|
||||
const [i, a] = w(), [t, l] = w(), [c, f] = w(n), [p, d] = w(), k = n !== c, g = R(
|
||||
() => new _e({ interval: o, onTrigger: e, onError: a, getTime: r }),
|
||||
[e, o]
|
||||
), C = T(async () => {
|
||||
if (!n) {
|
||||
console.log("no code..");
|
||||
return;
|
||||
}, K && /* @__PURE__ */ d.createElement(_e, {
|
||||
value: s,
|
||||
onChange: g,
|
||||
onViewChanged: x
|
||||
})), n && /* @__PURE__ */ d.createElement("canvas", {
|
||||
id: S,
|
||||
className: "w-full pointer-events-none",
|
||||
height: m,
|
||||
ref: (o) => {
|
||||
o && o.width !== o.clientWidth && (o.width = o.clientWidth);
|
||||
}
|
||||
try {
|
||||
const { pattern: h } = await G(n);
|
||||
f(n), g?.setPattern(h), d(h), l();
|
||||
} catch (h) {
|
||||
l(h), console.warn("eval error", h);
|
||||
}
|
||||
}, [n, g]), v = I();
|
||||
return q(() => {
|
||||
!v.current && s && (v.current = !0, C());
|
||||
}, [C, s]), { schedulerError: i, scheduler: g, evalError: t, evaluate: C, activeCode: c, isDirty: k, pattern: p };
|
||||
}), !!L.length && /* @__PURE__ */ d.createElement("div", {
|
||||
className: "sc-bg-gray-800 sc-rounded-md sc-p-2"
|
||||
}, L.map(({ message: o }, v) => /* @__PURE__ */ d.createElement("div", {
|
||||
key: v
|
||||
}, o))));
|
||||
}
|
||||
const $e = (e) => j(() => (window.addEventListener("keydown", e, !0), () => window.removeEventListener("keydown", e, !0)), [e]);
|
||||
function We(e) {
|
||||
const { ready: o, connected: r, disconnected: n } = e, [s, i] = w(!0), [a, t] = w(N?.outputs || []);
|
||||
return q(() => {
|
||||
se().then(() => {
|
||||
N.addListener("connected", (c) => {
|
||||
t([...N.outputs]), r?.(N, c);
|
||||
}), N.addListener("disconnected", (c) => {
|
||||
t([...N.outputs]), n?.(N, c);
|
||||
}), o?.(N), i(!1);
|
||||
}).catch((c) => {
|
||||
if (c) {
|
||||
console.error(c), console.warn("Web Midi could not be enabled..");
|
||||
return;
|
||||
}
|
||||
});
|
||||
}, [o, r, n, a]), { loading: s, outputs: a, outputByName: (c) => N.getOutputByName(c) };
|
||||
function Oe(e) {
|
||||
Be(ve.key, e);
|
||||
}
|
||||
function Be(e, t, r = !1) {
|
||||
k(() => (document.addEventListener(e, t, r), () => {
|
||||
document.removeEventListener(e, t, r);
|
||||
}), [t]);
|
||||
}
|
||||
const Te = (e) => te(() => (window.addEventListener("keydown", e, !0), () => window.removeEventListener("keydown", e, !0)), [e]);
|
||||
export {
|
||||
de as CodeMirror,
|
||||
Be as MiniRepl,
|
||||
$ as cx,
|
||||
ie as flash,
|
||||
fe as useCycle,
|
||||
ye as useHighlighting,
|
||||
$e as useKeydown,
|
||||
ge as usePostMessage,
|
||||
pe as useRepl,
|
||||
Ve as useStrudel,
|
||||
We as useWebMidi
|
||||
_e as CodeMirror,
|
||||
Ze as MiniRepl,
|
||||
T as cx,
|
||||
we as flash,
|
||||
Me as useHighlighting,
|
||||
Te as useKeydown,
|
||||
Ce as usePostMessage,
|
||||
De as useStrudel
|
||||
};
|
||||
|
||||
Vendored
+1
-1
@@ -1 +1 @@
|
||||
.cm-editor{background-color:transparent!important;height:100%;z-index:11;font-size:16px}.cm-theme-light{width:100%}.cm-line>*{background:#00000095}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sc-h-5{height:1.25rem}.sc-w-5{width:1.25rem}@keyframes sc-pulse{50%{opacity:.5}}.sc-animate-pulse{animation:sc-pulse 2s cubic-bezier(.4,0,.6,1) infinite}._container_3i85k_1{overflow:hidden;border-radius:.375rem;--tw-bg-opacity: 1;background-color:rgb(34 34 34 / var(--tw-bg-opacity))}._header_3i85k_5{display:flex;justify-content:space-between;border-top-width:1px;--tw-border-opacity: 1;border-color:rgb(100 116 139 / var(--tw-border-opacity));--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity))}._buttons_3i85k_9{display:flex}._button_3i85k_9{display:flex;width:4rem;cursor:pointer;align-items:center;justify-content:center;border-right-width:1px;--tw-border-opacity: 1;border-color:rgb(100 116 139 / var(--tw-border-opacity));--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity));padding:.25rem;--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}._button_3i85k_9:hover{--tw-bg-opacity: 1;background-color:rgb(71 85 105 / var(--tw-bg-opacity))}._buttonDisabled_3i85k_17{display:flex;width:4rem;cursor:pointer;cursor:not-allowed;align-items:center;justify-content:center;--tw-bg-opacity: 1;background-color:rgb(71 85 105 / var(--tw-bg-opacity));padding:.25rem;--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity))}._error_3i85k_21{padding:.25rem;text-align:right;font-size:.875rem;line-height:1.25rem;--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity))}._body_3i85k_25{position:relative;overflow:auto}
|
||||
.cm-editor{background-color:transparent!important;height:100%;z-index:11;font-size:18px}.cm-theme-light{width:100%}.cm-line>*{background:#00000095}*,:before,:after{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }::backdrop{--tw-border-spacing-x: 0;--tw-border-spacing-y: 0;--tw-translate-x: 0;--tw-translate-y: 0;--tw-rotate: 0;--tw-skew-x: 0;--tw-skew-y: 0;--tw-scale-x: 1;--tw-scale-y: 1;--tw-pan-x: ;--tw-pan-y: ;--tw-pinch-zoom: ;--tw-scroll-snap-strictness: proximity;--tw-ordinal: ;--tw-slashed-zero: ;--tw-numeric-figure: ;--tw-numeric-spacing: ;--tw-numeric-fraction: ;--tw-ring-inset: ;--tw-ring-offset-width: 0px;--tw-ring-offset-color: #fff;--tw-ring-color: rgb(59 130 246 / .5);--tw-ring-offset-shadow: 0 0 #0000;--tw-ring-shadow: 0 0 #0000;--tw-shadow: 0 0 #0000;--tw-shadow-colored: 0 0 #0000;--tw-blur: ;--tw-brightness: ;--tw-contrast: ;--tw-grayscale: ;--tw-hue-rotate: ;--tw-invert: ;--tw-saturate: ;--tw-sepia: ;--tw-drop-shadow: ;--tw-backdrop-blur: ;--tw-backdrop-brightness: ;--tw-backdrop-contrast: ;--tw-backdrop-grayscale: ;--tw-backdrop-hue-rotate: ;--tw-backdrop-invert: ;--tw-backdrop-opacity: ;--tw-backdrop-saturate: ;--tw-backdrop-sepia: }.sc-h-5{height:1.25rem}.sc-w-5{width:1.25rem}@keyframes sc-pulse{50%{opacity:.5}}.sc-animate-pulse{animation:sc-pulse 2s cubic-bezier(.4,0,.6,1) infinite}.sc-rounded-md{border-radius:.375rem}.sc-bg-gray-800{--tw-bg-opacity: 1;background-color:rgb(31 41 55 / var(--tw-bg-opacity))}.sc-p-2{padding:.5rem}._container_3i85k_1{overflow:hidden;border-radius:.375rem;--tw-bg-opacity: 1;background-color:rgb(34 34 34 / var(--tw-bg-opacity))}._header_3i85k_5{display:flex;justify-content:space-between;border-top-width:1px;--tw-border-opacity: 1;border-color:rgb(100 116 139 / var(--tw-border-opacity));--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity))}._buttons_3i85k_9{display:flex}._button_3i85k_9{display:flex;width:4rem;cursor:pointer;align-items:center;justify-content:center;border-right-width:1px;--tw-border-opacity: 1;border-color:rgb(100 116 139 / var(--tw-border-opacity));--tw-bg-opacity: 1;background-color:rgb(51 65 85 / var(--tw-bg-opacity));padding:.25rem;--tw-text-opacity: 1;color:rgb(255 255 255 / var(--tw-text-opacity))}._button_3i85k_9:hover{--tw-bg-opacity: 1;background-color:rgb(71 85 105 / var(--tw-bg-opacity))}._buttonDisabled_3i85k_17{display:flex;width:4rem;cursor:pointer;cursor:not-allowed;align-items:center;justify-content:center;--tw-bg-opacity: 1;background-color:rgb(71 85 105 / var(--tw-bg-opacity));padding:.25rem;--tw-text-opacity: 1;color:rgb(148 163 184 / var(--tw-text-opacity))}._error_3i85k_21{padding:.25rem;text-align:right;font-size:.875rem;line-height:1.25rem;--tw-text-opacity: 1;color:rgb(254 202 202 / var(--tw-text-opacity))}._body_3i85k_25{position:relative;overflow:auto}
|
||||
|
||||
@@ -82,7 +82,7 @@ function App() {
|
||||
view,
|
||||
pattern,
|
||||
active: !activeCode?.includes('strudel disable-highlighting'),
|
||||
getTime: () => scheduler.phase,
|
||||
getTime: () => scheduler.getPhase(),
|
||||
});
|
||||
|
||||
const error = evalError || schedulerError;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import { defineConfig } from 'vite';
|
||||
import react from '@vitejs/plugin-react';
|
||||
|
||||
// https://vitejs.dev/config/
|
||||
export default defineConfig({
|
||||
plugins: [react()]
|
||||
})
|
||||
plugins: [react()],
|
||||
});
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<!-- <link rel="icon" type="image/svg+xml" href="/src/favicon.svg" /> -->
|
||||
<!-- <link rel="icon" type="image/svg+xml" href="/src/favicon.svg" /> -->
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Strudel React Components</title>
|
||||
</head>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/react",
|
||||
"version": "0.3.3",
|
||||
"version": "0.5.0",
|
||||
"description": "React components for strudel",
|
||||
"main": "dist/index.cjs.js",
|
||||
"module": "dist/index.es.js",
|
||||
@@ -17,6 +17,7 @@
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"watch": "vite build --watch",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"repository": {
|
||||
@@ -38,9 +39,10 @@
|
||||
"homepage": "https://github.com/tidalcycles/strudel#readme",
|
||||
"dependencies": {
|
||||
"@codemirror/lang-javascript": "^6.1.1",
|
||||
"@strudel.cycles/core": "^0.3.2",
|
||||
"@strudel.cycles/eval": "^0.3.2",
|
||||
"@strudel.cycles/tone": "^0.3.3",
|
||||
"@strudel.cycles/core": "^0.5.0",
|
||||
"@strudel.cycles/tone": "^0.5.0",
|
||||
"@strudel.cycles/transpiler": "^0.5.0",
|
||||
"@strudel.cycles/webaudio": "^0.5.0",
|
||||
"@uiw/codemirror-themes": "^4.12.4",
|
||||
"@uiw/react-codemirror": "^4.12.4",
|
||||
"react-hook-inview": "^4.5.0"
|
||||
|
||||
@@ -9,4 +9,4 @@ module.exports = {
|
||||
tailwindcss: {},
|
||||
autoprefixer: {},
|
||||
},
|
||||
}
|
||||
};
|
||||
|
||||
@@ -6,7 +6,7 @@ import { controls, evalScope } from '@strudel.cycles/core';
|
||||
evalScope(
|
||||
controls,
|
||||
import('@strudel.cycles/core'),
|
||||
import('@strudel.cycles/tone'),
|
||||
// import('@strudel.cycles/tone'),
|
||||
import('@strudel.cycles/tonal'),
|
||||
import('@strudel.cycles/mini'),
|
||||
import('@strudel.cycles/midi'),
|
||||
|
||||
@@ -26,6 +26,13 @@ export function Icon({ type }) {
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
),
|
||||
stop: (
|
||||
<path
|
||||
fillRule="evenodd"
|
||||
d="M2 10a8 8 0 1116 0 8 8 0 01-16 0zm5-2.25A.75.75 0 017.75 7h4.5a.75.75 0 01.75.75v4.5a.75.75 0 01-.75.75h-4.5a.75.75 0 01-.75-.75v-4.5z"
|
||||
clipRule="evenodd"
|
||||
/>
|
||||
),
|
||||
}[type]
|
||||
}
|
||||
</svg>
|
||||
|
||||
@@ -1,25 +1,50 @@
|
||||
import React, { useState, useMemo, useRef, useEffect, useLayoutEffect } from 'react';
|
||||
import { getAudioContext, webaudioOutput } from '@strudel.cycles/webaudio';
|
||||
import React, { useLayoutEffect, useMemo, useRef, useState, useCallback, useEffect } from 'react';
|
||||
import { useInView } from 'react-hook-inview';
|
||||
import useRepl from '../hooks/useRepl.mjs';
|
||||
import 'tailwindcss/tailwind.css';
|
||||
import cx from '../cx';
|
||||
import useHighlighting from '../hooks/useHighlighting.mjs';
|
||||
import useStrudel from '../hooks/useStrudel.mjs';
|
||||
import CodeMirror6, { flash } from './CodeMirror6';
|
||||
import 'tailwindcss/tailwind.css';
|
||||
import './style.css';
|
||||
import styles from './MiniRepl.module.css';
|
||||
import { Icon } from './Icon';
|
||||
import { Tone } from '@strudel.cycles/tone';
|
||||
import styles from './MiniRepl.module.css';
|
||||
import './style.css';
|
||||
import { logger } from '@strudel.cycles/core';
|
||||
|
||||
const getTime = () => getAudioContext().currentTime;
|
||||
|
||||
export function MiniRepl({ tune, hideOutsideView = false, enableKeyboard, drawTime, punchcard, canvasHeight = 200 }) {
|
||||
drawTime = drawTime || (punchcard ? [0, 4] : undefined);
|
||||
const evalOnMount = !!drawTime;
|
||||
const drawContext = useCallback(
|
||||
!!drawTime ? (canvasId) => document.querySelector('#' + canvasId)?.getContext('2d') : null,
|
||||
[drawTime],
|
||||
);
|
||||
const {
|
||||
code,
|
||||
setCode,
|
||||
evaluate,
|
||||
activateCode,
|
||||
error,
|
||||
isDirty,
|
||||
activeCode,
|
||||
pattern,
|
||||
started,
|
||||
scheduler,
|
||||
togglePlay,
|
||||
stop,
|
||||
canvasId,
|
||||
id: replId,
|
||||
} = useStrudel({
|
||||
initialCode: tune,
|
||||
defaultOutput: webaudioOutput,
|
||||
editPattern: (pat) => (punchcard ? pat.punchcard() : pat),
|
||||
getTime,
|
||||
evalOnMount,
|
||||
drawContext,
|
||||
drawTime,
|
||||
});
|
||||
|
||||
export function MiniRepl({ tune, hideOutsideView = false, init, onEvent, enableKeyboard }) {
|
||||
const { code, setCode, pattern, activeCode, activateCode, evaluateOnly, error, cycle, dirty, togglePlay, stop } =
|
||||
useRepl({
|
||||
tune,
|
||||
autolink: false,
|
||||
onEvent,
|
||||
});
|
||||
useEffect(() => {
|
||||
init && evaluateOnly();
|
||||
}, [tune, init]);
|
||||
const [view, setView] = useState();
|
||||
const [ref, isVisible] = useInView({
|
||||
threshold: 0.01,
|
||||
@@ -34,8 +59,8 @@ export function MiniRepl({ tune, hideOutsideView = false, init, onEvent, enableK
|
||||
useHighlighting({
|
||||
view,
|
||||
pattern,
|
||||
active: cycle.started && !activeCode?.includes('strudel disable-highlighting'),
|
||||
getTime: () => Tone.getTransport().seconds,
|
||||
active: started && !activeCode?.includes('strudel disable-highlighting'),
|
||||
getTime: () => scheduler.now(),
|
||||
});
|
||||
|
||||
// set active pattern on ctrl+enter
|
||||
@@ -48,7 +73,7 @@ export function MiniRepl({ tune, hideOutsideView = false, init, onEvent, enableK
|
||||
flash(view);
|
||||
await activateCode();
|
||||
} else if (e.code === 'Period') {
|
||||
cycle.stop();
|
||||
stop();
|
||||
e.preventDefault();
|
||||
}
|
||||
}
|
||||
@@ -56,16 +81,30 @@ export function MiniRepl({ tune, hideOutsideView = false, init, onEvent, enableK
|
||||
window.addEventListener('keydown', handleKeyPress, true);
|
||||
return () => window.removeEventListener('keydown', handleKeyPress, true);
|
||||
}
|
||||
}, [enableKeyboard, pattern, code, activateCode, cycle, view]);
|
||||
}, [enableKeyboard, pattern, code, evaluate, stop, view]);
|
||||
|
||||
const [log, setLog] = useState([]);
|
||||
useLogger(
|
||||
useCallback((e) => {
|
||||
const { data } = e.detail;
|
||||
const logId = data?.hap?.context?.id;
|
||||
// const logId = data?.pattern?.meta?.id;
|
||||
if (logId === replId) {
|
||||
setLog((l) => {
|
||||
return l.concat([e.detail]).slice(-10);
|
||||
});
|
||||
}
|
||||
}, []),
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={styles.container} ref={ref}>
|
||||
<div className={styles.header}>
|
||||
<div className={styles.buttons}>
|
||||
<button className={cx(styles.button, cycle.started ? 'sc-animate-pulse' : '')} onClick={() => togglePlay()}>
|
||||
<Icon type={cycle.started ? 'pause' : 'play'} />
|
||||
<button className={cx(styles.button, started ? 'sc-animate-pulse' : '')} onClick={() => togglePlay()}>
|
||||
<Icon type={started ? 'stop' : 'play'} />
|
||||
</button>
|
||||
<button className={cx(dirty ? styles.button : styles.buttonDisabled)} onClick={() => activateCode()}>
|
||||
<button className={cx(isDirty ? styles.button : styles.buttonDisabled)} onClick={() => activateCode()}>
|
||||
<Icon type="refresh" />
|
||||
</button>
|
||||
</div>
|
||||
@@ -74,6 +113,40 @@ export function MiniRepl({ tune, hideOutsideView = false, init, onEvent, enableK
|
||||
<div className={styles.body}>
|
||||
{show && <CodeMirror6 value={code} onChange={setCode} onViewChanged={setView} />}
|
||||
</div>
|
||||
{drawTime && (
|
||||
<canvas
|
||||
id={canvasId}
|
||||
className="w-full pointer-events-none"
|
||||
height={canvasHeight}
|
||||
ref={(el) => {
|
||||
if (el && el.width !== el.clientWidth) {
|
||||
el.width = el.clientWidth;
|
||||
}
|
||||
}}
|
||||
></canvas>
|
||||
)}
|
||||
{!!log.length && (
|
||||
<div className="sc-bg-gray-800 sc-rounded-md sc-p-2">
|
||||
{log.map(({ message }, i) => (
|
||||
<div key={i}>{message}</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: dedupe
|
||||
function useLogger(onTrigger) {
|
||||
useEvent(logger.key, onTrigger);
|
||||
}
|
||||
|
||||
// TODO: dedupe
|
||||
function useEvent(name, onTrigger, useCapture = false) {
|
||||
useEffect(() => {
|
||||
document.addEventListener(name, onTrigger, useCapture);
|
||||
return () => {
|
||||
document.removeEventListener(name, onTrigger, useCapture);
|
||||
};
|
||||
}, [onTrigger]);
|
||||
}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
background-color: transparent !important;
|
||||
height: 100%;
|
||||
z-index: 11;
|
||||
font-size: 16px;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.cm-theme-light {
|
||||
|
||||
@@ -1,86 +0,0 @@
|
||||
/*
|
||||
useCycle.mjs - <short description TODO>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/strudel/blob/main/repl/src/useCycle.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 { useEffect, useState } from 'react';
|
||||
import { Tone } from '@strudel.cycles/tone';
|
||||
import { State, TimeSpan } from '@strudel.cycles/core';
|
||||
|
||||
/* export declare interface UseCycleProps {
|
||||
onEvent: ToneEventCallback<any>;
|
||||
onQuery?: (state: State) => Hap[];
|
||||
onSchedule?: (events: Hap[], cycle: number) => void;
|
||||
onDraw?: ToneEventCallback<any>;
|
||||
ready?: boolean; // if false, query will not be called on change props
|
||||
} */
|
||||
|
||||
// function useCycle(props: UseCycleProps) {
|
||||
function useCycle(props) {
|
||||
// onX must use useCallback!
|
||||
const { onEvent, onQuery, onSchedule, ready = true, onDraw } = props;
|
||||
const [started, setStarted] = useState(false);
|
||||
const cycleDuration = 1;
|
||||
const activeCycle = () => Math.floor(Tone.getTransport().seconds / cycleDuration);
|
||||
|
||||
// pull events with onQuery + count up to next cycle
|
||||
const query = (cycle = activeCycle()) => {
|
||||
const timespan = new TimeSpan(cycle, cycle + 1);
|
||||
const events = onQuery?.(new State(timespan)) || [];
|
||||
onSchedule?.(events, cycle);
|
||||
// cancel events after current query. makes sure no old events are player for rescheduled cycles
|
||||
// console.log('schedule', cycle);
|
||||
// query next cycle in the middle of the current
|
||||
const cancelFrom = timespan.begin.valueOf();
|
||||
Tone.getTransport().cancel(cancelFrom);
|
||||
// const queryNextTime = (cycle + 1) * cycleDuration - 0.1;
|
||||
const queryNextTime = (cycle + 1) * cycleDuration - 0.5;
|
||||
|
||||
// if queryNextTime would be before current time, execute directly (+0.1 for safety that it won't miss)
|
||||
const t = Math.max(Tone.getTransport().seconds, queryNextTime) + 0.1;
|
||||
Tone.getTransport().schedule(() => {
|
||||
query(cycle + 1);
|
||||
}, t);
|
||||
|
||||
// schedule events for next cycle
|
||||
events
|
||||
?.filter((event) => event.part.begin.equals(event.whole?.begin))
|
||||
.forEach((event) => {
|
||||
Tone.getTransport().schedule((time) => {
|
||||
onEvent(time, event, Tone.getContext().currentTime);
|
||||
Tone.Draw.schedule(() => {
|
||||
// do drawing or DOM manipulation here
|
||||
onDraw?.(time, event);
|
||||
}, time);
|
||||
}, event.part.begin.valueOf());
|
||||
});
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
ready && query();
|
||||
}, [onEvent, onSchedule, onQuery, onDraw, ready]);
|
||||
|
||||
const start = async () => {
|
||||
setStarted(true);
|
||||
await Tone.start();
|
||||
Tone.getTransport().start('+0.1');
|
||||
};
|
||||
const stop = () => {
|
||||
Tone.getTransport().pause();
|
||||
setStarted(false);
|
||||
};
|
||||
const toggle = () => (started ? stop() : start());
|
||||
return {
|
||||
start,
|
||||
stop,
|
||||
onEvent,
|
||||
started,
|
||||
setStarted,
|
||||
toggle,
|
||||
query,
|
||||
activeCycle,
|
||||
};
|
||||
}
|
||||
|
||||
export default useCycle;
|
||||
@@ -0,0 +1,43 @@
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
function useFrame(callback, autostart = false) {
|
||||
const requestRef = useRef();
|
||||
const previousTimeRef = useRef();
|
||||
|
||||
const animate = (time) => {
|
||||
if (previousTimeRef.current !== undefined) {
|
||||
const deltaTime = time - previousTimeRef.current;
|
||||
callback(time, deltaTime);
|
||||
}
|
||||
previousTimeRef.current = time;
|
||||
requestRef.current = requestAnimationFrame(animate);
|
||||
};
|
||||
|
||||
const start = () => {
|
||||
requestRef.current = requestAnimationFrame(animate);
|
||||
};
|
||||
const stop = () => {
|
||||
requestRef.current && cancelAnimationFrame(requestRef.current);
|
||||
delete requestRef.current;
|
||||
};
|
||||
useEffect(() => {
|
||||
if (requestRef.current) {
|
||||
stop();
|
||||
start();
|
||||
}
|
||||
}, [callback]);
|
||||
|
||||
useEffect(() => {
|
||||
if (autostart) {
|
||||
start();
|
||||
}
|
||||
return stop;
|
||||
}, []); // Make sure the effect only runs once
|
||||
|
||||
return {
|
||||
start,
|
||||
stop,
|
||||
};
|
||||
}
|
||||
|
||||
export default useFrame;
|
||||
@@ -3,31 +3,28 @@ import { setHighlights } from '../components/CodeMirror6';
|
||||
|
||||
function useHighlighting({ view, pattern, active, getTime }) {
|
||||
const highlights = useRef([]);
|
||||
const lastEnd = useRef();
|
||||
const lastEnd = useRef(0);
|
||||
useEffect(() => {
|
||||
if (view) {
|
||||
if (pattern && active) {
|
||||
let frame = requestAnimationFrame(updateHighlights);
|
||||
|
||||
function updateHighlights() {
|
||||
lastEnd.current = 0;
|
||||
let frame = requestAnimationFrame(function updateHighlights() {
|
||||
try {
|
||||
const audioTime = getTime();
|
||||
// force min framerate of 10 fps => fixes crash on tab refocus, where lastEnd could be far away
|
||||
// see https://github.com/tidalcycles/strudel/issues/108
|
||||
const begin = Math.max(lastEnd.current || audioTime, audioTime - 1 / 10);
|
||||
const begin = Math.max(lastEnd.current ?? audioTime, audioTime - 1 / 10, -0.01); // negative time seems buggy
|
||||
const span = [begin, audioTime + 1 / 60];
|
||||
lastEnd.current = audioTime + 1 / 60;
|
||||
lastEnd.current = span[1];
|
||||
highlights.current = highlights.current.filter((hap) => hap.whole.end > audioTime); // keep only highlights that are still active
|
||||
const haps = pattern.queryArc(...span).filter((hap) => hap.hasOnset());
|
||||
highlights.current = highlights.current.concat(haps); // add potential new onsets
|
||||
view.dispatch({ effects: setHighlights.of(highlights.current) }); // highlight all still active + new active haps
|
||||
} catch (err) {
|
||||
// console.log('error in updateHighlights', err);
|
||||
view.dispatch({ effects: setHighlights.of([]) });
|
||||
}
|
||||
frame = requestAnimationFrame(updateHighlights);
|
||||
}
|
||||
|
||||
});
|
||||
return () => {
|
||||
cancelAnimationFrame(frame);
|
||||
};
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { useCallback, useEffect, useRef } from 'react';
|
||||
import 'tailwindcss/tailwind.css';
|
||||
import useFrame from '../hooks/useFrame.mjs';
|
||||
|
||||
function usePatternFrame({ pattern, started, getTime, onDraw, drawTime = [-2, 2] }) {
|
||||
let [lookbehind, lookahead] = drawTime;
|
||||
lookbehind = Math.abs(lookbehind);
|
||||
let visibleHaps = useRef([]);
|
||||
let lastFrame = useRef(null);
|
||||
useEffect(() => {
|
||||
if (pattern && started) {
|
||||
const t = getTime();
|
||||
const futureHaps = pattern.queryArc(Math.max(t, 0), t + lookahead + 0.1); // +0.1 = workaround for weird holes in query..
|
||||
visibleHaps.current = visibleHaps.current.filter((h) => h.whole.begin < t);
|
||||
visibleHaps.current = visibleHaps.current.concat(futureHaps);
|
||||
}
|
||||
}, [pattern, started]);
|
||||
const { start: startFrame, stop: stopFrame } = useFrame(
|
||||
useCallback(() => {
|
||||
const phase = getTime() + lookahead;
|
||||
if (lastFrame.current === null) {
|
||||
lastFrame.current = phase;
|
||||
return;
|
||||
}
|
||||
const haps = pattern.queryArc(Math.max(lastFrame.current, phase - 1 / 10), phase);
|
||||
lastFrame.current = phase;
|
||||
visibleHaps.current = (visibleHaps.current || [])
|
||||
.filter((h) => h.whole.end >= phase - lookbehind - lookahead) // in frame
|
||||
.concat(haps.filter((h) => h.hasOnset()));
|
||||
onDraw(pattern, phase - lookahead, visibleHaps.current, drawTime);
|
||||
}, [pattern]),
|
||||
);
|
||||
useEffect(() => {
|
||||
if (started) {
|
||||
startFrame();
|
||||
} else {
|
||||
visibleHaps.current = [];
|
||||
stopFrame();
|
||||
}
|
||||
}, [started]);
|
||||
return {
|
||||
clear: () => {
|
||||
visibleHaps.current = [];
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default usePatternFrame;
|
||||
@@ -1,150 +0,0 @@
|
||||
/*
|
||||
useRepl.mjs - <short description TODO>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/strudel/blob/main/repl/src/useRepl.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 { useCallback, useState, useMemo } from 'react';
|
||||
import { evaluate } from '@strudel.cycles/eval';
|
||||
import useCycle from './useCycle.mjs';
|
||||
import usePostMessage from './usePostMessage.mjs';
|
||||
import { webaudioOutputTrigger } from '@strudel.cycles/webaudio';
|
||||
|
||||
let s4 = () => {
|
||||
return Math.floor((1 + Math.random()) * 0x10000)
|
||||
.toString(16)
|
||||
.substring(1);
|
||||
};
|
||||
const generateHash = (code) => encodeURIComponent(btoa(code));
|
||||
|
||||
function useRepl({ tune, autolink = true, onEvent, onDraw: onDrawProp }) {
|
||||
const id = useMemo(() => s4(), []);
|
||||
const [code, setCode] = useState(tune);
|
||||
const [activeCode, setActiveCode] = useState();
|
||||
const [log, setLog] = useState('');
|
||||
const [error, setError] = useState();
|
||||
const [pending, setPending] = useState(false);
|
||||
const [hash, setHash] = useState('');
|
||||
const [pattern, setPattern] = useState();
|
||||
const dirty = useMemo(() => code !== activeCode || error, [code, activeCode, error]);
|
||||
const pushLog = useCallback((message) => setLog((log) => log + `${log ? '\n\n' : ''}${message}`), []);
|
||||
|
||||
// below block allows disabling the highlighting by including "strudel disable-highlighting" in the code (as comment)
|
||||
const onDraw = useMemo(() => {
|
||||
if (activeCode && !activeCode.includes('strudel disable-highlighting')) {
|
||||
return (time, event) => onDrawProp?.(time, event, activeCode);
|
||||
}
|
||||
}, [activeCode, onDrawProp]);
|
||||
|
||||
const hideHeader = useMemo(() => activeCode && activeCode.includes('strudel hide-header'), [activeCode]);
|
||||
const hideConsole = useMemo(() => activeCode && activeCode.includes('strudel hide-console'), [activeCode]);
|
||||
// cycle hook to control scheduling
|
||||
const cycle = useCycle({
|
||||
onDraw,
|
||||
onEvent: useCallback(
|
||||
(time, event, currentTime) => {
|
||||
try {
|
||||
onEvent?.(event);
|
||||
if (event.context.logs?.length) {
|
||||
event.context.logs.forEach(pushLog);
|
||||
}
|
||||
const { onTrigger = webaudioOutputTrigger } = event.context;
|
||||
onTrigger(time, event, currentTime, 1 /* cps */);
|
||||
} catch (err) {
|
||||
console.warn(err);
|
||||
err.message = 'unplayable event: ' + err?.message;
|
||||
pushLog(err.message); // not with setError, because then we would have to setError(undefined) on next playable event
|
||||
}
|
||||
},
|
||||
[onEvent, pushLog],
|
||||
),
|
||||
onQuery: useCallback(
|
||||
(state) => {
|
||||
try {
|
||||
return pattern?.query(state) || [];
|
||||
} catch (err) {
|
||||
console.warn(err);
|
||||
err.message = 'query error: ' + err.message;
|
||||
setError(err);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
[pattern],
|
||||
),
|
||||
onSchedule: useCallback((_events, cycle) => logCycle(_events, cycle), []),
|
||||
ready: !!pattern && !!activeCode,
|
||||
});
|
||||
|
||||
const broadcast = usePostMessage(({ data: { from, type } }) => {
|
||||
if (type === 'start' && from !== id) {
|
||||
// console.log('message', from, type);
|
||||
cycle.setStarted(false);
|
||||
setActiveCode(undefined);
|
||||
}
|
||||
});
|
||||
|
||||
const activateCode = useCallback(
|
||||
async (_code = code) => {
|
||||
if (activeCode && !dirty) {
|
||||
setError(undefined);
|
||||
cycle.start();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
setPending(true);
|
||||
const parsed = await evaluate(_code);
|
||||
cycle.start();
|
||||
broadcast({ type: 'start', from: id });
|
||||
setPattern(() => parsed.pattern);
|
||||
if (autolink) {
|
||||
window.location.hash = '#' + encodeURIComponent(btoa(code));
|
||||
}
|
||||
setHash(generateHash(code));
|
||||
setError(undefined);
|
||||
setActiveCode(_code);
|
||||
setPending(false);
|
||||
} catch (err) {
|
||||
err.message = 'evaluation error: ' + err.message;
|
||||
console.warn(err);
|
||||
setError(err);
|
||||
}
|
||||
},
|
||||
[activeCode, dirty, code, cycle, autolink, id, broadcast],
|
||||
);
|
||||
// logs events of cycle
|
||||
const logCycle = (_events, cycle) => {
|
||||
if (_events.length) {
|
||||
// pushLog(`# cycle ${cycle}\n` + _events.map((e: any) => e.show()).join('\n'));
|
||||
}
|
||||
};
|
||||
|
||||
const togglePlay = () => {
|
||||
if (!cycle.started) {
|
||||
activateCode();
|
||||
} else {
|
||||
cycle.stop();
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
hideHeader,
|
||||
hideConsole,
|
||||
pending,
|
||||
code,
|
||||
setCode,
|
||||
pattern,
|
||||
error,
|
||||
cycle,
|
||||
setPattern,
|
||||
dirty,
|
||||
log,
|
||||
togglePlay,
|
||||
setActiveCode,
|
||||
activateCode,
|
||||
activeCode,
|
||||
pushLog,
|
||||
hash,
|
||||
};
|
||||
}
|
||||
|
||||
export default useRepl;
|
||||
@@ -1,43 +1,168 @@
|
||||
import { useRef, useCallback, useEffect, useMemo, useState } from 'react';
|
||||
import { repl } from '@strudel.cycles/core/repl.mjs';
|
||||
import { repl } from '@strudel.cycles/core';
|
||||
import { transpiler } from '@strudel.cycles/transpiler';
|
||||
import usePatternFrame from './usePatternFrame';
|
||||
import usePostMessage from './usePostMessage.mjs';
|
||||
|
||||
function useStrudel({ defaultOutput, interval, getTime, code, evalOnMount = false }) {
|
||||
function useStrudel({
|
||||
defaultOutput,
|
||||
interval,
|
||||
getTime,
|
||||
evalOnMount = false,
|
||||
initialCode = '',
|
||||
autolink = false,
|
||||
beforeEval,
|
||||
afterEval,
|
||||
editPattern,
|
||||
onEvalError,
|
||||
onToggle,
|
||||
canvasId,
|
||||
drawContext,
|
||||
drawTime = [-2, 2],
|
||||
}) {
|
||||
const id = useMemo(() => s4(), []);
|
||||
canvasId = canvasId || `canvas-${id}`;
|
||||
// scheduler
|
||||
const [schedulerError, setSchedulerError] = useState();
|
||||
const [evalError, setEvalError] = useState();
|
||||
const [activeCode, setActiveCode] = useState(code);
|
||||
const [code, setCode] = useState(initialCode);
|
||||
const [activeCode, setActiveCode] = useState();
|
||||
const [pattern, setPattern] = useState();
|
||||
const [started, setStarted] = useState(false);
|
||||
const isDirty = code !== activeCode;
|
||||
const { scheduler, evaluate: _evaluate } = useMemo(
|
||||
const shouldPaint = useCallback((pat) => !!(pat?.context?.onPaint && drawContext), [drawContext]);
|
||||
|
||||
// TODO: make sure this hook reruns when scheduler.started changes
|
||||
const { scheduler, evaluate, start, stop, pause } = useMemo(
|
||||
() =>
|
||||
repl({
|
||||
interval,
|
||||
defaultOutput,
|
||||
onSchedulerError: setSchedulerError,
|
||||
onEvalError: setEvalError,
|
||||
onEvalError: (err) => {
|
||||
setEvalError(err);
|
||||
onEvalError?.(err);
|
||||
},
|
||||
getTime,
|
||||
drawContext,
|
||||
transpiler,
|
||||
onEval: ({ pattern: _pattern, code }) => {
|
||||
editPattern,
|
||||
beforeEval: ({ code }) => {
|
||||
setCode(code);
|
||||
beforeEval?.();
|
||||
},
|
||||
afterEval: ({ pattern: _pattern, code }) => {
|
||||
setActiveCode(code);
|
||||
setPattern(_pattern);
|
||||
setEvalError();
|
||||
setSchedulerError();
|
||||
if (autolink) {
|
||||
window.location.hash = '#' + encodeURIComponent(btoa(code));
|
||||
}
|
||||
afterEval?.();
|
||||
},
|
||||
onToggle: (v) => {
|
||||
setStarted(v);
|
||||
onToggle?.(v);
|
||||
},
|
||||
onEvalError: setEvalError,
|
||||
}),
|
||||
[defaultOutput, interval, getTime],
|
||||
);
|
||||
const evaluate = useCallback(() => _evaluate(code), [_evaluate, code]);
|
||||
const broadcast = usePostMessage(({ data: { from, type } }) => {
|
||||
if (type === 'start' && from !== id) {
|
||||
// console.log('message', from, type);
|
||||
stop();
|
||||
}
|
||||
});
|
||||
const activateCode = useCallback(
|
||||
async (autostart = true) => {
|
||||
const res = await evaluate(code, autostart);
|
||||
broadcast({ type: 'start', from: id });
|
||||
return res;
|
||||
},
|
||||
[evaluate, code],
|
||||
);
|
||||
|
||||
const onDraw = useCallback(
|
||||
(pattern, time, haps, drawTime) => {
|
||||
const { onPaint } = pattern.context || {};
|
||||
const ctx = typeof drawContext === 'function' ? drawContext(canvasId) : drawContext;
|
||||
onPaint?.(ctx, time, haps, drawTime);
|
||||
},
|
||||
[drawContext, canvasId],
|
||||
);
|
||||
|
||||
const drawFirstFrame = useCallback(
|
||||
(pat) => {
|
||||
if (shouldPaint(pat)) {
|
||||
const [_, lookahead] = drawTime;
|
||||
const haps = pat.queryArc(0, lookahead);
|
||||
// draw at -0.001 to avoid activating haps at 0
|
||||
onDraw(pat, -0.001, haps, drawTime);
|
||||
}
|
||||
},
|
||||
[drawTime, onDraw, shouldPaint],
|
||||
);
|
||||
|
||||
const inited = useRef();
|
||||
useEffect(() => {
|
||||
if (!inited.current && evalOnMount && code) {
|
||||
inited.current = true;
|
||||
evaluate();
|
||||
evaluate(code, false).then((pat) => drawFirstFrame(pat));
|
||||
}
|
||||
}, [evaluate, evalOnMount, code]);
|
||||
}, [evalOnMount, code, evaluate, drawFirstFrame]);
|
||||
|
||||
return { schedulerError, scheduler, evalError, evaluate, activeCode, isDirty, pattern };
|
||||
// this will stop the scheduler when hot reloading in development
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
scheduler.stop();
|
||||
};
|
||||
}, [scheduler]);
|
||||
|
||||
const togglePlay = async () => {
|
||||
if (started) {
|
||||
scheduler.stop();
|
||||
drawFirstFrame(pattern);
|
||||
} else {
|
||||
await activateCode();
|
||||
}
|
||||
};
|
||||
const error = schedulerError || evalError;
|
||||
|
||||
usePatternFrame({
|
||||
pattern,
|
||||
started: shouldPaint(pattern) && started,
|
||||
getTime: () => scheduler.now(),
|
||||
drawTime,
|
||||
onDraw,
|
||||
});
|
||||
|
||||
return {
|
||||
id,
|
||||
canvasId,
|
||||
code,
|
||||
setCode,
|
||||
error,
|
||||
schedulerError,
|
||||
scheduler,
|
||||
evalError,
|
||||
evaluate,
|
||||
activateCode,
|
||||
activeCode,
|
||||
isDirty,
|
||||
pattern,
|
||||
started,
|
||||
start,
|
||||
stop,
|
||||
pause,
|
||||
togglePlay,
|
||||
};
|
||||
}
|
||||
|
||||
export default useStrudel;
|
||||
|
||||
function s4() {
|
||||
return Math.floor((1 + Math.random()) * 0x10000)
|
||||
.toString(16)
|
||||
.substring(1);
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
/*
|
||||
useWebMidi.js - <short description TODO>
|
||||
Copyright (C) 2022 Strudel contributors - see <https://github.com/tidalcycles/strudel/blob/main/repl/src/useWebMidi.js>
|
||||
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 { useEffect, useState } from 'react';
|
||||
import { enableWebMidi, WebMidi } from '@strudel.cycles/midi'
|
||||
|
||||
export function useWebMidi(props) {
|
||||
const { ready, connected, disconnected } = props;
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [outputs, setOutputs] = useState(WebMidi?.outputs || []);
|
||||
useEffect(() => {
|
||||
enableWebMidi()
|
||||
.then(() => {
|
||||
// Reacting when a new device becomes available
|
||||
WebMidi.addListener('connected', (e) => {
|
||||
setOutputs([...WebMidi.outputs]);
|
||||
connected?.(WebMidi, e);
|
||||
});
|
||||
// Reacting when a device becomes unavailable
|
||||
WebMidi.addListener('disconnected', (e) => {
|
||||
setOutputs([...WebMidi.outputs]);
|
||||
disconnected?.(WebMidi, e);
|
||||
});
|
||||
ready?.(WebMidi);
|
||||
setLoading(false);
|
||||
})
|
||||
.catch((err) => {
|
||||
if (err) {
|
||||
console.error(err);
|
||||
//throw new Error("Web Midi could not be enabled...");
|
||||
console.warn('Web Midi could not be enabled..');
|
||||
return;
|
||||
}
|
||||
});
|
||||
}, [ready, connected, disconnected, outputs]);
|
||||
const outputByName = (name) => WebMidi.getOutputByName(name);
|
||||
return { loading, outputs, outputByName };
|
||||
}
|
||||
@@ -2,11 +2,8 @@
|
||||
|
||||
export { default as CodeMirror, flash } from './components/CodeMirror6';
|
||||
export * from './components/MiniRepl';
|
||||
export { default as useCycle } from './hooks/useCycle';
|
||||
export { default as useHighlighting } from './hooks/useHighlighting';
|
||||
export { default as usePostMessage } from './hooks/usePostMessage';
|
||||
export { default as useRepl } from './hooks/useRepl';
|
||||
export { default as useStrudel } from './hooks/useStrudel';
|
||||
export { default as useKeydown } from './hooks/useKeydown';
|
||||
export { default as cx } from './cx';
|
||||
export { useWebMidi } from './hooks/useWebMidi';
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
import React from 'react'
|
||||
import ReactDOM from 'react-dom'
|
||||
import App from './App'
|
||||
import React from 'react';
|
||||
import ReactDOM from 'react-dom';
|
||||
import App from './App';
|
||||
|
||||
ReactDOM.render(<React.StrictMode><App /></React.StrictMode>,document.getElementById('root'))
|
||||
ReactDOM.render(
|
||||
<React.StrictMode>
|
||||
<App />
|
||||
</React.StrictMode>,
|
||||
document.getElementById('root'),
|
||||
);
|
||||
|
||||
@@ -8,28 +8,36 @@ export default createTheme({
|
||||
caret: '#ffcc00',
|
||||
selection: 'rgba(128, 203, 196, 0.5)',
|
||||
selectionMatch: '#036dd626',
|
||||
lineHighlight: '#8a91991a',
|
||||
// lineHighlight: '#8a91991a', // original
|
||||
lineHighlight: '#00000050',
|
||||
gutterBackground: 'transparent',
|
||||
// gutterForeground: '#8a919966',
|
||||
gutterForeground: '#676e95',
|
||||
gutterForeground: '#8a919966',
|
||||
},
|
||||
styles: [
|
||||
{ tag: t.keyword, color: '#c792ea' },
|
||||
{ tag: t.operator, color: '#89ddff' },
|
||||
{ tag: t.special(t.variableName), color: '#eeffff' },
|
||||
{ tag: t.typeName, color: '#f07178' },
|
||||
// { tag: t.typeName, color: '#f07178' }, // original
|
||||
{ tag: t.typeName, color: '#c3e88d' },
|
||||
{ tag: t.atom, color: '#f78c6c' },
|
||||
{ tag: t.number, color: '#ff5370' },
|
||||
// { tag: t.number, color: '#ff5370' }, // original
|
||||
{ tag: t.number, color: '#c3e88d' },
|
||||
{ tag: t.definition(t.variableName), color: '#82aaff' },
|
||||
{ tag: t.string, color: '#c3e88d' },
|
||||
{ tag: t.special(t.string), color: '#f07178' },
|
||||
// { tag: t.special(t.string), color: '#f07178' }, // original
|
||||
{ tag: t.special(t.string), color: '#c3e88d' },
|
||||
{ tag: t.comment, color: '#7d8799' },
|
||||
{ tag: t.variableName, color: '#f07178' },
|
||||
{ tag: t.tagName, color: '#ff5370' },
|
||||
{ tag: t.bracket, color: '#a2a1a4' },
|
||||
// { tag: t.variableName, color: '#f07178' }, // original
|
||||
{ tag: t.variableName, color: '#c792ea' },
|
||||
// { tag: t.tagName, color: '#ff5370' }, // original
|
||||
{ tag: t.tagName, color: '#c3e88d' },
|
||||
{ tag: t.bracket, color: '#525154' },
|
||||
// { tag: t.bracket, color: '#a2a1a4' }, // original
|
||||
{ tag: t.meta, color: '#ffcb6b' },
|
||||
{ tag: t.attributeName, color: '#c792ea' },
|
||||
{ tag: t.propertyName, color: '#c792ea' },
|
||||
|
||||
{ tag: t.className, color: '#decb6b' },
|
||||
{ tag: t.invalid, color: '#ffffff' },
|
||||
],
|
||||
|
||||
@@ -24,8 +24,9 @@ export default defineConfig({
|
||||
// TODO: find out which of below names are obsolete now
|
||||
'@strudel.cycles/tone',
|
||||
'@strudel.cycles/eval',
|
||||
'@strudel.cycles/transpiler',
|
||||
'acorn',
|
||||
'@strudel.cycles/core',
|
||||
'@strudel.cycles/core/util.mjs',
|
||||
'@strudel.cycles/mini',
|
||||
'@strudel.cycles/tonal',
|
||||
'@strudel.cycles/midi',
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/serial",
|
||||
"version": "0.1.3",
|
||||
"version": "0.3.0",
|
||||
"description": "Webserial API for strudel",
|
||||
"main": "serial.mjs",
|
||||
"repository": {
|
||||
|
||||
+70
-30
@@ -6,71 +6,111 @@ This program is free software: you can redistribute it and/or modify it under th
|
||||
|
||||
import { Pattern, isPattern } from '@strudel.cycles/core';
|
||||
|
||||
var serialWriter;
|
||||
var writeMessage;
|
||||
var choosing = false;
|
||||
|
||||
export async function getWriter(br=38400) {
|
||||
export async function getWriter(br = 38400) {
|
||||
if (choosing) {
|
||||
return;
|
||||
}
|
||||
choosing = true;
|
||||
if (serialWriter) {
|
||||
return serialWriter;
|
||||
if (writeMessage) {
|
||||
return writeMessage;
|
||||
}
|
||||
if ('serial' in navigator) {
|
||||
const port = await navigator.serial.requestPort();
|
||||
await port.open({ baudRate: br });
|
||||
const textEncoder = new TextEncoderStream();
|
||||
const writableStreamClosed = textEncoder.readable.pipeTo(port.writable);
|
||||
const writer = textEncoder.writable.getWriter();
|
||||
serialWriter = function (message) {
|
||||
writer.write(message)
|
||||
}
|
||||
}
|
||||
else {
|
||||
throw('Webserial is not available in this browser.')
|
||||
const encoder = new TextEncoder();
|
||||
const writer = port.writable.getWriter();
|
||||
writeMessage = function (message, chk) {
|
||||
const encoded = encoder.encode(message);
|
||||
if (!chk) {
|
||||
writer.write(encoded);
|
||||
} else {
|
||||
const bytes = new Uint8Array(4);
|
||||
bytes[0] = 124; // | symbol
|
||||
bytes[1] = (chk >> 8) & 0xff;
|
||||
bytes[2] = chk & 0xff;
|
||||
bytes[3] = 59; // semicolon
|
||||
const withchk = new Uint8Array(encoded.length + 4);
|
||||
withchk.set(encoded);
|
||||
withchk.set(bytes, encoded.length);
|
||||
writer.write(withchk);
|
||||
}
|
||||
};
|
||||
} else {
|
||||
throw 'Webserial is not available in this browser.';
|
||||
}
|
||||
}
|
||||
|
||||
const latency = 0.1;
|
||||
|
||||
Pattern.prototype.serial = function (...args) {
|
||||
return this._withHap((hap) => {
|
||||
if (!serialWriter) {
|
||||
getWriter(...args);
|
||||
// crc16 (CCITT-FALSE) https://gist.github.com/tijnkooijmans/10981093
|
||||
function crc16(data) {
|
||||
const length = data.length;
|
||||
if (length == 0) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
var crc = 0xffff;
|
||||
for (var i = 0; i < length; ++i) {
|
||||
crc ^= data.charCodeAt(i) << 8;
|
||||
for (var j = 0; j < 8; ++j) {
|
||||
crc = (crc & 0x8000) > 0 ? (crc << 1) ^ 0x1021 : crc << 1;
|
||||
}
|
||||
}
|
||||
|
||||
return crc & 0xffff;
|
||||
}
|
||||
|
||||
Pattern.prototype.serial = function (br = 38400, sendcrc = false, singlecharids = false) {
|
||||
return this.withHap((hap) => {
|
||||
if (!writeMessage) {
|
||||
getWriter(br);
|
||||
}
|
||||
const onTrigger = (time, hap, currentTime) => {
|
||||
var message = "";
|
||||
var message = '';
|
||||
var chk = 0;
|
||||
if (typeof hap.value === 'object') {
|
||||
if ('action' in hap.value) {
|
||||
message += hap.value['action'] + '(';
|
||||
var action = hap.value['action'];
|
||||
if (singlecharids) {
|
||||
action = action.charAt(0);
|
||||
}
|
||||
message += action + '(';
|
||||
var first = true;
|
||||
for (const [key, val] of Object.entries(hap.value)) {
|
||||
for (var [key, val] of Object.entries(hap.value)) {
|
||||
if (key === 'action') {
|
||||
continue;
|
||||
}
|
||||
if (first) {
|
||||
first = false;
|
||||
} else {
|
||||
message += ',';
|
||||
}
|
||||
else {
|
||||
message +=',';
|
||||
if (singlecharids) {
|
||||
key = key.charAt(0);
|
||||
}
|
||||
message += `${key}:${val}`
|
||||
message += key + ':' + val;
|
||||
}
|
||||
message += ')';
|
||||
}
|
||||
else {
|
||||
if (sendcrc) {
|
||||
chk = crc16(message);
|
||||
}
|
||||
} else {
|
||||
for (const [key, val] of Object.entries(hap.value)) {
|
||||
message += `${key}:${val};`
|
||||
message += `${key}:${val}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
} else {
|
||||
message = hap.value;
|
||||
}
|
||||
const offset = (time - currentTime + latency) * 1000;
|
||||
window.setTimeout(serialWriter, offset, message);
|
||||
|
||||
window.setTimeout(function () {
|
||||
writeMessage(message, chk);
|
||||
}, offset);
|
||||
};
|
||||
return hap.setContext({ ...hap.context, onTrigger });
|
||||
return hap.setContext({ ...hap.context, onTrigger, dominantTrigger: true });
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { toMidi } from '@strudel.cycles/core';
|
||||
|
||||
let loadCache = {};
|
||||
async function loadFont(name) {
|
||||
if (loadCache[name]) {
|
||||
|
||||
@@ -42,7 +42,7 @@ export const instruments = [
|
||||
'0031_FluidR3_GM_sf2_file',
|
||||
'0031_GeneralUserGS_sf2_file',
|
||||
'0031_SoundBlasterOld_sf2', // pianos until here
|
||||
'0040_Aspirin_sf2_file',
|
||||
'0040_Aspirin_sf2_file',
|
||||
'0040_Chaos_sf2_file',
|
||||
'0040_FluidR3_GM_sf2_file', // rhodes
|
||||
'0040_GeneralUserGS_sf2_file', // staccato rhodes
|
||||
@@ -59,7 +59,7 @@ export const instruments = [
|
||||
'0046_GeneralUserGS_sf2_file', // ?
|
||||
'0050_Aspirin_sf2_file', // glass organ
|
||||
'0050_Chaos_sf2_file', // short glass organ
|
||||
'0050_FluidR3_GM_sf2_file',// long glass organ !
|
||||
'0050_FluidR3_GM_sf2_file', // long glass organ !
|
||||
'0050_GeneralUserGS_sf2_file', // short glass organ
|
||||
'0050_JCLive_sf2_file', // glass organ
|
||||
'0050_SBLive_sf2', // ?
|
||||
@@ -1635,7 +1635,7 @@ export const drums = [
|
||||
'81_4_Chaos_sf2_file',
|
||||
];
|
||||
|
||||
// see https://www.midi.org/specifications-old/item/gm-level-1-sound-set
|
||||
// see https://www.midi.org/specifications-old/item/gm-level-1-sound-set
|
||||
export const instrumentNames = [];
|
||||
instrumentNames[0] = 'Acoustic Grand Piano: Piano';
|
||||
instrumentNames[1] = 'Bright Acoustic Piano: Piano';
|
||||
|
||||
Generated
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/soundfonts",
|
||||
"version": "0.3.2",
|
||||
"version": "0.5.0",
|
||||
"lockfileVersion": 2,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@strudel.cycles/soundfonts",
|
||||
"version": "0.3.2",
|
||||
"version": "0.5.0",
|
||||
"description": "Soundsfont support for strudel",
|
||||
"main": "index.mjs",
|
||||
"type": "module",
|
||||
@@ -22,8 +22,8 @@
|
||||
},
|
||||
"homepage": "https://github.com/tidalcycles/strudel#readme",
|
||||
"dependencies": {
|
||||
"@strudel.cycles/core": "^0.3.2",
|
||||
"@strudel.cycles/webaudio": "^0.3.2",
|
||||
"@strudel.cycles/core": "^0.5.0",
|
||||
"@strudel.cycles/webaudio": "^0.5.0",
|
||||
"sfumato": "^0.1.2",
|
||||
"soundfont2": "^0.4.0"
|
||||
},
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Pattern } from '@strudel.cycles/core';
|
||||
import { Pattern, getPlayableNoteValue, toMidi } from '@strudel.cycles/core';
|
||||
import { getAudioContext } from '@strudel.cycles/webaudio';
|
||||
import { loadSoundfont as _loadSoundfont, startPresetNote } from 'sfumato';
|
||||
|
||||
Pattern.prototype.soundfont = function (sf, n = 0) {
|
||||
|
||||
@@ -31,4 +31,4 @@ yields:
|
||||
|
||||
## Tonal API
|
||||
|
||||
See "Tonal API" in the [Strudel Tutorial](https://strudel.tidalcycles.org/tutorial/)
|
||||
See "Tonal API" in the [Strudel Tutorial](https://strudel.tidalcycles.org/learn/tonal)
|
||||
|
||||
@@ -1,2 +1,5 @@
|
||||
import './tonal.mjs';
|
||||
import './voicings.mjs';
|
||||
|
||||
export * from './tonal.mjs';
|
||||
export * from './voicings.mjs';
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user