« get me outta code hell

main.js « js « src - scratchblocks-generator-3 - scratchblocks generator for projects made in 3.0
about summary refs log tree commit diff
path: root/src/js/main.js
blob: f7ad5f45bec7ddf858c49c37682b7433d1d4369d (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
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
'use strict';

require('../index.html');
require('../css/style.css');

const { Project } = require('sb-edit');
const { scriptToScratchblocks } = require('./sb3-gen');

// setup step

const urlInput = document.getElementById('url-input');
const fileInput = document.getElementById('file-input');
const generateButton = document.getElementById('generate-button');
const errorElement = document.getElementById('error-element');
const downloadIndicator = document.getElementById('download-indicator');

function assetURL({md5, ext}) {
    return 'https://assets.scratch.mit.edu/' + md5 + '.' + ext;
}

function isUrlInputValid() {
    const re = /^((.*:\/\/scratch.mit.edu\/projects\/[0-9]+\/?)|[0-9]+)(:.*)?$/;
    return re.test(urlInput.value);
}

urlInput.addEventListener('input', () => {
    if (urlInput.value === '' || isUrlInputValid()) {
        generateButton.classList.add('enabled');
        generateButton.classList.remove('disabled');
    } else {
        generateButton.classList.remove('enabled');
        generateButton.classList.add('disabled');
    }
});

function clearChildren(el) {
    while (el.firstChild) {
        el.firstChild.remove();
    }
}

function showError(msg) {
    clearChildren(errorElement);
    errorElement.appendChild(document.createTextNode(msg));
}

async function submitGenerate(evt) {
    try {
        if (!isUrlInputValid()) {
            return;
        }

        const url = urlInput.value;
        const id = url.match(/[0-9]+/)[0];
        const result = await fetch('https://projects.scratch.mit.edu/' + id);

        let projectObj;
        try {
            projectObj = await result.json();
        } catch (error) { /* Scratch 1.4. */ }
        if (!(projectObj && projectObj.meta && projectObj.meta.semver && projectObj.meta.semver.startsWith('3.'))) {
            showError(`That project hasn't been saved in Scratch 3.0, so it won't work here.\nTry remixing it! That will make an up-to-date version.`);
            return;
        }

        let assetsDownloaded = 0;
        const totalAssets = projectObj.targets.map(t => t.costumes.length + t.sounds.length).reduce((a, b) => a + b, 0);
        const project = await Project.fromSb3JSON(projectObj, {
            getAsset: async asset => {
                const body = await fetch(assetURL(asset));
                const blob = await body.blob();
                assetsDownloaded++;
                downloadIndicator.style.width = `${Math.round(assetsDownloaded / totalAssets * 100)}%`;
                return blob;
            }
        });
        downloadIndicator.style.opacity = 0;
        presentProject(project);
    } catch (error) {
        console.error(error);
        showError(`Sorry, there was an error loading that project.`);
    }
}

async function submitFile() {
    try {
        if (!fileInput.files.length) {
            return;
        }

        const file = fileInput.files[0];
        const project = await Project.fromSb3(file);
        presentProject(project);
    } catch (error) {
        console.error(error);
        showError(`Sorry, there was an error loading that project.`);
    }
}

document.getElementById('form').addEventListener('submit', evt => {
    evt.preventDefault();
    submitGenerate();
});

function spaceEnterToClick(a) {
    a.addEventListener('keydown', evt => {
        if (evt.keyCode === 13 || evt.keyCode === 32) {
            evt.target.click();
        }
    });
}

for (const a of document.querySelectorAll('a.button')) {
    spaceEnterToClick(a);
}

document.getElementById('generate-button').addEventListener('click', submitGenerate);
fileInput.addEventListener('input', submitFile);

if (location.hash.length > 1) {
    urlInput.value = decodeURIComponent(location.hash.slice(1));
    submitGenerate();
}

// present step

const targetList = document.getElementById('target-list');
const scriptArea = document.getElementById('script-area');

let project;
let selectedTarget;
const sym = Symbol();

function presentTarget(targetName) {
    if (!project) {
        return;
    }

    const target = [project.stage, ...project.sprites].find(t => t.name === targetName);
    if (!target) {
        return;
    }

    if (target === selectedTarget) {
        return;
    }

    if (selectedTarget) {
        if (!selectedTarget[sym]) {
            selectedTarget[sym] = {};
        }
        Object.assign(selectedTarget[sym], {
            scrollLeft: scriptArea.scrollLeft,
            scrollTop: scriptArea.scrollTop
        });
    }

    selectedTarget = target;

    if (target[sym]) {
        Object.assign(scriptArea, {
            scrollLeft: target[sym].scrollLeft,
            scrollTop: target[sym].scrollTop
        });
    } else {
        Object.assign(scriptArea, {
            scrollLeft: 0,
            scrollTop: 0
        });
    }

    for (const el of document.querySelectorAll('.target.selected')) {
        el.classList.remove('selected');
    }
    const el = document.querySelector(`.target[data-name="${targetName.replace(/"/g, '\\"')}"]`);
    el.classList.add('selected');
    // XXX: this is a hack! we wait 100ms as a guard so that we _probably_ run scrollIntoView after
    // any images have loaded. however, this doesn't work if the images don't load within that
    // time, in which case the element will not properly be scrolled into view (the loaded images
    // will push it out of the way). to deal with this, we should wait until all images positioned
    // before this target's element have loaded (but we should also make sure to skip images that
    // have already loaded).
    setTimeout(() => el.scrollIntoView(), 100);

    clearChildren(scriptArea);
    if (target.scripts.length) {
        const offsetX = -target.scripts.reduce((least, s) => Math.min(least, s.x), target.scripts[0].x) + 240;
        const offsetY = -target.scripts.reduce((least, s) => Math.min(least, s.y), target.scripts[0].y);
        for (const script of target.scripts) {
            const sb = scriptToScratchblocks(script, target);
            const pre = document.createElement('pre');
            pre.classList.add('blocks');
            pre.appendChild(document.createTextNode(sb));
            pre.style.position = 'absolute';
            pre.style.left = (script.x + offsetX) + 'px';
            pre.style.top = (script.y + offsetY) + 'px';
            scriptArea.appendChild(pre);
        }
    }

    window.scratchblocks.renderMatching('pre.blocks', {
        style: 'scratch3'
    });
}

function presentProject(p) {
    project = p;

    clearChildren(targetList);
    for (const target of [project.stage, ...project.sprites]) {
        const el = document.createElement('a');
        el.setAttribute('tabindex', 0);
        el.classList.add('target');
        const img = document.createElement('img');
        img.src = assetURL(target.costumes[target.costumeNumber]);
        el.appendChild(img);
        const span = document.createElement('span');
        span.appendChild(document.createTextNode(target.name));
        el.appendChild(span);
        el.dataset.name = target.name;
        targetList.appendChild(el);
        spaceEnterToClick(el);
        el.addEventListener('click', () => presentTarget(target.name));
    }

    if (location.hash.includes(':')) {
        const targetName = decodeURIComponent(location.hash.slice(location.hash.indexOf(':') + 1));
        presentTarget(targetName);
    }
}