aboutsummaryrefslogtreecommitdiffhomepage
path: root/experimental/webtry/res/js/webtry.js
blob: 2b46c10d8aa83d33d04727f8e2e0f31d08dd3985 (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
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
/**
 * Common JS that talks XHR back to the server and runs the code and receives
 * the results.
 */


/**
 * All the functionality is wrapped up in this anonymous closure, but we need
 * to be told if we are on the workspace page or a normal try page, so the
 * workspaceName is passed into the closure, it must be set in the global
 * namespace. If workspaceName is the empty string then we know we aren't
 * running on a workspace page.
 *
 * If we are on a workspace page we also look for a 'history_'
 * variable in the global namespace which contains the list of tries
 * that are included in this workspace. That variable is used to
 * populate the history list.
 */
(function() {
    function onLoad() {
      var run             = document.getElementById('run');
      var permalink       = document.getElementById('permalink');
      var embed           = document.getElementById('embed');
      var embedButton     = document.getElementById('embedButton');
      var code            = document.getElementById('code');
      var output          = document.getElementById('output');
      var stdout          = document.getElementById('stdout');
      var img             = document.getElementById('img');
      var tryHistory      = document.getElementById('tryHistory');
      var parser          = new DOMParser();
      var tryTemplate     = document.getElementById('tryTemplate');
      var sourcesTemplate = document.getElementById('sourcesTemplate');

      var enableSource   = document.getElementById('enableSource');
      var selectedSource = document.getElementById('selectedSource');
      var sourceCode     = document.getElementById('sourceCode');
      var chooseSource   = document.getElementById('chooseSource');
      var chooseList     = document.getElementById('chooseList');

      // Id of the source image to use, 0 if no source image is used.
      var sourceId = 0;

      sourceId = parseInt(enableSource.getAttribute('data-id'));
      if (sourceId) {
        sourceSelectByID(sourceId);
      }

      function setIFrameURL() {
        var url = document.URL;
        url = url.replace('/c/', '/iframe/');
        embed.value = '<iframe src="' + url + '" width="740" height="550" style="border: solid #00a 5px; border-radius: 5px;"/>'
      }

      function beginWait() {
        document.body.classList.add('waiting');
        run.disabled = true;
      }


      function endWait() {
        document.body.classList.remove('waiting');
        run.disabled = false;
      }


      function sourceSelectByID(id) {
        sourceId = id;
        if (id > 0) {
          enableSource.checked = true;
          selectedSource.innerHTML = '<img with=64 height=64 src="/i/image-'+sourceId+'.png" />';
          selectedSource.classList.add('show');
          sourceCode.classList.add('show');
          chooseSource.classList.remove('show');
        } else {
          enableSource.checked = false;
          selectedSource.classList.remove('show');
          sourceCode.classList.remove('show');
        }
      }


      /**
       * A selection has been made in the choiceList.
       */
      function sourceSelect() {
        sourceSelectByID(parseInt(this.getAttribute('data-id')));
      }


      /**
       * Callback when the loading of the image sources is complete.
       *
       * Fills in the list of images from the data returned.
       */
      function sourcesComplete(e) {
        endWait();
        // The response is JSON of the form:
        // [
        //   {"id": 1},
        //   {"id": 3},
        //   ...
        // ]
        body = JSON.parse(e.target.response);
        // Clear out the old list if present.
        while (chooseList.firstChild) {
          chooseList.removeChild(chooseList.firstChild);
        }
        body.forEach(function(source) {
         var id = 'i'+source.id;
         var imgsrc = '/i/image-'+source.id+'.png';
         var clone = sourcesTemplate.content.cloneNode(true);
         clone.querySelector('img').src     = imgsrc;
         clone.querySelector('button').setAttribute('id', id);
         clone.querySelector('button').setAttribute('data-id', source.id);
         chooseList.insertBefore(clone, chooseList.firstChild);
         chooseList.querySelector('#'+id).addEventListener('click', sourceSelect, true);
        });
        chooseSource.classList.add('show');
      }


      /**
       * Toggle the use of a source image, or select a new source image.
       *
       * If enabling source images then load the list of available images via
       * XHR.
       */
      function sourceClick(e) {
        selectedSource.classList.remove('show');
        sourceCode.classList.remove('show');
        if (enableSource.checked) {
          beginWait();
          var req = new XMLHttpRequest();
          req.addEventListener('load', sourcesComplete);
          req.addEventListener('error', xhrError);
          req.overrideMimeType('application/json');
          req.open('GET', '/sources/', true);
          req.send();
        } else {
          sourceId = 0;
          chooseSource.classList.remove('show');
        }
      }

      enableSource.addEventListener('click', sourceClick, true);
      selectedSource.addEventListener('click', sourceClick, true);


      var editor = CodeMirror.fromTextArea(code, {
        theme: "default",
        lineNumbers: true,
        matchBrackets: true,
        lineWrapping: true,
        mode: "text/x-c++src",
        indentUnit: 4,
      });

      // Match the initial textarea width, but leave the height alone
      // The css will automatically resize the editor vertically.
      editor.setSize(editor.defaultCharWidth() * code.cols,
                     null);


      /**
       * Callback when there's an XHR error.
       * @param e The callback event.
       */
      function xhrError(e) {
        endWait();
        alert('Something bad happened: ' + e);
      }

      function clearOutput() {
        output.textContent = "";
        output.style.display='none';
        if (stdout) {
          stdout.textContent = "";
          stdout.style.display='none';
        }
        if (embed) {
          embed.style.display='none';
        }
      }

      /**
       * Called when an image in the workspace history is clicked.
       */
      function historyClick() {
        beginWait();
        clearOutput();
        var req = new XMLHttpRequest();
        req.addEventListener('load', historyComplete);
        req.addEventListener('error', xhrError);
        req.overrideMimeType('application/json');
        req.open('GET', this.getAttribute('data-try'), true);
        req.send();
      }


      /**
       * Callback for when the XHR kicked off in historyClick() returns.
       */
      function historyComplete(e) {
        // The response is JSON of the form:
        // {
        //   "hash": "unique id for a try",
        //   "code": "source code for try"
        // }
        endWait();
        body = JSON.parse(e.target.response);
        code.value = body.code;
        editor.setValue(body.code);
        img.src = '/i/'+body.hash+'.png';
        sourceSelectByID(body.source);
        if (permalink) {
          permalink.href = '/c/' + body.hash;
          permalink.style.display='inline-block';
        }
      }


      /**
       * Add the given try image to the history of a workspace.
       */
      function addToHistory(hash, imgUrl) {
        var clone = tryTemplate.content.cloneNode(true);
        clone.querySelector('img').src = imgUrl;
        clone.querySelector('.tries').setAttribute('data-try', '/json/' + hash);
        tryHistory.insertBefore(clone, tryHistory.firstChild);
        tryHistory.querySelector('.tries').addEventListener('click', historyClick, true);
      }


      /**
       * Callback for when the XHR returns after attempting to run the code.
       * @param e The callback event.
       */
      function codeComplete(e) {
        // The response is JSON of the form:
        // {
        //   "message": "you had an error...",
        //   "img": "<base64 encoded image but only on success>"
        // }
        //
        // The img is optional and only appears if there is a valid
        // image to display.
        endWait();
        console.log(e.target.response);
        body = JSON.parse(e.target.response);
        output.textContent = body.message;
        if (body.message) {
          output.style.display = 'block';
        }
        if (stdout) {
          stdout.textContent = body.stdout;
          if (body.stdout) {
            stdout.style.display = 'block';
          }
        }
        if (body.hasOwnProperty('img')) {
          img.src = 'data:image/png;base64,' + body.img;
        } else {
          img.src = '';
        }
        // Add the image to the history if we are on a workspace page.
        if (tryHistory) {
          addToHistory(body.hash, 'data:image/png;base64,' + body.img);
        } else {
          window.history.pushState(null, null, '/c/' + body.hash);
        }
        if (permalink) {
          permalink.href = '/c/' + body.hash;
          permalink.style.display = 'inline-block';
        }
        if (embed) {
          setIFrameURL();
        }
        if (embedButton) {
          embedButton.style.display = 'inline-block';
        }
      }


      function onSubmitCode() {
        beginWait();
        clearOutput();
        var req = new XMLHttpRequest();
        req.addEventListener('load', codeComplete);
        req.addEventListener('error', xhrError);
        req.overrideMimeType('application/json');
        req.open('POST', '/', true);
        req.setRequestHeader('content-type', 'application/json');
        req.send(JSON.stringify({'code': editor.getValue(), 'name': workspaceName, 'source': sourceId}));
      }
      run.addEventListener('click', onSubmitCode);


      function onEmbedClick() {
        embed.style.display='inline';
      }

      if (embedButton) {
        embedButton.addEventListener('click', onEmbedClick);
      }

      setIFrameURL();

      // Add the images to the history if we are on a workspace page.
      if (tryHistory && history_) {
        for (var i=0; i<history_.length; i++) {
          addToHistory(history_[i].hash, '/i/'+history_[i].hash+'.png');
        }
      }
    }

    // If loaded via HTML Imports then DOMContentLoaded will be long done.
    if (document.readyState != "loading") {
      onLoad();
    } else {
      this.addEventListener('load', onLoad);
    }

})();