PageSourceSearch

https://hypermovilidad.com/lib/knob/jquery.knob.js

js hypermovilidad.com collected 2026-09-24 14:45:00 UTC 25,946 bytes, 793 lines download raw bytes

1(function (factory) {
2    if (typeof exports === 'object') {
3        // CommonJS
4        module.exports = factory(require('jquery'));
5    } else if (typeof define === 'function' && define.amd) {
6        // AMD. Register as an anonymous module.
7        define(['jquery'], factory);
8    } else {
9        // Browser globals
10        factory(jQuery);
11    }
12}(function ($) {
13
14    /**
15     * Kontrol library
16     */
17    "use strict";
18
19    /**
20     * Definition of globals and core
21     */
22    var k = {}, // kontrol
23        max = Math.max,
24        min = Math.min;
25
26    k.c = {};
27    k.c.d = $(document);
28    k.c.t = function (e) {
29        return e.originalEvent.touches.length - 1;
30    };
31
32    /**
33     * Kontrol Object
34     *
35     * Definition of an abstract UI control
36     *
37     * Each concrete component must call this one.
38     * <code>
39     * k.o.call(this);
40     * </code>
41     */
42    k.o = function () {
43        var s = this;
44
45        this.o = null; // array of options
46        this.$ = null; // jQuery wrapped element
47        this.i = null; // mixed HTMLInputElement or array of HTMLInputElement
48        this.g = null; // deprecated 2D graphics context for 'pre-rendering'
49        this.v = null; // value ; mixed array or integer
50        this.cv = null; // change value ; not commited value
51        this.x = 0; // canvas x position
52        this.y = 0; // canvas y position
53        this.w = 0; // canvas width
54        this.h = 0; // canvas height
55        this.$c = null; // jQuery canvas element
56        this.c = null; // rendered canvas context
57        this.t = 0; // touches index
58        this.isInit = false;
59        this.fgColor = null; // main color
60        this.pColor = null; // previous color
61        this.dH = null; // draw hook
62        this.cH = null; // change hook
63        this.eH = null; // cancel hook
64        this.rH = null; // release hook
65        this.scale = 1; // scale factor
66        this.relative = false;
67        this.relativeWidth = false;
68        this.relativeHeight = false;
69        this.$div = null; // component div
70
71        this.run = function () {
72            var cf = function (e, conf) {
73                var k;
74                for (k in conf) {
75                    s.o[k] = conf[k];
76                }
77                s._carve().init();
78                s._configure()
79                 ._draw();
80            };
81
82            if (this.$.data('kontroled')) return;
83            this.$.data('kontroled', true);
84
85            this.extend();
86            this.o = $.extend({
87                    // Config
88                    min: this.$.data('min') !== undefined ? this.$.data('min') : 0,
89                    max: this.$.data('max') !== undefined ? this.$.data('max') : 999999,
90                    stopper: true,
91                    readOnly: this.$.data('readonly') || (this.$.attr('readonly') === 'readonly'),
92
93                    // UI
94                    cursor: this.$.data('cursor') === true && 30
95                            || this.$.data('cursor') || 0,
96                    thickness: this.$.data('thickness')
97                               && Math.max(Math.min(this.$.data('thickness'), 1), 0.01)
98                               || 0.35,
99                    lineCap: this.$.data('linecap') || 'butt',
100                    width: this.$.data('width') || 200,
101                    height: this.$.data('height') || 200,
102                    displayInput: this.$.data('displayinput') == null || this.$.data('displayinput'),
103                    displayPrevious: this.$.data('displayprevious'),
104                    fgColor: this.$.data('fgcolor') || '#ECC331 ',
105                    inputColor: this.$.data('inputcolor'),
106                    font: this.$.data('font') || 'Arial',
107                    fontWeight: this.$.data('font-weight') || 'bold',
108                    inline: false,
109                    step: this.$.data('step') || 1,
110                    rotation: this.$.data('rotation'),
111
112                    // Hooks
113                    draw: null, // function () {}
114                    change: null, // function (value) {}
115                    cancel: null, // function () {}
116                    release: null, // function (value) {}
117
118                    // Output formatting, allows to add unit: %, ms ...
119                    format: function(v) {
120                        return v;
121                    },
122                    parse: function (v) {
123                        return parseFloat(v);
124                    }
125                }, this.o
126            );
127
128            // finalize options
129            this.o.flip = this.o.rotation === 'anticlockwise' || this.o.rotation === 'acw';
130            if (!this.o.inputColor) {
131                this.o.inputColor = this.o.fgColor;
132            }
133
134            // routing value
135            if (this.$.is('fieldset')) {
136
137                // fieldset = array of integer
138                this.v = {};
139                this.i = this.$.find('input');
140                this.i.each(function(k) {
141                    var $this = $(this);
142                    s.i[k] = $this;
143                    s.v[k] = s.o.parse($this.val());
144
145                    $this.bind(
146                        'change blur',
147                        function () {
148                            var val = {};
149                            val[k] = $this.val();
150                            s.val(s._validate(val));
151                        }
152                    );
153                });
154                this.$.find('legend').remove();
155            } else {
156
157                // input = integer
158                this.i = this.$;
159                this.v = this.o.parse(this.$.val());
160                this.v === '' && (this.v = this.o.min);
161                this.$.bind(
162                    'change blur',
163                    function () {
164                        s.val(s._validate(s.o.parse(s.$.val())));
165                    }
166                );
167
168            }
169
170            !this.o.displayInput && this.$.hide();
171
172            // adds needed DOM elements (canvas, div)
173            this.$c = $(document.createElement('canvas')).attr({
174                width: this.o.width,
175                height: this.o.height
176            });
177
178            // wraps all elements in a div
179            // add to DOM before Canvas init is triggered
180            this.$div = $('<div style="'
181                + (this.o.inline ? 'display:inline;' : '')
182                + 'width:' + this.o.width + 'px;height:' + this.o.height + 'px;'
183                + '"></div>');
184
185            this.$.wrap(this.$div).before(this.$c);
186            this.$div = this.$.parent();
187
188            if (typeof G_vmlCanvasManager !== 'undefined') {
189                G_vmlCanvasManager.initElement(this.$c[0]);
190            }
191
192            this.c = this.$c[0].getContext ? this.$c[0].getContext('2d') : null;
193
194            if (!this.c) {
195                throw {
196                    name:        "CanvasNotSupportedException",
197                    message:     "Canvas not supported. Please use excanvas on IE8.0.",
198                    toString:    function(){return this.name + ": " + this.message}
199                }
200            }
201
202            // hdpi support
203            this.scale = (window.devicePixelRatio || 1) / (
204                            this.c.webkitBackingStorePixelRatio ||
205                            this.c.mozBackingStorePixelRatio ||
206                            this.c.msBackingStorePixelRatio ||
207                            this.c.oBackingStorePixelRatio ||
208                            this.c.backingStorePixelRatio || 1
209                         );
210
211            // detects relative width / height
212            this.relativeWidth =  this.o.width % 1 !== 0
213                                  && this.o.width.indexOf('%');
214            this.relativeHeight = this.o.height % 1 !== 0
215                                  && this.o.height.indexOf('%');
216            this.relative = this.relativeWidth || this.relativeHeight;
217
218            // computes size and carves the component
219            this._carve();
220
221            // prepares props for transaction
222            if (this.v instanceof Object) {
223                this.cv = {};
224                this.copy(this.v, this.cv);
225            } else {
226                this.cv = this.v;
227            }
228
229            // binds configure event
230            this.$
231                .bind("configure", cf)
232                .parent()
233                .bind("configure", cf);
234
235            // finalize init
236            this._listen()
237                ._configure()
238                ._xy()
239                .init();
240
241            this.isInit = true;
242
243            this.$.val(this.o.format(this.v));
244            this._draw();
245
246            return this;
247        };
248
249        this._carve = function() {
250            if (this.relative) {
251                var w = this.relativeWidth ?
252                        this.$div.parent().width() *
253                        parseInt(this.o.width) / 100
254                        : this.$div.parent().width(),
255                    h = this.relativeHeight ?
256                        this.$div.parent().height() *
257                        parseInt(this.o.height) / 100
258                        : this.$div.parent().height();
259
260                // apply relative
261                this.w = this.h = Math.min(w, h);
262            } else {
263                this.w = this.o.width;
264                this.h = this.o.height;
265            }
266
267            // finalize div
268            this.$div.css({
269                'width': this.w + 'px',
270                'height': this.h + 'px'
271            });
272
273            // finalize canvas with computed width
274            this.$c.attr({
275                width: this.w,
276                height: this.h
277            });
278
279            // scaling
280            if (this.scale !== 1) {
281                this.$c[0].width = this.$c[0].width * this.scale;
282                this.$c[0].height = this.$c[0].height * this.scale;
283                this.$c.width(this.w);
284                this.$c.height(this.h);
285            }
286
287            return this;
288        };
289
290        this._draw = function () {
291
292            // canvas pre-rendering
293            var d = true;
294
295            s.g = s.c;
296
297            s.clear();
298
299            s.dH && (d = s.dH());
300
301            d !== false && s.draw();
302        };
303
304        this._touch = function (e) {
305            var touchMove = function (e) {
306                var v = s.xy2val(
307                            e.originalEvent.touches[s.t].pageX,
308                            e.originalEvent.touches[s.t].pageY
309                        );
310
311                if (v == s.cv) return;
312
313                if (s.cH && s.cH(v) === false) return;
314
315                s.change(s._validate(v));
316                s._draw();
317            };
318
319            // get touches index
320            this.t = k.c.t(e);
321
322            // First touch
323            touchMove(e);
324
325            // Touch events listeners
326            k.c.d
327                .bind("touchmove.k", touchMove)
328                .bind(
329                    "touchend.k",
330                    function () {
331                        k.c.d.unbind('touchmove.k touchend.k');
332                        s.val(s.cv);
333                    }
334                );
335
336            return this;
337        };
338
339        this._mouse = function (e) {
340            var mouseMove = function (e) {
341                var v = s.xy2val(e.pageX, e.pageY);
342
343                if (v == s.cv) return;
344
345                if (s.cH && (s.cH(v) === false)) return;
346
347                s.change(s._validate(v));
348                s._draw();
349            };
350
351            // First click
352            mouseMove(e);
353
354            // Mouse events listeners
355            k.c.d
356                .bind("mousemove.k", mouseMove)
357                .bind(
358                    // Escape key cancel current change
359                    "keyup.k",
360                    function (e) {
361                        if (e.keyCode === 27) {
362                            k.c.d.unbind("mouseup.k mousemove.k keyup.k");
363
364                            if (s.eH && s.eH() === false)
365                                return;
366
367                            s.cancel();
368                        }
369                    }
370                )
371                .bind(
372                    "mouseup.k",
373                    function (e) {
374                        k.c.d.unbind('mousemove.k mouseup.k keyup.k');
375                        s.val(s.cv);
376                    }
377                );
378
379            return this;
380        };
381
382        this._xy = function () {
383            var o = this.$c.offset();
384            this.x = o.left;
385            this.y = o.top;
386
387            return this;
388        };
389
390        this._listen = function () {
391            if (!this.o.readOnly) {
392                this.$c
393                    .bind(
394                        "mousedown",
395                        function (e) {
396                            e.preventDefault();
397                            s._xy()._mouse(e);
398                        }
399                    )
400                    .bind(
401                        "touchstart",
402                        function (e) {
403                            e.preventDefault();
404                            s._xy()._touch(e);
405                        }
406                    );
407
408                this.listen();
409            } else {
410                this.$.attr('readonly', 'readonly');
411            }
412
413            if (this.relative) {
414                $(window).resize(function() {
415                    s._carve().init();
416                    s._draw();
417                });
418            }
419
420            return this;
421        };
422
423        this._configure = function () {
424
425            // Hooks
426            if (this.o.draw) this.dH = this.o.draw;
427            if (this.o.change) this.cH = this.o.change;
428            if (this.o.cancel) this.eH = this.o.cancel;
429            if (this.o.release) this.rH = this.o.release;
430
431            if (this.o.displayPrevious) {
432                this.pColor = this.h2rgba(this.o.fgColor, "0.4");
433                this.fgColor = this.h2rgba(this.o.fgColor, "0.6");
434            } else {
435                this.fgColor = this.o.fgColor;
436            }
437
438            return this;
439        };
440
441        this._clear = function () {
442            this.$c[0].width = this.$c[0].width;
443        };
444
445        this._validate = function (v) {
446            var val = (~~ (((v < 0) ? -0.5 : 0.5) + (v/this.o.step))) * this.o.step;
447            return Math.round(val * 100) / 100;
448        };
449
450        // Abstract methods
451        this.listen = function () {}; // on start, one time
452        this.extend = function () {}; // each time configure triggered
453        this.init = function () {}; // each time configure triggered
454        this.change = function (v) {}; // on change
455        this.val = function (v) {}; // on release
456        this.xy2val = function (x, y) {}; //
457        this.draw = function () {}; // on change / on release
458        this.clear = function () { this._clear(); };
459
460        // Utils
461        this.h2rgba = function (h, a) {
462            var rgb;
463            h = h.substring(1,7);
464            rgb = [
465                parseInt(h.substring(0,2), 16),
466                parseInt(h.substring(2,4), 16),
467                parseInt(h.substring(4,6), 16)
468            ];
469
470            return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + a + ")";
471        };
472
473        this.copy = function (f, t) {
474            for (var i in f) {
475                t[i] = f[i];
476            }
477        };
478    };
479
480
481    /**
482     * k.Dial
483     */
484    k.Dial = function () {
485        k.o.call(this);
486
487        this.startAngle = null;
488        this.xy = null;
489        this.radius = null;
490        this.lineWidth = null;
491        this.cursorExt = null;
492        this.w2 = null;
493        this.PI2 = 2*Math.PI;
494
495        this.extend = function () {
496            this.o = $.extend({
497                bgColor: this.$.data('bgcolor') || '#EEEEEE',
498                angleOffset: this.$.data('angleoffset') || 0,
499                angleArc: this.$.data('anglearc') || 360,
500                inline: true
501            }, this.o);
502        };
503
504        this.val = function (v, triggerRelease) {
505            if (null != v) {
506
507                // reverse format
508                v = this.o.parse(v);
509
510                if (triggerRelease !== false
511                    && v != this.v
512                    && this.rH
513                    && this.rH(v) === false) { return; }
514
515                this.cv = this.o.stopper ? max(min(v, this.o.max), this.o.min) : v;
516                this.v = this.cv;
517                this.$.val(this.o.format(this.v));
518                this._draw();
519            } else {
520                return this.v;
521            }
522        };
523
524        this.xy2val = function (x, y) {
525            var a, ret;
526
527            a = Math.atan2(
528                        x - (this.x + this.w2),
529                        - (y - this.y - this.w2)
530                    ) - this.angleOffset;
531
532            if (this.o.flip) {
533                a = this.angleArc - a - this.PI2;
534            }
535
536            if (this.angleArc != this.PI2 && (a < 0) && (a > -0.5)) {
537
538                // if isset angleArc option, set to min if .5 under min
539                a = 0;
540            } else if (a < 0) {
541                a += this.PI2;
542            }
543
544            ret = (a * (this.o.max - this.o.min) / this.angleArc) + this.o.min;
545
546            this.o.stopper && (ret = max(min(ret, this.o.max), this.o.min));
547
548            return ret;
549        };
550
551        this.listen = function () {
552
553            // bind MouseWheel
554            var s = this, mwTimerStop,
555                mwTimerRelease,
556                mw = function (e) {
557                    e.preventDefault();
558
559                    var ori = e.originalEvent,
560                        deltaX = ori.detail || ori.wheelDeltaX,
561                        deltaY = ori.detail || ori.wheelDeltaY,
562                        v = s._validate(s.o.parse(s.$.val()))
563                            + (
564                                deltaX > 0 || deltaY > 0
565                                ? s.o.step
566                                : deltaX < 0 || deltaY < 0 ? -s.o.step : 0
567                              );
568
569                    v = max(min(v, s.o.max), s.o.min);
570
571                    s.val(v, false);
572
573                    if (s.rH) {
574                        // Handle mousewheel stop
575                        clearTimeout(mwTimerStop);
576                        mwTimerStop = setTimeout(function () {
577                            s.rH(v);
578                            mwTimerStop = null;
579                        }, 100);
580
581                        // Handle mousewheel releases
582                        if (!mwTimerRelease) {
583                            mwTimerRelease = setTimeout(function () {
584                                if (mwTimerStop)
585                                    s.rH(v);
586                                mwTimerRelease = null;
587                            }, 200);
588                        }
589                    }
590                },
591                kval,
592                to,
593                m = 1,
594                kv = {
595                    37: -s.o.step,
596                    38: s.o.step,
597                    39: s.o.step,
598                    40: -s.o.step
599                };
600
601            this.$
602                .bind(
603                    "keydown",
604                    function (e) {
605                        var kc = e.keyCode;
606
607                        // numpad support
608                        if (kc >= 96 && kc <= 105) {
609                            kc = e.keyCode = kc - 48;
610                        }
611
612                        kval = parseInt(String.fromCharCode(kc));
613
614                        if (isNaN(kval)) {
615                            (kc !== 13)                     // enter
616                            && kc !== 8                     // bs
617                            && kc !== 9                     // tab
618                            && kc !== 189                   // -
619                            && (kc !== 190
620                                || s.$.val().match(/\./))   // . allowed once
621                            && e.preventDefault();
622
623                            // arrows
624                            if ($.inArray(kc,[37,38,39,40]) > -1) {
625                                e.preventDefault();
626
627                                var v = s.o.parse(s.$.val()) + kv[kc] * m;
628                                s.o.stopper && (v = max(min(v, s.o.max), s.o.min));
629
630                                s.change(s._validate(v));
631                                s._draw();
632
633                                // long time keydown speed-up
634                                to = window.setTimeout(function () {
635                                    m *= 2;
636                                }, 30);
637                            }
638                        }
639                    }
640                )
641                .bind(
642                    "keyup",
643                    function (e) {
644                        if (isNaN(kval)) {
645                            if (to) {
646                                window.clearTimeout(to);
647                                to = null;
648                                m = 1;
649                                s.val(s.$.val());
650                            }
651                        } else {
652                            // kval postcond
653                            (s.$.val() >
653 s.o.max && s.$.val(s.o.max))
654                            || (s.$.val() < s.o.min && s.$.val(s.o.min));
655                        }
656                    }
657                );
658
659            this.$c.bind("mousewheel DOMMouseScroll", mw);
660            this.$.bind("mousewheel DOMMouseScroll", mw);
661        };
662
663        this.init = function () {
664            if (this.v < this.o.min
665                || this.v > this.o.max) { this.v = this.o.min; }
666
667            this.$.val(this.v);
668            this.w2 = this.w / 2;
669            this.cursorExt = this.o.cursor / 100;
670            this.xy = this.w2 * this.scale;
671            this.lineWidth = this.xy * this.o.thickness;
672            this.lineCap = this.o.lineCap;
673            this.radius = this.xy - this.lineWidth / 2;
674
675            this.o.angleOffset
676            && (this.o.angleOffset = isNaN(this.o.angleOffset) ? 0 : this.o.angleOffset);
677
678            this.o.angleArc
679            && (this.o.angleArc = isNaN(this.o.angleArc) ? this.PI2 : this.o.angleArc);
680
681            // deg to rad
682            this.angleOffset = this.o.angleOffset * Math.PI / 180;
683            this.angleArc = this.o.angleArc * Math.PI / 180;
684
685            // compute start and end angles
686            this.startAngle = 1.5 * Math.PI + this.angleOffset;
687            this.endAngle = 1.5 * Math.PI + this.angleOffset + this.angleArc;
688
689            var s = max(
690                String(Math.abs(this.o.max)).length,
691                String(Math.abs(this.o.min)).length,
692                2
693            ) + 2;
694
695            this.o.displayInput
696                && this.i.css({
697                        'width' : ((this.w / 2 + 4) >> 0) + 'px',
698                        'height' : ((this.w / 3) >> 0) + 'px',
699                        'position' : 'absolute',
700                        'vertical-align' : 'middle',
701                        'margin-top' : ((this.w / 3) >> 0) + 'px',
702                        'margin-left' : '-' + ((this.w * 3 / 4 + 2) >> 0) + 'px',
703                        'border' : 0,
704                        'background' : 'none',
705                        'font' : this.o.fontWeight + ' ' + ((this.w / s) >> 0) + 'px ' + this.o.font,
706                        'text-align' : 'center',
707                        'color' : this.o.inputColor || this.o.fgColor,
708                        'padding' : '0px',
709                        '-webkit-appearance': 'none'
710                        }) || this.i.css({
711                            'width': '0px',
712                            'visibility': 'hidden'
713                        });
714        };
715
716        this.change = function (v) {
717            this.cv = v;
718            this.$.val(this.o.format(v));
719        };
720
721        this.angle = function (v) {
722            return (v - this.o.min) * this.angleArc / (this.o.max - this.o.min);
723        };
724
725        this.arc = function (v) {
726          var sa, ea;
727          v = this.angle(v);
728          if (this.o.flip) {
729              sa = this.endAngle + 0.00001;
730              ea = sa - v - 0.00001;
731          } else {
732              sa = this.startAngle - 0.00001;
733              ea = sa + v + 0.00001;
734          }
735          this.o.cursor
736              && (sa = ea - this.cursorExt)
737              && (ea = ea + this.cursorExt);
738
739          return {
740              s: sa,
741              e: ea,
742              d: this.o.flip && !this.o.cursor
743          };
744        };
745
746        this.draw = function () {
747            var c = this.g,                 // context
748                a = this.arc(this.cv),      // Arc
749                pa,                         // Previous arc
750                r = 1;
751
752            c.lineWidth = this.lineWidth;
753            c.lineCap = this.lineCap;
754
755            if (this.o.bgColor !== "none") {
756                c.beginPath();
757                    c.strokeStyle = this.o.bgColor;
758                    c.arc(this.xy, this.xy, this.radius, this.endAngle - 0.00001, this.startAngle + 0.00001, true);
759                c.stroke();
760            }
761
762            if (this.o.displayPrevious) {
763                pa = this.arc(this.v);
764                c.beginPath();
765                c.strokeStyle = this.pColor;
766                c.arc(this.xy, this.xy, this.radius, pa.s, pa.e, pa.d);
767                c.stroke();
768                r = this.cv == this.v;
769            }
770
771            c.beginPath();
772            c.strokeStyle = r ? this.o.fgColor : this.fgColor ;
773            c.arc(this.xy, this.xy, this.radius, a.s, a.e, a.d);
774            c.stroke();
775        };
776
777        this.cancel = function () {
778            this.val(this.v);
779        };
780    };
781
782    $.fn.dial = $.fn.knob = function (o) {
783        return this.each(
784            function () {
785                var d = new k.Dial();
786                d.o = o;
787                d.$ = $(this);
788                d.run();
789            }
790        ).parent();
791    };
792
793}));

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.