-
Notifications
You must be signed in to change notification settings - Fork 0
/
nexusUI 1.js
9690 lines (8032 loc) · 263 KB
/
nexusUI 1.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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
var manager = require('./lib/core/manager');
var domUtils = require('./lib/utils/dom');
var drawingUtils = require('./lib/utils/drawing');
var mathUtils = require('./lib/utils/math');
var extend = require('extend');
var WebFont = require('webfontloader');
/************************************************
* INSTANTIATE NX MANAGER AND CREATE ELEMENTS *
************************************************/
window.nx = new manager();
window.nx.onload = function() {};
window.nx = extend(window.nx,domUtils)
window.nx = extend(window.nx,drawingUtils)
window.nx = extend(window.nx,mathUtils)
/* this onload function turns canvases into nexus elements,
* using the canvas's id as its var name */
window.onload = function() {
try {
WebFont.load({
google: {
families: ['Open Sans']
}
});
} catch(e) {
console.log("font not loaded")
}
nx.addStylesheet();
// get all canvases on the page and add them to the manager
var allcanvi = document.getElementsByTagName("canvas");
for (i=0;i<allcanvi.length;i++) nx.transform(allcanvi[i]);
if (nx.isTouchDevice) {
document.addEventListener("touchmove", nx.blockMove, true);
document.addEventListener("touchstart", nx.blockMove, true);
}
nx.onload();
nx.startPulse();
};
},{"./lib/core/manager":2,"./lib/utils/dom":4,"./lib/utils/drawing":5,"./lib/utils/math":6,"extend":52,"webfontloader":53}],2:[function(require,module,exports){
/**
@title NexusUI API
@overview NexusUI is a JavaScript toolkit for easily creating musical interfaces in web browsers. Interfaces are rendered on HTML5 canvases and are ideal for web audio projects, mobile apps, or for sending OSC to external audio applications like Max.
@author Ben Taylor, Jesse Allison, Yemin Oh, Sébastien Piquemal
@copyright © 2011-2014
@license MIT
*/
var timingUtils = require('../utils/timing');
var drawingUtils = require('../utils/drawing');
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var transmit = require('../utils/transmit');
//var WAAClock = require('waaclock');
var manager = module.exports = function() {
/**
@class nx
@description Central nexusUI manager with shared utility functions for all nexusUI objects
*/
EventEmitter.apply(this)
/**@property {object} widgets Contains all interface widgets (e.g. nx.widgets.dial1, nx.widgets.toggle1) */
this.widgets = new Object();
this.elemTypeArr = new Array();
this.aniItems = new Array();
/* @property {boolean} showLabels Whether or not to draw an automatic text label on each interface component. */
this.showLabels = false;
this.starttime = new Date().getTime();
if (transmit) {
/**
@method sendsTo
@param {string or function} [destination] Protocol for transmitting data from interfaces (i.e. "js", "ajax", "ios", "max", or "node"). Also accepts custom functions.
```js
nx.sendsTo("ajax")
// or
nx.sendsTo(function(data) {
//define a custom transmission function
})
```
*/
this.sendsTo = transmit.setGlobalTransmit;
/**
@method setAjaxPath
@param {string} [path] If sending via AJAX, define the path to ajax destination
*/
this.setAjaxPath = transmit.setAjaxPath;
/** @property {string} destination NexusUI's transmission protocol (i.e. "js" or "ajax"). Defaults to "js". We recommend setting this property using nx.sendsTo() which ensures that all widgets receive this setting. */
this.destination = "js";
/** @property {string} ajaxPath If sending via AJAX, the destination path. Defaults to "lib/nexusOSCRelay.php". We recommend setting this property using nx.setAjaxPath() which ensures that all widgets receive this setting. */
this.ajaxPath = "lib/nexusOSCRelay.php";
}
/** @property {boolean} isTouchDevice Returns true if page is loaded on a touch device. */
this.isTouchDevice = ('ontouchstart' in document.documentElement)? true:false;
this.metas = document.getElementsByTagName('meta');
/** @property {boolean} globalWidgets Whether or not to instantiate a global variable for each widget (i.e. button1). Defaults to true. Designers of other softwares who wish to keep nexusUI entirely encapsulated in the nx object may set this property to false. In that case, all widgets are accessible in nx.widgets */
this.globalWidgets = true;
this.font = "'open sans'";
this.fontSize = 14;
this.fontWeight = "normal";
this.context = new(window.AudioContext || window.webkitAudioContext)()
this.sys = navigator.userAgent.toLowerCase();
this.isAndroid = this.sys.indexOf("android") > -1;
this.isMobile = this.sys.indexOf("mobile") > -1;
/** @property {integer} throttlePeriod Throttle time in ms (for nx.throttle). */
this.throttlePeriod = 20;
/* extra colors */
this.colors.borderhl = drawingUtils.shadeBlendConvert(-0.5,this.colors.border); // colors.border + [20% Darker] => colors.darkborder
this.colors.accenthl = drawingUtils.shadeBlendConvert(0.15,this.colors.accent);
}
util.inherits(manager, EventEmitter)
/**
@method add
Adds a NexusUI element to the webpage. This will create an HTML5 canvas and draw the interface on it.
@param {string} [type] NexusUI widget type (i.e. "dial").
@param {object} [settings] (Optional.) Extra settings for the new widget. This settings object may have any of the following properties: x (integer in px), y, w (width), h (height), name (widget's OSC name and canvas ID), parent (the ID of the element you wish to add the canvas into). If no settings are provided, the element will be at default size and appended to the body of the HTML document.
*/
manager.prototype.add = function(type, args) {
//args may have optional properties: x, y, w, h, name, parent
if(type) {
var canv = document.createElement("canvas");
canv.setAttribute('nx', type);
if (args) {
if (args.x || args.y) {
canv.style.position = "absolute";
}
if (args.x) {
canv.style.left = args.x + "px";
}
if (args.y) {
canv.style.top = args.y + "px";
}
if (args.w) {
canv.style.width = args.w;
if (typeof args.w != "string")
canv.width = args.w;
}
if (args.h) {
canv.style.height = args.h;
if (typeof args.h != "string")
canv.height = args.h;
}
if (args.parent) {
var parent;
if (typeof args.parent === "string") {
parent = document.getElementById(args.parent);
} else if (args.parent instanceof HTMLElement){
parent = args.parent;
} else if (args.parent instanceof jQuery){
parent = args.parent[0];
}
}
if (args.name) {
canv.id = args.name
}
}
if (!parent) {
var parent = document.body
}
parent.appendChild(canv);
return this.transform(canv);
}
}
/** @method transform
Transform an existing canvas into a NexusUI widget.
@param {string} [canvasID] The ID of the canvas to be transformed.
@param {string} [type] (Optional.) Specify which type of widget the canvas will become. If no type is given, the canvas must have an nx attribute with a valid widget type.
*/
manager.prototype.transform = function(canvas, type) {
for (var key in nx.widgets) {
if (nx.widgets[key].canvasID == canvas.id) {
return;
}
}
if (type) {
var nxType = type;
} else {
var nxType = canvas.getAttribute("nx");
}
if (!nxType) {
return;
}
var elemCount = 0;
var newObj;
/* find out how many of the same elem type have come before
i.e. nx.elemTypeArr will look like [ dial, dial, toggle, toggle ]
allowing you to count how many dials already exist on the page
and give your new dial the appropriate index and id: dial3 */
for (j=0;j<this.elemTypeArr.length;j++) {
if (this.elemTypeArr[j] === nxType) {
elemCount++;
}
}
// add your new nexus element type to the element list
this.elemTypeArr.push(nxType);
// check to see if it has a pre-given ID
// and use that as its id if so
if (!canvas.id) {
var idNum = elemCount + 1;
canvas.id = nxType + idNum;
}
if(nxType) {
try {
var newObj = new (require('../widgets')[nxType])(canvas.id);
} catch (err) {
console.log("creation of " + nxType + " failed");
return;
}
}
newObj.type = nxType;
this.widgets[newObj.canvasID] = newObj;
if (this.globalWidgets) {
window[newObj.canvasID] = this.widgets[newObj.canvasID]
}
newObj.init();
return newObj;
}
/** @method transmit
The "output" instructions for sending a widget's data to another application or to a JS callback. Inherited by each widget and executed when each widget is interacted with or its value changes. Set using nx.sendsTo() to ensure that all widgets inherit the new function correctly.
@param {object} [data] The data to be transmitted. Each property of the object will become its own OSC message. (This works with objects nested to up to 2 levels).
*/
manager.prototype.transmit = function(data, passive) {
//console.log(passive + " manager.transmit")
this.makeOSC(this.emit, data, passive);
this.emit('*',data, passive);
}
/**
@method colorize
@param {string} [aspect] Which part of ui to change, i.e. "accent" "fill", "border"
@param {string} [color] Hex or rgb color code
Change the color of all nexus objects, by aspect ([fill, accent, border, accentborder]
```js
nx.colorize("#00ff00") // changes the accent color by default
nx.colorize("border", "#000000") // changes the border color
```
**/
manager.prototype.colorize = function(aspect, newCol) {
if (!newCol) {
// just sending in a color value colorizes the accent
newCol = aspect;
aspect = "accent";
}
this.colors[aspect] = newCol;
this.colors.borderhl = drawingUtils.shadeBlendConvert(0.1,this.colors.border,this.colors.black); // colors.border + [20% Darker] => colors.darkborder
this.colors.accenthl = drawingUtils.shadeBlendConvert(0.3,this.colors.accent);
for (var key in this.widgets) {
this.widgets[key].colors[aspect] = newCol;
this.widgets[key].colors["borderhl"] = this.colors.borderhl;
this.widgets[key].colors["accenthl"] = this.colors.accenthl;
this.widgets[key].draw();
}
}
/** @method setThrottlePeriod
Set throttle time of nx.throttle, which controls rapid network transmissions of widget data.
@param {integer} [throttle time] Throttle time in milliseconds.
*/
manager.prototype.setThrottlePeriod = function(newThrottle) {
this.throttlePeriod = newThrottle;
for (var key in this.widgets) {
this.widgets[key].throttlePeriod = this.throttlePeriod;
}
}
/*
* GUI
*/
/** @property {object} colors The interface's color settings. Set with nx.colorize(). */
manager.prototype.colors = {
"accent": "#ff5500",
"fill": "#eeeeee",
"border": "#e3e3e3",
"mid": "#1af",
"black": "#000000",
"white": "#FFFFFF"
};
/** @method startPulse
Start an animation interval for animated widgets (calls nx.pulse() every 30 ms). Executed by default when NexusUI loads.
*/
manager.prototype.startPulse = function() {
this.pulseInt = setInterval("nx.pulse()", 30);
}
/** @method stopPulse
Stop the animation pulse interval.
*/
manager.prototype.stopPulse = function() {
clearInterval(this.pulseInt);
}
/** @method pulse
Animation pulse which executes all functions stored in the nx.aniItems array.
*/
manager.prototype.pulse = function() {
for (var i=0;i<this.aniItems.length;i++) {
this.aniItems[i]();
}
}
manager.prototype.addAni = function(fn) {
}
manager.prototype.removeAni = function(fn) {
this.aniItems.splice(this.aniItems.indexOf(fn));
}
manager.prototype.addStylesheet = function() {
var htmlstr = '<style>'
+ 'select {'
+ 'width: 150px;'
+ 'padding: 5px 5px;'
+ 'font-size: 16px;'
+ 'color:#666666;'
+ 'border: solid 2px #e4e4e4;'
+ 'border-radius: 0;'
+ '-webkit-appearance: none;'
//+ 'border: 0;'
+ 'outline: none;'
// + 'cursor:pointer;'
+ 'background-color:#EEE;'
+ 'font-family:"open sans";'
+ '}'
+ ''
+ 'input[type=text]::-moz-selection { background: transparent; }'
+ 'input[type=text]::selection { background: transparent; }'
+ 'input[type=text]::-webkit-selection { background: transparent; }'
+ ''
+ 'canvas { '
// + 'cursor:pointer;'
+ 'border-radius:0px;'
+ 'moz-border-radius:0px;'
+ 'webkit-border-radius:0px;'
+ 'box-sizing:border-box;'
+ '-moz-box-sizing:border-box;'
+ '-webkit-box-sizing:border-box;'
+ '}'
+ ''
+ 'input[type=text] { '
// + 'cursor:pointer;'
+ 'border-radius:5px;'
+ 'moz-border-radius:5px;'
+ 'webkit-border-radius:5px;'
+ 'box-sizing:border-box;'
+ '-moz-box-sizing:border-box;'
+ '-webkit-box-sizing:border-box;'
+ '}'
+ '</style>';
document.head.innerHTML = document.head.innerHTML + htmlstr
}
/** @method setViewport
Set mobile viewport scale (similar to a zoom)
@param {integer} [scale] Zoom ratio (i.e. 0.5, 1, 2) */
manager.prototype.setViewport = function(scale) {
for (i=0; i<this.metas.length; i++) {
if (this.metas[i].name == "viewport") {
this.metas[i].content = "minimum-scale="+scale+", maximum-scale="+scale;
}
}
}
/* @method setLabels
Tell all widgets whether or not draw text labels on widgets
@param {boolean} [on/off] true to add labels, false to remove labels
*/
manager.prototype.setLabels = function(onoff) {
if (onoff=="on") {
this.showLabels = true;
} else {
this.showLabels = false;
}
for (var key in this.widgets) {
this.widgets[key].draw()
}
}
manager.prototype.setProp = function(prop,val) {
if (prop && val) {
nx[prop] = val;
for (var key in this.widgets) {
this.widgets[key][prop] = val;
this.widgets[key].draw()
}
}
}
manager.prototype.blockMove = function(e) {
if (e.target.attributes["nx"]) {
e.preventDefault();
if (this.isAndroid) {
e.stopPropagation ? e.stopPropagation() : false;
}
}
}
manager.prototype.calculateDigits = function(value) {
var nondecimals = this.max ? Math.floor(this.max).toString().length : 1
if (nondecimals < this.maxdigits) {
var decimals = 3-nondecimals
} else {
var decimals = 0
}
var valdigits = nondecimals + decimals
return {
wholes: nondecimals,
decimals: decimals,
total: nondecimals + decimals,
}
}
manager.prototype.themes = {
"light": {
"fill": "#DDDDDD",
"border": "#DADADA",
"black": "#000000",
"white": "#FFFFFF",
"body": "#F3F3F3"
},
"dark": {
"fill": "#222",
"border": "#292929",
"black": "#FFFFFF",
"white": "#000000",
"body": "#111"
},
"red": "#f24",
"orange": "#f50",
"yellow": "#ec1",
"green": "#1c9",
"blue": "#09d",
"purple": "#40a",
}
manager.prototype.skin = function(name) {
var names = name.split("-")
nx.colorize("fill", nx.themes[names[0]].fill)
nx.colorize("border", nx.themes[names[0]].border)
nx.colorize("black", nx.themes[names[0]].black)
nx.colorize("white", nx.themes[names[0]].white)
nx.colorize("accent", nx.themes[names[1]])
document.body.style.backgroundColor = nx.themes[names[0]].body
}
manager.prototype.labelSize = function(size) {
for (var key in this.widgets) {
var widget = this.widgets[key]
if (widget.label) {
var newheight = widget.GUI.h + size
widget.labelSize = size
if (["select","number","text"].indexOf(widget.type)<0) {
widget.resize(false,newheight)
}
}
}
var textLabels = document.querySelectorAll(".nxlabel");
console.log(textLabels)
for (var i = 0; i < textLabels.length; i++) {
console.log(textLabels[i])
textLabels[i].style.fontSize = size/2.8+"px"
console.log(textLabels[i].style.fontSize)
}
}
},{"../utils/drawing":5,"../utils/timing":7,"../utils/transmit":8,"../widgets":18,"events":47,"util":51}],3:[function(require,module,exports){
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var domUtils = require('../utils/dom');
var drawingUtils = require('../utils/drawing');
var timingUtils = require('../utils/timing');
var transmit = require('../utils/transmit');
var widget = module.exports = function (target) {
EventEmitter.apply(this)
this.preClick = this.preClick.bind(this)
this.preMove = this.preMove.bind(this)
this.preRelease = this.preRelease.bind(this)
this.preTouch = this.preTouch.bind(this)
this.preTouchMove = this.preTouchMove.bind(this)
this.preTouchRelease = this.preTouchRelease.bind(this)
/**
@class widget
All NexusUI interface widgets inherit from the widget class. The properties and methods of the widget class are usable by any NexusUI interface.
*/
/** @property {string} canvasID ID attribute of the interface's HTML5 canvas */
this.canvasID = target;
/** @property {string} oscPath OSC prefix for this interface. By default this is populated using the canvas ID (i.e. an ID of dial1 has OSC path /dial1) */
this.oscPath = "/"+target;
if (!document.getElementById(target)) {
var newcanv = document.createElement("canvas")
newcanv.id = target;
document.body.appendChild(newcanv)
}
/**
* @property {string} type The type of NexusUI widget (i.e. "dial", "toggle", "slider"). Set automatically at creation.
*/
this.type = undefined;
/** @property {DOM element} canvas The widget's HTML5 canvas */
this.canvas = document.getElementById(target);
/** @property {HTML5 drawing context} context The canvas's drawing context */
this.context = this.canvas.getContext("2d");
this.checkPercentage();
this.canvas.className = this.canvas.className ? this.canvas.className += " nx" : "nx"
this.canvas.height = window.getComputedStyle(document.getElementById(target), null).getPropertyValue("height").replace("px","");
this.canvas.width = window.getComputedStyle(document.getElementById(target), null).getPropertyValue("width").replace("px","");
/** @property {integer} height The widget canvas's computed height in pixels */
this.height = parseInt(window.getComputedStyle(document.getElementById(target), null).getPropertyValue("height").replace("px",""));
/** @property {integer} width The widget canvas's computed width in pixels */
this.width = parseInt(window.getComputedStyle(document.getElementById(target), null).getPropertyValue("width").replace("px",""));
if (!this.defaultSize) {
/** @property {object} defaultSize The widget's default size if not defined with HTML/CSS style. (Has properties 'width' and 'height', both in pixels) */
this.defaultSize = { width: 100, height: 100 };
}
/** @property {boolean} label Whether or not to draw a text label this widget. */
this.label = false
this.labelSize = 30
this.labelAlign = "center"
this.labelFont = "'Open Sans'"
if (this.canvas.getAttribute("label")!=null) {
this.label = this.canvas.getAttribute("label")
this.origDefaultHeight = this.defaultSize.height
}
if (this.label) {
this.defaultSize.height += this.labelSize
}
if (this.width==300 && this.height==150) {
this.canvas.width = this.defaultSize.width*2;
this.canvas.height = this.defaultSize.height*2;
this.width = this.defaultSize.width;
this.height = this.defaultSize.height;
} else {
var proxyw = this.width;
var proxyh = this.height;
this.canvas.width = proxyw*2;
this.canvas.height = proxyh*2;
this.width = proxyw;
this.height = proxyh;
}
this.canvas.style.width = this.canvas.width/2+"px";
this.canvas.style.height = this.canvas.height/2+"px";
this.context.scale(2,2)
this.makeRoomForLabel()
/** @property {object} offset The widget's computed offset from the top left of the document. (Has properties 'top' and 'left', both in pixels) */
this.offset = domUtils.findPosition(this.canvas);
/** @property {object} center The center of the widget's canvas. A 100x100 widget would have a center at 50x50. (Has properties 'x' and 'y', both in pixels) */
this.center = {
x: this.GUI.w/2,
y: this.GUI.h/2
};
//drawing
/** @property {integer} lineWidth The default line width for drawing (default is 2 pixels). In many widgets, this is overwritten to suite the widget. However it does dictate the border width on most widgets. */
this.lineWidth = 2;
this.context.lineWidth = this.lineWidth;
/** @property {object} colors A widget's individual color scheme. Inherited from nx.colors. (Has properties "accent", "fill", "border", "black", and "white") */
this.colors = new Object();
// define colors individually so they are not pointers to nx.colors
// this way each object can have its own color scheme
for (var key in nx.colors) {
this.colors[key] = nx.colors[key]
}
/*this.colors.accent = nx.colors.accent;
this.colors.fill = nx.colors.fill;
this.colors.border = nx.colors.border;
this.colors.accentborder = nx.colors.accentborder;
this.colors.black = nx.colors.black;
this.colors.white = nx.colors.white;
this.colors.highlight = nx.colors.highlight; */
//interaction
/** @property {object} clickPos The most recent mouse/touch position when interating with a widget. (Has properties x and y) */
this.clickPos = {x: 0, y: 0};
/** @property {array} clickPos.touches If multitouch, an array of touch positions */
this.clickPos.touches = new Array();
/** @property {boolean} clicked Whether or not the widget is currently clicked */
this.clicked = false;
this.value = 0;
/**
@property {object} val An object containing the core interactive values of the widget, which are also the widget's data output.
*/
this.val = new Object();
this.pval = new Object();
this.nodePos = new Array();
/** @property {object} deltaMove Difference between the current touch/mouse position and the previous touch/mouse position, in pixels. */
this.deltaMove = new Object();
this.throttlePeriod = nx.throttlePeriod;
this.throttle = timingUtils.throttle;
this.hasMoved = false;
//recording
/** @property {boolean} isRecording Whether or not this widget's output is being recorded to a "remix" widget */
this.isRecording = false;
this.tapeNum = 0;
this.recorder = null;
//transmission
if (transmit) {
/** @method sendsTo
Set the transmission protocol for this widget individually
@param {string or function} [destination] Protocol for transmitting data from this widget (i.e. "js", "ajax", "ios", "max", or "node"). Also accepts custom functions.
```js
dial1.sendsTo("ajax")
// or
dial1.sendsTo(function(data) {
//define a custom transmission function
})
```
*/
this.sendsTo = transmit.setWidgetTransmit;
this.destination = "js";
}
this.events = new Object();
// Setup interaction
if (nx.isTouchDevice) {
this.canvas.ontouchstart = this.preTouch;
this.canvas.ontouchmove = this.preTouchMove;
this.canvas.ontouchend = this.preTouchRelease;
} else {
this.canvas.addEventListener('mousedown', this.preClick, false);
}
this.fontSize = nx.fontSize;
this.fontWeight = nx.fontWeight;
this.font = nx.font;
this.clickCB = false;
this.releaseCB = false;
this.actuated = true;
}
util.inherits(widget, EventEmitter)
/** @method transmit
The "output" instructions for sending the widget's data to another application or to a JS callback. Inherited from nx.transmit and executed when each widget is interacted with or during animation. Set using .sendsTo() to use our built-in transmission defintions.
@param {object} [data] The data to be transmitted. Each property of the object will become its own OSC message if sending via "ajax" or "max7" protocols. (This works with objects nested to up to 2 levels).
*/
widget.prototype.transmit = nx.transmit;
/** @method makeOSC
Loops through an object (i.e. a widget's data), creates OSC path/value pairs, and executes a callback function with these two arguments.
@param {function} [callback] A function defining the action to be taken with each OSC path/value pair. This function should have two parameters, path (string) and data (type depends on widget data type).
@param {object} [data] The data as an object, to be broken into individual OSC messages.
*/
widget.prototype.makeOSC = function(action, data) {
this.action = action;
if ((typeof data == "object") && (data !== null)) {
for (var key in data) {
if ((typeof data[key] == "object") && (data[key] !== null)) {
for (var key2 in data[key]) {
this.action(key+"/"+key2, data[key][key2])
}
} else {
this.action(key, data[key])
}
}
} else if (typeof data == "number" || typeof data == "string") {
this.action('value', data)
}
}
// getoffset is useful as an API for others
// otherwise they would have to write
// dial1.offset = utils.findPosition()
// now it is simply:
// dial1.getOffset()
/** @method getOffset
Recalculate the computed offset of the widget's canvas and store it in widget.offset. This is useful if a widget has been moved after being created.
*/
widget.prototype.getOffset = function() {
this.offset = domUtils.findPosition(this.canvas)
}
widget.prototype.preClick = function(e) {
this.actuated = true;
this.offset = domUtils.findPosition(this.canvas)
this.clickPos = domUtils.getCursorPosition(e, this.offset);
// need something like:
// if (this.clickPos.y < this.GUI.h) {
document.addEventListener("mousemove", this.preMove, false);
document.addEventListener("mouseup", this.preRelease, false);
this.clicked = true;
this.deltaMove.x = 0;
this.deltaMove.y = 0;
this.hasMoved = false;
this.clickCB ? this.clickCB() : null;
this.click(e);
document.body.style.userSelect = "none";
document.body.style.mozUserSelect = "none";
document.body.style.webkitUserSelect = "none";
document.body.style.cursor = "none"
}
widget.prototype.preMove = function(e) {
this.actuated = true;
var newClickPos = domUtils.getCursorPosition(e, this.offset);
this.deltaMove.y = newClickPos.y - this.clickPos.y;
this.deltaMove.x = newClickPos.x - this.clickPos.x;
this.clickPos = newClickPos;
this.hasMoved = true;
this.move(e);
}
widget.prototype.preRelease = function(e) {
this.actuated = true;
document.removeEventListener("mousemove", this.preMove, false);
document.removeEventListener("mouseup", this.preRelease, false);
this.clicked = false;
this.releaseCB ? this.releaseCB() : null;
this.release();
document.body.style.userSelect = "text";
document.body.style.mozUserSelect = "text";
document.body.style.webkitUserSelect = "text";
document.body.style.cursor = "pointer"
}
widget.prototype.preTouch = function(e) {
this.actuated = true;
this.clickPos = domUtils.getTouchPosition(e, this.offset);
this.clicked = true;
this.deltaMove.x = 0;
this.deltaMove.y = 0;
this.hasMoved = false;
this.touch(e);
}
widget.prototype.preTouchMove = function(e) {
if (this.clicked) {
this.actuated = true;
var newClickPos = domUtils.getTouchPosition(e, this.offset);
this.deltaMove.y = newClickPos.y - this.clickPos.y;
this.deltaMove.x = newClickPos.x - this.clickPos.x;
this.clickPos = newClickPos;
this.hasMoved = true;
this.touchMove(e);
}
}
widget.prototype.preTouchRelease = function(e) {
this.actuated = true;
if (e.targetTouches.length>=1) {
var newClickPos = domUtils.getTouchPosition(e, this.offset);
this.clickPos = newClickPos;
} else {
this.clicked = false;
}
this.touchRelease();
}
/** @method init
Initialize or re-initialize the widget. Defined separately within each widget.
*/
/** @method draw
Draw the widget onto the canvas.
*/
widget.prototype.draw = function() {
}
/** @method click
Executes when the widget is clicked on
*/
widget.prototype.click = function() {
}
/** @method move
Executes on drag (mouse moves while clicked).
*/
widget.prototype.move = function() {
}
/** @method release
Executes when the mouse releases after having clicked on the widget.
*/
widget.prototype.release = function() {
}
/** @method touch
Executes when the widget is touched on a touch device.
*/
widget.prototype.touch = function() {
this.click();
}
/** @method touchMove
Executes on drag (touch then move) on a touch device
*/
widget.prototype.touchMove = function() {
this.move();
}
/** @method touchRelease
Executes when the touch releases after having touched the widget.
*/
widget.prototype.touchRelease = function() {
this.release();
}
widget.prototype.adjustSizeIfDefault = function() {
if (this.width==300 && this.height==150) {
this.canvas.width = this.defaultSize.width;
this.canvas.height = this.defaultSize.height;
this.width = this.defaultSize.width;
this.height = this.defaultSize.height;
}
}
widget.prototype.makeRoundedBG = function() {
this.bgLeft = this.lineWidth;
this.bgRight = this.width - this.lineWidth;
this.bgTop = this.lineWidth;
this.bgBottom = this.height - this.lineWidth;
this.bgHeight = this.bgBottom - this.lineWidth;
this.bgWidth = this.bgRight - this.lineWidth;
drawingUtils.makeRoundRect(this.context, this.bgLeft, this.bgTop, this.bgWidth, this.bgHeight);
}
/** @method erase
Erase the widget's canvas.
*/
widget.prototype.erase = function() {
this.context.clearRect(0,0,this.width,this.height);
}
widget.prototype.hideCursor = function() {
this.canvas.style.cursor = "none";
}
widget.prototype.showCursor = function() {
this.canvas.style.cursor = "auto";
}
// allow us to get the constructor function name programatically
//i.e. if element is a dial, this function will return "dial"
//deprecated
widget.prototype.getName = function() {
return "deprecated -- use widget.type instead"
}
/** @method set
Manually set a widget's value (that is, set any properties of a widget's .val). See widget.val or the .val property of individual widgets for more info.
@param {object} [data] Parameter/value pairs in object notation.
@param {boolean} [transmit] (optional) Whether or not to transmit new value after being set.
Sets the value of an object.
```js
position1.set({
x: 100,
y: 250
})
```
An optional second argument decides whether the object then transmits its new value.
```js
button1.set({
press: 100
}, true)
```
*/
widget.prototype.set = function(data, transmit) {
this.actuated = false;
if (typeof this.val == "object" && this.val !== "null") {
if (typeof data == "object" && data !== "null") {
for (var key in data) {
this.val[key] = data[key];
}
}
} else if (typeof this.val == "string" || typeof this.val == "number") {
if (typeof data == "object" && data !== "null") {
this.val = data["value"];
this.draw();
} else if (typeof data == "string" || typeof data == "number") {
this.val = data;
}
}
this.draw();
if (transmit) {
this.transmit(this.val,true)
}
}
/** @method destroy
Remove the widget object, canvas, and all related event listeners from the document.
*/
widget.prototype.destroy = function() {
var type = nx.elemTypeArr.indexOf(this.getName())
nx.elemTypeArr.splice(type,1)
this.canvas.ontouchmove = null;
this.canvas.ontouchend = null;
this.canvas.onclick = null;
this.canvas.onmousemove = null;
this.canvas.onmouseoff = null;
document.removeEventListener("mousemove", this.preMove, false);
document.removeEventListener("mouseup", this.preRelease, false);
var elemToKill = document.getElementById(this.canvasID)
if (elemToKill) {
elemToKill.parentNode.removeChild(elemToKill);
}
this.customDestroy();
var id = this.canvasID
delete nx.widgets[id];
delete window[id];