Compare commits

...

11 Commits

Author SHA1 Message Date
Felix Roos f805560827 dedupe 2026-11-26 23:30:21 +01:00
Felix Roos f8bb10d2a0 format 2026-11-26 23:16:35 +01:00
Felix Roos a160f76d23 pull out control-using pattern functions to controls.mjs 2026-11-26 23:16:17 +01:00
Felix Roos 3fc1cc871c fix import 2026-11-26 23:15:29 +01:00
Felix Roos 2c2c6bc6bf move evaluate back to core, keep strudelScope in pattern package 2026-11-26 22:31:33 +01:00
Felix Roos 089187b9b2 lockfile 2026-11-26 21:27:48 +01:00
Felix Roos dc441e68df fix old core imports to use pattern package 2026-11-26 21:27:39 +01:00
Felix Roos c6253789ab move pattern core to @strudel/pattern 2026-11-26 21:22:14 +01:00
Alex McLean b8b59d911f Merge pull request 'Reimplement reverted vim-mode features' (#2176) from wrbs/strudel:vim-ex-actions into main
Reviewed-on: https://codeberg.org/uzu/strudel/pulls/2176
2026-11-25 20:09:50 +01:00
William Robson 7a343930aa Add support for 'gc' vim command for togling comments
Missing keybind from the default codemirror vim stuff, but easy to wire
up ourselves in the same way as the upstream ones are.
2026-11-07 11:49:37 -05:00
William Robson 266e5da109 Add back :w and :q vim ex-command bindings for evaluate/stop
This is ultimately the equivalent of doing

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

but to make it a little more robust it uses a codemirror facet; this
means other editors like prebake won't clash as there's no
editorActions.of() provider there and it'll be a slient no-op for things
like .onEvaluate?.()
2026-11-07 11:49:36 -05:00
45 changed files with 780 additions and 652 deletions
+1 -1
View File
@@ -80,4 +80,4 @@
"engines": {
"node": ">=18.0.0"
}
}
}
+2 -1
View File
@@ -19,7 +19,7 @@ import { isAutoCompletionEnabled } from './autocomplete.mjs';
import { basicSetup } from './basicSetup.mjs';
import { flash, isFlashEnabled } from './flash.mjs';
import { highlightMiniLocations, isPatternHighlightingEnabled, updateMiniLocations } from './highlight.mjs';
import { keybindings } from './keybindings.mjs';
import { editorActions, keybindings } from './keybindings.mjs';
import { sliderPlugin, updateSliderWidgets } from './slider.mjs';
import { activateTheme, initTheme, theme } from './themes.mjs';
import { isTooltipEnabled } from './tooltip.mjs';
@@ -101,6 +101,7 @@ export function initEditor({ initialCode = '', onChange, onEvaluate, onStop, roo
syntaxHighlighting(defaultHighlightStyle),
EditorView.updateListener.of((v) => onChange(v)),
drawSelection({ cursorBlinkRate: 0 }),
editorActions.of({ onEvaluate, onStop }),
Prec.highest(
keymap.of([
{
+18 -4
View File
@@ -1,12 +1,15 @@
import { defaultKeymap } from '@codemirror/commands';
import { Prec, EditorState } from '@codemirror/state';
import { defaultKeymap, toggleLineComment } from '@codemirror/commands';
import { Facet, Prec, EditorState } from '@codemirror/state';
import { keymap, ViewPlugin } from '@codemirror/view';
// import { searchKeymap } from '@codemirror/search';
import { emacs } from '@replit/codemirror-emacs';
import { vim } from '@replit/codemirror-vim';
import { vim, Vim } from '@replit/codemirror-vim';
// import { vim } from './vim_test.mjs';
import { vscodeKeymap } from '@replit/codemirror-vscode-keymap';
// Per-editor way to plumb down { onEvaluate, onStop }, provided by initEditor.
export const editorActions = Facet.define({ combine: (values) => values[0] ?? {} });
const vscodePlugin = ViewPlugin.fromClass(
class {
constructor() {}
@@ -26,7 +29,18 @@ const keymaps = {
vscode: vscodeExtension,
};
export { Vim } from '@replit/codemirror-vim';
export { Vim }; // export for patterns/prebake to define custom actions
Vim.defineEx('write', 'w', (cm) => cm.cm6.state.facet(editorActions).onEvaluate?.());
Vim.defineEx('quit', 'q', (cm) => cm.cm6.state.facet(editorActions).onStop?.());
Vim.defineOperator('toggleComment', (cm, _args, _ranges, oldAnchor) => {
// By the time an operator runs, vim has selected the motion's range in the
// real editor so we can just call the normal codemirror command
toggleLineComment(cm.cm6);
return oldAnchor;
});
Vim.mapCommand('gc', 'operator', 'toggleComment', {}, { isEdit: true });
export function keybindings(name) {
const active = keymaps[name];
+463 -2
View File
@@ -4,8 +4,19 @@ Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { logger } from './logger.mjs';
import { Pattern, pure, register, reify } from './pattern.mjs';
import {
Pattern,
pure,
register,
reify,
logger,
stack,
slowcat,
Fraction,
sequence,
lcm,
__steps,
} from '@strudel/pattern';
export function createParam(names) {
let isMulti = Array.isArray(names);
@@ -3311,3 +3322,453 @@ export const bmod = (config) => pure({}).bmod(config);
export const { transient } = registerControl(['transient', 'transsustain']);
export const { FXrelease, FXrel, FXr, fxr } = registerControl('FXrelease', 'FXrel', 'FXr', 'fxr');
// moved from pattern.mjs, because they use controls:
/**
* Both speeds up the pattern (like 'fast') and the sample playback (like 'speed').
* @tags temporal
* @example
* s("bd sd:2").hurry("<1 2 4 3>").slow(1.5)
*/
export const hurry = register('hurry', function (r, pat) {
return pat._fast(r).mul(pure({ speed: r }));
});
/**
* Jux with adjustable stereo width. 0 = mono, 1 = full stereo.
* @tags temporal
* @name juxBy
* @synonyms juxby
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxBy("<0 .5 1>/2", rev)
*/
export const { juxBy, juxby } = register(['juxBy', 'juxby'], function (by, func, pat) {
by /= 2;
const elem_or = function (dict, key, dflt) {
if (key in dict) {
return dict[key];
}
return dflt;
};
const left = pat.withValue((val) => Object.assign({}, val, { pan: elem_or(val, 'pan', 0.5) - by }));
const right = func(pat.withValue((val) => Object.assign({}, val, { pan: elem_or(val, 'pan', 0.5) + by })));
return stack(left, right).setSteps(__steps ? lcm(left._steps, right._steps) : undefined);
});
/**
* Like juxBy, except it flips the ears each cycle.
* @name juxFlipBy
* @synonyms juxflipby, fluxBy, fluxby
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxFlipBy(".8", rev)
*/
export const { juxFlipBy, juxflipby, fluxBy, fluxby } = register(
['juxFlipBy', 'juxflipby', 'fluxBy', 'fluxby'],
function (by, func, pat) {
return pat.juxBy(slowcat(by, -by), func);
},
);
/**
* The jux function creates strange stereo effects, by applying a function to a pattern, but only in the right-hand channel.
* @tags temporal, superdough
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").jux(rev)
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").jux(press)
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").jux(iter(4))
*/
export const jux = register('jux', function (func, pat) {
return pat._juxBy(1, func, pat);
});
/**
* Like jux, but flips the ears each cycle.
* @name juxFlip
* @synonyms juxflip, flux
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxFlip(rev)
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxFlip(press)
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxFlip(iter(4))
*/
export const { juxFlip, flux } = register(['juxFlip', 'juxflip', 'flux'], function (func, pat) {
return pat._juxFlipBy(1, func, pat);
});
/**
* Superimpose and offset multiple times, gradually decreasing the velocity
* @tags temporal
* @name echo
* @memberof Pattern.prototype
* @returns {Pattern}
* @param {number} times how many times to repeat
* @param {number} time cycle offset between iterations
* @param {number} feedback velocity multiplicator for each iteration
* @example
* s("bd sd").echo(3, 1/6, .8)
*/
export const echo = register('echo', function (times, time, feedback, pat) {
return pat._echoWith(times, time, (pat, i) => pat.gain(Math.pow(feedback, i)));
});
/**
* Deprecated. Like echo, but the last 2 parameters are flipped.
* @tags temporal
* @name stut
* @param {number} times how many times to repeat
* @param {number} feedback velocity multiplicator for each iteration
* @param {number} time cycle offset between iterations
* @example
* s("bd sd").stut(3, .8, 1/6)
*/
export const stut = register('stut', function (times, feedback, time, pat) {
return pat._echoWith(times, time, (pat, i) => pat.gain(Math.pow(feedback, i)));
});
/**
* Sets the pattern's color to the given [hsla](https://www.w3schools.com/htmL/html_colors_hsl.asp)
*
* @name hsla
* @param {number} hue (0 - 360)
* @param {number} saturation percentage (0 - 100)
* @param {number} lightness percentage (0 - 100)
* @param {number} alpha (transparency) (0.0 - 1.0)
* @tags visualization
*/
export const hsla = register('hsla', (h, s, l, a, pat) => {
return pat.color(`hsla(${h}turn,${s * 100}%,${l * 100}%,${a})`);
});
/**
* Sets the pattern's color to the given [hsl](https://www.w3schools.com/htmL/html_colors_hsl.asp)
*
* @name hsl
* @param {number} hue (0 - 360)
* @param {number} saturation percentage (0 - 100)
* @param {number} lightness percentage (0 - 100)
* @tags visualization
*/
export const hsl = register('hsl', (h, s, l, pat) => {
return pat.color(`hsl(${h}turn,${s * 100}%,${l * 100}%)`);
});
/**
* Cuts each sample into the given number of parts, allowing you to explore a technique known as 'granular synthesis'.
* It turns a pattern of samples into a pattern of parts of samples.
* @name chop
* @tags samples
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* samples({ rhodes: 'https://cdn.freesound.org/previews/132/132051_316502-lq.mp3' })
* s("rhodes")
* .chop(4)
* .rev() // reverse order of chops
* .loopAt(2) // fit sample into 2 cycles
*
*/
export const chop = register('chop', function (n, pat) {
const slices = Array.from({ length: n }, (x, i) => i);
const slice_objects = slices.map((i) => ({ begin: i / n, end: (i + 1) / n }));
const merge = function (a, b) {
if ('begin' in a && 'end' in a && a.begin !== undefined && a.end !== undefined) {
const d = a.end - a.begin;
b = { begin: a.begin + b.begin * d, end: a.begin + b.end * d };
}
// return a;
return Object.assign({}, a, b);
};
const func = function (o) {
return sequence(slice_objects.map((slice_o) => merge(o, slice_o)));
};
return pat.squeezeBind(func).setSteps(__steps ? Fraction(n).mulmaybe(pat._steps) : undefined);
});
/**
* Cuts each sample into the given number of parts, triggering progressive portions of each sample at each loop.
* @name striate
* @tags samples
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("numbers:0 numbers:1 numbers:2").striate(6).slow(3)
*/
export const striate = register('striate', function (n, pat) {
const slices = Array.from({ length: n }, (x, i) => i);
const slice_objects = slices.map((i) => ({ begin: i / n, end: (i + 1) / n }));
const slicePat = slowcat(...slice_objects);
return pat
.set(slicePat)
._fast(n)
.setSteps(__steps ? Fraction(n).mulmaybe(pat._steps) : undefined);
});
/**
* Makes the sample fit the given number of cycles by changing the speed.
* @param {number} factor
* @param {Pattern} pat
* @param {number} [cps=0.5]
* @name loopAt
* @tags samples, pitch
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* samples({ rhodes: 'https://cdn.freesound.org/previews/132/132051_316502-lq.mp3' })
* s("rhodes").loopAt(2)
*/
const _loopAt = function (factor, pat, cps = 0.5) {
return pat
.speed((1 / factor) * cps)
.unit('c')
.slow(factor);
};
export const { loopAt, loopat } = register(['loopAt', 'loopat'], function (factor, pat) {
const steps = pat._steps ? pat._steps.div(factor) : undefined;
return new Pattern((state) => _loopAt(factor, pat, state.controls._cps).query(state), steps);
});
/**
* Chops samples into the given number of slices, triggering those slices with a given pattern of slice numbers.
* Instead of a number, it also accepts a list of numbers from 0 to 1 to slice at specific points.
* @name slice
* @tags samples
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* samples('github:tidalcycles/dirt-samples')
* s("breaks165").slice(8, "0 1 <2 2*2> 3 [4 0] 5 6 7".every(3, rev)).slow(0.75)
* @example
* samples('github:tidalcycles/dirt-samples')
* s("breaks125").fit().slice([0,.25,.5,.75], "0 1 1 <2 3>")
*/
export const slice = register(
'slice',
function (npat, ipat, opat) {
return npat
.innerBind((n) =>
ipat.outerBind((i) =>
opat.outerBind((o) => {
// If it's not an object, assume it's a string and make it a 's' control parameter
o = o instanceof Object ? o : { s: o };
const begin = Array.isArray(n) ? n[i] : i / n;
const end = Array.isArray(n) ? n[i + 1] : (i + 1) / n;
return pure({ begin, end, _slices: n, ...o });
}),
),
)
.setSteps(ipat._steps);
},
false, // turns off auto-patternification
);
/**
* Works the same as slice, but changes the playback speed of each slice to match the duration of its step.
* @name splice
* @tags samples, pitch
* @example
* samples('github:tidalcycles/dirt-samples')
* s("breaks165")
* .splice(8, "0 1 [2 3 0]@2 3 0@2 7")
*/
export const splice = register(
'splice',
function (npat, ipat, opat) {
const sliced = slice(npat, ipat, opat);
return new Pattern((state) => {
// TODO - default cps to 0.5
const cps = state.controls._cps || 1;
const haps = sliced.query(state);
return haps.map((hap) =>
hap.withValue((v) => ({
...{
speed: (cps / v._slices / hap.whole.duration) * (v.speed || 1),
unit: 'c',
},
...v,
})),
);
}).setSteps(ipat._steps);
},
false, // turns off auto-patternification
);
/**
* Makes the sample fit its event duration. Good for rhythmical loops like drum breaks.
* Similar to `loopAt`.
* @name fit
* @tags samples, pitch
* @example
* samples({ rhodes: 'https://cdn.freesound.org/previews/132/132051_316502-lq.mp3' })
* s("rhodes/2").fit()
*/
export const fit = register('fit', (pat) =>
pat.withHaps((haps, state) =>
haps.map((hap) =>
hap.withValue((v) => {
const slicedur = ('end' in v ? v.end : 1) - ('begin' in v ? v.begin : 0);
return {
...v,
speed: ((state.controls._cps || 1) / hap.whole.duration) * slicedur,
unit: 'c',
};
}),
),
),
);
/**
* Makes the sample fit the given number of cycles and cps value, by
* changing the speed. deprecated: use loopAt or fit instead, together with setCps / setCpm.
* @name loopAtCps
* @tags samples, pitch
* @memberof Pattern.prototype
* @deprecated
* @returns {Pattern}
* @example
* samples({ rhodes: 'https://cdn.freesound.org/previews/132/132051_316502-lq.mp3' })
* s("rhodes").loopAtCps(4,1.5).cps(1.5)
*/
export const { loopAtCps, loopatcps } = register(['loopAtCps', 'loopatcps'], function (factor, cps, pat) {
return _loopAt(factor, pat, cps);
});
let fadeGain = (p) => (p < 0.5 ? 1 : 1 - (p - 0.5) / 0.5);
/**
* Cross-fades between left and right from 0 to 1:
* - 0 = (full left, no right)
* - .5 = (both equal)
* - 1 = (no left, full right)
*
* @param {Pattern} a
* @param {Pattern} pos
* @param {Pattern} b
* @name xfade
* @tags amplitude
* @returns {Pattern}
* @example
* xfade(s("bd*2"), "<0 .25 .5 .75 1>", s("hh*8"))
*/
export let xfade = (a, pos, b) => {
pos = reify(pos);
a = reify(a);
b = reify(b);
let gaina = pos.fmap((v) => ({ gain: fadeGain(v) }));
let gainb = pos.fmap((v) => ({ gain: fadeGain(1 - v) }));
return stack(a.mul(gaina), b.mul(gainb));
};
// the prototype version is actually flipped so left/right makes sense
Pattern.prototype.xfade = function (pos, b) {
return xfade(this, pos, b);
};
const _distortWithAlg = function (name) {
const func = function (args, pat) {
const argsPat = reify(args).fmap((v) => (Array.isArray(v) ? [...v, name] : [v, 1, name]));
if (!pat) {
return pure({}).distort(argsPat);
}
return pat.distort(argsPat);
};
Pattern.prototype[name] = function (args) {
return func(args, this);
};
return func;
};
/**
* Soft-clipping distortion
*
* @name soft
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const soft = _distortWithAlg('soft');
/**
* Hard-clipping distortion
*
* @name hard
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const hard = _distortWithAlg('hard');
/**
* Cubic polynomial distortion
*
* @name cubic
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const cubic = _distortWithAlg('cubic');
/**
* Diode-emulating distortion
*
* @name diode
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const diode = _distortWithAlg('diode');
/**
* Asymmetrical diode distortion
*
* @name asym
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const asym = _distortWithAlg('asym');
/**
* Wavefolding distortion
*
* @name fold
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const fold = _distortWithAlg('fold');
/**
* Wavefolding distortion composed with sinusoid
*
* @name sinefold
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const sinefold = _distortWithAlg('sinefold');
/**
* Distortion via Chebyshev polynomials
*
* @name chebyshev
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const chebyshev = _distortWithAlg('chebyshev');
+1 -1
View File
@@ -5,7 +5,7 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import createClock from './zyklus.mjs';
import { errorLogger, logger } from './logger.mjs';
import { errorLogger, logger } from '@strudel/pattern';
export class Cyclist {
constructor({
+1 -1
View File
@@ -4,7 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
export const strudelScope = {};
import { strudelScope } from '@strudel/pattern';
export const evalScope = async (...args) => {
const results = await Promise.allSettled(args);
+35 -27
View File
@@ -5,37 +5,45 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import * as controls from './controls.mjs'; // legacy
export * from './euclid.mjs';
import Fraction from './fraction.mjs';
import createClock from './zyklus.mjs';
import { logger } from './logger.mjs';
export { Fraction, controls, createClock };
import { Pattern } from '@strudel/pattern';
export { controls, createClock };
export * from '@strudel/pattern';
export * from './controls.mjs';
export * from './cyclist.mjs';
export * from './evaluate.mjs';
export * from './hap.mjs';
export * from './impure.mjs';
export * from './logger.mjs';
export * from './pattern.mjs';
export * from './pick.mjs';
export * from './repl.mjs';
export * from './signal.mjs';
export * from './speak.mjs';
export * from './state.mjs';
export * from './schedulerState.mjs';
export * from './timespan.mjs';
export * from './ui.mjs';
export * from './util.mjs';
export { default as drawLine } from './drawLine.mjs';
// below won't work with runtime.mjs (json import fails)
/* import * as p from './package.json';
export const version = p.version; */
logger('🌀 @strudel/core loaded 🌀');
if (globalThis._strudelLoaded) {
console.warn(
`@strudel/core was loaded more than once...
This might happen when you have multiple versions of strudel installed.
Please check with "npm ls @strudel/core".`,
);
}
globalThis._strudelLoaded = true;
export * from './evaluate.mjs';
import { getClockTime } from './schedulerState.mjs';
// legacy:
Pattern.prototype.onTrigger = function (onTrigger, dominant = true) {
console.warn('onTrigger is deprecated.. use onSchedule(hap, time, cps) instead');
return this.onSchedule((hap, t, cps) => {
const currentTime = getClockTime();
return onTrigger(hap, currentTime, cps, t);
}, dominant);
};
/**
*
* make something happen on event time
* uses browser timeout which is innacurate for audio tasks
* @param {Function} func
* @name onTriggerTime
* @tags external_io
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("bd!8").onTriggerTime((hap) => {console.log(hap)})
*/
Pattern.prototype.onTriggerTime = function (func) {
return this.onSchedule((hap, targetTime) => {
const diff = targetTime - getClockTime();
setTimeout(() => {
func(hap);
}, diff * 1000);
}, false);
};
+1 -2
View File
@@ -4,8 +4,7 @@ Copyright (C) 2022 Strudel contributors - see <https://codeberg.org/uzu/strudel/
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
import { logger } from './logger.mjs';
import { ClockCollator, cycleToSeconds } from './util.mjs';
import { logger, ClockCollator, cycleToSeconds } from '@strudel/pattern';
export class NeoCyclist {
constructor({ onSchedule, onToggle, getTime, onTrigger }) {
+2 -1
View File
@@ -31,7 +31,8 @@
},
"homepage": "https://strudel.cc",
"dependencies": {
"fraction.js": "^5.2.1"
"fraction.js": "^5.2.1",
"@strudel/pattern": "workspace:*"
},
"gitHead": "0e26d4e741500f5bae35b023608f062a794905c2",
"devDependencies": {
+3 -4
View File
@@ -1,7 +1,9 @@
import { NeoCyclist } from './neocyclist.mjs';
import { evalScope } from './evaluate.mjs';
import { Cyclist } from './cyclist.mjs';
import { reset_state } from '@strudel/pattern';
import { evaluate as _evaluate } from './evaluate.mjs';
import { errorLogger, logger } from './logger.mjs';
import { errorLogger, logger, register, Pattern, isPattern, silence, stack } from '@strudel/pattern';
import {
setCpsFunc,
setIsStarted,
@@ -10,9 +12,6 @@ import {
setScheduleFunc,
setClockTime,
} from './schedulerState.mjs';
import { evalScope } from './evaluate.mjs';
import { register, Pattern, isPattern, silence, stack } from './pattern.mjs';
import { reset_state } from './impure.mjs';
export function repl({
onSchedule,
+116 -1
View File
@@ -7,7 +7,8 @@ This program is free software: you can redistribute it and/or modify it under th
import { s, pan, getControlName } from '../controls.mjs';
import { mini } from '../../mini/mini.mjs';
import { describe, it, expect } from 'vitest';
import Fraction from '../fraction.mjs';
import { Fraction, sequence, pure, fast, stack } from '@strudel/pattern';
import { sameFirst } from '../../pattern/test/pattern.test.mjs';
describe('controls', () => {
it('should support controls', () => {
@@ -44,3 +45,117 @@ describe('controls', () => {
expect(getControlName('cutoff')).toEqual('cutoff');
});
});
describe('chop', () => {
it('Can _chop(2)', () => {
expect(sequence({ sound: 'a' }, { sound: 'b' })._chop(2).firstCycle()).toStrictEqual(
sequence(
{ sound: 'a', begin: 0, end: 0.5 },
{ sound: 'a', begin: 0.5, end: 1 },
{ sound: 'b', begin: 0, end: 0.5 },
{ sound: 'b', begin: 0.5, end: 1 },
).firstCycle(),
);
});
it('Can chop(2,3)', () => {
expect(pure({ sound: 'a' }).fast(2).chop(2, 3).sortHapsByPart().firstCycle()).toStrictEqual(
sequence(
[
{ sound: 'a', begin: 0, end: 0.5 },
{ sound: 'a', begin: 0.5, end: 1 },
],
[
{ sound: 'a', begin: 0, end: 1 / 3 },
{ sound: 'a', begin: 1 / 3, end: 2 / 3 },
{ sound: 'a', begin: 2 / 3, end: 1 },
],
)
.sortHapsByPart()
.firstCycle(),
);
});
it('Can chop chops', () => {
expect(pure({ s: 'bev' }).chop(2).chop(2).firstCycle()).toStrictEqual(pure({ s: 'bev' }).chop(4).firstCycle());
});
});
describe('loopAt', () => {
it('maintains steps', () => {
expect(s('bev').chop(8).loopAt(2)._steps).toStrictEqual(Fraction(4));
});
});
describe('_steps', () => {
it('Is correctly preserved/calculated through transformations', () => {
expect(sequence({ n: 0 }, { n: 1 }, { n: 2 }).chop(4)._steps).toStrictEqual(Fraction(12));
expect(sequence(0, 1, 2, 3).hurry(4)._steps).toStrictEqual(Fraction(4));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).chop(4)._steps).toStrictEqual(Fraction(8));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).striate(4)._steps).toStrictEqual(Fraction(8));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).slice(4, sequence(0, 1, 2, 3))._steps).toStrictEqual(Fraction(4));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).splice(4, sequence(0, 1, 2, 3))._steps).toStrictEqual(
Fraction(4),
);
});
});
describe('hurry', () => {
it('Can speed up patterns and sounds', () => {
sameFirst(s(sequence('a', 'b')).hurry(2), s(sequence('a', 'b')).fast(2).set({ speed: 2 }));
});
});
describe('jux', () => {
it('Can juxtapose', () => {
expect(pure({ a: 1 }).jux(fast(2)).sortHapsByPart().firstCycle()).toStrictEqual(
stack(pure({ a: 1, pan: 0 }), pure({ a: 1, pan: 1 }).fast(2))
.sortHapsByPart()
.firstCycle(),
);
});
});
describe('juxBy', () => {
it('Can juxtapose by half', () => {
expect(pure({ a: 1 }).juxBy(0.5, fast(2)).sortHapsByPart().firstCycle()).toStrictEqual(
stack(pure({ a: 1, pan: 0.25 }), pure({ a: 1, pan: 0.75 }).fast(2))
.sortHapsByPart()
.firstCycle(),
);
});
});
describe('striate', () => {
it('Can striate(2)', () => {
sameFirst(
sequence({ sound: 'a' }).striate(2),
sequence({ sound: 'a', begin: 0, end: 0.5 }, { sound: 'a', begin: 0.5, end: 1 }),
);
});
});
describe('slice', () => {
it('Can slice a sample', () => {
sameFirst(
s('break').slice(4, sequence(0, 1, 2, 3)),
sequence(
{ begin: 0, end: 0.25, s: 'break', _slices: 4 },
{ begin: 0.25, end: 0.5, s: 'break', _slices: 4 },
{ begin: 0.5, end: 0.75, s: 'break', _slices: 4 },
{ begin: 0.75, end: 1, s: 'break', _slices: 4 },
),
);
});
});
describe('splice', () => {
it('Can splice a sample', () => {
sameFirst(
s('break').splice(4, sequence(0, 1, 2, 3)),
sequence(
{ begin: 0, end: 0.25, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.25, end: 0.5, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.5, end: 0.75, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.75, end: 1, s: 'break', _slices: 4, unit: 'c', speed: 1 },
),
);
});
});
+1 -1
View File
@@ -1,5 +1,5 @@
import { listen } from '@tauri-apps/api/event';
import { logger } from '../core/logger.mjs';
import { logger } from '@strudel/core';
// listen for log events from the Tauri backend and log in the UI
await listen('log-event', (e) => {
+1 -1
View File
@@ -1,6 +1,6 @@
import { describe, bench } from 'vitest';
import { calculateSteps } from '../../core/index.mjs';
import { calculateSteps } from '@strudel/pattern';
import { mini } from '../index.mjs';
describe('mini', () => {
+2 -2
View File
@@ -5,8 +5,8 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import * as krill from './krill-parser.js';
import * as strudel from '@strudel/core';
import Fraction, { lcm } from '@strudel/core/fraction.mjs';
import * as strudel from '@strudel/pattern';
import { Fraction, lcm } from '@strudel/pattern';
const randOffset = 0.0003;
+1 -1
View File
@@ -32,7 +32,7 @@
},
"homepage": "https://codeberg.org/uzu/strudel#readme",
"dependencies": {
"@strudel/core": "workspace:*"
"@strudel/pattern": "workspace:*"
},
"devDependencies": {
"peggy": "^4.2.0",
+2 -2
View File
@@ -5,8 +5,8 @@ This program is free software: you can redistribute it and/or modify it under th
*/
import { getLeafLocation, getLeafLocations, mini, mini2ast } from '../mini.mjs';
import '@strudel/core/euclid.mjs';
import { Fraction } from '@strudel/core/index.mjs';
import '@strudel/pattern';
import { Fraction } from '@strudel/pattern';
import { describe, expect, it } from 'vitest';
describe('mini', () => {
+1 -1
View File
@@ -1,6 +1,6 @@
// motion.mjs
import { signal } from '../core/signal.mjs';
import { signal } from '@strudel/core';
/**
* The accelerometer's x-axis value ranges from 0 to 1.
+32
View File
@@ -0,0 +1,32 @@
/*
index.mjs - <short description TODO>
Copyright (C) 2025 Strudel contributors - see <https://codeberg.org/uzu/strudel/src/branch/main/packages/core/index.mjs>
This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
export * from './euclid.mjs';
import Fraction, { lcm } from './fraction.mjs';
import { logger } from './logger.mjs';
export { Fraction, lcm };
export * from './hap.mjs';
export * from './impure.mjs';
export * from './logger.mjs';
export * from './pattern.mjs';
export * from './pick.mjs';
export * from './signal.mjs';
export * from './state.mjs';
export * from './timespan.mjs';
export * from './util.mjs';
export { default as drawLine } from './drawLine.mjs';
// below won't work with runtime.mjs (json import fails)
/* import * as p from './package.json';
export const version = p.version; */
logger('🌀 @strudel/pattern loaded 🌀');
if (globalThis._strudelLoaded) {
console.warn(
`@strudel/pattern was loaded more than once...
This might happen when you have multiple versions of strudel installed.
Please check with "npm ls @strudel/pattern".`,
);
}
globalThis._strudelLoaded = true;
@@ -5,7 +5,7 @@ let debounce = 1000,
lastTime;
export function errorLogger(e, origin = 'cyclist') {
if (process.env.NODE_ENV === 'development') {
if (typeof process !== 'undefined' && process.env.NODE_ENV === 'development') {
console.error(e);
}
logger(`[${origin}] error: ${e.message}`);
+44
View File
@@ -0,0 +1,44 @@
{
"name": "@strudel/pattern",
"version": "1.2.6",
"description": "Port of Tidal Cycles to JavaScript. This package contains only the pattern representation.",
"main": "index.mjs",
"type": "module",
"publishConfig": {
"main": "dist/index.mjs"
},
"scripts": {
"test": "vitest run",
"bench": "vitest bench",
"build": "vite build",
"prepublishOnly": "pnpm build"
},
"repository": {
"type": "git",
"url": "git+https://codeberg.org/uzu/strudel.git"
},
"keywords": [
"tidalcycles",
"strudel",
"pattern",
"livecoding",
"algorave"
],
"author": "Alex McLean <alex@slab.org> (https://slab.org)",
"license": "AGPL-3.0-or-later",
"bugs": {
"url": "https://codeberg.org/uzu/strudel/issues"
},
"homepage": "https://strudel.cc",
"dependencies": {
"fraction.js": "^5.2.1"
},
"gitHead": "0e26d4e741500f5bae35b023608f062a794905c2",
"devDependencies": {
"vite": "^6.0.11",
"vitest": "^3.0.4"
},
"engines": {
"node": ">=18.0.0"
}
}
@@ -26,12 +26,12 @@ import {
} from './util.mjs';
import drawLine from './drawLine.mjs';
import { errorLogger, logger } from './logger.mjs';
import { strudelScope } from './evaluate.mjs';
import { getClockTime } from './schedulerState.mjs';
export const strudelScope = {};
let stringParser;
let __steps = true;
export let __steps = true;
export const calculateSteps = function (x) {
__steps = x ? true : false;
@@ -959,15 +959,6 @@ export class Pattern {
);
}
// legacy:
onTrigger(onTrigger, dominant = true) {
console.warn('onTrigger is deprecated.. use onSchedule(hap, time, cps) instead');
return this.onSchedule((hap, t, cps) => {
const currentTime = getClockTime();
return onTrigger(hap, currentTime, cps, t);
}, dominant);
}
/**
* Writes the content of the current event to the console (visible in the side menu).
* @param {Function} [func]
@@ -2410,16 +2401,6 @@ export const fast = register(
true,
);
/**
* Both speeds up the pattern (like 'fast') and the sample playback (like 'speed').
* @tags temporal
* @example
* s("bd sd:2").hurry("<1 2 4 3>").slow(1.5)
*/
export const hurry = register('hurry', function (r, pat) {
return pat._fast(r).mul(pure({ speed: r }));
});
/**
* Slow down a pattern over the given number of cycles. Like the "/" operator in mini notation.
*
@@ -2920,71 +2901,6 @@ export const palindrome = register(
true,
);
/**
* Jux with adjustable stereo width. 0 = mono, 1 = full stereo.
* @tags temporal
* @name juxBy
* @synonyms juxby
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxBy("<0 .5 1>/2", rev)
*/
export const { juxBy, juxby } = register(['juxBy', 'juxby'], function (by, func, pat) {
by /= 2;
const elem_or = function (dict, key, dflt) {
if (key in dict) {
return dict[key];
}
return dflt;
};
const left = pat.withValue((val) => Object.assign({}, val, { pan: elem_or(val, 'pan', 0.5) - by }));
const right = func(pat.withValue((val) => Object.assign({}, val, { pan: elem_or(val, 'pan', 0.5) + by })));
return stack(left, right).setSteps(__steps ? lcm(left._steps, right._steps) : undefined);
});
/**
* Like juxBy, except it flips the ears each cycle.
* @name juxFlipBy
* @synonyms juxflipby, fluxBy, fluxby
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxFlipBy(".8", rev)
*/
export const { juxFlipBy, juxflipby, fluxBy, fluxby } = register(
['juxFlipBy', 'juxflipby', 'fluxBy', 'fluxby'],
function (by, func, pat) {
return pat.juxBy(slowcat(by, -by), func);
},
);
/**
* The jux function creates strange stereo effects, by applying a function to a pattern, but only in the right-hand channel.
* @tags temporal, superdough
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").jux(rev)
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").jux(press)
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").jux(iter(4))
*/
export const jux = register('jux', function (func, pat) {
return pat._juxBy(1, func, pat);
});
/**
* Like jux, but flips the ears each cycle.
* @name juxFlip
* @synonyms juxflip, flux
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxFlip(rev)
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxFlip(press)
* @example
* s("bd lt [~ ht] mt cp ~ bd hh").juxFlip(iter(4))
*/
export const { juxFlip, flux } = register(['juxFlip', 'juxflip', 'flux'], function (func, pat) {
return pat._juxFlipBy(1, func, pat);
});
/**
* Superimpose and offset multiple times, applying the given function each time.
* @tags temporal, functional
@@ -3005,36 +2921,6 @@ export const { echoWith, echowith, stutWith, stutwith } = register(
},
);
/**
* Superimpose and offset multiple times, gradually decreasing the velocity
* @tags temporal
* @name echo
* @memberof Pattern.prototype
* @returns {Pattern}
* @param {number} times how many times to repeat
* @param {number} time cycle offset between iterations
* @param {number} feedback velocity multiplicator for each iteration
* @example
* s("bd sd").echo(3, 1/6, .8)
*/
export const echo = register('echo', function (times, time, feedback, pat) {
return pat._echoWith(times, time, (pat, i) => pat.gain(Math.pow(feedback, i)));
});
/**
* Deprecated. Like echo, but the last 2 parameters are flipped.
* @tags temporal
* @name stut
* @param {number} times how many times to repeat
* @param {number} feedback velocity multiplicator for each iteration
* @param {number} time cycle offset between iterations
* @example
* s("bd sd").stut(3, .8, 1/6)
*/
export const stut = register('stut', function (times, feedback, time, pat) {
return pat._echoWith(times, time, (pat, i) => pat.gain(Math.pow(feedback, i)));
});
export const applyN = register('applyN', function (n, func, p) {
let result = p;
for (let i = 0; i < n; i++) {
@@ -3303,33 +3189,6 @@ export const { ribbon, rib } = register(['ribbon', 'rib'], (offset, cycles, pat)
pat.early(offset).restart(pure(1).slow(cycles)),
);
/**
* Sets the pattern's color to the given [hsla](https://www.w3schools.com/htmL/html_colors_hsl.asp)
*
* @name hsla
* @param {number} hue (0 - 360)
* @param {number} saturation percentage (0 - 100)
* @param {number} lightness percentage (0 - 100)
* @param {number} alpha (transparency) (0.0 - 1.0)
* @tags visualization
*/
export const hsla = register('hsla', (h, s, l, a, pat) => {
return pat.color(`hsla(${h}turn,${s * 100}%,${l * 100}%,${a})`);
});
/**
* Sets the pattern's color to the given [hsl](https://www.w3schools.com/htmL/html_colors_hsl.asp)
*
* @name hsl
* @param {number} hue (0 - 360)
* @param {number} saturation percentage (0 - 100)
* @param {number} lightness percentage (0 - 100)
* @tags visualization
*/
export const hsl = register('hsl', (h, s, l, pat) => {
return pat.color(`hsl(${h}turn,${s * 100}%,${l * 100}%)`);
});
/**
* Tags each Hap with an identifier. Good for filtering. The function populates Hap.context.tags (Array).
* @name tag
@@ -3946,210 +3805,6 @@ Pattern.prototype.steps = Pattern.prototype.pace;
// Control-related functions, i.e. ones that manipulate patterns of
// objects
/**
* Cuts each sample into the given number of parts, allowing you to explore a technique known as 'granular synthesis'.
* It turns a pattern of samples into a pattern of parts of samples.
* @name chop
* @tags samples
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* samples({ rhodes: 'https://cdn.freesound.org/previews/132/132051_316502-lq.mp3' })
* s("rhodes")
* .chop(4)
* .rev() // reverse order of chops
* .loopAt(2) // fit sample into 2 cycles
*
*/
export const chop = register('chop', function (n, pat) {
const slices = Array.from({ length: n }, (x, i) => i);
const slice_objects = slices.map((i) => ({ begin: i / n, end: (i + 1) / n }));
const merge = function (a, b) {
if ('begin' in a && 'end' in a && a.begin !== undefined && a.end !== undefined) {
const d = a.end - a.begin;
b = { begin: a.begin + b.begin * d, end: a.begin + b.end * d };
}
// return a;
return Object.assign({}, a, b);
};
const func = function (o) {
return sequence(slice_objects.map((slice_o) => merge(o, slice_o)));
};
return pat.squeezeBind(func).setSteps(__steps ? Fraction(n).mulmaybe(pat._steps) : undefined);
});
/**
* Cuts each sample into the given number of parts, triggering progressive portions of each sample at each loop.
* @name striate
* @tags samples
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("numbers:0 numbers:1 numbers:2").striate(6).slow(3)
*/
export const striate = register('striate', function (n, pat) {
const slices = Array.from({ length: n }, (x, i) => i);
const slice_objects = slices.map((i) => ({ begin: i / n, end: (i + 1) / n }));
const slicePat = slowcat(...slice_objects);
return pat
.set(slicePat)
._fast(n)
.setSteps(__steps ? Fraction(n).mulmaybe(pat._steps) : undefined);
});
/**
* Makes the sample fit the given number of cycles by changing the speed.
* @param {number} factor
* @param {Pattern} pat
* @param {number} [cps=0.5]
* @name loopAt
* @tags samples, pitch
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* samples({ rhodes: 'https://cdn.freesound.org/previews/132/132051_316502-lq.mp3' })
* s("rhodes").loopAt(2)
*/
const _loopAt = function (factor, pat, cps = 0.5) {
return pat
.speed((1 / factor) * cps)
.unit('c')
.slow(factor);
};
export const { loopAt, loopat } = register(['loopAt', 'loopat'], function (factor, pat) {
const steps = pat._steps ? pat._steps.div(factor) : undefined;
return new Pattern((state) => _loopAt(factor, pat, state.controls._cps).query(state), steps);
});
/**
* Chops samples into the given number of slices, triggering those slices with a given pattern of slice numbers.
* Instead of a number, it also accepts a list of numbers from 0 to 1 to slice at specific points.
* @name slice
* @tags samples
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* samples('github:tidalcycles/dirt-samples')
* s("breaks165").slice(8, "0 1 <2 2*2> 3 [4 0] 5 6 7".every(3, rev)).slow(0.75)
* @example
* samples('github:tidalcycles/dirt-samples')
* s("breaks125").fit().slice([0,.25,.5,.75], "0 1 1 <2 3>")
*/
export const slice = register(
'slice',
function (npat, ipat, opat) {
return npat
.innerBind((n) =>
ipat.outerBind((i) =>
opat.outerBind((o) => {
// If it's not an object, assume it's a string and make it a 's' control parameter
o = o instanceof Object ? o : { s: o };
const begin = Array.isArray(n) ? n[i] : i / n;
const end = Array.isArray(n) ? n[i + 1] : (i + 1) / n;
return pure({ begin, end, _slices: n, ...o });
}),
),
)
.setSteps(ipat._steps);
},
false, // turns off auto-patternification
);
/**
*
* make something happen on event time
* uses browser timeout which is innacurate for audio tasks
* @param {Function} func
* @name onTriggerTime
* @tags external_io
* @memberof Pattern.prototype
* @returns {Pattern}
* @example
* s("bd!8").onTriggerTime((hap) => {console.log(hap)})
*/
Pattern.prototype.onTriggerTime = function (func) {
return this.onSchedule((hap, targetTime) => {
const diff = targetTime - getClockTime();
setTimeout(() => {
func(hap);
}, diff * 1000);
}, false);
};
/**
* Works the same as slice, but changes the playback speed of each slice to match the duration of its step.
* @name splice
* @tags samples, pitch
* @example
* samples('github:tidalcycles/dirt-samples')
* s("breaks165")
* .splice(8, "0 1 [2 3 0]@2 3 0@2 7")
*/
export const splice = register(
'splice',
function (npat, ipat, opat) {
const sliced = slice(npat, ipat, opat);
return new Pattern((state) => {
// TODO - default cps to 0.5
const cps = state.controls._cps || 1;
const haps = sliced.query(state);
return haps.map((hap) =>
hap.withValue((v) => ({
...{
speed: (cps / v._slices / hap.whole.duration) * (v.speed || 1),
unit: 'c',
},
...v,
})),
);
}).setSteps(ipat._steps);
},
false, // turns off auto-patternification
);
/**
* Makes the sample fit its event duration. Good for rhythmical loops like drum breaks.
* Similar to `loopAt`.
* @name fit
* @tags samples, pitch
* @example
* samples({ rhodes: 'https://cdn.freesound.org/previews/132/132051_316502-lq.mp3' })
* s("rhodes/2").fit()
*/
export const fit = register('fit', (pat) =>
pat.withHaps((haps, state) =>
haps.map((hap) =>
hap.withValue((v) => {
const slicedur = ('end' in v ? v.end : 1) - ('begin' in v ? v.begin : 0);
return {
...v,
speed: ((state.controls._cps || 1) / hap.whole.duration) * slicedur,
unit: 'c',
};
}),
),
),
);
/**
* Makes the sample fit the given number of cycles and cps value, by
* changing the speed. deprecated: use loopAt or fit instead, together with setCps / setCpm.
* @name loopAtCps
* @tags samples, pitch
* @memberof Pattern.prototype
* @deprecated
* @returns {Pattern}
* @example
* samples({ rhodes: 'https://cdn.freesound.org/previews/132/132051_316502-lq.mp3' })
* s("rhodes").loopAtCps(4,1.5).cps(1.5)
*/
export const { loopAtCps, loopatcps } = register(['loopAtCps', 'loopatcps'], function (factor, cps, pat) {
return _loopAt(factor, pat, cps);
});
/** exposes a custom value at query time. basically allows mutating state without evaluation
* @param {function():Pattern} accessor
* @returns {Pattern}
@@ -4160,37 +3815,6 @@ export const ref = (accessor) =>
.withValue(() => reify(accessor()))
.innerJoin();
let fadeGain = (p) => (p < 0.5 ? 1 : 1 - (p - 0.5) / 0.5);
/**
* Cross-fades between left and right from 0 to 1:
* - 0 = (full left, no right)
* - .5 = (both equal)
* - 1 = (no left, full right)
*
* @param {Pattern} a
* @param {Pattern} pos
* @param {Pattern} b
* @name xfade
* @tags amplitude
* @returns {Pattern}
* @example
* xfade(s("bd*2"), "<0 .25 .5 .75 1>", s("hh*8"))
*/
export let xfade = (a, pos, b) => {
pos = reify(pos);
a = reify(a);
b = reify(b);
let gaina = pos.fmap((v) => ({ gain: fadeGain(v) }));
let gainb = pos.fmap((v) => ({ gain: fadeGain(1 - v) }));
return stack(a.mul(gaina), b.mul(gainb));
};
// the prototype version is actually flipped so left/right makes sense
Pattern.prototype.xfade = function (pos, b) {
return xfade(this, pos, b);
};
/**
* creates a structure pattern from divisions of a cycle
* especially useful for creating rhythms
@@ -4287,108 +3911,6 @@ export const morph = (frompat, topat, bypat) => {
return frompat.innerBind((from) => topat.innerBind((to) => bypat.innerBind((by) => _morph(from, to, by))));
};
const _distortWithAlg = function (name) {
const func = function (args, pat) {
const argsPat = reify(args).fmap((v) => (Array.isArray(v) ? [...v, name] : [v, 1, name]));
if (!pat) {
return pure({}).distort(argsPat);
}
return pat.distort(argsPat);
};
Pattern.prototype[name] = function (args) {
return func(args, this);
};
return func;
};
/**
* Soft-clipping distortion
*
* @name soft
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const soft = _distortWithAlg('soft');
/**
* Hard-clipping distortion
*
* @name hard
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const hard = _distortWithAlg('hard');
/**
* Cubic polynomial distortion
*
* @name cubic
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const cubic = _distortWithAlg('cubic');
/**
* Diode-emulating distortion
*
* @name diode
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const diode = _distortWithAlg('diode');
/**
* Asymmetrical diode distortion
*
* @name asym
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const asym = _distortWithAlg('asym');
/**
* Wavefolding distortion
*
* @name fold
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const fold = _distortWithAlg('fold');
/**
* Wavefolding distortion composed with sinusoid
*
* @name sinefold
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const sinefold = _distortWithAlg('sinefold');
/**
* Distortion via Chebyshev polynomials
*
* @name chebyshev
* @tags distortion, superdough
* @param {number | Pattern} distortion amount of distortion to apply
* @param {number | Pattern} volume linear postgain of the distortion
*
*/
export const chebyshev = _distortWithAlg('chebyshev');
/**
* Turns a list of patterns into a single pattern which outputs list-values
*
@@ -58,11 +58,12 @@ import {
arp,
} from '../index.mjs';
import { log, logValues, stackCenter } from '../pattern.mjs';
import { reify, stackCenter } from '../pattern.mjs';
import { steady } from '../signal.mjs';
import { n, s } from '../controls.mjs';
let n = (value) => reify(value).fmap((v) => ({ n: v }));
let s = (value) => reify(value).fmap((v) => ({ s: v }));
const st = (begin, end) => new State(ts(begin, end));
const ts = (begin, end) => new TimeSpan(Fraction(begin), Fraction(end));
@@ -71,7 +72,7 @@ const hap = (whole, part, value, context = {}) => new Hap(whole, part, value, co
const third = Fraction(1, 3);
const twothirds = Fraction(2, 3);
const sameFirst = (a, b) => {
export const sameFirst = (a, b) => {
return expect(a.sortHapsByPart().firstCycle()).toStrictEqual(b.sortHapsByPart().firstCycle());
};
@@ -876,24 +877,6 @@ describe('Pattern', () => {
);
});
});
describe('jux', () => {
it('Can juxtapose', () => {
expect(pure({ a: 1 }).jux(fast(2)).sortHapsByPart().firstCycle()).toStrictEqual(
stack(pure({ a: 1, pan: 0 }), pure({ a: 1, pan: 1 }).fast(2))
.sortHapsByPart()
.firstCycle(),
);
});
});
describe('juxBy', () => {
it('Can juxtapose by half', () => {
expect(pure({ a: 1 }).juxBy(0.5, fast(2)).sortHapsByPart().firstCycle()).toStrictEqual(
stack(pure({ a: 1, pan: 0.25 }), pure({ a: 1, pan: 0.75 }).fast(2))
.sortHapsByPart()
.firstCycle(),
);
});
});
describe('_squeezeJoin', () => {
it('Can squeeze', () => {
expect(
@@ -931,46 +914,6 @@ describe('Pattern', () => {
expect(sequence(1, 2, 3).ply(2).early(8).firstCycle().length).toBe(6);
});
});
describe('striate', () => {
it('Can striate(2)', () => {
sameFirst(
sequence({ sound: 'a' }).striate(2),
sequence({ sound: 'a', begin: 0, end: 0.5 }, { sound: 'a', begin: 0.5, end: 1 }),
);
});
});
describe('chop', () => {
it('Can _chop(2)', () => {
expect(sequence({ sound: 'a' }, { sound: 'b' })._chop(2).firstCycle()).toStrictEqual(
sequence(
{ sound: 'a', begin: 0, end: 0.5 },
{ sound: 'a', begin: 0.5, end: 1 },
{ sound: 'b', begin: 0, end: 0.5 },
{ sound: 'b', begin: 0.5, end: 1 },
).firstCycle(),
);
});
it('Can chop(2,3)', () => {
expect(pure({ sound: 'a' }).fast(2).chop(2, 3).sortHapsByPart().firstCycle()).toStrictEqual(
sequence(
[
{ sound: 'a', begin: 0, end: 0.5 },
{ sound: 'a', begin: 0.5, end: 1 },
],
[
{ sound: 'a', begin: 0, end: 1 / 3 },
{ sound: 'a', begin: 1 / 3, end: 2 / 3 },
{ sound: 'a', begin: 2 / 3, end: 1 },
],
)
.sortHapsByPart()
.firstCycle(),
);
});
it('Can chop chops', () => {
expect(pure({ s: 'bev' }).chop(2).chop(2).firstCycle()).toStrictEqual(pure({ s: 'bev' }).chop(4).firstCycle());
});
});
describe('range', () => {
it('Can be patterned', () => {
expect(sequence(0, 0).range(sequence(0, 0.5), 1).firstCycle()).toStrictEqual(sequence(0, 0.5).firstCycle());
@@ -1053,11 +996,6 @@ describe('Pattern', () => {
sameFirst(sequence('a', 'b', 'c', 'd').press(), sequence(silence, 'a', silence, 'b', silence, 'c', silence, 'd'));
});
});
describe('hurry', () => {
it('Can speed up patterns and sounds', () => {
sameFirst(s(sequence('a', 'b')).hurry(2), s(sequence('a', 'b')).fast(2).speed(2));
});
});
/*describe('composable functions', () => {
it('Can compose functions', () => {
sameFirst(sequence(3, 4).fast(2).rev().fast(2), fast(2).rev().fast(2)(sequence(3, 4)));
@@ -1076,32 +1014,6 @@ describe('Pattern', () => {
});
});
*/
describe('slice', () => {
it('Can slice a sample', () => {
sameFirst(
s('break').slice(4, sequence(0, 1, 2, 3)),
sequence(
{ begin: 0, end: 0.25, s: 'break', _slices: 4 },
{ begin: 0.25, end: 0.5, s: 'break', _slices: 4 },
{ begin: 0.5, end: 0.75, s: 'break', _slices: 4 },
{ begin: 0.75, end: 1, s: 'break', _slices: 4 },
),
);
});
});
describe('splice', () => {
it('Can splice a sample', () => {
sameFirst(
s('break').splice(4, sequence(0, 1, 2, 3)),
sequence(
{ begin: 0, end: 0.25, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.25, end: 0.5, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.5, end: 0.75, s: 'break', _slices: 4, unit: 'c', speed: 1 },
{ begin: 0.75, end: 1, s: 'break', _slices: 4, unit: 'c', speed: 1 },
),
);
});
});
describe('chunk', () => {
it('Processes each cycle of the source pattern multiple times, once for each chunk', () => {
expect(sequence(0, 1, 2, 3).slow(2).chunk(2, add(10)).fast(4).firstCycleValues).toStrictEqual([
@@ -1189,24 +1101,15 @@ describe('Pattern', () => {
);
});
});
describe('_steps', () => {
it('Is correctly preserved/calculated through transformations', () => {
expect(sequence(0, 1, 2, 3).linger(4)._steps).toStrictEqual(Fraction(4));
expect(sequence(0, 1, 2, 3).iter(4)._steps).toStrictEqual(Fraction(4));
expect(sequence(0, 1, 2, 3).fast(4)._steps).toStrictEqual(Fraction(4));
expect(sequence(0, 1, 2, 3).hurry(4)._steps).toStrictEqual(Fraction(4));
expect(sequence(0, 1, 2, 3).rev()._steps).toStrictEqual(Fraction(4));
expect(sequence(1).segment(10)._steps).toStrictEqual(Fraction(10));
expect(sequence(1, 0, 1).invert()._steps).toStrictEqual(Fraction(3));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).chop(4)._steps).toStrictEqual(Fraction(8));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).striate(4)._steps).toStrictEqual(Fraction(8));
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).slice(4, sequence(0, 1, 2, 3))._steps).toStrictEqual(
Fraction(4),
);
expect(sequence({ s: 'bev' }, { s: 'amenbreak' }).splice(4, sequence(0, 1, 2, 3))._steps).toStrictEqual(
Fraction(4),
);
expect(sequence({ n: 0 }, { n: 1 }, { n: 2 }).chop(4)._steps).toStrictEqual(Fraction(12));
expect(
pure((x) => x + 1)
.setSteps(3)
@@ -1319,11 +1222,6 @@ describe('Pattern', () => {
);
});
});
describe('loopAt', () => {
it('maintains steps', () => {
expect(s('bev').chop(8).loopAt(2)._steps).toStrictEqual(Fraction(4));
});
});
describe('bite', () => {
it('works with uneven patterns', () => {
sameFirst(
@@ -1405,7 +1303,7 @@ describe('Pattern', () => {
describe('logValues', () => {
it('logs values to console', () => {
const mockConsoleLog = vi.spyOn(console, 'log').mockImplementation(() => {});
const pattern = pure('a').note('c#').logValues();
const pattern = pure({ s: 'bd', speed: 2 }).logValues();
const haps = pattern.queryArc(0, 1);
// Force a trigger
@@ -1414,7 +1312,7 @@ describe('Pattern', () => {
});
expect(mockConsoleLog).toHaveBeenCalledWith(
'%c[hap] value:a note:c#',
'%c[hap] s:bd speed:2',
'background-color: black;color:white;border-radius:15px',
);
mockConsoleLog.mockRestore();
@@ -6,7 +6,7 @@ This program is free software: you can redistribute it and/or modify it under th
import Fraction from 'fraction.js';
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect } from 'vitest';
import {
saw,
@@ -25,7 +25,7 @@ import {
perx,
cyclesPer,
} from '../signal.mjs';
import { fastcat, sequence, State, TimeSpan, Hap, note } from '../index.mjs';
import { fastcat, sequence, State, TimeSpan, Hap, seq } from '../index.mjs';
const st = (begin, end) => new State(ts(begin, end));
const ts = (begin, end) => new TimeSpan(Fraction(begin), Fraction(end));
@@ -122,6 +122,6 @@ describe('perx', () => {
describe('shuffle', () => {
it('returns original pattern if input is 1', () => {
expect(note('c d e f').sound('piano').shuffle(1).firstCycle()).toEqual(note('c d e f').sound('piano').firstCycle());
expect(seq(1, 2, 3, 4).shuffle(1).firstCycle()).toEqual(seq(1, 2, 3, 4).firstCycle());
});
});
@@ -6,7 +6,6 @@ This program is free software: you can redistribute it and/or modify it under th
import { describe, it, expect } from 'vitest';
import { map, valued, mul } from '../value.mjs';
import { n } from '../controls.mjs';
describe('Value', () => {
it('unionWith', () => {
+20
View File
@@ -0,0 +1,20 @@
import { defineConfig } from 'vite';
import { dependencies } from './package.json';
import { resolve } from 'path';
// https://vitejs.dev/config/
export default defineConfig({
base: './',
plugins: [],
build: {
lib: {
entry: resolve(__dirname, 'index.mjs'),
formats: ['es'],
fileName: (ext) => ({ es: 'index.mjs' })[ext],
},
rollupOptions: {
external: [...Object.keys(dependencies)],
},
target: 'esnext',
},
});
+18 -2
View File
@@ -258,6 +258,9 @@ importers:
packages/core:
dependencies:
'@strudel/pattern':
specifier: workspace:*
version: link:../pattern
fraction.js:
specifier: ^5.2.1
version: 5.2.1
@@ -410,9 +413,9 @@ importers:
packages/mini:
dependencies:
'@strudel/core':
'@strudel/pattern':
specifier: workspace:*
version: link:../core
version: link:../pattern
devDependencies:
peggy:
specifier: ^4.2.0
@@ -500,6 +503,19 @@ importers:
specifier: ^6.0.11
version: 6.0.11(@types/node@22.10.10)(jiti@2.4.2)(lightningcss@1.29.1)(terser@5.37.0)(yaml@2.7.0)
packages/pattern:
dependencies:
fraction.js:
specifier: ^5.2.1
version: 5.2.1
devDependencies:
vite:
specifier: ^6.0.11
version: 6.0.11(@types/node@22.10.10)(jiti@2.4.2)(lightningcss@1.29.1)(terser@5.37.0)(yaml@2.7.0)
vitest:
specifier: ^3.0.4
version: 3.0.4(@types/debug@4.1.12)(@types/node@22.10.10)(@vitest/ui@3.0.4)(jiti@2.4.2)(lightningcss@1.29.1)(terser@5.37.0)(yaml@2.7.0)
packages/reference:
devDependencies:
vite:
+1 -2
View File
@@ -1,6 +1,5 @@
import { afterEach } from 'vitest';
import { useRNG } from './packages/core/signal.mjs';
import { setDefaultJoin } from './packages/core/pattern.mjs';
import { useRNG, setDefaultJoin } from './packages/pattern/index.mjs';
afterEach(() => {
// Avoid bleed between tests