-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
91 lines (74 loc) · 2.01 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
var Through = require('through')
var keycode = require('keycode')
var KeyStream = require('./key_stream')
module.exports = function(options){
options = options || {}
var currentOffset = options.offset || 0
var currentVelocity = options.velocity || 127
var chan = options.channel || 0
var modes = {
'piano': {
notes: "AWSEDFTGYHUJKOLP;['".toLowerCase().split(''),
offsetBy: 12,
offset: ['z', 'x'],
velocity: ['c', 'v']
},
'grid': {
notes: 'QWERTYUIASDFGHJKZXCVBNM,'.toLowerCase().split(''),
offsetBy: 8,
offset: ['-', '='],
velocity: ['[', ']']
}
}
var commands = {}
var mode = modes[options.mode || 'keys']
commands[mode.offset[0]] = function octDown(){
currentOffset = Math.max(-mode.offsetBy, currentOffset - mode.offsetBy)
}
commands[mode.offset[1]] = function octUp(){
currentOffset = Math.min(127-mode.notes.length, currentOffset + mode.offsetBy)
}
commands[mode.velocity[0]] = function velDown(){
currentVelocity = Math.max(0, currentVelocity - 16)
}
commands[mode.velocity[1]] = function velUp(){
currentVelocity = Math.min(127, currentVelocity + 16)
}
var notes = mode.notes
var keyboard = Through(function(e){
var note = getNote(e)
if (note){
this.queue(note)
} else {
command(e)
}
})
if (global.document && global.document.addEventListener && options.bind !== false){
KeyStream().pipe(keyboard)
}
var ups = {}
function getNote(e){
var id = notes.indexOf(keycode(e.keyCode))
if (~id){
if (e.type == 'keyup'){
var up = ups[id]
ups[id] = null
return up
} else {
if (!ups[id]){
ups[id] = [144+chan||0, id+currentOffset, 0]
return [144+chan||0, id+currentOffset, currentVelocity]
}
}
}
}
function command(e){
if (e.type == 'keydown'){
var command = commands[keycode(e.keyCode)]
if (typeof command === 'function'){
command()
}
}
}
return keyboard
}