summaryrefslogtreecommitdiff
path: root/app/assets/javascripts/blob/sketch/index.js
blob: 767e205fcaab3fe9b15e8811b820c57564004fd0 (plain)
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
import JSZip from 'jszip';
import JSZipUtils from 'jszip-utils';
import { __ } from '~/locale';

export default class SketchLoader {
  constructor(container) {
    this.container = container;
    this.loadingIcon = this.container.querySelector('.js-loading-icon');

    this.load();
  }

  load() {
    return this.getZipFile()
      .then(data => JSZip.loadAsync(data))
      .then(asyncResult => asyncResult.files['previews/preview.png'].async('uint8array'))
      .then(content => {
        const url = window.URL || window.webkitURL;
        const blob = new Blob([new Uint8Array(content)], {
          type: 'image/png',
        });
        const previewUrl = url.createObjectURL(blob);

        this.render(previewUrl);
      })
      .catch(this.error.bind(this));
  }

  getZipFile() {
    return new JSZip.external.Promise((resolve, reject) => {
      JSZipUtils.getBinaryContent(this.container.dataset.endpoint, (err, data) => {
        if (err) {
          reject(err);
        } else {
          resolve(data);
        }
      });
    });
  }

  render(previewUrl) {
    const previewLink = document.createElement('a');
    const previewImage = document.createElement('img');

    previewLink.href = previewUrl;
    previewLink.target = '_blank';
    previewImage.src = previewUrl;
    previewImage.className = 'img-fluid';

    previewLink.appendChild(previewImage);
    this.container.appendChild(previewLink);

    this.removeLoadingIcon();
  }

  error() {
    const errorMsg = document.createElement('p');

    errorMsg.className = 'gl-mt-3 gl-mb-3 text-center';
    errorMsg.textContent = __(`
      Cannot show preview. For previews on sketch files, they must have the file format
      introduced by Sketch version 43 and above.
    `);
    this.container.appendChild(errorMsg);

    this.removeLoadingIcon();
  }

  removeLoadingIcon() {
    if (this.loadingIcon) {
      this.loadingIcon.remove();
    }
  }
}