contentscript.js 2.2 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. import * as WaveformPlaylist from 'waveform-playlist';
  2. import delay from 'delay';
  3. import html from 'nanohtml'
  4. import { parseMediaFragmentIdentifier } from '../util/media-fragment-identifier.js';
  5. async function init() {
  6. document.body.innerHTML = '';
  7. const mainEl = html`
  8. <main>
  9. <div id="controls">
  10. <button id="playpause" onclick=${playpause}>⏯</button>
  11. <div>
  12. <label for="volume" id="volume-label">🔊</label>
  13. <input type="range" min="0" max="100" value="100" id="volume" oninput=${updateVolume}/>
  14. </div>
  15. </div>
  16. <div id="container">
  17. </div>
  18. </main>
  19. `;
  20. document.body.appendChild(mainEl);
  21. const playlist = WaveformPlaylist.init({
  22. container: document.getElementById('container'),
  23. timescale: true,
  24. waveHeight: 100,
  25. state: 'select',
  26. });
  27. const eventEmitter = playlist.getEventEmitter();
  28. function playpause() {
  29. eventEmitter.emit(playlist.isPlaying() ? 'pause' : 'play');
  30. }
  31. function updateVolume(event) {
  32. eventEmitter.emit('mastervolumechange', event.target.value);
  33. }
  34. // Load the file
  35. await playlist.load([{
  36. src: document.URL,
  37. }]);
  38. function syncFragmentToSelection() {
  39. // Read target fragment from URL
  40. let start, end;
  41. const fragmentIdentifier = window.location.hash;
  42. if (fragmentIdentifier) {
  43. try {
  44. const parsed = parseMediaFragmentIdentifier(fragmentIdentifier);
  45. start = parsed.start;
  46. end = parsed.end;
  47. } catch (err) {}
  48. }
  49. // Emit event to update selection in player
  50. eventEmitter.emit('select', start, end);
  51. }
  52. // Bind window hash change to update player
  53. window.addEventListener('hashchange', async function() {
  54. if(playlist.isPlaying()) {
  55. eventEmitter.emit('stop')
  56. // pause needs a small delay, coz the lib doesn't
  57. // update player view (drawRequest) when isPlaying() = true.
  58. await delay(10);
  59. }
  60. await syncFragmentToSelection();
  61. eventEmitter.emit('play');
  62. });
  63. // Read start & end from window location.
  64. syncFragmentToSelection();
  65. // Start playing. A tiny delay seems needed in Firefox to show the cursor at the right place.
  66. requestAnimationFrame(() => eventEmitter.emit('play'));
  67. return playlist;
  68. }
  69. init().then(playlist => {
  70. // Store playlist as a shared global variable.
  71. self.playlist = playlist;
  72. });