-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwavesurfer.js
6248 lines (5263 loc) · 195 KB
/
wavesurfer.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
/*!
* wavesurfer.js 4.1.1 (2020-09-25)
* https://wavesurfer-js.org
* @license BSD-3-Clause
*/
(function webpackUniversalModuleDefinition(root, factory) {
if(typeof exports === 'object' && typeof module === 'object')
module.exports = factory();
else if(typeof define === 'function' && define.amd)
define("WaveSurfer", [], factory);
else if(typeof exports === 'object')
exports["WaveSurfer"] = factory();
else
root["WaveSurfer"] = factory();
})(this, function() {
return /******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
/******/
/******/ // define __esModule on exports
/******/ __webpack_require__.r = function(exports) {
/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
/******/ }
/******/ Object.defineProperty(exports, '__esModule', { value: true });
/******/ };
/******/
/******/ // create a fake namespace object
/******/ // mode & 1: value is a module id, require it
/******/ // mode & 2: merge all properties of value into the ns
/******/ // mode & 4: return value when already ns object
/******/ // mode & 8|1: behave like require
/******/ __webpack_require__.t = function(value, mode) {
/******/ if(mode & 1) value = __webpack_require__(value);
/******/ if(mode & 8) return value;
/******/ if((mode & 4) && typeof value === 'object' && value && value.__esModule) return value;
/******/ var ns = Object.create(null);
/******/ __webpack_require__.r(ns);
/******/ Object.defineProperty(ns, 'default', { enumerable: true, value: value });
/******/ if(mode & 2 && typeof value != 'string') for(var key in value) __webpack_require__.d(ns, key, function(key) { return value[key]; }.bind(null, key));
/******/ return ns;
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = "./src/wavesurfer.js");
/******/ })
/************************************************************************/
/******/ ({
/***/ "./node_modules/debounce/index.js":
/*!****************************************!*\
!*** ./node_modules/debounce/index.js ***!
\****************************************/
/*! no static exports found */
/***/ (function(module, exports) {
/**
* Returns a function, that, as long as it continues to be invoked, will not
* be triggered. The function will be called after it stops being called for
* N milliseconds. If `immediate` is passed, trigger the function on the
* leading edge, instead of the trailing. The function also has a property 'clear'
* that is a function which will clear the timer to prevent previously scheduled executions.
*
* @source underscore.js
* @see http://unscriptable.com/2009/03/20/debouncing-javascript-methods/
* @param {Function} function to wrap
* @param {Number} timeout in ms (`100`)
* @param {Boolean} whether to execute at the beginning (`false`)
* @api public
*/
function debounce(func, wait, immediate){
var timeout, args, context, timestamp, result;
if (null == wait) wait = 100;
function later() {
var last = Date.now() - timestamp;
if (last < wait && last >= 0) {
timeout = setTimeout(later, wait - last);
} else {
timeout = null;
if (!immediate) {
result = func.apply(context, args);
context = args = null;
}
}
};
var debounced = function(){
context = this;
args = arguments;
timestamp = Date.now();
var callNow = immediate && !timeout;
if (!timeout) timeout = setTimeout(later, wait);
if (callNow) {
result = func.apply(context, args);
context = args = null;
}
return result;
};
debounced.clear = function() {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
};
debounced.flush = function() {
if (timeout) {
result = func.apply(context, args);
context = args = null;
clearTimeout(timeout);
timeout = null;
}
};
return debounced;
};
// Adds compatibility for ES modules
debounce.debounce = debounce;
module.exports = debounce;
/***/ }),
/***/ "./src/drawer.canvasentry.js":
/*!***********************************!*\
!*** ./src/drawer.canvasentry.js ***!
\***********************************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _style = _interopRequireDefault(__webpack_require__(/*! ./util/style */ "./src/util/style.js"));
var _getId = _interopRequireDefault(__webpack_require__(/*! ./util/get-id */ "./src/util/get-id.js"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
/**
* The `CanvasEntry` class represents an element consisting of a wave `canvas`
* and an (optional) progress wave `canvas`.
*
* The `MultiCanvas` renderer uses one or more `CanvasEntry` instances to
* render a waveform, depending on the zoom level.
*/
var CanvasEntry = /*#__PURE__*/function () {
function CanvasEntry() {
_classCallCheck(this, CanvasEntry);
/**
* The wave node
*
* @type {HTMLCanvasElement}
*/
this.wave = null;
/**
* The wave canvas rendering context
*
* @type {CanvasRenderingContext2D}
*/
this.waveCtx = null;
/**
* The (optional) progress wave node
*
* @type {HTMLCanvasElement}
*/
this.progress = null;
/**
* The (optional) progress wave canvas rendering context
*
* @type {CanvasRenderingContext2D}
*/
this.progressCtx = null;
/**
* Start of the area the canvas should render, between 0 and 1
*
* @type {number}
*/
this.start = 0;
/**
* End of the area the canvas should render, between 0 and 1
*
* @type {number}
*/
this.end = 1;
/**
* Unique identifier for this entry
*
* @type {string}
*/
this.id = (0, _getId.default)(typeof this.constructor.name !== 'undefined' ? this.constructor.name.toLowerCase() + '_' : 'canvasentry_');
/**
* Canvas 2d context attributes
*
* @type {object}
*/
this.canvasContextAttributes = {};
}
/**
* Store the wave canvas element and create the 2D rendering context
*
* @param {HTMLCanvasElement} element The wave `canvas` element.
*/
_createClass(CanvasEntry, [{
key: "initWave",
value: function initWave(element) {
this.wave = element;
this.waveCtx = this.wave.getContext('2d', this.canvasContextAttributes);
}
/**
* Store the progress wave canvas element and create the 2D rendering
* context
*
* @param {HTMLCanvasElement} element The progress wave `canvas` element.
*/
}, {
key: "initProgress",
value: function initProgress(element) {
this.progress = element;
this.progressCtx = this.progress.getContext('2d', this.canvasContextAttributes);
}
/**
* Update the dimensions
*
* @param {number} elementWidth Width of the entry
* @param {number} totalWidth Total width of the multi canvas renderer
* @param {number} width The new width of the element
* @param {number} height The new height of the element
*/
}, {
key: "updateDimensions",
value: function updateDimensions(elementWidth, totalWidth, width, height) {
// where the canvas starts and ends in the waveform, represented as a
// decimal between 0 and 1
this.start = this.wave.offsetLeft / totalWidth || 0;
this.end = this.start + elementWidth / totalWidth; // set wave canvas dimensions
this.wave.width = width;
this.wave.height = height;
var elementSize = {
width: elementWidth + 'px'
};
(0, _style.default)(this.wave, elementSize);
if (this.hasProgressCanvas) {
// set progress canvas dimensions
this.progress.width = width;
this.progress.height = height;
(0, _style.default)(this.progress, elementSize);
}
}
/**
* Clear the wave and progress rendering contexts
*/
}, {
key: "clearWave",
value: function clearWave() {
// wave
this.waveCtx.clearRect(0, 0, this.waveCtx.canvas.width, this.waveCtx.canvas.height); // progress
if (this.hasProgressCanvas) {
this.progressCtx.clearRect(0, 0, this.progressCtx.canvas.width, this.progressCtx.canvas.height);
}
}
/**
* Set the fill styles for wave and progress
*
* @param {string} waveColor Fill color for the wave canvas
* @param {?string} progressColor Fill color for the progress canvas
*/
}, {
key: "setFillStyles",
value: function setFillStyles(waveColor, progressColor) {
this.waveCtx.fillStyle = waveColor;
if (this.hasProgressCanvas) {
this.progressCtx.fillStyle = progressColor;
}
}
/**
* Draw a rectangle for wave and progress
*
* @param {number} x X start position
* @param {number} y Y start position
* @param {number} width Width of the rectangle
* @param {number} height Height of the rectangle
* @param {number} radius Radius of the rectangle
*/
}, {
key: "fillRects",
value: function fillRects(x, y, width, height, radius) {
this.fillRectToContext(this.waveCtx, x, y, width, height, radius);
if (this.hasProgressCanvas) {
this.fillRectToContext(this.progressCtx, x, y, width, height, radius);
}
}
/**
* Draw the actual rectangle on a `canvas` element
*
* @param {CanvasRenderingContext2D} ctx Rendering context of target canvas
* @param {number} x X start position
* @param {number} y Y start position
* @param {number} width Width of the rectangle
* @param {number} height Height of the rectangle
* @param {number} radius Radius of the rectangle
*/
}, {
key: "fillRectToContext",
value: function fillRectToContext(ctx, x, y, width, height, radius) {
if (!ctx) {
return;
}
if (radius) {
this.drawRoundedRect(ctx, x, y, width, height, radius);
} else {
ctx.fillRect(x, y, width, height);
}
}
/**
* Draw a rounded rectangle on Canvas
*
* @param {CanvasRenderingContext2D} ctx Canvas context
* @param {number} x X-position of the rectangle
* @param {number} y Y-position of the rectangle
* @param {number} width Width of the rectangle
* @param {number} height Height of the rectangle
* @param {number} radius Radius of the rectangle
*
* @return {void}
* @example drawRoundedRect(ctx, 50, 50, 5, 10, 3)
*/
}, {
key: "drawRoundedRect",
value: function drawRoundedRect(ctx, x, y, width, height, radius) {
if (height === 0) {
return;
} // peaks are float values from -1 to 1. Use absolute height values in
// order to correctly calculate rounded rectangle coordinates
if (height < 0) {
height *= -1;
y -= height;
}
ctx.beginPath();
ctx.moveTo(x + radius, y);
ctx.lineTo(x + width - radius, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + radius);
ctx.lineTo(x + width, y + height - radius);
ctx.quadraticCurveTo(x + width, y + height, x + width - radius, y + height);
ctx.lineTo(x + radius, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - radius);
ctx.lineTo(x, y + radius);
ctx.quadraticCurveTo(x, y, x + radius, y);
ctx.closePath();
ctx.fill();
}
/**
* Render the actual wave and progress lines
*
* @param {number[]} peaks Array with peaks data
* @param {number} absmax Maximum peak value (absolute)
* @param {number} halfH Half the height of the waveform
* @param {number} offsetY Offset to the top
* @param {number} start The x-offset of the beginning of the area that
* should be rendered
* @param {number} end The x-offset of the end of the area that
* should be rendered
*/
}, {
key: "drawLines",
value: function drawLines(peaks, absmax, halfH, offsetY, start, end) {
this.drawLineToContext(this.waveCtx, peaks, absmax, halfH, offsetY, start, end);
if (this.hasProgressCanvas) {
this.drawLineToContext(this.progressCtx, peaks, absmax, halfH, offsetY, start, end);
}
}
/**
* Render the actual waveform line on a `canvas` element
*
* @param {CanvasRenderingContext2D} ctx Rendering context of target canvas
* @param {number[]} peaks Array with peaks data
* @param {number} absmax Maximum peak value (absolute)
* @param {number} halfH Half the height of the waveform
* @param {number} offsetY Offset to the top
* @param {number} start The x-offset of the beginning of the area that
* should be rendered
* @param {number} end The x-offset of the end of the area that
* should be rendered
*/
}, {
key: "drawLineToContext",
value: function drawLineToContext(ctx, peaks, absmax, halfH, offsetY, start, end) {
if (!ctx) {
return;
}
var length = peaks.length / 2;
var first = Math.round(length * this.start); // use one more peak value to make sure we join peaks at ends -- unless,
// of course, this is the last canvas
var last = Math.round(length * this.end) + 1;
var canvasStart = first;
var canvasEnd = last;
var scale = this.wave.width / (canvasEnd - canvasStart - 1); // optimization
var halfOffset = halfH + offsetY;
var absmaxHalf = absmax / halfH;
ctx.beginPath();
ctx.moveTo((canvasStart - first) * scale, halfOffset);
ctx.lineTo((canvasStart - first) * scale, halfOffset - Math.round((peaks[2 * canvasStart] || 0) / absmaxHalf));
var i, peak, h;
for (i = canvasStart; i < canvasEnd; i++) {
peak = peaks[2 * i] || 0;
h = Math.round(peak / absmaxHalf);
ctx.lineTo((i - first) * scale + this.halfPixel, halfOffset - h);
} // draw the bottom edge going backwards, to make a single
// closed hull to fill
var j = canvasEnd - 1;
for (j; j >= canvasStart; j--) {
peak = peaks[2 * j + 1] || 0;
h = Math.round(peak / absmaxHalf);
ctx.lineTo((j - first) * scale + this.halfPixel, halfOffset - h);
}
ctx.lineTo((canvasStart - first) * scale, halfOffset - Math.round((peaks[2 * canvasStart + 1] || 0) / absmaxHalf));
ctx.closePath();
ctx.fill();
}
/**
* Destroys this entry
*/
}, {
key: "destroy",
value: function destroy() {
this.waveCtx = null;
this.wave = null;
this.progressCtx = null;
this.progress = null;
}
/**
* Return image data of the wave `canvas` element
*
* When using a `type` of `'blob'`, this will return a `Promise` that
* resolves with a `Blob` instance.
*
* @param {string} format='image/png' An optional value of a format type.
* @param {number} quality=0.92 An optional value between 0 and 1.
* @param {string} type='dataURL' Either 'dataURL' or 'blob'.
* @return {string|Promise} When using the default `'dataURL'` `type` this
* returns a data URL. When using the `'blob'` `type` this returns a
* `Promise` that resolves with a `Blob` instance.
*/
}, {
key: "getImage",
value: function getImage(format, quality, type) {
var _this = this;
if (type === 'blob') {
return new Promise(function (resolve) {
_this.wave.toBlob(resolve, format, quality);
});
} else if (type === 'dataURL') {
return this.wave.toDataURL(format, quality);
}
}
}]);
return CanvasEntry;
}();
exports.default = CanvasEntry;
module.exports = exports.default;
/***/ }),
/***/ "./src/drawer.js":
/*!***********************!*\
!*** ./src/drawer.js ***!
\***********************/
/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var util = _interopRequireWildcard(__webpack_require__(/*! ./util */ "./src/util/index.js"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Date.prototype.toString.call(Reflect.construct(Date, [], function () {})); return true; } catch (e) { return false; } }
function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
/**
* Parent class for renderers
*
* @extends {Observer}
*/
var Drawer = /*#__PURE__*/function (_util$Observer) {
_inherits(Drawer, _util$Observer);
var _super = _createSuper(Drawer);
/**
* @param {HTMLElement} container The container node of the wavesurfer instance
* @param {WavesurferParams} params The wavesurfer initialisation options
*/
function Drawer(container, params) {
var _this;
_classCallCheck(this, Drawer);
_this = _super.call(this);
_this.container = container;
/**
* @type {WavesurferParams}
*/
_this.params = params;
/**
* The width of the renderer
* @type {number}
*/
_this.width = 0;
/**
* The height of the renderer
* @type {number}
*/
_this.height = params.height * _this.params.pixelRatio;
_this.lastPos = 0;
/**
* The `<wave>` element which is added to the container
* @type {HTMLElement}
*/
_this.wrapper = null;
return _this;
}
/**
* Alias of `util.style`
*
* @param {HTMLElement} el The element that the styles will be applied to
* @param {Object} styles The map of propName: attribute, both are used as-is
* @return {HTMLElement} el
*/
_createClass(Drawer, [{
key: "style",
value: function style(el, styles) {
return util.style(el, styles);
}
/**
* Create the wrapper `<wave>` element, style it and set up the events for
* interaction
*/
}, {
key: "createWrapper",
value: function createWrapper() {
this.wrapper = this.container.appendChild(document.createElement('wave'));
this.style(this.wrapper, {
display: 'block',
position: 'relative',
userSelect: 'none',
webkitUserSelect: 'none',
height: this.params.height + 'px'
});
if (this.params.fillParent || this.params.scrollParent) {
this.style(this.wrapper, {
width: '100%',
overflowX: this.params.hideScrollbar ? 'hidden' : 'auto',
overflowY: 'hidden'
});
}
this.setupWrapperEvents();
}
/**
* Handle click event
*
* @param {Event} e Click event
* @param {?boolean} noPrevent Set to true to not call `e.preventDefault()`
* @return {number} Playback position from 0 to 1
*/
}, {
key: "handleEvent",
value: function handleEvent(e, noPrevent) {
!noPrevent && e.preventDefault();
var clientX = e.targetTouches ? e.targetTouches[0].clientX : e.clientX;
var bbox = this.wrapper.getBoundingClientRect();
var nominalWidth = this.width;
var parentWidth = this.getWidth();
var progress;
if (!this.params.fillParent && nominalWidth < parentWidth) {
progress = (this.params.rtl ? bbox.right - clientX : clientX - bbox.left) * (this.params.pixelRatio / nominalWidth) || 0;
} else {
progress = ((this.params.rtl ? bbox.right - clientX : clientX - bbox.left) + this.wrapper.scrollLeft) / this.wrapper.scrollWidth || 0;
}
return util.clamp(progress, 0, 1);
}
}, {
key: "setupWrapperEvents",
value: function setupWrapperEvents() {
var _this2 = this;
this.wrapper.addEventListener('click', function (e) {
var scrollbarHeight = _this2.wrapper.offsetHeight - _this2.wrapper.clientHeight;
if (scrollbarHeight !== 0) {
// scrollbar is visible. Check if click was on it
var bbox = _this2.wrapper.getBoundingClientRect();
if (e.clientY >= bbox.bottom - scrollbarHeight) {
// ignore mousedown as it was on the scrollbar
return;
}
}
if (_this2.params.interact) {
_this2.fireEvent('click', e, _this2.handleEvent(e));
}
});
this.wrapper.addEventListener('dblclick', function (e) {
if (_this2.params.interact) {
_this2.fireEvent('dblclick', e, _this2.handleEvent(e));
}
});
this.wrapper.addEventListener('scroll', function (e) {
return _this2.fireEvent('scroll', e);
});
}
/**
* Draw peaks on the canvas
*
* @param {number[]|Number.<Array[]>} peaks Can also be an array of arrays
* for split channel rendering
* @param {number} length The width of the area that should be drawn
* @param {number} start The x-offset of the beginning of the area that
* should be rendered
* @param {number} end The x-offset of the end of the area that should be
* rendered
*/
}, {
key: "drawPeaks",
value: function drawPeaks(peaks, length, start, end) {
if (!this.setWidth(length)) {
this.clearWave();
}
this.params.barWidth ? this.drawBars(peaks, 0, start, end) : this.drawWave(peaks, 0, start, end);
}
/**
* Scroll to the beginning
*/
}, {
key: "resetScroll",
value: function resetScroll() {
if (this.wrapper !== null) {
this.wrapper.scrollLeft = 0;
}
}
/**
* Recenter the view-port at a certain percent of the waveform
*
* @param {number} percent Value from 0 to 1 on the waveform
*/
}, {
key: "recenter",
value: function recenter(percent) {
var position = this.wrapper.scrollWidth * percent;
this.recenterOnPosition(position, true);
}
/**
* Recenter the view-port on a position, either scroll there immediately or
* in steps of 5 pixels
*
* @param {number} position X-offset in pixels
* @param {boolean} immediate Set to true to immediately scroll somewhere
*/
}, {
key: "recenterOnPosition",
value: function recenterOnPosition(position, immediate) {
var scrollLeft = this.wrapper.scrollLeft;
var half = ~~(this.wrapper.clientWidth / 2);
var maxScroll = this.wrapper.scrollWidth - this.wrapper.clientWidth;
var target = position - half;
var offset = target - scrollLeft;
if (maxScroll == 0) {
// no need to continue if scrollbar is not there
return;
} // if the cursor is currently visible...
if (!immediate && -half <= offset && offset < half) {
// set rate at which waveform is centered
var rate = this.params.autoCenterRate; // make rate depend on width of view and length of waveform
rate /= half;
rate *= maxScroll;
offset = Math.max(-rate, Math.min(rate, offset));
target = scrollLeft + offset;
} // limit target to valid range (0 to maxScroll)
target = Math.max(0, Math.min(maxScroll, target)); // no use attempting to scroll if we're not moving
if (target != scrollLeft) {
this.wrapper.scrollLeft = target;
}
}
/**
* Get the current scroll position in pixels
*
* @return {number} Horizontal scroll position in pixels
*/
}, {
key: "getScrollX",
value: function getScrollX() {
var x = 0;
if (this.wrapper) {
var pixelRatio = this.params.pixelRatio;
x = Math.round(this.wrapper.scrollLeft * pixelRatio); // In cases of elastic scroll (safari with mouse wheel) you can
// scroll beyond the limits of the container
// Calculate and floor the scrollable extent to make sure an out
// of bounds value is not returned
// Ticket #1312
if (this.params.scrollParent) {
var maxScroll = ~~(this.wrapper.scrollWidth * pixelRatio - this.getWidth());
x = Math.min(maxScroll, Math.max(0, x));
}
}
return x;
}
/**
* Get the width of the container
*
* @return {number} The width of the container
*/
}, {
key: "getWidth",
value: function getWidth() {
return Math.round(this.container.clientWidth * this.params.pixelRatio);
}
/**
* Set the width of the container
*
* @param {number} width The new width of the container
* @return {boolean} Whether the width of the container was updated or not
*/
}, {
key: "setWidth",
value: function setWidth(width) {
if (this.width == width) {
return false;
}
this.width = width;
if (this.params.fillParent || this.params.scrollParent) {
this.style(this.wrapper, {
width: ''
});
} else {
this.style(this.wrapper, {
width: ~~(this.width / this.params.pixelRatio) + 'px'
});
}
this.updateSize();
return true;
}
/**
* Set the height of the container
*
* @param {number} height The new height of the container.
* @return {boolean} Whether the height of the container was updated or not
*/
}, {
key: "setHeight",
value: function setHeight(height) {
if (height == this.height) {
return false;
}
this.height = height;
this.style(this.wrapper, {
height: ~~(this.height / this.params.pixelRatio) + 'px'
});
this.updateSize();
return true;
}
/**
* Called by wavesurfer when progress should be rendered
*
* @param {number} progress From 0 to 1
*/
}, {
key: "progress",
value: function progress(_progress) {
var minPxDelta = 1 / this.params.pixelRatio;
var pos = Math.round(_progress * this.width) * minPxDelta;
if (pos < this.lastPos || pos - this.lastPos >= minPxDelta) {
this.lastPos = pos;
if (this.params.scrollParent && this.params.autoCenter) {
var newPos = ~~(this.wrapper.scrollWidth * _progress);
this.recenterOnPosition(newPos, this.params.autoCenterImmediately);
}
this.updateProgress(pos);
}
}
/**
* This is called when wavesurfer is destroyed
*/
}, {
key: "destroy",
value: function destroy() {
this.unAll();
if (this.wrapper) {
if (this.wrapper.parentNode == this.container) {
this.container.removeChild(this.wrapper);
}
this.wrapper = null;
}
}
/* Renderer-specific methods */
/**
* Called after cursor related params have changed.
*
* @abstract
*/
}, {
key: "updateCursor",
value: function updateCursor() {}
/**
* Called when the size of the container changes so the renderer can adjust
*
* @abstract
*/
}, {
key: "updateSize",
value: function updateSize() {}
/**
* Draw a waveform with bars
*