audioPreview.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*---------------------------------------------------------------------------------------------
  2. * Copyright (c) Microsoft Corporation. All rights reserved.
  3. * Licensed under the MIT License. See License.txt in the project root for license information.
  4. *--------------------------------------------------------------------------------------------*/
  5. // @ts-check
  6. "use strict";
  7. (function () {
  8. // @ts-ignore
  9. const vscode = acquireVsCodeApi();
  10. function getSettings() {
  11. const element = document.getElementById('settings');
  12. if (element) {
  13. const data = element.getAttribute('data-settings');
  14. if (data) {
  15. return JSON.parse(data);
  16. }
  17. }
  18. throw new Error(`Could not load settings`);
  19. }
  20. const settings = getSettings();
  21. // State
  22. let hasLoadedMedia = false;
  23. // Elements
  24. const container = document.createElement('div');
  25. container.className = 'audio-container';
  26. document.body.appendChild(container);
  27. const audio = new Audio(settings.src === null ? undefined : settings.src);
  28. audio.controls = true;
  29. function onLoaded() {
  30. if (hasLoadedMedia) {
  31. return;
  32. }
  33. hasLoadedMedia = true;
  34. document.body.classList.remove('loading');
  35. document.body.classList.add('ready');
  36. container.append(audio);
  37. }
  38. audio.addEventListener('error', e => {
  39. if (hasLoadedMedia) {
  40. return;
  41. }
  42. hasLoadedMedia = true;
  43. document.body.classList.add('error');
  44. document.body.classList.remove('loading');
  45. });
  46. if (settings.src === null) {
  47. onLoaded();
  48. } else {
  49. audio.addEventListener('canplaythrough', () => {
  50. onLoaded();
  51. });
  52. }
  53. document.querySelector('.open-file-link')?.addEventListener('click', (e) => {
  54. e.preventDefault();
  55. vscode.postMessage({
  56. type: 'reopen-as-text',
  57. });
  58. });
  59. }());