Skip to content

Commit

Permalink
add func
Browse files Browse the repository at this point in the history
  • Loading branch information
daslyfe committed Dec 31, 2024
1 parent e71db24 commit 4251958
Show file tree
Hide file tree
Showing 3 changed files with 8,797 additions and 10,671 deletions.
27 changes: 26 additions & 1 deletion packages/core/signal.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ 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, register } from './pattern.mjs';
import Fraction from './fraction.mjs';
import { id, _mod, clamp, objectMap } from './util.mjs';

import { id, _mod, clamp, objectMap, getCurrentKeyboardState } from './util.mjs';

export function steady(value) {
// A continuous value
Expand Down Expand Up @@ -831,3 +832,27 @@ export const never = register('never', function (_, pat) {
export const always = register('always', function (func, pat) {
return func(pat);
});

/**
*
* Do something on a keypress, or array of keypresses
*
* @name onKey
* @memberof Pattern
* @returns Pattern
* @example
* * s("bd(5,8)").onKey("Control:j", x => x.segment(16).color("red")).onKey("Control:i", x => x.fast(2).color("blue"))
*/

export const onKey = register('onKey', function (input, func, pat) {
if (Array.isArray(input) === false) {
input = [input];
}

const keyState = getCurrentKeyboardState();

const on = input.every((x) => {
return keyState[x];
});
return pat.when(on, func);
});
19 changes: 19 additions & 0 deletions packages/core/util.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -434,6 +434,25 @@ function getUnixTimeSeconds() {
return Date.now() * 0.001;
}

let keyState;

export function getCurrentKeyboardState() {
if (keyState == null) {
keyState = {};
// Listen for the keydown event to mark the key as pressed
window.addEventListener('keydown', (event) => {
keyState[event.key] = true; // Mark the key as pressed
});

// Listen for the keyup event to mark the key as released
window.addEventListener('keyup', (event) => {
keyState[event.key] = false; // Mark the key as released
});
}

return { ...keyState }; // Return a shallow copy of the key state object
}

// Floating point versions, see Fraction for rational versions
// // greatest common divisor
// export const gcd = function (x, y, ...z) {
Expand Down
Loading

0 comments on commit 4251958

Please sign in to comment.